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 |
|---|---|---|---|---|---|
Java | Java | handle special headers in tomcat and jetty | 10d5de7d630587bfa96f4f6998ab141693d55386 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/JettyHttpHandlerAdapter.java
<ide> import java.io.IOException;
<ide> import java.net.URISyntaxException;
<ide> import java.nio.ByteBuffer;
<add>import java.nio.charset.Charset;
<ide> import javax.servlet.AsyncContext;
<ide> import javax.servlet.ServletResponse;
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.MediaType;
<ide>
<ide> /**
<ide> * {@link ServletHttpHandlerAdapter} extension that uses Jetty APIs for writing
<ide> private static HttpHeaders createHeaders(HttpServletResponse response) {
<ide>
<ide> @Override
<ide> protected void applyHeaders() {
<add> MediaType contentType = getHeaders().getContentType();
<add> HttpServletResponse response = getNativeResponse();
<add> if (response.getContentType() == null && contentType != null) {
<add> response.setContentType(contentType.toString());
<add> }
<add> Charset charset = (contentType != null ? contentType.getCharset() : null);
<add> if (response.getCharacterEncoding() == null && charset != null) {
<add> response.setCharacterEncoding(charset.name());
<add> }
<add> long contentLength = getHeaders().getContentLength();
<add> if (contentLength != -1) {
<add> response.setContentLengthLong(contentLength);
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHttpHandlerAdapter.java
<ide> import java.lang.reflect.Field;
<ide> import java.net.URISyntaxException;
<ide> import java.nio.ByteBuffer;
<add>import java.nio.charset.Charset;
<ide> import javax.servlet.AsyncContext;
<ide> import javax.servlet.ServletRequest;
<ide> import javax.servlet.ServletResponse;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.MediaType;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ReflectionUtils;
<ide>
<ide> private static HttpHeaders createTomcatHttpHeaders(HttpServletResponse response)
<ide>
<ide> @Override
<ide> protected void applyHeaders() {
<add> HttpServletResponse response = getNativeResponse();
<add> MediaType contentType = getHeaders().getContentType();
<add> if (response.getContentType() == null && contentType != null) {
<add> response.setContentType(contentType.toString());
<add> }
<add> Charset charset = (contentType != null ? contentType.getCharset() : null);
<add> if (response.getCharacterEncoding() == null && charset != null) {
<add> response.setCharacterEncoding(charset.name());
<add> }
<add> long contentLength = getHeaders().getContentLength();
<add> if (contentLength != -1) {
<add> response.setContentLengthLong(contentLength);
<add> }
<ide> }
<ide>
<ide> @Override | 2 |
Go | Go | fix comments and for hasdevice() and exists() | f5c0eb9ffe9a9d30ac6ff81fa1a4c216908189a6 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) UnmountDevice(hash string) error {
<ide> return nil
<ide> }
<ide>
<del>// HasDevice returns true if the device is in the hash and mounted.
<add>// HasDevice returns true if the device metadata exists.
<ide> func (devices *DeviceSet) HasDevice(hash string) bool {
<ide> devices.Lock()
<ide> defer devices.Unlock()
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> func (d *Driver) Put(id string) error {
<ide> return err
<ide> }
<ide>
<del>// Exists checks to see if the device is mounted.
<add>// Exists checks to see if the device exists.
<ide> func (d *Driver) Exists(id string) bool {
<ide> return d.DeviceSet.HasDevice(id)
<ide> } | 2 |
Javascript | Javascript | add more validation to `pdflinkservice_navigateto` | e1412de32075e76f3c6129dc59ef6631cc68b6c6 | <ide><path>web/pdf_link_service.js
<ide> var PDFLinkService = (function PDFLinkServiceClosure() {
<ide>
<ide> var goToDestination = function(destRef) {
<ide> // dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
<del> var pageNumber = destRef instanceof Object ?
<del> self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
<del> (destRef + 1);
<add> var pageNumber;
<add> if (destRef instanceof Object) {
<add> pageNumber = self._cachedPageNumber(destRef);
<add> } else if ((destRef | 0) === destRef) { // Integer
<add> pageNumber = destRef + 1;
<add> } else {
<add> console.error('PDFLinkService_navigateTo: "' + destRef +
<add> '" is not a valid destination reference.');
<add> return;
<add> }
<add>
<ide> if (pageNumber) {
<del> if (pageNumber > self.pagesCount) {
<del> console.error('PDFLinkService_navigateTo: ' +
<del> 'Trying to navigate to a non-existent page.');
<add> if (pageNumber < 1 || pageNumber > self.pagesCount) {
<add> console.error('PDFLinkService_navigateTo: "' + pageNumber +
<add> '" is a non-existent page number.');
<ide> return;
<ide> }
<ide> self.pdfViewer.scrollPageIntoView({
<ide> var PDFLinkService = (function PDFLinkServiceClosure() {
<ide> }
<ide> } else {
<ide> self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
<del> var pageNum = pageIndex + 1;
<del> var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
<del> self._pagesRefCache[cacheKey] = pageNum;
<add> self.cachePageRef(pageIndex + 1, destRef);
<ide> goToDestination(destRef);
<add> }).catch(function () {
<add> console.error('PDFLinkService_navigateTo: "' + destRef +
<add> '" is not a valid page reference.');
<add> return;
<ide> });
<ide> }
<ide> };
<ide> var PDFLinkService = (function PDFLinkServiceClosure() {
<ide> destinationPromise.then(function(destination) {
<ide> dest = destination;
<ide> if (!(destination instanceof Array)) {
<del> return; // invalid destination
<add> console.error('PDFLinkService_navigateTo: "' + destination +
<add> '" is not a valid destination array.');
<add> return;
<ide> }
<ide> goToDestination(destination[0]);
<ide> });
<ide> var PDFLinkService = (function PDFLinkServiceClosure() {
<ide> cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
<ide> var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
<ide> this._pagesRefCache[refStr] = pageNum;
<del> }
<add> },
<add>
<add> _cachedPageNumber: function PDFLinkService_cachedPageNumber(pageRef) {
<add> var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
<add> return (this._pagesRefCache && this._pagesRefCache[refStr]) || null;
<add> },
<ide> };
<ide>
<ide> function isValidExplicitDestination(dest) { | 1 |
Javascript | Javascript | take object as first parameter | b6becb40c08230c96377a1b927b9f56b4c0b28e1 | <ide><path>lib/webpack.js
<ide> exportPlugins(exports.debug = {}, {
<ide> "ProfilingPlugin": () => require("./debug/ProfilingPlugin"),
<ide> });
<ide>
<del>const defineMissingPluginError = (pluginName, errorMessage) => {
<del> Reflect.defineProperty(exports.optimize, pluginName, {
<add>const defineMissingPluginError = (namespace, pluginName, errorMessage) => {
<add> Reflect.defineProperty(namespace, pluginName, {
<ide> configurable: false,
<ide> enumerable: true,
<ide> get() {
<ide> const defineMissingPluginError = (pluginName, errorMessage) => {
<ide>
<ide> // TODO remove in webpack 5
<ide> defineMissingPluginError(
<add> exports.optimize,
<ide> "UglifyJsPlugin",
<ide> "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead."
<ide> );
<ide>
<ide> // TODO remove in webpack 5
<ide> defineMissingPluginError(
<add> exports.optimize,
<ide> "CommonsChunkPlugin",
<ide> "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead."
<ide> ); | 1 |
PHP | PHP | fix most test failures in cake\network | aedd63feedd27ccb590aa15a44560a049c5c09a5 | <ide><path>lib/Cake/Network/Email/Email.php
<ide> public function send($content = null) {
<ide> if ($this->_config['log'] !== true) {
<ide> $level = $this->_config['log'];
<ide> }
<del> Log::write($level, PHP_EOL . $contents['headers'] . PHP_EOL . $contents['message']);
<add> Log::write($level, PHP_EOL . $contents['headers'] . PHP_EOL . $contents['message'], ['email']);
<ide> }
<ide> return $contents;
<ide> }
<ide><path>lib/Cake/Network/Http/HttpSocket.php
<ide> <?php
<ide> /**
<del> * HTTP Socket connection class.
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @package Cake.Network.Http
<ide> * @since CakePHP(tm) v 1.2.0
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Network\Http;
<add>
<ide> use Cake\Core\App;
<ide> use Cake\Error;
<ide> use Cake\Network\Socket;
<ide><path>lib/Cake/Test/TestCase/Network/Email/EmailTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Log\Log;
<add>use Cake\Log\LogInterface;
<ide> use Cake\Network\Email\Email;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\File;
<ide> class ExtendTransport {
<ide> }
<ide>
<ide> /**
<del> * CakeEmailTest class
<add> * EmailTest class
<ide> *
<ide> * @package Cake.Test.Case.Network.Email
<ide> */
<del>class CakeEmailTest extends TestCase {
<add>class EmailTest extends TestCase {
<ide>
<ide> /**
<ide> * setUp
<ide> public function testSendWithNoContentDispositionAttachments() {
<ide> */
<ide> public function testSendWithLog() {
<ide> $path = CAKE . 'Test/TestApp/tmp/';
<del> Log::config('email', array(
<del> 'engine' => 'FileLog',
<del> 'path' => TMP
<del> ));
<del> Log::drop('default');
<add> $log = $this->getMock('Cake\Log\Engine\BaseLog', ['write'], ['scopes' => 'email']);
<add>
<add> $message = 'Logging This';
<add>
<add> $log->expects($this->once())
<add> ->method('write')
<add> ->with(
<add> 'debug',
<add> $this->logicalAnd(
<add> $this->stringContains($message),
<add> $this->stringContains('cake@cakephp.org'),
<add> $this->stringContains('me@cakephp.org')
<add> )
<add> );
<add>
<add> Log::engine('email', $log);
<add>
<ide> $this->CakeEmail->transport('Debug');
<ide> $this->CakeEmail->to('me@cakephp.org');
<ide> $this->CakeEmail->from('cake@cakephp.org');
<ide> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->config(array('log' => 'cake_test_emails'));
<del> $result = $this->CakeEmail->send("Logging This");
<del>
<del> $File = new File(TMP . 'cake_test_emails.log');
<del> $log = $File->read();
<del> $this->assertTrue(strpos($log, $result['headers']) !== false);
<del> $this->assertTrue(strpos($log, $result['message']) !== false);
<del> $File->delete();
<del> Log::drop('email');
<add> $this->CakeEmail->config(array('log' => 'debug'));
<add> $result = $this->CakeEmail->send($message);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/TestCase/Network/Email/SmtpTransportTest.php
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Network.Email
<ide> * @since CakePHP(tm) v 2.0.0
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Test\TestCase\Network\Email;
<add>
<ide> use Cake\Network\Email\Email;
<ide> use Cake\Network\Email\SmtpTransport;
<ide> use Cake\Network\Socket;
<ide> /**
<ide> * Help to test SmtpTransport
<ide> *
<add> * @package Cake.Test.Case.Network.Email
<ide> */
<ide> class SmtpTestTransport extends SmtpTransport {
<ide>
<ide> public function testConnectEhloTls() {
<ide> /**
<ide> * testConnectEhloTlsOnNonTlsServer method
<ide> *
<del> * @expectedException SocketException
<add> * @expectedException Cake\Error\SocketException
<ide> * @return void
<ide> */
<ide> public function testConnectEhloTlsOnNonTlsServer() {
<ide> public function testConnectEhloTlsOnNonTlsServer() {
<ide> /**
<ide> * testConnectEhloNoTlsOnRequiredTlsServer method
<ide> *
<del> * @expectedException SocketException
<add> * @expectedException Cake\Error\SocketException
<ide> * @return void
<ide> */
<ide> public function testConnectEhloNoTlsOnRequiredTlsServer() {
<ide> public function testRcpt() {
<ide> * @return void
<ide> */
<ide> public function testSendData() {
<del> $this->getMock('Cake\Network\Email\Email', array('message'), array(), 'SmtpCakeEmail');
<del> $email = new \SmtpCakeEmail();
<add> $email = $this->getMock('Cake\Network\Email\Email', array('message'));
<ide> $email->from('noreply@cakephp.org', 'CakePHP Test');
<ide> $email->returnPath('pleasereply@cakephp.org', 'CakePHP Return');
<ide> $email->to('cake@cakephp.org', 'CakePHP');
<ide> public function testSendData() {
<ide> $email->messageID('<4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>');
<ide> $email->subject('Testing SMTP');
<ide> $date = date(DATE_RFC2822);
<del> $email->setHeaders(array('X-Mailer' => SmtpCakeEmail::EMAIL_CLIENT, 'Date' => $date));
<del> $email->expects($this->any())->method('message')->will($this->returnValue(array('First Line', 'Second Line', '.Third Line', '')));
<add> $email->setHeaders(array('X-Mailer' => Email::EMAIL_CLIENT, 'Date' => $date));
<add> $email->expects($this->any())
<add> ->method('message')
<add> ->will($this->returnValue(array('First Line', 'Second Line', '.Third Line', '')));
<ide>
<ide> $data = "From: CakePHP Test <noreply@cakephp.org>\r\n";
<ide> $data .= "Return-Path: CakePHP Return <pleasereply@cakephp.org>\r\n";
<ide><path>lib/Cake/Test/TestCase/Network/Http/HttpSocketTest.php
<ide> <?php
<ide> /**
<del> * HttpSocketTest file
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<del> * @package Cake.Test.Case.Network.Http
<ide> * @since CakePHP(tm) v 1.2.0.4206
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace Cake\Test\TestCase\Network\Http;
<add>
<ide> use Cake\Network\Http\HttpResponse;
<ide> use Cake\Network\Http\HttpSocket;
<ide> use Cake\TestSuite\TestCase;
<ide> * TestAuthentication class
<ide> *
<ide> * @package Cake.Test.Case.Network.Http
<del> * @package Cake.Test.Case.Network.Http
<ide> */
<ide> class TestAuthentication {
<ide>
<ide> public function testRequestWithRedirectAsIntReachingZero() {
<ide> */
<ide> public function testProxy() {
<ide> $this->Socket->reset();
<del> $this->Socket->expects($this->any())->method('connect')->will($this->returnValue(true));
<del> $this->Socket->expects($this->any())->method('read')->will($this->returnValue(false));
<add> $this->Socket->expects($this->any())
<add> ->method('connect')
<add> ->will($this->returnValue(true));
<add>
<add> $this->Socket->expects($this->any())
<add> ->method('read')
<add> ->will($this->returnValue(false));
<ide>
<ide> $this->Socket->configProxy('proxy.server', 123);
<ide> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n";
<ide> public function testProxy() {
<ide> $this->assertEquals($expected, $this->Socket->request['proxy']);
<ide>
<ide> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nProxy-Authorization: Test mark.secret\r\n\r\n";
<del> $this->Socket->configProxy('proxy.server', 123, 'Test', 'mark', 'secret');
<add> $class = __NAMESPACE__ . '\TestAuthentication';
<add> $this->Socket->configProxy('proxy.server', 123, $class, 'mark', 'secret');
<ide> $this->Socket->request('http://www.cakephp.org/');
<ide> $this->assertEquals($expected, $this->Socket->request['raw']);
<ide> $this->assertEquals('proxy.server', $this->Socket->config['host']);
<ide> $this->assertEquals(123, $this->Socket->config['port']);
<ide> $expected = array(
<ide> 'host' => 'proxy.server',
<ide> 'port' => 123,
<del> 'method' => 'Test',
<add> 'method' => $class,
<ide> 'user' => 'mark',
<ide> 'pass' => 'secret'
<ide> );
<ide> $this->assertEquals($expected, $this->Socket->request['proxy']);
<ide>
<del> $this->Socket->configAuth('Test', 'login', 'passwd');
<add> $this->Socket->configAuth($class, 'login', 'passwd');
<ide> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nProxy-Authorization: Test mark.secret\r\nAuthorization: Test login.passwd\r\n\r\n";
<ide> $this->Socket->request('http://www.cakephp.org/');
<ide> $this->assertEquals($expected, $this->Socket->request['raw']);
<ide> $expected = array(
<ide> 'host' => 'proxy.server',
<ide> 'port' => 123,
<del> 'method' => 'Test',
<add> 'method' => $class,
<ide> 'user' => 'mark',
<ide> 'pass' => 'secret'
<ide> );
<ide> $this->assertEquals($expected, $this->Socket->request['proxy']);
<ide> $expected = array(
<del> 'Test' => array(
<add> $class => array(
<ide> 'user' => 'login',
<ide> 'pass' => 'passwd'
<ide> )
<ide> public function testAuth() {
<ide> $socket->get('http://example.com/test');
<ide> $this->assertFalse(strpos($socket->request['header'], 'Authorization:'));
<ide>
<del> $socket->configAuth('Test', 'mark', 'passwd');
<add> $class = __NAMESPACE__ . '\TestAuthentication';
<add> $socket->configAuth($class, 'mark', 'passwd');
<ide> $socket->get('http://example.com/test');
<ide> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Test mark.passwd') !== false);
<ide> } | 5 |
Python | Python | update stable version for published docs | 550395192929f86376151b4385cea6b8dfb76e8e | <ide><path>docs/exts/docs_build/docs_builder.py
<ide> def publish(self):
<ide> pretty_target = pretty_format_path(output_dir, AIRFLOW_SITE_DIR)
<ide> print(f"Copy directory: {pretty_source} => {pretty_target}")
<ide> shutil.copytree(self._build_dir, output_dir)
<add> if self.is_versioned:
<add> with open(os.path.join(output_dir, "..", "stable.txt"), "w") as stable_file:
<add> stable_file.write(self._current_version)
<ide> print()
<ide>
<ide> | 1 |
Text | Text | add beginner solution to pig latin | 7a37788ea163300d37cff800dd6efed3bc86551b | <ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin/index.md
<ide> You will need to use everything you know about string manipulation to get the la
<ide>
<ide> **Solution ahead!**
<ide>
<add>##  Basic Code Solution:
<add>
<add> function translatePigLatin(str) {
<add> let consonantRegex = /^[^aeiou]+/;
<add> let myConsonants = str.match(consonantRegex);
<add> return (myConsonants !== null) ? str.replace(consonantRegex, "").concat(myConsonants).concat("ay") : str.concat("way");
<add> }
<add>
<add> translatePigLatin("consonant");
<add>
<add>
<add>### Code Explanation:
<add>* start at beginning and get longest match of everything not a vowel (consonants)
<add>* if regex pattern found, it saves the match; else, it returns null
<add>
<add>* if regex pattern found (starts with consonants), it deletes match, adds the match to the end, and adds "ay" to the end
<add>* if regex pattern not found (starts with vowels), it just adds "way" to the ending
<add>
<add>#### Relevant Links
<add>
<add>* <a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet/" target='_blank' rel='nofollow'>Regex Match</a>
<add>* <a href='https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator/' target='_blank' rel='nofollow'>Ternary Operator</a>
<add>* <a href='https://guide.freecodecamp.org/javascript/standard-objects/string/string-prototype-concat/' target='_blank' rel='nofollow'>concat()</a>
<add>
<add>
<ide> ##  Basic Code Solution:
<ide>
<ide> function translatePigLatin(str) { | 1 |
Javascript | Javascript | avoid toboolean coercion in `meta_listeners` | eea8c112213138a47a53547fc15fb37300e747b9 | <ide><path>packages/ember-metal/lib/is_proxy.js
<ide> import { peekMeta } from './meta';
<ide>
<ide> export function isProxy(value) {
<del> if (typeof value === 'object' && value) {
<add> if (typeof value === 'object' && value !== null) {
<ide> let meta = peekMeta(value);
<ide> return meta && meta.isProxy();
<ide> }
<ide><path>packages/ember-metal/lib/meta_listeners.js
<ide> export const SUSPENDED = 2;
<ide> export const protoMethods = {
<ide>
<ide> addToListeners(eventName, target, method, flags) {
<del> if (!this._listeners) {
<add> if (this._listeners === undefined) {
<ide> this._listeners = [];
<ide> }
<ide> this._listeners.push(eventName, target, method, flags);
<ide> },
<ide>
<ide> _finalizeListeners() {
<ide> if (this._listenersFinalized) { return; }
<del> if (!this._listeners) { this._listeners = []; }
<add> if (this._listeners === undefined) { this._listeners = []; }
<ide> let pointer = this.parent;
<del> while (pointer) {
<add> while (pointer !== undefined) {
<ide> let listeners = pointer._listeners;
<del> if (listeners) {
<add> if (listeners !== undefined) {
<ide> this._listeners = this._listeners.concat(listeners);
<ide> }
<ide> if (pointer._listenersFinalized) { break; }
<ide> export const protoMethods = {
<ide>
<ide> removeFromListeners(eventName, target, method, didRemove) {
<ide> let pointer = this;
<del> while (pointer) {
<add> while (pointer !== undefined) {
<ide> let listeners = pointer._listeners;
<del> if (listeners) {
<add> if (listeners !== undefined) {
<ide> for (let index = listeners.length - 4; index >= 0; index -= 4) {
<ide> if (listeners[index] === eventName && (!method || (listeners[index + 1] === target && listeners[index + 2] === method))) {
<ide> if (pointer === this) {
<ide> export const protoMethods = {
<ide> watchedEvents() {
<ide> let pointer = this;
<ide> let names = {};
<del> while (pointer) {
<add> while (pointer !== undefined) {
<ide> let listeners = pointer._listeners;
<del> if (listeners) {
<add> if (listeners !== undefined) {
<ide> for (let index = 0; index < listeners.length - 3; index += 4) {
<ide> names[listeners[index]] = true;
<ide> }
<ide> function pushUniqueListener(destination, source, index) {
<ide> let target = source[index + 1];
<ide> let method = source[index + 2];
<ide> for (let destinationIndex = 0; destinationIndex < destination.length - 2; destinationIndex += 3) {
<del> if (destination[destinationIndex] === target && destination[destinationIndex + 1] === method) {
<add> if (destination[destinationIndex] === target && destination[destinationIndex + 1] === method) {
<ide> return;
<ide> }
<ide> }
<ide><path>packages/ember-metal/lib/tags.js
<ide> export function tagForProperty(object, propertyKey, _meta) {
<ide> }
<ide>
<ide> export function tagFor(object, _meta) {
<del> if (typeof object === 'object' && object) {
<add> if (typeof object === 'object' && object !== null) {
<ide> let meta = _meta || metaFor(object);
<ide> return meta.writableTag(makeTag);
<ide> } else { | 3 |
PHP | PHP | fix deprecation message | b4fa77e1da222eb7c5a53a92ff9d5747e94a77f5 | <ide><path>src/View/ViewBuilder.php
<ide> public function build(
<ide>
<ide> if (!empty($vars)) {
<ide> deprecationWarning(
<del> 'The $vars argument is deprecated. Use the setVar()/setVar() methods instead.'
<add> 'The $vars argument is deprecated. Use the setVar()/setVars() methods instead.'
<ide> );
<ide> }
<ide> | 1 |
Ruby | Ruby | correct the time comparison for remember_me token | 7564da46f23bb0075390e44b5fbedcdc8a0c4dc5 | <ide><path>activesupport/lib/active_support/message_verifier.rb
<ide> module ActiveSupport
<ide> # In the authentication filter:
<ide> #
<ide> # id, time = @verifier.verify(cookies[:remember_me])
<del> # if time < Time.now
<add> # if Time.now < time
<ide> # self.current_user = User.find(id)
<ide> # end
<ide> # | 1 |
Javascript | Javascript | use accessors for eventtransitions | 9ef59af7269fdea81be06eb51fbf2e640a39e67c | <ide><path>packages/ember-states/lib/state.js
<ide> Ember.State = Ember.Object.extend(Ember.Evented,
<ide> init: function() {
<ide> var states = get(this, 'states'), foundStates;
<ide> set(this, 'childStates', Ember.A());
<del> this.eventTransitions = this.eventTransitions || {};
<add> set(this, 'eventTransitions', get(this, 'eventTransitions') || {});
<ide>
<ide> var name, value, transitionTarget;
<ide> | 1 |
Python | Python | fix some unicode issues | c3a0fb9711a119ac303d18719cea702efeff408f | <ide><path>doc/sphinxext/numpydoc.py
<ide> def mangle_docstrings(app, what, name, obj, options, lines,
<ide>
<ide> if what == 'module':
<ide> # Strip top title
<del> title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*',
<add> title_re = re.compile(ur'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*',
<ide> re.I|re.S)
<del> lines[:] = title_re.sub('', "\n".join(lines)).split("\n")
<add> lines[:] = title_re.sub(u'', u"\n".join(lines)).split(u"\n")
<ide> else:
<del> doc = get_doc_object(obj, what, "\n".join(lines))
<add> doc = get_doc_object(obj, what, u"\n".join(lines))
<ide> doc.use_plots = app.config.numpydoc_use_plots
<del> lines[:] = str(doc).split("\n")
<add> lines[:] = unicode(doc).split(u"\n")
<ide>
<ide> if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
<ide> obj.__name__:
<ide> if hasattr(obj, '__module__'):
<del> v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__))
<add> v = dict(full_name=u"%s.%s" % (obj.__module__, obj.__name__))
<ide> else:
<ide> v = dict(full_name=obj.__name__)
<del> lines += ['', '.. htmlonly::', '']
<del> lines += [' %s' % x for x in
<add> lines += [u'', u'.. htmlonly::', '']
<add> lines += [u' %s' % x for x in
<ide> (app.config.numpydoc_edit_link % v).split("\n")]
<ide>
<ide> # replace reference numbers so that there are no duplicates
<ide> references = []
<ide> for line in lines:
<ide> line = line.strip()
<del> m = re.match(r'^.. \[([a-z0-9_.-])\]', line, re.I)
<add> m = re.match(ur'^.. \[([a-z0-9_.-])\]', line, re.I)
<ide> if m:
<ide> references.append(m.group(1))
<ide>
<ide> def mangle_docstrings(app, what, name, obj, options, lines,
<ide> if references:
<ide> for i, line in enumerate(lines):
<ide> for r in references:
<del> if re.match(r'^\d+$', r):
<del> new_r = "R%d" % (reference_offset[0] + int(r))
<add> if re.match(ur'^\d+$', r):
<add> new_r = u"R%d" % (reference_offset[0] + int(r))
<ide> else:
<del> new_r = "%s%d" % (r, reference_offset[0])
<del> lines[i] = lines[i].replace('[%s]_' % r,
<del> '[%s]_' % new_r)
<del> lines[i] = lines[i].replace('.. [%s]' % r,
<del> '.. [%s]' % new_r)
<add> new_r = u"%s%d" % (r, reference_offset[0])
<add> lines[i] = lines[i].replace(u'[%s]_' % r,
<add> u'[%s]_' % new_r)
<add> lines[i] = lines[i].replace(u'.. [%s]' % r,
<add> u'.. [%s]' % new_r)
<ide>
<ide> reference_offset[0] += len(references)
<ide>
<ide> def mangle_signature(app, what, name, obj, options, sig, retann):
<ide>
<ide> doc = SphinxDocString(pydoc.getdoc(obj))
<ide> if doc['Signature']:
<del> sig = re.sub("^[^(]*", "", doc['Signature'])
<del> return sig, ''
<add> sig = re.sub(u"^[^(]*", u"", doc['Signature'])
<add> return sig, u''
<ide>
<ide> def initialize(app):
<ide> try: | 1 |
Mixed | Python | fix typo in athena sensor retries | 2b8dea64e9e8716fba8c38a1b439f7835bbd2918 | <ide><path>UPDATING.md
<ide> The `AwsBatchOperator` can use a new `waiters` parameter, an instance of `AwsBat
<ide> specify that custom job waiters will be used to monitor a batch job. See the latest API
<ide> documentation for details.
<ide>
<add>### AthenaSensor
<add>
<add>Replace parameter `max_retires` with `max_retries` to fix typo.
<add>
<ide> ### Additional arguments passed to BaseOperator cause an exception
<ide>
<ide> Previous versions of Airflow took additional arguments and displayed a message on the console. When the
<ide><path>airflow/providers/amazon/aws/sensors/athena.py
<ide> class AthenaSensor(BaseSensorOperator):
<ide> """
<ide> Asks for the state of the Query until it reaches a failure state or success state.
<del> If it fails, failing the task.
<add> If the query fails, the task will fail.
<ide>
<ide> :param query_execution_id: query_execution_id to check the state of
<ide> :type query_execution_id: str
<del> :param max_retires: Number of times to poll for query state before
<add> :param max_retries: Number of times to poll for query state before
<ide> returning the current state, defaults to None
<del> :type max_retires: int
<add> :type max_retries: int
<ide> :param aws_conn_id: aws connection to use, defaults to 'aws_default'
<ide> :type aws_conn_id: str
<del> :param sleep_time: Time to wait between two consecutive call to
<add> :param sleep_time: Time in seconds to wait between two consecutive call to
<ide> check query status on athena, defaults to 10
<ide> :type sleep_time: int
<ide> """
<ide> class AthenaSensor(BaseSensorOperator):
<ide> @apply_defaults
<ide> def __init__(self,
<ide> query_execution_id,
<del> max_retires=None,
<add> max_retries=None,
<ide> aws_conn_id='aws_default',
<ide> sleep_time=10,
<ide> *args, **kwargs):
<ide> super().__init__(*args, **kwargs)
<ide> self.aws_conn_id = aws_conn_id
<ide> self.query_execution_id = query_execution_id
<ide> self.sleep_time = sleep_time
<del> self.max_retires = max_retires
<add> self.max_retries = max_retries
<ide> self.hook = None
<ide>
<ide> def poke(self, context):
<del> state = self.get_hook().poll_query_status(self.query_execution_id, self.max_retires)
<add> state = self.get_hook().poll_query_status(self.query_execution_id, self.max_retries)
<ide>
<ide> if state in self.FAILURE_STATES:
<ide> raise AirflowException('Athena sensor failed')
<ide><path>tests/providers/amazon/aws/sensors/test_athena.py
<ide> def setUp(self):
<ide> self.sensor = AthenaSensor(task_id='test_athena_sensor',
<ide> query_execution_id='abc',
<ide> sleep_time=5,
<del> max_retires=1,
<add> max_retries=1,
<ide> aws_conn_id='aws_default')
<ide>
<ide> @mock.patch.object(AWSAthenaHook, 'poll_query_status', side_effect=("SUCCEEDED",)) | 3 |
Python | Python | use yaml safe load | 7f4935bab36c41d5927610e38c46a30da2b80906 | <ide><path>airflow/providers/google/cloud/operators/cloud_build.py
<ide> def prepare_template(self) -> None:
<ide> return
<ide> with open(self.build_raw) as file:
<ide> if any(self.build_raw.endswith(ext) for ext in ['.yaml', '.yml']):
<del> self.build = yaml.load(file.read(), Loader=yaml.FullLoader)
<add> self.build = yaml.safe_load_all(file.read())
<ide> if self.build_raw.endswith('.json'):
<ide> self.build = json.loads(file.read())
<ide> | 1 |
Python | Python | add tests for recent void byteswap problem | 29cb5ffae98ad43a3e7ebada8dc77ce0a4045529 | <ide><path>numpy/core/tests/test_regression.py
<ide> def check_void_coercion(self, level=rlevel):
<ide> dt = N.dtype([('a','f4'),('b','i4')])
<ide> x = N.zeros((1,),dt)
<ide> assert(N.r_[x,x].dtype == dt)
<add>
<add> def check_void_copyswap(self, level=rlevel):
<add> dt = N.dtype([('one', '<i4'),('two', '<i4')])
<add> x = N.array((1,2), dtype=dt)
<add> x = x.byteswap()
<add> assert(x['one'] > 1 and x['two'] > 2)
<ide>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run() | 1 |
Mixed | Ruby | add option for class_attribute default | 1c275d812f35f53f93cd96184a4f319983766cc5 | <ide><path>actioncable/lib/action_cable/channel/periodic_timers.rb
<ide> module PeriodicTimers
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :periodic_timers, instance_reader: false
<del> self.periodic_timers = []
<add> class_attribute :periodic_timers, instance_reader: false, default: []
<ide>
<ide> after_subscribe :start_periodic_timers
<ide> after_unsubscribe :stop_periodic_timers
<ide><path>actioncable/lib/action_cable/connection/identification.rb
<ide> module Identification
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :identifiers
<del> self.identifiers = Set.new
<add> class_attribute :identifiers, default: Set.new
<ide> end
<ide>
<ide> class_methods do
<ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def _protected_ivars # :nodoc:
<ide>
<ide> helper ActionMailer::MailHelper
<ide>
<del> class_attribute :default_params
<del> self.default_params = {
<add> class_attribute :default_params, default: {
<ide> mime_version: "1.0",
<ide> charset: "UTF-8",
<ide> content_type: "text/plain",
<ide><path>actionmailer/lib/action_mailer/delivery_methods.rb
<ide> module DeliveryMethods
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :delivery_methods, :delivery_method
<del>
<ide> # Do not make this inheritable, because we always want it to propagate
<ide> cattr_accessor :raise_delivery_errors
<ide> self.raise_delivery_errors = true
<ide> module DeliveryMethods
<ide> cattr_accessor :deliver_later_queue_name
<ide> self.deliver_later_queue_name = :mailers
<ide>
<del> self.delivery_methods = {}.freeze
<del> self.delivery_method = :smtp
<add> class_attribute :delivery_methods, default: {}.freeze
<add> class_attribute :delivery_method, default: :smtp
<ide>
<ide> add_delivery_method :smtp, Mail::SMTP,
<ide> address: "localhost",
<ide><path>actionpack/lib/abstract_controller/caching.rb
<ide> def cache_configured?
<ide> config_accessor :enable_fragment_cache_logging
<ide> self.enable_fragment_cache_logging = false
<ide>
<del> class_attribute :_view_cache_dependencies
<del> self._view_cache_dependencies = []
<add> class_attribute :_view_cache_dependencies, default: []
<ide> helper_method :view_cache_dependencies if respond_to?(:helper_method)
<ide> end
<ide>
<ide><path>actionpack/lib/abstract_controller/helpers.rb
<ide> module Helpers
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :_helpers
<del> self._helpers = Module.new
<del>
<del> class_attribute :_helper_methods
<del> self._helper_methods = Array.new
<add> class_attribute :_helpers, default: Module.new
<add> class_attribute :_helper_methods, default: Array.new
<ide> end
<ide>
<ide> class MissingHelperError < LoadError
<ide><path>actionpack/lib/action_controller/metal.rb
<ide> def reset_session
<ide> @_request.reset_session
<ide> end
<ide>
<del> class_attribute :middleware_stack
<del> self.middleware_stack = ActionController::MiddlewareStack.new
<add> class_attribute :middleware_stack, default: ActionController::MiddlewareStack.new
<ide>
<ide> def self.inherited(base) # :nodoc:
<ide> base.middleware_stack = middleware_stack.dup
<ide><path>actionpack/lib/action_controller/metal/conditional_get.rb
<ide> module ConditionalGet
<ide> include Head
<ide>
<ide> included do
<del> class_attribute :etaggers
<del> self.etaggers = []
<add> class_attribute :etaggers, default: []
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>actionpack/lib/action_controller/metal/etag_with_template_digest.rb
<ide> module EtagWithTemplateDigest
<ide> include ActionController::ConditionalGet
<ide>
<ide> included do
<del> class_attribute :etag_with_template_digest
<del> self.etag_with_template_digest = true
<add> class_attribute :etag_with_template_digest, default: true
<ide>
<ide> ActiveSupport.on_load :action_view, yield: true do
<ide> etag do |options|
<ide><path>actionpack/lib/action_controller/metal/flash.rb
<ide> module Flash
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :_flash_types, instance_accessor: false
<del> self._flash_types = []
<add> class_attribute :_flash_types, instance_accessor: false, default: []
<ide>
<ide> delegate :flash, to: :request
<ide> add_flash_types(:alert, :notice)
<ide><path>actionpack/lib/action_controller/metal/helpers.rb
<ide> class << self; attr_accessor :helpers_path; end
<ide> include AbstractController::Helpers
<ide>
<ide> included do
<del> class_attribute :helpers_path, :include_all_helpers
<del> self.helpers_path ||= []
<del> self.include_all_helpers = true
<add> class_attribute :helpers_path, default: []
<add> class_attribute :include_all_helpers, default: true
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>actionpack/lib/action_controller/metal/params_wrapper.rb
<ide> def _default_wrap_model
<ide> end
<ide>
<ide> included do
<del> class_attribute :_wrapper_options
<del> self._wrapper_options = Options.from_hash(format: [])
<add> class_attribute :_wrapper_options, default: Options.from_hash(format: [])
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>actionpack/lib/action_controller/metal/renderers.rb
<ide> module Renderers
<ide> RENDERERS = Set.new
<ide>
<ide> included do
<del> class_attribute :_renderers
<del> self._renderers = Set.new.freeze
<add> class_attribute :_renderers, default: Set.new.freeze
<ide> end
<ide>
<ide> # Used in <tt>ActionController::Base</tt>
<ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> class FormBuilder
<ide> include ModelNaming
<ide>
<ide> # The methods which wrap a form helper call.
<del> class_attribute :field_helpers
<del> self.field_helpers = [:fields_for, :fields, :label, :text_field, :password_field,
<del> :hidden_field, :file_field, :text_area, :check_box,
<del> :radio_button, :color_field, :search_field,
<del> :telephone_field, :phone_field, :date_field,
<del> :time_field, :datetime_field, :datetime_local_field,
<del> :month_field, :week_field, :url_field, :email_field,
<del> :number_field, :range_field]
<add> class_attribute :field_helpers, default: [
<add> :fields_for, :fields, :label, :text_field, :password_field,
<add> :hidden_field, :file_field, :text_area, :check_box,
<add> :radio_button, :color_field, :search_field,
<add> :telephone_field, :phone_field, :date_field,
<add> :time_field, :datetime_field, :datetime_local_field,
<add> :month_field, :week_field, :url_field, :email_field,
<add> :number_field, :range_field
<add> ]
<ide>
<ide> attr_accessor :object_name, :object, :options
<ide>
<ide><path>actionview/lib/action_view/layouts.rb
<ide> module Layouts
<ide> include ActionView::Rendering
<ide>
<ide> included do
<del> class_attribute :_layout, :_layout_conditions, instance_accessor: false
<del> self._layout = nil
<del> self._layout_conditions = {}
<add> class_attribute :_layout, instance_accessor: false
<add> class_attribute :_layout_conditions, instance_accessor: false, default: {}
<add>
<ide> _write_layout_method
<ide> end
<ide>
<ide><path>actionview/lib/action_view/template/handlers/builder.rb
<ide> module ActionView
<ide> module Template::Handlers
<ide> class Builder
<del> # Default format used by Builder.
<del> class_attribute :default_format
<del> self.default_format = :xml
<add> class_attribute :default_format, default: :xml
<ide>
<ide> def call(template)
<ide> require_engine
<ide> def call(template)
<ide> end
<ide>
<ide> private
<del>
<ide> def require_engine # :doc:
<ide> @required ||= begin
<ide> require "builder"
<ide><path>actionview/lib/action_view/template/handlers/erb.rb
<ide> class ERB
<ide>
<ide> # Specify trim mode for the ERB compiler. Defaults to '-'.
<ide> # See ERB documentation for suitable values.
<del> class_attribute :erb_trim_mode
<del> self.erb_trim_mode = "-"
<add> class_attribute :erb_trim_mode, default: "-"
<ide>
<ide> # Default implementation used.
<del> class_attribute :erb_implementation
<del> self.erb_implementation = Erubi
<add> class_attribute :erb_implementation, default: Erubi
<ide>
<ide> # Do not escape templates of these mime types.
<del> class_attribute :escape_whitelist
<del> self.escape_whitelist = ["text/plain"]
<add> class_attribute :escape_whitelist, default: ["text/plain"]
<ide>
<ide> ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")
<ide>
<ide><path>actionview/lib/action_view/view_paths.rb
<ide> module ViewPaths
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :_view_paths
<del> self._view_paths = ActionView::PathSet.new
<del> _view_paths.freeze
<add> class_attribute :_view_paths, default: ActionView::PathSet.new.freeze
<ide> end
<ide>
<ide> delegate :template_exists?, :any_templates?, :view_paths, :formats, :formats=,
<ide><path>activejob/lib/active_job/queue_name.rb
<ide> def queue_name_from_part(part_name) #:nodoc:
<ide> end
<ide>
<ide> included do
<del> class_attribute :queue_name, instance_accessor: false
<del> class_attribute :queue_name_delimiter, instance_accessor: false
<del>
<del> self.queue_name = default_queue_name
<del> self.queue_name_delimiter = "_" # set default delimiter to '_'
<add> class_attribute :queue_name, instance_accessor: false, default: default_queue_name
<add> class_attribute :queue_name_delimiter, instance_accessor: false, default: "_"
<ide> end
<ide>
<ide> # Returns the name of the queue the job will be run on.
<ide><path>activejob/lib/active_job/queue_priority.rb
<ide> def queue_with_priority(priority = nil, &block)
<ide> end
<ide>
<ide> included do
<del> class_attribute :priority, instance_accessor: false
<del>
<del> self.priority = default_priority
<add> class_attribute :priority, instance_accessor: false, default: default_priority
<ide> end
<ide>
<ide> # Returns the priority that the job will be created with
<ide><path>activemodel/lib/active_model/attribute_methods.rb
<ide> module AttributeMethods
<ide> CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
<ide>
<ide> included do
<del> class_attribute :attribute_aliases, :attribute_method_matchers, instance_writer: false
<del> self.attribute_aliases = {}
<del> self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
<add> class_attribute :attribute_aliases, instance_writer: false, default: {}
<add> class_attribute :attribute_method_matchers, instance_writer: false, default: [ ClassMethods::AttributeMethodMatcher.new ]
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activemodel/lib/active_model/serializers/json.rb
<ide> module JSON
<ide> included do
<ide> extend ActiveModel::Naming
<ide>
<del> class_attribute :include_root_in_json, instance_writer: false
<del> self.include_root_in_json = false
<add> class_attribute :include_root_in_json, instance_writer: false, default: false
<ide> end
<ide>
<ide> # Returns a hash representing the model. Some configuration can be
<ide><path>activemodel/lib/active_model/validations.rb
<ide> module Validations
<ide> private :validation_context=
<ide> define_callbacks :validate, scope: :name
<ide>
<del> class_attribute :_validators, instance_writer: false
<del> self._validators = Hash.new { |h, k| h[k] = [] }
<add> class_attribute :_validators, instance_writer: false, default: Hash.new { |h, k| h[k] = [] }
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activerecord/lib/active_record/attribute_decorators.rb
<ide> module AttributeDecorators # :nodoc:
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :attribute_type_decorations, instance_accessor: false # :internal:
<del> self.attribute_type_decorations = TypeDecorator.new
<add> class_attribute :attribute_type_decorations, instance_accessor: false, default: TypeDecorator.new # :internal:
<ide> end
<ide>
<ide> module ClassMethods # :nodoc:
<ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb
<ide> module Dirty # :nodoc:
<ide> raise "You cannot include Dirty after Timestamp"
<ide> end
<ide>
<del> class_attribute :partial_writes, instance_writer: false
<del> self.partial_writes = true
<add> class_attribute :partial_writes, instance_writer: false, default: true
<ide>
<ide> after_create { changes_internally_applied }
<ide> after_update { changes_internally_applied }
<ide><path>activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
<ide> def map_avoiding_infinite_recursion(value)
<ide> mattr_accessor :time_zone_aware_attributes, instance_writer: false
<ide> self.time_zone_aware_attributes = false
<ide>
<del> class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false
<del> self.skip_time_zone_conversion_for_attributes = []
<del>
<del> class_attribute :time_zone_aware_types, instance_writer: false
<del> self.time_zone_aware_types = [:datetime, :time]
<add> class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false, default: []
<add> class_attribute :time_zone_aware_types, instance_writer: false, default: [ :datetime, :time ]
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activerecord/lib/active_record/attributes.rb
<ide> module Attributes
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :attributes_to_define_after_schema_loads, instance_accessor: false # :internal:
<del> self.attributes_to_define_after_schema_loads = {}
<add> class_attribute :attributes_to_define_after_schema_loads, instance_accessor: false, default: {} # :internal:
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def update_table_definition(table_name, base) # :nodoc:
<ide> # to your application.rb file:
<ide> #
<ide> # ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans = false
<del> class_attribute :emulate_booleans
<del> self.emulate_booleans = true
<add> class_attribute :emulate_booleans, default: true
<ide>
<ide> NATIVE_DATABASE_TYPES = {
<ide> primary_key: "bigint auto_increment PRIMARY KEY",
<ide><path>activerecord/lib/active_record/enum.rb
<ide> module ActiveRecord
<ide>
<ide> module Enum
<ide> def self.extended(base) # :nodoc:
<del> base.class_attribute(:defined_enums, instance_writer: false)
<del> base.defined_enums = {}
<add> base.class_attribute(:defined_enums, instance_writer: false, default: {})
<ide> end
<ide>
<ide> def inherited(base) # :nodoc:
<ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def after_teardown # :nodoc:
<ide>
<ide> included do
<ide> class_attribute :fixture_path, instance_writer: false
<del> class_attribute :fixture_table_names
<del> class_attribute :fixture_class_names
<del> class_attribute :use_transactional_tests
<del> class_attribute :use_instantiated_fixtures # true, false, or :no_instances
<del> class_attribute :pre_loaded_fixtures
<del> class_attribute :config
<del>
<del> self.fixture_table_names = []
<del> self.use_instantiated_fixtures = false
<del> self.pre_loaded_fixtures = false
<del> self.config = ActiveRecord::Base
<del>
<del> self.fixture_class_names = {}
<del> self.use_transactional_tests = true
<add> class_attribute :fixture_table_names, default: []
<add> class_attribute :fixture_class_names, default: {}
<add> class_attribute :use_transactional_tests, default: true
<add> class_attribute :use_instantiated_fixtures, default: false # true, false, or :no_instances
<add> class_attribute :pre_loaded_fixtures, default: false
<add> class_attribute :config, default: ActiveRecord::Base
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activerecord/lib/active_record/inheritance.rb
<ide> module Inheritance
<ide> included do
<ide> # Determines whether to store the full constant name including namespace when using STI.
<ide> # This is true, by default.
<del> class_attribute :store_full_sti_class, instance_writer: false
<del> self.store_full_sti_class = true
<add> class_attribute :store_full_sti_class, instance_writer: false, default: true
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activerecord/lib/active_record/integration.rb
<ide> module Integration
<ide> # versioning is off. Accepts any of the symbols in <tt>Time::DATE_FORMATS</tt>.
<ide> #
<ide> # This is +:usec+, by default.
<del> class_attribute :cache_timestamp_format, instance_writer: false
<del> self.cache_timestamp_format = :usec
<add> class_attribute :cache_timestamp_format, instance_writer: false, default: :usec
<ide>
<ide> ##
<ide> # :singleton-method:
<ide> # Indicates whether to use a stable #cache_key method that is accompanied
<ide> # by a changing version in the #cache_version method.
<ide> #
<ide> # This is +false+, by default until Rails 6.0.
<del> class_attribute :cache_versioning, instance_writer: false
<del> self.cache_versioning = false
<add> class_attribute :cache_versioning, instance_writer: false, default: false
<ide> end
<ide>
<ide> # Returns a +String+, which Action Pack uses for constructing a URL to this
<ide><path>activerecord/lib/active_record/locking/optimistic.rb
<ide> module Optimistic
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :lock_optimistically, instance_writer: false
<del> self.lock_optimistically = true
<add> class_attribute :lock_optimistically, instance_writer: false, default: true
<ide> end
<ide>
<ide> def locking_enabled? #:nodoc:
<ide><path>activerecord/lib/active_record/model_schema.rb
<ide> module ModelSchema
<ide> included do
<ide> mattr_accessor :primary_key_prefix_type, instance_writer: false
<ide>
<del> class_attribute :table_name_prefix, instance_writer: false
<del> self.table_name_prefix = ""
<del>
<del> class_attribute :table_name_suffix, instance_writer: false
<del> self.table_name_suffix = ""
<del>
<del> class_attribute :schema_migrations_table_name, instance_accessor: false
<del> self.schema_migrations_table_name = "schema_migrations"
<del>
<del> class_attribute :internal_metadata_table_name, instance_accessor: false
<del> self.internal_metadata_table_name = "ar_internal_metadata"
<del>
<del> class_attribute :protected_environments, instance_accessor: false
<del> self.protected_environments = ["production"]
<del>
<del> class_attribute :pluralize_table_names, instance_writer: false
<del> self.pluralize_table_names = true
<del>
<del> class_attribute :ignored_columns, instance_accessor: false
<del> self.ignored_columns = [].freeze
<add> class_attribute :table_name_prefix, instance_writer: false, default: ""
<add> class_attribute :table_name_suffix, instance_writer: false, default: ""
<add> class_attribute :schema_migrations_table_name, instance_accessor: false, default: "schema_migrations"
<add> class_attribute :internal_metadata_table_name, instance_accessor: false, default: "ar_internal_metadata"
<add> class_attribute :protected_environments, instance_accessor: false, default: [ "production" ]
<add> class_attribute :pluralize_table_names, instance_writer: false, default: true
<add> class_attribute :ignored_columns, instance_accessor: false, default: [].freeze
<ide>
<ide> self.inheritance_column = "type"
<ide>
<ide><path>activerecord/lib/active_record/nested_attributes.rb
<ide> class TooManyRecords < ActiveRecordError
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :nested_attributes_options, instance_writer: false
<del> self.nested_attributes_options = {}
<add> class_attribute :nested_attributes_options, instance_writer: false, default: {}
<ide> end
<ide>
<ide> # = Active Record Nested Attributes
<ide><path>activerecord/lib/active_record/readonly_attributes.rb
<ide> module ReadonlyAttributes
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :_attr_readonly, instance_accessor: false
<del> self._attr_readonly = []
<add> class_attribute :_attr_readonly, instance_accessor: false, default: []
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activerecord/lib/active_record/reflection.rb
<ide> module Reflection # :nodoc:
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :_reflections, instance_writer: false
<del> class_attribute :aggregate_reflections, instance_writer: false
<del> self._reflections = {}
<del> self.aggregate_reflections = {}
<add> class_attribute :_reflections, instance_writer: false, default: {}
<add> class_attribute :aggregate_reflections, instance_writer: false, default: {}
<ide> end
<ide>
<ide> def self.create(macro, name, scope, options, ar)
<ide><path>activerecord/lib/active_record/scoping/default.rb
<ide> module Default
<ide>
<ide> included do
<ide> # Stores the default scope for the class.
<del> class_attribute :default_scopes, instance_writer: false, instance_predicate: false
<del> class_attribute :default_scope_override, instance_writer: false, instance_predicate: false
<del>
<del> self.default_scopes = []
<del> self.default_scope_override = nil
<add> class_attribute :default_scopes, instance_writer: false, instance_predicate: false, default: []
<add> class_attribute :default_scope_override, instance_writer: false, instance_predicate: false, default: nil
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activerecord/lib/active_record/timestamp.rb
<ide> module Timestamp
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :record_timestamps
<del> self.record_timestamps = true
<add> class_attribute :record_timestamps, default: true
<ide> end
<ide>
<ide> def initialize_dup(other) # :nodoc:
<ide><path>activesupport/CHANGELOG.md
<add>* Add default option to class_attribute. Before:
<add>
<add> class_attribute :settings
<add> self.settings = {}
<add>
<add> Now:
<add>
<add> class_attribute :settings, default: {}
<add>
<add> *DHH*
<add>
<ide> * `#singularize` and `#pluralize` now respect uncountables for the specified locale.
<ide>
<ide> *Eilis Hamilton*
<ide><path>activesupport/lib/active_support/callbacks.rb
<ide> module Callbacks
<ide>
<ide> included do
<ide> extend ActiveSupport::DescendantsTracker
<del> class_attribute :__callbacks, instance_writer: false
<del> self.__callbacks ||= {}
<add> class_attribute :__callbacks, instance_writer: false, default: {}
<ide> end
<ide>
<ide> CALLBACK_FILTER_TYPES = [:before, :after, :around]
<ide><path>activesupport/lib/active_support/core_ext/class/attribute.rb
<ide> class Class
<ide> # object.setting = false # => NoMethodError
<ide> #
<ide> # To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
<add> #
<add> # To set a default value for the attribute, pass <tt>default:</tt>, like so:
<add> #
<add> # class_attribute :settings, default: {}
<ide> def class_attribute(*attrs)
<ide> options = attrs.extract_options!
<del> instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
<del> instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
<add> instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
<add> instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
<ide> instance_predicate = options.fetch(:instance_predicate, true)
<add> default_value = options.fetch(:default, nil)
<ide>
<ide> attrs.each do |name|
<ide> remove_possible_singleton_method(name)
<ide> def class_attribute(*attrs)
<ide> remove_possible_method "#{name}="
<ide> attr_writer name
<ide> end
<add>
<add> unless default_value.nil?
<add> self.send("#{name}=", default_value)
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/reloader.rb
<ide> def self.wrap
<ide> end
<ide> end
<ide>
<del> class_attribute :executor
<del> class_attribute :check
<del>
<del> self.executor = Executor
<del> self.check = lambda { false }
<add> class_attribute :executor, default: Executor
<add> class_attribute :check, default: lambda { false }
<ide>
<ide> def self.check! # :nodoc:
<ide> @should_reload ||= check.call
<ide><path>activesupport/lib/active_support/rescuable.rb
<ide> module Rescuable
<ide> extend Concern
<ide>
<ide> included do
<del> class_attribute :rescue_handlers
<del> self.rescue_handlers = []
<add> class_attribute :rescue_handlers, default: []
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activesupport/test/core_ext/class/attribute_test.rb
<ide>
<ide> class ClassAttributeTest < ActiveSupport::TestCase
<ide> def setup
<del> @klass = Class.new { class_attribute :setting }
<add> @klass = Class.new do
<add> class_attribute :setting
<add> class_attribute :timeout, default: 5
<add> end
<add>
<ide> @sub = Class.new(@klass)
<ide> end
<ide>
<ide> def setup
<ide> assert_nil @sub.setting
<ide> end
<ide>
<add> test "custom default" do
<add> assert_equal 5, @klass.timeout
<add> end
<add>
<ide> test "inheritable" do
<ide> @klass.setting = 1
<ide> assert_equal 1, @sub.setting
<ide><path>railties/lib/rails/generators/testing/behaviour.rb
<ide> module Behaviour
<ide> include ActiveSupport::Testing::Stream
<ide>
<ide> included do
<del> class_attribute :destination_root, :current_path, :generator_class, :default_arguments
<del>
<ide> # Generators frequently change the current path using +FileUtils.cd+.
<ide> # So we need to store the path at file load and revert back to it after each test.
<del> self.current_path = File.expand_path(Dir.pwd)
<del> self.default_arguments = []
<add> class_attribute :current_path, default: File.expand_path(Dir.pwd)
<add> class_attribute :default_arguments, default: []
<add> class_attribute :destination_root
<add> class_attribute :generator_class
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>railties/lib/rails/test_unit/reporter.rb
<ide>
<ide> module Rails
<ide> class TestUnitReporter < Minitest::StatisticsReporter
<del> class_attribute :executable
<del> self.executable = "bin/rails test"
<add> class_attribute :executable, default: "bin/rails test"
<ide>
<ide> def record(result)
<ide> super | 47 |
PHP | PHP | add encryption configuration | f7b982ebdf7bd31eda9f05f901bd92ed32446156 | <ide><path>config/database.php
<ide> 'charset' => 'utf8',
<ide> 'prefix' => '',
<ide> 'prefix_indexes' => true,
<add> // 'encrypt' => env('DB_ENCRYPT', 'yes'),
<add> // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'true'),
<ide> ],
<ide>
<ide> ], | 1 |
Text | Text | remove old links from debugging guide [ci skip] | 987df0fea05d37bcdeb4af3ea8f72381540b4ff6 | <ide><path>guides/source/debugging_rails_applications.md
<ide> more.
<ide> References
<ide> ----------
<ide>
<del>* [ruby-debug Homepage](http://bashdb.sourceforge.net/ruby-debug/home-page.html)
<del>* [debugger Homepage](https://github.com/cldwalker/debugger)
<ide> * [byebug Homepage](https://github.com/deivid-rodriguez/byebug)
<ide> * [web-console Homepage](https://github.com/rails/web-console)
<del>* [Article: Debugging a Rails application with ruby-debug](http://www.sitepoint.com/debug-rails-app-ruby-debug/)
<del>* [Ryan Bates' debugging ruby (revised) screencast](http://railscasts.com/episodes/54-debugging-ruby-revised)
<del>* [Ryan Bates' stack trace screencast](http://railscasts.com/episodes/24-the-stack-trace)
<del>* [Ryan Bates' logger screencast](http://railscasts.com/episodes/56-the-logger)
<del>* [Debugging with ruby-debug](http://bashdb.sourceforge.net/ruby-debug.html) | 1 |
Text | Text | add remote component to upgrade | 69d044730173a5ab5582f4d13b54b294e4d19ba9 | <ide><path>upgrade.md
<ide> to use `Illuminate\Routing\Controller`
<ide> - Edit `app/controllers/BaseController.php` change `use Illuminate\Routing\Controllers\Controller;` to `use Illuminate\Routing\Controller;
<ide> `
<add>- Edit `app/config/app.php`; in `providers` add `'Illuminate\Remote\RemoteServiceProvider',`
<add>- Edit `app/config/app.php`; in `aliases` add `'SSH' => 'Illuminate\Support\Facades\SSH',`
<add>
<ide> - If you are overriding `missingMethod` in your controllers, add $method as the first parameter.
<ide> - Password reminder system tweaked for greater developer freedom. Inspect stub controller by running `auth:reminders-controller` Artisan command.
<del>- Update `reminders.php` language file.
<ide>\ No newline at end of file
<add>- Update `reminders.php` language file. | 1 |
Text | Text | add all core modules to caine's spec | e3aa802b382d2893db0218730b70f60e0c16874a | <ide><path>CONTRIBUTING.md
<ide> and/or gather required information for the core team members?
<ide> If the error is not reproducible with just core modules - it is most
<ide> likely not a io.js problem. _Expected: `yes`_
<ide> * Which part of core do you think it might be related to?
<del> _One of: `tls, crypto, buffer, http, https, assert, util, streams,
<del> smalloc, cluster, child_process, dgram, c++, docs, other`_ (_label_)
<add> _One of: `debugger, http, assert, buffer, child_process, cluster, crypto,
<add> dgram, dns, domain, events, fs, http, https, module, net, os, path,
<add> querystring, readline, repl, smalloc, stream, timers, tls, url, util, vm,
<add> zlib, c++, docs, other`_ (_label_)
<ide> * Which versions of io.js do you think are affected by this?
<ide> _One of: `v0.10, v0.12, v1.0.0`_ (_label_)
<ide> * _PR-only_ Does `make test` pass after applying this Pull Request. | 1 |
Text | Text | add netlify link | 9a47205b0eb7b016989259de9238223854eed2ed | <ide><path>README.md
<ide> Our bottles (binary packages) are hosted by [Bintray](https://bintray.com/homebr
<ide>
<ide> [](https://bintray.com/homebrew)
<ide>
<add>[Our website](https://brew.sh) is hosted by [Netlify](https://www.netlify.com).
<add>
<add>[](https://www.netlify.com)
<add>
<ide> Secure password storage and syncing provided by [1Password for Teams](https://1password.com/teams/) by [AgileBits](https://agilebits.com)
<ide>
<ide> [](https://agilebits.com) | 1 |
PHP | PHP | fix setmatching return type | f813cf8385cddac0b8e1cb17298227018b497d25 | <ide><path>src/ORM/EagerLoader.php
<ide> public function autoFields($enable = null)
<ide> * @param callable|null $builder the callback function to be used for setting extra
<ide> * options to the filtering query
<ide> * @param array $options Extra options for the association matching.
<del> * @return self
<add> * @return array Containments.
<ide> */
<ide> public function setMatching($assoc, callable $builder = null, $options = [])
<ide> {
<ide> public function setMatching($assoc, callable $builder = null, $options = [])
<ide>
<ide> $pointer[$last] = ['queryBuilder' => $builder, 'matching' => true] + $options;
<ide>
<del> $this->_matching->contain($containments);
<del>
<del> return $this;
<add> return $this->_matching->contain($containments);
<ide> }
<ide>
<ide> /**
<ide><path>src/ORM/Query.php
<ide> protected function _addAssociationsToTypeMap($table, $typeMap, $associations)
<ide> */
<ide> public function matching($assoc, callable $builder = null)
<ide> {
<del> $result = $this->getEagerLoader()->matching($assoc, $builder);
<add> $result = $this->getEagerLoader()->setMatching($assoc, $builder);
<ide> $this->_addAssociationsToTypeMap($this->repository(), $this->typeMap(), $result);
<ide> $this->_dirty();
<ide>
<ide> public function matching($assoc, callable $builder = null)
<ide> */
<ide> public function leftJoinWith($assoc, callable $builder = null)
<ide> {
<del> $result = $this->getEagerLoader()->matching($assoc, $builder, [
<add> $result = $this->getEagerLoader()->setMatching($assoc, $builder, [
<ide> 'joinType' => 'LEFT',
<ide> 'fields' => false
<ide> ]);
<ide> public function leftJoinWith($assoc, callable $builder = null)
<ide> */
<ide> public function innerJoinWith($assoc, callable $builder = null)
<ide> {
<del> $result = $this->getEagerLoader()->matching($assoc, $builder, [
<add> $result = $this->getEagerLoader()->setMatching($assoc, $builder, [
<ide> 'joinType' => 'INNER',
<ide> 'fields' => false
<ide> ]);
<ide> public function innerJoinWith($assoc, callable $builder = null)
<ide> */
<ide> public function notMatching($assoc, callable $builder = null)
<ide> {
<del> $result = $this->getEagerLoader()->matching($assoc, $builder, [
<add> $result = $this->getEagerLoader()->setMatching($assoc, $builder, [
<ide> 'joinType' => 'LEFT',
<ide> 'fields' => false,
<ide> 'negateMatch' => true | 2 |
Text | Text | improve eventlooputilization documentation | 642f2064c06793b799959d7df0488f14df594181 | <ide><path>doc/api/perf_hooks.md
<ide> Performance Timeline. If `name` is provided, removes only the named mark.
<ide> added: v14.10.0
<ide> -->
<ide>
<del>* `utilization1` {Object} The result of a previous call to `eventLoopUtilization()`
<del>* `utilization2` {Object} The result of a previous call to `eventLoopUtilization()`
<del> prior to `util1`
<add>* `utilization1` {Object} The result of a previous call to
<add> `eventLoopUtilization()`.
<add>* `utilization2` {Object} The result of a previous call to
<add> `eventLoopUtilization()` prior to `utilization1`.
<ide> * Returns {Object}
<ide> * `idle` {number}
<ide> * `active` {number}
<ide> The `eventLoopUtilization()` method returns an object that contains the
<ide> cumulative duration of time the event loop has been both idle and active as a
<ide> high resolution milliseconds timer. The `utilization` value is the calculated
<ide> Event Loop Utilization (ELU). If bootstrapping has not yet finished, the
<del>properties have the value of 0.
<add>properties have the value of `0`.
<ide>
<del>`utilization1` and `utilization2` are optional parameters.
<add>Both `utilization1` and `utilization2` are optional parameters.
<ide>
<ide> If `utilization1` is passed, then the delta between the current call's `active`
<ide> and `idle` times, as well as the corresponding `utilization` value are
<ide> setImmediate(() => {
<ide> ```
<ide>
<ide> Although the CPU is mostly idle while running this script, the value of
<del>`utilization` is 1. This is because the call to [`child_process.spawnSync()`][]
<del>blocks the event loop from proceeding.
<add>`utilization` is `1`. This is because the call to
<add>[`child_process.spawnSync()`][] blocks the event loop from proceeding.
<ide>
<ide> Passing in a user-defined object instead of the result of a previous call to
<ide> `eventLoopUtilization()` will lead to undefined behavior. The return values | 1 |
Python | Python | add snowflake operators based on sql checks | a8970764d98f33a54be0e880df27f86b311038ac | <ide><path>airflow/providers/snowflake/operators/snowflake.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>from typing import Any, Optional
<add>from typing import Any, Optional, SupportsAbs
<ide>
<ide> from airflow.models import BaseOperator
<add>from airflow.operators.sql import SQLCheckOperator, SQLIntervalCheckOperator, SQLValueCheckOperator
<ide> from airflow.providers.snowflake.hooks.snowflake import SnowflakeHook
<ide>
<ide>
<add>def get_db_hook(self) -> SnowflakeHook:
<add> """
<add> Create and return SnowflakeHook.
<add>
<add> :return: a SnowflakeHook instance.
<add> :rtype: SnowflakeHook
<add> """
<add> return SnowflakeHook(
<add> snowflake_conn_id=self.snowflake_conn_id,
<add> warehouse=self.warehouse,
<add> database=self.database,
<add> role=self.role,
<add> schema=self.schema,
<add> authenticator=self.authenticator,
<add> session_parameters=self.session_parameters,
<add> )
<add>
<add>
<ide> class SnowflakeOperator(BaseOperator):
<ide> """
<ide> Executes SQL code in a Snowflake database
<ide> def __init__(
<ide> self.session_parameters = session_parameters
<ide> self.query_ids = []
<ide>
<del> def get_hook(self) -> SnowflakeHook:
<del> """
<del> Create and return SnowflakeHook.
<del> :return: a SnowflakeHook instance.
<del> :rtype: SnowflakeHook
<del> """
<del> return SnowflakeHook(
<del> snowflake_conn_id=self.snowflake_conn_id,
<del> warehouse=self.warehouse,
<del> database=self.database,
<del> role=self.role,
<del> schema=self.schema,
<del> authenticator=self.authenticator,
<del> session_parameters=self.session_parameters,
<del> )
<add> def get_db_hook(self) -> SnowflakeHook:
<add> return get_db_hook(self)
<ide>
<ide> def execute(self, context: Any) -> None:
<ide> """Run query on snowflake"""
<ide> self.log.info('Executing: %s', self.sql)
<del> hook = self.get_hook()
<add> hook = self.get_db_hook()
<ide> execution_info = hook.run(self.sql, autocommit=self.autocommit, parameters=self.parameters)
<ide> self.query_ids = hook.query_ids
<ide>
<ide> if self.do_xcom_push:
<ide> return execution_info
<add>
<add>
<add>class SnowflakeCheckOperator(SQLCheckOperator):
<add> """
<add> Performs a check against Snowflake. The ``SnowflakeCheckOperator`` expects
<add> a sql query that will return a single row. Each value on that
<add> first row is evaluated using python ``bool`` casting. If any of the
<add> values return ``False`` the check is failed and errors out.
<add>
<add> Note that Python bool casting evals the following as ``False``:
<add>
<add> * ``False``
<add> * ``0``
<add> * Empty string (``""``)
<add> * Empty list (``[]``)
<add> * Empty dictionary or set (``{}``)
<add>
<add> Given a query like ``SELECT COUNT(*) FROM foo``, it will fail only if
<add> the count ``== 0``. You can craft much more complex query that could,
<add> for instance, check that the table has the same number of rows as
<add> the source table upstream, or that the count of today's partition is
<add> greater than yesterday's partition, or that a set of metrics are less
<add> than 3 standard deviation for the 7 day average.
<add>
<add> This operator can be used as a data quality check in your pipeline, and
<add> depending on where you put it in your DAG, you have the choice to
<add> stop the critical path, preventing from
<add> publishing dubious data, or on the side and receive email alerts
<add> without stopping the progress of the DAG.
<add>
<add> :param sql: the sql code to be executed. (templated)
<add> :type sql: Can receive a str representing a sql statement,
<add> a list of str (sql statements), or reference to a template file.
<add> Template reference are recognized by str ending in '.sql'
<add> :param snowflake_conn_id: Reference to
<add> :ref:`Snowflake connection id<howto/connection:snowflake>`
<add> :type snowflake_conn_id: str
<add> :param autocommit: if True, each command is automatically committed.
<add> (default value: True)
<add> :type autocommit: bool
<add> :param parameters: (optional) the parameters to render the SQL query with.
<add> :type parameters: dict or iterable
<add> :param warehouse: name of warehouse (will overwrite any warehouse
<add> defined in the connection's extra JSON)
<add> :type warehouse: str
<add> :param database: name of database (will overwrite database defined
<add> in connection)
<add> :type database: str
<add> :param schema: name of schema (will overwrite schema defined in
<add> connection)
<add> :type schema: str
<add> :param role: name of role (will overwrite any role defined in
<add> connection's extra JSON)
<add> :type role: str
<add> :param authenticator: authenticator for Snowflake.
<add> 'snowflake' (default) to use the internal Snowflake authenticator
<add> 'externalbrowser' to authenticate using your web browser and
<add> Okta, ADFS or any other SAML 2.0-compliant identify provider
<add> (IdP) that has been defined for your account
<add> 'https://<your_okta_account_name>.okta.com' to authenticate
<add> through native Okta.
<add> :type authenticator: str
<add> :param session_parameters: You can set session-level parameters at
<add> the time you connect to Snowflake
<add> :type session_parameters: dict
<add> """
<add>
<add> template_fields = ('sql',)
<add> template_ext = ('.sql',)
<add> ui_color = '#ededed'
<add>
<add> def __init__(
<add> self,
<add> *,
<add> sql: Any,
<add> snowflake_conn_id: str = 'snowflake_default',
<add> parameters: Optional[dict] = None,
<add> autocommit: bool = True,
<add> do_xcom_push: bool = True,
<add> warehouse: Optional[str] = None,
<add> database: Optional[str] = None,
<add> role: Optional[str] = None,
<add> schema: Optional[str] = None,
<add> authenticator: Optional[str] = None,
<add> session_parameters: Optional[dict] = None,
<add> **kwargs,
<add> ) -> None:
<add> super().__init__(sql=sql, **kwargs)
<add> self.snowflake_conn_id = snowflake_conn_id
<add> self.sql = sql
<add> self.autocommit = autocommit
<add> self.do_xcom_push = do_xcom_push
<add> self.parameters = parameters
<add> self.warehouse = warehouse
<add> self.database = database
<add> self.role = role
<add> self.schema = schema
<add> self.authenticator = authenticator
<add> self.session_parameters = session_parameters
<add> self.query_ids = []
<add>
<add> def get_db_hook(self) -> SnowflakeHook:
<add> return get_db_hook(self)
<add>
<add>
<add>class SnowflakeValueCheckOperator(SQLValueCheckOperator):
<add> """
<add> Performs a simple check using sql code against a specified value, within a
<add> certain level of tolerance.
<add>
<add> :param sql: the sql to be executed
<add> :type sql: str
<add> :param pass_value: the value to check against
<add> :type pass_value: Any
<add> :param tolerance: (optional) the tolerance allowed to accept the query as
<add> passing
<add> :type tolerance: Any
<add> :param snowflake_conn_id: Reference to
<add> :ref:`Snowflake connection id<howto/connection:snowflake>`
<add> :type snowflake_conn_id: str
<add> :param autocommit: if True, each command is automatically committed.
<add> (default value: True)
<add> :type autocommit: bool
<add> :param parameters: (optional) the parameters to render the SQL query with.
<add> :type parameters: dict or iterable
<add> :param warehouse: name of warehouse (will overwrite any warehouse
<add> defined in the connection's extra JSON)
<add> :type warehouse: str
<add> :param database: name of database (will overwrite database defined
<add> in connection)
<add> :type database: str
<add> :param schema: name of schema (will overwrite schema defined in
<add> connection)
<add> :type schema: str
<add> :param role: name of role (will overwrite any role defined in
<add> connection's extra JSON)
<add> :type role: str
<add> :param authenticator: authenticator for Snowflake.
<add> 'snowflake' (default) to use the internal Snowflake authenticator
<add> 'externalbrowser' to authenticate using your web browser and
<add> Okta, ADFS or any other SAML 2.0-compliant identify provider
<add> (IdP) that has been defined for your account
<add> 'https://<your_okta_account_name>.okta.com' to authenticate
<add> through native Okta.
<add> :type authenticator: str
<add> :param session_parameters: You can set session-level parameters at
<add> the time you connect to Snowflake
<add> :type session_parameters: dict
<add> """
<add>
<add> def __init__(
<add> self,
<add> *,
<add> sql: str,
<add> pass_value: Any,
<add> tolerance: Any = None,
<add> snowflake_conn_id: str = 'snowflake_default',
<add> parameters: Optional[dict] = None,
<add> autocommit: bool = True,
<add> do_xcom_push: bool = True,
<add> warehouse: Optional[str] = None,
<add> database: Optional[str] = None,
<add> role: Optional[str] = None,
<add> schema: Optional[str] = None,
<add> authenticator: Optional[str] = None,
<add> session_parameters: Optional[dict] = None,
<add> **kwargs,
<add> ) -> None:
<add> super().__init__(sql=sql, pass_value=pass_value, tolerance=tolerance, **kwargs)
<add> self.snowflake_conn_id = snowflake_conn_id
<add> self.sql = sql
<add> self.autocommit = autocommit
<add> self.do_xcom_push = do_xcom_push
<add> self.parameters = parameters
<add> self.warehouse = warehouse
<add> self.database = database
<add> self.role = role
<add> self.schema = schema
<add> self.authenticator = authenticator
<add> self.session_parameters = session_parameters
<add> self.query_ids = []
<add>
<add> def get_db_hook(self) -> SnowflakeHook:
<add> return get_db_hook(self)
<add>
<add>
<add>class SnowflakeIntervalCheckOperator(SQLIntervalCheckOperator):
<add> """
<add> Checks that the values of metrics given as SQL expressions are within
<add> a certain tolerance of the ones from days_back before.
<add>
<add> This method constructs a query like so ::
<add>
<add> SELECT {metrics_threshold_dict_key} FROM {table}
<add> WHERE {date_filter_column}=<date>
<add>
<add> :param table: the table name
<add> :type table: str
<add> :param days_back: number of days between ds and the ds we want to check
<add> against. Defaults to 7 days
<add> :type days_back: int
<add> :param metrics_thresholds: a dictionary of ratios indexed by metrics, for
<add> example 'COUNT(*)': 1.5 would require a 50 percent or less difference
<add> between the current day, and the prior days_back.
<add> :type metrics_thresholds: dict
<add> :param snowflake_conn_id: Reference to
<add> :ref:`Snowflake connection id<howto/connection:snowflake>`
<add> :type snowflake_conn_id: str
<add> :param autocommit: if True, each command is automatically committed.
<add> (default value: True)
<add> :type autocommit: bool
<add> :param parameters: (optional) the parameters to render the SQL query with.
<add> :type parameters: dict or iterable
<add> :param warehouse: name of warehouse (will overwrite any warehouse
<add> defined in the connection's extra JSON)
<add> :type warehouse: str
<add> :param database: name of database (will overwrite database defined
<add> in connection)
<add> :type database: str
<add> :param schema: name of schema (will overwrite schema defined in
<add> connection)
<add> :type schema: str
<add> :param role: name of role (will overwrite any role defined in
<add> connection's extra JSON)
<add> :type role: str
<add> :param authenticator: authenticator for Snowflake.
<add> 'snowflake' (default) to use the internal Snowflake authenticator
<add> 'externalbrowser' to authenticate using your web browser and
<add> Okta, ADFS or any other SAML 2.0-compliant identify provider
<add> (IdP) that has been defined for your account
<add> 'https://<your_okta_account_name>.okta.com' to authenticate
<add> through native Okta.
<add> :type authenticator: str
<add> :param session_parameters: You can set session-level parameters at
<add> the time you connect to Snowflake
<add> :type session_parameters: dict
<add> """
<add>
<add> def __init__(
<add> self,
<add> *,
<add> table: str,
<add> metrics_thresholds: dict,
<add> date_filter_column: str = 'ds',
<add> days_back: SupportsAbs[int] = -7,
<add> snowflake_conn_id: str = 'snowflake_default',
<add> parameters: Optional[dict] = None,
<add> autocommit: bool = True,
<add> do_xcom_push: bool = True,
<add> warehouse: Optional[str] = None,
<add> database: Optional[str] = None,
<add> role: Optional[str] = None,
<add> schema: Optional[str] = None,
<add> authenticator: Optional[str] = None,
<add> session_parameters: Optional[dict] = None,
<add> **kwargs,
<add> ) -> None:
<add> super().__init__(
<add> table=table,
<add> metrics_thresholds=metrics_thresholds,
<add> date_filter_column=date_filter_column,
<add> days_back=days_back,
<add> **kwargs,
<add> )
<add> self.snowflake_conn_id = snowflake_conn_id
<add> self.autocommit = autocommit
<add> self.do_xcom_push = do_xcom_push
<add> self.parameters = parameters
<add> self.warehouse = warehouse
<add> self.database = database
<add> self.role = role
<add> self.schema = schema
<add> self.authenticator = authenticator
<add> self.session_parameters = session_parameters
<add> self.query_ids = []
<add>
<add> def get_db_hook(self) -> SnowflakeHook:
<add> return get_db_hook(self)
<ide><path>tests/providers/snowflake/operators/test_snowflake.py
<ide> import unittest
<ide> from unittest import mock
<ide>
<add>import pytest
<add>
<ide> from airflow.models.dag import DAG
<del>from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
<add>from airflow.providers.snowflake.operators.snowflake import (
<add> SnowflakeCheckOperator,
<add> SnowflakeIntervalCheckOperator,
<add> SnowflakeOperator,
<add> SnowflakeValueCheckOperator,
<add>)
<ide> from airflow.utils import timezone
<ide>
<ide> DEFAULT_DATE = timezone.datetime(2015, 1, 1)
<ide> DEFAULT_DATE_ISO = DEFAULT_DATE.isoformat()
<ide> DEFAULT_DATE_DS = DEFAULT_DATE_ISO[:10]
<ide> TEST_DAG_ID = 'unit_test_dag'
<ide> LONG_MOCK_PATH = "airflow.providers.snowflake.operators.snowflake."
<del>LONG_MOCK_PATH += 'SnowflakeOperator.get_hook'
<add>LONG_MOCK_PATH += 'SnowflakeOperator.get_db_hook'
<ide>
<ide>
<ide> class TestSnowflakeOperator(unittest.TestCase):
<ide> def setUp(self):
<ide> self.dag = dag
<ide>
<ide> @mock.patch(LONG_MOCK_PATH)
<del> def test_snowflake_operator(self, mock_get_hook):
<add> def test_snowflake_operator(self, mock_get_db_hook):
<ide> sql = """
<ide> CREATE TABLE IF NOT EXISTS test_airflow (
<ide> dummy VARCHAR(50)
<ide> def test_snowflake_operator(self, mock_get_hook):
<ide> operator = SnowflakeOperator(task_id='basic_snowflake', sql=sql, dag=self.dag, do_xcom_push=False)
<ide> # do_xcom_push=False because otherwise the XCom test will fail due to the mocking (it actually works)
<ide> operator.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
<add>
<add>
<add>@pytest.mark.parametrize(
<add> "operator_class, kwargs",
<add> [
<add> (SnowflakeCheckOperator, dict(sql='Select * from test_table')),
<add> (SnowflakeValueCheckOperator, dict(sql='Select * from test_table', pass_value=95)),
<add> (SnowflakeIntervalCheckOperator, dict(table='test-table-id', metrics_thresholds={'COUNT(*)': 1.5})),
<add> ],
<add>)
<add>class TestSnowflakeCheckOperators:
<add> @mock.patch("airflow.providers.snowflake.operators.snowflake.get_db_hook")
<add> def test_get_db_hook(
<add> self,
<add> mock_get_db_hook,
<add> operator_class,
<add> kwargs,
<add> ):
<add> operator = operator_class(task_id='snowflake_check', snowflake_conn_id='snowflake_default', **kwargs)
<add> operator.get_db_hook()
<add> mock_get_db_hook.assert_called_once() | 2 |
Text | Text | add @daviwil focus items | 138a4a0d72087b6eb9cedd9cd7931b44b504fa55 | <ide><path>docs/focus/2018-04-23.md
<ide> ## Focus for week ahead
<ide>
<ide> - Atom core
<add> - Shipped Atom 1.26.0 and 1.27.0-beta0 :shipit:
<ide> - Atom IDE
<ide> - GitHub Package
<ide> - :notebook: Planning, roadmapping, prioritizing, scheming | 1 |
Ruby | Ruby | use curl with --insecure when on os x < 10.6 | 4ba0e9ebaebecf7bff389d0d49e7d59b31eef237 | <ide><path>Library/Homebrew/utils.rb
<ide> def quiet_system cmd, *args
<ide> end
<ide>
<ide> def curl *args
<add> # See https://github.com/mxcl/homebrew/issues/6103
<add> args << "--insecure" if MacOS.version < 10.6
<add>
<ide> safe_system '/usr/bin/curl', HOMEBREW_CURL_ARGS, HOMEBREW_USER_AGENT, *args unless args.empty?
<ide> end
<ide>
<ide> def nostdout
<ide> end
<ide>
<ide> module MacOS extend self
<add> def version
<add> MACOS_VERSION
<add> end
<ide>
<ide> def default_cc
<ide> Pathname.new("/usr/bin/cc").realpath.basename.to_s | 1 |
Text | Text | add change string to changelog.md | bc55ee6bd2603f952e4a6754a3a78ccbbd69319c | <ide><path>CHANGELOG.md
<add>* Fixed: Using toggle comment shortcut respects indentation level
<add>
<ide> * Fixed: Search never completing in the command panel
<ide>
<ide> * Fixed: cmd-n now works when no windows are open | 1 |
Python | Python | update available record types in zerigo driver | 2318442c75dae0caad7ac99eba84d5942b63f9ad | <ide><path>libcloud/dns/drivers/zerigo.py
<ide> RecordType.A: 'A',
<ide> RecordType.AAAA: 'AAAA',
<ide> RecordType.CNAME: 'CNAME',
<add> RecordType.MX: 'MX',
<add> RecordType.REDIRECT: 'REDIRECT',
<ide> RecordType.TXT: 'TXT',
<ide> RecordType.SRV: 'SRV',
<add> RecordType.NAPTR: 'NAPTR',
<add> RecordType.NS: 'NS',
<add> RecordType.PTR: 'PTR',
<add> RecordType.SPF: 'SPF',
<ide> }
<ide>
<ide> | 1 |
Python | Python | monitor pods by labels instead of names | 8985df0bfcb5f2b2cd69a21b9814021f9f8ce953 | <ide><path>airflow/executors/kubernetes_executor.py
<ide> """
<ide> import base64
<ide> import datetime
<del>import hashlib
<ide> import json
<ide> import multiprocessing
<del>import re
<ide> import time
<ide> from queue import Empty, Queue # pylint: disable=unused-import
<ide> from typing import Any, Dict, Optional, Tuple, Union
<ide> from airflow.configuration import conf
<ide> from airflow.exceptions import AirflowConfigException, AirflowException
<ide> from airflow.executors.base_executor import NOT_STARTED_MESSAGE, BaseExecutor, CommandType
<add>from airflow.kubernetes import pod_generator
<ide> from airflow.kubernetes.kube_client import get_kube_client
<ide> from airflow.kubernetes.pod_generator import MAX_POD_ID_LEN, PodGenerator
<ide> from airflow.kubernetes.pod_launcher import PodLauncher
<ide> def run_next(self, next_job: KubernetesJobType) -> None:
<ide> namespace=self.namespace,
<ide> worker_uuid=self.worker_uuid,
<ide> pod_id=self._create_pod_id(dag_id, task_id),
<del> dag_id=self._make_safe_label_value(dag_id),
<del> task_id=self._make_safe_label_value(task_id),
<add> dag_id=pod_generator.make_safe_label_value(dag_id),
<add> task_id=pod_generator.make_safe_label_value(task_id),
<ide> try_number=try_number,
<ide> date=self._datetime_to_label_safe_datestring(execution_date),
<ide> command=command,
<ide> def _make_safe_pod_id(safe_dag_id: str, safe_task_id: str, safe_uuid: str) -> st
<ide>
<ide> return safe_pod_id
<ide>
<del> @staticmethod
<del> def _make_safe_label_value(string: str) -> str:
<del> """
<del> Valid label values must be 63 characters or less and must be empty or begin and
<del> end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_),
<del> dots (.), and alphanumerics between.
<del>
<del> If the label value is then greater than 63 chars once made safe, or differs in any
<del> way from the original value sent to this function, then we need to truncate to
<del> 53chars, and append it with a unique hash.
<del> """
<del> safe_label = re.sub(r'^[^a-z0-9A-Z]*|[^a-zA-Z0-9_\-\.]|[^a-z0-9A-Z]*$', '', string)
<del>
<del> if len(safe_label) > MAX_LABEL_LEN or string != safe_label:
<del> safe_hash = hashlib.md5(string.encode()).hexdigest()[:9]
<del> safe_label = safe_label[:MAX_LABEL_LEN - len(safe_hash) - 1] + "-" + safe_hash
<del>
<del> return safe_label
<del>
<ide> @staticmethod
<ide> def _create_pod_id(dag_id: str, task_id: str) -> str:
<ide> safe_dag_id = AirflowKubernetesScheduler._strip_unsafe_kubernetes_special_chars(
<ide> def _labels_to_key(self, labels: Dict[str, str]) -> Optional[TaskInstanceKeyType
<ide> )
<ide> for task in tasks:
<ide> if (
<del> self._make_safe_label_value(task.dag_id) == dag_id and
<del> self._make_safe_label_value(task.task_id) == task_id and
<add> pod_generator.make_safe_label_value(task.dag_id) == dag_id and
<add> pod_generator.make_safe_label_value(task.task_id) == task_id and
<ide> task.execution_date == ex_time
<ide> ):
<ide> self.log.info(
<ide> def clear_not_launched_queued_tasks(self, session=None) -> None:
<ide> # pylint: disable=protected-access
<ide> dict_string = (
<ide> "dag_id={},task_id={},execution_date={},airflow-worker={}".format(
<del> AirflowKubernetesScheduler._make_safe_label_value(task.dag_id),
<del> AirflowKubernetesScheduler._make_safe_label_value(task.task_id),
<add> pod_generator.make_safe_label_value(task.dag_id),
<add> pod_generator.make_safe_label_value(task.task_id),
<ide> AirflowKubernetesScheduler._datetime_to_label_safe_datestring(
<ide> task.execution_date
<ide> ),
<ide><path>airflow/kubernetes/pod_generator.py
<ide> """
<ide>
<ide> import copy
<add>import hashlib
<ide> import inspect
<ide> import os
<add>import re
<ide> import uuid
<ide> from functools import reduce
<ide> from typing import Dict, List, Optional, Union
<ide>
<ide> MAX_POD_ID_LEN = 253
<ide>
<add>MAX_LABEL_LEN = 63
<add>
<ide>
<ide> class PodDefaults:
<ide> """
<ide> class PodDefaults:
<ide> )
<ide>
<ide>
<add>def make_safe_label_value(string):
<add> """
<add> Valid label values must be 63 characters or less and must be empty or begin and
<add> end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_),
<add> dots (.), and alphanumerics between.
<add>
<add> If the label value is greater than 63 chars once made safe, or differs in any
<add> way from the original value sent to this function, then we need to truncate to
<add> 53 chars, and append it with a unique hash.
<add> """
<add> safe_label = re.sub(r"^[^a-z0-9A-Z]*|[^a-zA-Z0-9_\-\.]|[^a-z0-9A-Z]*$", "", string)
<add>
<add> if len(safe_label) > MAX_LABEL_LEN or string != safe_label:
<add> safe_hash = hashlib.md5(string.encode()).hexdigest()[:9]
<add> safe_label = safe_label[:MAX_LABEL_LEN - len(safe_hash) - 1] + "-" + safe_hash
<add>
<add> return safe_label
<add>
<add>
<ide> class PodGenerator:
<ide> """
<ide> Contains Kubernetes Airflow Worker configuration logic
<ide><path>airflow/kubernetes/pod_launcher.py
<ide> def delete_pod(self, pod: V1Pod):
<ide> if e.status != 404:
<ide> raise
<ide>
<del> def run_pod(
<add> def start_pod(
<ide> self,
<ide> pod: V1Pod,
<del> startup_timeout: int = 120,
<del> get_logs: bool = True) -> Tuple[State, Optional[str]]:
<add> startup_timeout: int = 120):
<ide> """
<ide> Launches the pod synchronously and waits for completion.
<ide>
<ide> :param pod:
<ide> :param startup_timeout: Timeout for startup of the pod (if pod is pending for too long, fails task)
<del> :param get_logs: whether to query k8s for logs
<ide> :return:
<ide> """
<ide> resp = self.run_pod_async(pod)
<ide> def run_pod(
<ide> time.sleep(1)
<ide> self.log.debug('Pod not yet started')
<ide>
<del> return self._monitor_pod(pod, get_logs)
<add> def monitor_pod(self, pod: V1Pod, get_logs: bool) -> Tuple[State, Optional[str]]:
<add> """
<add> Monitors a pod and returns the final state
<ide>
<del> def _monitor_pod(self, pod: V1Pod, get_logs: bool) -> Tuple[State, Optional[str]]:
<add> :param pod: pod spec that will be monitored
<add> :type pod : V1Pod
<add> :param get_logs: whether to read the logs locally
<add> :return: Tuple[State, Optional[str]]
<add> """
<ide> if get_logs:
<ide> logs = self.read_pod_logs(pod)
<ide> for line in logs:
<ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py
<ide> # under the License.
<ide> """Executes task in a Kubernetes POD"""
<ide> import re
<del>from typing import Dict, List, Optional
<add>from typing import Dict, List, Optional, Tuple
<ide>
<ide> import kubernetes.client.models as k8s
<ide>
<ide> class KubernetesPodOperator(BaseOperator): # pylint: disable=too-many-instance-
<ide> :param cluster_context: context that points to kubernetes cluster.
<ide> Ignored when in_cluster is True. If None, current-context is used.
<ide> :type cluster_context: str
<add> :param reattach_on_restart: if the scheduler dies while the pod is running, reattach and monitor
<add> :type reattach_on_restart: bool
<ide> :param labels: labels to apply to the Pod.
<ide> :type labels: dict
<ide> :param startup_timeout_seconds: timeout in seconds to startup the pod.
<ide> def __init__(self, # pylint: disable=too-many-arguments,too-many-locals
<ide> in_cluster: Optional[bool] = None,
<ide> cluster_context: Optional[str] = None,
<ide> labels: Optional[Dict] = None,
<add> reattach_on_restart: bool = True,
<ide> startup_timeout_seconds: int = 120,
<ide> get_logs: bool = True,
<ide> image_pull_policy: str = 'IfNotPresent',
<ide> def __init__(self, # pylint: disable=too-many-arguments,too-many-locals
<ide> self.secrets = secrets or []
<ide> self.in_cluster = in_cluster
<ide> self.cluster_context = cluster_context
<add> self.reattach_on_restart = reattach_on_restart
<ide> self.get_logs = get_logs
<ide> self.image_pull_policy = image_pull_policy
<ide> self.node_selectors = node_selectors or {}
<ide> def __init__(self, # pylint: disable=too-many-arguments,too-many-locals
<ide> self.pod_template_file = pod_template_file
<ide> self.name = self._set_name(name)
<ide>
<del> def execute(self, context):
<add> @staticmethod
<add> def create_labels_for_pod(context) -> dict:
<add> """
<add> Generate labels for the pod to track the pod in case of Operator crash
<add>
<add> :param context: task context provided by airflow DAG
<add> :return: dict
<add> """
<add> labels = {
<add> 'dag_id': context['dag'].dag_id,
<add> 'task_id': context['task'].task_id,
<add> 'execution_date': context['ts'],
<add> 'try_number': context['ti'].try_number,
<add> }
<add> # In the case of sub dags this is just useful
<add> if context['dag'].is_subdag:
<add> labels['parent_dag_id'] = context['dag'].parent_dag.dag_id
<add> # Ensure that label is valid for Kube,
<add> # and if not truncate/remove invalid chars and replace with short hash.
<add> for label_id, label in labels.items():
<add> safe_label = pod_generator.make_safe_label_value(str(label))
<add> labels[label_id] = safe_label
<add> return labels
<add>
<add> def execute(self, context) -> Optional[str]:
<ide> try:
<ide> if self.in_cluster is not None:
<ide> client = kube_client.get_kube_client(in_cluster=self.in_cluster,
<ide> def execute(self, context):
<ide> client = kube_client.get_kube_client(cluster_context=self.cluster_context,
<ide> config_file=self.config_file)
<ide>
<del> if not (self.full_pod_spec or self.pod_template_file):
<del> # Add Airflow Version to the label
<del> # And a label to identify that pod is launched by KubernetesPodOperator
<del> self.labels.update(
<del> {
<del> 'airflow_version': airflow_version.replace('+', '-'),
<del> 'kubernetes_pod_operator': 'True',
<del> }
<del> )
<del> pod = pod_generator.PodGenerator(
<del> image=self.image,
<del> namespace=self.namespace,
<del> cmds=self.cmds,
<del> args=self.arguments,
<del> labels=self.labels,
<del> name=self.name,
<del> envs=self.env_vars,
<del> extract_xcom=self.do_xcom_push,
<del> image_pull_policy=self.image_pull_policy,
<del> node_selectors=self.node_selectors,
<del> annotations=self.annotations,
<del> affinity=self.affinity,
<del> image_pull_secrets=self.image_pull_secrets,
<del> service_account_name=self.service_account_name,
<del> hostnetwork=self.hostnetwork,
<del> tolerations=self.tolerations,
<del> configmaps=self.configmaps,
<del> security_context=self.security_context,
<del> dnspolicy=self.dnspolicy,
<del> schedulername=self.schedulername,
<del> init_containers=self.init_containers,
<del> restart_policy='Never',
<del> priority_class_name=self.priority_class_name,
<del> pod_template_file=self.pod_template_file,
<del> pod=self.full_pod_spec,
<del> ).gen_pod()
<add> # Add combination of labels to uniquely identify a running pod
<add> labels = self.create_labels_for_pod(context)
<ide>
<del> pod = append_to_pod(
<del> pod,
<del> self.pod_runtime_info_envs +
<del> self.ports +
<del> self.resources +
<del> self.secrets +
<del> self.volumes +
<del> self.volume_mounts
<del> )
<add> label_selector = self._get_pod_identifying_label_string(labels)
<ide>
<del> self.pod = pod
<add> pod_list = client.list_namespaced_pod(self.namespace, label_selector=label_selector)
<ide>
<del> launcher = pod_launcher.PodLauncher(kube_client=client,
<del> extract_xcom=self.do_xcom_push)
<add> if len(pod_list.items) > 1:
<add> raise AirflowException(
<add> 'More than one pod running with labels: '
<add> '{label_selector}'.format(label_selector=label_selector))
<ide>
<del> try:
<del> (final_state, result) = launcher.run_pod(
<del> pod,
<del> startup_timeout=self.startup_timeout_seconds,
<del> get_logs=self.get_logs)
<del> except AirflowException:
<del> if self.log_events_on_failure:
<del> for event in launcher.read_pod_events(pod).items:
<del> self.log.error("Pod Event: %s - %s", event.reason, event.message)
<del> raise
<del> finally:
<del> if self.is_delete_operator_pod:
<del> launcher.delete_pod(pod)
<add> launcher = pod_launcher.PodLauncher(kube_client=client, extract_xcom=self.do_xcom_push)
<ide>
<add> if len(pod_list.items) == 1 and \
<add> self._try_numbers_do_not_match(context, pod_list.items[0]) and \
<add> self.reattach_on_restart:
<add> self.log.info("found a running pod with labels %s but a different try_number"
<add> "Will attach to this pod and monitor instead of starting new one", labels)
<add> final_state, _, result = self.create_new_pod_for_operator(labels, launcher)
<add> elif len(pod_list.items) == 1:
<add> self.log.info("found a running pod with labels %s."
<add> "Will monitor this pod instead of starting new one", labels)
<add> final_state, result = self.monitor_launched_pod(launcher, pod_list[0])
<add> else:
<add> final_state, _, result = self.create_new_pod_for_operator(labels, launcher)
<ide> if final_state != State.SUCCESS:
<del> if self.log_events_on_failure:
<del> for event in launcher.read_pod_events(pod).items:
<del> self.log.error("Pod Event: %s - %s", event.reason, event.message)
<ide> raise AirflowException(
<del> 'Pod returned a failure: {state}'.format(state=final_state)
<del> )
<del>
<add> 'Pod returned a failure: {state}'.format(state=final_state))
<ide> return result
<ide> except AirflowException as ex:
<ide> raise AirflowException('Pod Launching failed: {error}'.format(error=ex))
<ide>
<add> @staticmethod
<add> def _get_pod_identifying_label_string(labels):
<add> filtered_labels = {label_id: label for label_id, label in labels.items() if label_id != 'try_number'}
<add> return ','.join([label_id + '=' + label for label_id, label in sorted(filtered_labels.items())])
<add>
<add> @staticmethod
<add> def _try_numbers_do_not_match(context, pod):
<add> return pod.metadata.labels['try_number'] != context['ti'].try_number
<add>
<ide> @staticmethod
<ide> def _set_resources(resources):
<ide> if not resources:
<ide> def _set_name(self, name):
<ide> return None
<ide> validate_key(name, max_length=220)
<ide> return re.sub(r'[^a-z0-9.-]+', '-', name.lower())
<add>
<add> def create_new_pod_for_operator(self, labels, launcher) -> Tuple[State, k8s.V1Pod, Optional[str]]:
<add> """
<add> Creates a new pod and monitors for duration of task
<add>
<add> @param labels: labels used to track pod
<add> @param launcher: pod launcher that will manage launching and monitoring pods
<add> @return:
<add> """
<add> if not (self.full_pod_spec or self.pod_template_file):
<add> # Add Airflow Version to the label
<add> # And a label to identify that pod is launched by KubernetesPodOperator
<add> self.labels.update(
<add> {
<add> 'airflow_version': airflow_version.replace('+', '-'),
<add> 'kubernetes_pod_operator': 'True',
<add> }
<add> )
<add> self.labels.update(labels)
<add> pod = pod_generator.PodGenerator(
<add> image=self.image,
<add> namespace=self.namespace,
<add> cmds=self.cmds,
<add> args=self.arguments,
<add> labels=self.labels,
<add> name=self.name,
<add> envs=self.env_vars,
<add> extract_xcom=self.do_xcom_push,
<add> image_pull_policy=self.image_pull_policy,
<add> node_selectors=self.node_selectors,
<add> annotations=self.annotations,
<add> affinity=self.affinity,
<add> image_pull_secrets=self.image_pull_secrets,
<add> service_account_name=self.service_account_name,
<add> hostnetwork=self.hostnetwork,
<add> tolerations=self.tolerations,
<add> configmaps=self.configmaps,
<add> security_context=self.security_context,
<add> dnspolicy=self.dnspolicy,
<add> schedulername=self.schedulername,
<add> init_containers=self.init_containers,
<add> restart_policy='Never',
<add> priority_class_name=self.priority_class_name,
<add> pod_template_file=self.pod_template_file,
<add> pod=self.full_pod_spec,
<add> ).gen_pod()
<add>
<add> # noinspection PyTypeChecker
<add> pod = append_to_pod(
<add> pod,
<add> self.pod_runtime_info_envs + # type: ignore
<add> self.ports + # type: ignore
<add> self.resources + # type: ignore
<add> self.secrets + # type: ignore
<add> self.volumes + # type: ignore
<add> self.volume_mounts # type: ignore
<add> )
<add>
<add> self.pod = pod
<add>
<add> try:
<add> launcher.start_pod(
<add> pod,
<add> startup_timeout=self.startup_timeout_seconds)
<add> final_state, result = launcher.monitor_pod(pod=pod, get_logs=self.get_logs)
<add> except AirflowException:
<add> if self.log_events_on_failure:
<add> for event in launcher.read_pod_events(pod).items:
<add> self.log.error("Pod Event: %s - %s", event.reason, event.message)
<add> raise
<add> finally:
<add> if self.is_delete_operator_pod:
<add> launcher.delete_pod(pod)
<add> return final_state, pod, result
<add>
<add> def monitor_launched_pod(self, launcher, pod) -> Tuple[State, Optional[str]]:
<add> """
<add> Montitors a pod to completion that was created by a previous KubernetesPodOperator
<add>
<add> @param launcher: pod launcher that will manage launching and monitoring pods
<add> :param pod: podspec used to find pod using k8s API
<add> :return:
<add> """
<add> try:
<add> (final_state, result) = launcher.monitor_pod(pod, get_logs=self.get_logs)
<add> finally:
<add> if self.is_delete_operator_pod:
<add> launcher.delete_pod(pod)
<add> if final_state != State.SUCCESS:
<add> if self.log_events_on_failure:
<add> for event in launcher.read_pod_events(pod).items:
<add> self.log.error("Pod Event: %s - %s", event.reason, event.message)
<add> raise AirflowException(
<add> 'Pod returned a failure: {state}'.format(state=final_state)
<add> )
<add> return final_state, result
<ide><path>tests/executors/test_kubernetes_executor.py
<ide> from airflow.executors.kubernetes_executor import AirflowKubernetesScheduler
<ide> from airflow.executors.kubernetes_executor import KubernetesExecutor
<ide> from airflow.executors.kubernetes_executor import KubeConfig
<add> from airflow.kubernetes import pod_generator
<ide> from airflow.kubernetes.pod_generator import PodGenerator
<ide> from airflow.utils.state import State
<ide> except ImportError:
<ide> def test_create_pod_id(self):
<ide>
<ide> def test_make_safe_label_value(self):
<ide> for dag_id, task_id in self._cases():
<del> safe_dag_id = AirflowKubernetesScheduler._make_safe_label_value(dag_id)
<add> safe_dag_id = pod_generator.make_safe_label_value(dag_id)
<ide> self.assertTrue(self._is_safe_label_value(safe_dag_id))
<del> safe_task_id = AirflowKubernetesScheduler._make_safe_label_value(task_id)
<add> safe_task_id = pod_generator.make_safe_label_value(task_id)
<ide> self.assertTrue(self._is_safe_label_value(safe_task_id))
<ide> dag_id = "my_dag_id"
<ide> self.assertEqual(
<ide> dag_id,
<del> AirflowKubernetesScheduler._make_safe_label_value(dag_id)
<add> pod_generator.make_safe_label_value(dag_id)
<ide> )
<ide> dag_id = "my_dag_id_" + "a" * 64
<ide> self.assertEqual(
<ide> "my_dag_id_" + "a" * 43 + "-0ce114c45",
<del> AirflowKubernetesScheduler._make_safe_label_value(dag_id)
<add> pod_generator.make_safe_label_value(dag_id)
<ide> )
<ide>
<ide> @unittest.skipIf(AirflowKubernetesScheduler is None,
<ide><path>tests/runtime/kubernetes/test_kubernetes_pod_operator.py
<ide> from unittest.mock import ANY
<ide>
<ide> import kubernetes.client.models as k8s
<add>import pendulum
<ide> import pytest
<ide> from kubernetes.client.api_client import ApiClient
<ide> from kubernetes.client.rest import ApiException
<ide>
<ide> from airflow.exceptions import AirflowException
<add>from airflow.kubernetes import kube_client
<ide> from airflow.kubernetes.pod import Port
<ide> from airflow.kubernetes.pod_generator import PodDefaults
<ide> from airflow.kubernetes.pod_launcher import PodLauncher
<ide> from airflow.kubernetes.secret import Secret
<ide> from airflow.kubernetes.volume import Volume
<ide> from airflow.kubernetes.volume_mount import VolumeMount
<add>from airflow.models import DAG, TaskInstance
<ide> from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator
<add>from airflow.utils import timezone
<ide> from airflow.version import version as airflow_version
<ide>
<ide>
<ide> def setUp(self):
<ide> 'annotations': {},
<ide> 'labels': {
<ide> 'foo': 'bar', 'kubernetes_pod_operator': 'True',
<del> 'airflow_version': airflow_version.replace('+', '-')
<del> }
<add> 'airflow_version': airflow_version.replace('+', '-'),
<add> 'execution_date': '2016-01-01T0100000100-a2f50a31f',
<add> 'dag_id': 'dag',
<add> 'task_id': 'task',
<add> 'try_number': '1'},
<ide> },
<ide> 'spec': {
<ide> 'affinity': {},
<ide> def setUp(self):
<ide> }
<ide> }
<ide>
<add> def tearDown(self) -> None:
<add> client = kube_client.get_kube_client(in_cluster=False)
<add> client.delete_collection_namespaced_pod(namespace="default")
<add>
<add> def create_context(self, task):
<add> dag = DAG(dag_id="dag")
<add> tzinfo = pendulum.timezone("Europe/Amsterdam")
<add> execution_date = timezone.datetime(2016, 1, 1, 1, 0, 0, tzinfo=tzinfo)
<add> task_instance = TaskInstance(task=task,
<add> execution_date=execution_date)
<add> return {
<add> "dag": dag,
<add> "ts": execution_date.isoformat(),
<add> "task": task,
<add> "ti": task_instance,
<add> }
<add>
<ide> def test_do_xcom_push_defaults_false(self):
<ide> new_config_path = '/tmp/kube_config'
<ide> old_config_path = os.path.expanduser('~/.kube/config')
<ide> def test_config_path_move(self):
<ide> cmds=["bash", "-cx"],
<ide> arguments=["echo 10"],
<ide> labels={"foo": "bar"},
<del> name="test",
<add> name="test1",
<ide> task_id="task",
<ide> in_cluster=False,
<ide> do_xcom_push=False,
<ide> config_file=new_config_path,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide>
<del> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.run_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<ide> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<del> def test_config_path(self, client_mock, launcher_mock):
<add> def test_config_path(self, client_mock, monitor_mock, start_mock): # pylint: disable=unused-argument
<ide> from airflow.utils.state import State
<ide>
<ide> file_path = "/tmp/fake_file"
<ide> def test_config_path(self, client_mock, launcher_mock):
<ide> config_file=file_path,
<ide> cluster_context='default',
<ide> )
<del> launcher_mock.return_value = (State.SUCCESS, None)
<del> k.execute(None)
<add> monitor_mock.return_value = (State.SUCCESS, None)
<add> client_mock.list_namespaced_pod.return_value = []
<add> context = self.create_context(k)
<add> k.execute(context=context)
<ide> client_mock.assert_called_once_with(
<ide> in_cluster=False,
<ide> cluster_context='default',
<ide> config_file=file_path,
<ide> )
<ide>
<del> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.run_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<ide> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<del> def test_image_pull_secrets_correctly_set(self, mock_client, launcher_mock):
<add> def test_image_pull_secrets_correctly_set(self, mock_client, monitor_mock, start_mock):
<ide> from airflow.utils.state import State
<ide>
<ide> fake_pull_secrets = "fakeSecret"
<ide> def test_image_pull_secrets_correctly_set(self, mock_client, launcher_mock):
<ide> image_pull_secrets=fake_pull_secrets,
<ide> cluster_context='default',
<ide> )
<del> launcher_mock.return_value = (State.SUCCESS, None)
<del> k.execute(None)
<add> monitor_mock.return_value = (State.SUCCESS, None)
<add> context = self.create_context(k)
<add> k.execute(context=context)
<ide> self.assertEqual(
<del> launcher_mock.call_args[0][0].spec.image_pull_secrets,
<add> start_mock.call_args[0][0].spec.image_pull_secrets,
<ide> [k8s.V1LocalObjectReference(name=fake_pull_secrets)]
<ide> )
<ide>
<del> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.run_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<ide> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.delete_pod")
<ide> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<del> def test_pod_delete_even_on_launcher_error(self, mock_client, delete_pod_mock, run_pod_mock):
<add> def test_pod_delete_even_on_launcher_error(
<add> self,
<add> mock_client,
<add> delete_pod_mock,
<add> monitor_pod_mock,
<add> start_pod_mock): # pylint: disable=unused-argument
<ide> k = KubernetesPodOperator(
<ide> namespace='default',
<ide> image="ubuntu:16.04",
<ide> def test_pod_delete_even_on_launcher_error(self, mock_client, delete_pod_mock, r
<ide> cluster_context='default',
<ide> is_delete_operator_pod=True,
<ide> )
<del> run_pod_mock.side_effect = AirflowException('fake failure')
<add> monitor_pod_mock.side_effect = AirflowException('fake failure')
<ide> with self.assertRaises(AirflowException):
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context=context)
<ide> assert delete_pod_mock.called
<ide>
<ide> def test_working_pod(self):
<ide> def test_working_pod(self):
<ide> in_cluster=False,
<ide> do_xcom_push=False,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<del> self.assertEqual(self.expected_pod, actual_pod)
<add> self.assertEqual(self.expected_pod['spec'], actual_pod['spec'])
<add> self.assertEqual(self.expected_pod['metadata']['labels'], actual_pod['metadata']['labels'])
<ide>
<ide> def test_delete_operator_pod(self):
<ide> k = KubernetesPodOperator(
<ide> def test_delete_operator_pod(self):
<ide> do_xcom_push=False,
<ide> is_delete_operator_pod=True,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<del> self.assertEqual(self.expected_pod, actual_pod)
<add> self.assertEqual(self.expected_pod['spec'], actual_pod['spec'])
<add> self.assertEqual(self.expected_pod['metadata']['labels'], actual_pod['metadata']['labels'])
<ide>
<ide> def test_pod_hostnetwork(self):
<ide> k = KubernetesPodOperator(
<ide> def test_pod_hostnetwork(self):
<ide> do_xcom_push=False,
<ide> hostnetwork=True,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['hostNetwork'] = True
<del> self.assertEqual(self.expected_pod, actual_pod)
<add> self.assertEqual(self.expected_pod['spec'], actual_pod['spec'])
<add> self.assertEqual(self.expected_pod['metadata']['labels'], actual_pod['metadata']['labels'])
<ide>
<ide> def test_pod_dnspolicy(self):
<ide> dns_policy = "ClusterFirstWithHostNet"
<ide> def test_pod_dnspolicy(self):
<ide> hostnetwork=True,
<ide> dnspolicy=dns_policy
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['hostNetwork'] = True
<ide> self.expected_pod['spec']['dnsPolicy'] = dns_policy
<del> self.assertEqual(self.expected_pod, actual_pod)
<add> self.assertEqual(self.expected_pod['spec'], actual_pod['spec'])
<add> self.assertEqual(self.expected_pod['metadata']['labels'], actual_pod['metadata']['labels'])
<ide>
<ide> def test_pod_schedulername(self):
<ide> scheduler_name = "default-scheduler"
<ide> def test_pod_schedulername(self):
<ide> do_xcom_push=False,
<ide> schedulername=scheduler_name
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['schedulerName'] = scheduler_name
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_pod_node_selectors(self):
<ide> do_xcom_push=False,
<ide> node_selectors=node_selectors,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['nodeSelector'] = node_selectors
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_pod_resources(self):
<ide> do_xcom_push=False,
<ide> resources=resources,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['containers'][0]['resources'] = {
<ide> 'requests': {
<ide> def test_pod_affinity(self):
<ide> do_xcom_push=False,
<ide> affinity=affinity,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context=context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['affinity'] = affinity
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_port(self):
<ide> do_xcom_push=False,
<ide> ports=[port],
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context=context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['containers'][0]['ports'] = [{
<ide> 'name': 'http',
<ide> def test_volume_mount(self):
<ide> in_cluster=False,
<ide> do_xcom_push=False,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context=context)
<ide> mock_logger.info.assert_any_call(b"retrieved from mount\n")
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['containers'][0]['args'] = args
<ide> def test_run_as_user_root(self):
<ide> do_xcom_push=False,
<ide> security_context=security_context,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['securityContext'] = security_context
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_run_as_user_non_root(self):
<ide> do_xcom_push=False,
<ide> security_context=security_context,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['securityContext'] = security_context
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_fs_group(self):
<ide> do_xcom_push=False,
<ide> security_context=security_context,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['securityContext'] = security_context
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_faulty_image(self):
<ide> startup_timeout_seconds=5,
<ide> )
<ide> with self.assertRaises(AirflowException):
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['containers'][0]['image'] = bad_image_name
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_faulty_service_account(self):
<ide> service_account_name=bad_service_account_name,
<ide> )
<ide> with self.assertRaises(ApiException):
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['serviceAccountName'] = bad_service_account_name
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_pod_failure(self):
<ide> do_xcom_push=False,
<ide> )
<ide> with self.assertRaises(AirflowException):
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['containers'][0]['args'] = bad_internal_command
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide> def test_xcom_push(self):
<ide> in_cluster=False,
<ide> do_xcom_push=True,
<ide> )
<del> self.assertEqual(k.execute(None), json.loads(return_value))
<add> context = self.create_context(k)
<add> self.assertEqual(k.execute(context), json.loads(return_value))
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> volume = self.api_client.sanitize_for_serialization(PodDefaults.VOLUME)
<ide> volume_mount = self.api_client.sanitize_for_serialization(PodDefaults.VOLUME_MOUNT)
<ide> def test_xcom_push(self):
<ide> self.expected_pod['spec']['containers'].append(container)
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide>
<del> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.run_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<ide> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<del> def test_envs_from_configmaps(self, mock_client, mock_launcher):
<add> def test_envs_from_configmaps(self, mock_client, mock_monitor, mock_start):
<ide> # GIVEN
<ide> from airflow.utils.state import State
<ide>
<ide> def test_envs_from_configmaps(self, mock_client, mock_launcher):
<ide> configmaps=[configmap],
<ide> )
<ide> # THEN
<del> mock_launcher.return_value = (State.SUCCESS, None)
<del> k.execute(None)
<add> mock_monitor.return_value = (State.SUCCESS, None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> self.assertEqual(
<del> mock_launcher.call_args[0][0].spec.containers[0].env_from,
<add> mock_start.call_args[0][0].spec.containers[0].env_from,
<ide> [k8s.V1EnvFromSource(config_map_ref=k8s.V1ConfigMapEnvSource(
<ide> name=configmap
<ide> ))]
<ide> )
<ide>
<del> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.run_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<ide> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<del> def test_envs_from_secrets(self, mock_client, launcher_mock):
<add> def test_envs_from_secrets(self, mock_client, monitor_mock, start_mock):
<ide> # GIVEN
<ide> from airflow.utils.state import State
<ide> secret_ref = 'secret_name'
<ide> def test_envs_from_secrets(self, mock_client, launcher_mock):
<ide> do_xcom_push=False,
<ide> )
<ide> # THEN
<del> launcher_mock.return_value = (State.SUCCESS, None)
<del> k.execute(None)
<add> monitor_mock.return_value = (State.SUCCESS, None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> self.assertEqual(
<del> launcher_mock.call_args[0][0].spec.containers[0].env_from,
<add> start_mock.call_args[0][0].spec.containers[0].env_from,
<ide> [k8s.V1EnvFromSource(secret_ref=k8s.V1SecretEnvSource(
<ide> name=secret_ref
<ide> ))]
<ide> def test_init_container(self):
<ide>
<ide> volume_config = {
<ide> 'persistentVolumeClaim':
<del> {
<del> 'claimName': 'test-volume'
<del> }
<add> {
<add> 'claimName': 'test-volume'
<add> }
<ide> }
<ide> volume = Volume(name='test-volume', configs=volume_config)
<ide>
<ide> def test_init_container(self):
<ide> in_cluster=False,
<ide> do_xcom_push=False,
<ide> )
<del> k.execute(None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['initContainers'] = [expected_init_container]
<ide> self.expected_pod['spec']['volumes'] = [{
<ide> def test_init_container(self):
<ide> }]
<ide> self.assertEqual(self.expected_pod, actual_pod)
<ide>
<del> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.run_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<ide> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<del> def test_pod_template_file(self, mock_client, launcher_mock):
<add> def test_pod_template_file(
<add> self,
<add> mock_client,
<add> monitor_mock,
<add> start_mock): # pylint: disable=unused-argument
<ide> from airflow.utils.state import State
<ide> k = KubernetesPodOperator(
<ide> task_id='task',
<ide> pod_template_file='tests/kubernetes/pod.yaml',
<ide> do_xcom_push=True
<ide> )
<del> launcher_mock.return_value = (State.SUCCESS, None)
<del> k.execute(None)
<add> monitor_mock.return_value = (State.SUCCESS, None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.assertEqual({
<ide> 'apiVersion': 'v1',
<ide> def test_pod_template_file(self, mock_client, launcher_mock):
<ide> }
<ide> }, actual_pod)
<ide>
<del> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.run_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<ide> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<del> def test_pod_priority_class_name(self, mock_client, launcher_mock):
<add> def test_pod_priority_class_name(
<add> self,
<add> mock_client,
<add> monitor_mock,
<add> start_mock): # pylint: disable=unused-argument
<ide> """Test ability to assign priorityClassName to pod
<ide>
<ide> """
<ide> def test_pod_priority_class_name(self, mock_client, launcher_mock):
<ide> priority_class_name=priority_class_name,
<ide> )
<ide>
<del> launcher_mock.return_value = (State.SUCCESS, None)
<del> k.execute(None)
<add> monitor_mock.return_value = (State.SUCCESS, None)
<add> context = self.create_context(k)
<add> k.execute(context)
<ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod)
<ide> self.expected_pod['spec']['priorityClassName'] = priority_class_name
<ide> self.assertEqual(self.expected_pod, actual_pod) | 6 |
Python | Python | fix weird windows ssl issues | d097055dfae56861264b235b757be434a239bc2c | <ide><path>pip-date.py
<ide> from bisect import bisect
<ide> from datetime import datetime
<ide> from datetime import timedelta
<add>import ssl
<ide>
<ide> try:
<del> from urllib.request import urlopen
<add> from urllib.request import Request, build_opener, HTTPSHandler, URLError
<ide> except ImportError:
<del> from urllib import urlopen
<add> from urllib2 import Request, build_opener, HTTPSHandler, URLError
<ide>
<ide> from pip.commands.uninstall import UninstallCommand
<ide> from pip.commands.install import InstallCommand
<ide> from pip import get_installed_distributions
<ide>
<ide>
<ide> def get_releases(package_name):
<del> url = 'http://pypi.python.org/pypi/%s/json' % package_name
<del> return json.loads(urlopen(url).read().decode('utf8'))['releases']
<add> url = 'https://pypi.python.org/pypi/%s/json' % package_name
<add>
<add> ssl_context = HTTPSHandler(
<add> context=ssl.SSLContext(ssl.PROTOCOL_TLSv1))
<add> opener = build_opener(ssl_context)
<add>
<add> retries = 10
<add> while retries > 0:
<add> try:
<add> r = opener.open(Request(url))
<add> break
<add> except URLError:
<add> retries -= 1
<add>
<add> return json.loads(r.read().decode('utf8'))['releases']
<ide>
<ide>
<ide> def parse_iso8601(s): | 1 |
Go | Go | correct the info message when stop container | 6716a3a167fcd0a9abc013ce536117175922af96 | <ide><path>daemon/stop.go
<ide> func (daemon *Daemon) containerStop(container *container.Container, seconds int)
<ide> return nil
<ide> }
<ide>
<del> // 1. Send a SIGTERM
<del> if err := daemon.killPossiblyDeadProcess(container, container.StopSignal()); err != nil {
<del> logrus.Infof("Failed to send SIGTERM to the process, force killing")
<add> stopSignal := container.StopSignal()
<add> // 1. Send a stop signal
<add> if err := daemon.killPossiblyDeadProcess(container, stopSignal); err != nil {
<add> logrus.Infof("Failed to send signal %d to the process, force killing", stopSignal)
<ide> if err := daemon.killPossiblyDeadProcess(container, 9); err != nil {
<ide> return err
<ide> }
<ide> }
<ide>
<ide> // 2. Wait for the process to exit on its own
<ide> if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil {
<del> logrus.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
<add> logrus.Infof("Container %v failed to exit within %d seconds of signal %d - using the force", container.ID, seconds, stopSignal)
<ide> // 3. If it doesn't, then send SIGKILL
<ide> if err := daemon.Kill(container); err != nil {
<ide> container.WaitStop(-1 * time.Second) | 1 |
Python | Python | remove ignored applications files | f312e5acf16100c6e5c1ce4b37a66eed3e62e846 | <ide><path>keras/applications/mobilenetv2.py
<del># Only for backwards compatibility.
<del>from .mobilenet_v2 import *
<ide><path>keras/applications/resnext.py
<del>from __future__ import absolute_import
<del>from __future__ import division
<del>from __future__ import print_function
<del>
<del>try:
<del> from keras_applications import resnext
<del>except:
<del> resnext = None
<del>from . import keras_modules_injection
<del>
<del>
<del>@keras_modules_injection
<del>def ResNeXt50(*args, **kwargs):
<del> return resnext.ResNeXt50(*args, **kwargs)
<del>
<del>
<del>@keras_modules_injection
<del>def ResNeXt101(*args, **kwargs):
<del> return resnext.ResNeXt101(*args, **kwargs)
<del>
<del>
<del>@keras_modules_injection
<del>def decode_predictions(*args, **kwargs):
<del> return resnext.decode_predictions(*args, **kwargs)
<del>
<del>
<del>@keras_modules_injection
<del>def preprocess_input(*args, **kwargs):
<del> return resnext.preprocess_input(*args, **kwargs) | 2 |
Javascript | Javascript | update snapshots for typo | 2f4e370ee8add8ffa123a77884a1c015fda7cfc5 | <ide><path>test/Validation.test.js
<ide> describe("Validation", () => {
<ide>
<ide> createTestCase("undefined configuration", undefined, msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration should be an object:
<ide> object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, experiments?, externals?, infrastructureLogging?, loader?, mode?, module?, name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }"
<ide> `)
<ide> );
<ide>
<ide> createTestCase("null configuration", null, msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration should be an object:
<ide> object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, experiments?, externals?, infrastructureLogging?, loader?, mode?, module?, name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }"
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.entry should be an non-empty string.
<ide> -> An entry point without name. The string is resolved to a module which is loaded upon startup."
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.entry['bundle'] should be an non-empty array.
<ide> -> A non-empty array of non-empty strings"
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.module.wrappedContextRegExp should be an instance of RegExp
<ide> -> Set the inner regular expression for partial dynamic dependencies."
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.parallelism should be >= 1.
<ide> -> The number of parallel processed modules in the compilation."
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.entry should not contain the item 'abc' twice.
<ide> -> A non-empty array of non-empty strings"
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.entry[0] should be a non-empty string.
<ide> -> A non-empty string
<ide> - configuration.output.filename should be one of these:
<ide> describe("Validation", () => {
<ide> ],
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration[0].entry[0] should be a non-empty string.
<ide> -> A non-empty string
<ide> - configuration[1].output.filename should be one of these:
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.module.rules[0].oneOf[0] has an unknown property 'passer'. These properties are valid:
<ide> object { compiler?, enforce?, exclude?, generator?, include?, issuer?, loader?, oneOf?, options?, parser?, realResource?, resolve?, resource?, resourceQuery?, rules?, sideEffects?, test?, type?, use? }
<ide> -> A rule"
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration has an unknown property 'postcss'. These properties are valid:
<ide> object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, experiments?, externals?, infrastructureLogging?, loader?, mode?, module?, name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }
<ide> For typos: please correct them.
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.devtool should be one of these:
<ide> false | \\"eval\\" | string (should match pattern \\"^(inline-|hidden-|eval-)?(nosources-)?(cheap-(module-)?)?source-map$\\")
<ide> -> A developer tool to enhance debugging (false | eval | [inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map).
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.output.path: The provided value \\"/somepath/!test\\" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
<ide> -> The output directory as **absolute path** (required)."
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.output.filename: A relative path is expected. However, the provided value \\"/bar\\" is an absolute path!
<ide> Please use output.path to specify absolute path and output.filename for the file name."
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.context: The provided value \\"baz\\" is not an absolute path!
<ide> -> The base directory (absolute path!) for resolving the \`entry\` option. If \`output.pathinfo\` is set, the included pathinfo is shortened to this directory."
<ide> `)
<ide> describe("Validation", () => {
<ide> .replace(/object \{ .* \}/g, "object {...}")
<ide> .replace(/"none" \| .+/g, '"none" | ...')
<ide> ).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.stats has an unknown property 'foobar'. These properties are valid:
<ide> object {...}"
<ide> `);
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.plugins[0] should be one of these:
<ide> object { apply, … } | function
<ide> -> Plugin of type object or instanceof Function
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.plugins[0] should be one of these:
<ide> object { apply, … } | function
<ide> -> Plugin of type object or instanceof Function
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.plugins[0] should be one of these:
<ide> object { apply, … } | function
<ide> -> Plugin of type object or instanceof Function
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.plugins[0] should be one of these:
<ide> object { apply, … } | function
<ide> -> Plugin of type object or instanceof Function
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.plugins[0] misses the property 'apply'. Should be:
<ide> function
<ide> -> The run point of the plugin, required method."
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.mode should be one of these:
<ide> \\"development\\" | \\"production\\" | \\"none\\"
<ide> -> Enable production optimizations or development hints."
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration has an unknown property 'debug'. These properties are valid:
<ide> object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, experiments?, externals?, infrastructureLogging?, loader?, mode?, module?, name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }
<ide> The 'debug' property was removed in webpack 2.0.0.
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.optimization.splitChunks.cacheGroups should not be object { test, … }
<ide> -> Using the cacheGroup shorthand syntax with a cache group named 'test' is a potential config error
<ide> Did you intent to define a cache group with a test instead?
<ide> describe("Validation", () => {
<ide> ],
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration[1] should be an object:
<ide> object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, experiments?, externals?, infrastructureLogging?, loader?, mode?, module?, name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }"
<ide> `)
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.output.ecmaVersion should be one of these:
<ide> number (should be >= 5 and <= 11) | 2009 | number (should be >= 2015 and <= 2020)
<ide> -> The maximum EcmaScript version of the webpack generated code (doesn't include input source code from modules).
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.output.ecmaVersion should be one of these:
<ide> number (should be >= 5 and <= 11) | 2009 | number (should be >= 2015 and <= 2020)
<ide> -> The maximum EcmaScript version of the webpack generated code (doesn't include input source code from modules).
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.output.ecmaVersion should be one of these:
<ide> number (should be >= 5 and <= 11) | 2009 | number (should be >= 2015 and <= 2020)
<ide> -> The maximum EcmaScript version of the webpack generated code (doesn't include input source code from modules).
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.output.ecmaVersion should be one of these:
<ide> number (should be >= 5 and <= 11) | 2009 | number (should be >= 2015 and <= 2020)
<ide> -> The maximum EcmaScript version of the webpack generated code (doesn't include input source code from modules).
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.devtool should match pattern \\"^(inline-|hidden-|eval-)?(nosources-)?(cheap-(module-)?)?source-map$\\"."
<ide> `)
<ide> );
<ide> describe("Validation", () => {
<ide> },
<ide> msg =>
<ide> expect(msg).toMatchInlineSnapshot(`
<del> "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.devtool should match pattern \\"^(inline-|hidden-|eval-)?(nosources-)?(cheap-(module-)?)?source-map$\\"."
<ide> `)
<ide> ); | 1 |
Go | Go | drop containerfs type alias | 9ce2b30b817ad6fe6da8d91e5ac0aa19fb64e0d1 | <ide><path>builder/builder.go
<ide> import (
<ide> containerpkg "github.com/docker/docker/container"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> )
<ide>
<ide> const (
<ide> const (
<ide> // instructions in the builder.
<ide> type Source interface {
<ide> // Root returns root path for accessing source
<del> Root() containerfs.ContainerFS
<add> Root() string
<ide> // Close allows to signal that the filesystem tree won't be used anymore.
<ide> // For Context implementations using a temporary directory, it is recommended to
<ide> // delete the temporary directory in Close().
<ide> type ROLayer interface {
<ide> // RWLayer is active layer that can be read/modified
<ide> type RWLayer interface {
<ide> Release() error
<del> Root() containerfs.ContainerFS
<add> Root() string
<ide> Commit() (ROLayer, error)
<ide> }
<ide><path>builder/dockerfile/copy.go
<ide> type pathCache interface {
<ide> // copyInfo is a data object which stores the metadata about each source file in
<ide> // a copyInstruction
<ide> type copyInfo struct {
<del> root containerfs.ContainerFS
<add> root string
<ide> path string
<ide> hash string
<ide> noDecompress bool
<ide><path>builder/dockerfile/internals_test.go
<ide> import (
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/go-connections/nat"
<ide> "github.com/opencontainers/go-digest"
<ide> "gotest.tools/v3/assert"
<ide> func TestDeepCopyRunConfig(t *testing.T) {
<ide>
<ide> type MockRWLayer struct{}
<ide>
<del>func (l *MockRWLayer) Release() error { return nil }
<del>func (l *MockRWLayer) Root() containerfs.ContainerFS { return "" }
<add>func (l *MockRWLayer) Release() error { return nil }
<add>func (l *MockRWLayer) Root() string { return "" }
<ide> func (l *MockRWLayer) Commit() (builder.ROLayer, error) {
<ide> return &MockROLayer{
<ide> diffID: layer.DiffID(digest.Digest("sha256:1234")),
<ide><path>builder/dockerfile/mockbackend_test.go
<ide> import (
<ide> containerpkg "github.com/docker/docker/container"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> )
<ide>
<ide> // MockBackend implements the builder.Backend interface for unit testing
<ide> func (l *mockRWLayer) Commit() (builder.ROLayer, error) {
<ide> return nil, nil
<ide> }
<ide>
<del>func (l *mockRWLayer) Root() containerfs.ContainerFS {
<add>func (l *mockRWLayer) Root() string {
<ide> return ""
<ide> }
<ide><path>builder/remotecontext/archive.go
<ide> import (
<ide> )
<ide>
<ide> type archiveContext struct {
<del> root containerfs.ContainerFS
<add> root string
<ide> sums tarsum.FileInfoSums
<ide> }
<ide>
<ide> func FromArchive(tarStream io.Reader) (builder.Source, error) {
<ide> return tsc, nil
<ide> }
<ide>
<del>func (c *archiveContext) Root() containerfs.ContainerFS {
<add>func (c *archiveContext) Root() string {
<ide> return c.root
<ide> }
<ide>
<ide> func (c *archiveContext) Hash(path string) (string, error) {
<ide> return path, nil // backwards compat TODO: see if really needed
<ide> }
<ide>
<del>func normalize(path string, root containerfs.ContainerFS) (cleanPath, fullPath string, err error) {
<add>func normalize(path string, root string) (cleanPath, fullPath string, err error) {
<ide> cleanPath = filepath.Clean(string(filepath.Separator) + path)[1:]
<ide> fullPath, err = containerfs.ResolveScopedPath(root, path)
<ide> if err != nil {
<ide><path>builder/remotecontext/detect_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/builder"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> )
<ide>
<ide> const (
<ide> func TestProcessShouldLeaveAllFiles(t *testing.T) {
<ide>
<ide> // TODO: remove after moving to a separate pkg
<ide> type stubRemote struct {
<del> root containerfs.ContainerFS
<add> root string
<ide> }
<ide>
<ide> func (r *stubRemote) Hash(path string) (string, error) {
<ide> return "", errors.New("not implemented")
<ide> }
<ide>
<del>func (r *stubRemote) Root() containerfs.ContainerFS {
<add>func (r *stubRemote) Root() string {
<ide> return r.root
<ide> }
<ide> func (r *stubRemote) Close() error {
<ide><path>builder/remotecontext/lazycontext.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/builder"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<ide> // NewLazySource creates a new LazyContext. LazyContext defines a hashed build
<ide> // context based on a root directory. Individual files are hashed first time
<ide> // they are asked. It is not safe to call methods of LazyContext concurrently.
<del>func NewLazySource(root containerfs.ContainerFS) (builder.Source, error) {
<add>func NewLazySource(root string) (builder.Source, error) {
<ide> return &lazySource{
<ide> root: root,
<ide> sums: make(map[string]string),
<ide> }, nil
<ide> }
<ide>
<ide> type lazySource struct {
<del> root containerfs.ContainerFS
<add> root string
<ide> sums map[string]string
<ide> }
<ide>
<del>func (c *lazySource) Root() containerfs.ContainerFS {
<add>func (c *lazySource) Root() string {
<ide> return c.root
<ide> }
<ide>
<ide> func (c *lazySource) prepareHash(relPath string, fi os.FileInfo) (string, error)
<ide>
<ide> // Rel makes a path relative to base path. Same as `filepath.Rel` but can also
<ide> // handle UUID paths in windows.
<del>func Rel(basepath containerfs.ContainerFS, targpath string) (string, error) {
<add>func Rel(basepath string, targpath string) (string, error) {
<ide> // filepath.Rel can't handle UUID paths in windows
<ide> if runtime.GOOS == "windows" {
<ide> pfx := basepath + `\`
<ide><path>builder/remotecontext/tarsum.go
<ide> import (
<ide> "path/filepath"
<ide> "sync"
<ide>
<del> "github.com/docker/docker/pkg/containerfs"
<ide> iradix "github.com/hashicorp/go-immutable-radix"
<ide> "github.com/opencontainers/go-digest"
<ide> "github.com/pkg/errors"
<ide> type hashed interface {
<ide> // CachableSource is a source that contains cache records for its contents
<ide> type CachableSource struct {
<ide> mu sync.Mutex
<del> root containerfs.ContainerFS
<add> root string
<ide> tree *iradix.Tree
<ide> txn *iradix.Txn
<ide> }
<ide> func (cs *CachableSource) Hash(path string) (string, error) {
<ide> }
<ide>
<ide> // Root returns a root directory for the source
<del>func (cs *CachableSource) Root() containerfs.ContainerFS {
<add>func (cs *CachableSource) Root() string {
<ide> return cs.root
<ide> }
<ide>
<ide><path>container/container.go
<ide> type ExitStatus struct {
<ide> type Container struct {
<ide> StreamConfig *stream.Config
<ide> // embed for Container to support states directly.
<del> *State `json:"State"` // Needed for Engine API version <= 1.11
<del> Root string `json:"-"` // Path to the "home" of the container, including metadata.
<del> BaseFS containerfs.ContainerFS `json:"-"` // interface containing graphdriver mount
<del> RWLayer layer.RWLayer `json:"-"`
<add> *State `json:"State"` // Needed for Engine API version <= 1.11
<add> Root string `json:"-"` // Path to the "home" of the container, including metadata.
<add> BaseFS string `json:"-"` // Path to the graphdriver mountpoint
<add> RWLayer layer.RWLayer `json:"-"`
<ide> ID string
<ide> Created time.Time
<ide> Managed bool
<ide><path>daemon/daemon_unix.go
<ide> import (
<ide> "github.com/docker/docker/libnetwork/options"
<ide> lntypes "github.com/docker/docker/libnetwork/types"
<ide> "github.com/docker/docker/opts"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> func removeDefaultBridgeInterface() {
<ide> }
<ide> }
<ide>
<del>func setupInitLayer(idMapping idtools.IdentityMapping) func(containerfs.ContainerFS) error {
<del> return func(initPath containerfs.ContainerFS) error {
<add>func setupInitLayer(idMapping idtools.IdentityMapping) func(string) error {
<add> return func(initPath string) error {
<ide> return initlayer.Setup(initPath, idMapping.RootPair())
<ide> }
<ide> }
<ide><path>daemon/daemon_windows.go
<ide> import (
<ide> winlibnetwork "github.com/docker/docker/libnetwork/drivers/windows"
<ide> "github.com/docker/docker/libnetwork/netlabel"
<ide> "github.com/docker/docker/libnetwork/options"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/parsers/operatingsystem"
<ide> func (daemon *Daemon) parseSecurityOpt(container *container.Container, hostConfi
<ide> return nil
<ide> }
<ide>
<del>func setupInitLayer(idMapping idtools.IdentityMapping) func(containerfs.ContainerFS) error {
<add>func setupInitLayer(idMapping idtools.IdentityMapping) func(string) error {
<ide> return nil
<ide> }
<ide>
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> func atomicRemove(source string) error {
<ide>
<ide> // Get returns the rootfs path for the id.
<ide> // This will mount the dir at its given path
<del>func (a *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) {
<add>func (a *Driver) Get(id, mountLabel string) (string, error) {
<ide> a.locker.Lock(id)
<ide> defer a.locker.Unlock(id)
<ide> parents, err := a.getParentLayerPaths(id)
<ide><path>daemon/graphdriver/btrfs/btrfs.go
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide>
<ide> // Get the requested filesystem id.
<del>func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) {
<add>func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> dir := d.subvolumesDirID(id)
<ide> st, err := os.Stat(dir)
<ide> if err != nil {
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> import (
<ide> "strconv"
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/devicemapper"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> units "github.com/docker/go-units"
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide>
<ide> // Get mounts a device with given id into the root filesystem
<del>func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) {
<add>func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> d.locker.Lock(id)
<ide> defer d.locker.Unlock(id)
<ide> mp := path.Join(d.home, "mnt", id)
<ide><path>daemon/graphdriver/driver.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/plugingetter"
<ide> "github.com/pkg/errors"
<ide> type ProtoDriver interface {
<ide> // Get returns the mountpoint for the layered filesystem referred
<ide> // to by this id. You can optionally specify a mountLabel or "".
<ide> // Returns the absolute path to the mounted layered filesystem.
<del> Get(id, mountLabel string) (fs containerfs.ContainerFS, err error)
<add> Get(id, mountLabel string) (fs string, err error)
<ide> // Put releases the system resources for the specified id,
<ide> // e.g, unmounting layered filesystem.
<ide> Put(id string) error
<ide><path>daemon/graphdriver/fuse-overlayfs/fuseoverlayfs.go
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide>
<ide> // Get creates and mounts the required file system for the given id and returns the mount path.
<del>func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
<add>func (d *Driver) Get(id, mountLabel string) (_ string, retErr error) {
<ide> d.locker.Lock(id)
<ide> defer d.locker.Unlock(id)
<ide> dir := d.dir(id)
<ide><path>daemon/graphdriver/overlay/overlay.go
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide>
<ide> // Get creates and mounts the required file system for the given id and returns the mount path.
<del>func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, err error) {
<add>func (d *Driver) Get(id, mountLabel string) (_ string, err error) {
<ide> d.locker.Lock(id)
<ide> defer d.locker.Unlock(id)
<ide> dir := d.dir(id)
<ide><path>daemon/graphdriver/overlay2/overlay.go
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide>
<ide> // Get creates and mounts the required file system for the given id and returns the mount path.
<del>func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
<add>func (d *Driver) Get(id, mountLabel string) (_ string, retErr error) {
<ide> d.locker.Lock(id)
<ide> defer d.locker.Unlock(id)
<ide> dir := d.dir(id)
<ide><path>daemon/graphdriver/proxy.go
<ide> import (
<ide> "io"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/plugingetter"
<ide> "github.com/docker/docker/pkg/plugins"
<ide> func (d *graphDriverProxy) Remove(id string) error {
<ide> return nil
<ide> }
<ide>
<del>func (d *graphDriverProxy) Get(id, mountLabel string) (containerfs.ContainerFS, error) {
<add>func (d *graphDriverProxy) Get(id, mountLabel string) (string, error) {
<ide> args := &graphDriverRequest{
<ide> ID: id,
<ide> MountLabel: mountLabel,
<ide><path>daemon/graphdriver/vfs/driver.go
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide>
<ide> // Get returns the directory for the given id.
<del>func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) {
<add>func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> dir := d.dir(id)
<ide> if st, err := os.Stat(dir); err != nil {
<ide> return "", err
<ide><path>daemon/graphdriver/windows/windows.go
<ide> import (
<ide> "github.com/Microsoft/hcsshim/osversion"
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/longpath"
<ide> func (d *Driver) GetLayerPath(id string) (string, error) {
<ide> }
<ide>
<ide> // Get returns the rootfs path for the id. This will mount the dir at its given path.
<del>func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) {
<add>func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> logrus.Debugf("WindowsGraphDriver Get() id %s mountLabel %s", id, mountLabel)
<ide> var dir string
<ide>
<ide><path>daemon/graphdriver/zfs/zfs.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> zfs "github.com/mistifyio/go-zfs"
<ide> func (d *Driver) Remove(id string) error {
<ide> }
<ide>
<ide> // Get returns the mountpoint for the given id after creating the target directories if necessary.
<del>func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
<add>func (d *Driver) Get(id, mountLabel string) (_ string, retErr error) {
<ide> d.locker.Lock(id)
<ide> defer d.locker.Unlock(id)
<ide> mountpoint := d.mountPath(id)
<ide><path>daemon/images/image_builder.go
<ide> import (
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> type rwLayer struct {
<ide> released bool
<ide> layerStore layer.Store
<ide> rwLayer layer.RWLayer
<del> fs containerfs.ContainerFS
<add> fs string
<ide> }
<ide>
<del>func (l *rwLayer) Root() containerfs.ContainerFS {
<add>func (l *rwLayer) Root() string {
<ide> return l.fs
<ide> }
<ide>
<ide><path>daemon/initlayer/setup_unix.go
<ide> import (
<ide> "path/filepath"
<ide> "strings"
<ide>
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "golang.org/x/sys/unix"
<ide> )
<ide> import (
<ide> //
<ide> // This extra layer is used by all containers as the top-most ro layer. It protects
<ide> // the container from unwanted side-effects on the rw layer.
<del>func Setup(initLayerFs containerfs.ContainerFS, rootIdentity idtools.Identity) error {
<add>func Setup(initLayerFs string, rootIdentity idtools.Identity) error {
<ide> // Since all paths are local to the container, we can just extract initLayerFs.Path()
<ide> initLayer := initLayerFs
<ide>
<ide><path>layer/layer.go
<ide> import (
<ide>
<ide> "github.com/docker/distribution"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/opencontainers/go-digest"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide> type RWLayer interface {
<ide>
<ide> // Mount mounts the RWLayer and returns the filesystem path
<ide> // to the writable layer.
<del> Mount(mountLabel string) (containerfs.ContainerFS, error)
<add> Mount(mountLabel string) (string, error)
<ide>
<ide> // Unmount unmounts the RWLayer. This should be called
<ide> // for every mount. If there are multiple mount calls
<ide> type Metadata struct {
<ide> // writable mount. Changes made here will
<ide> // not be included in the Tar stream of the
<ide> // RWLayer.
<del>type MountInit func(root containerfs.ContainerFS) error
<add>type MountInit func(root string) error
<ide>
<ide> // CreateRWLayerOpts contains optional arguments to be passed to CreateRWLayer
<ide> type CreateRWLayerOpts struct {
<ide><path>layer/layer_test.go
<ide> import (
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/daemon/graphdriver/vfs"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/opencontainers/go-digest"
<ide> func newTestStore(t *testing.T) (Store, string, func()) {
<ide> }
<ide> }
<ide>
<del>type layerInit func(root containerfs.ContainerFS) error
<add>type layerInit func(root string) error
<ide>
<ide> func createLayer(ls Store, parent ChainID, layerFunc layerInit) (Layer, error) {
<ide> containerID := stringid.GenerateRandomID()
<ide> func createLayer(ls Store, parent ChainID, layerFunc layerInit) (Layer, error) {
<ide> }
<ide>
<ide> type FileApplier interface {
<del> ApplyFile(root containerfs.ContainerFS) error
<add> ApplyFile(root string) error
<ide> }
<ide>
<ide> type testFile struct {
<ide> func newTestFile(name string, content []byte, perm os.FileMode) FileApplier {
<ide> }
<ide> }
<ide>
<del>func (tf *testFile) ApplyFile(root containerfs.ContainerFS) error {
<add>func (tf *testFile) ApplyFile(root string) error {
<ide> fullPath := filepath.Join(root, tf.name)
<ide> if err := os.MkdirAll(filepath.Dir(fullPath), 0755); err != nil {
<ide> return err
<ide> func (tf *testFile) ApplyFile(root containerfs.ContainerFS) error {
<ide> }
<ide>
<ide> func initWithFiles(files ...FileApplier) layerInit {
<del> return func(root containerfs.ContainerFS) error {
<add> return func(root string) error {
<ide> for _, f := range files {
<ide> if err := f.ApplyFile(root); err != nil {
<ide> return err
<ide><path>layer/mount_test.go
<ide> import (
<ide>
<ide> "github.com/containerd/continuity/driver"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> )
<ide>
<ide> func TestMountInit(t *testing.T) {
<ide> func TestMountInit(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> mountInit := func(root containerfs.ContainerFS) error {
<add> mountInit := func(root string) error {
<ide> return initfile.ApplyFile(root)
<ide> }
<ide>
<ide> func TestMountSize(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> mountInit := func(root containerfs.ContainerFS) error {
<add> mountInit := func(root string) error {
<ide> return newTestFile("file-init", contentInit, 0777).ApplyFile(root)
<ide> }
<ide> rwLayerOpts := &CreateRWLayerOpts{
<ide> func TestMountChanges(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> mountInit := func(root containerfs.ContainerFS) error {
<add> mountInit := func(root string) error {
<ide> return initfile.ApplyFile(root)
<ide> }
<ide> rwLayerOpts := &CreateRWLayerOpts{
<ide><path>layer/mounted_layer.go
<ide> import (
<ide> "sync"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/containerfs"
<ide> )
<ide>
<ide> type mountedLayer struct {
<ide> type referencedRWLayer struct {
<ide> *mountedLayer
<ide> }
<ide>
<del>func (rl *referencedRWLayer) Mount(mountLabel string) (containerfs.ContainerFS, error) {
<add>func (rl *referencedRWLayer) Mount(mountLabel string) (string, error) {
<ide> return rl.layerStore.driver.Get(rl.mountedLayer.mountID, mountLabel)
<ide> }
<ide>
<ide><path>pkg/containerfs/containerfs.go
<ide> import (
<ide> "github.com/moby/sys/symlink"
<ide> )
<ide>
<del>// ContainerFS is that represents a root file system
<del>type ContainerFS = string
<del>
<ide> // ResolveScopedPath evaluates the given path scoped to the root.
<ide> // For example, if root=/a, and path=/b/c, then this function would return /a/b/c.
<ide> func ResolveScopedPath(root, path string) (string, error) { | 29 |
Python | Python | fix mypy errors in aws/transfers | 463e3b2b25ee5c116313160c64bb8e2644e1fef3 | <ide><path>airflow/providers/amazon/aws/transfers/ftp_to_s3.py
<ide> def __init__(
<ide> replace: bool = False,
<ide> encrypt: bool = False,
<ide> gzip: bool = False,
<del> acl_policy: str = None,
<add> acl_policy: Optional[str] = None,
<ide> **kwargs,
<ide> ):
<ide> super().__init__(**kwargs)
<ide><path>airflow/providers/amazon/aws/transfers/google_api_to_s3.py
<ide> def _load_data_to_s3(self, data: dict) -> None:
<ide> )
<ide>
<ide> def _update_google_api_endpoint_params_via_xcom(self, task_instance: TaskInstance) -> None:
<del> google_api_endpoint_params = task_instance.xcom_pull(
<del> task_ids=self.google_api_endpoint_params_via_xcom_task_ids,
<del> key=self.google_api_endpoint_params_via_xcom,
<del> )
<del> self.google_api_endpoint_params.update(google_api_endpoint_params)
<add>
<add> if self.google_api_endpoint_params_via_xcom:
<add> google_api_endpoint_params = task_instance.xcom_pull(
<add> task_ids=self.google_api_endpoint_params_via_xcom_task_ids,
<add> key=self.google_api_endpoint_params_via_xcom,
<add> )
<add> self.google_api_endpoint_params.update(google_api_endpoint_params)
<ide>
<ide> def _expose_google_api_response_via_xcom(self, task_instance: TaskInstance, data: dict) -> None:
<ide> if sys.getsizeof(data) < MAX_XCOM_SIZE:
<ide><path>airflow/providers/amazon/aws/transfers/mongo_to_s3.py
<ide> def __init__(
<ide> self.allow_disk_use = allow_disk_use
<ide> self.compression = compression
<ide>
<del> def execute(self, context) -> bool:
<add> def execute(self, context):
<ide> """Is written to depend on transform method"""
<ide> s3_conn = S3Hook(self.aws_conn_id)
<ide>
<ide><path>airflow/providers/amazon/aws/transfers/redshift_to_s3.py
<ide> def __init__(
<ide> *,
<ide> s3_bucket: str,
<ide> s3_key: str,
<del> schema: str = None,
<del> table: str = None,
<del> select_query: str = None,
<add> schema: Optional[str] = None,
<add> table: Optional[str] = None,
<add> select_query: Optional[str] = None,
<ide> redshift_conn_id: str = 'redshift_default',
<ide> aws_conn_id: str = 'aws_default',
<ide> verify: Optional[Union[bool, str]] = None,
<ide><path>airflow/providers/amazon/aws/transfers/s3_to_redshift.py
<ide> def execute(self, context) -> None:
<ide>
<ide> copy_statement = self._build_copy_query(copy_destination, credentials_block, copy_options)
<ide>
<add> sql: Union[list, str]
<add>
<ide> if self.method == 'REPLACE':
<ide> sql = ["BEGIN;", f"DELETE FROM {destination};", copy_statement, "COMMIT"]
<ide> elif self.method == 'UPSERT': | 5 |
Javascript | Javascript | remove unused $scope | 4f9dc44f88d61609837b30696ecb286aa43af0a9 | <ide><path>src/ngMessages/messages.js
<ide> angular.module('ngMessages', [])
<ide>
<ide> return {
<ide> restrict: 'AE',
<del> controller: ['$scope', function($scope) {
<add> controller: function() {
<ide> this.$renderNgMessageClasses = angular.noop;
<ide>
<ide> var messages = [];
<ide> angular.module('ngMessages', [])
<ide> return value !== null && value !== false && value;
<ide> }
<ide> };
<del> }],
<add> },
<ide> require: 'ngMessages',
<ide> link: function($scope, element, $attrs, ctrl) {
<ide> ctrl.renderElementClasses = function(bool) { | 1 |
PHP | PHP | ensure carbon is reset after rate tests | 08100578cb467d359f5f0ef8efa7765bdde127f8 | <ide><path>src/Illuminate/Cache/RateLimiter.php
<ide> public function tooManyAttempts($key, $maxAttempts, $decayMinutes = 1)
<ide> if ($this->attempts($key) >= $maxAttempts) {
<ide> if ($this->cache->has($key.':timer')) {
<ide> return true;
<del> } else {
<del> $this->resetAttempts($key);
<del>
<del> return false;
<ide> }
<add>
<add> $this->resetAttempts($key);
<ide> }
<ide>
<ide> return false;
<ide><path>tests/Integration/Http/ThrottleRequestsTest.php
<ide>
<ide> namespace Illuminate\Tests\Integration\Http;
<ide>
<add>use Throwable;
<ide> use Illuminate\Support\Carbon;
<ide> use Orchestra\Testbench\TestCase;
<ide> use Illuminate\Support\Facades\Route;
<ide> protected function getEnvironmentSetUp($app)
<ide> public function setup()
<ide> {
<ide> parent::setup();
<del>
<ide> resolve('redis')->flushall();
<ide> }
<ide>
<add> public function tearDown()
<add> {
<add> parent::tearDown();
<add> Carbon::setTestNow(null);
<add> }
<add>
<ide> public function test_lock_opens_immediately_after_decay()
<ide> {
<ide> Carbon::setTestNow(null);
<ide> public function test_lock_opens_immediately_after_decay()
<ide> );
<ide>
<ide> try {
<del> $response = $this->withoutExceptionHandling()->get('/');
<del> } catch (\Throwable $e) {
<add> $this->withoutExceptionHandling()->get('/');
<add> } catch (Throwable $e) {
<ide> $this->assertEquals(429, $e->getStatusCode());
<ide> $this->assertEquals(2, $e->getHeaders()['X-RateLimit-Limit']);
<ide> $this->assertEquals(0, $e->getHeaders()['X-RateLimit-Remaining']);
<ide><path>tests/Integration/Http/ThrottleRequestsWithRedisTest.php
<ide>
<ide> namespace Illuminate\Tests\Integration\Http;
<ide>
<add>use Throwable;
<ide> use Illuminate\Support\Carbon;
<ide> use Orchestra\Testbench\TestCase;
<ide> use Illuminate\Support\Facades\Route;
<ide> */
<ide> class ThrottleRequestsWithRedisTest extends TestCase
<ide> {
<add> public function tearDown()
<add> {
<add> parent::tearDown();
<add> Carbon::setTestNow(null);
<add> }
<add>
<ide> public function test_lock_opens_immediately_after_decay()
<ide> {
<ide> Carbon::setTestNow(null);
<ide> public function test_lock_opens_immediately_after_decay()
<ide> );
<ide>
<ide> try {
<del> $response = $this->withoutExceptionHandling()->get('/');
<del> } catch (\Throwable $e) {
<add> $this->withoutExceptionHandling()->get('/');
<add> } catch (Throwable $e) {
<ide> $this->assertEquals(429, $e->getStatusCode());
<ide> $this->assertEquals(2, $e->getHeaders()['X-RateLimit-Limit']);
<ide> $this->assertEquals(0, $e->getHeaders()['X-RateLimit-Remaining']);
<ide> $this->assertTrue(in_array($e->getHeaders()['Retry-After'], [2, 3]));
<del> $this->assertTrue(in_array($e->getHeaders()['X-RateLimit-Reset'], [Carbon::now()->getTimestamp() + 2, Carbon::now()->timestamp + 3]));
<add> $this->assertTrue(in_array($e->getHeaders()['X-RateLimit-Reset'], [Carbon::now()->getTimestamp() + 2, Carbon::now()->getTimestamp() + 3]));
<ide> }
<ide> }
<ide> } | 3 |
Java | Java | refine propertydescriptor filtering | 002546b3e4b8d791ea6acccb81eb3168f51abb15 | <ide><path>spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.beans.PropertyDescriptor;
<ide> import java.lang.reflect.Method;
<ide> import java.lang.reflect.Modifier;
<add>import java.security.ProtectionDomain;
<ide> import java.util.Collections;
<ide> import java.util.HashSet;
<ide> import java.util.LinkedHashMap;
<ide> private CachedIntrospectionResults(Class<?> beanClass) throws BeansException {
<ide> // This call is slow so we do it once.
<ide> PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
<ide> for (PropertyDescriptor pd : pds) {
<del> if (Class.class == beanClass &&
<del> ("classLoader".equals(pd.getName()) || "protectionDomain".equals(pd.getName()))) {
<del> // Ignore Class.getClassLoader() and getProtectionDomain() methods - nobody needs to bind to those
<add> if (Class.class == beanClass && (!"name".equals(pd.getName()) && !pd.getName().endsWith("Name"))) {
<add> // Only allow all name variants of Class properties
<add> continue;
<add> }
<add> if (pd.getPropertyType() != null && (ClassLoader.class.isAssignableFrom(pd.getPropertyType())
<add> || ProtectionDomain.class.isAssignableFrom(pd.getPropertyType()))) {
<add> // Ignore ClassLoader and ProtectionDomain types - nobody needs to bind to those
<ide> continue;
<ide> }
<ide> if (logger.isTraceEnabled()) {
<ide> private void introspectInterfaces(Class<?> beanClass, Class<?> currClass, Set<St
<ide> // GenericTypeAwarePropertyDescriptor leniently resolves a set* write method
<ide> // against a declared read method, so we prefer read method descriptors here.
<ide> pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
<add> if (pd.getPropertyType() != null && (ClassLoader.class.isAssignableFrom(pd.getPropertyType())
<add> || ProtectionDomain.class.isAssignableFrom(pd.getPropertyType()))) {
<add> // Ignore ClassLoader and ProtectionDomain types - nobody needs to bind to those
<add> continue;
<add> }
<ide> this.propertyDescriptors.put(pd.getName(), pd);
<ide> Method readMethod = pd.getReadMethod();
<ide> if (readMethod != null) { | 1 |
Text | Text | make minor improvements to collab guide | e406cca5c3eb768dd66301fcac5429223e200955 | <ide><path>COLLABORATOR_GUIDE.md
<ide> For first-time contributors, check if the commit author is the same as the
<ide> pull request author, and ask if they have configured their git
<ide> username and email to their liking as per [this guide][git-username].
<ide> This is to make sure they would be promoted to "contributor" once
<del>their pull request gets landed.
<add>their pull request lands.
<ide>
<ide> ### Closing Issues and Pull Requests
<ide>
<ide> necessary.
<ide> ### Author ready pull requests
<ide>
<ide> A pull request that is still awaiting the minimum review time is considered
<del>`author-ready` as soon as the CI has been started, it has at least one approval,
<add>_author ready_ as soon as the CI has been started, it has at least one approval,
<ide> and it has no outstanding review comments. Please always make sure to add the
<del>appropriate `author-ready` label to the PR in that case and remove it again as
<del>soon as that condition is not met anymore.
<add>`author ready` label to the PR in that case and remove it again as soon as that
<add>condition is not met anymore.
<ide>
<ide> ### Handling own pull requests
<ide>
<del>If you as a Collaborator open a pull request, it is recommended to start a CI
<del>right after (see [testing and CI](#testing-and-ci) for further information on
<del>how to do that) and to post the link to it as well. Starting a new CI after each
<del>update is also recommended (due to e.g., a change request in a review or due to
<del>rebasing).
<add>When you open a pull request, it is recommended to start a CI right away (see
<add>[testing and CI](#testing-and-ci) for instructions) and to post the link to it
<add>in a comment in the pull request. Starting a new CI after each update is also
<add>recommended (for example, after an additional code change or after rebasing).
<ide>
<del>As soon as the PR is ready to land, please go ahead and do so on your own.
<del>Landing your own pull requests distributes the work load for each Collaborator
<del>equally. If it is still awaiting the
<del>[minimum time to land](#waiting-for-approvals), please add the `author-ready`
<del>label to it so it is obvious that the PR can land as soon as the time ends.
<add>As soon as the PR is ready to land, please do so. Landing your own pull requests
<add>allows other Collaborators to focus on other pull requests. If your pull request
<add>is still awaiting the [minimum time to land](#waiting-for-approvals), add the
<add>`author ready` label so other Collaborators know it can land as soon as the time
<add>ends.
<ide>
<ide> ## Accepting Modifications
<ide>
<ide> All modifications to the Node.js code and documentation should be performed via
<ide> GitHub pull requests, including modifications by Collaborators and TSC members.
<ide> A pull request must be reviewed, and must also be tested with CI, before being
<del>landed into the codebase. There may be exception to the latter (the changed code
<del>can not be tested with a CI or similar). If that is the case, please leave a
<add>landed into the codebase. There may be exceptions to the latter (the changed
<add>code cannot be tested with a CI or similar). If that is the case, please leave a
<ide> comment that explains why the PR does not require a CI run.
<ide>
<ide> ### Code Reviews
<ide> the CI outcome.
<ide> If there is no disagreement amongst Collaborators, a pull request should be
<ide> landed given appropriate review, a green CI, and the minimum
<ide> [waiting time](#waiting-for-approvals) for a PR. If it is still awaiting the
<del>[minimum time to land](#waiting-for-approvals), please add the `author-ready`
<add>[minimum time to land](#waiting-for-approvals), please add the `author ready`
<ide> label to it so it is obvious that the PR can land as soon as the time ends.
<ide>
<ide> Where there is discussion amongst Collaborators, consensus should be sought if | 1 |
Ruby | Ruby | define @title to avoid warnings | ad2c21089e435527641d891a30ff8f695114071b | <ide><path>actionpack/test/controller/capture_test.rb
<ide> def self.controller_name; "test"; end
<ide> def self.controller_path; "test"; end
<ide>
<ide> def content_for
<add> @title = nil
<ide> render :layout => "talk_from_action"
<ide> end
<ide>
<ide> def content_for_with_parameter
<add> @title = nil
<ide> render :layout => "talk_from_action"
<ide> end
<ide>
<ide> def content_for_concatenated
<add> @title = nil
<ide> render :layout => "talk_from_action"
<ide> end
<ide>
<ide> def non_erb_block_content_for
<add> @title = nil
<ide> render :layout => "talk_from_action"
<ide> end
<ide> | 1 |
Go | Go | fix a typo in docker/daemon/state.go | 7e01ecc119ea3871058309a47a3f9cbf2a9483dd | <ide><path>daemon/state.go
<ide> func (s *State) setStopped(exitStatus *execdriver.ExitStatus) {
<ide> s.waitChan = make(chan struct{})
<ide> }
<ide>
<del>// SetRestarting is when docker hanldes the auto restart of containers when they are
<add>// SetRestarting is when docker handles the auto restart of containers when they are
<ide> // in the middle of a stop and being restarted again
<ide> func (s *State) SetRestarting(exitStatus *execdriver.ExitStatus) {
<ide> s.Lock() | 1 |
Text | Text | update urls for redux.js.org | e1f12d64fd5be7cf790983f5db33620125a544d0 | <ide><path>README.md
<ide> We have a variety of resources available to help you learn Redux, no matter what
<ide>
<ide> If you're brand new to Redux and want to understand the basic concepts, see:
<ide>
<del>- The **[Motivation](https://redux.js.org/introduction/motivation)** behind building Redux, the **[Core Concepts](https://redux.js.org/introduction/coreconcepts)**, and the **[Three Principles](https://redux.js.org/introduction/threeprinciples)**.
<add>- The **[Motivation](https://redux.js.org/introduction/motivation)** behind building Redux, the **[Core Concepts](https://redux.js.org/introduction/core-concepts)**, and the **[Three Principles](https://redux.js.org/introduction/three-principles)**.
<ide> - The **[basic tutorial in the Redux docs](https://redux.js.org/basics)**
<ide> - Redux creator Dan Abramov's **free ["Getting Started with Redux" video series](https://egghead.io/series/getting-started-with-redux)** on Egghead.io
<ide> - Redux co-maintainer Mark Erikson's **["Redux Fundamentals" slideshow](http://blog.isquaredsoftware.com/2018/03/presentation-reactathon-redux-fundamentals/)** and **[list of suggested resources for learning Redux](http://blog.isquaredsoftware.com/2017/12/blogged-answers-learn-redux/)** | 1 |
Ruby | Ruby | integrate amo json serializer into ar | 783db25e0c640c1588732967a87d65c10fddc08e | <ide><path>activemodel/lib/active_model/attributes.rb
<ide>
<ide> module ActiveModel
<ide> module Attributes
<add> def self.append_features(base)
<add> unless base.instance_methods.include?('attributes')
<add> super
<add> else
<add> false
<add> end
<add> end
<add>
<ide> def attributes
<ide> instance_values
<ide> end
<ide><path>activemodel/lib/active_model/serializer.rb
<ide> class Serializer
<ide> def initialize(serializable, options = nil)
<ide> @serializable = serializable
<ide> @options = options ? options.dup : {}
<add>
<add> @options[:only] = Array.wrap(@options[:only]).map { |n| n.to_s }
<add> @options[:except] = Array.wrap(@options[:except]).map { |n| n.to_s }
<ide> end
<ide>
<ide> def serialize
<ide> def to_s(&block)
<ide> serialize(&block)
<ide> end
<ide>
<del> protected
<del> def serializable_attribute_names
<del> attribute_names = @serializable.attributes.keys
<del>
<del> if options[:only]
<del> only = Array.wrap(options[:only]).map { |n| n.to_s }
<del> attribute_names &= only
<del> elsif options[:except]
<del> except = Array.wrap(options[:except]).map { |n| n.to_s }
<del> attribute_names -= except
<del> end
<del>
<del> attribute_names
<add> # To replicate the behavior in ActiveRecord#attributes,
<add> # <tt>:except</tt> takes precedence over <tt>:only</tt>. If <tt>:only</tt> is not set
<add> # for a N level model but is set for the N+1 level models,
<add> # then because <tt>:except</tt> is set to a default value, the second
<add> # level model can have both <tt>:except</tt> and <tt>:only</tt> set. So if
<add> # <tt>:only</tt> is set, always delete <tt>:except</tt>.
<add> def serializable_attribute_names
<add> attribute_names = @serializable.attributes.keys.sort
<add>
<add> if options[:only].any?
<add> attribute_names &= options[:only]
<add> elsif options[:except].any?
<add> attribute_names -= options[:except]
<ide> end
<ide>
<del> def serializable_method_names
<del> Array.wrap(options[:methods]).inject([]) do |methods, name|
<del> methods << name if @serializable.respond_to?(name.to_s)
<del> methods
<del> end
<del> end
<add> attribute_names
<add> end
<ide>
<del> def serializable_names
<del> serializable_attribute_names + serializable_method_names
<add> def serializable_method_names
<add> Array.wrap(options[:methods]).inject([]) do |methods, name|
<add> methods << name if @serializable.respond_to?(name.to_s)
<add> methods
<ide> end
<add> end
<ide>
<del> def serializable_hash
<del> serializable_names.inject({}) { |hash, name|
<del> hash[name] = @serializable.send(name)
<del> hash
<del> }
<del> end
<add> def serializable_names
<add> serializable_attribute_names + serializable_method_names
<add> end
<add>
<add> def serializable_hash
<add> serializable_names.inject({}) { |hash, name|
<add> hash[name] = @serializable.send(name)
<add> hash
<add> }
<add> end
<ide> end
<ide> end
<ide><path>activemodel/lib/active_model/serializers/json.rb
<ide> module JSON
<ide> class Serializer < ActiveModel::Serializer
<ide> def serializable_hash
<ide> model = super
<del> if @serializable.include_root_in_json
<del> model = { @serializable.class.model_name.element => model }
<del> end
<del> model
<add> @serializable.include_root_in_json ?
<add> { @serializable.class.model_name.element => model } :
<add> model
<ide> end
<ide>
<ide> def serialize
<ide> ActiveSupport::JSON.encode(serializable_hash)
<ide> end
<ide> end
<ide>
<add> # Returns a JSON string representing the model. Some configuration is
<add> # available through +options+.
<add> #
<add> # The option <tt>ActiveRecord::Base.include_root_in_json</tt> controls the
<add> # top-level behavior of to_json. In a new Rails application, it is set to
<add> # <tt>true</tt> in initializers/new_rails_defaults.rb. When it is <tt>true</tt>,
<add> # to_json will emit a single root node named after the object's type. For example:
<add> #
<add> # konata = User.find(1)
<add> # ActiveRecord::Base.include_root_in_json = true
<add> # konata.to_json
<add> # # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
<add> # "created_at": "2006/08/01", "awesome": true} }
<add> #
<add> # ActiveRecord::Base.include_root_in_json = false
<add> # konata.to_json
<add> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<add> # "created_at": "2006/08/01", "awesome": true}
<add> #
<add> # The remainder of the examples in this section assume include_root_in_json is set to
<add> # <tt>false</tt>.
<add> #
<add> # Without any +options+, the returned JSON string will include all
<add> # the model's attributes. For example:
<add> #
<add> # konata = User.find(1)
<add> # konata.to_json
<add> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<add> # "created_at": "2006/08/01", "awesome": true}
<add> #
<add> # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
<add> # included, and work similar to the +attributes+ method. For example:
<add> #
<add> # konata.to_json(:only => [ :id, :name ])
<add> # # => {"id": 1, "name": "Konata Izumi"}
<add> #
<add> # konata.to_json(:except => [ :id, :created_at, :age ])
<add> # # => {"name": "Konata Izumi", "awesome": true}
<add> #
<add> # To include any methods on the model, use <tt>:methods</tt>.
<add> #
<add> # konata.to_json(:methods => :permalink)
<add> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<add> # "created_at": "2006/08/01", "awesome": true,
<add> # "permalink": "1-konata-izumi"}
<add> #
<add> # To include associations, use <tt>:include</tt>.
<add> #
<add> # konata.to_json(:include => :posts)
<add> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<add> # "created_at": "2006/08/01", "awesome": true,
<add> # "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
<add> # {"id": 2, author_id: 1, "title": "So I was thinking"}]}
<add> #
<add> # 2nd level and higher order associations work as well:
<add> #
<add> # konata.to_json(:include => { :posts => {
<add> # :include => { :comments => {
<add> # :only => :body } },
<add> # :only => :title } })
<add> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<add> # "created_at": "2006/08/01", "awesome": true,
<add> # "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
<add> # "title": "Welcome to the weblog"},
<add> # {"comments": [{"body": "Don't think too hard"}],
<add> # "title": "So I was thinking"}]}
<ide> def encode_json(encoder)
<ide> Serializer.new(self, encoder.options).to_s
<ide> end
<ide><path>activerecord/lib/active_record/serialization.rb
<ide> module ActiveRecord #:nodoc:
<ide> module Serialization
<del> class Serializer #:nodoc:
<del> attr_reader :options
<del>
<del> def initialize(record, options = nil)
<del> @record = record
<del> @options = options ? options.dup : {}
<del> end
<del>
<del> # To replicate the behavior in ActiveRecord#attributes,
<del> # <tt>:except</tt> takes precedence over <tt>:only</tt>. If <tt>:only</tt> is not set
<del> # for a N level model but is set for the N+1 level models,
<del> # then because <tt>:except</tt> is set to a default value, the second
<del> # level model can have both <tt>:except</tt> and <tt>:only</tt> set. So if
<del> # <tt>:only</tt> is set, always delete <tt>:except</tt>.
<del> def serializable_attribute_names
<del> attribute_names = @record.attribute_names
<del>
<del> if options[:only]
<del> options.delete(:except)
<del> attribute_names = attribute_names & Array.wrap(options[:only]).collect { |n| n.to_s }
<del> else
<del> options[:except] = Array.wrap(options[:except]) | Array.wrap(@record.class.inheritance_column)
<del> attribute_names = attribute_names - options[:except].collect { |n| n.to_s }
<del> end
<del>
<del> attribute_names
<del> end
<del>
<del> def serializable_method_names
<del> Array.wrap(options[:methods]).inject([]) do |method_attributes, name|
<del> method_attributes << name if @record.respond_to?(name.to_s)
<del> method_attributes
<del> end
<del> end
<del>
<del> def serializable_names
<del> serializable_attribute_names + serializable_method_names
<add> module RecordSerializer #:nodoc:
<add> def initialize(*args)
<add> super
<add> options[:except] |= Array.wrap(@serializable.class.inheritance_column)
<ide> end
<ide>
<ide> # Add associations specified via the <tt>:includes</tt> option.
<ide> def add_includes(&block)
<ide> associations = include_has_options ? include_associations.keys : Array.wrap(include_associations)
<ide>
<ide> for association in associations
<del> records = case @record.class.reflect_on_association(association).macro
<add> records = case @serializable.class.reflect_on_association(association).macro
<ide> when :has_many, :has_and_belongs_to_many
<del> @record.send(association).to_a
<add> @serializable.send(association).to_a
<ide> when :has_one, :belongs_to
<del> @record.send(association)
<add> @serializable.send(association)
<ide> end
<ide>
<ide> unless records.nil?
<ide> def add_includes(&block)
<ide> end
<ide> end
<ide>
<del> def serializable_record
<del> record = {}
<del> serializable_names.each { |name| record[name] = @record.send(name) }
<add> def serializable_hash
<add> hash = super
<ide>
<ide> add_includes do |association, records, opts|
<del> record[association] =
<add> hash[association] =
<ide> if records.is_a?(Enumerable)
<del> records.collect { |r| self.class.new(r, opts).serializable_record }
<add> records.collect { |r| self.class.new(r, opts).serializable_hash }
<ide> else
<del> self.class.new(records, opts).serializable_record
<add> self.class.new(records, opts).serializable_hash
<ide> end
<ide> end
<ide>
<del> record
<del> end
<del>
<del> def serialize
<del> # overwrite to implement
<del> end
<del>
<del> def to_s(&block)
<del> serialize(&block)
<add> hash
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/serializers/json_serializer.rb
<del>require 'active_support/json'
<del>require 'active_model/naming'
<del>
<ide> module ActiveRecord #:nodoc:
<ide> module Serialization
<ide> extend ActiveSupport::Concern
<add> include ActiveModel::Serializers::JSON
<ide>
<del> included do
<del> cattr_accessor :include_root_in_json, :instance_writer => false
<add> class JSONSerializer < ActiveModel::Serializers::JSON::Serializer
<add> include Serialization::RecordSerializer
<ide> end
<ide>
<del> # Returns a JSON string representing the model. Some configuration is
<del> # available through +options+.
<del> #
<del> # The option <tt>ActiveRecord::Base.include_root_in_json</tt> controls the
<del> # top-level behavior of to_json. In a new Rails application, it is set to
<del> # <tt>true</tt> in initializers/new_rails_defaults.rb. When it is <tt>true</tt>,
<del> # to_json will emit a single root node named after the object's type. For example:
<del> #
<del> # konata = User.find(1)
<del> # ActiveRecord::Base.include_root_in_json = true
<del> # konata.to_json
<del> # # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
<del> # "created_at": "2006/08/01", "awesome": true} }
<del> #
<del> # ActiveRecord::Base.include_root_in_json = false
<del> # konata.to_json
<del> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<del> # "created_at": "2006/08/01", "awesome": true}
<del> #
<del> # The remainder of the examples in this section assume include_root_in_json is set to
<del> # <tt>false</tt>.
<del> #
<del> # Without any +options+, the returned JSON string will include all
<del> # the model's attributes. For example:
<del> #
<del> # konata = User.find(1)
<del> # konata.to_json
<del> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<del> # "created_at": "2006/08/01", "awesome": true}
<del> #
<del> # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
<del> # included, and work similar to the +attributes+ method. For example:
<del> #
<del> # konata.to_json(:only => [ :id, :name ])
<del> # # => {"id": 1, "name": "Konata Izumi"}
<del> #
<del> # konata.to_json(:except => [ :id, :created_at, :age ])
<del> # # => {"name": "Konata Izumi", "awesome": true}
<del> #
<del> # To include any methods on the model, use <tt>:methods</tt>.
<del> #
<del> # konata.to_json(:methods => :permalink)
<del> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<del> # "created_at": "2006/08/01", "awesome": true,
<del> # "permalink": "1-konata-izumi"}
<del> #
<del> # To include associations, use <tt>:include</tt>.
<del> #
<del> # konata.to_json(:include => :posts)
<del> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<del> # "created_at": "2006/08/01", "awesome": true,
<del> # "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
<del> # {"id": 2, author_id: 1, "title": "So I was thinking"}]}
<del> #
<del> # 2nd level and higher order associations work as well:
<del> #
<del> # konata.to_json(:include => { :posts => {
<del> # :include => { :comments => {
<del> # :only => :body } },
<del> # :only => :title } })
<del> # # => {"id": 1, "name": "Konata Izumi", "age": 16,
<del> # "created_at": "2006/08/01", "awesome": true,
<del> # "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
<del> # "title": "Welcome to the weblog"},
<del> # {"comments": [{"body": "Don't think too hard"}],
<del> # "title": "So I was thinking"}]}
<ide> def encode_json(encoder)
<del> hash = Serializer.new(self, encoder.options).serializable_record
<del> hash = { self.class.model_name.element => hash } if include_root_in_json
<del> ActiveSupport::JSON.encode(hash)
<del> end
<del>
<del> def as_json(options = nil) self end #:nodoc:
<del>
<del> def from_json(json)
<del> self.attributes = ActiveSupport::JSON.decode(json)
<del> self
<add> JSONSerializer.new(self, encoder.options).to_s
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/serializers/xml_serializer.rb
<ide> def from_xml(xml)
<ide> end
<ide> end
<ide>
<del> class XmlSerializer < ActiveRecord::Serialization::Serializer #:nodoc:
<add> class XmlSerializer < ActiveModel::Serializer #:nodoc:
<add> include Serialization::RecordSerializer
<add>
<ide> def builder
<ide> @builder ||= begin
<ide> require 'builder' unless defined? ::Builder
<ide> def builder
<ide> end
<ide>
<ide> def root
<del> root = (options[:root] || @record.class.to_s.underscore).to_s
<add> root = (options[:root] || @serializable.class.to_s.underscore).to_s
<ide> reformat_name(root)
<ide> end
<ide>
<ide> def reformat_name(name)
<ide> end
<ide>
<ide> def serializable_attributes
<del> serializable_attribute_names.collect { |name| Attribute.new(name, @record) }
<add> serializable_attribute_names.collect { |name| Attribute.new(name, @serializable) }
<ide> end
<ide>
<ide> def serializable_method_attributes
<ide> Array(options[:methods]).inject([]) do |method_attributes, name|
<del> method_attributes << MethodAttribute.new(name.to_s, @record) if @record.respond_to?(name.to_s)
<add> method_attributes << MethodAttribute.new(name.to_s, @serializable) if @serializable.respond_to?(name.to_s)
<ide> method_attributes
<ide> end
<ide> end
<ide> def add_associations(association, records, opts)
<ide> end
<ide> end
<ide> else
<del> if record = @record.send(association)
<add> if record = @serializable.send(association)
<ide> record.to_xml(opts.merge(:root => association))
<ide> end
<ide> end | 6 |
Python | Python | fix email addresses | 4957e5ed4ef51beb8687e64c4f9c5315602d86aa | <ide><path>numpy/core/tests/test_umath.py
<ide> import nose
<ide> from numpy import inf, nan, pi
<ide>
<add># Because of the way Python handles literals (e.g. (-0.0, 0.0) can give
<add># (-0.0, -0.0)). Use this for -0.0 instead.
<add>negzero = -0.0
<add>
<add>
<ide> class TestDivision(TestCase):
<ide> def test_division_int(self):
<ide> # int division should return the floor of the result, a la Python
<ide> class TestC99(object):
<ide>
<ide> def test_clog(self):
<ide> for p, v, e in [
<del> ((-0., 0.), (-inf, pi), 'divide'),
<del> ((+0., 0.), (-inf, 0.), 'XXX divide'), # fails on OSX?
<add> ((negzero, 0.0), (-inf, pi), 'divide'),
<add> ((0.0, 0.0), (-inf, 0.0), 'divide'), # fails on OSX?
<ide> ((1., inf), (inf, pi/2), ''),
<ide> ((1., nan), (nan, nan), 'invalid-optional'),
<ide> ((-inf, 1.), (inf, pi), ''),
<ide> def test_clog(self):
<ide> ((-inf, nan), (inf, nan), ''),
<ide> ((nan, 1.), (nan, nan), 'invalid-optional'),
<ide> ((nan, inf), (inf, nan), ''),
<del> ((+nan, nan), (nan, nan), 'XXX'), # raises 'invalid' on some platfs
<add> ((+nan, nan), (nan, nan), ''), # raises 'invalid' on some platfs
<ide> ]:
<ide> yield self._check, np.log, p, v, e
<ide>
<ide> def test_csqrt(self):
<ide> for p, v, e in [
<del> ((-0., 0.), (0.,0.), 'XXX'), # now (-0., 0.)
<add> ((negzero, 0.0), (0.0, 0.0), ''), # now (-0., 0.)
<ide> ((0., 0.), (0.,0.), ''),
<ide> ((1., inf), (inf,inf), 'XXX invalid'), # now (inf, nan)
<ide> ((nan, inf), (inf,inf), 'XXX'), # now (nan, nan)
<ide> def test_csqrt(self):
<ide>
<ide> def test_cacos(self):
<ide> for p, v, e in [
<del> ((0., 0.), (pi/2, -0.), 'XXX'), # now (-0., 0.)
<del> ((-0., 0.), (pi/2, -0.), ''),
<add> ((0., 0.), (pi/2, negzero), 'XXX'), # now (-0., 0.)
<add> ((negzero, 0.0), (pi/2, negzero), ''),
<ide> ((0., nan), (pi/2, nan), 'XXX'), # now (nan, nan)
<del> ((-0., nan), (pi/2, nan), 'XXX'), # now (nan, nan)
<add> ((negzero, nan), (pi/2, nan), ''), # now (nan, nan)
<ide> ((1., inf), (pi/2, -inf), 'XXX'), # now (nan, -inf)
<ide> ((1., nan), (nan, nan), 'invalid-optional'),
<ide> ((-inf, 1.), (pi, -inf), 'XXX'), # now (nan, -inf)
<ide> def test_cacos(self):
<ide> def test_cacosh(self):
<ide> for p, v, e in [
<ide> ((0., 0), (0, pi/2), ''),
<del> ((-0., 0), (0, pi/2), ''),
<add> ((negzero, 0), (0, pi/2), ''),
<ide> ((1., inf), (inf, pi/2), 'XXX'), # now: (nan, nan)
<ide> ((1., nan), (nan, nan), 'invalid-optional'),
<ide> ((-inf, 1.), (inf, pi), 'XXX'), # now: (inf, nan)
<ide><path>setup.py
<ide> def setup_package():
<ide> setup(
<ide> name = 'numpy',
<ide> maintainer = "NumPy Developers",
<del> maintainer_email = "numpy-discussion@lists.sourceforge.net",
<add> maintainer_email = "numpy-discussion@scipy.org",
<ide> description = DOCLINES[0],
<ide> long_description = "\n".join(DOCLINES[2:]),
<ide> url = "http://numpy.scipy.org",
<ide> download_url = "http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103",
<ide> license = 'BSD',
<ide> classifiers=filter(None, CLASSIFIERS.split('\n')),
<ide> author = "Travis E. Oliphant, et.al.",
<del> author_email = "oliphant@ee.byu.edu",
<add> author_email = "oliphant@enthought.com",
<ide> platforms = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"],
<ide> configuration=configuration )
<ide> finally: | 2 |
Mixed | Ruby | update linux requirements | 1882ae4f6e7bbfaf9d19e2e2dc87616ae43fef8d | <ide><path>Library/Homebrew/os/linux/kernel.rb
<ide> module Kernel
<ide>
<ide> sig { returns(Version) }
<ide> def minimum_version
<del> Version.new "2.6.32"
<add> Version.new "3.2"
<ide> end
<ide>
<ide> def below_minimum_version?
<ide><path>docs/Homebrew-on-Linux.md
<ide> If you're using an older distribution of Linux, installing your first package wi
<ide>
<ide> ## Requirements
<ide>
<del>- **GCC** 4.7.0 or newer
<del>- **Linux** 2.6.32 or newer
<add>- **Linux** 3.2 or newer
<ide> - **Glibc** 2.13 or newer
<ide> - **64-bit x86_64** CPU
<ide>
<ide> To install build tools, paste at a terminal prompt:
<ide> ```sh
<ide> sudo yum groupinstall 'Development Tools'
<ide> sudo yum install procps-ng curl file git
<del> sudo yum install libxcrypt-compat # needed by Fedora 30 and up
<ide> ```
<ide>
<ide> ### ARM | 2 |
Ruby | Ruby | remove bad doctor check | 86daf9070037b8d91739871f5dd73eed6d05e0e7 | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_stray_developer_directory
<ide> end
<ide> end
<ide>
<del>def check_cc
<del> if !MacOS::CLT.installed? && MacOS::Xcode.version < "4.3"
<del> 'No compiler found in /usr/bin!'
<del> end
<del>end
<del>
<ide> def check_standard_compilers
<ide> return if check_xcode_clt # only check if Xcode is up to date
<ide> compiler_status = MacOS.compilers_standard? | 1 |
Python | Python | remove unused method | 4107fcf3fd39278ac251c3e2697013fae2c3d8dd | <ide><path>glances/outputs/glances_bottle.py
<ide> def _favicon(self):
<ide> # Return the static file
<ide> return static_file('favicon.ico', root=self.STATIC_PATH)
<ide>
<del> def enable_cors(self):
<del> """Enable CORS"""
<del> response.headers['Access-Control-Allow-Origin'] = '*'
<del> response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
<del> response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
<del>
<ide> def _api_plugins(self):
<ide> """
<ide> Glances API RESTFul implementation | 1 |
Mixed | Javascript | add support for typedarray to getunpackedsettings | ad0a01caedbd792a7a62080439bf44ec27146798 | <ide><path>doc/api/http2.md
<ide> console.log(packed.toString('base64'));
<ide> added: v8.4.0
<ide> -->
<ide>
<del>* `buf` {Buffer|Uint8Array} The packed settings.
<add>* `buf` {Buffer|TypedArray} The packed settings.
<ide> * Returns: {HTTP/2 Settings Object}
<ide>
<ide> Returns a [HTTP/2 Settings Object][] containing the deserialized settings from
<ide><path>lib/internal/buffer.js
<ide> module.exports = {
<ide> addBufferPrototypeMethods,
<ide> markAsUntransferable,
<ide> createUnsafeBuffer,
<add> readUInt16BE,
<add> readUInt32BE,
<ide> reconnectZeroFillToggle
<ide> };
<ide><path>lib/internal/http2/core.js
<ide> const {
<ide> ObjectDefineProperty,
<ide> ObjectPrototypeHasOwnProperty,
<ide> Promise,
<add> ReflectApply,
<ide> ReflectGetPrototypeOf,
<ide> Set,
<ide> Symbol,
<ide> const assert = require('assert');
<ide> const EventEmitter = require('events');
<ide> const fs = require('fs');
<ide> const http = require('http');
<add>const { readUInt16BE, readUInt32BE } = require('internal/buffer');
<ide> const net = require('net');
<ide> const { Duplex } = require('stream');
<ide> const tls = require('tls');
<ide> function getPackedSettings(settings) {
<ide> }
<ide>
<ide> function getUnpackedSettings(buf, options = {}) {
<del> if (!isArrayBufferView(buf)) {
<add> if (!isArrayBufferView(buf) || buf.length === undefined) {
<ide> throw new ERR_INVALID_ARG_TYPE('buf',
<del> ['Buffer', 'TypedArray', 'DataView'], buf);
<add> ['Buffer', 'TypedArray'], buf);
<ide> }
<ide> if (buf.length % 6 !== 0)
<ide> throw new ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH();
<ide> const settings = {};
<ide> let offset = 0;
<ide> while (offset < buf.length) {
<del> const id = buf.readUInt16BE(offset);
<add> const id = ReflectApply(readUInt16BE, buf, [offset]);
<ide> offset += 2;
<del> const value = buf.readUInt32BE(offset);
<add> const value = ReflectApply(readUInt32BE, buf, [offset]);
<ide> switch (id) {
<ide> case NGHTTP2_SETTINGS_HEADER_TABLE_SIZE:
<ide> settings.headerTableSize = value;
<ide><path>test/parallel/test-http2-getpackedsettings.js
<ide> http2.getPackedSettings({ enablePush: false });
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> name: 'TypeError',
<ide> message:
<del> 'The "buf" argument must be an instance of Buffer, TypedArray, or ' +
<del> `DataView.${common.invalidArgTypeHelper(input)}`
<add> 'The "buf" argument must be an instance of Buffer or TypedArray.' +
<add> common.invalidArgTypeHelper(input)
<ide> });
<ide> });
<ide>
<ide> http2.getPackedSettings({ enablePush: false });
<ide> assert.strictEqual(settings.enableConnectProtocol, false);
<ide> }
<ide>
<add>{
<add> const packed = new Uint16Array([
<add> 0x00, 0x01, 0x00, 0x00, 0x00, 0x64,
<add> 0x00, 0x03, 0x00, 0x00, 0x00, 0xc8,
<add> 0x00, 0x05, 0x00, 0x00, 0x4e, 0x20,
<add> 0x00, 0x04, 0x00, 0x00, 0x00, 0x64,
<add> 0x00, 0x06, 0x00, 0x00, 0x00, 0x64,
<add> 0x00, 0x02, 0x00, 0x00, 0x00, 0x01,
<add> 0x00, 0x08, 0x00, 0x00, 0x00, 0x00]);
<add>
<add> assert.throws(() => {
<add> http2.getUnpackedSettings(packed.slice(5));
<add> }, {
<add> code: 'ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH',
<add> name: 'RangeError',
<add> message: 'Packed settings length must be a multiple of six'
<add> });
<add>
<add> const settings = http2.getUnpackedSettings(packed);
<add>
<add> assert(settings);
<add> assert.strictEqual(settings.headerTableSize, 100);
<add> assert.strictEqual(settings.initialWindowSize, 100);
<add> assert.strictEqual(settings.maxFrameSize, 20000);
<add> assert.strictEqual(settings.maxConcurrentStreams, 200);
<add> assert.strictEqual(settings.maxHeaderListSize, 100);
<add> assert.strictEqual(settings.maxHeaderSize, 100);
<add> assert.strictEqual(settings.enablePush, true);
<add> assert.strictEqual(settings.enableConnectProtocol, false);
<add>}
<add>
<add>{
<add> const packed = new DataView(Buffer.from([
<add> 0x00, 0x01, 0x00, 0x00, 0x00, 0x64,
<add> 0x00, 0x03, 0x00, 0x00, 0x00, 0xc8,
<add> 0x00, 0x05, 0x00, 0x00, 0x4e, 0x20,
<add> 0x00, 0x04, 0x00, 0x00, 0x00, 0x64,
<add> 0x00, 0x06, 0x00, 0x00, 0x00, 0x64,
<add> 0x00, 0x02, 0x00, 0x00, 0x00, 0x01,
<add> 0x00, 0x08, 0x00, 0x00, 0x00, 0x00]).buffer);
<add>
<add> assert.throws(() => {
<add> http2.getUnpackedSettings(packed);
<add> }, {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError',
<add> message:
<add> 'The "buf" argument must be an instance of Buffer or TypedArray.' +
<add> common.invalidArgTypeHelper(packed)
<add> });
<add>}
<add>
<ide> {
<ide> const packed = Buffer.from([
<ide> 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, | 4 |
PHP | PHP | fix more tests | ee9b499de4454a33dac076d6bdcee54c9fb95872 | <ide><path>tests/TestCase/Command/HelpCommandTest.php
<ide> public function testMainAsXml()
<ide> $find = '<shell name="sample" call_as="sample" provider="TestApp\Shell\SampleShell" help="sample -h"';
<ide> $this->assertOutputContains($find);
<ide>
<del> $find = '<shell name="orm_cache" call_as="orm_cache" provider="Cake\Shell\OrmCacheShell" help="orm_cache -h"';
<add> $find = '<shell name="schema_cache" call_as="schema_cache" provider="Cake\Shell\SchemaCacheShell" help="schema_cache -h"';
<ide> $this->assertOutputContains($find);
<ide>
<ide> $find = '<shell name="test_plugin.sample" call_as="test_plugin.sample" provider="TestPlugin\Shell\SampleShell" help="test_plugin.sample -h"';
<ide><path>tests/TestCase/TestSuite/ConsoleIntegrationTestTraitTest.php
<ide> public function setUp()
<ide> public function testExecWithCommandRunner()
<ide> {
<ide> $this->useCommandRunner();
<del>
<del> $this->exec('routes');
<add> $this->exec('');
<ide>
<ide> $this->assertExitCode(Shell::CODE_SUCCESS);
<add> $this->assertOutputContains('Current Paths');
<ide> }
<ide>
<ide> /**
<ide> public function testExecWithCommandRunner()
<ide> */
<ide> public function testExec()
<ide> {
<del> $this->exec('');
<add> $this->exec('routes');
<ide>
<del> $this->assertOutputContains('Welcome to CakePHP');
<del> $this->assertExitCode(Shell::CODE_ERROR);
<add> $this->assertOutputContains('Route name');
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> }
<ide>
<ide> /** | 2 |
Text | Text | fix broken links in views doc | 453b7b03dd5ee43cd4e63d05258116fd9f005fb3 | <ide><path>docs/api-guide/views.md
<ide> The core of this functionality is the `api_view` decorator, which takes a list o
<ide> return Response({"message": "Hello, world!"})
<ide>
<ide>
<del>This view will use the default renderers, parsers, authentication classes etc specified in the [settings](settings).
<add>This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
<ide>
<ide> ## API policy decorators
<ide>
<del>To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
<add>To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
<ide>
<ide> from rest_framework.decorators import api_view, throttle_classes
<ide> from rest_framework.throttling import UserRateThrottle | 1 |
Javascript | Javascript | skip all failing tests | 3a90910e7ffe5ca80d6d36837801fb41eddacb09 | <ide><path>packages/ember-htmlbars/lib/hooks/get-root.js
<ide> function getKey(scope, key) {
<ide> }
<ide>
<ide> function getGlobal(name) {
<del> Ember.deprecate("Global lookup of " + name + " from a Handlebars template is deprecated");
<add> Ember.deprecate("Global lookup of " + name + " from a Handlebars template is deprecated.");
<ide>
<ide> // This stream should be memoized, but this path is deprecated and
<ide> // will be removed soon so it's not worth the trouble.
<ide><path>packages/ember-htmlbars/lib/keywords/input.js
<ide> export default {
<ide> var type = env.hooks.getValue(hash.type) || 'text';
<ide>
<ide> Ember.assert("{{input type='checkbox'}} does not support setting `value=someBooleanValue`;" +
<del> " you must use `checked=someBooleanValue` instead.", !(type === 'checked' && hash.hasOwnProperty('value')));
<add> " you must use `checked=someBooleanValue` instead.", !(type === 'checkbox' && hash.hasOwnProperty('value')));
<ide>
<ide> return { componentName: classification[type] };
<ide> },
<ide><path>packages/ember-htmlbars/tests/attr_nodes/data_test.js
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars-attribute-syntax')) {
<ide> equalInnerHTML(view.element, '<div data-name="mmun">Hi!</div>', "attribute is updated output");
<ide> });
<ide>
<del> QUnit.test("updates fail silently after an element is destroyed", function() {
<del>
<add> QUnit.skip("updates fail silently after an element is destroyed", function() {
<ide> var context = EmberObject.create({ name: 'erik' });
<ide> view = EmberView.create({
<ide> context: context,
<ide><path>packages/ember-htmlbars/tests/compat/make_bound_helper_test.js
<ide> QUnit.test("should update bound helpers in a subexpression when properties chang
<ide> equal(view.$('div[data-foo="not-thing"]').text(), 'notThing', "helper output is correct");
<ide> });
<ide>
<del>QUnit.test("should allow for computed properties with dependencies", function() {
<add>QUnit.skip("should allow for computed properties with dependencies", function() {
<ide> expectDeprecationInHTMLBars();
<ide>
<ide> helper('capitalizeName', function(value) {
<ide> QUnit.test("should allow for computed properties with dependencies", function()
<ide> equal(view.$().text(), 'WES', "helper output updated");
<ide> });
<ide>
<del>QUnit.test("bound helpers should support options", function() {
<add>QUnit.skip("bound helpers should support options", function() {
<ide> registerRepeatHelper();
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("bound helper should support this keyword", function() {
<ide> equal(view.$().text(), 'AB', "helper output is correct");
<ide> });
<ide>
<del>QUnit.test("bound helpers should support bound options", function() {
<add>QUnit.skip("bound helpers should support bound options", function() {
<ide> registerRepeatHelper();
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("bound helpers should support multiple bound properties", function()
<ide> equal(view.$().text(), 'WOOTYEAH', "helper correctly re-rendered after both bound helper properties changed");
<ide> });
<ide>
<del>QUnit.test("bound helpers should expose property names in options.data.properties", function() {
<add>QUnit.skip("bound helpers should expose property names in options.data.properties", function() {
<ide> expectDeprecationInHTMLBars();
<ide>
<ide> helper('echo', function() {
<ide> QUnit.test("bound helpers can be invoked with zero args", function() {
<ide> equal(view.$().text(), 'TROLOLOL and bork', "helper output is correct");
<ide> });
<ide>
<del>QUnit.test("bound helpers should not be invoked with blocks", function() {
<add>QUnit.skip("bound helpers should not be invoked with blocks", function() {
<ide> registerRepeatHelper();
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("bound helpers should not be invoked with blocks", function() {
<ide> }, /registerBoundHelper-generated helpers do not support use with Handlebars blocks/i);
<ide> });
<ide>
<del>QUnit.test("should observe dependent keys passed to registerBoundHelper", function() {
<add>QUnit.skip("should observe dependent keys passed to registerBoundHelper", function() {
<ide> try {
<ide> expectDeprecationInHTMLBars();
<ide>
<ide> QUnit.test("shouldn't treat quoted strings as bound paths", function() {
<ide> equal(helperCount, 5, "changing controller property with same name as quoted string doesn't re-render helper");
<ide> });
<ide>
<del>QUnit.test("bound helpers can handle nulls in array (with primitives) [DEPRECATED]", function() {
<add>QUnit.skip("bound helpers can handle nulls in array (with primitives) [DEPRECATED]", function() {
<ide> expectDeprecationInHTMLBars();
<ide>
<ide> helper('reverse', function(val) {
<ide> QUnit.test("bound helpers can handle nulls in array (with primitives) [DEPRECATE
<ide> equal(view.$().text(), '0|NOPE |NOPE false|NOPE OMG|GMO blorg|grolb 0|NOPE |NOPE false|NOPE OMG|GMO blorg|grolb ', "helper output is still correct");
<ide> });
<ide>
<del>QUnit.test("bound helpers can handle nulls in array (with objects)", function() {
<add>QUnit.skip("bound helpers can handle nulls in array (with objects)", function() {
<ide> expectDeprecationInHTMLBars();
<ide>
<ide> helper('print-foo', function(val) {
<ide> QUnit.test("bound helpers can handle nulls in array (with objects)", function()
<ide> equal(view.$().text(), '|NOPE 5|5 6|6 |NOPE 5|5 6|6 ', "helper output is correct");
<ide> });
<ide>
<del>QUnit.test("bound helpers can handle `this` keyword when it's a non-object", function() {
<add>QUnit.skip("bound helpers can handle `this` keyword when it's a non-object", function() {
<ide> expectDeprecationInHTMLBars();
<ide>
<ide> helper("shout", function(value) {
<ide><path>packages/ember-htmlbars/tests/helpers/bind_attr_test.js
<ide> QUnit.test("should be able to bind classes to globals with {{bind-attr class}}",
<ide> ok(view.$('img').hasClass('is-open'), "sets classname to the dasherized value of the global property");
<ide> });
<ide>
<del>QUnit.test("should be able to bind-attr to 'this' in an {{#each}} block", function() {
<del>
<add>QUnit.skip("should be able to bind-attr to 'this' in an {{#each}} block", function() {
<ide> ignoreDeprecation(function() {
<ide> view = EmberView.create({
<ide> template: compile('{{#each view.images}}<img {{bind-attr src=this}}>{{/each}}'),
<ide> QUnit.test("should be able to bind-attr to 'this' in an {{#each}} block", functi
<ide> ok(/three\.gif$/.test(images[2].src));
<ide> });
<ide>
<del>QUnit.test("should be able to bind classes to 'this' in an {{#each}} block with {{bind-attr class}}", function() {
<add>QUnit.skip("should be able to bind classes to 'this' in an {{#each}} block with {{bind-attr class}}", function() {
<ide> ignoreDeprecation(function() {
<ide> view = EmberView.create({
<ide> template: compile('{{#each view.items}}<li {{bind-attr class="this"}}>Item</li>{{/each}}'),
<ide><path>packages/ember-htmlbars/tests/helpers/collection_test.js
<ide> QUnit.module("collection helper", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("Collection views that specify an example view class have their children be of that class", function() {
<add>QUnit.skip("Collection views that specify an example view class have their children be of that class", function() {
<ide> var ExampleViewCollection = CollectionView.extend({
<ide> itemViewClass: EmberView.extend({
<ide> isCustom: true
<ide> QUnit.test("Collection views that specify an example view class have their child
<ide> ok(firstGrandchild(view).isCustom, "uses the example view class");
<ide> });
<ide>
<del>QUnit.test("itemViewClass works in the #collection helper with a global (DEPRECATED)", function() {
<add>QUnit.skip("itemViewClass works in the #collection helper with a global (DEPRECATED)", function() {
<ide> TemplateTests.ExampleItemView = EmberView.extend({
<ide> isAlsoCustom: true
<ide> });
<ide> QUnit.test("itemViewClass works in the #collection helper with a global (DEPRECA
<ide> ok(firstGrandchild(view).isAlsoCustom, "uses the example view class specified in the #collection helper");
<ide> });
<ide>
<del>QUnit.test("itemViewClass works in the #collection helper with a property", function() {
<add>QUnit.skip("itemViewClass works in the #collection helper with a property", function() {
<ide> var ExampleItemView = EmberView.extend({
<ide> isAlsoCustom: true
<ide> });
<ide> QUnit.test("itemViewClass works in the #collection helper with a property", func
<ide> ok(firstGrandchild(view).isAlsoCustom, "uses the example view class specified in the #collection helper");
<ide> });
<ide>
<del>QUnit.test("itemViewClass works in the #collection via container", function() {
<add>QUnit.skip("itemViewClass works in the #collection via container", function() {
<ide> registry.register('view:example-item', EmberView.extend({
<ide> isAlsoCustom: true
<ide> }));
<ide> QUnit.test("itemViewClass works in the #collection via container", function() {
<ide> });
<ide>
<ide>
<del>QUnit.test("passing a block to the collection helper sets it as the template for example views", function() {
<add>QUnit.skip("passing a block to the collection helper sets it as the template for example views", function() {
<ide> var CollectionTestView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A(['foo', 'bar', 'baz'])
<ide> QUnit.test("passing a block to the collection helper sets it as the template for
<ide> equal(view.$('label').length, 3, 'one label element is created for each content item');
<ide> });
<ide>
<del>QUnit.test("collection helper should try to use container to resolve view", function() {
<add>QUnit.skip("collection helper should try to use container to resolve view", function() {
<ide> var registry = new Registry();
<ide> var container = registry.container();
<ide>
<ide> QUnit.test("collection helper should try to use container to resolve view", func
<ide> equal(view.$('label').length, 3, 'one label element is created for each content item');
<ide> });
<ide>
<del>QUnit.test("collection helper should accept relative paths", function() {
<add>QUnit.skip("collection helper should accept relative paths", function() {
<ide> view = EmberView.create({
<ide> template: compile('{{#collection view.collection}} <label></label> {{/collection}}'),
<ide> collection: CollectionView.extend({
<ide> QUnit.test("collection helper should accept relative paths", function() {
<ide> equal(view.$('label').length, 3, 'one label element is created for each content item');
<ide> });
<ide>
<del>QUnit.test("empty views should be removed when content is added to the collection (regression, ht: msofaer)", function() {
<add>QUnit.skip("empty views should be removed when content is added to the collection (regression, ht: msofaer)", function() {
<ide> var EmptyView = EmberView.extend({
<ide> template : compile("<td>No Rows Yet</td>")
<ide> });
<ide> QUnit.test("empty views should be removed when content is added to the collectio
<ide> equal(view.$('tr:nth-child(1) td').text(), 'Go Away, Placeholder Row!', 'The content is the updated data.');
<ide> });
<ide>
<del>QUnit.test("should be able to specify which class should be used for the empty view", function() {
<add>QUnit.skip("should be able to specify which class should be used for the empty view", function() {
<ide> var App;
<ide>
<ide> run(function() {
<ide> QUnit.test("should be able to specify which class should be used for the empty v
<ide> runDestroy(App);
<ide> });
<ide>
<del>QUnit.test("if no content is passed, and no 'else' is specified, nothing is rendered", function() {
<add>QUnit.skip("if no content is passed, and no 'else' is specified, nothing is rendered", function() {
<ide> var CollectionTestView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A()
<ide> QUnit.test("if no content is passed, and no 'else' is specified, nothing is rend
<ide> equal(view.$('li').length, 0, 'if no "else" is specified, nothing is rendered');
<ide> });
<ide>
<del>QUnit.test("if no content is passed, and 'else' is specified, the else block is rendered", function() {
<add>QUnit.skip("if no content is passed, and 'else' is specified, the else block is rendered", function() {
<ide> var CollectionTestView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A()
<ide> QUnit.test("if no content is passed, and 'else' is specified, the else block is
<ide> equal(view.$('li:has(del)').length, 1, 'the else block is rendered');
<ide> });
<ide>
<del>QUnit.test("a block passed to a collection helper defaults to the content property of the context", function() {
<add>QUnit.skip("a block passed to a collection helper defaults to the content property of the context", function() {
<ide> var CollectionTestView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A(['foo', 'bar', 'baz'])
<ide> QUnit.test("a block passed to a collection helper defaults to the content proper
<ide> equal(view.$('li:nth-child(3) label').text(), 'baz');
<ide> });
<ide>
<del>QUnit.test("a block passed to a collection helper defaults to the view", function() {
<add>QUnit.skip("a block passed to a collection helper defaults to the view", function() {
<ide> var CollectionTestView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A(['foo', 'bar', 'baz'])
<ide> QUnit.test("a block passed to a collection helper defaults to the view", functio
<ide> equal(view.$('label').length, 0, "all list item views should be removed from DOM");
<ide> });
<ide>
<del>QUnit.test("should include an id attribute if id is set in the options hash", function() {
<add>QUnit.skip("should include an id attribute if id is set in the options hash", function() {
<ide> var CollectionTestView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A(['foo', 'bar', 'baz'])
<ide> QUnit.test("should include an id attribute if id is set in the options hash", fu
<ide> equal(view.$('ul#baz').length, 1, "adds an id attribute");
<ide> });
<ide>
<del>QUnit.test("should give its item views the class specified by itemClass", function() {
<add>QUnit.skip("should give its item views the class specified by itemClass", function() {
<ide> var ItemClassTestCollectionView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A(['foo', 'bar', 'baz'])
<ide> QUnit.test("should give its item views the class specified by itemClass", functi
<ide> equal(view.$('ul li.baz').length, 3, "adds class attribute");
<ide> });
<ide>
<del>QUnit.test("should give its item views the class specified by itemClass", function() {
<add>QUnit.skip("should give its item views the class specified by itemClass", function() {
<ide> var ItemClassBindingTestCollectionView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A([EmberObject.create({ isBaz: false }), EmberObject.create({ isBaz: true }), EmberObject.create({ isBaz: true })])
<ide> QUnit.test("should give its item views the class specified by itemClass", functi
<ide> // to introduce a new keyword that could be used from within `itemClassBinding`. For instance, `itemClassBinding="item.isBaz"`.
<ide> });
<ide>
<del>QUnit.test("should give its item views the property specified by itemProperty", function() {
<add>QUnit.skip("should give its item views the property specified by itemProperty", function() {
<ide> var ItemPropertyBindingTestItemView = EmberView.extend({
<ide> tagName: 'li'
<ide> });
<ide> QUnit.test("should give its item views the property specified by itemProperty",
<ide> equal(view.$('ul li:first').text(), "yobaz", "change property of sub view");
<ide> });
<ide>
<del>QUnit.test("should unsubscribe stream bindings", function() {
<add>QUnit.skip("should unsubscribe stream bindings", function() {
<ide> view = EmberView.create({
<ide> baz: "baz",
<ide> content: A([EmberObject.create(), EmberObject.create(), EmberObject.create()]),
<ide> function countSubscribers(stream) {
<ide> return count;
<ide> }
<ide>
<del>QUnit.test("should work inside a bound {{#if}}", function() {
<add>QUnit.skip("should work inside a bound {{#if}}", function() {
<ide> var testData = A([EmberObject.create({ isBaz: false }), EmberObject.create({ isBaz: true }), EmberObject.create({ isBaz: true })]);
<ide> var IfTestCollectionView = CollectionView.extend({
<ide> tagName: 'ul',
<ide> QUnit.test("should work inside a bound {{#if}}", function() {
<ide> equal(view.$('ul li').length, 3, "collection renders when conditional changes to true");
<ide> });
<ide>
<del>QUnit.test("should pass content as context when using {{#each}} helper [DEPRECATED]", function() {
<add>QUnit.skip("should pass content as context when using {{#each}} helper [DEPRECATED]", function() {
<ide> view = EmberView.create({
<ide> template: compile('{{#each view.releases}}Mac OS X {{version}}: {{name}} {{/each}}'),
<ide>
<ide> QUnit.test("should pass content as context when using {{#each}} helper [DEPRECAT
<ide> equal(view.$().text(), "Mac OS X 10.7: Lion Mac OS X 10.6: Snow Leopard Mac OS X 10.5: Leopard ", "prints each item in sequence");
<ide> });
<ide>
<del>QUnit.test("should re-render when the content object changes", function() {
<add>QUnit.skip("should re-render when the content object changes", function() {
<ide> var RerenderTest = CollectionView.extend({
<ide> tagName: 'ul',
<ide> content: A()
<ide> QUnit.test("should re-render when the content object changes", function() {
<ide> equal(trim(view.$('li:eq(0)').text()), "ramalamadingdong");
<ide> });
<ide>
<del>QUnit.test("select tagName on collection helper automatically sets child tagName to option", function() {
<add>QUnit.skip("select tagName on collection helper automatically sets child tagName to option", function() {
<ide> var RerenderTest = CollectionView.extend({
<ide> content: A(['foo'])
<ide> });
<ide> QUnit.test("select tagName on collection helper automatically sets child tagName
<ide> equal(view.$('option').length, 1, "renders the correct child tag name");
<ide> });
<ide>
<del>QUnit.test("tagName works in the #collection helper", function() {
<add>QUnit.skip("tagName works in the #collection helper", function() {
<ide> var RerenderTest = CollectionView.extend({
<ide> content: A(['foo', 'bar'])
<ide> });
<ide> QUnit.test("tagName works in the #collection helper", function() {
<ide> equal(trim(view.$('li:eq(0)').text()), "bing");
<ide> });
<ide>
<del>QUnit.test("should render nested collections", function() {
<add>QUnit.skip("should render nested collections", function() {
<ide> var registry = new Registry();
<ide> var container = registry.container();
<ide> registry.register('view:inner-list', CollectionView.extend({
<ide> QUnit.test("should render nested collections", function() {
<ide>
<ide> });
<ide>
<del>QUnit.test("should render multiple, bound nested collections (#68)", function() {
<add>QUnit.skip("should render multiple, bound nested collections (#68)", function() {
<ide> var view;
<ide>
<ide> run(function() {
<ide> QUnit.test("should render multiple, bound nested collections (#68)", function()
<ide> runDestroy(view);
<ide> });
<ide>
<del>QUnit.test("should allow view objects to be swapped out without throwing an error (#78)", function() {
<add>QUnit.skip("should allow view objects to be swapped out without throwing an error (#78)", function() {
<ide> var view, dataset, secondDataset;
<ide>
<ide> run(function() {
<ide> QUnit.test("should allow view objects to be swapped out without throwing an erro
<ide> runDestroy(view);
<ide> });
<ide>
<del>QUnit.test("context should be content", function() {
<add>QUnit.skip("context should be content", function() {
<ide> var view;
<ide>
<ide> registry = new Registry();
<ide><path>packages/ember-htmlbars/tests/helpers/component_test.js
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars-component-helper')) {
<ide> equal(view.$().text(), 'yummy Loisaida arepas!', 'component was updated and re-rendered');
<ide> });
<ide>
<del> QUnit.test("component helper with actions", function() {
<add> QUnit.skip("component helper with actions", function() {
<ide> registry.register('template:components/foo-bar', compile('yippie! {{yield}}'));
<ide> registry.register('component:foo-bar', Ember.Component.extend({
<ide> classNames: 'foo-bar',
<ide><path>packages/ember-htmlbars/tests/helpers/each_test.js
<ide> import { runAppend, runDestroy } from "ember-runtime/tests/utils";
<ide> import compile from "ember-template-compiler/system/compile";
<ide> import { deprecation as eachDeprecation } from "ember-htmlbars/helpers/each";
<ide>
<add>
<ide> var people, view, registry, container;
<ide> var template, templateMyView, MyView, MyEmptyView, templateMyEmptyView;
<ide>
<ide> QUnit.test("it works inside a table element", function() {
<ide> runDestroy(tableView);
<ide> });
<ide>
<del>QUnit.test("it supports itemController", function() {
<add>QUnit.skip("it supports itemController", function() {
<ide> var Controller = EmberController.extend({
<ide> controllerName: computed(function() {
<ide> return "controller:"+this.get('model.name');
<ide> QUnit.test("it supports itemController", function() {
<ide> strictEqual(view._childViews[0]._arrayController.get('target'), parentController, "the target property of the child controllers are set correctly");
<ide> });
<ide>
<del>QUnit.test("itemController specified in template gets a parentController property", function() {
<add>QUnit.skip("itemController specified in template gets a parentController property", function() {
<ide> // using an ObjectController for this test to verify that parentController does accidentally get set
<ide> // on the proxied model.
<ide> var Controller = ObjectController.extend({
<ide> QUnit.test("itemController specified in template gets a parentController propert
<ide> equal(view.$().text(), "controller:Steve Holt of Yappcontroller:Annabelle of Yapp");
<ide> });
<ide>
<del>QUnit.test("itemController specified in ArrayController gets a parentController property", function() {
<add>QUnit.skip("itemController specified in ArrayController gets a parentController property", function() {
<ide> var PersonController = ObjectController.extend({
<ide> controllerName: computed(function() {
<ide> return "controller:" + get(this, 'model.name') + ' of ' + get(this, 'parentController.company');
<ide> QUnit.test("itemController specified in ArrayController gets a parentController
<ide> equal(view.$().text(), "controller:Steve Holt of Yappcontroller:Annabelle of Yapp");
<ide> });
<ide>
<del>QUnit.test("itemController's parentController property, when the ArrayController has a parentController", function() {
<add>QUnit.skip("itemController's parentController property, when the ArrayController has a parentController", function() {
<ide> var PersonController = ObjectController.extend({
<ide> controllerName: computed(function() {
<ide> return "controller:" + get(this, 'model.name') + ' of ' + get(this, 'parentController.company');
<ide> QUnit.test("itemController's parentController property, when the ArrayController
<ide> equal(view.$().text(), "controller:Steve Holt of Yappcontroller:Annabelle of Yapp");
<ide> });
<ide>
<del>QUnit.test("it supports itemController when using a custom keyword", function() {
<add>QUnit.skip("it supports itemController when using a custom keyword", function() {
<ide> var Controller = EmberController.extend({
<ide> controllerName: computed(function() {
<ide> return "controller:"+this.get('model.name');
<ide> QUnit.test("it supports itemController when using a custom keyword", function()
<ide> equal(view.$().text(), "controller:Steve Holtcontroller:Annabelle");
<ide> });
<ide>
<del>QUnit.test("it supports {{itemView=}}", function() {
<add>QUnit.skip("it supports {{itemView=}}", function() {
<ide> var itemView = EmberView.extend({
<ide> template: templateFor('itemView:{{name}}')
<ide> });
<ide> QUnit.test("it supports {{itemView=}}", function() {
<ide> });
<ide>
<ide>
<del>QUnit.test("it defers all normalization of itemView names to the resolver", function() {
<add>QUnit.skip("it defers all normalization of itemView names to the resolver", function() {
<ide> var itemView = EmberView.extend({
<ide> template: templateFor('itemView:{{name}}')
<ide> });
<ide> QUnit.test("it defers all normalization of itemView names to the resolver", func
<ide>
<ide> });
<ide>
<del>QUnit.test("it supports {{itemViewClass=}} with global (DEPRECATED)", function() {
<add>QUnit.skip("it supports {{itemViewClass=}} with global (DEPRECATED)", function() {
<ide> runDestroy(view);
<ide> view = EmberView.create({
<ide> template: templateFor('{{each view.people itemViewClass=MyView}}'),
<ide> QUnit.test("it supports {{itemViewClass=}} with global (DEPRECATED)", function()
<ide> assertText(view, "Steve HoltAnnabelle");
<ide> });
<ide>
<del>QUnit.test("it supports {{itemViewClass=}} via container", function() {
<add>QUnit.skip("it supports {{itemViewClass=}} via container", function() {
<ide> runDestroy(view);
<ide> view = EmberView.create({
<ide> container: {
<ide> QUnit.test("it supports {{itemViewClass=}} via container", function() {
<ide> assertText(view, "Steve HoltAnnabelle");
<ide> });
<ide>
<del>QUnit.test("it supports {{itemViewClass=}} with tagName (DEPRECATED)", function() {
<add>QUnit.skip("it supports {{itemViewClass=}} with tagName (DEPRECATED)", function() {
<ide> runDestroy(view);
<ide> view = EmberView.create({
<ide> template: templateFor('{{each view.people itemViewClass=MyView tagName="ul"}}'),
<ide> QUnit.test("it supports {{itemViewClass=}} with tagName (DEPRECATED)", function(
<ide> equal(view.$('ul li').text(), 'Steve HoltAnnabelle');
<ide> });
<ide>
<del>QUnit.test("it supports {{itemViewClass=}} with in format", function() {
<del>
<add>QUnit.skip("it supports {{itemViewClass=}} with in format", function() {
<ide> MyView = EmberView.extend({
<ide> template: templateFor("{{person.name}}")
<ide> });
<ide> QUnit.test("it supports {{itemViewClass=}} with in format", function() {
<ide>
<ide> });
<ide>
<del>QUnit.test("it supports {{emptyView=}}", function() {
<add>QUnit.skip("it supports {{emptyView=}}", function() {
<ide> var emptyView = EmberView.extend({
<ide> template: templateFor('emptyView:sad panda')
<ide> });
<ide> QUnit.test("it supports {{emptyView=}}", function() {
<ide> assertText(view, "emptyView:sad panda");
<ide> });
<ide>
<del>QUnit.test("it defers all normalization of emptyView names to the resolver", function() {
<add>QUnit.skip("it defers all normalization of emptyView names to the resolver", function() {
<ide> var emptyView = EmberView.extend({
<ide> template: templateFor('emptyView:sad panda')
<ide> });
<ide> QUnit.test("it defers all normalization of emptyView names to the resolver", fun
<ide> runAppend(view);
<ide> });
<ide>
<del>QUnit.test("it supports {{emptyViewClass=}} with global (DEPRECATED)", function() {
<add>QUnit.skip("it supports {{emptyViewClass=}} with global (DEPRECATED)", function() {
<ide> runDestroy(view);
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("it supports {{emptyViewClass=}} with global (DEPRECATED)", function(
<ide> assertText(view, "I'm empty");
<ide> });
<ide>
<del>QUnit.test("it supports {{emptyViewClass=}} via container", function() {
<add>QUnit.skip("it supports {{emptyViewClass=}} via container", function() {
<ide> runDestroy(view);
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("it supports {{emptyViewClass=}} via container", function() {
<ide> assertText(view, "I'm empty");
<ide> });
<ide>
<del>QUnit.test("it supports {{emptyViewClass=}} with tagName (DEPRECATED)", function() {
<add>QUnit.skip("it supports {{emptyViewClass=}} with tagName (DEPRECATED)", function() {
<ide> runDestroy(view);
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("it supports {{emptyViewClass=}} with tagName (DEPRECATED)", function
<ide> equal(view.$('b').text(), "I'm empty");
<ide> });
<ide>
<del>QUnit.test("it supports {{emptyViewClass=}} with in format", function() {
<add>QUnit.skip("it supports {{emptyViewClass=}} with in format", function() {
<ide> runDestroy(view);
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("it supports {{emptyViewClass=}} with in format", function() {
<ide> assertText(view, "I'm empty");
<ide> });
<ide>
<del>QUnit.test("it supports {{else}}", function() {
<add>QUnit.skip("it supports {{else}}", function() {
<ide> runDestroy(view);
<ide> view = EmberView.create({
<ide> template: templateFor("{{#each view.items}}{{this}}{{else}}Nothing{{/each}}"),
<ide> QUnit.test("it supports {{else}}", function() {
<ide> assertHTML(view, "Nothing");
<ide> });
<ide>
<del>QUnit.test("it works with the controller keyword", function() {
<add>QUnit.skip("it works with the controller keyword", function() {
<ide> runDestroy(view);
<ide>
<ide> var controller = ArrayController.create({
<ide> QUnit.test("it works with the controller keyword", function() {
<ide> equal(view.$().text(), "foobarbaz");
<ide> });
<ide>
<del>QUnit.test("views inside #each preserve the new context [DEPRECATED]", function() {
<add>QUnit.skip("views inside #each preserve the new context [DEPRECATED]", function() {
<ide> runDestroy(view);
<ide>
<ide> var controller = A([{ name: "Adam" }, { name: "Steve" }]);
<ide> QUnit.test("views inside #each preserve the new context [DEPRECATED]", function(
<ide> equal(view.$().text(), "AdamSteve");
<ide> });
<ide>
<del>QUnit.test("single-arg each defaults to current context [DEPRECATED]", function() {
<add>QUnit.skip("single-arg each defaults to current context [DEPRECATED]", function() {
<ide> runDestroy(view);
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("single-arg each defaults to current context [DEPRECATED]", function(
<ide> equal(view.$().text(), "AdamSteve");
<ide> });
<ide>
<del>QUnit.test("single-arg each will iterate over controller if present [DEPRECATED]", function() {
<add>QUnit.skip("single-arg each will iterate over controller if present [DEPRECATED]", function() {
<ide> runDestroy(view);
<ide>
<ide> view = EmberView.create({
<ide> function testEachWithItem(moduleName, useBlockParams) {
<ide> });
<ide>
<ide> if (!useBlockParams) {
<del> QUnit.test("views inside #each preserve the new context [DEPRECATED]", function() {
<add> QUnit.skip("views inside #each preserve the new context [DEPRECATED]", function() {
<ide> var controller = A([{ name: "Adam" }, { name: "Steve" }]);
<ide>
<ide> view = EmberView.create({
<ide> function testEachWithItem(moduleName, useBlockParams) {
<ide> });
<ide> }
<ide>
<del> QUnit.test("controller is assignable inside an #each", function() {
<add> QUnit.skip("controller is assignable inside an #each", function() {
<ide> var controller = ArrayController.create({
<ide> model: A([{ name: "Adam" }, { name: "Steve" }])
<ide> });
<ide> function testEachWithItem(moduleName, useBlockParams) {
<ide> ok(true, "No assertion from valid template");
<ide> });
<ide>
<del> QUnit.test("itemController specified in template with name binding does not change context", function() {
<add> QUnit.skip("itemController specified in template with name binding does not change context", function() {
<ide> var Controller = EmberController.extend({
<ide> controllerName: computed(function() {
<ide> return "controller:"+this.get('model.name');
<ide> function testEachWithItem(moduleName, useBlockParams) {
<ide> });
<ide>
<ide> if (!useBlockParams) {
<del> QUnit.test("{{each}} without arguments [DEPRECATED]", function() {
<add> QUnit.skip("{{each}} without arguments [DEPRECATED]", function() {
<ide> expect(2);
<ide>
<ide> view = EmberView.create({
<ide><path>packages/ember-htmlbars/tests/helpers/if_unless_test.js
<ide> QUnit.test("The `unbound if` helper should work when its inverse is not present"
<ide> equal(view.$().text(), '');
<ide> });
<ide>
<del>QUnit.test('should not rerender if truthiness does not change', function() {
<add>QUnit.skip('should not rerender if truthiness does not change', function() {
<ide> view = EmberView.create({
<ide> template: compile('<h1 id="first">{{#if view.shouldDisplay}}{{view view.InnerViewClass}}{{/if}}</h1>'),
<ide>
<ide><path>packages/ember-htmlbars/tests/helpers/input_test.js
<ide> var controller, registry, container;
<ide> function commonSetup() {
<ide> registry = new Registry();
<ide> registry.register('component:-text-field', TextField);
<del> registry.register('component:-check-box', Checkbox);
<add> registry.register('component:-checkbox', Checkbox);
<ide> registry.register('component-lookup:main', ComponentLookup);
<ide> container = registry.container();
<ide> }
<ide><path>packages/ember-htmlbars/tests/helpers/new_each_helper_test.js
<del>/*jshint newcap:false*/
<del>import Ember from "ember-metal/core"; // Ember.lookup;
<del>import EmberObject from "ember-runtime/system/object";
<del>import run from "ember-metal/run_loop";
<del>import EmberView from "ember-views/views/view";
<del>import _MetamorphView from "ember-views/views/metamorph_view";
<del>import { computed } from "ember-metal/computed";
<del>import ArrayController from "ember-runtime/controllers/array_controller";
<del>import { A } from "ember-runtime/system/native_array";
<del>import { default as EmberController } from "ember-runtime/controllers/controller";
<del>import { Registry } from "ember-runtime/system/container";
<del>
<del>import { get } from "ember-metal/property_get";
<del>import { set } from "ember-metal/property_set";
<del>import { runAppend, runDestroy } from "ember-runtime/tests/utils";
<del>
<del>import compile from "ember-template-compiler/system/compile";
<del>
<del>var people, view, registry, container;
<del>
<del>// This function lets us write {{#EACH|people|p}} {{p}} {{/each}}
<del>// and generate:
<del>//
<del>// - {{#each p in people}} (legacy)
<del>// - {{#each people as |p|}} (legacy)
<del>function makeReplacer(useBlockParams) {
<del> return function(_, matchString) {
<del> var values = matchString.split("|");
<del> if (values.length === 1) { return "each"; }
<del>
<del> var arr = useBlockParams ?
<del> ["each", values[1], "as", "|" + values[2] + "|"] :
<del> ["each", values[2], "in", values[1]];
<del>
<del> var options = values[3];
<del> if (options) {
<del> if (useBlockParams) {
<del> arr.splice(2, 0, options);
<del> } else {
<del> arr.push(options);
<del> }
<del> }
<del>
<del> return arr.join(" ");
<del> };
<del>}
<del>
<del>var parseEachReplacerBlockParam = makeReplacer(true);
<del>var parseEachReplacerNonBlockParam = makeReplacer(false);
<del>
<del>var EACH_REGEX = /(EACH[^\}]*)/g;
<del>
<del>function parseEach(str, useBlockParams) {
<del> return str.replace(EACH_REGEX, useBlockParams ? parseEachReplacerBlockParam : parseEachReplacerNonBlockParam);
<del>}
<del>
<del>QUnit.module("#each new world - parseEach test helper");
<del>
<del>QUnit.test("block param syntax substitution", function() {
<del> equal(parseEach("{{#EACH|people|p}}p people{{/EACH}}", true), "{{#each people as |p|}}p people{{/each}}");
<del> equal(parseEach("{{#EACH|people|p|a='b' c='d'}}p people{{/EACH}}", true), "{{#each people a='b' c='d' as |p|}}p people{{/each}}");
<del>});
<del>
<del>QUnit.test("non-block param syntax substitution", function() {
<del> equal(parseEach("{{#EACH|people|p}}p people{{/EACH}}", false), "{{#each p in people}}p people{{/each}}");
<del> equal(parseEach("{{#EACH|people|p|a='b' c='d'}}p people{{/EACH}}", false), "{{#each p in people a='b' c='d'}}p people{{/each}}");
<del>});
<del>
<del>function templateFor(templateString, useBlockParams) {
<del> return compile(parseEach(templateString, useBlockParams));
<del>}
<del>
<del>function assertText(view, expectedText) {
<del> equal(view.$().text(), expectedText);
<del>}
<del>
<del>function testEachWithItem(moduleName, useBlockParams) {
<del> QUnit.module(moduleName, {
<del> setup: function() {
<del> registry = new Registry();
<del> container = registry.container();
<del>
<del> registry.register('view:default', _MetamorphView);
<del> registry.register('view:toplevel', EmberView.extend());
<del> },
<del> teardown: function() {
<del> runDestroy(container);
<del> runDestroy(view);
<del> container = view = null;
<del> }
<del> });
<del>
<del> QUnit.test("#each accepts a name binding", function() {
<del> view = EmberView.create({
<del> template: templateFor("{{#EACH|view.items|item}}{{view.title}} {{item}}{{/each}}", useBlockParams),
<del> title: "My Cool Each Test",
<del> items: A([1, 2])
<del> });
<del>
<del> runAppend(view);
<del>
<del> equal(view.$().text(), "My Cool Each Test 1My Cool Each Test 2");
<del> });
<del>
<del> QUnit.test("#each accepts a name binding and does not change the context", function() {
<del> var controller = EmberController.create({
<del> name: 'bob the controller'
<del> });
<del> var obj = EmberObject.create({
<del> name: 'henry the item'
<del> });
<del>
<del> view = EmberView.create({
<del> template: templateFor("{{#EACH|view.items|item}}{{name}}{{/each}}", useBlockParams),
<del> title: "My Cool Each Test",
<del> items: A([obj]),
<del> controller: controller
<del> });
<del>
<del> runAppend(view);
<del>
<del> equal(view.$().text(), "bob the controller");
<del> });
<del>
<del>
<del> QUnit.test("#each accepts a name binding and can display child properties", function() {
<del> view = EmberView.create({
<del> template: templateFor("{{#EACH|view.items|item}}{{view.title}} {{item.name}}{{/each}}", useBlockParams),
<del> title: "My Cool Each Test",
<del> items: A([{ name: 1 }, { name: 2 }])
<del> });
<del>
<del> runAppend(view);
<del>
<del> equal(view.$().text(), "My Cool Each Test 1My Cool Each Test 2");
<del> });
<del>
<del> QUnit.test("#each accepts 'this' as the right hand side", function() {
<del> view = EmberView.create({
<del> template: templateFor("{{#EACH|this|item}}{{view.title}} {{item.name}}{{/each}}", useBlockParams),
<del> title: "My Cool Each Test",
<del> controller: A([{ name: 1 }, { name: 2 }])
<del> });
<del>
<del> runAppend(view);
<del>
<del> equal(view.$().text(), "My Cool Each Test 1My Cool Each Test 2");
<del> });
<del>
<del> if (!useBlockParams) {
<del> QUnit.test("views inside #each preserve the new context [DEPRECATED]", function() {
<del> var controller = A([{ name: "Adam" }, { name: "Steve" }]);
<del>
<del> view = EmberView.create({
<del> container: container,
<del> controller: controller,
<del> template: templateFor('{{#each controller}}{{#view}}{{name}}{{/view}}{{/each}}', useBlockParams)
<del> });
<del>
<del> expectDeprecation(function() {
<del> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<del>
<del> equal(view.$().text(), "AdamSteve");
<del> });
<del> }
<del>
<del> QUnit.test("controller is assignable inside an #each", function() {
<del> var controller = ArrayController.create({
<del> model: A([{ name: "Adam" }, { name: "Steve" }])
<del> });
<del>
<del> view = EmberView.create({
<del> container: container,
<del> controller: controller,
<del> template: templateFor('{{#EACH|this|personController}}{{#view controllerBinding="personController"}}{{name}}{{/view}}{{/each}}', useBlockParams)
<del> });
<del>
<del> runAppend(view);
<del>
<del> equal(view.$().text(), "AdamSteve");
<del> });
<del>
<del> QUnit.test("it doesn't assert when the morph tags have the same parent", function() {
<del> view = EmberView.create({
<del> controller: A(['Cyril', 'David']),
<del> template: templateFor('<table><tbody>{{#EACH|this|name}}<tr><td>{{name}}</td></tr>{{/each}}</tbody></table>', useBlockParams)
<del> });
<del>
<del> runAppend(view);
<del>
<del> ok(true, "No assertion from valid template");
<del> });
<del>
<del> QUnit.test("itemController specified in template with name binding does not change context", function() {
<del> var Controller = EmberController.extend({
<del> controllerName: computed(function() {
<del> return "controller:"+this.get('model.name');
<del> })
<del> });
<del>
<del> registry = new Registry();
<del> container = registry.container();
<del>
<del> people = A([{ name: "Steve Holt" }, { name: "Annabelle" }]);
<del>
<del> var parentController = {
<del> container: container,
<del> people: people,
<del> controllerName: 'controller:parentController'
<del> };
<del>
<del> registry.register('controller:array', ArrayController.extend());
<del>
<del> view = EmberView.create({
<del> container: container,
<del> template: templateFor('{{#EACH|people|person|itemController="person"}}{{controllerName}} - {{person.controllerName}} - {{/each}}', useBlockParams),
<del> controller: parentController
<del> });
<del>
<del> registry.register('controller:person', Controller);
<del>
<del> runAppend(view);
<del>
<del> equal(view.$().text(), "controller:parentController - controller:Steve Holt - controller:parentController - controller:Annabelle - ");
<del>
<del> run(function() {
<del> people.pushObject({ name: "Yehuda Katz" });
<del> });
<del>
<del> assertText(view, "controller:parentController - controller:Steve Holt - controller:parentController - controller:Annabelle - controller:parentController - controller:Yehuda Katz - ");
<del>
<del> run(function() {
<del> set(parentController, 'people', A([{ name: "Trek Glowacki" }, { name: "Geoffrey Grosenbach" }]));
<del> });
<del>
<del> assertText(view, "controller:parentController - controller:Trek Glowacki - controller:parentController - controller:Geoffrey Grosenbach - ");
<del>
<del> strictEqual(view._childViews[0]._arrayController.get('target'), parentController, "the target property of the child controllers are set correctly");
<del> });
<del>
<del> QUnit.test("itemController specified in ArrayController with name binding does not change context", function() {
<del> people = A([{ name: "Steve Holt" }, { name: "Annabelle" }]);
<del>
<del> var PersonController = EmberController.extend({
<del> controllerName: computed(function() {
<del> return "controller:" + get(this, 'model.name') + ' of ' + get(this, 'parentController.company');
<del> })
<del> });
<del> var PeopleController = ArrayController.extend({
<del> model: people,
<del> itemController: 'person',
<del> company: 'Yapp',
<del> controllerName: 'controller:people'
<del> });
<del> registry = new Registry();
<del> container = registry.container();
<del>
<del> registry.register('controller:people', PeopleController);
<del> registry.register('controller:person', PersonController);
<del>
<del> view = EmberView.create({
<del> container: container,
<del> template: templateFor('{{#EACH|this|person}}{{controllerName}} - {{person.controllerName}} - {{/each}}', useBlockParams),
<del> controller: container.lookup('controller:people')
<del> });
<del>
<del>
<del> runAppend(view);
<del>
<del> equal(view.$().text(), "controller:people - controller:Steve Holt of Yapp - controller:people - controller:Annabelle of Yapp - ");
<del> });
<del>
<del> if (!useBlockParams) {
<del> QUnit.test("{{each}} without arguments [DEPRECATED]", function() {
<del> expect(2);
<del>
<del> view = EmberView.create({
<del> controller: A([{ name: "Adam" }, { name: "Steve" }]),
<del> template: templateFor('{{#each}}{{name}}{{/each}}', useBlockParams)
<del> });
<del>
<del> expectDeprecation(function() {
<del> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<del>
<del> equal(view.$().text(), "AdamSteve");
<del> });
<del>
<del> QUnit.test("{{each this}} without keyword [DEPRECATED]", function() {
<del> expect(2);
<del>
<del> view = EmberView.create({
<del> controller: A([{ name: "Adam" }, { name: "Steve" }]),
<del> template: templateFor('{{#each this}}{{name}}{{/each}}', useBlockParams)
<del> });
<del>
<del> expectDeprecation(function() {
<del> runAppend(view);
<del> }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.');
<del>
<del> equal(view.$().text(), "AdamSteve");
<del> });
<del> }
<del>
<del> if (useBlockParams) {
<del> if (Ember.FEATURES.isEnabled('ember-htmlbars-each-with-index')) {
<del> QUnit.test("the index is passed as the second parameter to #each blocks", function() {
<del> expect(3);
<del>
<del> var adam = { name: "Adam" };
<del> view = EmberView.create({
<del> controller: A([adam, { name: "Steve" }]),
<del> template: templateFor('{{#each this as |person index|}}{{index}}. {{person.name}}{{/each}}', true)
<del> });
<del> runAppend(view);
<del> equal(view.$().text(), "0. Adam1. Steve");
<del>
<del> run(function() {
<del> view.get('controller').unshiftObject({ name: "Bob" });
<del> });
<del> equal(view.$().text(), "0. Bob1. Adam2. Steve");
<del>
<del> run(function() {
<del> view.get('controller').removeObject(adam);
<del> });
<del> equal(view.$().text(), "0. Bob1. Steve");
<del> });
<del> }
<del> }
<del>}
<del>
<del>testEachWithItem("new world - {{#each bar as |foo|}}", true);
<del>
<ide><path>packages/ember-htmlbars/tests/helpers/template_test.js
<ide> QUnit.module("Support for {{template}} helper", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("should render other templates via the container (DEPRECATED)", function() {
<add>QUnit.skip("should render other templates via the container (DEPRECATED)", function() {
<ide> registry.register('template:sub_template_from_container', compile('sub-template'));
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("should render other templates via the container (DEPRECATED)", funct
<ide> equal(trim(view.$().text()), "This sub-template is pretty great.");
<ide> });
<ide>
<del>QUnit.test("should use the current view's context (DEPRECATED)", function() {
<add>QUnit.skip("should use the current view's context (DEPRECATED)", function() {
<ide> registry.register('template:person_name', compile("{{firstName}} {{lastName}}"));
<ide>
<ide> view = EmberView.create({
<ide><path>packages/ember-htmlbars/tests/helpers/text_area_test.js
<ide> QUnit.module("{{textarea}}", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("Should insert a textarea", function() {
<add>QUnit.skip("Should insert a textarea", function() {
<ide> equal(textArea.$('textarea').length, 1, "There is a single textarea");
<ide> });
<ide>
<del>QUnit.test("Should become disabled when the controller changes", function() {
<add>QUnit.skip("Should become disabled when the controller changes", function() {
<ide> ok(textArea.$('textarea').is(':not(:disabled)'), "Nothing is disabled yet");
<ide> set(controller, 'disabled', true);
<ide> ok(textArea.$('textarea').is(':disabled'), "The disabled attribute is updated");
<ide> });
<ide>
<del>QUnit.test("Should bind its contents to the specified value", function() {
<add>QUnit.skip("Should bind its contents to the specified value", function() {
<ide> equal(textArea.$('textarea').val(), "Lorem ipsum dolor", "The contents are included");
<ide> set(controller, 'val', "sit amet");
<ide> equal(textArea.$('textarea').val(), "sit amet", "The new contents are included");
<ide><path>packages/ember-htmlbars/tests/helpers/unbound_test.js
<ide> QUnit.test('it should not re-render if the property changes', function() {
<ide> equal(view.$().text(), 'BORK BORK', 'should not re-render if the property changes');
<ide> });
<ide>
<del>QUnit.test('it should throw the helper missing error if multiple properties are provided', function() {
<add>QUnit.skip('it should throw the helper missing error if multiple properties are provided', function() {
<ide> throws(function() {
<ide> runAppend(EmberView.create({
<ide> template: compile('{{unbound foo bar}}'),
<ide> QUnit.test('it should throw the helper missing error if multiple properties are
<ide> }, EmberError);
<ide> });
<ide>
<del>QUnit.test('should property escape unsafe hrefs', function() {
<add>QUnit.skip('should property escape unsafe hrefs', function() {
<ide> /* jshint scripturl:true */
<ide>
<ide> expect(3);
<ide> QUnit.module("ember-htmlbars: {{#unbound boundHelper arg1 arg2... argN}} form: r
<ide> }
<ide> });
<ide>
<del>QUnit.test("should be able to render an unbound helper invocation", function() {
<add>QUnit.skip("should be able to render an unbound helper invocation", function() {
<ide> try {
<ide> registerBoundHelper('repeat', function(value, options) {
<ide> var count = options.hash.count;
<ide> QUnit.test("should be able to render an unbound helper invocation", function() {
<ide> }
<ide> });
<ide>
<del>QUnit.test("should be able to render an bound helper invocation mixed with static values", function() {
<add>QUnit.skip("should be able to render an bound helper invocation mixed with static values", function() {
<ide> view = EmberView.create({
<ide> template: compile('{{unbound surround prefix value "bar"}} {{surround prefix value "bar"}} {{unbound surround "bar" value suffix}} {{surround "bar" value suffix}}'),
<ide> context: EmberObject.create({
<ide> QUnit.test("should be able to render an bound helper invocation mixed with stati
<ide> equal(view.$().text(), "before-core-bar beforeChanged-coreChanged-bar bar-core-after bar-coreChanged-afterChanged", "only bound values change");
<ide> });
<ide>
<del>QUnit.test("should be able to render unbound forms of multi-arg helpers", function() {
<add>QUnit.skip("should be able to render unbound forms of multi-arg helpers", function() {
<ide> view = EmberView.create({
<ide> template: compile("{{fauxconcat foo bar bing}} {{unbound fauxconcat foo bar bing}}"),
<ide> context: EmberObject.create({
<ide> QUnit.test("should be able to render unbound forms of multi-arg helpers", functi
<ide> equal(view.$().text(), "aXc abc", "unbound helpers/properties stayed the same");
<ide> });
<ide>
<del>QUnit.test("should be able to render an unbound helper invocation for helpers with dependent keys", function() {
<add>QUnit.skip("should be able to render an unbound helper invocation for helpers with dependent keys", function() {
<ide> view = EmberView.create({
<ide> template: compile("{{capitalizeName person}} {{unbound capitalizeName person}} {{concatNames person}} {{unbound concatNames person}}"),
<ide> context: EmberObject.create({
<ide> QUnit.test("should be able to render an unbound helper invocation for helpers wi
<ide> equal(view.$().text(), "SALLY SHOOBY sallytaylor shoobytaylor", "only bound values change");
<ide> });
<ide>
<del>QUnit.test("should be able to render an unbound helper invocation in #each helper", function() {
<add>QUnit.skip("should be able to render an unbound helper invocation in #each helper", function() {
<ide> view = EmberView.create({
<ide> template: compile(
<ide> ["{{#each person in people}}",
<ide> QUnit.test("should be able to render an unbound helper invocation in #each helpe
<ide> equal(view.$().text(), "SHOOBY SHOOBYCINDY CINDY", "unbound rendered correctly");
<ide> });
<ide>
<del>QUnit.test("should be able to render an unbound helper invocation with bound hash options", function() {
<add>QUnit.skip("should be able to render an unbound helper invocation with bound hash options", function() {
<ide> try {
<ide> Ember.Handlebars.registerBoundHelper('repeat', function(value) {
<ide> return [].slice.call(arguments, 0, -1).join('');
<ide> QUnit.test("should be able to render an unbound helper invocation with bound has
<ide> }
<ide> });
<ide>
<del>QUnit.test("should be able to render bound form of a helper inside unbound form of same helper", function() {
<add>QUnit.skip("should be able to render bound form of a helper inside unbound form of same helper", function() {
<ide> view = EmberView.create({
<ide> template: compile(
<ide> ["{{#unbound if foo}}",
<ide> QUnit.module("ember-htmlbars: {{#unbound}} helper -- Container Lookup", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("should lookup helpers in the container", function() {
<add>QUnit.skip("should lookup helpers in the container", function() {
<ide> expectDeprecationInHTMLBars();
<ide>
<ide> registry.register('helper:up-case', makeBoundHelper(function(value) {
<ide> QUnit.test("should be able to use unbound helper in #each helper (with objects)"
<ide> equal(view.$('li').children().length, 0, 'No markers');
<ide> });
<ide>
<del>QUnit.test('should work properly with attributes', function() {
<add>QUnit.skip('should work properly with attributes', function() {
<ide> expect(4);
<ide>
<ide> view = EmberView.create({
<ide><path>packages/ember-htmlbars/tests/helpers/view_test.js
<ide> QUnit.test("should not enter an infinite loop when binding an attribute in Handl
<ide> runDestroy(parentView);
<ide> });
<ide>
<del>QUnit.test("By default view:toplevel is used", function() {
<add>QUnit.skip("By default view:toplevel is used", function() {
<ide> var DefaultView = viewClass({
<ide> elementId: 'toplevel-view',
<ide> template: compile('hello world')
<ide> QUnit.test("By default view:toplevel is used", function() {
<ide> equal(jQuery('#toplevel-view').text(), 'hello world');
<ide> });
<ide>
<del>QUnit.test("By default, without a container, EmberView is used", function() {
<add>QUnit.skip("By default, without a container, EmberView is used", function() {
<ide> view = EmberView.extend({
<ide> template: compile('{{view tagName="span"}}')
<ide> }).create();
<ide> QUnit.test("By default, without a container, EmberView is used", function() {
<ide> ok(jQuery('#qunit-fixture').html().toUpperCase().match(/<SPAN/), 'contains view with span');
<ide> });
<ide>
<del>QUnit.test("View lookup - App.FuView (DEPRECATED)", function() {
<add>QUnit.skip("View lookup - App.FuView (DEPRECATED)", function() {
<ide> Ember.lookup = {
<ide> App: {
<ide> FuView: viewClass({
<ide> QUnit.test("View lookup - App.FuView (DEPRECATED)", function() {
<ide> equal(jQuery('#fu').text(), 'bro');
<ide> });
<ide>
<del>QUnit.test("View lookup - 'fu'", function() {
<add>QUnit.skip("View lookup - 'fu'", function() {
<ide> var FuView = viewClass({
<ide> elementId: "fu",
<ide> template: compile("bro")
<ide> QUnit.test("View lookup - 'fu'", function() {
<ide> equal(jQuery('#fu').text(), 'bro');
<ide> });
<ide>
<del>QUnit.test("View lookup - 'fu' when fu is a property and a view name", function() {
<add>QUnit.skip("View lookup - 'fu' when fu is a property and a view name", function() {
<ide> var FuView = viewClass({
<ide> elementId: "fu",
<ide> template: compile("bro")
<ide> QUnit.test("View lookup - 'fu' when fu is a property and a view name", function(
<ide> equal(jQuery('#fu').text(), 'bro');
<ide> });
<ide>
<del>QUnit.test("View lookup - view.computed", function() {
<add>QUnit.skip("View lookup - view.computed", function() {
<ide> var FuView = viewClass({
<ide> elementId: "fu",
<ide> template: compile("bro")
<ide> QUnit.test("View lookup - view.computed", function() {
<ide> equal(jQuery('#fu').text(), 'bro');
<ide> });
<ide>
<del>QUnit.test("id bindings downgrade to one-time property lookup", function() {
<add>QUnit.skip("id bindings downgrade to one-time property lookup", function() {
<ide> view = EmberView.extend({
<ide> template: compile("{{#view id=view.meshuggah}}{{view.parentView.meshuggah}}{{/view}}"),
<ide> meshuggah: 'stengah'
<ide> QUnit.test("id bindings downgrade to one-time property lookup", function() {
<ide> equal(jQuery('#stengah').text(), 'omg', "id didn't change");
<ide> });
<ide>
<del>QUnit.test("specifying `id` as a static value works properly", function() {
<add>QUnit.skip("specifying `id` as a static value works properly", function() {
<ide> view = EmberView.extend({
<ide> template: compile("{{#view id='blah'}}{{view.parentView.meshuggah}}{{/view}}"),
<ide> meshuggah: 'stengah'
<ide> QUnit.test("specifying `id` as a static value works properly", function() {
<ide> equal(view.$('#blah').text(), 'stengah', "id binding performed property lookup");
<ide> });
<ide>
<del>QUnit.test("mixing old and new styles of property binding fires a warning, treats value as if it were quoted", function() {
<add>QUnit.skip("mixing old and new styles of property binding fires a warning, treats value as if it were quoted", function() {
<ide> if (EmberDev && EmberDev.runningProdBuild) {
<ide> ok(true, 'Logging does not occur in production builds');
<ide> return;
<ide> QUnit.test("mixing old and new styles of property binding fires a warning, treat
<ide> Ember.warn = oldWarn;
<ide> });
<ide>
<del>QUnit.test('"Binding"-suffixed bindings are runloop-synchronized [DEPRECATED]', function() {
<add>QUnit.skip('"Binding"-suffixed bindings are runloop-synchronized [DEPRECATED]', function() {
<ide> expect(6);
<ide>
<ide> var subview;
<ide> QUnit.test('"Binding"-suffixed bindings are runloop-synchronized [DEPRECATED]',
<ide> equal(get(subview, 'color'), 'persian rose', 'bound property is updated after runloop flush');
<ide> });
<ide>
<del>QUnit.test('Non-"Binding"-suffixed bindings are runloop-synchronized', function() {
<add>QUnit.skip('Non-"Binding"-suffixed bindings are runloop-synchronized', function() {
<ide> expect(5);
<ide>
<ide> var subview;
<ide> QUnit.test('Non-"Binding"-suffixed bindings are runloop-synchronized', function(
<ide> equal(get(subview, 'color'), 'persian rose', 'bound property is updated after runloop flush');
<ide> });
<ide>
<del>QUnit.test("allows you to pass attributes that will be assigned to the class instance, like class=\"foo\"", function() {
<add>QUnit.skip("allows you to pass attributes that will be assigned to the class instance, like class=\"foo\"", function() {
<ide> expect(4);
<ide>
<ide> registry = new Registry();
<ide> QUnit.test("allows you to pass attributes that will be assigned to the class ins
<ide> equal(jQuery('#bar').text(), 'Bar');
<ide> });
<ide>
<del>QUnit.test("Should apply class without condition always", function() {
<add>QUnit.skip("Should apply class without condition always", function() {
<ide> view = EmberView.create({
<ide> controller: Ember.Object.create(),
<ide> template: compile('{{#view id="foo" classBinding=":foo"}} Foo{{/view}}')
<ide> QUnit.test("Should apply class without condition always", function() {
<ide> ok(jQuery('#foo').hasClass('foo'), "Always applies classbinding without condition");
<ide> });
<ide>
<del>QUnit.test("Should apply classes when bound controller.* property specified", function() {
<add>QUnit.skip("Should apply classes when bound controller.* property specified", function() {
<ide> view = EmberView.create({
<ide> controller: {
<ide> someProp: 'foo'
<ide> QUnit.test("Should not apply classes when bound property specified is false", fu
<ide> ok(!jQuery('#foo').hasClass('some-prop'), "does not add class when value is falsey");
<ide> });
<ide>
<del>QUnit.test("Should apply classes of the dasherized property name when bound property specified is true", function() {
<add>QUnit.skip("Should apply classes of the dasherized property name when bound property specified is true", function() {
<ide> view = EmberView.create({
<ide> controller: {
<ide> someProp: true
<ide> QUnit.test("Should apply classes of the dasherized property name when bound prop
<ide> ok(jQuery('#foo').hasClass('some-prop'), "adds dasherized class when value is true");
<ide> });
<ide>
<del>QUnit.test("Should update classes from a bound property", function() {
<add>QUnit.skip("Should update classes from a bound property", function() {
<ide> var controller = {
<ide> someProp: true
<ide> };
<ide> QUnit.test("Should update classes from a bound property", function() {
<ide> ok(jQuery('#foo').hasClass('fooBar'), "changes property to string value (but does not dasherize)");
<ide> });
<ide>
<del>QUnit.test("bound properties should be available in the view", function() {
<add>QUnit.skip("bound properties should be available in the view", function() {
<ide> var FuView = viewClass({
<ide> elementId: 'fu',
<ide> template: compile("{{view.foo}}")
<ide> QUnit.test('should teardown observers from bound properties on rerender', functi
<ide> equal(observersFor(view, 'foo').length, 1);
<ide> });
<ide>
<del>QUnit.test('should update bound values after the view is removed and then re-appended', function() {
<add>QUnit.skip('should update bound values after the view is removed and then re-appended', function() {
<ide> view = EmberView.create({
<ide> template: compile('{{#if view.showStuff}}{{view.boundValue}}{{else}}Not true.{{/if}}'),
<ide> showStuff: true,
<ide> QUnit.test('views set the template of their children to a passed block', functio
<ide> ok(view.$('h1:has(span)').length === 1, "renders the passed template inside the parent template");
<ide> });
<ide>
<del>QUnit.test('{{view}} should not override class bindings defined on a child view', function() {
<add>QUnit.skip('{{view}} should not override class bindings defined on a child view', function() {
<ide> var LabelView = EmberView.extend({
<ide> container: container,
<ide> classNameBindings: ['something'],
<ide> QUnit.test('{{view}} should not override class bindings defined on a child view'
<ide> ok(view.$('.visible').length > 0, 'class bindings are not overriden');
<ide> });
<ide>
<del>QUnit.test('child views can be inserted using the {{view}} helper', function() {
<add>QUnit.skip('child views can be inserted using the {{view}} helper', function() {
<ide> registry.register('template:nester', compile('<h1 id="hello-world">Hello {{world}}</h1>{{view view.labelView}}'));
<ide> registry.register('template:nested', compile('<div id="child-view">Goodbye {{cruel}} {{world}}</div>'));
<ide>
<ide> QUnit.test('child views can be inserted using the {{view}} helper', function() {
<ide> ok(view.$().text().match(/Hello world!.*Goodbye cruel world\!/), 'parent view should appear before the child view');
<ide> });
<ide>
<del>QUnit.test('should be able to explicitly set a view\'s context', function() {
<add>QUnit.skip('should be able to explicitly set a view\'s context', function() {
<ide> var context = EmberObject.create({
<ide> test: 'test'
<ide> });
<ide> QUnit.test('should be able to explicitly set a view\'s context', function() {
<ide> equal(view.$().text(), 'test');
<ide> });
<ide>
<del>QUnit.test('Template views add an elementId to child views created using the view helper', function() {
<add>QUnit.skip('Template views add an elementId to child views created using the view helper', function() {
<ide> registry.register('template:parent', compile('<div>{{view view.childView}}</div>'));
<ide> registry.register('template:child', compile('I can\'t believe it\'s not butter.'));
<ide>
<ide> QUnit.test('Template views add an elementId to child views created using the vie
<ide> equal(view.$().children().first().children().first().attr('id'), get(childView, 'elementId'));
<ide> });
<ide>
<del>QUnit.test('Child views created using the view helper should have their parent view set properly', function() {
<add>QUnit.skip('Child views created using the view helper should have their parent view set properly', function() {
<ide> var template = '{{#view}}{{#view}}{{view}}{{/view}}{{/view}}';
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test('Child views created using the view helper should have their parent v
<ide> equal(childView, get(firstChild(childView), 'parentView'), 'parent view is correct');
<ide> });
<ide>
<del>QUnit.test('Child views created using the view helper should have their IDs registered for events', function() {
<add>QUnit.skip('Child views created using the view helper should have their IDs registered for events', function() {
<ide> var template = '{{view}}{{view id="templateViewTest"}}';
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test('Child views created using the view helper should have their IDs regi
<ide> equal(EmberView.views[id], childView, 'childView with passed ID is registered with View.views so that it can properly receive events from EventDispatcher');
<ide> });
<ide>
<del>QUnit.test('Child views created using the view helper and that have a viewName should be registered as properties on their parentView', function() {
<add>QUnit.skip('Child views created using the view helper and that have a viewName should be registered as properties on their parentView', function() {
<ide> var template = '{{#view}}{{view viewName="ohai"}}{{/view}}';
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test('{{view}} id attribute should set id on layer', function() {
<ide> equal(view.$('#bar').text(), 'baz', 'emits content');
<ide> });
<ide>
<del>QUnit.test('{{view}} tag attribute should set tagName of the view', function() {
<add>QUnit.skip('{{view}} tag attribute should set tagName of the view', function() {
<ide> registry.register('template:foo', compile('{{#view view.tagView tag="span"}}baz{{/view}}'));
<ide>
<ide> var TagView = EmberView;
<ide> QUnit.test('{{view}} class attribute should set class on layer', function() {
<ide> equal(view.$('.bar').text(), 'baz', 'emits content');
<ide> });
<ide>
<del>QUnit.test('{{view}} should not allow attributeBindings to be set', function() {
<add>QUnit.skip('{{view}} should not allow attributeBindings to be set', function() {
<ide> expectAssertion(function() {
<ide> view = EmberView.create({
<ide> template: compile('{{view attributeBindings="one two"}}')
<ide> QUnit.test('{{view}} should not allow attributeBindings to be set', function() {
<ide> }, /Setting 'attributeBindings' via template helpers is not allowed/);
<ide> });
<ide>
<del>QUnit.test('{{view}} should be able to point to a local view', function() {
<add>QUnit.skip('{{view}} should be able to point to a local view', function() {
<ide> view = EmberView.create({
<ide> template: compile('{{view view.common}}'),
<ide>
<ide> QUnit.test('{{view}} should be able to point to a local view', function() {
<ide> equal(view.$().text(), 'common', 'tries to look up view name locally');
<ide> });
<ide>
<del>QUnit.test('{{view}} should evaluate class bindings set to global paths DEPRECATED', function() {
<add>QUnit.skip('{{view}} should evaluate class bindings set to global paths DEPRECATED', function() {
<ide> var App;
<ide>
<ide> run(function() {
<ide> QUnit.test('{{view}} should evaluate class bindings set to global paths DEPRECAT
<ide> runDestroy(lookup.App);
<ide> });
<ide>
<del>QUnit.test('{{view}} should evaluate class bindings set in the current context', function() {
<add>QUnit.skip('{{view}} should evaluate class bindings set in the current context', function() {
<ide> view = EmberView.create({
<ide> isView: true,
<ide> isEditable: true,
<ide> QUnit.test('{{view}} should evaluate class bindings set in the current context',
<ide> ok(view.$('input').hasClass('disabled'), 'evaluates ternary operator in classBindings');
<ide> });
<ide>
<del>QUnit.test('{{view}} should evaluate class bindings set with either classBinding or classNameBindings from globals DEPRECATED', function() {
<add>QUnit.skip('{{view}} should evaluate class bindings set with either classBinding or classNameBindings from globals DEPRECATED', function() {
<ide> var App;
<ide>
<ide> run(function() {
<ide> QUnit.test('{{view}} should evaluate class bindings set with either classBinding
<ide> runDestroy(lookup.App);
<ide> });
<ide>
<del>QUnit.test('{{view}} should evaluate other attribute bindings set to global paths', function() {
<add>QUnit.skip('{{view}} should evaluate other attribute bindings set to global paths', function() {
<ide> run(function() {
<ide> lookup.App = Namespace.create({
<ide> name: 'myApp'
<ide> QUnit.test('{{view}} should evaluate other attribute bindings set to global path
<ide> runDestroy(lookup.App);
<ide> });
<ide>
<del>QUnit.test('{{view}} should evaluate other attributes bindings set in the current context', function() {
<add>QUnit.skip('{{view}} should evaluate other attributes bindings set in the current context', function() {
<ide> view = EmberView.create({
<ide> name: 'myView',
<ide> textField: TextField,
<ide> QUnit.test('{{view}} should evaluate other attributes bindings set in the curren
<ide> equal(view.$('input').val(), 'myView', 'evaluates attributes bound in the current context');
<ide> });
<ide>
<del>QUnit.test('{{view}} should be able to bind class names to truthy properties', function() {
<add>QUnit.skip('{{view}} should be able to bind class names to truthy properties', function() {
<ide> registry.register('template:template', compile('{{#view view.classBindingView classBinding="view.number:is-truthy"}}foo{{/view}}'));
<ide>
<ide> var ClassBindingView = EmberView.extend();
<ide> QUnit.test('{{view}} should be able to bind class names to truthy properties', f
<ide> equal(view.$('.is-truthy').length, 0, 'removes class name if bound property is set to falsey');
<ide> });
<ide>
<del>QUnit.test('{{view}} should be able to bind class names to truthy or falsy properties', function() {
<add>QUnit.skip('{{view}} should be able to bind class names to truthy or falsy properties', function() {
<ide> registry.register('template:template', compile('{{#view view.classBindingView classBinding="view.number:is-truthy:is-falsy"}}foo{{/view}}'));
<ide>
<ide> var ClassBindingView = EmberView.extend();
<ide> QUnit.test('{{view}} should be able to bind class names to truthy or falsy prope
<ide> equal(view.$('.is-falsy').length, 1, "sets class name to falsy value");
<ide> });
<ide>
<del>QUnit.test('a view helper\'s bindings are to the parent context', function() {
<add>QUnit.skip('a view helper\'s bindings are to the parent context', function() {
<ide> var Subview = EmberView.extend({
<ide> classNameBindings: ['color'],
<ide> controller: EmberObject.create({
<ide> QUnit.test('a view helper\'s bindings are to the parent context', function() {
<ide> equal(view.$('h1 .mauve').text(), 'foo bar', 'renders property bound in template from subview context');
<ide> });
<ide>
<del>QUnit.test('should expose a controller keyword when present on the view', function() {
<add>QUnit.skip('should expose a controller keyword when present on the view', function() {
<ide> var templateString = '{{controller.foo}}{{#view}}{{controller.baz}}{{/view}}';
<ide> view = EmberView.create({
<ide> container: container,
<ide> QUnit.test('should expose a controller keyword when present on the view', functi
<ide> equal(view.$().text(), 'aString', 'renders the controller itself if no additional path is specified');
<ide> });
<ide>
<del>QUnit.test('should expose a controller keyword that can be used in conditionals', function() {
<add>QUnit.skip('should expose a controller keyword that can be used in conditionals', function() {
<ide> var templateString = '{{#view}}{{#if controller}}{{controller.foo}}{{/if}}{{/view}}';
<ide> view = EmberView.create({
<ide> container: container,
<ide> QUnit.test('should expose a controller keyword that can be used in conditionals'
<ide> equal(view.$().text(), '', 'updates the DOM when the controller is changed');
<ide> });
<ide>
<del>QUnit.test('should expose a controller keyword that persists through Ember.ContainerView', function() {
<add>QUnit.skip('should expose a controller keyword that persists through Ember.ContainerView', function() {
<ide> var templateString = '{{view view.containerView}}';
<ide> view = EmberView.create({
<ide> containerView: ContainerView,
<ide> QUnit.test('should work with precompiled templates', function() {
<ide> equal(view.$().text(), 'updated', 'the precompiled template was updated');
<ide> });
<ide>
<del>QUnit.test('bindings should be relative to the current context [DEPRECATED]', function() {
<add>QUnit.skip('bindings should be relative to the current context [DEPRECATED]', function() {
<ide> view = EmberView.create({
<ide> museumOpen: true,
<ide>
<ide> QUnit.test('bindings should be relative to the current context [DEPRECATED]', fu
<ide> equal(trim(view.$().text()), 'Name: SFMoMA Price: $20', 'should print baz twice');
<ide> });
<ide>
<del>QUnit.test('bindings should respect keywords [DEPRECATED]', function() {
<add>QUnit.skip('bindings should respect keywords [DEPRECATED]', function() {
<ide> view = EmberView.create({
<ide> museumOpen: true,
<ide>
<ide> QUnit.test('should bind to the property if no registered helper found for a must
<ide> ok(view.$().text() === 'foobarProperty', 'Property was bound to correctly');
<ide> });
<ide>
<del>QUnit.test('{{view}} should be able to point to a local instance of view', function() {
<add>QUnit.skip('{{view}} should be able to point to a local instance of view', function() {
<ide> view = EmberView.create({
<ide> template: compile("{{view view.common}}"),
<ide>
<ide> QUnit.test('{{view}} should be able to point to a local instance of view', funct
<ide> equal(view.$().text(), "common", "tries to look up view name locally");
<ide> });
<ide>
<del>QUnit.test("{{view}} should be able to point to a local instance of subclass of view", function() {
<add>QUnit.skip("{{view}} should be able to point to a local instance of subclass of view", function() {
<ide> var MyView = EmberView.extend();
<ide> view = EmberView.create({
<ide> template: compile("{{view view.subclassed}}"),
<ide> QUnit.test("{{view}} asserts that a view subclass instance is present off contro
<ide> }, /must be a subclass or an instance of Ember.View/);
<ide> });
<ide>
<del>QUnit.test('Specifying `id` to {{view}} is set on the view.', function() {
<add>QUnit.skip('Specifying `id` to {{view}} is set on the view.', function() {
<ide> registry.register('view:derp', EmberView.extend({
<ide> template: compile('<div id="view-id">{{view.id}}</div><div id="view-elementId">{{view.elementId}}</div>')
<ide> }));
<ide> QUnit.test('Specifying `id` to {{view}} is set on the view.', function() {
<ide> equal(view.$('#view-elementId').text(), 'bar', 'the views elementId property is set');
<ide> });
<ide>
<del>QUnit.test('Specifying `id` to {{view}} does not allow bound id changes.', function() {
<add>QUnit.skip('Specifying `id` to {{view}} does not allow bound id changes.', function() {
<ide> registry.register('view:derp', EmberView.extend({
<ide> template: compile('<div id="view-id">{{view.id}}</div><div id="view-elementId">{{view.elementId}}</div>')
<ide> }));
<ide><path>packages/ember-htmlbars/tests/helpers/with_test.js
<ide> function testWithAs(moduleName, templateString) {
<ide> equal(view.$().text(), "Señor Engineer: Tom Dale", "should be properly scoped");
<ide> });
<ide>
<del> QUnit.test("updating the context should update the alias", function() {
<add> QUnit.skip("updating the context should update the alias", function() {
<ide> run(function() {
<ide> view.set('context.person', {
<ide> name: "Yehuda Katz"
<ide> QUnit.test("re-using the same variable with different #with blocks does not over
<ide> equal(view.$().text(), "Admin: Tom Dale User: Yehuda Katz", "should be properly scoped");
<ide> });
<ide>
<del>QUnit.test("the scoped variable is not available outside the {{with}} block.", function() {
<add>QUnit.skip("the scoped variable is not available outside the {{with}} block.", function() {
<ide> run(function() {
<ide> view.set('template', compile("{{name}}-{{#with other as name}}{{name}}{{/with}}-{{name}}"));
<ide> view.set('context', {
<ide> QUnit.test("the scoped variable is not available outside the {{with}} block.", f
<ide> equal(view.$().text(), "Stef-Yehuda-Stef", "should be properly scoped after updating");
<ide> });
<ide>
<del>QUnit.test("nested {{with}} blocks shadow the outer scoped variable properly.", function() {
<add>QUnit.skip("nested {{with}} blocks shadow the outer scoped variable properly.", function() {
<ide> run(function() {
<ide> view.set('template', compile("{{#with first as ring}}{{ring}}-{{#with fifth as ring}}{{ring}}-{{#with ninth as ring}}{{ring}}-{{/with}}{{ring}}-{{/with}}{{ring}}{{/with}}"));
<ide> view.set('context', {
<ide> QUnit.module("Handlebars {{#with}} globals helper [DEPRECATED]", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("it should support #with Foo.bar as qux [DEPRECATED]", function() {
<add>QUnit.skip("it should support #with Foo.bar as qux [DEPRECATED]", function() {
<ide> expectDeprecation(function() {
<ide> runAppend(view);
<ide> }, /Global lookup of Foo from a Handlebars template is deprecated/);
<ide> QUnit.test("it should support #with view as foo", function() {
<ide> runDestroy(view);
<ide> });
<ide>
<del>QUnit.test("it should support #with name as food, then #with foo as bar", function() {
<add>QUnit.skip("it should support #with name as food, then #with foo as bar", function() {
<ide> var view = EmberView.create({
<ide> template: compile("{{#with name as foo}}{{#with foo as bar}}{{bar}}{{/with}}{{/with}}"),
<ide> context: { name: "caterpillar" }
<ide> QUnit.test("it should support #with this as qux", function() {
<ide>
<ide> QUnit.module("Handlebars {{#with foo}} with defined controller");
<ide>
<del>QUnit.test("it should wrap context with object controller [DEPRECATED]", function() {
<add>QUnit.skip("it should wrap context with object controller [DEPRECATED]", function() {
<ide> var childController;
<ide>
<ide> var Controller = ObjectController.extend({
<ide> QUnit.test("re-using the same variable with different #with blocks does not over
<ide> equal(view.$().text(), "Admin: Tom Dale User: Yehuda Katz", "should be properly scoped");
<ide> });
<ide>
<del>QUnit.test("the scoped variable is not available outside the {{with}} block.", function() {
<add>QUnit.skip("the scoped variable is not available outside the {{with}} block.", function() {
<ide> run(function() {
<ide> view.set('template', compile("{{name}}-{{#with other as |name|}}{{name}}{{/with}}-{{name}}"));
<ide> view.set('context', {
<ide> QUnit.test("the scoped variable is not available outside the {{with}} block.", f
<ide> equal(view.$().text(), "Stef-Yehuda-Stef", "should be properly scoped after updating");
<ide> });
<ide>
<del>QUnit.test("nested {{with}} blocks shadow the outer scoped variable properly.", function() {
<add>QUnit.skip("nested {{with}} blocks shadow the outer scoped variable properly.", function() {
<ide> run(function() {
<ide> view.set('template', compile("{{#with first as |ring|}}{{ring}}-{{#with fifth as |ring|}}{{ring}}-{{#with ninth as |ring|}}{{ring}}-{{/with}}{{ring}}-{{/with}}{{ring}}{{/with}}"));
<ide> view.set('context', {
<ide><path>packages/ember-htmlbars/tests/helpers/yield_test.js
<ide> QUnit.module("ember-htmlbars: Support for {{yield}} helper", {
<ide>
<ide> QUnit.test("a view with a layout set renders its template where the {{yield}} helper appears", function() {
<ide> var ViewWithLayout = EmberView.extend({
<del> layout: compile('<div class="wrapper"><h1>{{title}}</h1>{{yield}}</div>')
<add> layout: compile('<div class="wrapper"><h1>{{attrs.title}}</h1>{{yield}}</div>')
<ide> });
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("a view with a layout set renders its template where the {{yield}} he
<ide> });
<ide>
<ide> QUnit.test("block should work properly even when templates are not hard-coded", function() {
<del> registry.register('template:nester', compile('<div class="wrapper"><h1>{{title}}</h1>{{yield}}</div>'));
<add> registry.register('template:nester', compile('<div class="wrapper"><h1>{{attrs.title}}</h1>{{yield}}</div>'));
<ide> registry.register('template:nested', compile('{{#view "with-layout" title="My Fancy Page"}}<div class="page-body">Show something interesting here</div>{{/view}}'));
<ide>
<ide> registry.register('view:with-layout', EmberView.extend({
<ide> QUnit.test("block should work properly even when templates are not hard-coded",
<ide>
<ide> });
<ide>
<del>QUnit.test("templates should yield to block, when the yield is embedded in a hierarchy of virtual views", function() {
<add>QUnit.skip("templates should yield to block, when the yield is embedded in a hierarchy of virtual views", function() {
<ide> var TimesView = EmberView.extend({
<ide> layout: compile('<div class="times">{{#each item in view.index}}{{yield}}{{/each}}</div>'),
<ide> n: null,
<ide> QUnit.test("templates should yield to block, when the yield is embedded in a hie
<ide> equal(view.$('div#container div.times-item').length, 5, 'times-item is embedded within wrapping container 5 times, as expected');
<ide> });
<ide>
<del>QUnit.test("templates should yield to block, when the yield is embedded in a hierarchy of non-virtual views", function() {
<add>QUnit.skip("templates should yield to block, when the yield is embedded in a hierarchy of non-virtual views", function() {
<ide> var NestingView = EmberView.extend({
<ide> layout: compile('{{#view tagName="div" classNames="nesting"}}{{yield}}{{/view}}')
<ide> });
<ide> QUnit.test("templates should yield to block, when the yield is embedded in a hie
<ide> equal(view.$('div#container div.nesting div#block').length, 1, 'nesting view yields correctly even within a view hierarchy in the nesting view');
<ide> });
<ide>
<del>QUnit.test("block should not be required", function() {
<add>QUnit.skip("block should not be required", function() {
<ide> var YieldingView = EmberView.extend({
<ide> layout: compile('{{#view tagName="div" classNames="yielding"}}{{yield}}{{/view}}')
<ide> });
<ide> QUnit.test("block should not be required", function() {
<ide> equal(view.$('div#container div.yielding').length, 1, 'yielding view is rendered as expected');
<ide> });
<ide>
<del>QUnit.test("yield uses the outer context", function() {
<add>QUnit.skip("yield uses the outer context", function() {
<ide> var component = Component.extend({
<ide> boundText: "inner",
<ide> layout: compile("<p>{{boundText}}</p><p>{{yield}}</p>")
<ide> QUnit.test("yield uses the outer context", function() {
<ide> });
<ide>
<ide>
<del>QUnit.test("yield inside a conditional uses the outer context [DEPRECATED]", function() {
<add>QUnit.skip("yield inside a conditional uses the outer context [DEPRECATED]", function() {
<ide> var component = Component.extend({
<ide> boundText: "inner",
<ide> truthy: true,
<ide> QUnit.test("yield inside a conditional uses the outer context [DEPRECATED]", fun
<ide> equal(view.$('div p:contains(inner) + p:contains(insideWith)').length, 1, "Yield points at the right context");
<ide> });
<ide>
<del>QUnit.test("outer keyword doesn't mask inner component property", function () {
<add>QUnit.skip("outer keyword doesn't mask inner component property", function () {
<ide> var component = Component.extend({
<ide> item: "inner",
<ide> layout: compile("<p>{{item}}</p><p>{{yield}}</p>")
<ide> QUnit.test("outer keyword doesn't mask inner component property", function () {
<ide> equal(view.$('div p:contains(inner) + p:contains(outer)').length, 1, "inner component property isn't masked by outer keyword");
<ide> });
<ide>
<del>QUnit.test("inner keyword doesn't mask yield property", function() {
<add>QUnit.skip("inner keyword doesn't mask yield property", function() {
<ide> var component = Component.extend({
<ide> boundText: "inner",
<ide> layout: compile("{{#with boundText as item}}<p>{{item}}</p><p>{{yield}}</p>{{/with}}")
<ide> QUnit.test("inner keyword doesn't mask yield property", function() {
<ide> equal(view.$('div p:contains(inner) + p:contains(outer)').length, 1, "outer property isn't masked by inner keyword");
<ide> });
<ide>
<del>QUnit.test("can bind a keyword to a component and use it in yield", function() {
<add>QUnit.skip("can bind a keyword to a component and use it in yield", function() {
<ide> var component = Component.extend({
<ide> content: null,
<ide> layout: compile("<p>{{content}}</p><p>{{yield}}</p>")
<ide> QUnit.test("can bind a keyword to a component and use it in yield", function() {
<ide> equal(view.$('div p:contains(update) + p:contains(update)').length, 1, "keyword has correctly propagated update");
<ide> });
<ide>
<del>QUnit.test("yield view should be a virtual view", function() {
<add>QUnit.skip("yield view should be a virtual view", function() {
<ide> var component = Component.extend({
<ide> isParentComponent: true,
<ide>
<ide> QUnit.test("yield view should be a virtual view", function() {
<ide> });
<ide>
<ide>
<del>QUnit.test("adding a layout should not affect the context of normal views", function() {
<add>QUnit.skip("adding a layout should not affect the context of normal views", function() {
<ide> var parentView = EmberView.create({
<ide> context: "ParentContext"
<ide> });
<ide> QUnit.test("adding a layout should not affect the context of normal views", func
<ide> runDestroy(parentView);
<ide> });
<ide>
<del>QUnit.test("yield should work for views even if _parentView is null", function() {
<add>QUnit.skip("yield should work for views even if _parentView is null", function() {
<ide> view = EmberView.create({
<ide> layout: compile('Layout: {{yield}}'),
<ide> template: compile("View Content")
<ide> QUnit.test("yield should work for views even if _parentView is null", function()
<ide>
<ide> });
<ide>
<del>QUnit.test("simple bindings inside of a yielded template should work properly when the yield is nested inside of another view", function() {
<add>QUnit.skip("simple bindings inside of a yielded template should work properly when the yield is nested inside of another view", function() {
<ide> view = EmberView.create({
<ide> layout: compile('{{#if view.falsy}}{{else}}{{yield}}{{/if}}'),
<ide> template: compile("{{view.text}}"),
<ide> QUnit.test("simple bindings inside of a yielded template should work properly wh
<ide> equal(view.$().text(), "ohai");
<ide> });
<ide>
<del>QUnit.test("nested simple bindings inside of a yielded template should work properly when the yield is nested inside of another view", function() {
<add>QUnit.skip("nested simple bindings inside of a yielded template should work properly when the yield is nested inside of another view", function() {
<ide> view = EmberView.create({
<ide> layout: compile('{{#if view.falsy}}{{else}}{{yield}}{{/if}}'),
<ide> template: compile("{{#if view.falsy}}{{else}}{{view.text}}{{/if}}"),
<ide> QUnit.module("ember-htmlbars: Component {{yield}}", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("yield with nested components (#3220)", function() {
<add>QUnit.skip("yield with nested components (#3220)", function() {
<ide> var count = 0;
<ide> var InnerComponent = Component.extend({
<ide> layout: compile("{{yield}}"),
<ide> QUnit.test("yield with nested components (#3220)", function() {
<ide> equal(view.$('div > span').text(), "Hello world");
<ide> });
<ide>
<del>QUnit.test("yield works inside a conditional in a component that has Ember._Metamorph mixed in", function() {
<add>QUnit.skip("yield works inside a conditional in a component that has Ember._Metamorph mixed in", function() {
<ide> var component = Component.extend(Ember._Metamorph, {
<ide> item: "inner",
<ide> layout: compile("<p>{{item}}</p>{{#if item}}<p>{{yield}}</p>{{/if}}")
<ide><path>packages/ember-htmlbars/tests/hooks/element_test.js
<ide> QUnit.module('ember-htmlbars: element hook', {
<ide> }
<ide> });
<ide>
<del>QUnit.test('allows unbound usage within an element', function() {
<add>QUnit.skip('allows unbound usage within an element', function() {
<ide> expect(4);
<ide>
<ide> function someHelper(params, hash, options, env) {
<ide> QUnit.test('allows unbound usage within an element', function() {
<ide> equal(view.$('.foo').length, 1, 'class attribute was added by helper');
<ide> });
<ide>
<del>QUnit.test('allows unbound usage within an element from property', function() {
<add>QUnit.skip('allows unbound usage within an element from property', function() {
<ide> expect(2);
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test('allows unbound usage within an element from property', function() {
<ide> equal(view.$('.foo').length, 1, 'class attribute was added by helper');
<ide> });
<ide>
<del>QUnit.test('allows unbound usage within an element creating multiple attributes', function() {
<add>QUnit.skip('allows unbound usage within an element creating multiple attributes', function() {
<ide> expect(2);
<ide>
<ide> view = EmberView.create({
<ide><path>packages/ember-htmlbars/tests/integration/binding_integration_test.js
<ide> QUnit.test("should be able to update when bound property updates", function() {
<ide> equal(view.$('i').text(), 'second, second - computed', "view rerenders when bound properties change");
<ide> });
<ide>
<del>QUnit.test('should cleanup bound properties on rerender', function() {
<add>QUnit.skip('should cleanup bound properties on rerender', function() {
<ide> view = EmberView.create({
<ide> controller: EmberObject.create({ name: 'wycats' }),
<ide> template: compile('{{name}}')
<ide> QUnit.test('should cleanup bound properties on rerender', function() {
<ide> equal(view._childViews.length, 1);
<ide> });
<ide>
<del>QUnit.test("should update bound values after view's parent is removed and then re-appended", function() {
<add>QUnit.skip("should update bound values after view's parent is removed and then re-appended", function() {
<ide> expectDeprecation("Setting `childViews` on a Container is deprecated.");
<ide>
<ide> var controller = EmberObject.create();
<ide> QUnit.test("should update bound values after view's parent is removed and then r
<ide> runDestroy(parentView);
<ide> });
<ide>
<del>QUnit.test('should accept bindings as a string or an Ember.Binding', function() {
<add>QUnit.skip('should accept bindings as a string or an Ember.Binding', function() {
<ide> var ViewWithBindings = EmberView.extend({
<ide> oneWayBindingTestBinding: Binding.oneWay('context.direction'),
<ide> twoWayBindingTestBinding: Binding.from('context.direction'),
<ide><path>packages/ember-htmlbars/tests/integration/block_params_test.js
<ide> QUnit.module("ember-htmlbars: block params", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("should raise error if helper not available", function() {
<add>QUnit.skip("should raise error if helper not available", function() {
<ide> view = View.create({
<ide> template: compile('{{#shouldfail}}{{/shouldfail}}')
<ide> });
<ide> QUnit.test("should raise error if helper not available", function() {
<ide>
<ide> });
<ide>
<del>QUnit.test("basic block params usage", function() {
<add>QUnit.skip("basic block params usage", function() {
<ide> view = View.create({
<ide> committer: { name: "rwjblue" },
<ide> template: compile('{{#alias view.committer.name as |name|}}name: {{name}}, length: {{name.length}}{{/alias}}')
<ide> QUnit.test("basic block params usage", function() {
<ide> equal(view.$().text(), "name: krisselden, length: 10");
<ide> });
<ide>
<del>QUnit.test("nested block params shadow correctly", function() {
<add>QUnit.skip("nested block params shadow correctly", function() {
<ide> view = View.create({
<ide> context: { name: "ebryn" },
<ide> committer1: { name: "trek" },
<ide> QUnit.test("nested block params shadow correctly", function() {
<ide> equal(view.$().text(), "ebryn[trek[machty]trek]ebryn[machty[trek]machty]ebryn");
<ide> });
<ide>
<del>QUnit.test("components can yield values", function() {
<add>QUnit.skip("components can yield values", function() {
<ide> registry.register('template:components/x-alias', compile('{{yield param.name}}'));
<ide>
<ide> view = View.create({
<ide><path>packages/ember-htmlbars/tests/integration/escape_integration_test.js
<ide> QUnit.test('should read from an Object.create(null)', function() {
<ide> equal(view.$().text(), 'baz');
<ide> });
<ide>
<del>QUnit.test('should escape HTML in primitive value contexts when using normal mustaches', function() {
<add>QUnit.skip('should escape HTML in primitive value contexts when using normal mustaches', function() {
<ide> view = EmberView.create({
<ide> context: '<b>Max</b><b>James</b>',
<ide> template: compile('{{this}}')
<ide> QUnit.test('should escape HTML in primitive value contexts when using normal mus
<ide> equal(view.$('i').length, 0, 'does not create an element when value is updated');
<ide> });
<ide>
<del>QUnit.test('should not escape HTML in primitive value contexts when using triple mustaches', function() {
<add>QUnit.skip('should not escape HTML in primitive value contexts when using triple mustaches', function() {
<ide> view = EmberView.create({
<ide> context: '<b>Max</b><b>James</b>',
<ide> template: compile('{{{this}}}')
<ide><path>packages/ember-htmlbars/tests/integration/select_in_template_test.js
<ide> QUnit.module("ember-htmlbars: Ember.Select - usage inside templates", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("works from a template with bindings [DEPRECATED]", function() {
<add>QUnit.skip("works from a template with bindings [DEPRECATED]", function() {
<ide> var Person = EmberObject.extend({
<ide> id: null,
<ide> firstName: null,
<ide> QUnit.test("works from a template", function() {
<ide> equal(select.get('selection'), erik, "Selection was maintained after new option was added");
<ide> });
<ide>
<del>QUnit.test("upon content change, the DOM should reflect the selection (#481)", function() {
<add>QUnit.skip("upon content change, the DOM should reflect the selection (#481)", function() {
<ide> var userOne = { name: 'Mike', options: Ember.A(['a', 'b']), selectedOption: 'a' };
<ide> var userTwo = { name: 'John', options: Ember.A(['c', 'd']), selectedOption: 'd' };
<ide>
<ide> QUnit.test("upon content change, the DOM should reflect the selection (#481)", f
<ide> equal(selectEl.selectedIndex, 1, "The DOM reflects the correct selection");
<ide> });
<ide>
<del>QUnit.test("upon content change with Array-like content, the DOM should reflect the selection", function() {
<add>QUnit.skip("upon content change with Array-like content, the DOM should reflect the selection", function() {
<ide> var tom = { id: 4, name: 'Tom' };
<ide> var sylvain = { id: 5, name: 'Sylvain' };
<ide>
<ide> function testValueBinding(templateString) {
<ide> equal(selectEl.selectedIndex, 1, "The DOM is updated to reflect the new selection");
<ide> }
<ide>
<del>QUnit.test("select element should correctly initialize and update selectedIndex and bound properties when using valueBinding [DEPRECATED]", function() {
<add>QUnit.skip("select element should correctly initialize and update selectedIndex and bound properties when using valueBinding [DEPRECATED]", function() {
<ide> expectDeprecation(/You're attempting to render a view by passing .+Binding to a view helper, but this syntax is deprecated./);
<ide>
<ide> testValueBinding(
<ide> QUnit.test("select element should correctly initialize and update selectedIndex
<ide> );
<ide> });
<ide>
<del>QUnit.test("select element should correctly initialize and update selectedIndex and bound properties when using a bound value", function() {
<add>QUnit.skip("select element should correctly initialize and update selectedIndex and bound properties when using valueBinding", function() {
<ide> testValueBinding(
<ide> '{{view view.selectView viewName="select"' +
<ide> ' content=view.collection' +
<ide> function testSelectionBinding(templateString) {
<ide> equal(select.$('option:eq(1)').prop('selected'), true, "Selected property is set to proper option");
<ide> }
<ide>
<del>QUnit.test("select element should correctly initialize and update selectedIndex and bound properties when using selectionBinding [DEPRECATED]", function() {
<add>QUnit.skip("select element should correctly initialize and update selectedIndex and bound properties when using selectionBinding [DEPRECATED]", function() {
<ide> expectDeprecation(/You're attempting to render a view by passing .+Binding to a view helper, but this syntax is deprecated./);
<ide>
<ide> testSelectionBinding(
<ide> QUnit.test("select element should correctly initialize and update selectedIndex
<ide> );
<ide> });
<ide>
<del>QUnit.test("select element should correctly initialize and update selectedIndex and bound properties when using a bound selection", function() {
<add>QUnit.skip("select element should correctly initialize and update selectedIndex and bound properties when using a bound selection", function() {
<ide> testSelectionBinding(
<ide> '{{view view.selectView viewName="select"' +
<ide> ' content=view.collection' +
<ide> QUnit.test("select element should correctly initialize and update selectedIndex
<ide> );
<ide> });
<ide>
<del>QUnit.test("select element should correctly initialize and update selectedIndex and bound properties when using selectionBinding and optionValuePath with custom path", function() {
<add>QUnit.skip("select element should correctly initialize and update selectedIndex and bound properties when using selectionBinding and optionValuePath with custom path", function() {
<ide> var templateString = '{{view view.selectView viewName="select"' +
<ide> ' content=view.collection' +
<ide> ' optionLabelPath="content.name"' +
<ide><path>packages/ember-htmlbars/tests/integration/with_view_test.js
<ide> QUnit.module('ember-htmlbars: {{#with}} and {{#view}} integration', {
<ide> }
<ide> });
<ide>
<del>QUnit.test('View should update when the property used with the #with helper changes [DEPRECATED]', function() {
<add>QUnit.skip('View should update when the property used with the #with helper changes [DEPRECATED]', function() {
<ide> registry.register('template:foo', compile('<h1 id="first">{{#with view.content}}{{wham}}{{/with}}</h1>'));
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test('View should update when the property used with the #with helper chan
<ide> equal(view.$('#first').text(), 'bazam', 'view updates when a bound property changes');
<ide> });
<ide>
<del>QUnit.test('should expose a view keyword [DEPRECATED]', function() {
<add>QUnit.skip('should expose a view keyword [DEPRECATED]', function() {
<ide> var templateString = '{{#with view.differentContent}}{{view.foo}}{{#view baz="bang"}}{{view.baz}}{{/view}}{{/with}}';
<ide> view = EmberView.create({
<ide> container: container,
<ide> QUnit.test('should expose a view keyword [DEPRECATED]', function() {
<ide> equal(view.$().text(), 'barbang', 'renders values from view and child view');
<ide> });
<ide>
<del>QUnit.test('bindings can be `this`, in which case they *are* the current context [DEPRECATED]', function() {
<add>QUnit.skip('bindings can be `this`, in which case they *are* the current context [DEPRECATED]', function() {
<ide> view = EmberView.create({
<ide> museumOpen: true,
<ide>
<ide> QUnit.test('bindings can be `this`, in which case they *are* the current context
<ide> equal(trim(view.$().text()), 'Name: SFMoMA Price: $20', 'should print baz twice');
<ide> });
<ide>
<del>QUnit.test('child views can be inserted inside a bind block', function() {
<add>QUnit.skip('child views can be inserted inside a bind block', function() {
<ide> registry.register('template:nester', compile('<h1 id="hello-world">Hello {{world}}</h1>{{view view.bqView}}'));
<ide> registry.register('template:nested', compile('<div id="child-view">Goodbye {{#with content as thing}}{{thing.blah}} {{view view.otherView}}{{/with}} {{world}}</div>'));
<ide> registry.register('template:other', compile('cruel'));
<ide> QUnit.test('views render their template in the context of the parent view\'s con
<ide> equal(view.$('h1').text(), 'Lana del Heeeyyyyyy', 'renders properties from parent context');
<ide> });
<ide>
<del>QUnit.test('views make a view keyword available that allows template to reference view context', function() {
<add>QUnit.skip('views make a view keyword available that allows template to reference view context', function() {
<ide> registry.register('template:parent', compile('<h1>{{#with view.content as person}}{{#view person.subview}}{{view.firstName}} {{person.lastName}}{{/view}}{{/with}}</h1>'));
<ide>
<ide> view = EmberView.create({
<ide><path>packages/ember-htmlbars/tests/system/append-templated-view-test.js
<ide> QUnit.module('ember-htmlbars: appendTemplatedView', {
<ide> }
<ide> });
<ide>
<del>QUnit.test('can accept a view instance', function() {
<add>QUnit.skip('can accept a view instance', function() {
<ide> var controller = {
<ide> someProp: 'controller context',
<ide> someView: EmberView.create({
<ide> QUnit.test('can accept a view instance', function() {
<ide> equal(view.$().text(), 'controller context - controller context');
<ide> });
<ide>
<del>QUnit.test('can accept a view factory', function() {
<add>QUnit.skip('can accept a view factory', function() {
<ide> var controller = {
<ide> someProp: 'controller context',
<ide> someView: EmberView.extend({
<ide> QUnit.test('can accept a view factory', function() {
<ide> equal(view.$().text(), 'controller context - controller context');
<ide> });
<ide>
<del>QUnit.test('does change the context if the view factory has a controller specified', function() {
<add>QUnit.skip('does change the context if the view factory has a controller specified', function() {
<ide> var controller = {
<ide> someProp: 'controller context',
<ide> someView: EmberView.extend({
<ide> QUnit.test('does change the context if the view factory has a controller specifi
<ide> equal(view.$().text(), 'controller context - view local controller context');
<ide> });
<ide>
<del>QUnit.test('does change the context if a component factory is used', function() {
<add>QUnit.skip('does change the context if a component factory is used', function() {
<ide> var controller = {
<ide> someProp: 'controller context',
<ide> someView: EmberComponent.extend({
<ide> QUnit.test('does change the context if a component factory is used', function()
<ide> equal(view.$().text(), 'controller context - view local controller context');
<ide> });
<ide>
<del>QUnit.test('does change the context if a component instanced is used', function() {
<add>QUnit.skip('does change the context if a component instanced is used', function() {
<ide> var controller = {
<ide> someProp: 'controller context',
<ide> someView: EmberComponent.create({
<ide><path>packages/ember-htmlbars/tests/system/lookup-helper_test.js
<ide> QUnit.test('does not lookup in the container if the name does not contain a dash
<ide> equal(actual, undefined, 'does not blow up if view does not have a container');
<ide> });
<ide>
<del>QUnit.test('does a lookup in the container if the name contains a dash (and helper is not found in env)', function() {
<add>QUnit.skip('does a lookup in the container if the name contains a dash (and helper is not found in env)', function() {
<ide> var env = generateEnv();
<ide> var view = {
<ide> container: generateContainer()
<ide> QUnit.test('does a lookup in the container if the name contains a dash (and help
<ide> equal(actual, someName, 'does not wrap provided function if `isHTMLBars` is truthy');
<ide> });
<ide>
<del>QUnit.test('wraps helper from container in a Handlebars compat helper', function() {
<add>QUnit.skip('wraps helper from container in a Handlebars compat helper', function() {
<ide> expect(2);
<ide> var env = generateEnv();
<ide> var view = {
<ide> QUnit.test('wraps helper from container in a Handlebars compat helper', function
<ide> ok(called, 'HTMLBars compatible wrapper is wraping the provided function');
<ide> });
<ide>
<del>QUnit.test('asserts if component-lookup:main cannot be found', function() {
<add>QUnit.skip('asserts if component-lookup:main cannot be found', function() {
<ide> var env = generateEnv();
<ide> var view = {
<ide> container: generateContainer()
<ide> QUnit.test('asserts if component-lookup:main cannot be found', function() {
<ide> }, 'Could not find \'component-lookup:main\' on the provided container, which is necessary for performing component lookups');
<ide> });
<ide>
<del>QUnit.test('registers a helper in the container if component is found', function() {
<add>QUnit.skip('registers a helper in the container if component is found', function() {
<ide> var env = generateEnv();
<ide> var view = {
<ide> container: generateContainer()
<ide><path>packages/ember-htmlbars/tests/system/make_bound_helper_test.js
<ide> QUnit.module("ember-htmlbars: makeBoundHelper", {
<ide> }
<ide> });
<ide>
<del>QUnit.test("should update bound helpers in a subexpression when properties change", function() {
<add>QUnit.skip("should update bound helpers in a subexpression when properties change", function() {
<ide> registry.register('helper:x-dasherize', makeBoundHelper(function(params, hash, options, env) {
<ide> return dasherize(params[0]);
<ide> }));
<ide> QUnit.test("should update bound helpers in a subexpression when properties chang
<ide> equal(view.$('div[data-foo="not-thing"]').text(), 'notThing', "helper output is correct");
<ide> });
<ide>
<del>QUnit.test("should update bound helpers when properties change", function() {
<add>QUnit.skip("should update bound helpers when properties change", function() {
<ide> registry.register('helper:x-capitalize', makeBoundHelper(function(params, hash, options, env) {
<ide> return params[0].toUpperCase();
<ide> }));
<ide> QUnit.test("should update bound helpers when properties change", function() {
<ide> equal(view.$().text(), 'WES', "helper output updated");
<ide> });
<ide>
<del>QUnit.test("should update bound helpers when hash properties change", function() {
<add>QUnit.skip("should update bound helpers when hash properties change", function() {
<ide> registerRepeatHelper();
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("should update bound helpers when hash properties change", function()
<ide> equal(view.$().text(), 'YoYoYoYoYo', "helper output updated");
<ide> });
<ide>
<del>QUnit.test("bound helpers should support keywords", function() {
<add>QUnit.skip("bound helpers should support keywords", function() {
<ide> registry.register('helper:x-capitalize', makeBoundHelper(function(params, hash, options, env) {
<ide> return params[0].toUpperCase();
<ide> }));
<ide> QUnit.test("bound helpers should not process `fooBinding` style hash properties"
<ide> runAppend(view);
<ide> });
<ide>
<del>QUnit.test("bound helpers should support multiple bound properties", function() {
<add>QUnit.skip("bound helpers should support multiple bound properties", function() {
<ide>
<ide> registry.register('helper:x-combine', makeBoundHelper(function(params, hash, options, env) {
<ide> return params.join('');
<ide> QUnit.test("bound helpers can be invoked with zero args", function() {
<ide> equal(view.$().text(), 'TROLOLOL and bork', "helper output is correct");
<ide> });
<ide>
<del>QUnit.test("bound helpers should not be invoked with blocks", function() {
<add>QUnit.skip("bound helpers should not be invoked with blocks", function() {
<ide> registerRepeatHelper();
<ide> view = EmberView.create({
<ide> container: container,
<ide> QUnit.test("bound helpers should not be invoked with blocks", function() {
<ide> }, /makeBoundHelper generated helpers do not support use with blocks/i);
<ide> });
<ide>
<del>QUnit.test("shouldn't treat raw numbers as bound paths", function() {
<add>QUnit.skip("shouldn't treat raw numbers as bound paths", function() {
<ide> registry.register('helper:x-sum', makeBoundHelper(function(params) {
<ide> return params[0] + params[1];
<ide> }));
<ide> QUnit.test("shouldn't treat raw numbers as bound paths", function() {
<ide> equal(view.$().text(), '6 5 11', "helper still updates as expected");
<ide> });
<ide>
<del>QUnit.test("should have correct argument types", function() {
<add>QUnit.skip("should have correct argument types", function() {
<ide> registry.register('helper:get-type', makeBoundHelper(function(params) {
<ide> return typeof params[0];
<ide> }));
<ide><path>packages/ember-htmlbars/tests/system/make_view_helper_test.js
<ide> import makeViewHelper from "ember-htmlbars/system/make-view-helper";
<ide>
<ide> QUnit.module("ember-htmlbars: makeViewHelper");
<ide>
<del>QUnit.test("makes helpful assertion when called with invalid arguments", function() {
<add>QUnit.skip("makes helpful assertion when called with invalid arguments", function() {
<ide> var viewClass = { toString() { return 'Some Random Class'; } };
<ide>
<ide> var helper = makeViewHelper(viewClass); | 27 |
Javascript | Javascript | add start of {{render}} documentation | 0f740430c0fcfdeb41d9c7e5bb412651db688b18 | <ide><path>packages/ember-routing/lib/helpers/render.js
<ide> require('ember-handlebars/helpers/view');
<ide>
<ide> Ember.onLoad('Ember.Handlebars', function(Handlebars) {
<ide>
<add> /**
<add> Renders the named template in the current context using the singleton
<add> instance of the same-named controller.
<add>
<add> If a view class with the same name exists, uses the view class.
<add>
<add> If a `model` is specified, it becomes the model for that controller.
<add>
<add> The default target for `{{action}}`s in the rendered template is the
<add> named controller.
<add>
<add> @method action
<add> @for Ember.Handlebars.helpers
<add> @param {String} actionName
<add> @param {Object?} model
<add> @param {Hash} options
<add> */
<ide> Ember.Handlebars.registerHelper('render', function(name, contextString, options) {
<ide> Ember.assert("You must pass a template to render", arguments.length >= 2);
<ide> var container, router, controller, view, context; | 1 |
Python | Python | remove commented line | 53c6c9795c8c1e6e90d8c1bee216e14c14e68b70 | <ide><path>libcloud/compute/drivers/dimensiondata.py
<ide> def list_images(self, location=None):
<ide> if location is not None:
<ide> params['datacenterId'] = self._location_to_location_id(location)
<ide>
<del> # return self._to_images(
<del> # self.connection.request_with_orgId_api_2(
<del> # 'image/osImage',
<del> # params=params)
<del> # .object)
<del>
<del> images = self._to_images(
<add> return self._to_images(
<ide> self.connection.request_with_orgId_api_2(
<ide> 'image/osImage',
<ide> params=params)
<ide> .object)
<ide>
<del> return images
<del>
<ide> def list_sizes(self, location=None):
<ide> """
<ide> return a list of available sizes | 1 |
Javascript | Javascript | add reach24 app to react native showcase | d03d455cc46f7ccfeb3fa99ccd27a3248ecc4554 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/raindrop.io-keep-your-favorites/id1021913807',
<ide> author: 'Mussabekov Rustem',
<ide> },
<add> {
<add> name: 'Reach24',
<add> icon: 'http://a4.mzstatic.com/us/r30/Purple49/v4/35/0e/c8/350ec8b4-c725-4b03-3e9e-131b85e72166/icon175x175.jpeg',
<add> linkAppStore: 'https://itunes.apple.com/us/app/reach24x7/id962380755?ls=1&mt=8',
<add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.vantage.reachtwo&hl=en',
<add> author: 'Spritle Software',
<add> },
<ide> {
<ide> name: 'ReactTo36',
<ide> icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple5/v4/e3/c8/79/e3c87934-70c6-4974-f20d-4adcfc68d71d/mzl.wevtbbkq.png', | 1 |
Python | Python | fix _to_port to make it work with old versions | d34b3f0734befd1dfd8b7c044af5cf911bcd69b9 | <ide><path>libcloud/compute/drivers/openstack.py
<ide> def _to_port(self, element):
<ide> mac_address=element['mac_address'],
<ide> name=element['name'],
<ide> network_id=element['network_id'],
<del> project_id=element['project_id'],
<del> port_security_enabled=element['port_security_enabled'],
<del> revision_number=element['revision_number'],
<add> project_id=element.get('project_id', None),
<add> port_security_enabled=element.get('port_security_enabled',
<add> None),
<add> revision_number=element.get('revision_number', None),
<ide> security_groups=element['security_groups'],
<del> tags=element['tags'],
<add> tags=element.get('tags', None),
<ide> tenant_id=element['tenant_id'],
<ide> updated=updated,
<ide> )
<ide> def _to_floating_ips(self, obj):
<ide> def _to_floating_ip(self, obj):
<ide> instance_id = None
<ide>
<add> print(obj)
<ide> # In neutron version prior to 13.0.0 port_details does not exists
<del> if 'port_details' not in obj and 'port_id' in obj:
<add> if 'port_details' not in obj and 'port_id' in obj and obj['port_id']:
<ide> port = self.connection.driver.ex_get_port(obj['port_id'])
<ide> if port:
<ide> obj['port_details'] = {"device_id": port.extra["device_id"], | 1 |
Java | Java | release cached item in channelsendoperator | 9c48d63082e371da4d0870f6e222db35a4412362 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ChannelSendOperator.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import reactor.core.publisher.Operators;
<ide> import reactor.util.context.Context;
<ide>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> public void request(long n) {
<ide> }
<ide>
<ide> private boolean emitCachedSignals() {
<del> if (this.item != null) {
<del> requiredWriteSubscriber().onNext(this.item);
<del> }
<ide> if (this.error != null) {
<del> requiredWriteSubscriber().onError(this.error);
<add> try {
<add> requiredWriteSubscriber().onError(this.error);
<add> }
<add> finally {
<add> releaseCachedItem();
<add> }
<ide> return true;
<ide> }
<add> T item = this.item;
<add> this.item = null;
<add> if (item != null) {
<add> requiredWriteSubscriber().onNext(item);
<add> }
<ide> if (this.completed) {
<ide> requiredWriteSubscriber().onComplete();
<ide> return true;
<ide> public void cancel() {
<ide> Subscription s = this.subscription;
<ide> if (s != null) {
<ide> this.subscription = null;
<del> s.cancel();
<add> try {
<add> s.cancel();
<add> }
<add> finally {
<add> releaseCachedItem();
<add> }
<add> }
<add> }
<add>
<add> private void releaseCachedItem() {
<add> synchronized (this) {
<add> Object item = this.item;
<add> if (item instanceof DataBuffer) {
<add> DataBufferUtils.release((DataBuffer) item);
<add> }
<add> this.item = null;
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.http.server.reactive;
<ide>
<add>import java.nio.charset.StandardCharsets;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.concurrent.Executors;
<ide> import java.util.concurrent.TimeUnit;
<ide>
<add>import io.netty.buffer.ByteBufAllocator;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.reactivestreams.Publisher;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<add>import reactor.core.publisher.BaseSubscriber;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.core.publisher.Signal;
<ide>
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertNotNull;
<del>import static org.junit.Assert.assertSame;
<del>import static org.junit.Assert.assertTrue;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.LeakAwareDataBufferFactory;
<add>import org.springframework.core.io.buffer.NettyDataBufferFactory;
<add>
<add>import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> public void setUp() throws Exception {
<ide> this.writer = new OneByOneAsyncWriter();
<ide> }
<ide>
<del> private <T> Mono<Void> sendOperator(Publisher<String> source){
<del> return new ChannelSendOperator<>(source, writer::send);
<del> }
<ide>
<ide> @Test
<ide> public void errorBeforeFirstItem() throws Exception {
<ide> public void errorAfterMultipleItems() throws Exception {
<ide> assertSame(error, this.writer.error);
<ide> }
<ide>
<add> @Test // gh-22720
<add> public void cancelWhileItemCached() {
<add> NettyDataBufferFactory delegate = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
<add> LeakAwareDataBufferFactory bufferFactory = new LeakAwareDataBufferFactory(delegate);
<add>
<add> ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>(
<add> Mono.fromCallable(() -> {
<add> DataBuffer dataBuffer = bufferFactory.allocateBuffer();
<add> dataBuffer.write("foo", StandardCharsets.UTF_8);
<add> return dataBuffer;
<add> }),
<add> publisher -> {
<add> ZeroDemandSubscriber subscriber = new ZeroDemandSubscriber();
<add> publisher.subscribe(subscriber);
<add> return Mono.never();
<add> });
<add>
<add> BaseSubscriber<Void> subscriber = new BaseSubscriber<Void>() {};
<add> operator.subscribe(subscriber);
<add> subscriber.cancel();
<add>
<add> bufferFactory.checkForLeaks();
<add> }
<add>
<add> @Test // gh-22720
<add> public void errorWhileItemCached() {
<add> NettyDataBufferFactory delegate = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
<add> LeakAwareDataBufferFactory bufferFactory = new LeakAwareDataBufferFactory(delegate);
<add> ZeroDemandSubscriber writeSubscriber = new ZeroDemandSubscriber();
<add>
<add> ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>(
<add> Flux.create(sink -> {
<add> DataBuffer dataBuffer = bufferFactory.allocateBuffer();
<add> dataBuffer.write("foo", StandardCharsets.UTF_8);
<add> sink.next(dataBuffer);
<add> sink.error(new IllegalStateException("err"));
<add> }),
<add> publisher -> {
<add> publisher.subscribe(writeSubscriber);
<add> return Mono.never();
<add> });
<add>
<add>
<add> operator.subscribe(new BaseSubscriber<Void>() {});
<add> try {
<add> writeSubscriber.signalDemand(1); // Let cached signals ("foo" and error) be published..
<add> }
<add> catch (Throwable ex) {
<add> assertNotNull(ex.getCause());
<add> assertEquals("err", ex.getCause().getMessage());
<add> }
<add>
<add> bufferFactory.checkForLeaks();
<add> }
<add>
<add>
<add> private <T> Mono<Void> sendOperator(Publisher<String> source){
<add> return new ChannelSendOperator<>(source, writer::send);
<add> }
<add>
<ide>
<ide> private static class OneByOneAsyncWriter {
<ide>
<ide> public void onComplete() {
<ide> }
<ide> }
<ide>
<add>
<add> private static class ZeroDemandSubscriber extends BaseSubscriber<DataBuffer> {
<add>
<add>
<add> @Override
<add> protected void hookOnSubscribe(Subscription subscription) {
<add> // Just subscribe without requesting
<add> }
<add>
<add> public void signalDemand(long demand) {
<add> upstream().request(demand);
<add> }
<add> }
<add>
<ide> } | 2 |
Python | Python | remove test that fails on windows | 9355b1c4c1daea10f32819111d36030ddd84f217 | <ide><path>numpy/core/tests/test_regression.py
<ide> def check_intp(self,level=rlevel):
<ide> assert_equal(255,N.intp('0xFF',16))
<ide> assert_equal(1024,N.intp(1024))
<ide>
<del> def check_fromfile(self,level=rlevel):
<del> """Ticket #103"""
<del> from tempfile import TemporaryFile
<del> import os
<del>
<del> dt = '<f8'
<del> x = N.random.randn(2048,39).astype(dt)
<del> f = TemporaryFile()
<del> x.tofile(f)
<del> f.seek(0)
<del> y = N.fromfile(f,dtype=dt)
<del> assert_equal(os.fstat(f.fileno())[6], x.size * 8)
<del> assert_equal(x.size, y.size)
<del>
<ide> def check_endian_bool_indexing(self,level=rlevel):
<ide> """Ticket #105"""
<ide> a = N.arange(10.,dtype='>f8') | 1 |
PHP | PHP | use a tap | 067f6a5173c1527ae6e109f0ba891b104392f7a9 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function findOrFail($id, $columns = ['*'])
<ide> return $result;
<ide> }
<ide>
<del> throw (new ModelNotFoundException)->setModel(get_class($this->model), $id);
<add> throw (new ModelNotFoundException)->setModel(
<add> get_class($this->model), $id
<add> );
<ide> }
<ide>
<ide> /**
<ide> public function firstOrCreate(array $attributes, array $values = [])
<ide> */
<ide> public function updateOrCreate(array $attributes, array $values = [])
<ide> {
<del> $instance = $this->firstOrNew($attributes);
<del>
<del> $instance->fill($values)->save();
<del>
<del> return $instance;
<add> return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
<add> $instance->fill($values)->save();
<add> });
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | update sponsor url | c5be86a6dbf3d21b00a296af5994fa075826bf0b | <ide><path>README.md
<ide> Please see the [security policy][security-policy].
<ide> [cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png
<ide>
<ide> [sentry-url]: https://getsentry.com/welcome/
<del>[stream-url]: https://getstream.io/?utm_source=drf&utm_medium=sponsorship&utm_content=developer
<add>[stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage
<ide> [rollbar-url]: https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial
<ide> [esg-url]: https://software.esg-usa.com/
<ide> [retool-url]: https://retool.com/?utm_source=djangorest&utm_medium=sponsorship
<ide><path>docs/index.md
<ide> continued development by **[signing up for a paid plan][funding]**.
<ide>
<ide> <ul class="premium-promo promo">
<ide> <li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<del> <li><a href="https://getstream.io/?utm_source=drf&utm_medium=sponsorship&utm_content=developer" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<add> <li><a href="https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<ide> <li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
<ide> <li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<ide> <li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
<ide> continued development by **[signing up for a paid plan][funding]**.
<ide> </ul>
<ide> <div style="clear: both; padding-bottom: 20px;"></div>
<ide>
<del>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=sponsorship&utm_content=developer), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), and [CryptAPI](https://cryptapi.io).*
<add>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), and [CryptAPI](https://cryptapi.io).*
<ide>
<ide> ---
<ide> | 2 |
Javascript | Javascript | avoid cyclic dependency | 04174a3d7aaf8c838811efe74455f379e65d73aa | <ide><path>src/math/Box3.js
<ide> import { Vector3 } from './Vector3.js';
<del>import { Sphere } from './Sphere.js';
<ide>
<ide> /**
<ide> * @author bhouston / http://clara.io
<ide> Object.assign( Box3.prototype, {
<ide>
<ide> if ( target === undefined ) {
<ide>
<del> console.warn( 'THREE.Box3: .getBoundingSphere() target is now required' );
<del> target = new Sphere();
<add> console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
<add> //target = new Sphere(); // removed to avoid cyclic dependency
<ide>
<ide> }
<ide> | 1 |
Javascript | Javascript | stop v8 benchmark clobbering regexp | 50177fb13cae68067845cca7622798eb7a34f8e9 | <ide><path>benchmark/misc/v8-bench.js
<ide> global.print = function(s) {
<ide> console.log('misc/v8_bench.js %s', s);
<ide> };
<ide>
<del>global.load = function (x) {
<del> var source = fs.readFileSync(path.join(dir, x), 'utf8');
<del> vm.runInThisContext(source, x);
<del>}
<add>global.load = function(filename) {
<add> var source = fs.readFileSync(path.join(dir, filename), 'utf8');
<add> // deps/v8/benchmarks/regexp.js breaks console.log() because it clobbers
<add> // the RegExp global, Restore the original when the script is done.
<add> var $RegExp = global.RegExp;
<add> vm.runInThisContext(source, { filename: filename });
<add> global.RegExp = $RegExp;
<add>};
<ide>
<ide> load('run.js'); | 1 |
Python | Python | remove dead code | f0ce83ff67908806b6b85240d8a383b2306ab2e8 | <ide><path>numpy/distutils/misc_util.py
<ide> def add_installed_library(self, name, sources, install_dir, build_info=None):
<ide> """
<ide> if not build_info:
<ide> build_info = {}
<del> # self.add_library(name, sources)
<del> #else:
<del> # self.add_library(name, sources, **build_info)
<ide>
<ide> build_info = copy.copy(build_info)
<ide> name = name #+ '__OF__' + self.name
<ide> def get_numpy_include_dirs():
<ide> def get_npymath_info():
<ide> """Return a extra_info-compatible dict to link against the core npymath
<ide> library.
<del>
<add>
<ide> Example
<ide> -------
<ide> >>> npymath_info = get_npymath_info() | 1 |
Text | Text | add validate_<fieldname> bugfix to release notes | 30046cae8c64790d7ae0d9ca4d2faee1cd2968aa | <ide><path>docs/topics/release-notes.md
<ide> Major version numbers (x.0.0) are reserved for project milestones. No major poi
<ide> * `format_suffix_patterns()` now supports `include` style URL patterns.
<ide> * Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
<ide> * Bugfix: Support nullable FKs with `SlugRelatedField`.
<add>* Bugfix: Don't call custom validation methods if the field has an error.
<ide>
<ide> ### 2.1.16
<ide> | 1 |
Javascript | Javascript | remove unique requirement from username | aab3b98f5d0fd3dba0b75ef63c8c47247c718520 | <ide><path>models/User.js
<ide> var userSchema = new mongoose.Schema({
<ide> username: {
<ide> type: String,
<ide> default: '',
<del> unique: true,
<add> //unique: true,
<ide> lowercase: true,
<ide> trim: true
<ide> } | 1 |
Java | Java | add support for responseentity result handling | 9aa6f5caacac316c74e374550a387f222e7e1921 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java
<ide> import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
<ide> import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
<ide> import org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler;
<add>import org.springframework.web.reactive.result.method.annotation.ResponseEntityResultHandler;
<ide> import org.springframework.web.reactive.result.view.ViewResolutionResultHandler;
<ide> import org.springframework.web.reactive.result.view.ViewResolver;
<ide>
<ide> public SimpleHandlerAdapter simpleHandlerAdapter() {
<ide> }
<ide>
<ide> @Bean
<del> public ResponseBodyResultHandler responseBodyResultHandler() {
<del> return new ResponseBodyResultHandler(getMessageConverters(), mvcConversionService());
<add> public SimpleResultHandler simpleResultHandler() {
<add> return new SimpleResultHandler(mvcConversionService());
<ide> }
<ide>
<ide> @Bean
<del> public SimpleResultHandler simpleResultHandler() {
<del> return new SimpleResultHandler(mvcConversionService());
<add> public ResponseEntityResultHandler responseEntityResultHandler() {
<add> return new ResponseEntityResultHandler(getMessageConverters(), mvcConversionService(),
<add> mvcContentTypeResolver());
<add> }
<add>
<add> @Bean
<add> public ResponseBodyResultHandler responseBodyResultHandler() {
<add> return new ResponseBodyResultHandler(getMessageConverters(), mvcConversionService(),
<add> mvcContentTypeResolver());
<ide> }
<ide>
<ide> @Bean
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageConverterResultHandler.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.reactive.result.method.annotation;
<add>
<add>import java.util.List;
<add>import java.util.stream.Collectors;
<add>
<add>import org.reactivestreams.Publisher;
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.convert.ConversionService;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.http.converter.reactive.HttpMessageConverter;
<add>import org.springframework.http.server.reactive.ServerHttpResponse;
<add>import org.springframework.util.Assert;
<add>import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<add>import org.springframework.web.reactive.result.ContentNegotiatingResultHandlerSupport;
<add>import org.springframework.web.server.NotAcceptableStatusException;
<add>import org.springframework.web.server.ServerWebExchange;
<add>
<add>/**
<add> * Abstract base class for result handlers that handle return values by writing
<add> * to the response with {@link HttpMessageConverter}.
<add> *
<add> * @author Rossen Stoyanchev
<add> */
<add>public abstract class AbstractMessageConverterResultHandler extends ContentNegotiatingResultHandlerSupport {
<add>
<add> private final List<HttpMessageConverter<?>> messageConverters;
<add>
<add>
<add> /**
<add> * Constructor with message converters, a {@code ConversionService}, and a
<add> * {@code RequestedContentTypeResolver}.
<add> *
<add> * @param converters converters for writing the response body with
<add> * @param conversionService for converting other reactive types (e.g.
<add> * rx.Observable, rx.Single, etc.) to Flux or Mono
<add> * @param contentTypeResolver for resolving the requested content type
<add> */
<add> protected AbstractMessageConverterResultHandler(List<HttpMessageConverter<?>> converters,
<add> ConversionService conversionService, RequestedContentTypeResolver contentTypeResolver) {
<add>
<add> super(conversionService, contentTypeResolver);
<add> Assert.notEmpty(converters, "At least one message converter is required.");
<add> this.messageConverters = converters;
<add> }
<add>
<add> /**
<add> * Return the configured message converters.
<add> */
<add> public List<HttpMessageConverter<?>> getMessageConverters() {
<add> return this.messageConverters;
<add> }
<add>
<add>
<add> @SuppressWarnings("unchecked")
<add> protected Mono<Void> writeBody(ServerWebExchange exchange, Object body, ResolvableType bodyType) {
<add>
<add> Publisher<?> publisher;
<add> ResolvableType elementType;
<add>
<add> if (getConversionService().canConvert(bodyType.getRawClass(), Publisher.class)) {
<add> if (body != null) {
<add> publisher = getConversionService().convert(body, Publisher.class);
<add> }
<add> else {
<add> publisher = Mono.empty();
<add> }
<add> elementType = bodyType.getGeneric(0);
<add> if (Void.class.equals(elementType.getRawClass())) {
<add> return Mono.from((Publisher<Void>) publisher);
<add> }
<add> }
<add> else {
<add> publisher = Mono.justOrEmpty(body);
<add> elementType = bodyType;
<add> }
<add>
<add> List<MediaType> producibleTypes = getProducibleMediaTypes(elementType);
<add> MediaType bestMediaType = selectMediaType(exchange, producibleTypes);
<add>
<add> if (bestMediaType != null) {
<add> for (HttpMessageConverter<?> converter : getMessageConverters()) {
<add> if (converter.canWrite(elementType, bestMediaType)) {
<add> ServerHttpResponse response = exchange.getResponse();
<add> return converter.write((Publisher) publisher, elementType, bestMediaType, response);
<add> }
<add> }
<add> }
<add>
<add> return Mono.error(new NotAcceptableStatusException(producibleTypes));
<add> }
<add>
<add> private List<MediaType> getProducibleMediaTypes(ResolvableType elementType) {
<add> return getMessageConverters().stream()
<add> .filter(converter -> converter.canWrite(elementType, null))
<add> .flatMap(converter -> converter.getWritableMediaTypes().stream())
<add> .collect(Collectors.toList());
<add> }
<add>
<add>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandler.java
<ide> package org.springframework.web.reactive.result.method.annotation;
<ide>
<ide> import java.util.List;
<del>import java.util.Optional;
<del>import java.util.stream.Collectors;
<ide>
<del>import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.MethodParameter;
<del>import org.springframework.core.Ordered;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> import org.springframework.core.convert.ConversionService;
<del>import org.springframework.http.MediaType;
<ide> import org.springframework.http.converter.reactive.HttpMessageConverter;
<del>import org.springframework.http.server.reactive.ServerHttpResponse;
<del>import org.springframework.util.Assert;
<ide> import org.springframework.web.bind.annotation.ResponseBody;
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.reactive.HandlerResultHandler;
<ide> import org.springframework.web.reactive.accept.HeaderContentTypeResolver;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<del>import org.springframework.web.reactive.result.ContentNegotiatingResultHandlerSupport;
<del>import org.springframework.web.server.NotAcceptableStatusException;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide>
<ide> * with {@code @ResponseBody} writing to the body of the request or response with
<ide> * an {@link HttpMessageConverter}.
<ide> *
<del> * <p>By default the order for the result handler is set to 0. It is generally
<del> * safe and expected it will be ordered ahead of other result handlers since it
<del> * only gets involved based on the presence of an {@code @ResponseBody}
<del> * annotation.
<add> * <p>By default the order for the result handler is set to 100. It detects the
<add> * presence of an {@code @ResponseBody} annotation and should be ordered after
<add> * result handlers that look for a specific return type such as
<add> * {@code ResponseEntity}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @author Stephane Maldini
<ide> * @author Sebastien Deleuze
<ide> * @author Arjen Poutsma
<ide> */
<del>public class ResponseBodyResultHandler extends ContentNegotiatingResultHandlerSupport
<del> implements HandlerResultHandler, Ordered {
<del>
<del> private final List<HttpMessageConverter<?>> messageConverters;
<del>
<add>public class ResponseBodyResultHandler extends AbstractMessageConverterResultHandler
<add> implements HandlerResultHandler {
<ide>
<ide> /**
<ide> * Constructor with message converters and a {@code ConversionService} only
<ide> public ResponseBodyResultHandler(List<HttpMessageConverter<?>> converters,
<ide> public ResponseBodyResultHandler(List<HttpMessageConverter<?>> converters,
<ide> ConversionService conversionService, RequestedContentTypeResolver contentTypeResolver) {
<ide>
<del> super(conversionService, contentTypeResolver);
<del> Assert.notEmpty(converters, "At least one message converter is required.");
<del> this.messageConverters = converters;
<del> setOrder(0);
<add> super(converters, conversionService, contentTypeResolver);
<add> setOrder(100);
<ide> }
<ide>
<ide>
<del> /**
<del> * Return the configured message converters.
<del> */
<del> public List<HttpMessageConverter<?>> getMessageConverters() {
<del> return this.messageConverters;
<del> }
<del>
<ide> @Override
<ide> public boolean supports(HandlerResult result) {
<ide> Object handler = result.getHandler();
<ide> public boolean supports(HandlerResult result) {
<ide> }
<ide>
<ide> @Override
<del> @SuppressWarnings("unchecked")
<ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
<del>
<del> Publisher<?> publisher;
<del> ResolvableType elementType;
<del> ResolvableType returnType = result.getReturnValueType();
<del>
<del> if (getConversionService().canConvert(returnType.getRawClass(), Publisher.class)) {
<del> Optional<Object> optionalValue = result.getReturnValue();
<del> if (optionalValue.isPresent()) {
<del> publisher = getConversionService().convert(optionalValue.get(), Publisher.class);
<del> }
<del> else {
<del> publisher = Mono.empty();
<del> }
<del> elementType = returnType.getGeneric(0);
<del> if (Void.class.equals(elementType.getRawClass())) {
<del> return Mono.from((Publisher<Void>)publisher);
<del> }
<del> }
<del> else {
<del> publisher = Mono.justOrEmpty(result.getReturnValue());
<del> elementType = returnType;
<del> }
<del>
<del> List<MediaType> producibleTypes = getProducibleMediaTypes(elementType);
<del> MediaType bestMediaType = selectMediaType(exchange, producibleTypes);
<del>
<del> if (bestMediaType != null) {
<del> for (HttpMessageConverter<?> converter : this.messageConverters) {
<del> if (converter.canWrite(elementType, bestMediaType)) {
<del> ServerHttpResponse response = exchange.getResponse();
<del> return converter.write((Publisher) publisher, elementType, bestMediaType, response);
<del> }
<del> }
<del> }
<del>
<del> return Mono.error(new NotAcceptableStatusException(producibleTypes));
<del> }
<del>
<del> private List<MediaType> getProducibleMediaTypes(ResolvableType type) {
<del> return this.messageConverters.stream()
<del> .filter(converter -> converter.canWrite(type, null))
<del> .flatMap(converter -> converter.getWritableMediaTypes().stream())
<del> .collect(Collectors.toList());
<add> Object body = result.getReturnValue().orElse(null);
<add> ResolvableType bodyType = result.getReturnValueType();
<add> return writeBody(exchange, body, bodyType);
<ide> }
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.reactive.result.method.annotation;
<add>
<add>import java.util.List;
<add>import java.util.Optional;
<add>
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.convert.ConversionService;
<add>import org.springframework.http.HttpEntity;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.RequestEntity;
<add>import org.springframework.http.ResponseEntity;
<add>import org.springframework.http.converter.reactive.HttpMessageConverter;
<add>import org.springframework.util.Assert;
<add>import org.springframework.web.reactive.HandlerResult;
<add>import org.springframework.web.reactive.HandlerResultHandler;
<add>import org.springframework.web.reactive.accept.HeaderContentTypeResolver;
<add>import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<add>import org.springframework.web.server.ServerWebExchange;
<add>
<add>/**
<add> * Handles {@link HttpEntity} and {@link ResponseEntity} return values.
<add> *
<add> * <p>By default the order for this result handler is set to 0. It is generally
<add> * safe to place it early in the order as it looks for a concrete return type.
<add> *
<add> * @author Rossen Stoyanchev
<add> */
<add>public class ResponseEntityResultHandler extends AbstractMessageConverterResultHandler
<add> implements HandlerResultHandler {
<add>
<add> /**
<add> * Constructor with message converters and a {@code ConversionService} only
<add> * and creating a {@link HeaderContentTypeResolver}, i.e. using Accept header
<add> * to determine the requested content type.
<add> *
<add> * @param converters converters for writing the response body with
<add> * @param conversionService for converting to Flux and Mono from other reactive types
<add> */
<add> public ResponseEntityResultHandler(List<HttpMessageConverter<?>> converters,
<add> ConversionService conversionService) {
<add>
<add> this(converters, conversionService, new HeaderContentTypeResolver());
<add> }
<add>
<add> /**
<add> * Constructor with message converters, a {@code ConversionService}, and a
<add> * {@code RequestedContentTypeResolver}.
<add> *
<add> * @param converters converters for writing the response body with
<add> * @param conversionService for converting other reactive types (e.g.
<add> * rx.Observable, rx.Single, etc.) to Flux or Mono
<add> * @param contentTypeResolver for resolving the requested content type
<add> */
<add> public ResponseEntityResultHandler(List<HttpMessageConverter<?>> converters,
<add> ConversionService conversionService, RequestedContentTypeResolver contentTypeResolver) {
<add>
<add> super(converters, conversionService, contentTypeResolver);
<add> setOrder(0);
<add> }
<add>
<add>
<add> @Override
<add> public boolean supports(HandlerResult result) {
<add> ResolvableType returnType = result.getReturnValueType();
<add> return (HttpEntity.class.isAssignableFrom(returnType.getRawClass()) &&
<add> !RequestEntity.class.isAssignableFrom(returnType.getRawClass()));
<add> }
<add>
<add>
<add> @Override
<add> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
<add>
<add> Object body = null;
<add>
<add> Optional<Object> optional = result.getReturnValue();
<add> if (optional.isPresent()) {
<add> Assert.isInstanceOf(HttpEntity.class, optional.get());
<add> HttpEntity<?> httpEntity = (HttpEntity<?>) optional.get();
<add>
<add> if (httpEntity instanceof ResponseEntity) {
<add> ResponseEntity<?> responseEntity = (ResponseEntity<?>) httpEntity;
<add> exchange.getResponse().setStatusCode(responseEntity.getStatusCode());
<add> }
<add>
<add> HttpHeaders entityHeaders = httpEntity.getHeaders();
<add> HttpHeaders responseHeaders = exchange.getResponse().getHeaders();
<add>
<add> if (!entityHeaders.isEmpty()) {
<add> entityHeaders.entrySet().stream()
<add> .filter(entry -> responseHeaders.containsKey(entry.getKey()))
<add> .forEach(entry -> responseHeaders.put(entry.getKey(), entry.getValue()));
<add> }
<add>
<add> body = httpEntity.getBody();
<add> }
<add>
<add> ResolvableType bodyType = result.getReturnValueType().getGeneric(0);
<add> return writeBody(exchange, body, bodyType);
<add> }
<add>
<add>}
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/config/WebReactiveConfigurationTests.java
<ide> import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
<ide> import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
<ide> import org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler;
<add>import org.springframework.web.reactive.result.method.annotation.ResponseEntityResultHandler;
<ide> import org.springframework.web.reactive.result.view.HttpMessageConverterView;
<ide> import org.springframework.web.reactive.result.view.View;
<ide> import org.springframework.web.reactive.result.view.ViewResolutionResultHandler;
<ide> public void mvcConversionService() throws Exception {
<ide> service.canConvert(Observable.class, Flux.class);
<ide> }
<ide>
<add> @Test
<add> public void responseEntityResultHandler() throws Exception {
<add> ApplicationContext context = loadConfig(WebReactiveConfiguration.class);
<add>
<add> String name = "responseEntityResultHandler";
<add> ResponseEntityResultHandler handler = context.getBean(name, ResponseEntityResultHandler.class);
<add> assertNotNull(handler);
<add>
<add> assertEquals(0, handler.getOrder());
<add>
<add> List<HttpMessageConverter<?>> converters = handler.getMessageConverters();
<add> assertEquals(5, converters.size());
<add>
<add> assertHasConverter(converters, ByteBuffer.class, MediaType.APPLICATION_OCTET_STREAM);
<add> assertHasConverter(converters, String.class, MediaType.TEXT_PLAIN);
<add> assertHasConverter(converters, Resource.class, MediaType.IMAGE_PNG);
<add> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML);
<add> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_JSON);
<add>
<add> name = "mvcContentTypeResolver";
<add> RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
<add> assertSame(resolver, handler.getContentTypeResolver());
<add> }
<ide>
<ide> @Test
<ide> public void responseBodyResultHandler() throws Exception {
<ide> public void responseBodyResultHandler() throws Exception {
<ide> ResponseBodyResultHandler handler = context.getBean(name, ResponseBodyResultHandler.class);
<ide> assertNotNull(handler);
<ide>
<del> assertEquals(0, handler.getOrder());
<add> assertEquals(100, handler.getOrder());
<ide>
<ide> List<HttpMessageConverter<?>> converters = handler.getMessageConverters();
<ide> assertEquals(5, converters.size());
<ide> public void responseBodyResultHandler() throws Exception {
<ide> assertHasConverter(converters, Resource.class, MediaType.IMAGE_PNG);
<ide> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_XML);
<ide> assertHasConverter(converters, TestBean.class, MediaType.APPLICATION_JSON);
<add>
<add> name = "mvcContentTypeResolver";
<add> RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
<add> assertSame(resolver, handler.getContentTypeResolver());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java
<ide> public void serializeAsCompletableFuture() throws Exception {
<ide> serializeAsPojo("http://localhost:" + port + "/completable-future");
<ide> }
<ide>
<add> @Test
<add> @Ignore // Issue #119
<add> public void serializeAsMonoResponseEntity() throws Exception {
<add> serializeAsPojo("http://localhost:" + port + "/monoResponseEntity");
<add> }
<add>
<ide> @Test
<ide> public void serializeAsMono() throws Exception {
<ide> serializeAsPojo("http://localhost:" + port + "/mono");
<ide> public Observable<ByteBuffer> rawObservableResponseBody() {
<ide> return Observable.just(ByteBuffer.wrap("Hello!".getBytes()));
<ide> }
<ide>
<add> @RequestMapping("/monoResponseEntity")
<add> public ResponseEntity<Mono<Person>> monoResponseEntity() {
<add> Mono<Person> body = Mono.just(new Person("Robert"));
<add> return ResponseEntity.ok(body);
<add> }
<add>
<ide> @RequestMapping("/mono")
<ide> public Mono<Person> monoResponseBody() {
<ide> return Mono.just(new Person("Robert"));
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandlerTests.java
<ide> import static org.junit.Assert.assertFalse;
<ide> import static org.junit.Assert.assertTrue;
<ide> import static org.mockito.Mockito.mock;
<add>import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
<ide>
<ide>
<ide> /**
<ide> public void supports() throws NoSuchMethodException {
<ide> @Test
<ide> public void defaultOrder() throws Exception {
<ide> ResponseBodyResultHandler handler = createHandler(new StringEncoder());
<del> assertEquals(0, handler.getOrder());
<add> assertEquals(100, handler.getOrder());
<ide> }
<ide>
<ide> @Test
<ide> public void usesContentTypeResolver() throws Exception {
<del> MediaType contentType = MediaType.APPLICATION_JSON_UTF8;
<del> RequestedContentTypeResolver resolver = new FixedContentTypeResolver(contentType);
<add> RequestedContentTypeResolver resolver = new FixedContentTypeResolver(APPLICATION_JSON_UTF8);
<ide> HandlerResultHandler handler = createHandler(resolver, new StringEncoder(), new JacksonJsonEncoder());
<ide>
<ide> ServerWebExchange exchange = createExchange("/foo");
<ide> HandlerResult result = new HandlerResult(new Object(), "fooValue", ResolvableType.forClass(String.class));
<ide> handler.handleResult(exchange, result).block();
<ide>
<del> assertEquals(contentType, exchange.getResponse().getHeaders().getContentType());
<add> assertEquals(APPLICATION_JSON_UTF8, exchange.getResponse().getHeaders().getContentType());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.reactive.result.method.annotation;
<add>
<add>import java.net.URI;
<add>import java.net.URISyntaxException;
<add>import java.nio.charset.Charset;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>import java.util.stream.Collectors;
<add>
<add>import org.junit.Test;
<add>import reactor.core.test.TestSubscriber;
<add>
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.codec.Encoder;
<add>import org.springframework.core.codec.support.JacksonJsonEncoder;
<add>import org.springframework.core.codec.support.StringEncoder;
<add>import org.springframework.core.convert.support.DefaultConversionService;
<add>import org.springframework.core.io.buffer.support.DataBufferTestUtils;
<add>import org.springframework.http.HttpMethod;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.http.ResponseEntity;
<add>import org.springframework.http.converter.reactive.CodecHttpMessageConverter;
<add>import org.springframework.http.converter.reactive.HttpMessageConverter;
<add>import org.springframework.http.server.reactive.MockServerHttpRequest;
<add>import org.springframework.http.server.reactive.MockServerHttpResponse;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.ui.ExtendedModelMap;
<add>import org.springframework.web.method.HandlerMethod;
<add>import org.springframework.web.reactive.HandlerResult;
<add>import org.springframework.web.reactive.HandlerResultHandler;
<add>import org.springframework.web.reactive.accept.FixedContentTypeResolver;
<add>import org.springframework.web.reactive.accept.HeaderContentTypeResolver;
<add>import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.adapter.DefaultServerWebExchange;
<add>import org.springframework.web.server.session.WebSessionManager;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertTrue;
<add>import static org.mockito.Mockito.mock;
<add>import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
<add>
<add>/**
<add> * Unit tests for {@link ResponseEntityResultHandler}.
<add> * @author Rossen Stoyanchev
<add> */
<add>public class ResponseEntityResultHandlerTests {
<add>
<add> private MockServerHttpResponse response = new MockServerHttpResponse();
<add>
<add>
<add> @Test
<add> public void supports() throws NoSuchMethodException {
<add> ResponseEntityResultHandler handler = createHandler(new StringEncoder());
<add> TestController controller = new TestController();
<add>
<add> HandlerMethod hm = new HandlerMethod(controller, TestController.class.getMethod("responseString"));
<add> ResolvableType type = ResolvableType.forMethodParameter(hm.getReturnType());
<add> assertTrue(handler.supports(new HandlerResult(hm, null, type, new ExtendedModelMap())));
<add>
<add> hm = new HandlerMethod(controller, TestController.class.getMethod("responseVoid"));
<add> type = ResolvableType.forMethodParameter(hm.getReturnType());
<add> assertTrue(handler.supports(new HandlerResult(hm, null, type, new ExtendedModelMap())));
<add>
<add> hm = new HandlerMethod(controller, TestController.class.getMethod("string"));
<add> type = ResolvableType.forMethodParameter(hm.getReturnType());
<add> assertFalse(handler.supports(new HandlerResult(hm, null, type, new ExtendedModelMap())));
<add> }
<add>
<add> @Test
<add> public void defaultOrder() throws Exception {
<add> ResponseEntityResultHandler handler = createHandler(new StringEncoder());
<add> assertEquals(0, handler.getOrder());
<add> }
<add>
<add> @Test
<add> public void jsonResponseBody() throws Exception {
<add> RequestedContentTypeResolver resolver = new FixedContentTypeResolver(APPLICATION_JSON_UTF8);
<add> HandlerResultHandler handler = createHandler(resolver, new StringEncoder(), new JacksonJsonEncoder());
<add>
<add> TestController controller = new TestController();
<add> HandlerMethod hm = new HandlerMethod(controller, controller.getClass().getMethod("responseString"));
<add> ResolvableType type = ResolvableType.forMethodParameter(hm.getReturnType());
<add> HandlerResult result = new HandlerResult(hm, ResponseEntity.ok("fooValue"), type);
<add>
<add> ServerWebExchange exchange = createExchange("/foo");
<add> handler.handleResult(exchange, result).block();
<add>
<add> assertEquals(HttpStatus.OK, this.response.getStatus());
<add> assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType());
<add> TestSubscriber.subscribe(this.response.getBody())
<add> .assertValuesWith(buf -> assertEquals("\"fooValue\"",
<add> DataBufferTestUtils.dumpString(buf, Charset.forName("UTF-8"))));
<add> }
<add>
<add>
<add> private ResponseEntityResultHandler createHandler(Encoder<?>... encoders) {
<add> return createHandler(new HeaderContentTypeResolver(), encoders);
<add> }
<add>
<add> private ResponseEntityResultHandler createHandler(RequestedContentTypeResolver resolver,
<add> Encoder<?>... encoders) {
<add>
<add> List<HttpMessageConverter<?>> converters = Arrays.stream(encoders)
<add> .map(encoder -> new CodecHttpMessageConverter<>(encoder, null))
<add> .collect(Collectors.toList());
<add> return new ResponseEntityResultHandler(converters, new DefaultConversionService(), resolver);
<add> }
<add>
<add> private ServerWebExchange createExchange(String path) throws URISyntaxException {
<add> ServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, new URI(path));
<add> WebSessionManager sessionManager = mock(WebSessionManager.class);
<add> return new DefaultServerWebExchange(request, this.response, sessionManager);
<add> }
<add>
<add>
<add> @SuppressWarnings("unused")
<add> private static class TestController {
<add>
<add> public ResponseEntity<String> responseString() {
<add> return null;
<add> }
<add>
<add> public ResponseEntity<Void> responseVoid() {
<add> return null;
<add> }
<add>
<add> public String string() {
<add> return null;
<add> }
<add> }
<add>
<add>} | 8 |
PHP | PHP | increase code coverage | 5bafc8a4a3f18fd3a1c80699e08f42c869f30b57 | <ide><path>tests/TestCase/Cache/Engine/FileEngineTest.php
<ide> public function testSetWithTtl()
<ide> $this->assertTrue($engine->set('default_ttl', $data));
<ide> $this->assertTrue($engine->set('int_ttl', $data, 1));
<ide> $this->assertTrue($engine->set('interval_ttl', $data, new DateInterval('PT1S')));
<add> $this->assertTrue($engine->setMultiple(['multi' => $data], 1));
<ide>
<ide> sleep(2);
<ide> $this->assertNull($engine->get('int_ttl'));
<ide> $this->assertNull($engine->get('interval_ttl'));
<ide> $this->assertSame($data, $engine->get('default_ttl'));
<add> $this->assertNull($engine->get('multi'));
<add> }
<add>
<add> /**
<add> * Test has() method
<add> *
<add> * @return void
<add> */
<add> public function testHas()
<add> {
<add> $engine = Cache::pool('file_test');
<add> $this->assertFalse($engine->has('test'));
<add>
<add> $this->assertTrue($engine->set('test', 1));
<add> $this->assertTrue($engine->has('test', 1));
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | expect error for test_lookup_ipv6_hint on freebsd | f8152df5e815c98be702fe58753258b58f02c4ad | <ide><path>test/internet/test-dns.js
<ide> TEST(function test_lookup_ipv6_hint(done) {
<ide> family: 6,
<ide> hints: dns.V4MAPPED
<ide> }, function(err, ip, family) {
<del> if (err) throw err;
<add> if (err) {
<add> // FreeBSD does not support V4MAPPED
<add> if (process.platform === 'freebsd') {
<add> assert(err instanceof Error);
<add> assert.strictEqual(err.code, 'EAI_BADFLAGS');
<add> assert.strictEqual(err.hostname, 'www.google.com');
<add> assert.ok(/getaddrinfo EAI_BADFLAGS/.test(err.message));
<add> done();
<add> return;
<add> } else {
<add> throw err;
<add> }
<add> }
<ide> assert.ok(net.isIPv6(ip));
<ide> assert.strictEqual(family, 6);
<ide> | 1 |
Python | Python | use get_data_files_path to access test data | 4a91d110c39114f2be014211f67a7e1f60b2b75e | <ide><path>research/object_detection/model_test.py
<ide> from object_detection.core import standard_fields as fields
<ide> from object_detection.utils import config_util
<ide>
<del>FLAGS = tf.flags.FLAGS
<ide>
<ide> MODEL_NAME_FOR_TEST = model_test_util.SSD_INCEPTION_MODEL_NAME
<ide>
<ide>
<ide> def _get_data_path():
<ide> """Returns an absolute path to TFRecord file."""
<del> return os.path.join(FLAGS.test_srcdir, model_test_util.PATH_BASE, 'test_data',
<add> return os.path.join(tf.resource_loader.get_data_files_path(), 'test_data',
<ide> 'pets_examples.record')
<ide>
<ide>
<ide> def _get_labelmap_path():
<ide> """Returns an absolute path to label map file."""
<del> return os.path.join(FLAGS.test_srcdir, model_test_util.PATH_BASE, 'data',
<add> return os.path.join(tf.resource_loader.get_data_files_path(), 'data',
<ide> 'pet_label_map.pbtxt')
<ide>
<ide>
<ide><path>research/object_detection/model_test_util.py
<ide>
<ide> FASTER_RCNN_MODEL_NAME = 'faster_rcnn_resnet50_pets'
<ide> SSD_INCEPTION_MODEL_NAME = 'ssd_inception_v2_pets'
<del>PATH_BASE = 'google3/third_party/tensorflow_models/object_detection/'
<ide>
<ide>
<ide> def GetPipelineConfigPath(model_name):
<ide> """Returns path to the local pipeline config file."""
<del> return os.path.join(FLAGS.test_srcdir, PATH_BASE, 'samples', 'configs',
<del> model_name + '.config')
<add> return os.path.join(tf.resource_loader.get_data_files_path(), 'samples',
<add> 'configs', model_name + '.config')
<ide>
<ide>
<ide> def InitializeFlags(model_name_for_test): | 2 |
Python | Python | improve tests for storing dag code in db | 9fda0188f9a21eae75afb1933d5f8bebf3201e9b | <ide><path>tests/models/test_dagcode.py
<ide> # To move it to a shared module.
<ide> from airflow.utils.file import open_maybe_zipped
<ide> from airflow.utils.session import create_session
<add>from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_dag_code
<ide>
<ide>
<ide> def _write_two_example_dags(self):
<ide> DagCode(xcom_dag.fileloc).sync_to_db()
<ide> return [bash_dag, xcom_dag]
<ide>
<add> @conf_vars({('core', 'store_dag_code'): 'True'})
<ide> def _write_example_dags(self):
<ide> example_dags = make_example_dags(example_dags_module)
<ide> for dag in example_dags.values():
<del> DagCode(dag.fileloc).sync_to_db()
<add> dag.sync_to_db()
<ide> return example_dags
<ide>
<ide> def test_sync_to_db(self):
<ide> def test_detecting_duplicate_key(self, mock_hash):
<ide> def _compare_example_dags(self, example_dags):
<ide> with create_session() as session:
<ide> for dag in example_dags.values():
<add> if dag.is_subdag:
<add> dag.fileloc = dag.parent_dag.fileloc
<ide> self.assertTrue(DagCode.has_dag(dag.fileloc))
<ide> dag_fileloc_hash = DagCode.dag_fileloc_hash(dag.fileloc)
<ide> result = session.query( | 1 |
Javascript | Javascript | remove dead code in getwidthorheight | 96533cd0e889a09ca71b90d74d71e590623cf26f | <ide><path>src/css.js
<ide> function getWidthOrHeight( elem, name, extra ) {
<ide> val = curCSS( elem, name, styles ),
<ide> isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
<ide>
<del> // Fall back to uncomputed css if necessary
<del> if ( val < 0 || val == null ) {
<del> val = elem.style[ name ];
<del> }
<del>
<ide> // Computed unit is not pixels. Stop here and return.
<ide> if ( rnumnonpx.test( val ) ) {
<ide> return val; | 1 |
Text | Text | release notes for 1.3.0-beta.9 release-naming | 819dd5df92ad73b48e370c00d6e8cea10bf08e63 | <ide><path>CHANGELOG.md
<add><a name="1.3.0-beta.9"></a>
<add># 1.3.0-beta.9 release-naming (2014-05-16)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$compile:** pass `transcludeFn` down to nested transclude directives
<add> ([4f03dc5a](https://github.com/angular/angular.js/commit/4f03dc5a9650f3f22f78b438474322b4b8871dec),
<add> [#7240](https://github.com/angular/angular.js/issues/7240), [#7387](https://github.com/angular/angular.js/issues/7387))
<add>- **jqLite:** use jQuery only if jQuery.fn.on present
<add> ([e9bc51cb](https://github.com/angular/angular.js/commit/e9bc51cb0964ea682c1654919174dacebd09fcf6))
<add>- **ngClass:** handle index changes when an item is unshifted
<add> ([5fbd618c](https://github.com/angular/angular.js/commit/5fbd618c2ff0dbaa4e19d0fd0e55921ce7d89478),
<add> [#7256](https://github.com/angular/angular.js/issues/7256))
<add>- **ngMessages:** annotate ngMessages controller for minification
<add> ([0282ca97](https://github.com/angular/angular.js/commit/0282ca971df7923c8f3dba0eb0df544e244e5b93))
<add>- **numberFilter:** fix rounding error edge case
<add> ([81d427b5](https://github.com/angular/angular.js/commit/81d427b5f0d3502f65e8db5beaa5ad837c9ede17),
<add> [#7453](https://github.com/angular/angular.js/issues/7453), [#7478](https://github.com/angular/angular.js/issues/7478))
<add>
<add>
<add>## Features
<add>
<add>- **ngTouch:** add optional `ngSwipeDisableMouse` attribute to `ngSwipe` directives to ignore mouse events.
<add> ([5a568b4f](https://github.com/angular/angular.js/commit/5a568b4f960cc5381b3911e3a6423aff2ff7f7f9),
<add> [#6627](https://github.com/angular/angular.js/issues/6627), [#6626](https://github.com/angular/angular.js/issues/6626))
<add>
<add>
<add>## Breaking Changes
<add>
<add>- **jqLite:** due to [d71dbb1a](https://github.com/angular/angular.js/commit/d71dbb1ae50f174680533492ce4c7db3ff74df00),
<add> the jQuery `detach()` method does not trigger the `$destroy` event.
<add> If you want to destroy Angular data attached to the element, use `remove()`.
<add>
<add>
<ide> <a name="1.3.0-beta.8"></a>
<ide> # 1.3.0-beta.8 accidental-haiku (2014-05-09)
<ide> | 1 |
PHP | PHP | remove dead code (stubs) in test classes | 357c2664825911d53cbb9c43e7d5305b2161e2e8 | <ide><path>tests/Bus/BusDispatcherTest.php
<ide> public function handle()
<ide> }
<ide> }
<ide>
<del>class BusDispatcherTestBasicHandler {
<del> public function handle(BusDispatcherTestBasicCommand $command)
<del> {
<del>
<del> }
<del>}
<del>
<ide> class BusDispatcherTestQueuedHandler implements Illuminate\Contracts\Queue\ShouldBeQueued {
<ide>
<ide> }
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> protected function getMockQueryBuilder()
<ide>
<ide> }
<ide>
<del>class EloquentBuilderTestModelStub extends Illuminate\Database\Eloquent\Model {}
<del>
<ide> class EloquentBuilderTestScopeStub extends Illuminate\Database\Eloquent\Model {
<ide> public function scopeApproved($query)
<ide> {
<ide> $query->where('foo', 'bar');
<ide> }
<ide> }
<ide>
<del>class EloquentBuilderTestWithTrashedStub extends Illuminate\Database\Eloquent\Model {
<del> use Illuminate\Database\Eloquent\SoftDeletes;
<del> protected $table = 'table';
<del> public function getKeyName() { return 'foo'; }
<del>}
<del>
<ide> class EloquentBuilderTestNestedStub extends Illuminate\Database\Eloquent\Model {
<ide> protected $table = 'table';
<ide> use Illuminate\Database\Eloquent\SoftDeletes;
<ide><path>tests/Database/DatabaseEloquentMorphTest.php
<ide> protected function getManyRelation()
<ide> class EloquentMorphResetModelStub extends Illuminate\Database\Eloquent\Model {}
<ide>
<ide>
<del>class EloquentMorphResetBuilderStub extends Illuminate\Database\Eloquent\Builder {
<del> public function __construct() { $this->query = new EloquentRelationQueryStub; }
<del> public function getModel() { return new EloquentMorphResetModelStub; }
<del> public function isSoftDeleting() { return false; }
<del>}
<del>
<del>
<ide> class EloquentMorphQueryStub extends Illuminate\Database\Query\Builder {
<ide> public function __construct() {}
<ide> }
<ide><path>tests/Database/DatabaseEloquentPivotTest.php
<ide> public function testDeleteMethodDeletesModelByKeys()
<ide> }
<ide>
<ide>
<del>class DatabaseEloquentPivotTestModelStub extends Illuminate\Database\Eloquent\Model {}
<del>
<ide> class DatabaseEloquentPivotTestDateStub extends Illuminate\Database\Eloquent\Relations\Pivot {
<ide> public function getDates()
<ide> {
<ide><path>tests/Database/DatabaseEloquentRelationTest.php
<ide> public function getQuery()
<ide> }
<ide>
<ide>
<del>class EloquentRelationResetStub extends Illuminate\Database\Eloquent\Builder {
<del> public function __construct() { $this->query = new EloquentRelationQueryStub; }
<del> public function getModel() { return new EloquentRelationResetModelStub; }
<del>}
<del>
<del>
<del>class EloquentRelationQueryStub extends Illuminate\Database\Query\Builder {
<del> public function __construct() {}
<del>}
<del>
<ide> class EloquentRelationStub extends \Illuminate\Database\Eloquent\Relations\Relation {
<ide> public function addConstraints() {}
<ide> public function addEagerConstraints(array $models) {}
<ide><path>tests/Database/DatabaseSoftDeletingScopeTest.php
<ide> public function testOnlyTrashedExtension()
<ide> }
<ide>
<ide> }
<del>
<del>
<del>class DatabaseSoftDeletingScopeBuilderStub {
<del> public $extensions = [];
<del> public $onDelete;
<del> public function extend($name, $callback)
<del> {
<del> $this->extensions[$name] = $callback;
<del> }
<del> public function onDelete($callback)
<del> {
<del> $this->onDelete = $callback;
<del> }
<del>}
<ide><path>tests/Foundation/FoundationApplicationTest.php
<ide> public function testEnvironment()
<ide>
<ide> }
<ide>
<del>class ApplicationCustomExceptionHandlerStub extends Illuminate\Foundation\Application {
<del>
<del> public function prepareResponse($value)
<del> {
<del> $response = m::mock('Symfony\Component\HttpFoundation\Response');
<del> $response->shouldReceive('send')->once();
<del> return $response;
<del> }
<del>
<del> protected function setExceptionHandler(Closure $handler) { return $handler; }
<del>
<del>}
<del>
<del>class ApplicationKernelExceptionHandlerStub extends Illuminate\Foundation\Application {
<del>
<del> protected function setExceptionHandler(Closure $handler) { return $handler; }
<del>
<del>}
<del>
<del>class ApplicationGetMiddlewaresStub extends Illuminate\Foundation\Application
<del>{
<del> public function getMiddlewares()
<del> {
<del> return $this->middlewares;
<del> }
<del>}
<del>
<ide> class ApplicationDeferredSharedServiceProviderStub extends Illuminate\Support\ServiceProvider {
<ide> protected $defer = true;
<ide> public function register()
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> protected function getRealTranslator()
<ide> }
<ide>
<ide> }
<del>
<del>
<del>class ValidatorTestAfterCallbackStub {
<del> public function validate() {
<del> $_SERVER['__validator.after.test'] = true;
<del> }
<del>} | 8 |
Javascript | Javascript | fix license headers | a8474c25fda5f818c714bcc32fb3e6e362e32198 | <ide><path>Libraries/CustomComponents/Navigator/Navigation/NavigationRouteStack.js
<ide> /**
<del> * Copyright (c) 2013-present, Facebook, Inc.
<del> * All rights reserved.
<add> * Copyright (c) 2015, Facebook, Inc. All rights reserved.
<ide> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<add> * Facebook, Inc. ("Facebook") owns all right, title and interest, including
<add> * all intellectual property and other proprietary rights, in and to the React
<add> * Native CustomComponents software (the "Software"). Subject to your
<add> * compliance with these terms, you are hereby granted a non-exclusive,
<add> * worldwide, royalty-free copyright license to (1) use and copy the Software;
<add> * and (2) reproduce and distribute the Software as part of your own software
<add> * ("Your Software"). Facebook reserves all rights not expressly granted to
<add> * you in this license agreement.
<add> *
<add> * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS
<add> * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
<add> * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
<add> * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR
<add> * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
<add> * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
<add> * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
<add> * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
<add> * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
<add> * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF
<add> * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide> *
<ide> * @providesModule NavigationRouteStack
<ide> * @flow
<ide><path>Libraries/CustomComponents/Navigator/Navigation/NavigationTreeNode.js
<ide> /**
<ide> * Copyright (c) 2015, Facebook, Inc. All rights reserved.
<ide> *
<add> * Facebook, Inc. ("Facebook") owns all right, title and interest, including
<add> * all intellectual property and other proprietary rights, in and to the React
<add> * Native CustomComponents software (the "Software"). Subject to your
<add> * compliance with these terms, you are hereby granted a non-exclusive,
<add> * worldwide, royalty-free copyright license to (1) use and copy the Software;
<add> * and (2) reproduce and distribute the Software as part of your own software
<add> * ("Your Software"). Facebook reserves all rights not expressly granted to
<add> * you in this license agreement.
<add> *
<add> * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS
<add> * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
<add> * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
<add> * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR
<add> * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
<add> * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
<add> * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
<add> * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
<add> * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
<add> * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF
<add> * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<add> *
<ide> * @providesModule NavigationTreeNode
<ide> * @flow
<ide> */
<del>
<ide> 'use strict';
<ide>
<ide> var invariant = require('fbjs/lib/invariant');
<ide><path>Libraries/Image/AssetRegistry.js
<ide> /**
<del> * Copyright 2004-present Facebook. All Rights Reserved.
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule AssetRegistry
<ide> * @flow
<ide> */
<ide> 'use strict';
<ide>
<add>
<ide> export type PackagerAsset = {
<ide> __packager_asset: boolean,
<ide> fileSystemLocation: string,
<ide><path>Libraries/Interaction/InteractionMixin.js
<ide> /**
<del> * Copyright 2004-present Facebook. All Rights Reserved.
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule InteractionMixin
<ide> * @flow
<ide><path>Libraries/Utilities/MatrixMath.js
<ide> /**
<del> * Copyright 2004-present Facebook. All Rights Reserved.
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule MatrixMath
<ide> * @noflow
<ide><path>Libraries/Utilities/buildStyleInterpolator.js
<ide> /**
<del> * Copyright 2004-present Facebook. All Rights Reserved.
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule buildStyleInterpolator
<ide> */
<ide><path>Libraries/Utilities/differ/sizesDiffer.js
<ide> /**
<del> * Copyright 2004-present Facebook. All Rights Reserved.
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule sizesDiffer
<ide> */
<ide><path>Libraries/Utilities/dismissKeyboard.js
<ide> /**
<del> * Copyright 2004-present Facebook. All Rights Reserved.
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule dismissKeyboard
<ide> * | 8 |
Python | Python | add list_locations for slicehost | 36bd2bd9f171edfca17f3058e980124afb457dfc | <ide><path>libcloud/drivers/slicehost.py
<ide> Slicehost Driver
<ide> """
<ide> from libcloud.types import NodeState, InvalidCredsException, Provider
<del>from libcloud.base import ConnectionKey, Response, NodeDriver, Node, NodeSize, NodeImage
<add>from libcloud.base import ConnectionKey, Response, NodeDriver, Node, NodeSize, NodeImage, NodeLocation
<ide> import base64
<ide> import httplib
<ide> import struct
<ide> def list_sizes(self):
<ide> def list_images(self):
<ide> return self._to_images(self.connection.request('/images.xml').object)
<ide>
<add> def list_locations(self):
<add> # TODO: This isn't accurate. Some Slices are in Dallas, some are in St Louis (?)
<add> return [NodeLocation(0, "Slicehost Central US", 'us', self)]
<add>
<ide> def create_node(self, **kwargs):
<ide> name = kwargs['name']
<ide> image = kwargs['image'] | 1 |
Python | Python | fix the expression of pictures | dcb9fac5776285ce07475113b1734ec25b17fd93 | <ide><path>examples/deep_dream.py
<ide> result_prefix = args.result_prefix
<ide>
<ide> # dimensions of the generated picture.
<del>img_width = 600
<ide> img_height = 600
<add>img_width = 600
<ide>
<ide> # path to the model weights file.
<ide> weights_path = 'vgg16_weights.h5'
<ide>
<ide>
<ide> def preprocess_image(image_path):
<del> img = load_img(image_path, target_size=(img_width, img_height))
<add> img = load_img(image_path, target_size=(img_height, img_width))
<ide> img = img_to_array(img)
<ide> img = np.expand_dims(img, axis=0)
<ide> img = vgg16.preprocess_input(img)
<ide> def preprocess_image(image_path):
<ide>
<ide> def deprocess_image(x):
<ide> if K.image_dim_ordering() == 'th':
<del> x = x.reshape((3, img_width, img_height))
<add> x = x.reshape((3, img_height, img_width))
<ide> x = x.transpose((1, 2, 0))
<ide> else:
<del> x = x.reshape((img_width, img_height, 3))
<add> x = x.reshape((img_height, img_width, 3))
<ide> # Remove zero-center by mean pixel
<ide> x[:, :, 0] += 103.939
<ide> x[:, :, 1] += 116.779
<ide> def deprocess_image(x):
<ide> return x
<ide>
<ide> if K.image_dim_ordering() == 'th':
<del> img_size = (3, img_width, img_height)
<add> img_size = (3, img_height, img_width)
<ide> else:
<del> img_size = (img_width, img_height, 3)
<add> img_size = (img_height, img_width, 3)
<ide> # this will contain our generated image
<ide> dream = Input(batch_shape=(1,) + img_size)
<ide>
<ide> def deprocess_image(x):
<ide> def continuity_loss(x):
<ide> assert K.ndim(x) == 4
<ide> if K.image_dim_ordering() == 'th':
<del> a = K.square(x[:, :, :img_width - 1, :img_height - 1] -
<del> x[:, :, 1:, :img_height - 1])
<del> b = K.square(x[:, :, :img_width - 1, :img_height - 1] -
<del> x[:, :, :img_width - 1, 1:])
<add> a = K.square(x[:, :, :img_height - 1, :img_width - 1] -
<add> x[:, :, 1:, :img_width - 1])
<add> b = K.square(x[:, :, :img_height - 1, :img_width - 1] -
<add> x[:, :, :img_height - 1, 1:])
<ide> else:
<del> a = K.square(x[:, :img_width - 1, :img_height - 1, :] -
<del> x[:, 1:, :img_height - 1, :])
<del> b = K.square(x[:, :img_width - 1, :img_height - 1, :] -
<del> x[:, :img_width - 1, 1:, :])
<add> a = K.square(x[:, :img_height - 1, :img_width - 1, :] -
<add> x[:, 1:, :img_width - 1, :])
<add> b = K.square(x[:, :img_height - 1, :img_width - 1, :] -
<add> x[:, :img_height - 1, 1:, :])
<ide> return K.sum(K.pow(a + b, 1.25))
<ide>
<ide> # define the loss | 1 |
Javascript | Javascript | remove duplicate code, clearer parameter names | 4fa2c408f02c723bd7389a705d9aebd42429f8da | <ide><path>src/core/core.controller.js
<ide> function compare2Level(l1, l2) {
<ide> };
<ide> }
<ide>
<del>function onAnimationsComplete(ctx) {
<del> const chart = ctx.chart;
<add>function onAnimationsComplete(context) {
<add> const chart = context.chart;
<ide> const animationOptions = chart.options.animation;
<ide>
<ide> chart._plugins.notify(chart, 'afterRender');
<del> callCallback(animationOptions && animationOptions.onComplete, [ctx], chart);
<add> callCallback(animationOptions && animationOptions.onComplete, [context], chart);
<ide> }
<ide>
<del>function onAnimationProgress(ctx) {
<del> const chart = ctx.chart;
<add>function onAnimationProgress(context) {
<add> const chart = context.chart;
<ide> const animationOptions = chart.options.animation;
<del> callCallback(animationOptions && animationOptions.onProgress, [ctx], chart);
<add> callCallback(animationOptions && animationOptions.onProgress, [context], chart);
<ide> }
<ide>
<ide> function isDomSupported() {
<ide> class Chart {
<ide>
<ide> render() {
<ide> const me = this;
<del> const animationOptions = me.options.animation;
<ide> if (me._plugins.notify(me, 'beforeRender') === false) {
<ide> return;
<ide> }
<del> const onComplete = function() {
<del> me._plugins.notify(me, 'afterRender');
<del> callCallback(animationOptions && animationOptions.onComplete, [], me);
<del> };
<ide>
<ide> if (animator.has(me)) {
<ide> if (me.attached && !animator.running(me)) {
<ide> animator.start(me);
<ide> }
<ide> } else {
<ide> me.draw();
<del> onComplete();
<add> onAnimationsComplete({chart: me});
<ide> }
<ide> }
<ide> | 1 |
Text | Text | fix broken link | d96c422cfc1c63e7cdf56dcc3608cbda5efcd948 | <ide><path>website/docs/usage/linguistic-features.md
<ide> hyperparameters, pipeline and tokenizer used for constructing and training the
<ide> pipeline. The `[nlp.tokenizer]` block refers to a **registered function** that
<ide> takes the `nlp` object and returns a tokenizer. Here, we're registering a
<ide> function called `whitespace_tokenizer` in the
<del>[`@tokenizers` registry](/api/registry). To make sure spaCy knows how to
<add>[`@tokenizers` registry](/api/top-level#registry). To make sure spaCy knows how to
<ide> construct your tokenizer during training, you can pass in your Python file by
<ide> setting `--code functions.py` when you run [`spacy train`](/api/cli#train).
<ide> | 1 |
Ruby | Ruby | remove locale key for to_sentence | b99c21a0151df7f8828b3ba7d5638646849d825b | <ide><path>actionpack/lib/action_controller/metal/exceptions.rb
<ide> class UrlGenerationError < ActionControllerError #:nodoc:
<ide>
<ide> class MethodNotAllowed < ActionControllerError #:nodoc:
<ide> def initialize(*allowed_methods)
<del> super("Only #{allowed_methods.to_sentence(locale: :en)} requests are allowed.")
<add> super("Only #{allowed_methods.to_sentence} requests are allowed.")
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/associations.rb
<ide> def initialize(reflection = nil)
<ide> through_reflection = reflection.through_reflection
<ide> source_reflection_names = reflection.source_reflection_names
<ide> source_associations = reflection.through_reflection.klass._reflections.keys
<del> super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)}?")
<add> super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(two_words_connector: ' or ', last_word_connector: ', or ')} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ')}?")
<ide> else
<ide> super("Could not find the source association(s).")
<ide> end | 2 |
Text | Text | improve spanish translation for ruby's guide | c2bbde95a314df738be94e462e3b21930d2c84e4 | <ide><path>guide/spanish/ruby/common-array-methods/index.md
<ide> ---
<ide> title: Common Array Methods
<del>localeTitle: Métodos comunes de matriz
<add>localeTitle: Métodos comunes de Array
<ide> ---
<del>## Métodos comunes de matriz
<add>## Métodos comunes de Array
<ide>
<del>Ruby Arrays forma una base fundamental en la programación en Ruby, y la mayoría de los lenguajes de hecho. Se utiliza tanto que sería beneficioso conocer e incluso memorizar algunos de los métodos más utilizados para los arreglos. Si quieres saber más sobre Ruby Arrays, tenemos [un artículo sobre ellos](https://guide.freecodecamp.org/ruby/ruby-arrays) .
<add>Los Arrays (arreglos) de Ruby forman una base fundamental en la programación en Ruby, y en la mayoría de los lenguajes de hecho. Se utilizan tanto que sería beneficioso conocer e incluso memorizar algunos de los métodos más utilizados para arrays. Si quieres saber más sobre los Arrays de Ruby, tenemos [un artículo sobre ellos](https://guide.freecodecamp.org/ruby/ruby-arrays).
<ide>
<del>Para los fines de esta guía, nuestra matriz será la siguiente:
<add>Para los fines de esta guía, nuestro array será el siguiente:
<ide>
<del>\`\` \`rubí array = \[0, 1, 2, 3, 4\]
<del>```
<del>#### .length
<del> The .length method tallies the number of elements in your array and returns the count:
<add>``` ruby
<add>array = [0, 1, 2, 3, 4]
<ide> ```
<add>#### .length
<add>El método .length calcula el número de elementos en tu array y retorna la cuenta:
<ide>
<del>rubí array.length => 5
<del>```
<del>#### .first
<del> The .first method accesses the first element of the array, the element at index 0:
<add>``` ruby
<add>array.length
<add>=> 5
<ide> ```
<add>Este método es similar a los métodos .count y .size.
<ide>
<del>rubí array.first => 0
<add>``` ruby
<add>array.count
<add>=> 5
<ide> ```
<del>#### .last
<del> The .last method accesses the last element of the array:
<add>``` ruby
<add>array.size
<add>=> 5
<ide> ```
<ide>
<del>rubí array.last => 4
<del>```
<del>#### .take
<del> The .take method returns the first n elements of the array:
<del>```
<add>#### .first
<add>El método .first accede al primer elemento del array, es decir el elemento en el índice 0:
<ide>
<del>rubí array.take (3) => \[0, 1, 2\]
<del>```
<del>#### .drop
<del> The .drop method returns the elements after n elements of the array:
<add>``` ruby
<add>array.first
<add>=> 0
<ide> ```
<ide>
<del>rubí array.drop (3) => \[3, 4\]
<del>```
<del>#### array index
<del> You can access a specific element in an array by accessing its index. If the index does not exist in the array, nil will be returned:
<add>#### .last
<add>El método .last accede al último elemento del array:
<add>
<add>``` ruby
<add>array.last
<add>=> 4
<ide> ```
<ide>
<del>rubí array \[2\] => 2
<add>#### .take
<add>El método .take retorna los primeros n elementos del array:
<ide>
<del>array \[5\] => nil
<del>```
<del>#### .pop
<del> The .pop method will permantently remove the last element of an array:
<add>``` ruby
<add>array.take(3)
<add>=> [0, 1, 2]
<ide> ```
<ide>
<del>rubí array.pop => \[0, 1, 2, 3\]
<del>```
<del>#### .shift
<del> The .shift method will permantently remove the first element of an array and return this element:
<del>```
<add>#### .drop
<add>El método .drop retorna los elementos siguientes después de los primeros n elementos del array:
<ide>
<del>rubí array.shift => 0
<del>formación => \[1, 2, 3, 4\]
<del>```
<del>#### .push
<del> The .push method will allow you to add an element to the end of an array:
<add>``` ruby
<add>array.drop(3)
<add>=> [3, 4]
<ide> ```
<ide>
<del>rubí array.push (99) => \[0, 1, 2, 3, 4, 99\]
<del>```
<del>#### .unshift
<del> The .unshift method will allow you to add an element to the beginning of an array:
<del>```
<add>#### índice del array
<add>Puedes acceder a un elemento determinado en el array a través de su índice. Si el índice no existe en el array, se retornará nulo:
<ide>
<del>array = \[2, 3\] array.unshift (1) => \[1, 2, 3\]
<del>```
<del>#### .delete
<del> The .delete method removes a specified element from an array permanently:
<del>```
<add>```ruby
<add>array[2]
<add>=> 2
<ide>
<del>rubí array.delete (1) => \[0, 2, 3, 4\]
<del>```
<del>#### .delete_at
<del> The .delete_at method allows you to permanently remove an element of an array at a specified index:
<add>array[5]
<add>=> nil
<ide> ```
<ide>
<del>rubí array.delete\_at (0) => \[1, 2, 3, 4\]
<del>```
<del>#### .reverse
<del> The .reverse method reverses the array but does not mutate it (the original array stays as is):
<add>#### .pop
<add>El método .pop removerá de forma permanente el último elemento del array:
<add>
<add>``` ruby
<add>array.pop
<add>=> [0, 1, 2, 3]
<ide> ```
<ide>
<del>rubí array.reverse => \[4, 3, 2, 1, 0\]
<add>#### .shift
<add>El método .shift removerá de forma permanente el primer elemento del array y retornará este elemento:
<add>
<add>``` ruby
<add>array.shift
<add>=> 0
<add>array
<add>=> [1, 2, 3, 4]
<ide> ```
<del>#### .select
<del> The .select method iterates over an array and returns a new array that includes any items that return true to the expression provided.
<add>
<add>#### .push
<add>El método .push te permitirá agregar un elemento al final del array:
<add>
<add>``` ruby
<add>array.push(99)
<add>=> [0, 1, 2, 3, 4, 99]
<ide> ```
<ide>
<del>rubí array = \[1, 2, 3, 4, 5, 6, 7, 8, 9, 10\] array.select {| number | número> 4} => \[5, 6, 7, 8, 9, 10\] formación => \[5, 6, 7, 8, 9, 10\]
<add>#### .unshift
<add>El método .unshift te permitirá agregar un elemento al principio del array:
<add>
<ide> ```
<del>#### .include?
<del> The include? method checks to see if the argument given is included in the array:
<add>array = [2, 3]
<add>array.unshift(1)
<add>=> [1, 2, 3]
<ide> ```
<ide>
<del>rubí array = \[1, 2, 3, 4, 5\] => \[1, 2, 3, 4, 5\] array.include? (3) => verdadero
<add>#### .delete
<add>El método .delete remueve un elemento determinado de un array de forma permanente:
<ide>
<del>#### .aplanar
<add>``` ruby
<add>array.delete(1)
<add>=> [0, 2, 3, 4]
<add>```
<ide>
<del>El método de aplanamiento se puede usar para tomar una matriz que contiene matrices anidadas y crear una matriz unidimensional:
<add>#### .delete_at
<add>El método .delete_at te permite remover de forma permanente un elemento del array para un índice determinado:
<ide>
<del>\`\` \`rubí array = \[1, 2, \[3, 4, 5\], \[6, 7\]\] array.flatten => \[1, 2, 3, 4, 5, 6, 7\]
<del>```
<del>#### .join
<del> The .join method returns a string of all the elements of the array separated by a separator parameter. If the separator parameter is nil, the method uses an empty string as a separator between strings.
<add>``` ruby
<add>array.delete_at(0)
<add>=> [1, 2, 3, 4]
<ide> ```
<ide>
<del>rubí array.join => "1234" array.join (" _") => "1_ 2 _3_ 4"
<add>#### .reverse
<add>El método .reverse retorna un nuevo array con los mismos elementos del array original, pero con el orden invertido:
<add>
<add>``` ruby
<add>array.reverse
<add>=> [4, 3, 2, 1, 0]
<add>array
<add>=> [0, 1, 2, 3, 4]
<ide> ```
<del>#### .each
<del> The .each method iterates over each element of the array, allowing you to perform actions on them.
<add>
<add>#### .select
<add>El método .select itera sobre un array y retorna un nuevo array que incluye cualquier item que retorne verdadero a la expresión provista:
<add>
<add>``` ruby
<add>array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<add>array.select { |number| number > 4 }
<add>=> [5, 6, 7, 8, 9, 10]
<add>array
<add>=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<ide> ```
<ide>
<del>rubí array.each do | elemento | pone elemento fin => 0 1 2 3 4
<add>#### .include?
<add>El método include? verifica si el argumento dado está incluido en el array:
<add>
<add>``` ruby
<add>array = [1, 2, 3, 4, 5]
<add>=> [1, 2, 3, 4, 5]
<add>array.include?(3)
<add>=> true
<ide> ```
<del>#### .map
<del> The .map method is the same as the .collect method. The .map and .collect methods iterate over each element of the array, allowing you to perform actions on them. The .map and .collect methods differ from the .each method in that they return an array containing the transformed elements.
<add>
<add>#### .flatten
<add>
<add>El método .flatten se puede usar para tomar un array que contiene arrays anidados y crear uno nuevo de una sola dimensión:
<add>
<add>``` ruby
<add>array = [1, 2, [3, 4, 5], [6, 7]]
<add>array.flatten
<add>=> [1, 2, 3, 4, 5, 6, 7]
<ide> ```
<ide>
<del>rubí array.map {| element | elemento \* 2} pone elemento fin => 0 2 4 6 8
<add>#### .join
<add>El método .join retorna una cadena con todos los elementos del array separados por un parámetro separador. Si el parámetro separador es nulo, el método usa una cadena vacía como separador:
<add>
<add>``` ruby
<add>array.join
<add>=> "01234"
<add>array.join("*")
<add>=> "0*1*2*3*4"
<ide> ```
<del>#### .uniq
<del> The .uniq method takes in an array containing duplicate elements, and returns a copy of the array containing only unique elements--any duplicate elements are removed from the array.
<add>
<add>#### .each
<add>El método .each itera sobre cada elemento del array, permitiéndote ejecutar acciones sobre ellos:
<add>
<add>``` ruby
<add>array.each { |element| puts element }
<add>=>
<add>0
<add>1
<add>2
<add>3
<add>4
<ide> ```
<ide>
<del>rubí array = \[1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 6, 7, 8\] array.uniq => \[1, 2, 3, 4, 5, 6, 7, 8\]
<add>#### .map
<add>El método .map es igual que el método .collect. Los métodos .map y .collect iteran sobre cada elemento del array, permitiéndote ejecutar acciones sobre ellos. Los métodos .map y .collect se diferencian del método .each en que éstos retornan un array que contiene los elementos transformados:
<add>
<add>``` ruby
<add>array.map { |element| element * 2 }
<add>=> [0, 2, 4, 6, 8]
<ide> ```
<del>#### .concat
<del> The .concat method appends the elements from an array to the original array. The .concat method can take in multiple arrays as an argument, which will in turn append multiple arrays to the original array.
<add>
<add>#### .uniq
<add>El método .uniq toma un array que contiene elementos duplicados y retorna una copia del array conteniendo solo los elementos únicos. Cualquier elemento duplicado es removido de este array:
<add>
<add>``` ruby
<add>array = [1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 6, 7, 8]
<add>array.uniq
<add>=> [1, 2, 3, 4, 5, 6, 7, 8]
<ide> ```
<ide>
<del>rubí array = \[0, 1, 2, 3, 4\] array.concat (\[5, 6, 7\], \[8, 9, 10\]) => \[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\] \`\` \`
<add>#### .concat
<add>El método .concat concatena los elementos de un array provisto con los del array original. El método .concat puede tomar múliples arrays como argumento, lo cual concatenará múltiples arrays al array original:
<ide>
<del>## Más información
<add>``` ruby
<add>array = [0, 1, 2, 3, 4]
<add>array.concat([5, 6, 7], [8, 9, 10])
<add>=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<add>```
<ide>
<del>* [Documentos de Ruby Array](http://ruby-doc.org/core-2.5.1/Array.html)
<ide>\ No newline at end of file
<add>## Más información
<add>* [Documentos de Ruby Array](http://ruby-doc.org/core-2.5.1/Array.html) | 1 |
Java | Java | add syntax highlighting to javadoc where necessary | 2d68b726b5ac4d788c44bea58e9e6cd87c4ad5a0 | <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/PropertySource.java
<ide> * uses {@code @PropertySource} to contribute {@code app.properties} to the
<ide> * {@code Environment}'s set of {@code PropertySources}.
<ide> *
<del> * <pre>
<add> * <pre class="code">
<ide> * @Configuration
<ide> * @PropertySource("classpath:/com/myco/app.properties")
<ide> * public class AppConfig {
<ide> * {@code b.properties}, consider the following two configuration classes
<ide> * that reference them with {@code @PropertySource} annotations:
<ide> *
<del> * <pre>
<add> * <pre class="code">
<ide> * @Configuration
<ide> * @PropertySource("classpath:/com/myco/a.properties")
<ide> * public class ConfigA { }
<ide> *
<ide> * The override ordering depends on the order in which these classes are registered
<ide> * with the application context.
<del> * <pre>
<add> * <pre class="code">
<ide> * AnnotationConfigApplicationContext ctx =
<ide> * new AnnotationConfigApplicationContext();
<ide> * ctx.register(ConfigA.class);
<ide> * the ordering is difficult to predict. In such cases - and if overriding is important -
<ide> * it is recommended that the user fall back to using the programmatic PropertySource API.
<ide> * See {@link org.springframework.core.env.ConfigurableEnvironment ConfigurableEnvironment}
<del> * and * {@link org.springframework.core.env.MutablePropertySources MutablePropertySources}
<add> * and {@link org.springframework.core.env.MutablePropertySources MutablePropertySources}
<ide> * Javadoc for details.
<ide> *
<ide> * @author Chris Beams
<ide><path>org.springframework.core/src/main/java/org/springframework/core/env/AbstractEnvironment.java
<ide> public AbstractEnvironment() {
<ide> * "D". If the {@code Level2Environment} subclass wished to give property sources C
<ide> * and D higher precedence than A and B, it could simply call
<ide> * {@code super.customizePropertySources} after, rather than before adding its own:
<del> * <pre>
<add> * <pre class="code">
<ide> * public class Level2Environment extends Level1Environment {
<ide> * @Override
<ide> * protected void customizePropertySources(MutablePropertySources propertySources) {
<ide> public AbstractEnvironment() {
<ide> * property sources via the {@link #getPropertySources()} accessor, typically within
<ide> * an {@link org.springframework.context.ApplicationContextInitializer
<ide> * ApplicationContextInitializer}. For example:
<del> * <pre>
<add> * <pre class="code">
<ide> * ConfigurableEnvironment env = new StandardEnvironment();
<ide> * env.getPropertySources().addLast(new PropertySourceX(...));
<ide> * </pre>
<ide><path>org.springframework.test/src/main/java/org/springframework/mock/env/MockPropertySource.java
<ide> *
<ide> * The {@link #setProperty} and {@link #withProperty} methods are exposed for
<ide> * convenience, for example:
<del> * <pre>
<add> * <pre class="code">
<ide> * {@code
<ide> * PropertySource<?> source = new MockPropertySource().withProperty("foo", "bar");
<ide> * }
<ide><path>org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/EnableWebMvc.java
<ide> /**
<ide> * Enables default Spring MVC configuration and registers Spring MVC infrastructure components expected by the
<ide> * {@link DispatcherServlet}. Add this annotation to an application @{@link Configuration} class. It will in
<del> * turn import the @{@link Configuration} class {@link WebMvcConfiguration}, which provides default Spring MVC
<add> * turn import the @{@link Configuration} class {@link WebMvcConfiguration}, which provides default Spring MVC
<ide> * configuration.
<del> * <pre>
<add> * <pre class="code">
<ide> * @Configuration
<ide> * @EnableWebMvc
<ide> * @ComponentScan(
<del> * basePackageClasses = { MyConfiguration.class },
<add> * basePackageClasses = { MyConfiguration.class },
<ide> * excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Configuration.class) }
<ide> * )
<ide> * public class MyConfiguration {
<ide> * {@link WebMvcConfigurerAdapter} overriding specific methods. Your @{@link Configuration} class and any other
<ide> * Spring bean that implements {@link WebMvcConfigurer} will be detected and given an opportunity to customize
<ide> * the default Spring MVC configuration through the callback methods on the {@link WebMvcConfigurer} interface.
<del> * <pre>
<add> * <pre class="code">
<ide> * @Configuration
<ide> * @EnableWebMvc
<ide> * @ComponentScan( | 4 |
Python | Python | add type annotations for sqlite | 1bca31b541c9c39fb8e79131e1dd4a868b5122d4 | <ide><path>airflow/providers/sqlite/hooks/sqlite.py
<ide> class SqliteHook(DbApiHook):
<ide> conn_name_attr = 'sqlite_conn_id'
<ide> default_conn_name = 'sqlite_default'
<ide>
<del> def get_conn(self):
<add> def get_conn(self) -> sqlite3.dbapi2.Connection:
<ide> """
<ide> Returns a sqlite connection object
<ide> """
<ide><path>airflow/providers/sqlite/operators/sqlite.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>from typing import Iterable, Mapping, Optional, Union
<add>from typing import Any, Iterable, Mapping, Optional, Union
<ide>
<ide> from airflow.models import BaseOperator
<ide> from airflow.providers.sqlite.hooks.sqlite import SqliteHook
<ide> def __init__(
<ide> self.sql = sql
<ide> self.parameters = parameters or []
<ide>
<del> def execute(self, context):
<add> def execute(self, context: Mapping[Any, Any]) -> None:
<ide> self.log.info('Executing: %s', self.sql)
<ide> hook = SqliteHook(sqlite_conn_id=self.sqlite_conn_id)
<ide> hook.run(self.sql, parameters=self.parameters) | 2 |
Javascript | Javascript | fix typo in 'attributes' description | 9bf9c236cf5364ed7bfe01b770444eb9c3ef5450 | <ide><path>src/ng/compile.js
<ide> function directiveNormalize(name) {
<ide> *
<ide> * @description
<ide> * A shared object between directive compile / linking functions which contains normalized DOM
<del> * element attributes. The the values reflect current binding state `{{ }}`. The normalization is
<add> * element attributes. The values reflect current binding state `{{ }}`. The normalization is
<ide> * needed since all of these are treated as equivalent in Angular:
<ide> *
<ide> * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> | 1 |
PHP | PHP | fix coding standards | 932c9d4e2fffcccdd82648753334c1b6cf174dec | <ide><path>lib/Cake/Test/Case/Cache/CacheTest.php
<ide> public function testInvalidConfig() {
<ide> $read = Cache::read('Test', 'invalid');
<ide> }
<ide>
<del>
<ide> /**
<ide> * Test reading from a config that is undefined.
<ide> *
<ide><path>lib/Cake/Test/Case/Cache/Engine/ApcEngineTest.php
<ide> public function testExpiry() {
<ide> $result = Cache::read('other_test', 'apc');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::set(array('duration' => 1), 'apc');
<add> Cache::set(array('duration' => 1), 'apc');
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('other_test', $data, 'apc');
<ide> public function testDecrement() {
<ide>
<ide> $result = Cache::read('test_decrement', 'apc');
<ide> $this->assertEquals(2, $result);
<del>
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Cache/Engine/FileEngineTest.php
<ide> public function testExpiry() {
<ide> $result = Cache::read('other_test', 'file_test');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::set(array('duration' => "+1 second"), 'file_test');
<add> Cache::set(array('duration' => "+1 second"), 'file_test');
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('other_test', $data, 'file_test');
<ide> public function testMaskSetting() {
<ide> Cache::config('mask_test', array('engine' => 'File', 'path' => TMP . 'tests'));
<ide> $data = 'This is some test content';
<ide> $write = Cache::write('masking_test', $data, 'mask_test');
<del> $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS .'cake_masking_test')), -4);
<add> $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
<ide> $expected = '0664';
<ide> $this->assertEquals($expected, $result);
<ide> Cache::delete('masking_test', 'mask_test');
<ide> Cache::drop('mask_test');
<ide>
<ide> Cache::config('mask_test', array('engine' => 'File', 'mask' => 0666, 'path' => TMP . 'tests'));
<ide> $write = Cache::write('masking_test', $data, 'mask_test');
<del> $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS .'cake_masking_test')), -4);
<add> $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
<ide> $expected = '0666';
<ide> $this->assertEquals($expected, $result);
<ide> Cache::delete('masking_test', 'mask_test');
<ide> Cache::drop('mask_test');
<ide>
<ide> Cache::config('mask_test', array('engine' => 'File', 'mask' => 0644, 'path' => TMP . 'tests'));
<ide> $write = Cache::write('masking_test', $data, 'mask_test');
<del> $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS .'cake_masking_test')), -4);
<add> $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
<ide> $expected = '0644';
<ide> $this->assertEquals($expected, $result);
<ide> Cache::delete('masking_test', 'mask_test');
<ide> Cache::drop('mask_test');
<ide>
<ide> Cache::config('mask_test', array('engine' => 'File', 'mask' => 0640, 'path' => TMP . 'tests'));
<ide> $write = Cache::write('masking_test', $data, 'mask_test');
<del> $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS .'cake_masking_test')), -4);
<add> $result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
<ide> $expected = '0640';
<ide> $this->assertEquals($expected, $result);
<ide> Cache::delete('masking_test', 'mask_test');
<ide> Cache::drop('mask_test');
<ide> }
<add>
<ide> }
<ide><path>lib/Cake/Test/Case/Cache/Engine/MemcacheEngineTest.php
<ide> App::uses('MemcacheEngine', 'Cache/Engine');
<ide>
<ide> class TestMemcacheEngine extends MemcacheEngine {
<add>
<ide> /**
<ide> * public accessor to _parseServerString
<ide> *
<ide> public function parseServerString($server) {
<ide> public function setMemcache($memcache) {
<ide> $this->_Memcache = $memcache;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testExpiry() {
<ide> $result = Cache::read('other_test', 'memcache');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::set(array('duration' => "+1 second"), 'memcache');
<add> Cache::set(array('duration' => "+1 second"), 'memcache');
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('other_test', $data, 'memcache');
<ide><path>lib/Cake/Test/Case/Cache/Engine/WincacheEngineTest.php
<ide> public function testExpiry() {
<ide> $result = Cache::read('other_test', 'wincache');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::set(array('duration' => 1), 'wincache');
<add> Cache::set(array('duration' => 1), 'wincache');
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('other_test', $data, 'wincache');
<ide> public function testDecrement() {
<ide>
<ide> $result = Cache::read('test_decrement', 'wincache');
<ide> $this->assertEquals(2, $result);
<del>
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Cache/Engine/XcacheEngineTest.php
<ide> public function testExpiry() {
<ide> $result = Cache::read('other_test');
<ide> $this->assertFalse($result);
<ide>
<del> Cache::set(array('duration' => "+1 second"));
<add> Cache::set(array('duration' => "+1 second"));
<ide>
<ide> $data = 'this is a test of the emergency broadcasting system';
<ide> $result = Cache::write('other_test', $data); | 6 |
Python | Python | fix test_write_only_fields not being executed | fca39f9dbbdbda7baa24efa6f16a0ce688349176 | <ide><path>tests/test_write_only_fields.py
<ide> def create(self, attrs):
<ide>
<ide> self.Serializer = ExampleSerializer
<ide>
<del> def write_only_fields_are_present_on_input(self):
<add> def test_write_only_fields_are_present_on_input(self):
<ide> data = {
<ide> 'email': 'foo@example.com',
<ide> 'password': '123'
<ide> def write_only_fields_are_present_on_input(self):
<ide> assert serializer.is_valid()
<ide> assert serializer.validated_data == data
<ide>
<del> def write_only_fields_are_not_present_on_output(self):
<add> def test_write_only_fields_are_not_present_on_output(self):
<ide> instance = {
<ide> 'email': 'foo@example.com',
<ide> 'password': '123' | 1 |
Ruby | Ruby | avoid unnecessary hashes with error options | 73fb6349c98742bb404bd7ad97184d19f32a8366 | <ide><path>activerecord/lib/active_record/validations/uniqueness.rb
<ide> def validate_each(record, attribute, value)
<ide> relation = relation.merge(options[:conditions]) if options[:conditions]
<ide>
<ide> if relation.exists?
<del> record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope, :conditions).merge(:value => value))
<add> error_options = options.except(:case_sensitive, :scope, :conditions)
<add> error_options[:value] = value
<add>
<add> record.errors.add(attribute, :taken, error_options)
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | fix required proptype | 3b9872265c7c07d5ba4d4e90720c72849a2b0bc7 | <ide><path>Libraries/Experimental/SwipeableRow/SwipeableListView.js
<ide> const SwipeableListView = React.createClass({
<ide> */
<ide> dataSource: PropTypes.instanceOf(SwipeableListViewDataSource).isRequired,
<ide> // Maximum distance to open to after a swipe
<del> maxSwipeDistance: PropTypes.number,
<add> maxSwipeDistance: PropTypes.number.isRequired,
<ide> // Callback method to render the swipeable view
<ide> renderRow: PropTypes.func.isRequired,
<ide> // Callback method to render the view that will be unveiled on swipe | 1 |
Python | Python | add bdist_mpkg, bdist_wininst to binary dists | 19220c47cf6138b4f42f67b9b4d80f2575e22145 | <ide><path>numpy/f2py/setup.py
<ide> def _get_f2py_shebang():
<ide> """ Return shebang line for f2py script
<ide>
<del> If we are building an egg or a wheel binary package, then the shebang line
<add> If we are building a binary distribution format, then the shebang line
<ide> should be ``#!python`` rather than ``#!`` followed by the contents of
<ide> ``sys.executable``.
<ide> """
<del> if set(('bdist_wheel', 'bdist_egg')).intersection(sys.argv):
<add> if set(('bdist_wheel', 'bdist_egg', 'bdist_mpkg', 'bdist_wininst',
<add> 'bdist_rpm')).intersection(sys.argv):
<ide> return '#!python'
<ide> return '#!' + sys.executable
<ide> | 1 |
Javascript | Javascript | fix use of k without definition | 70eec3685613801310ca3799289a96be883ae843 | <ide><path>examples/js/exporters/OBJExporter.js
<ide> THREE.OBJExporter.prototype = {
<ide> var normal = new THREE.Vector3();
<ide> var uv = new THREE.Vector2();
<ide>
<del> var i, j, l, m, face = [];
<add> var i, j, k, l, m, face = [];
<ide>
<ide> var parseMesh = function ( mesh ) {
<ide> | 1 |
Text | Text | add html_escape note to changelog | 0228a73b1094a3e19ad291d2ce4789890c09578a | <ide><path>activesupport/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<del>* ActiveSupport::JSON::Variable is deprecated. Define your own #as_json and #encode_json methods
<del> for custom JSON string literals. *Erich Menge*
<del>
<del>* Add String#indent. *fxn & Ace Suares*
<del>
<del>* Inflections can now be defined per locale. `singularize` and `pluralize` accept locale as an extra argument. *David Celis*
<del>
<del>* `Object#try` will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new `Object#try!` *DHH*
<add>* `ERB::Util.html_escape` now escapes single quotes. *Santiago Pastorino*
<ide>
<ide> * `Time#change` now works with time values with offsets other than UTC or the local time zone. *Andrew White*
<ide> | 1 |
Javascript | Javascript | fix bad calls to .undelegate() | 8b4bd89addd2bab64656f699ee003aea03987c63 | <ide><path>test/unit/event.js
<ide> test("bind/delegate bubbling, isDefaultPrevented", function() {
<ide> });
<ide> fakeClick( $anchor2 );
<ide> $anchor2.unbind( "click" );
<del> $main.undelegate( "click" );
<add> $main.undelegate( "#foo", "click" );
<ide> $anchor2.click(function(e) {
<ide> // Let the default action occur
<ide> });
<ide> test("bind/delegate bubbling, isDefaultPrevented", function() {
<ide> });
<ide> fakeClick( $anchor2 );
<ide> $anchor2.unbind( "click" );
<del> $main.undelegate( "click" );
<add> $main.undelegate( "#foo", "click" );
<ide> });
<ide>
<ide> test("bind(), iframes", function() {
<ide> test("toggle(Function, Function, ...)", function() {
<ide> });
<ide>
<ide> test(".live()/.die()", function() {
<del> expect(66);
<add> expect(65);
<ide>
<ide> var submit = 0, div = 0, livea = 0, liveb = 0;
<ide>
<ide> test(".live()/.die()", function() {
<ide> jQuery("body").trigger("click");
<ide> equals( clicked, 2, "live with a context" );
<ide>
<del> // Make sure the event is actually stored on the context
<del> ok( jQuery._data(container, "events").live, "live with a context" );
<del>
<ide> // Test unbinding with a different context
<ide> jQuery("#foo", container).die("click");
<ide> jQuery("#foo").trigger("click");
<ide> test("live with special events", function() {
<ide> jQuery("#liveSpan1").trigger("foo");
<ide>
<ide> // Run: Handler 1, Default
<del> // TODO: Namespace doesn't trigger default (?)
<ide> jQuery("#liveSpan1").trigger("foo.a");
<ide>
<ide> // Run: remove
<ide> test("live with special events", function() {
<ide> });
<ide>
<ide> test(".delegate()/.undelegate()", function() {
<del> expect(65);
<add> expect(64);
<ide>
<ide> var submit = 0, div = 0, livea = 0, liveb = 0;
<ide>
<ide> test(".delegate()/.undelegate()", function() {
<ide> jQuery("body").trigger("click");
<ide> equals( clicked, 2, "delegate with a context" );
<ide>
<del> // Make sure the event is actually stored on the context
<del> ok( jQuery._data(container, "events").live, "delegate with a context" );
<del>
<ide> // Test unbinding with a different context
<ide> jQuery("#qunit-fixture").undelegate("#foo", "click");
<ide> jQuery("#foo").trigger("click"); | 1 |
Ruby | Ruby | support multiple inserts | 5d6d14cb6be217abc04253da0fe49721d09e9575 | <ide><path>lib/arel/insert_manager.rb
<ide> def insert fields
<ide> self
<ide> end
<ide>
<del> def create_values values, columns
<add> def create_values values, columns = nil
<ide> Nodes::Values.new values, columns
<ide> end
<add>
<add> def create_tuple values
<add> Nodes::Tuple.new values
<add> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes.rb
<ide> require 'arel/nodes/insert_statement'
<ide> require 'arel/nodes/update_statement'
<ide> require 'arel/nodes/bind_param'
<add>require 'arel/nodes/tuple'
<ide>
<ide> # terminal
<ide>
<ide><path>lib/arel/nodes/tuple.rb
<add># frozen_string_literal: true
<add>module Arel
<add> module Nodes
<add> class Tuple < Node
<add> attr_reader :values
<add>
<add> def initialize(values)
<add> @values = values
<add> super()
<add> end
<add> end
<add> end
<add>end
<ide><path>lib/arel/visitors/to_sql.rb
<ide> def visit_Arel_Nodes_InsertStatement o, collector
<ide> end
<ide>
<ide> if o.values
<add> collector << " VALUES"
<ide> maybe_visit o.values, collector
<ide> elsif o.select
<ide> maybe_visit o.select, collector
<ide> def visit_Arel_Nodes_False o, collector
<ide> collector << "FALSE"
<ide> end
<ide>
<add> def visit_Arel_Nodes_Tuple o, collector
<add> len = o.values.length - 1
<add> o.values.each_with_index { |value, i|
<add> collector = visit value, collector
<add> unless i == len
<add> collector << COMMA
<add> end
<add> }
<add> collector
<add> end
<add>
<ide> def visit_Arel_Nodes_Values o, collector
<del> collector << "VALUES ("
<add> collector << "("
<ide>
<ide> len = o.expressions.length - 1
<ide> o.expressions.each_with_index { |value, i|
<ide><path>test/test_insert_manager.rb
<ide> module Arel
<ide> }
<ide> end
<ide>
<add> it 'inserts multiple values' do
<add> table = Table.new(:users)
<add> manager = Arel::InsertManager.new
<add> manager.into table
<add>
<add> manager.columns << table[:id]
<add> manager.columns << table[:name]
<add>
<add> manager.values = manager.create_tuple([
<add> manager.create_values(%w{ 1 david }),
<add> manager.create_values(%w{ 2 kirs }),
<add> manager.create_values(["3", Arel.sql('DEFAULT')], []),
<add> ])
<add>
<add> manager.to_sql.must_be_like %{
<add> INSERT INTO \"users\" (\"id\", \"name\") VALUES ('1', 'david'), ('2', 'kirs'), ('3', DEFAULT)
<add> }
<add> end
<add>
<ide> it "inserts false" do
<ide> table = Table.new(:users)
<ide> manager = Arel::InsertManager.new
<ide><path>test/test_table.rb
<ide> module Arel
<ide> end
<ide>
<ide> it 'should return an insert manager' do
<del> im = @relation.compile_insert 'VALUES(NULL)'
<add> im = @relation.compile_insert '(NULL)'
<ide> assert_kind_of Arel::InsertManager, im
<ide> im.into Table.new(:users)
<del> assert_equal "INSERT INTO \"users\" VALUES(NULL)", im.to_sql
<add> assert_equal "INSERT INTO \"users\" VALUES (NULL)", im.to_sql
<ide> end
<ide>
<ide> describe 'skip' do
<ide><path>test/visitors/test_to_sql.rb
<ide> def compile node
<ide> bp = Nodes::BindParam.new
<ide> values = Nodes::Values.new([bp])
<ide> sql = compile values
<del> sql.must_be_like 'VALUES (?)'
<add> sql.must_be_like '(?)'
<ide> end
<ide>
<ide> it 'can define a dispatch method' do | 7 |
Python | Python | add missing emoticon | ff04748eb6bdfc0906ff968c4181ec2890ee0fdd | <ide><path>spacy/language_data/emoticons.py
<ide> :/
<ide> :-/
<ide> =/
<add>=|
<ide> :|
<ide> :-|
<ide> :1 | 1 |
Java | Java | implement containsproperty on mappropertysource | e71fbb9f46cd3bd49b68ef30a156bc0715bd979e | <ide><path>spring-core/src/main/java/org/springframework/core/env/MapPropertySource.java
<ide>
<ide> import java.util.Map;
<ide>
<add>import org.springframework.util.Assert;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> public String[] getPropertyNames() {
<ide> return StringUtils.toStringArray(this.source.keySet());
<ide> }
<ide>
<add> @Override
<add> public boolean containsProperty(String name) {
<add> Assert.notNull(name, "Property name must not be null");
<add> boolean containsProperty = this.source.containsKey(name);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug(String.format("PropertySource [%s] %s '%s'", getName(),
<add> (containsProperty ? "contains" : "does not contain"), name));
<add> }
<add> return containsProperty;
<add> }
<add>
<ide> } | 1 |
Text | Text | remove extra parentheses in privacy readme | d23fdb5876e98797f6e8f4ea6c984811b2142737 | <ide><path>privacy/README.md
<ide> proposing new student training approaches.
<ide>
<ide> To ask questions, please email `nicolas@papernot.fr` or open an issue on
<ide> the `tensorflow/models` issues tracker. Please assign issues to
<del>[(@npapernot)](https://github.com/npapernot).
<add>[@npapernot](https://github.com/npapernot). | 1 |
Text | Text | add extra info about the library | 4444ba2a8ce436c081cc88a6ede48638fc847b63 | <ide><path>guide/english/data-science-tools/pandas/index.md
<ide> title: pandas
<ide> 
<ide>
<ide> ## pandas
<del>[pandas](http://pandas.pydata.org/) is a Python library for data analysis using data frames. Data frames are tables of data, which may conceptually be compared to a spreadsheet. Data scientists familiar with R will feel at home here. pandas is often used along with numpy, pyplot, and scikit-learn.
<add>[pandas](http://pandas.pydata.org/) is a Python library for data analysis using data frames. The name `pandas` comes from *panel data*, i.e. a multi-dimensional data measured over time. Data frames are tables of data, which may conceptually be compared to a spreadsheet. Data scientists familiar with R will feel at home here. pandas is often used along with numpy, scipy, pyplot, seaborn and scikit-learn.
<ide>
<ide> ### Importing pandas
<ide> It is a widely used convention to import the pandas library using the alias `pd`: | 1 |
Mixed | Javascript | provide a way to copy files in exportpathmap | a8a97b07c7990c14e80f5f7d40e38c367b67a22b | <ide><path>README.md
<ide> next build
<ide> next export
<ide> ```
<ide>
<del>By default `next export` doesn't require any configuration. It will generate a default `exportPathMap` containing the routes to pages inside the `pages` directory.
<add>By default `next export` doesn't require any configuration. It will generate a default `exportPathMap` containing the routes to pages inside the `pages` directory. This default mapping is available as `defaultPathMap` in the example below.
<ide>
<ide> If your application has dynamic routes you can add a dynamic `exportPathMap` in `next.config.js`.
<ide> This function is asynchronous and gets the default `exportPathMap` as a parameter.
<ide> For an example, simply visit the `out` directory and run following command to de
<ide> now
<ide> ```
<ide>
<add>### Copying custom files
<add>
<add>In case you have to copy custom files like a robots.txt or generate a sitemap.xml you can do this inside of `exportPathMap`.
<add>`exportPathMap` gets a few contextual parameter to aid you with creating/copying files:
<add>
<add>- `dev` - `true` when `exportPathMap` is being called in development. `false` when running `next export`. In development `exportPathMap` is used to define routes and behavior like copying files is not required.
<add>- `dir` - Absolute path to the project directory
<add>- `outDir` - Absolute path to the `out` directory (configurable with `-o` or `--outdir`). When `dev` is `true` the value of `outDir` will be `null`.
<add>- `distDir` - Absolute path to the `.next` directory (configurable using the `distDir` config key)
<add>- `buildId` - The buildId the export is running for
<add>
<add>```js
<add>// next.config.js
<add>const fs = require('fs')
<add>const {join} = require('path')
<add>const {promisify} = require('util')
<add>const copyFile = promisify(fs.copyFile)
<add>
<add>module.exports = {
<add> exportPathMap: async function (defaultPathMap, {dev, dir, outDir, distDir, buildId}) {
<add> if (dev) {
<add> return defaultPathMap
<add> }
<add> // This will copy robots.txt from your project root into the out directory
<add> await copyFile(join(dir, 'robots.txt'), join(outDir, 'robots.txt'))
<add> return defaultPathMap
<add> }
<add>}
<add>```
<add>
<ide> ### Limitation
<ide>
<ide> With `next export`, we build a HTML version of your app. At export time we will run `getInitialProps` of your pages.
<ide><path>export/index.js
<ide> import { setAssetPrefix } from '../lib/asset'
<ide> import * as envConfig from '../lib/runtime-config'
<ide>
<ide> export default async function (dir, options, configuration) {
<add> function log (message) {
<add> if (options.silent) return
<add> console.log(message)
<add> }
<add>
<ide> dir = resolve(dir)
<ide> const nextConfig = configuration || loadConfig(PHASE_EXPORT, dir)
<ide> const distDir = join(dir, nextConfig.distDir)
<ide> export default async function (dir, options, configuration) {
<ide> )
<ide> }
<ide>
<del> // Copy dynamic import chunks
<del> if (existsSync(join(distDir, 'chunks'))) {
<del> log(' copying dynamic import chunks')
<del>
<del> await mkdirp(join(outDir, '_next', 'webpack'))
<del> await cp(
<del> join(distDir, 'chunks'),
<del> join(outDir, '_next', 'webpack', 'chunks')
<del> )
<del> }
<del>
<ide> // Get the exportPathMap from the config file
<ide> if (typeof nextConfig.exportPathMap !== 'function') {
<ide> console.log(`> No "exportPathMap" found in "${CONFIG_FILE}". Generating map from "./pages"`)
<ide> export default async function (dir, options, configuration) {
<ide> nextExport: true
<ide> }
<ide>
<del> const exportPathMap = await nextConfig.exportPathMap(defaultPathMap)
<add> const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {dev: false, dir, outDir, distDir, buildId})
<ide> const exportPaths = Object.keys(exportPathMap)
<ide>
<ide> for (const path of exportPaths) {
<ide> export default async function (dir, options, configuration) {
<ide>
<ide> // Add an empty line to the console for the better readability.
<ide> log('')
<del>
<del> function log (message) {
<del> if (options.silent) return
<del> console.log(message)
<del> }
<ide> }
<ide><path>server/index.js
<ide> export default class Server {
<ide> // So that the user doesn't have to define a custom server reading the exportPathMap
<ide> if (this.dev && this.nextConfig.exportPathMap) {
<ide> console.log('Defining routes from exportPathMap')
<del> const exportPathMap = await this.nextConfig.exportPathMap({}) // In development we can't give a default path mapping
<add> const exportPathMap = await this.nextConfig.exportPathMap({}, {dev: true, dir: this.dir, outDir: null, distDir: this.distDir, buildId: this.buildId}) // In development we can't give a default path mapping
<ide> for (const path in exportPathMap) {
<ide> const {page, query = {}} = exportPathMap[path]
<ide> routes[path] = async (req, res, params, parsedUrl) => { | 3 |
Text | Text | remove double word "where" | 31522406b1f618f50ac78b28b533c4e3b2ca0ff9 | <ide><path>doc/guides/cve_management_process.md
<ide> advance. These CVEs are managed in a repository within the Node.js
<ide> private organization called
<ide> [cve-management](https://github.com/nodejs-private/cve-management).
<ide> For each year there will be a markdown file titled "cve-management-XXXX"
<del>where where XXXX is the year (for example 'cve-management-2017.md').
<add>where XXXX is the year (for example 'cve-management-2017.md').
<ide>
<ide> This file will have the following sections:
<ide> | 1 |
Python | Python | add trivial keras model | b09685fe4cf64afa1e92fa6970ee713ff5ece86b | <ide><path>official/resnet/keras/keras_common.py
<ide> def define_keras_flags():
<ide> """Define flags for Keras models."""
<ide> flags.DEFINE_boolean(name='enable_eager', default=False, help='Enable eager?')
<ide> flags.DEFINE_boolean(name='skip_eval', default=False, help='Skip evaluation?')
<add> flags.DEFINE_boolean(name='use_trivial_model', default=False,
<add> help='Whether to use a trivial Keras model.')
<ide> flags.DEFINE_boolean(
<ide> name='enable_xla', default=False,
<ide> help='Whether to enable XLA auto jit compilation. This is still an '
<ide><path>official/resnet/keras/keras_imagenet_main.py
<ide> from official.resnet import imagenet_main
<ide> from official.resnet.keras import keras_common
<ide> from official.resnet.keras import resnet_model
<add>from official.resnet.keras import trivial_model
<ide> from official.utils.flags import core as flags_core
<ide> from official.utils.logs import logger
<ide> from official.utils.misc import distribution_utils
<ide> def run(flags_obj):
<ide> # can be enabled with a single line of code.
<ide> optimizer = tf.keras.mixed_precision.experimental.LossScaleOptimizer(
<ide> optimizer, loss_scale=flags_core.get_loss_scale(flags_obj))
<del> model = resnet_model.resnet50(num_classes=imagenet_main.NUM_CLASSES,
<del> dtype=dtype)
<add>
<add> if flags_obj.use_trivial_model:
<add> model = trivial_model.trivial_model(imagenet_main.NUM_CLASSES)
<add> else:
<add> model = resnet_model.resnet50(num_classes=imagenet_main.NUM_CLASSES,
<add> dtype=dtype)
<ide>
<ide> model.compile(loss='sparse_categorical_crossentropy',
<ide> optimizer=optimizer,
<ide><path>official/resnet/keras/trivial_model.py
<add># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""A trivial model for Keras."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>from tensorflow.python.keras import backend
<add>from tensorflow.python.keras import layers
<add>from tensorflow.python.keras import models
<add>
<add>
<add>def trivial_model(num_classes):
<add> """Trivial model for ImageNet dataset."""
<add>
<add> input_shape = (224, 224, 3)
<add> img_input = layers.Input(shape=input_shape)
<add>
<add> x = layers.Lambda(lambda x: backend.reshape(x, [-1, 224 * 224 * 3]),
<add> name='reshape')(img_input)
<add> x = layers.Dense(num_classes, activation='softmax', name='fc1000')(x)
<add>
<add> return models.Model(img_input, x, name='trivial') | 3 |
Javascript | Javascript | fix missing negation | e39e9c134c1f6043a5c86d838f2a31ac67b2ca9d | <ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> if(this.error) return true;
<ide>
<ide> // always rebuild when module is not cacheable
<del> if(this.cacheable) return true;
<add> if(!this.cacheable) return true;
<ide>
<ide> const highestFileDepTimestamp = this.getHighestTimestamp(
<ide> this.fileDependencies, fileTimestamps); | 1 |
Python | Python | delay import from inspect to reduce startup time | a80dbfe6e36a1c4cc455c3ce9b6e563588c7524c | <ide><path>numpy/testing/utils.py
<ide> import sys
<ide> import re
<ide> import operator
<del>from inspect import isfunction
<ide> from nosetester import import_nose
<ide>
<ide> __all__ = ['assert_equal', 'assert_almost_equal','assert_approx_equal',
<ide> def decorate_methods(cls, decorator, testmatch=None):
<ide> else:
<ide> testmatch = re.compile(testmatch)
<ide> cls_attr = cls.__dict__
<add>
<add> # delayed import to reduce startup time
<add> from inspect import isfunction
<add>
<ide> methods = filter(isfunction, cls_attr.values())
<ide> for function in methods:
<ide> try: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.