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
Python
Python
catch exception if pathlib not install
0c970caa4a0d7744df89666c537fd5e6adc2a3eb
<ide><path>pytorch_pretrained_bert/file_utils.py <ide> from pathlib import Path <ide> PYTORCH_PRETRAINED_BERT_CACHE = Path(os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', <ide> Path.home() / '.pytorch_pretrained_bert')) <del>except AttributeError: <add>except (AttributeError, ImportError): <ide> PYTORCH_PRETRAINED_BERT_CACHE = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', <ide> os.path.join(os.path.expanduser("~"), '.pytorch_pretrained_bert')) <ide>
1
Python
Python
fix construction of input examples for roberta
d812e6d76e39bd3a5e037524ccb1c3bc9b6c2420
<ide><path>examples/token-classification/run_pl_ner.py <ide> def prepare_data(self): <ide> cls_token=self.tokenizer.cls_token, <ide> cls_token_segment_id=2 if self.config.model_type in ["xlnet"] else 0, <ide> sep_token=self.tokenizer.sep_token, <del> sep_token_extra=bool(self.config.model_type in ["roberta"]), <add> sep_token_extra=False, <ide> pad_on_left=bool(self.config.model_type in ["xlnet"]), <ide> pad_token=self.tokenizer.pad_token_id, <ide> pad_token_segment_id=self.tokenizer.pad_token_type_id, <ide><path>examples/token-classification/utils_ner.py <ide> def __init__( <ide> cls_token=tokenizer.cls_token, <ide> cls_token_segment_id=2 if model_type in ["xlnet"] else 0, <ide> sep_token=tokenizer.sep_token, <del> sep_token_extra=bool(model_type in ["roberta"]), <add> sep_token_extra=False, <ide> # roberta uses an extra separator b/w pairs of sentences, cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805 <ide> pad_on_left=bool(tokenizer.padding_side == "left"), <ide> pad_token=tokenizer.pad_token_id, <ide> def __init__( <ide> cls_token=tokenizer.cls_token, <ide> cls_token_segment_id=2 if model_type in ["xlnet"] else 0, <ide> sep_token=tokenizer.sep_token, <del> sep_token_extra=bool(model_type in ["roberta"]), <add> sep_token_extra=False, <ide> # roberta uses an extra separator b/w pairs of sentences, cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805 <ide> pad_on_left=bool(tokenizer.padding_side == "left"), <ide> pad_token=tokenizer.pad_token_id,
2
PHP
PHP
add typehint to view cell
67390558aa7c16f2d6bb86a5e7b0ee029f5c54cc
<ide><path>src/View/Cell.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> abstract class Cell implements EventDispatcherInterface <ide> * @param array $cellOptions Cell options to apply. <ide> */ <ide> public function __construct( <del> ServerRequest $request = null, <del> Response $response = null, <del> EventManagerInterface $eventManager = null, <add> ?ServerRequest $request = null, <add> ?Response $response = null, <add> ?EventManagerInterface $eventManager = null, <ide> array $cellOptions = [] <ide> ) { <ide> if ($eventManager !== null) { <ide> public function __construct( <ide> * <ide> * @return void <ide> */ <del> public function initialize() <add> public function initialize(): void <ide> { <ide> } <ide> <ide> public function initialize() <ide> * @return string The rendered cell. <ide> * @throws \Cake\View\Exception\MissingCellViewException When a MissingTemplateException is raised during rendering. <ide> */ <del> public function render($template = null) <add> public function render(?string $template = null): string <ide> { <ide> $cache = []; <ide> if ($this->_cache) { <ide><path>src/View/CellTrait.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> trait CellTrait <ide> * @throws \Cake\View\Exception\MissingCellException If Cell class was not found. <ide> * @throws \BadMethodCallException If Cell class does not specified cell action. <ide> */ <del> protected function cell($cell, array $data = [], array $options = []) <add> protected function cell(string $cell, array $data = [], array $options = []): Cell <ide> { <ide> $parts = explode('::', $cell); <ide>
2
PHP
PHP
allow retrieving entity from entitycontext
1952f855a18a20ff134e11972f62bdc587bf1851
<ide><path>src/View/Form/EntityContext.php <ide> public function val($field) <ide> return null; <ide> } <ide> $parts = explode('.', $field); <del> $entity = $this->_getEntity($parts); <add> $entity = $this->entity($parts); <ide> <ide> if (end($parts) === '_ids' && !empty($entity)) { <ide> return $this->_extractMultiple($entity, $parts); <ide> protected function _extractMultiple($values, $path) <ide> * entity. If the path does not contain a leaf entity false <ide> * will be returned. <ide> * <del> * @param array $path Each one of the parts in a path for a field name <del> * @return \Cake\DataSource\EntityInterface|bool <add> * @param array|null $path Each one of the parts in a path for a field name <add> * or null to get the entity passed in contructor context. <add> * @return \Cake\DataSource\EntityInterface|\Traversable|array|bool <ide> * @throws \RuntimeException When properties cannot be read. <ide> */ <del> protected function _getEntity($path) <add> public function entity($path = null) <ide> { <add> if ($path === null) { <add> return $this->_context['entity']; <add> } <add> <ide> $oneElement = count($path) === 1; <ide> if ($oneElement && $this->_isCollection) { <ide> return false; <ide> protected function _getProp($target, $field) <ide> public function isRequired($field) <ide> { <ide> $parts = explode('.', $field); <del> $entity = $this->_getEntity($parts); <add> $entity = $this->entity($parts); <ide> <ide> $isNew = true; <ide> if ($entity instanceof Entity) { <ide> protected function _getValidator($parts) <ide> return !is_numeric($part); <ide> }); <ide> $key = implode('.', $keyParts); <del> $entity = $this->_getEntity($parts) ?: null; <add> $entity = $this->entity($parts) ?: null; <ide> <ide> if (isset($this->_validator[$key])) { <ide> $this->_validator[$key]->provider('entity', $entity); <ide> public function hasError($field) <ide> public function error($field) <ide> { <ide> $parts = explode('.', $field); <del> $entity = $this->_getEntity($parts); <add> $entity = $this->entity($parts); <ide> <ide> if ($entity instanceof Entity) { <ide> return $entity->errors(array_pop($parts)); <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> public function setUp() <ide> $this->request = new Request(); <ide> } <ide> <add> /** <add> * Test getting entity back from context. <add> * <add> * @return void <add> */ <add> public function testEntity() <add> { <add> $row = new Article(); <add> $context = new EntityContext($this->request, [ <add> 'entity' => $row, <add> ]); <add> $this->assertSame($row, $context->entity()); <add> } <add> <ide> /** <ide> * Test getting primary key data. <ide> *
2
Java
Java
fix various compiler warnings in spring-context
40357be72bcd687972c0778f03593d076fe05d98
<ide><path>spring-context/src/test/java/example/scannable/ServiceInvocationCounter.java <ide> public void serviceExecution() {} <ide> @Before("serviceExecution()") <ide> public void countUse() { <ide> this.useCount++; <del> this.threadLocalCount.set(this.useCount); <del> System.out.println(""); <add> threadLocalCount.set(this.useCount); <ide> } <ide> <ide> public int getCount() { <ide><path>spring-context/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java <ide> public Object resolveContextualObject(String key) { <ide> } <ide> <ide> public void close() { <del> for (Iterator it = this.callbacks.iterator(); it.hasNext();) { <del> Runnable runnable = (Runnable) it.next(); <add> for (Iterator<Runnable> it = this.callbacks.iterator(); it.hasNext();) { <add> Runnable runnable = it.next(); <ide> runnable.run(); <ide> } <ide> } <ide><path>spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java <ide> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) <ide> <ide> <ide> @Test <del> @SuppressWarnings("static-access") <ide> public void staticBeanMethodsDoNotRespectScoping() { <ide> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <ide> ctx.register(ConfigWithStaticBeanMethod.class); <ide> ctx.refresh(); <del> <del> ConfigWithStaticBeanMethod config = ctx.getBean(ConfigWithStaticBeanMethod.class); <del> assertThat(config.testBean(), not(sameInstance(config.testBean()))); <add> assertThat(ConfigWithStaticBeanMethod.testBean(), not(sameInstance(ConfigWithStaticBeanMethod.testBean()))); <ide> } <ide> <ide> <ide><path>spring-context/src/test/java/org/springframework/validation/DataBinderTests.java <ide> public void testAddAllErrors() { <ide> assertEquals("badName", nameError.getCode()); <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> public void testBindingWithResortedList() { <ide> IndexedTestBean tb = new IndexedTestBean(); <ide> DataBinder binder = new DataBinder(tb, "tb"); <ide> public void testNestedGrowingList() { <ide> mpv.add("f[list][1]", "secondValue"); <ide> binder.bind(mpv); <ide> assertFalse(binder.getBindingResult().hasErrors()); <add> @SuppressWarnings("unchecked") <ide> List<Object> list = (List<Object>) form.getF().get("list"); <ide> assertEquals("firstValue", list.get(0)); <ide> assertEquals("secondValue", list.get(1));
4
Javascript
Javascript
add playbackrates() method
6259ef79e90c0a66172ac722015a3ab43a72d173
<ide><path>src/js/control-bar/playback-rate-menu/playback-rate-menu-button.js <ide> * @file playback-rate-menu-button.js <ide> */ <ide> import MenuButton from '../../menu/menu-button.js'; <del>import Menu from '../../menu/menu.js'; <ide> import PlaybackRateMenuItem from './playback-rate-menu-item.js'; <ide> import Component from '../../component.js'; <ide> import * as Dom from '../../utils/dom.js'; <ide> class PlaybackRateMenuButton extends MenuButton { <ide> <ide> this.on(player, 'loadstart', (e) => this.updateVisibility(e)); <ide> this.on(player, 'ratechange', (e) => this.updateLabel(e)); <add> this.on(player, 'playbackrateschange', (e) => this.handlePlaybackRateschange(e)); <ide> } <ide> <ide> /** <ide> class PlaybackRateMenuButton extends MenuButton { <ide> } <ide> <ide> /** <del> * Create the playback rate menu <add> * Create the list of menu items. Specific to each subclass. <ide> * <del> * @return {Menu} <del> * Menu object populated with {@link PlaybackRateMenuItem}s <ide> */ <del> createMenu() { <del> const menu = new Menu(this.player()); <add> createItems() { <ide> const rates = this.playbackRates(); <add> const items = []; <ide> <del> if (rates) { <del> for (let i = rates.length - 1; i >= 0; i--) { <del> menu.addChild(new PlaybackRateMenuItem(this.player(), {rate: rates[i] + 'x'})); <del> } <add> for (let i = rates.length - 1; i >= 0; i--) { <add> items.push(new PlaybackRateMenuItem(this.player(), {rate: rates[i] + 'x'})); <ide> } <ide> <del> return menu; <add> return items; <ide> } <ide> <ide> /** <ide> class PlaybackRateMenuButton extends MenuButton { <ide> this.player().playbackRate(newRate); <ide> } <ide> <add> /** <add> * On playbackrateschange, update the menu to account for the new items. <add> * <add> * @listens Player#playbackrateschange <add> */ <add> handlePlaybackRateschange(event) { <add> this.update(); <add> } <add> <ide> /** <ide> * Get possible playback rates <ide> * <ide> * @return {Array} <ide> * All possible playback rates <ide> */ <ide> playbackRates() { <del> return this.options_.playbackRates || (this.options_.playerOptions && this.options_.playerOptions.playbackRates); <add> return this.player().playbackRates() || []; <ide> } <ide> <ide> /** <ide><path>src/js/control-bar/playback-rate-menu/playback-rate-menu-item.js <ide> class PlaybackRateMenuItem extends MenuItem { <ide> <ide> // Modify options for parent MenuItem class's init. <ide> options.label = label; <del> options.selected = rate === 1; <add> options.selected = rate === player.playbackRate(); <ide> options.selectable = true; <ide> options.multiSelectable = false; <ide> <ide><path>src/js/player.js <ide> class Player extends Component { <ide> <ide> this.middleware_ = []; <ide> <add> this.playbackRates(options.playbackRates); <add> <ide> this.initChildren(); <ide> <ide> // Set isAudio based on whether or not an audio tag was used <ide> class Player extends Component { <ide> src: '', <ide> source: {}, <ide> sources: [], <add> playbackRates: [], <ide> volume: 1 <ide> }; <ide> } <ide> class Player extends Component { <ide> this.previousLogLevel_ = undefined; <ide> this.debugEnabled_ = false; <ide> } <add> <add> } <add> <add> /** <add> * Set or get current playback rates. <add> * Takes an array and updates the playback rates menu with the new items. <add> * Pass in an empty array to hide the menu. <add> * Values other than arrays are ignored. <add> * <add> * @fires Player#playbackrateschange <add> * @param {number[]} newRates <add> * The new rates that the playback rates menu should update to. <add> * An empty array will hide the menu <add> * @return {number[]} When used as a getter will return the current playback rates <add> */ <add> playbackRates(newRates) { <add> if (newRates === undefined) { <add> return this.cache_.playbackRates; <add> } <add> <add> // ignore any value that isn't an array <add> if (!Array.isArray(newRates)) { <add> return; <add> } <add> <add> // ignore any arrays that don't only contain numbers <add> if (!newRates.every((rate) => typeof rate === 'number')) { <add> return; <add> } <add> <add> this.cache_.playbackRates = newRates; <add> <add> /** <add> * fires when the playback rates in a player are changed <add> * <add> * @event Player#playbackrateschange <add> * @type {EventTarget~Event} <add> */ <add> this.trigger('playbackrateschange'); <ide> } <ide> } <ide> <ide><path>test/unit/controls.test.js <ide> QUnit.test('calculateDistance should use changedTouches, if available', function <ide> slider.dispose(); <ide> }); <ide> <del>QUnit.test('should hide playback rate control if it\'s not supported', function(assert) { <add>QUnit.test('playback rate button is hidden by default', function(assert) { <ide> assert.expect(1); <ide> <ide> const player = TestHelpers.makePlayer(); <ide> const playbackRate = new PlaybackRateMenuButton(player); <ide> <del> assert.ok(playbackRate.el().className.indexOf('vjs-hidden') >= 0, 'playbackRate is not hidden'); <add> assert.ok(playbackRate.el().className.indexOf('vjs-hidden') >= 0, 'playbackRate is hidden'); <add> <add> player.dispose(); <add> playbackRate.dispose(); <add>}); <add> <add>QUnit.test('playback rate button is not hidden if playback rates are set', function(assert) { <add> assert.expect(1); <add> <add> const player = TestHelpers.makePlayer({ <add> playbackRates: [1, 2, 3] <add> }); <add> const playbackRate = new PlaybackRateMenuButton(player); <add> <add> assert.ok(playbackRate.el().className.indexOf('vjs-hidden') === -1, 'playbackRate is not hidden'); <add> <add> player.dispose(); <add> playbackRate.dispose(); <add>}); <add> <add>QUnit.test('should show or hide playback rate menu button on playback rates change', function(assert) { <add> const rates = [1, 2, 3]; <add> const norates = []; <add> let playbackRatesReturnValue = rates; <add> const player = TestHelpers.makePlayer(); <add> <add> player.playbackRates = () => playbackRatesReturnValue; <add> <add> const playbackRate = new PlaybackRateMenuButton(player); <add> <add> assert.ok(playbackRate.el().className.indexOf('vjs-hidden') === -1, 'playbackRate is not hidden'); <add> <add> playbackRatesReturnValue = norates; <add> <add> player.trigger('playbackrateschange'); <add> <add> assert.ok(playbackRate.el().className.indexOf('vjs-hidden') >= 0, 'playbackRate is hidden'); <ide> <ide> player.dispose(); <ide> playbackRate.dispose(); <ide><path>test/unit/player.test.js <ide> QUnit.test('player#reset clears the player cache', function(assert) { <ide> player.src(sources); <ide> player.duration(10); <ide> player.playbackRate(0.5); <add> player.playbackRates([1, 2, 3]); <ide> player.volume(0.2); <ide> <ide> assert.strictEqual(player.currentSrc(), sources[0].src, 'currentSrc is correct'); <ide> assert.deepEqual(player.currentSource(), sources[0], 'currentSource is correct'); <ide> assert.deepEqual(player.currentSources(), sources, 'currentSources is correct'); <ide> assert.strictEqual(player.duration(), 10, 'duration is correct'); <ide> assert.strictEqual(player.playbackRate(), 0.5, 'playbackRate is correct'); <add> assert.deepEqual(player.playbackRates(), [1, 2, 3], 'playbackRates is correct'); <ide> assert.strictEqual(player.volume(), 0.2, 'volume is correct'); <ide> assert.strictEqual(player.lastVolume_(), 0.2, 'lastVolume_ is correct'); <ide> <ide> QUnit.test('player#reset clears the player cache', function(assert) { <ide> assert.strictEqual(player.getCache().currentTime, 0, 'currentTime is correct'); <ide> assert.ok(isNaN(player.duration()), 'duration is correct'); <ide> assert.strictEqual(player.playbackRate(), 1, 'playbackRate is correct'); <add> assert.deepEqual(player.playbackRates(), [], 'playbackRates is correct'); <ide> assert.strictEqual(player.volume(), 1, 'volume is correct'); <ide> assert.strictEqual(player.lastVolume_(), 1, 'lastVolume_ is correct'); <ide> }); <ide> QUnit[testOrSkip]('Should only allow requestPictureInPicture if the tech support <ide> player.requestPictureInPicture(); <ide> assert.equal(count, 1, 'requestPictureInPicture not passed through when tech does not support'); <ide> }); <add> <add>QUnit.test('playbackRates should trigger a playbackrateschange event', function(assert) { <add> const player = TestHelpers.makePlayer({}); <add> const rates = []; <add> let rateschangeCount = 0; <add> <add> player.on('playbackrateschange', function() { <add> rates.push(player.playbackRates()); <add> rateschangeCount++; <add> }); <add> <add> player.playbackRates([1, 2, 3]); <add> player.playbackRates([]); <add> player.playbackRates([1, 4]); <add> <add> assert.equal(rateschangeCount, 3, 'we got 3 playbackrateschange events'); <add> assert.deepEqual(rates[0], [1, 2, 3], 'first rates is 1,2,3'); <add> assert.deepEqual(rates[1], [], 'second rates is empty'); <add> assert.deepEqual(rates[2], [1, 4], 'third rates is 1,4'); <add> <add> player.dispose(); <add>}); <add> <add>QUnit.test('playbackRates only accepts arrays of numbers', function(assert) { <add> const player = TestHelpers.makePlayer(); <add> let rateschangeCount = 0; <add> <add> player.on('playbackrateschange', function() { <add> rateschangeCount++; <add> }); <add> <add> player.playbackRates([1, 2, 3]); <add> assert.equal(rateschangeCount, 1, 'we got a playbackrateschange event'); <add> <add> player.playbackRates('hello'); <add> assert.equal(rateschangeCount, 1, 'we did not get a playbackrateschange event'); <add> <add> player.playbackRates([1, 4]); <add> assert.equal(rateschangeCount, 2, 'we got a playbackrateschange event'); <add> <add> player.playbackRates(5); <add> assert.equal(rateschangeCount, 2, 'we did not get a playbackrateschange event'); <add> <add> player.playbackRates(['hello', '2', 'why?']); <add> assert.equal(rateschangeCount, 2, 'we did not get a playbackrateschange event'); <add> <add> player.dispose(); <add>});
5
Javascript
Javascript
handle emit('error') before ctor
63edde0e01e577691002c2f2e39fb30abccec1bc
<ide><path>lib/events.js <ide> EventEmitter.prototype.setMaxListeners = function(n) { <ide> EventEmitter.prototype.emit = function(type) { <ide> var er, handler, len, args, i, listeners; <ide> <add> if (!this._events) <add> this._events = {}; <add> <ide> // If there is no 'error' event listener then throw. <ide> if (type === 'error') { <ide> if (!this._events.error || <ide> EventEmitter.prototype.emit = function(type) { <ide> } <ide> } <ide> <del> if (!this._events) <del> this._events = {}; <del> <ide> handler = this._events[type]; <ide> <ide> if (typeof handler === 'undefined') <ide><path>test/simple/test-event-emitter-subclass.js <ide> var myee = new MyEE(function() { <ide> called = true; <ide> }); <ide> <add> <add>util.inherits(ErrorEE, EventEmitter); <add>function ErrorEE() { <add> this.emit('error', new Error('blerg')); <add>} <add> <add>assert.throws(function() { <add> new ErrorEE(); <add>}, /blerg/); <add> <ide> process.on('exit', function() { <ide> assert(called); <ide> console.log('ok');
2
PHP
PHP
fix coding standards
d64b7ed3af6290b4748316e61a46402c6add75fc
<ide><path>lib/Cake/Controller/Component/RequestHandlerComponent.php <ide> public function isAjax() { <ide> public function isFlash() { <ide> return $this->request->is('flash'); <ide> } <del>; <add> <ide> /** <ide> * Returns true if the current request is over HTTPS, false otherwise. <ide> * <ide><path>lib/Cake/Controller/Controller.php <ide> use Cake\Routing\Router; <ide> use Cake\Utility\ClassRegistry; <ide> use Cake\Utility\Inflector; <del>use Cake\Utility\ObjectCollection; <ide> use Cake\Utility\MergeVariablesTrait; <add>use Cake\Utility\ObjectCollection; <ide> use Cake\Utility\ViewVarsTrait; <ide> use Cake\View\View; <ide> <ide><path>lib/Cake/Test/TestApp/Plugin/TestPlugin/Controller/Component/OtherComponent.php <ide> */ <ide> namespace TestPlugin\Controller\Component; <ide> <del>use Cake\Core\Object; <ide> use Cake\Controller\Component; <add>use Cake\Core\Object; <ide> <ide> class OtherComponent extends Component { <ide> } <ide><path>lib/Cake/Test/TestCase/Controller/ComponentCollectionTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Controller; <ide> <del>use Cake\Controller\Controller; <del>use Cake\Controller\ComponentCollection; <ide> use Cake\Controller\Component\CookieComponent; <add>use Cake\Controller\ComponentCollection; <add>use Cake\Controller\Controller; <ide> use Cake\Core\App; <ide> use Cake\Core\Plugin; <ide> use Cake\TestSuite\TestCase; <ide><path>lib/Cake/Test/TestCase/Controller/ControllerTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Controller; <ide> <del>use Cake\Controller\Controller; <ide> use Cake\Controller\Component; <add>use Cake\Controller\Controller; <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <ide> use Cake\Core\Object;
5
Text
Text
update instructions for modifying hint topics
a2c5e2379e8307ea3b3e2b1c99da4c80e335f3cc
<ide><path>docs/how-to-work-on-coding-challenges.md <ide> Here are specific formatting guidelines for the challenge seed code: <ide> <ide> Each challenge has a `Get a Hint` button, so a user can access any hints/solutions which have been created for the challenge. Curriculum hints/solutions topics are located on [our forum](https://www.freecodecamp.org/forum/c/guide) under the `Guide` category. <ide> <del>If you find a problem with an existing challenge's hints/solutions topic, you can make suggestions in the comments below the main wiki post if you are at least a level 3 forum user. Select moderators will review the comments and decide whether or not to include the changes in the existing topic. <add>If you find a problem with an existing challenge's hints/solutions topic, you can make suggestions in the [contributors category](https://www.freecodecamp.org/forum/c/contributors) on the forum. Moderators and users with trust level 3 will review the comments and decide whether or not to include the changes in the corresponding hint/solutions topic. <ide> <del>### Adding new Challenge hints/solutionsd Topics <del> <del>Only moderators can add new hints and solutions topics when new challenges are added to the curriculum. <add>### Adding new Challenge hints/solutions Topics <ide> <ide> Take the following steps when adding a new challenge hints/solutions related topic. <ide>
1
Text
Text
add content into activity section
62884faa2ec954392d00d8ba561783564511beed
<ide><path>guide/english/android-development/core-components/index.md <ide> Core components are the essential elements contained in an Android app. Each of <ide> ### [Activities](https://developer.android.com/guide/components/activities/) <ide> An _activity_ is a component that has a user interface and represents a single screen in an Android app. An app can have multiple activities, each of which can be an entry point to the application itself for the user or the system (an app's activity that wants to open another activity that belongs to the same application or to a different one). <ide> <add>An activity facilitates the following key interactions between system and app: <add>- Keeping track of what the user currently cares about (what is on screen) to ensure that the system keeps running the process that is hosting the activity. <add> <add> <ide> #### [Activity Lifecycle](https://developer.android.com/guide/components/activities/activity-lifecycle) <ide> ![Activity Lifecycle](https://developer.android.com/images/activity_lifecycle.png) <ide>
1
Text
Text
convert releasing rails guide to markdown
bbcbe6e9c86b6291411f10fdc7ce099a998dc314
<add><path>RELEASING_RAILS.md <del><path>RELEASING_RAILS.rdoc <del>= Releasing Rails <add># Releasing Rails <ide> <ide> In this document, we'll cover the steps necessary to release Rails. Each <ide> section contains steps to take during that time before the release. The times <ide> suggested in each header are just that: suggestions. However, they should <ide> really be considered as minimums. <ide> <del>== 10 Days before release <add>## 10 Days before release <ide> <ide> Today is mostly coordination tasks. Here are the things you must do today: <ide> <del>=== Is the CI green? If not, make it green. (See "Fixing the CI") <add>### Is the CI green? If not, make it green. (See "Fixing the CI") <ide> <ide> Do not release with a Red CI. You can find the CI status here: <ide> <del> http://travis-ci.org/rails/rails <add>``` <add>http://travis-ci.org/rails/rails <add>``` <ide> <del>=== Is Sam Ruby happy? If not, make him happy. <add>### Is Sam Ruby happy? If not, make him happy. <ide> <ide> Sam Ruby keeps a test suite that makes sure the code samples in his book (Agile <ide> Web Development with Rails) all work. These are valuable integration tests <ide> for Rails. You can check the status of his tests here: <ide> <del> http://intertwingly.net/projects/dashboard.html <add>``` <add>http://intertwingly.net/projects/dashboard.html <add>``` <ide> <ide> Do not release with Red AWDwR tests. <ide> <del>=== Do we have any Git dependencies? If so, contact those authors. <add>### Do we have any Git dependencies? If so, contact those authors. <ide> <ide> Having Git dependencies indicates that we depend on unreleased code. <ide> Obviously Rails cannot be released when it depends on unreleased code. <ide> Contact the authors of those particular gems and work out a release date that <ide> suits them. <ide> <del>=== Contact the security team (either Koz or tenderlove) <add>### Contact the security team (either Koz or tenderlove) <ide> <ide> Let them know of your plans to release. There may be security issues to be <ide> addressed, and that can impact your release date. <ide> <del>=== Notify implementors. <add>### Notify implementors. <ide> <ide> Ruby implementors have high stakes in making sure Rails works. Be kind and <ide> give them a heads up that Rails will be released soonish. <ide> lists: <ide> <ide> Implementors will love you and help you. <ide> <del>== 3 Days before release <add>### 3 Days before release <ide> <ide> This is when you should release the release candidate. Here are your tasks <ide> for today: <ide> <del>=== Is the CI green? If not, make it green. <add>### Is the CI green? If not, make it green. <ide> <del>=== Is Sam Ruby happy? If not, make him happy. <add>### Is Sam Ruby happy? If not, make him happy. <ide> <del>=== Contact the security team. CVE emails must be sent on this day. <add>### Contact the security team. CVE emails must be sent on this day. <ide> <del>=== Create a release branch. <add>### Create a release branch. <ide> <ide> From the stable branch, create a release branch. For example, if you're <ide> releasing Rails 3.0.10, do this: <ide> <del> [aaron@higgins rails (3-0-stable)]$ git checkout -b 3-0-10 <del> Switched to a new branch '3-0-10' <del> [aaron@higgins rails (3-0-10)]$ <add>``` <add>[aaron@higgins rails (3-0-stable)]$ git checkout -b 3-0-10 <add>Switched to a new branch '3-0-10' <add>[aaron@higgins rails (3-0-10)]$ <add>``` <ide> <del>=== Update each CHANGELOG. <add>### Update each CHANGELOG. <ide> <ide> Many times commits are made without the CHANGELOG being updated. You should <ide> review the commits since the last release, and fill in any missing information <ide> for each CHANGELOG. <ide> <ide> You can review the commits for the 3.0.10 release like this: <ide> <del> [aaron@higgins rails (3-0-10)]$ git log v3.0.9.. <add>``` <add>[aaron@higgins rails (3-0-10)]$ git log v3.0.9.. <add>``` <ide> <ide> If you're doing a stable branch release, you should also ensure that all of <ide> the CHANGELOG entries in the stable branch are also synced to the master <ide> branch. <ide> <del>=== Update the RAILS_VERSION file to include the RC. <add>### Update the RAILS_VERSION file to include the RC. <ide> <del>=== Build and test the gem. <add>### Build and test the gem. <ide> <ide> Run `rake install` to generate the gems and install them locally. Then try <ide> generating a new app and ensure that nothing explodes. <ide> <ide> This will stop you from looking silly when you push an RC to rubygems.org and <ide> then realize it is broken. <ide> <del>=== Release the gem. <add>### Release the gem. <ide> <ide> IMPORTANT: Due to YAML parse problems on the rubygems.org server, it is safest <ide> to use Ruby 1.8 when releasing. <ide> RAILS_VERSION, commit the changes, tag it, and push the gems to rubygems.org. <ide> Here are the commands that `rake release` should use, so you can understand <ide> what to do in case anything goes wrong: <ide> <del> $ rake all:build <del> $ git commit -am'updating RAILS_VERSION' <del> $ git tag -m 'v3.0.10.rc1 release' v3.0.10.rc1 <del> $ git push <del> $ git push --tags <del> $ for i in $(ls pkg); do gem push $i; done <add>``` <add>$ rake all:build <add>$ git commit -am'updating RAILS_VERSION' <add>$ git tag -m 'v3.0.10.rc1 release' v3.0.10.rc1 <add>$ git push <add>$ git push --tags <add>$ for i in $(ls pkg); do gem push $i; done <add>``` <ide> <del>=== Send Rails release announcements <add>### Send Rails release announcements <ide> <ide> Write a release announcement that includes the version, changes, and links to <ide> GitHub where people can find the specific commit list. Here are the mailing <ide> IMPORTANT: If any users experience regressions when using the release <ide> candidate, you *must* postpone the release. Bugfix releases *should not* <ide> break existing applications. <ide> <del>=== Post the announcement to the Rails blog. <add>### Post the announcement to the Rails blog. <ide> <ide> If you used Markdown format for your email, you can just paste it in to the <ide> blog. <ide> <ide> * http://weblog.rubyonrails.org <ide> <del>=== Post the announcement to the Rails Twitter account. <add>### Post the announcement to the Rails Twitter account. <ide> <del>== Time between release candidate and actual release <add>## Time between release candidate and actual release <ide> <ide> Check the rails-core mailing list and the GitHub issue list for regressions in <ide> the RC. <ide> When you fix the regressions, do not create a new branch. Fix them on the <ide> stable branch, then cherry pick the commit to your release branch. No other <ide> commits should be added to the release branch besides regression fixing commits. <ide> <del>== Day of release <add>## Day of release <ide> <ide> Many of these steps are the same as for the release candidate, so if you need <ide> more explanation on a particular step, see the RC steps. <ide> Today, do this stuff in this order: <ide> * Email security lists <ide> * Email general announcement lists <ide> <del>=== Emailing the Rails security announce list <add>### Emailing the Rails security announce list <ide> <ide> Email the security announce list once for each vulnerability fixed. <ide> <ide> so we need to give them the security fixes in patch form. <ide> * Merge the release branch to the stable branch. <ide> * Drink beer (or other cocktail) <ide> <del>== Misc <add>## Misc <ide> <del>=== Fixing the CI <add>### Fixing the CI <ide> <ide> There are two simple steps for fixing the CI: <ide> <ide> 1. Identify the problem <ide> 2. Fix it <ide> <del>Repeat these steps until the CI is green. <add>Repeat these steps until the CI is green. <ide>\ No newline at end of file
1
Ruby
Ruby
pull install tests into a separate class
b49d3bd0a99d2ffb7d85e0fd3a13decf820ff85c
<ide><path>Library/Homebrew/test/test_pathname.rb <ide> def test_install_removes_original <ide> refute_predicate @file, :exist? <ide> end <ide> <add> def test_install_creates_intermediate_directories <add> touch @file <add> refute_predicate @dir, :directory? <add> @dir.install(@file) <add> assert_predicate @dir, :directory? <add> end <add> <add> def test_install_renamed <add> @dir.extend(InstallRenamed) <add> <add> @file.write "a" <add> @dir.install @file <add> @file.write "b" <add> @dir.install @file <add> <add> assert_equal "a", File.read(@[email protected]) <add> assert_equal "b", File.read(@dir+"#{@file.basename}.default") <add> end <add>end <add> <add>class PathnameInstallTests < PathnameExtensionTests <ide> def setup_install_test <ide> (@src+'a.txt').write 'This is sample file a.' <ide> (@src+'b.txt').write 'This is sample file b.' <ide> def test_install_symlink <ide> assert_predicate @dst+"bin/b.txt", :exist? <ide> assert_predicate (@dst+"bin").readlink, :relative? <ide> end <del> <del> def test_install_creates_intermediate_directories <del> touch @file <del> refute_predicate @dir, :directory? <del> @dir.install(@file) <del> assert_predicate @dir, :directory? <del> end <del> <del> def test_install_renamed <del> @dir.extend(InstallRenamed) <del> <del> @file.write "a" <del> @dir.install @file <del> @file.write "b" <del> @dir.install @file <del> <del> assert_equal "a", File.read(@[email protected]) <del> assert_equal "b", File.read(@dir+"#{@file.basename}.default") <del> end <ide> end
1
Ruby
Ruby
fix formula version
3ee158bf16882c1a0c8b83f292ff303e7bef410e
<ide><path>Library/Homebrew/dev-cmd/pr-upload.rb <ide> def check_bottled_formulae(json_files) <ide> <ide> hashes.each do |name, hash| <ide> formula_path = HOMEBREW_REPOSITORY/hash["formula"]["path"] <del> formula_version = Formulary.factory(formula_path).version <add> formula_version = Formulary.factory(formula_path).pkg_version <ide> bottle_version = Version.new hash["formula"]["pkg_version"] <ide> next if formula_version == bottle_version <ide>
1
Javascript
Javascript
update copyright header in browserify config
d3c12487fd456f79b96c3985fbfbac95a518887c
<ide><path>grunt/config/browserify.js <ide> var LICENSE_TEMPLATE = <ide> '/**\n\ <ide> * @PACKAGE@ v@VERSION@\n\ <ide> *\n\ <del> * Copyright 2013 Facebook, Inc.\n\ <add> * Copyright 2013-2014 Facebook, Inc.\n\ <ide> *\n\ <ide> * Licensed under the Apache License, Version 2.0 (the "License");\n\ <ide> * you may not use this file except in compliance with the License.\n\
1
PHP
PHP
pass the locator to associationcollection
535f99f733b77636b8987783a73c2c211e0fc56f
<ide><path>src/ORM/AssociationCollection.php <ide> <ide> use ArrayIterator; <ide> use Cake\Datasource\EntityInterface; <add>use Cake\ORM\Locator\LocatorAwareTrait; <ide> use InvalidArgumentException; <ide> use IteratorAggregate; <ide> <ide> class AssociationCollection implements IteratorAggregate <ide> { <ide> <ide> use AssociationsNormalizerTrait; <add> use LocatorAwareTrait; <ide> <ide> /** <ide> * Stored associations <ide><path>src/ORM/Locator/TableLocator.php <ide> <ide> use Cake\Core\App; <ide> use Cake\Datasource\ConnectionManager; <add>use Cake\ORM\AssociationCollection; <ide> use Cake\ORM\Table; <ide> use Cake\Utility\Inflector; <ide> use RuntimeException; <ide> public function get($alias, array $options = []) <ide> } <ide> $options['connection'] = ConnectionManager::get($connectionName); <ide> } <add> if (empty($options['associations'])) { <add> $associations = new AssociationCollection(); <add> $associations->setTableLocator($this); <add> $options['associations'] = $associations; <add> } <ide> <ide> $options['registryAlias'] = $alias; <ide> $this->_instances[$alias] = $this->_create($options); <ide><path>tests/TestCase/ORM/Locator/TableLocatorTest.php <ide> public function testGet() <ide> $result2 = $this->_locator->get('Articles'); <ide> $this->assertSame($result, $result2); <ide> $this->assertEquals('my_articles', $result->table()); <add> <add> $this->assertSame($this->_locator, $result->associations()->getTableLocator()); <ide> } <ide> <ide> /**
3
Javascript
Javascript
add extra checks in simple/test-cli-eval
19a432260cd2a2981c067c88f37f71206d23ccd2
<ide><path>test/simple/test-cli-eval.js <ide> var filename = __filename.replace(/\\/g, '/'); <ide> child.exec(nodejs + ' --eval 42', <ide> function(err, stdout, stderr) { <ide> assert.equal(stdout, ''); <add> assert.equal(stderr, ''); <ide> }); <ide> <ide> // assert that "42\n" is written to stderr <ide> child.exec(nodejs + ' --eval "console.error(42)"', <ide> function(err, stdout, stderr) { <add> assert.equal(stdout, ''); <ide> assert.equal(stderr, '42\n'); <ide> }); <ide> <ide> child.exec(nodejs + ' --eval "console.error(42)"', <ide> child.exec(cmd + '42', <ide> function(err, stdout, stderr) { <ide> assert.equal(stdout, '42\n'); <add> assert.equal(stderr, ''); <ide> }); <ide> <ide> child.exec(cmd + "'[]'", <ide> function(err, stdout, stderr) { <ide> assert.equal(stdout, '[]\n'); <add> assert.equal(stderr, ''); <ide> }); <ide> }); <ide> <ide> child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { <ide> child.exec(nodejs + ' -p "\\-42"', <ide> function(err, stdout, stderr) { <ide> assert.equal(stdout, '-42\n'); <add> assert.equal(stderr, ''); <ide> });
1
Python
Python
add flag to enable xla in keras models
4571d3fa39d3e12ce141a5513e4156c837505889
<ide><path>official/resnet/keras/keras_cifar_main.py <ide> def learning_rate_schedule(current_epoch, <ide> Returns: <ide> Adjusted learning rate. <ide> """ <add> del current_batch, batches_per_epoch # not used <ide> initial_learning_rate = keras_common.BASE_LEARNING_RATE * batch_size / 128 <ide> learning_rate = initial_learning_rate <ide> for mult, start_epoch in LR_SCHEDULE: <ide> def run(flags_obj): <ide> Returns: <ide> Dictionary of training and eval stats. <ide> """ <add> config = keras_common.get_config_proto() <ide> # TODO(tobyboyd): Remove eager flag when tf 1.0 testing ends. <ide> # Eager is default in tf 2.0 and should not be toggled <del> if flags_obj.enable_eager and not keras_common.is_v2_0(): <del> tf.compat.v1.enable_eager_execution() <add> if not keras_common.is_v2_0(): <add> if flags_obj.enable_eager: <add> tf.compat.v1.enable_eager_execution(config=config) <add> else: <add> sess = tf.Session(config=config) <add> tf.keras.backend.set_session(sess) <add> # TODO(haoyuzhang): Set config properly in TF2.0 when the config API is ready. <ide> <ide> dtype = flags_core.get_tf_dtype(flags_obj) <ide> if dtype == 'fp16': <ide><path>official/resnet/keras/keras_common.py <ide> # pylint: disable=g-bad-import-order <ide> from absl import flags <ide> import tensorflow as tf <add> <add>from tensorflow.core.protobuf import rewriter_config_pb2 <ide> from tensorflow.python.keras.optimizer_v2 import (gradient_descent as <ide> gradient_descent_v2) <ide> <ide> def __init__(self, batch_size, log_steps): <ide> <ide> Args: <ide> batch_size: Total batch size. <add> log_steps: Interval of time history logs. <ide> <ide> """ <ide> self.batch_size = batch_size <ide> def on_batch_begin(self, batch, logs=None): <ide> 'change learning rate to %s.', self.epochs, batch, lr) <ide> <ide> <add>def get_config_proto(): <add> """Return config proto according to flag settings, or None to use default.""" <add> config = None <add> if FLAGS.enable_xla: <add> config = tf.ConfigProto() <add> config.graph_options.optimizer_options.global_jit_level = ( <add> tf.OptimizerOptions.ON_2) <add> # Disable PinToHostOptimizer in grappler when enabling XLA because it causes <add> # OOM and performance regression. <add> config.graph_options.rewrite_options.pin_to_host_optimization = ( <add> rewriter_config_pb2.RewriterConfig.OFF) <add> return config <add> <add> <ide> def get_optimizer(): <ide> """Returns optimizer to use.""" <ide> # The learning_rate is overwritten at the beginning of each step by callback. <ide> def build_stats(history, eval_output, time_callback): <ide> <ide> <ide> def define_keras_flags(): <add> """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( <add> name='enable_xla', default=False, <add> help='Whether to enable XLA auto jit compilation. This is still an ' <add> 'experimental feature, and is not yet effective with TF 2.0.') <ide> flags.DEFINE_integer( <ide> name='train_steps', default=None, <ide> help='The number of steps to run for training. If it is larger than ' <ide><path>official/resnet/keras/keras_imagenet_main.py <ide> def run(flags_obj): <ide> <ide> Raises: <ide> ValueError: If fp16 is passed as it is not currently supported. <add> <add> Returns: <add> Dictionary of training and eval stats. <ide> """ <add> config = keras_common.get_config_proto() <ide> # TODO(tobyboyd): Remove eager flag when tf 1.0 testing ends. <ide> # Eager is default in tf 2.0 and should not be toggled <del> if flags_obj.enable_eager and not keras_common.is_v2_0(): <del> tf.compat.v1.enable_eager_execution() <add> if not keras_common.is_v2_0(): <add> if flags_obj.enable_eager: <add> tf.compat.v1.enable_eager_execution(config=config) <add> else: <add> sess = tf.Session(config=config) <add> tf.keras.backend.set_session(sess) <add> # TODO(haoyuzhang): Set config properly in TF2.0 when the config API is ready. <ide> <ide> dtype = flags_core.get_tf_dtype(flags_obj) <ide> if dtype == 'fp16':
3
Java
Java
compare kind references before checking log levels
801f196de05a2d8424c30a66bede6f9a5bfa713d
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJWeaverMessageHandler.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class AspectJWeaverMessageHandler implements IMessageHandler { <ide> public boolean handleMessage(IMessage message) throws AbortException { <ide> Kind messageKind = message.getKind(); <ide> <del> if (LOGGER.isDebugEnabled() || LOGGER.isTraceEnabled()) { <del> if (messageKind == IMessage.DEBUG) { <add> if (messageKind == IMessage.DEBUG) { <add> if (LOGGER.isDebugEnabled() || LOGGER.isTraceEnabled()) { <ide> LOGGER.debug(makeMessageFor(message)); <ide> return true; <ide> } <ide> } <del> <del> if (LOGGER.isInfoEnabled()) { <del> if ((messageKind == IMessage.INFO) || (messageKind == IMessage.WEAVEINFO)) { <add> else if ((messageKind == IMessage.INFO) || (messageKind == IMessage.WEAVEINFO)) { <add> if (LOGGER.isInfoEnabled()) { <ide> LOGGER.info(makeMessageFor(message)); <ide> return true; <ide> } <ide> } <del> <del> if (LOGGER.isWarnEnabled()) { <del> if (messageKind == IMessage.WARNING) { <add> else if (messageKind == IMessage.WARNING) { <add> if (LOGGER.isWarnEnabled()) { <ide> LOGGER.warn(makeMessageFor(message)); <ide> return true; <ide> } <ide> } <del> <del> if (LOGGER.isErrorEnabled()) { <del> if (messageKind == IMessage.ERROR) { <add> else if (messageKind == IMessage.ERROR) { <add> if (LOGGER.isErrorEnabled()) { <ide> LOGGER.error(makeMessageFor(message)); <ide> return true; <ide> } <ide> } <del> <del> if (LOGGER.isFatalEnabled()) { <del> if (messageKind == IMessage.ABORT) { <add> else if (messageKind == IMessage.ABORT) { <add> if (LOGGER.isFatalEnabled()) { <ide> LOGGER.fatal(makeMessageFor(message)); <ide> return true; <ide> }
1
Javascript
Javascript
remove extra blank lines
bbf623208f6c4f48a10cc4505474002d49e1bcb6
<ide><path>examples/todomvc/components/MainSection.js <ide> import React, { PropTypes } from 'react'; <ide> import TodoItem from './TodoItem'; <ide> <ide> export default class MainSection { <del> <ide> static propTypes = { <ide> todos: PropTypes.array.isRequired, <ide> actions: PropTypes.object.isRequired <ide> }; <ide> <ide> render() { <del> <ide> let toggleAll = null; <ide> if (this.props.todos.length > 0) { <ide> toggleAll = (
1
Ruby
Ruby
clarify index_by and index_with docs [ci skip]
94b7453089d48049e4ad469edbb1865719d34ff1
<ide><path>activesupport/lib/active_support/core_ext/enumerable.rb <ide> def sum(identity = nil, &block) <ide> end <ide> end <ide> <del> # Convert an enumerable to a hash keying it by the block return value. <add> # Convert an enumerable to a hash, using the block result as the key and the <add> # element as the value. <ide> # <ide> # people.index_by(&:login) <ide> # # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...} <ide> def index_by <ide> end <ide> end <ide> <del> # Convert an enumerable to a hash keying it with the enumerable items and with the values returned in the block. <add> # Convert an enumerable to a hash, using the element as the key and the block <add> # result as the value. <ide> # <ide> # post = Post.new(title: "hey there", body: "what's up?") <ide> # <ide> # %i( title body ).index_with { |attr_name| post.public_send(attr_name) } <ide> # # => { title: "hey there", body: "what's up?" } <add> # <add> # If an argument is passed instead of a block, it will be used as the value <add> # for all elements: <add> # <add> # %i( created_at updated_at ).index_with(Time.now) <add> # # => { created_at: 2020-03-09 22:31:47, updated_at: 2020-03-09 22:31:47 } <ide> def index_with(default = INDEX_WITH_DEFAULT) <ide> if block_given? <ide> result = {}
1
Go
Go
allow overwrite in untar
5a3d774e5651da772a065282a1fb1a31e19e911c
<ide><path>archive/archive.go <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> // identity (uncompressed), gzip, bzip2, xz. <ide> // If `dest` does not exist, it is created unless there are multiple entries in `archive`. <ide> // In the latter case, an error is returned. <del>// An other error is returned if `dest` exists but is not a directory, to prevent overwriting. <add>// If `dest` is an existing file, it gets overwritten. <add>// If `dest` is an existing directory, its files get merged (with overwrite for conflicting files). <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> if archive == nil { <ide> return fmt.Errorf("Empty archive") <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> <ide> var ( <ide> dirs []*tar.Header <del> destNotExist bool <add> create bool <ide> multipleEntries bool <ide> ) <ide> <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> return err <ide> } <ide> // destination does not exist, so it is assumed it has to be created. <del> destNotExist = true <add> create = true <ide> } else if !fi.IsDir() { <del> return fmt.Errorf("Trying to untar to `%s`: exists but not a directory", dest) <add> // destination exists and is not a directory, so it will be overwritten. <add> create = true <ide> } <ide> <ide> // Iterate through the files in the archive. <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> } <ide> <ide> // Return an error if destination needs to be created and there is more than 1 entry in the tar stream. <del> if destNotExist && multipleEntries { <add> if create && multipleEntries { <ide> return fmt.Errorf("Trying to untar an archive with multiple entries to an inexistant target `%s`: did you mean `%s` instead?", dest, filepath.Dir(dest)) <ide> } <ide> <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> } <ide> <ide> var path string <del> if destNotExist { <add> if create { <ide> path = dest // we are renaming hdr.Name to dest <ide> } else { <ide> path = filepath.Join(dest, hdr.Name) <ide> func Untar(archive io.Reader, dest string, options *TarOptions) error { <ide> } <ide> } <ide> } <add> <ide> if err := createTarFile(path, dest, hdr, tr, options == nil || !options.NoLchown); err != nil { <ide> return err <ide> } <ide><path>archive/archive_test.go <ide> func TestTarUntarFile(t *testing.T) { <ide> if err := ioutil.WriteFile(path.Join(origin, "before", "file"), []byte("hello world"), 0700); err != nil { <ide> t.Fatal(err) <ide> } <add> if err := ioutil.WriteFile(path.Join(origin, "after", "file2"), []byte("please overwrite me"), 0700); err != nil { <add> t.Fatal(err) <add> } <ide> <ide> tar, err := TarWithOptions(path.Join(origin, "before"), &TarOptions{Compression: Uncompressed, Includes: []string{"file"}}) <ide> if err != nil {
2
Python
Python
fix 1.4 tests and make flatten_choice a utility
ee2afb83e2e531922a5fc10c236f8b17b30fae82
<ide><path>rest_framework/fields.py <ide> def set_value(dictionary, keys, value): <ide> dictionary[keys[-1]] = value <ide> <ide> <add>def flatten_choice(choice): <add> """ <add> Convert a single choices choice into a flat list of choices. <add> <add> Returns a list of choices pairs. <add> <add> flatten_choice(1) -> [(1, 1)] <add> flatten_choice((1, '1st')) -> [(1, '1st')] <add> flatten_choice(('Grp', ((1, '1st'), (2, '2nd')))) -> [(1, '1st'), (2, '2nd')] <add> """ <add> # Allow single, paired or grouped choices style: <add> # choices = [1, 2, 3] <add> # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] <add> # choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')] <add> if (not isinstance(choice, (list, tuple))): <add> # single choice <add> return [(choice, choice)] <add> else: <add> key, display_value = choice <add> if isinstance(display_value, (list, tuple)): <add> # grouped choices <add> sub_choices = [flatten_choice(c) for c in display_value] <add> return list(itertools.chain(*sub_choices)) <add> else: <add> # paired choice <add> return [(key, display_value)] <add> <add> <ide> class CreateOnlyDefault(object): <ide> """ <ide> This class may be used to provide default values that are only used <ide> class ChoiceField(Field): <ide> } <ide> <ide> def __init__(self, choices, **kwargs): <del> flat_choices = [self.flatten_choice(c) for c in choices] <del> self.choices = OrderedDict(itertools.chain(*flat_choices)) <add> flat_choices = [flatten_choice(c) for c in choices] <add> self.choices = OrderedDict(list(itertools.chain(*flat_choices))) <ide> <ide> # Map the string representation of choices to the underlying value. <ide> # Allows us to deal with eg. integer choices while supporting either <ide> def __init__(self, choices, **kwargs): <ide> <ide> super(ChoiceField, self).__init__(**kwargs) <ide> <del> def flatten_choice(self, choice): <del> """ <del> Convert a choices choice into a flat list of choices. <del> <del> Returns a list of choices. <del> """ <del> <del> # Allow single, paired or grouped choices style: <del> # choices = [1, 2, 3] <del> # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] <del> # choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')] <del> if (not isinstance(choice, (list, tuple))): <del> # single choice <del> return [(choice, choice)] <del> else: <del> key, display_value = choice <del> if isinstance(display_value, (list, tuple)): <del> # grouped choices <del> sub_choices = [self.flatten_choice(c) for c in display_value] <del> return list(itertools.chain(*sub_choices)) <del> else: <del> # paired choice <del> return [(key, display_value)] <del> <ide> def to_internal_value(self, data): <ide> if data == '' and self.allow_blank: <ide> return ''
1
PHP
PHP
add language line for file validation rule
cd032040441787c827aa07c428ae753281b685df
<ide><path>resources/lang/en/validation.php <ide> 'distinct' => 'The :attribute field has a duplicate value.', <ide> 'email' => 'The :attribute must be a valid email address.', <ide> 'exists' => 'The selected :attribute is invalid.', <add> 'file' => 'The :attribute must be a file.', <ide> 'filled' => 'The :attribute field is required.', <ide> 'image' => 'The :attribute must be an image.', <ide> 'in' => 'The selected :attribute is invalid.',
1
Ruby
Ruby
document the partialiteration object
7dc0f3fc8d3160db3408ef5a20c43a7268c0cd8e
<ide><path>actionview/lib/action_view/renderer/partial_renderer.rb <ide> require 'thread_safe' <ide> <ide> module ActionView <del> class PartialIteration # :nodoc: <del> attr_reader :size, :index <add> class PartialIteration <add> # The number of iterations that will be done by the partial. <add> attr_reader :size <add> <add> # The current iteration of the partial. <add> attr_reader :index <ide> <ide> def initialize(size) <ide> @size = size <ide> @index = 0 <ide> end <ide> <add> # Check if this is the first iteration of the partial. <ide> def first? <ide> index == 0 <ide> end <ide> <add> # Check if this is the last iteration of the partial. <ide> def last? <ide> index == size - 1 <ide> end <ide> <del> def iterate! <add> def iterate! # :nodoc: <ide> @index += 1 <ide> end <ide> end
1
Text
Text
streamline errors.md introductory material
4ee50e714cda9a1d3e7f76d7eb3fcc53e7c0d8d5
<ide><path>doc/api/errors.md <ide> Applications running in Node.js will generally experience four categories of <ide> errors: <ide> <del>- Standard JavaScript errors such as: <del> - {EvalError} : thrown when a call to `eval()` fails. <del> - {SyntaxError} : thrown in response to improper JavaScript language <del> syntax. <del> - {RangeError} : thrown when a value is not within an expected range <del> - {ReferenceError} : thrown when using undefined variables <del> - {TypeError} : thrown when passing arguments of the wrong type <del> - {URIError} : thrown when a global URI handling function is misused. <add>- Standard JavaScript errors such as {EvalError}, {SyntaxError}, {RangeError}, <add> {ReferenceError}, {TypeError}, and {URIError}. <ide> - System errors triggered by underlying operating system constraints such <del> as attempting to open a file that does not exist, attempting to send data <del> over a closed socket, etc; <del>- And User-specified errors triggered by application code. <del>- `AssertionError`s are a special class of error that can be triggered whenever <add> as attempting to open a file that does not exist or attempting to send data <add> over a closed socket. <add>- User-specified errors triggered by application code. <add>- `AssertionError`s are a special class of error that can be triggered when <ide> Node.js detects an exceptional logic violation that should never occur. These <ide> are raised typically by the `assert` module. <ide>
1
Ruby
Ruby
abandon top support
41b92914f89be855cc6af768f13fd5fc53c967fa
<ide><path>activerecord/lib/arel/nodes/select_core.rb <ide> module Arel # :nodoc: all <ide> module Nodes <ide> class SelectCore < Arel::Nodes::Node <del> attr_accessor :top, :projections, :wheres, :groups, :windows <add> attr_accessor :projections, :wheres, :groups, :windows <ide> attr_accessor :havings, :source, :set_quantifier <ide> <ide> def initialize <ide> super() <ide> @source = JoinSource.new nil <del> @top = nil <ide> <ide> # https://ronsavage.github.io/SQL/sql-92.bnf.html#set%20quantifier <ide> @set_quantifier = nil <ide> def initialize_copy(other) <ide> <ide> def hash <ide> [ <del> @source, @top, @set_quantifier, @projections, <add> @source, @set_quantifier, @projections, <ide> @wheres, @groups, @havings, @windows <ide> ].hash <ide> end <ide> <ide> def eql?(other) <ide> self.class == other.class && <ide> self.source == other.source && <del> self.top == other.top && <ide> self.set_quantifier == other.set_quantifier && <ide> self.projections == other.projections && <ide> self.wheres == other.wheres && <ide><path>activerecord/lib/arel/nodes/unary.rb <ide> def eql?(other) <ide> On <ide> Ordering <ide> RollUp <del> Top <ide> }.each do |name| <ide> const_set(name, Class.new(Unary)) <ide> end <ide><path>activerecord/lib/arel/select_manager.rb <ide> def with(*subqueries) <ide> def take(limit) <ide> if limit <ide> @ast.limit = Nodes::Limit.new(limit) <del> @ctx.top = Nodes::Top.new(limit) <ide> else <ide> @ast.limit = nil <del> @ctx.top = nil <ide> end <ide> self <ide> end <ide><path>activerecord/lib/arel/visitors/depth_first.rb <ide> def unary(o) <ide> alias :visit_Arel_Nodes_Ordering :unary <ide> alias :visit_Arel_Nodes_Ascending :unary <ide> alias :visit_Arel_Nodes_Descending :unary <del> alias :visit_Arel_Nodes_Top :unary <ide> alias :visit_Arel_Nodes_UnqualifiedColumn :unary <ide> <ide> def function(o) <ide><path>activerecord/lib/arel/visitors/dot.rb <ide> def unary(o) <ide> alias :visit_Arel_Nodes_Not :unary <ide> alias :visit_Arel_Nodes_Offset :unary <ide> alias :visit_Arel_Nodes_On :unary <del> alias :visit_Arel_Nodes_Top :unary <ide> alias :visit_Arel_Nodes_UnqualifiedColumn :unary <ide> alias :visit_Arel_Nodes_Preceding :unary <ide> alias :visit_Arel_Nodes_Following :unary <ide><path>activerecord/lib/arel/visitors/mssql.rb <ide> def initialize(*) <ide> <ide> private <ide> <del> # `top` wouldn't really work here. I.e. User.select("distinct first_name").limit(10) would generate <del> # "select top 10 distinct first_name from users", which is invalid query! it should be <del> # "select distinct top 10 first_name from users" <del> def visit_Arel_Nodes_Top(o) <del> "" <del> end <del> <ide> def visit_Arel_Visitors_MSSQL_RowNumber(o, collector) <ide> collector << "ROW_NUMBER() OVER (ORDER BY " <ide> inject_join(o.children, collector, ", ") << ") as _row_num" <ide><path>activerecord/lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_SelectOptions(o, collector) <ide> def visit_Arel_Nodes_SelectCore(o, collector) <ide> collector << "SELECT" <ide> <del> collector = maybe_visit o.top, collector <del> <ide> collector = maybe_visit o.set_quantifier, collector <ide> <ide> collect_nodes_for o.projections, collector, SPACE <ide> def visit_Arel_Nodes_Limit(o, collector) <ide> visit o.expr, collector <ide> end <ide> <del> # FIXME: this does nothing on most databases, but does on MSSQL <del> def visit_Arel_Nodes_Top(o, collector) <del> collector <del> end <del> <ide> def visit_Arel_Nodes_Lock(o, collector) <ide> visit o.expr, collector <ide> end <ide><path>activerecord/test/cases/arel/select_manager_test.rb <ide> def test_join_sources <ide> right = table.alias <ide> mgr = table.from <ide> mgr.join(right).on("omg") <del> mgr.to_sql.must_be_like %{ SELECT FROM "users" INNER JOIN "users" "users_2" ON omg } <add> mgr.to_sql.must_be_like %{ SELECT FROM "users" INNER JOIN "users" "users_2" ON omg } <ide> end <ide> <ide> it "converts to sqlliterals with multiple items" do <ide> table = Table.new :users <ide> right = table.alias <ide> mgr = table.from <ide> mgr.join(right).on("omg", "123") <del> mgr.to_sql.must_be_like %{ SELECT FROM "users" INNER JOIN "users" "users_2" ON omg AND 123 } <add> mgr.to_sql.must_be_like %{ SELECT FROM "users" INNER JOIN "users" "users_2" ON omg AND 123 } <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/arel/visitors/depth_first_test.rb <ide> def test_raises_with_object <ide> Arel::Nodes::Ordering, <ide> Arel::Nodes::StringJoin, <ide> Arel::Nodes::UnqualifiedColumn, <del> Arel::Nodes::Top, <ide> Arel::Nodes::Limit, <ide> Arel::Nodes::Else, <ide> ].each do |klass| <ide><path>activerecord/test/cases/arel/visitors/dot_test.rb <ide> def test_named_function <ide> Arel::Nodes::Offset, <ide> Arel::Nodes::Ordering, <ide> Arel::Nodes::UnqualifiedColumn, <del> Arel::Nodes::Top, <ide> Arel::Nodes::Limit, <ide> ].each do |klass| <ide> define_method("test_#{klass.name.gsub('::', '_')}") do
10
Java
Java
fix checkstyle violations
c4d7e6ff46348a34c55e45b1d26726d3ef6cf259
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java <ide> import org.mockito.junit.jupiter.MockitoSettings; <ide> import org.mockito.quality.Strictness; <ide> import org.reactivestreams.Publisher; <del>import org.springframework.web.reactive.function.BodyExtractors; <ide> import reactor.core.publisher.Mono; <ide> import reactor.test.StepVerifier; <ide> <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.codec.ClientCodecConfigurer; <add>import org.springframework.web.reactive.function.BodyExtractors; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java <ide> import org.junit.jupiter.api.Test; <ide> import org.junit.jupiter.params.ParameterizedTest; <ide> import org.junit.jupiter.params.provider.MethodSource; <del>import org.springframework.web.reactive.function.BodyExtractors; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> import reactor.netty.http.client.HttpClient; <ide> import org.springframework.http.client.reactive.HttpComponentsClientHttpConnector; <ide> import org.springframework.http.client.reactive.JettyClientHttpConnector; <ide> import org.springframework.http.client.reactive.ReactorClientHttpConnector; <add>import org.springframework.web.reactive.function.BodyExtractors; <ide> import org.springframework.web.testfixture.xml.Pojo; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat;
2
Python
Python
reduce complexity linear_discriminant_analysis.
4851942ec02b18bbe4c8b58c46efed9cc2115e32
<ide><path>machine_learning/linear_discriminant_analysis.py <ide> Linear Discriminant Analysis <ide> <ide> <add> <ide> Assumptions About Data : <ide> 1. The input variables has a gaussian distribution. <ide> 2. The variance calculated for each input variables by class grouping is the <ide> from math import log <ide> from os import name, system <ide> from random import gauss, seed <add>from typing import Callable, TypeVar <ide> <ide> <ide> # Make a training dataset drawn from a gaussian distribution <ide> def accuracy(actual_y: list, predicted_y: list) -> float: <ide> return (correct / len(actual_y)) * 100 <ide> <ide> <add>num = TypeVar("num") <add> <add> <add>def valid_input( <add> input_type: Callable[[object], num], # Usually float or int <add> input_msg: str, <add> err_msg: str, <add> condition: Callable[[num], bool] = lambda x: True, <add> default: str = None, <add>) -> num: <add> """ <add> Ask for user value and validate that it fulfill a condition. <add> <add> :input_type: user input expected type of value <add> :input_msg: message to show user in the screen <add> :err_msg: message to show in the screen in case of error <add> :condition: function that represents the condition that user input is valid. <add> :default: Default value in case the user does not type anything <add> :return: user's input <add> """ <add> while True: <add> try: <add> user_input = input_type(input(input_msg).strip() or default) <add> if condition(user_input): <add> return user_input <add> else: <add> print(f"{user_input}: {err_msg}") <add> continue <add> except ValueError: <add> print( <add> f"{user_input}: Incorrect input type, expected {input_type.__name__!r}" <add> ) <add> <add> <ide> # Main Function <ide> def main(): <ide> """ This function starts execution phase """ <ide> def main(): <ide> print("First of all we should specify the number of classes that") <ide> print("we want to generate as training dataset") <ide> # Trying to get number of classes <del> n_classes = 0 <del> while True: <del> try: <del> user_input = int( <del> input("Enter the number of classes (Data Groupings): ").strip() <del> ) <del> if user_input > 0: <del> n_classes = user_input <del> break <del> else: <del> print( <del> f"Your entered value is {user_input} , Number of classes " <del> f"should be positive!" <del> ) <del> continue <del> except ValueError: <del> print("Your entered value is not numerical!") <add> n_classes = valid_input( <add> input_type=int, <add> condition=lambda x: x > 0, <add> input_msg="Enter the number of classes (Data Groupings): ", <add> err_msg="Number of classes should be positive!", <add> ) <ide> <ide> print("-" * 100) <ide> <del> std_dev = 1.0 # Default value for standard deviation of dataset <ide> # Trying to get the value of standard deviation <del> while True: <del> try: <del> user_sd = float( <del> input( <del> "Enter the value of standard deviation" <del> "(Default value is 1.0 for all classes): " <del> ).strip() <del> or "1.0" <del> ) <del> if user_sd >= 0.0: <del> std_dev = user_sd <del> break <del> else: <del> print( <del> f"Your entered value is {user_sd}, Standard deviation should " <del> f"not be negative!" <del> ) <del> continue <del> except ValueError: <del> print("Your entered value is not numerical!") <add> std_dev = valid_input( <add> input_type=float, <add> condition=lambda x: x >= 0, <add> input_msg=( <add> "Enter the value of standard deviation" <add> "(Default value is 1.0 for all classes): " <add> ), <add> err_msg="Standard deviation should not be negative!", <add> default="1.0", <add> ) <ide> <ide> print("-" * 100) <ide> <ide> # Trying to get number of instances in classes and theirs means to generate <ide> # dataset <ide> counts = [] # An empty list to store instance counts of classes in dataset <ide> for i in range(n_classes): <del> while True: <del> try: <del> user_count = int( <del> input(f"Enter The number of instances for class_{i+1}: ") <del> ) <del> if user_count > 0: <del> counts.append(user_count) <del> break <del> else: <del> print( <del> f"Your entered value is {user_count}, Number of " <del> "instances should be positive!" <del> ) <del> continue <del> except ValueError: <del> print("Your entered value is not numerical!") <add> user_count = valid_input( <add> input_type=int, <add> condition=lambda x: x > 0, <add> input_msg=(f"Enter The number of instances for class_{i+1}: "), <add> err_msg="Number of instances should be positive!", <add> ) <add> counts.append(user_count) <ide> print("-" * 100) <ide> <ide> # An empty list to store values of user-entered means of classes <ide> user_means = [] <ide> for a in range(n_classes): <del> while True: <del> try: <del> user_mean = float( <del> input(f"Enter the value of mean for class_{a+1}: ") <del> ) <del> if isinstance(user_mean, float): <del> user_means.append(user_mean) <del> break <del> print(f"You entered an invalid value: {user_mean}") <del> except ValueError: <del> print("Your entered value is not numerical!") <add> user_mean = valid_input( <add> input_type=float, <add> input_msg=(f"Enter the value of mean for class_{a+1}: "), <add> err_msg="This is an invalid value.", <add> ) <add> user_means.append(user_mean) <ide> print("-" * 100) <ide> <ide> print("Standard deviation: ", std_dev)
1
Text
Text
add full stop where needed.
890f546c2534a0565012dc66778bee9e8fcd72d5
<ide><path>README.md <ide> Contributing <ide> We welcome pull requests from Free Code Camp campers (our students) and seasoned JavaScript developers alike! Follow these steps to contribute: <ide> <ide> 1. Check our [public Waffle Board](https://waffle.io/freecodecamp/freecodecamp). <del>2. Pick an issue that nobody has claimed and start working on it. If your issue isn't on the board, open an issue. If you think you can fix it yourself, start working on it. Feel free to ask for help in our [Gitter](https://gitter.im/FreeCodeCamp/FreeCodeCamp) <add>2. Pick an issue that nobody has claimed and start working on it. If your issue isn't on the board, open an issue. If you think you can fix it yourself, start working on it. Feel free to ask for help in our [Gitter](https://gitter.im/FreeCodeCamp/FreeCodeCamp). <ide> 3. Fork the project ([Need help with forking a project?](https://help.github.com/articles/fork-a-repo/)). You'll do all of your work on your forked copy. <ide> 4. Create a branch specific to the issue or feature you are working on. Push your work to that branch. ([Need help with branching?](https://github.com/Kunena/Kunena-Forum/wiki/Create-a-new-branch-with-git-and-manage-branches)) <ide> 5. Name the branch something like `user-xxx` where user is your username and xxx is the issue number you are addressing.
1
PHP
PHP
remove test for unimplementable feature
db3b6d97ed67d3bb7564cc641d602ce30d8ade42
<ide><path>tests/TestCase/Http/RunnerTest.php <ide> */ <ide> namespace Cake\Test\TestCase; <ide> <del>use Cake\Core\Exception\Exception; <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\Http\Response; <ide> use Cake\Http\Runner; <ide> public function testRunSingle() <ide> $this->assertInstanceof(ResponseInterface::class, $result); <ide> } <ide> <del> /** <del> * Test exception is thrown if double pass callable modifies response before <del> * calling $next. <del> * <del> * @return void <del> */ <del> public function testRunResponseReplace() <del> { <del> $this->markTestSkipped( <del> 'Skip until we figure out a way to test for premature response modification in DoublePassMiddleware.' <del> ); <del> <del> $one = function ($req, $res, $next) { <del> $res = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock(); <del> <del> return $next($req, $res); <del> }; <del> $this->queue->add($one); <del> $runner = new Runner(); <del> <del> $req = $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->getMock(); <del> $this->expectException(Exception::class); <del> $this->expectExceptionMessage('Callable should not modify response instance before calling $next.'); <del> $result = $runner->run($this->queue, $req); <del> } <del> <ide> /** <ide> * Test that middleware is run in sequence <ide> *
1
PHP
PHP
fix cs error
47bf1d09d6d1d70c095e4f17b0dcc02cb6977805
<ide><path>src/View/View.php <ide> protected function _getLayoutFileName(?string $name = null): string <ide> if ($name === null) { <ide> if ($this->layout === false) { <ide> throw new RuntimeException( <del> 'Setting View::$layout to false is no longer supported.' <del> . ' Set View::$autoLayout to false instead.' <add> 'Setting View::$layout to false is no longer supported.' . <add> ' Set View::$autoLayout to false instead.' <ide> ); <ide> } <ide> $name = $this->layout;
1
Javascript
Javascript
stop global event bubbling using onlyhandlers flag
560c33b395ec809cc296c97cab41244949ec863c
<ide><path>src/event.js <ide> jQuery.event = { <ide> <ide> // TODO: Stop taunting the data cache; remove global events and always attach to document <ide> cache = jQuery.cache; <del> event.stopPropagation(); <ide> for ( i in cache ) { <ide> if ( cache[ i ].events && cache[ i ].events[ type ] ) { <del> jQuery.event.trigger( event, data, cache[ i ].handle.elem ); <add> jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); <ide> } <ide> } <ide> return;
1
Javascript
Javascript
fix trailing slash issue. fixes
075ed988996a79bc27f76fd1a582ac6cd94452b2
<ide><path>packages/ember-routing/lib/vendor/route-recognizer.js <ide> define("route-recognizer", <ide> <ide> // DEBUG GROUP path <ide> <add> var pathLen = path.length; <add> <ide> if (path.charAt(0) !== "/") { path = "/" + path; } <ide> <add> if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { <add> path = path.substr(0, pathLen - 1); <add> } <add> <ide> for (i=0, l=path.length; i<l; i++) { <ide> states = recognizeChar(states, path.charAt(i)); <ide> if (!states.length) { break; }
1
PHP
PHP
trigger an exception when alias names do not match
c6eca2f9388c25c2d2cb79e27a76ae49bb1fe4e3
<ide><path>src/ORM/EagerLoader.php <ide> protected function _normalizeContain(Table $parent, $alias, $options, $paths) <ide> sprintf('%s is not associated with %s', $parent->alias(), $alias) <ide> ); <ide> } <add> if ($instance->alias() !== $alias) { <add> throw new InvalidArgumentException(sprintf( <add> "You have contained '%s' but that association was bound as '%s'.", <add> $alias, <add> $instance->alias() <add> )); <add> } <ide> <ide> $paths += ['aliasPath' => '', 'propertyPath' => '', 'root' => $alias]; <ide> $paths['aliasPath'] .= '.' . $alias; <ide><path>tests/TestCase/ORM/EagerLoaderTest.php <ide> public function testContainToFieldsDefault() <ide> $this->assertEquals($expected, $select); <ide> } <ide> <add> /** <add> * Check that normalizing contains checks alias names. <add> * <add> * @expectedException \InvalidArgumentException <add> * @expectedExceptionMessage You have contained 'Clients' but that association was bound as 'clients' <add> * @return void <add> */ <add> public function testNormalizedChecksAliasNames() <add> { <add> $contains = ['Clients']; <add> $loader = new EagerLoader; <add> $loader->contain($contains); <add> $loader->normalized($this->table); <add> } <add> <ide> /** <ide> * Tests that the path for gettings to a deep assocition is materialized in an <ide> * array key <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testSaveBelongsToManyJoinDataOnExistingRecord() <ide> public function testSaveBelongsToManyJoinData() <ide> { <ide> $articles = TableRegistry::get('Articles'); <del> $article = $articles->get(1, ['contain' => ['Tags']]); <add> $article = $articles->get(1, ['contain' => ['tags']]); <ide> $data = [ <ide> 'tags' => [ <ide> ['id' => 1, '_joinData' => ['highlighted' => 1]], <ide> public function testSaveBelongsToManyDeleteAllLinks() <ide> 'saveStrategy' => 'replace', <ide> ]); <ide> <del> $entity = $table->get(1, ['contain' => 'Tags']); <add> $entity = $table->get(1, ['contain' => 'tags']); <ide> $this->assertCount(2, $entity->tags, 'Fixture data did not change.'); <ide> <ide> $entity->tags = []; <ide> $result = $table->save($entity); <ide> $this->assertSame($result, $entity); <ide> $this->assertSame([], $entity->tags, 'No tags on the entity.'); <ide> <del> $entity = $table->get(1, ['contain' => 'Tags']); <add> $entity = $table->get(1, ['contain' => 'tags']); <ide> $this->assertSame([], $entity->tags, 'No tags in the db either.'); <ide> } <ide> <ide> public function testSaveBelongsToManyDeleteSomeLinks() <ide> 'saveStrategy' => 'replace', <ide> ]); <ide> <del> $entity = $table->get(1, ['contain' => 'Tags']); <add> $entity = $table->get(1, ['contain' => 'tags']); <ide> $this->assertCount(2, $entity->tags, 'Fixture data did not change.'); <ide> <ide> $tag = new \Cake\ORM\Entity([ <ide> public function testSaveBelongsToManyDeleteSomeLinks() <ide> $this->assertCount(1, $entity->tags, 'Only one tag left.'); <ide> $this->assertEquals($tag, $entity->tags[0]); <ide> <del> $entity = $table->get(1, ['contain' => 'Tags']); <add> $entity = $table->get(1, ['contain' => 'tags']); <ide> $this->assertCount(1, $entity->tags, 'Only one tag in the db.'); <ide> $this->assertEquals($tag->id, $entity->tags[0]->id); <ide> } <ide> public function testSaveBelongsToManyDeleteSomeLinks() <ide> */ <ide> public function testSaveBelongsToManyIgnoreNonEntityData() <ide> { <del> $articles = TableRegistry::get('Articles'); <del> $article = $articles->get(1, ['contain' => ['Tags']]); <add> $articles = TableRegistry::get('articles'); <add> $article = $articles->get(1, ['contain' => ['tags']]); <ide> $article->tags = [ <ide> '_ids' => [2, 1] <ide> ];
3
Javascript
Javascript
simplify objecttomap by using object.entries
c747449c651ad7bf0f6d5e0b46975f457e1f15df
<ide><path>lib/util/objectToMap.js <ide> "use strict"; <ide> <ide> /** <del> * convert an object into its 2D array equivalent to be turned <del> * into an ES6 map <add> * Convert an object into an ES6 map <ide> * <del> * @param {object} obj - any object type that works with Object.keys() <del> * @returns {Map<TODO, TODO>} an ES6 Map of KV pairs <add> * @param {object} obj - any object type that works with Object.entries() <add> * @returns {Map<string, any>} an ES6 Map of KV pairs <ide> */ <ide> module.exports = function objectToMap(obj) { <del> return new Map( <del> Object.keys(obj).map(key => { <del> /** @type {[string, string]} */ <del> const pair = [key, obj[key]]; <del> return pair; <del> }) <del> ); <add> return new Map(Object.entries(obj)); <ide> };
1
Ruby
Ruby
bring the missing parameters back
36368eaa1ea778fd2556db482183892324c58b95
<ide><path>activerecord/lib/active_record/attribute_methods.rb <ide> def [](name) <ide> end <ide> <ide> private <del> def method_body; raise NotImplementedError; end <add> <add> # Override this method in the subclasses for method body. <add> def method_body(method_name, const_name) <add> raise NotImplementedError, "Subclasses must implement a method_body(method_name, const_name) method." <add> end <ide> end <ide> <ide> module ClassMethods
1
PHP
PHP
add integration test for binary uuid
4db1edd813f83a6234c162c7ea66ddc9857cec4b
<ide><path>src/Database/Type/BinaryUuidType.php <ide> public function toDatabase($value, Driver $driver) <ide> /** <ide> * Generate a new binary UUID <ide> * <del> * @return mixed A new primary key value. <add> * @return string A new primary key value. <ide> */ <ide> public function newId() <ide> { <del> return $this->convertStringToBinaryUuid(Text::uuid()); <add> return Text::uuid(); <ide> } <ide> <ide> /** <ide><path>tests/Fixture/BinaryUuiditemsFixture.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 1.2.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\Fixture; <add> <add>use Cake\TestSuite\Fixture\TestFixture; <add> <add>/** <add> * BinaryUuiditemsFixture <add> */ <add>class BinaryUuiditemsFixture extends TestFixture <add>{ <add> <add> /** <add> * fields property <add> * <add> * @var array <add> */ <add> public $fields = [ <add> 'id' => ['type' => 'binaryuuid'], <add> 'name' => ['type' => 'string', 'null' => false], <add> 'published' => ['type' => 'boolean', 'null' => false], <add> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]] <add> ]; <add> <add> /** <add> * records property <add> * <add> * @var array <add> */ <add> public $records = [ <add> ['id' => '481fc6d0-b920-43e0-a40d-6d1740cf8569', 'published' => true, 'name' => 'Item 1'], <add> ['id' => '48298a29-81c0-4c26-a7fb-413140cf8569', 'published' => false, 'name' => 'Item 2'], <add> ['id' => '482b7756-8da0-419a-b21f-27da40cf8569', 'published' => true, 'name' => 'Item 3'], <add> ]; <add>} <ide><path>tests/TestCase/ORM/TableUuidTest.php <ide> class TableUuidTest extends TestCase <ide> * @var array <ide> */ <ide> public $fixtures = [ <del> 'core.uuiditems', 'core.uuidportfolios' <add> 'core.binary_uuiditems', <add> 'core.uuiditems', <ide> ]; <ide> <ide> /** <ide> public function tearDown() <ide> TableRegistry::clear(); <ide> } <ide> <add> /** <add> * Provider for testing that string and binary uuids work the same <add> * <add> * @return array <add> */ <add> public function uuidTableProvider() <add> { <add> return [['uuiditems'], ['binary_uuiditems']]; <add> } <add> <ide> /** <ide> * Test saving new records sets uuids <ide> * <add> * @dataProvider uuidTableProvider <ide> * @return void <ide> */ <del> public function testSaveNew() <add> public function testSaveNew($tableName) <ide> { <ide> $entity = new Entity([ <ide> 'name' => 'shiny new', <ide> 'published' => true, <ide> ]); <del> $table = TableRegistry::get('uuiditems'); <add> $table = TableRegistry::get($tableName); <ide> $this->assertSame($entity, $table->save($entity)); <ide> $this->assertRegExp('/^[a-f0-9-]{36}$/', $entity->id, 'Should be 36 characters'); <ide> <ide> public function testSaveNew() <ide> /** <ide> * Test saving new records allows manual uuids <ide> * <add> * @dataProvider uuidTableProvider <ide> * @return void <ide> */ <del> public function testSaveNewSpecificId() <add> public function testSaveNewSpecificId($tableName) <ide> { <ide> $id = Text::uuid(); <ide> $entity = new Entity([ <ide> 'id' => $id, <ide> 'name' => 'shiny and new', <ide> 'published' => true, <ide> ]); <del> $table = TableRegistry::get('uuiditems'); <add> $table = TableRegistry::get($tableName); <ide> $this->assertSame($entity, $table->save($entity)); <ide> $this->assertSame($id, $entity->id); <ide> <ide> public function testSaveNewSpecificId() <ide> /** <ide> * Test saving existing records works <ide> * <add> * @dataProvider uuidTableProvider <ide> * @return void <ide> */ <del> public function testSaveUpdate() <add> public function testSaveUpdate($tableName) <ide> { <ide> $id = '481fc6d0-b920-43e0-a40d-6d1740cf8569'; <ide> $entity = new Entity([ <ide> public function testSaveUpdate() <ide> 'published' => true, <ide> ]); <ide> <del> $table = TableRegistry::get('uuiditems'); <add> $table = TableRegistry::get($tableName); <ide> $this->assertSame($entity, $table->save($entity)); <ide> $this->assertEquals($id, $entity->id, 'Should be 36 characters'); <ide> <ide> public function testSaveUpdate() <ide> /** <ide> * Test delete with string pk. <ide> * <add> * @dataProvider uuidTableProvider <ide> * @return void <ide> */ <del> public function testDelete() <add> public function testDelete($tableName) <ide> { <ide> $id = '481fc6d0-b920-43e0-a40d-6d1740cf8569'; <del> $table = TableRegistry::get('uuiditems'); <add> $table = TableRegistry::get($tableName); <ide> $entity = $table->find('all')->where(['id' => $id])->first(); <ide> <ide> $this->assertTrue($table->delete($entity)); <ide> public function testDelete() <ide> /** <ide> * Tests that sql server does not error when an empty uuid is bound <ide> * <add> * @dataProvider uuidTableProvider <ide> * @return void <ide> */ <del> public function testEmptyUuid() <add> public function testEmptyUuid($tableName) <ide> { <ide> $id = ''; <del> $table = TableRegistry::get('uuiditems'); <add> $table = TableRegistry::get($tableName); <ide> $entity = $table->find('all') <ide> ->where(['id' => $id]) <ide> ->first();
3
Javascript
Javascript
update the documentation of the button component
6b7014ab047ae88aded9beb645ac05d16f4ddc37
<ide><path>Libraries/Components/Button.js <ide> * <ide> * @format <ide> * @flow <add> * @generate-docs <ide> */ <ide> <ide> 'use strict'; <ide> import type {ColorValue} from '../StyleSheet/StyleSheet'; <ide> <ide> type ButtonProps = $ReadOnly<{| <ide> /** <del> * Text to display inside the button <add> Text to display inside the button. On Android the given title will be <add> converted to the uppercased form. <ide> */ <ide> title: string, <ide> <ide> /** <del> * Handler to be called when the user taps the button <add> Handler to be called when the user taps the button. The first function <add> argument is an event in form of [PressEvent](pressevent). <ide> */ <ide> onPress: (event?: PressEvent) => mixed, <ide> <ide> /** <del> * If true, doesn't play system sound on touch (Android Only) <del> **/ <add> If `true`, doesn't play system sound on touch. <add> <add> @platform android <add> <add> @default false <add> */ <ide> touchSoundDisabled?: ?boolean, <ide> <ide> /** <del> * Color of the text (iOS), or background color of the button (Android) <add> Color of the text (iOS), or background color of the button (Android). <add> <add> @default {@platform android} '#2196F3' <add> @default {@platform ios} '#007AFF' <ide> */ <ide> color?: ?ColorValue, <ide> <ide> /** <del> * TV preferred focus (see documentation for the View component). <add> TV preferred focus. <add> <add> @platform tv <add> <add> @default false <ide> */ <ide> hasTVPreferredFocus?: ?boolean, <ide> <ide> /** <del> * TV next focus down (see documentation for the View component). <del> * <del> * @platform android <add> Designates the next view to receive focus when the user navigates down. See <add> the [Android documentation][android:nextFocusDown]. <add> <add> [android:nextFocusDown]: <add> https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusDown <add> <add> @platform android, tv <ide> */ <ide> nextFocusDown?: ?number, <ide> <ide> /** <del> * TV next focus forward (see documentation for the View component). <del> * <del> * @platform android <add> Designates the next view to receive focus when the user navigates forward. <add> See the [Android documentation][android:nextFocusForward]. <add> <add> [android:nextFocusForward]: <add> https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusForward <add> <add> @platform android, tv <ide> */ <ide> nextFocusForward?: ?number, <ide> <ide> /** <del> * TV next focus left (see documentation for the View component). <del> * <del> * @platform android <add> Designates the next view to receive focus when the user navigates left. See <add> the [Android documentation][android:nextFocusLeft]. <add> <add> [android:nextFocusLeft]: <add> https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusLeft <add> <add> @platform android, tv <ide> */ <ide> nextFocusLeft?: ?number, <ide> <ide> /** <del> * TV next focus right (see documentation for the View component). <del> * <del> * @platform android <add> Designates the next view to receive focus when the user navigates right. See <add> the [Android documentation][android:nextFocusRight]. <add> <add> [android:nextFocusRight]: <add> https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusRight <add> <add> @platform android, tv <ide> */ <ide> nextFocusRight?: ?number, <ide> <ide> /** <del> * TV next focus up (see documentation for the View component). <del> * <del> * @platform android <add> Designates the next view to receive focus when the user navigates up. See <add> the [Android documentation][android:nextFocusUp]. <add> <add> [android:nextFocusUp]: <add> https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusUp <add> <add> @platform android, tv <ide> */ <ide> nextFocusUp?: ?number, <ide> <ide> /** <del> * Text to display for blindness accessibility features <add> Text to display for blindness accessibility features. <ide> */ <ide> accessibilityLabel?: ?string, <ide> <ide> /** <del> * If true, disable all interactions for this component. <add> If `true`, disable all interactions for this component. <add> <add> @default false <ide> */ <ide> disabled?: ?boolean, <ide> <ide> /** <del> * Used to locate this view in end-to-end tests. <add> Used to locate this view in end-to-end tests. <ide> */ <ide> testID?: ?string, <ide> |}>; <ide> <ide> /** <del> * A basic button component that should render nicely on any platform. Supports <del> * a minimal level of customization. <del> * <del> * <center><img src="img/buttonExample.png"></img></center> <del> * <del> * If this button doesn't look right for your app, you can build your own <del> * button using [TouchableOpacity](docs/touchableopacity.html) <del> * or [TouchableNativeFeedback](docs/touchablenativefeedback.html). <del> * For inspiration, look at the [source code for this button component](https://github.com/facebook/react-native/blob/master/Libraries/Components/Button.js). <del> * Or, take a look at the [wide variety of button components built by the community](https://js.coach/react-native?search=button). <del> * <del> * Example usage: <del> * <del> * ``` <del> * import { Button } from 'react-native'; <del> * ... <del> * <del> * <Button <del> * onPress={onPressLearnMore} <del> * title="Learn More" <del> * color="#841584" <del> * accessibilityLabel="Learn more about this purple button" <del> * /> <del> * ``` <del> * <add> A basic button component that should render nicely on any platform. Supports a <add> minimal level of customization. <add> <add> If this button doesn't look right for your app, you can build your own button <add> using [TouchableOpacity](touchableopacity) or <add> [TouchableWithoutFeedback](touchablewithoutfeedback). For inspiration, look at <add> the [source code for this button component][button:source]. Or, take a look at <add> the [wide variety of button components built by the community] <add> [button:examples]. <add> <add> [button:source]: <add> https://github.com/facebook/react-native/blob/master/Libraries/Components/Button.js <add> <add> [button:examples]: <add> https://js.coach/?menu%5Bcollections%5D=React%20Native&page=1&query=button <add> <add> ```jsx <add> <Button <add> onPress={onPressLearnMore} <add> title="Learn More" <add> color="#841584" <add> accessibilityLabel="Learn more about this purple button" <add> /> <add> ``` <add> <add> ```SnackPlayer name=Button%20Example <add> import React from 'react'; <add> import { StyleSheet, Button, View, SafeAreaView, Text, Alert } from 'react-native'; <add> <add> const Separator = () => ( <add> <View style={styles.separator} /> <add> ); <add> <add> const App = () => ( <add> <SafeAreaView style={styles.container}> <add> <View> <add> <Text style={styles.title}> <add> The title and onPress handler are required. It is recommended to set accessibilityLabel to help make your app usable by everyone. <add> </Text> <add> <Button <add> title="Press me" <add> onPress={() => Alert.alert('Simple Button pressed')} <add> /> <add> </View> <add> <Separator /> <add> <View> <add> <Text style={styles.title}> <add> Adjust the color in a way that looks standard on each platform. On iOS, the color prop controls the color of the text. On Android, the color adjusts the background color of the button. <add> </Text> <add> <Button <add> title="Press me" <add> color="#f194ff" <add> onPress={() => Alert.alert('Button with adjusted color pressed')} <add> /> <add> </View> <add> <Separator /> <add> <View> <add> <Text style={styles.title}> <add> All interaction for the component are disabled. <add> </Text> <add> <Button <add> title="Press me" <add> disabled <add> onPress={() => Alert.alert('Cannot press this one')} <add> /> <add> </View> <add> <Separator /> <add> <View> <add> <Text style={styles.title}> <add> This layout strategy lets the title define the width of the button. <add> </Text> <add> <View style={styles.fixToText}> <add> <Button <add> title="Left button" <add> onPress={() => Alert.alert('Left button pressed')} <add> /> <add> <Button <add> title="Right button" <add> onPress={() => Alert.alert('Right button pressed')} <add> /> <add> </View> <add> </View> <add> </SafeAreaView> <add> ); <add> <add> const styles = StyleSheet.create({ <add> container: { <add> flex: 1, <add> justifyContent: 'center', <add> marginHorizontal: 16, <add> }, <add> title: { <add> textAlign: 'center', <add> marginVertical: 8, <add> }, <add> fixToText: { <add> flexDirection: 'row', <add> justifyContent: 'space-between', <add> }, <add> separator: { <add> marginVertical: 8, <add> borderBottomColor: '#737373', <add> borderBottomWidth: StyleSheet.hairlineWidth, <add> }, <add> }); <add> <add> export default App; <add> ``` <ide> */ <ide> <ide> class Button extends React.Component<ButtonProps> {
1
Python
Python
modernize python 2 code to get ready for python 3
ad6b0f1c6b3d79a8a8a17ea38ead4b5936f11917
<ide><path>Graphs/basic-graphs.py <ide> def adjm(): <ide> """ <ide> <ide> <del>def floy(xxx_todo_changeme): <del> (A, n) = xxx_todo_changeme <add>def floy(A_and_n): <add> (A, n) = A_and_n <ide> dist = list(A) <ide> path = [[0] * n for i in xrange(n)] <ide> for k in xrange(n): <ide> def edglist(): <ide> """ <ide> <ide> <del>def krusk(xxx_todo_changeme1): <add>def krusk(E_and_n): <ide> # Sort edges on the basis of distance <del> (E, n) = xxx_todo_changeme1 <add> (E, n) = E_and_n <ide> E.sort(reverse=True, key=lambda x: x[2]) <ide> s = [set([i]) for i in range(1, n + 1)] <ide> while True:
1
Python
Python
move unused args to kwargs
6b4c617666fd26646d44d54f0c45dfe1332b12ca
<ide><path>src/transformers/trainer.py <ide> def hyperparameter_search( <ide> hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None, <ide> compute_objective: Optional[Callable[[Dict[str, float]], float]] = None, <ide> n_trials: int = 20, <del> timeout: int = 1800, <del> n_jobs: int = 1, <ide> direction: str = "minimize", <ide> backend: Optional[Union["str", HPSearchBackend]] = None, <ide> **kwargs
1
Text
Text
fix ironic typo in changelog
45bd52d472c3131c7ad5077cf8b20a241d82c555
<ide><path>CHANGELOG.md <ide> * Registry: Implement login with private registry <ide> * Remote API: Bump to v1.5 <ide> * Packaging: Break down hack/make.sh into small scripts, one per 'bundle': test, binary, ubuntu etc. <del>* Documentation: General improvments <add>* Documentation: General improvements <ide> - Runtime: UID and GID are now also applied to volumes <ide> - Runtime: `docker start` set error code upon error <ide> - Runtime: `docker run` set the same error code as the process started
1
Javascript
Javascript
fix binding tests to not use sc.object
d191f7bf142c54d29ab25e3389f0f0e8a964efcf
<ide><path>packages/sproutcore-metal/tests/binding/and_test.js <ide> var MyApp, set = SC.set, get = SC.get; <ide> <ide> module('binding/and', { <ide> setup: function() { <del> MyApp = SC.Object.create({ <add> MyApp = { <ide> foo: false, <del> bar: false, <del> bazBinding: SC.Binding.and('foo', 'bar') <del> }); <add> bar: false <add> }; <add> SC.Binding.and("foo", "bar").to("baz").connect(MyApp) <ide> }, <ide> <ide> teardown: function() { <ide><path>packages/sproutcore-metal/tests/binding/bool_not_test.js <ide> function testBool(val, expected) { <ide> <ide> module('system/binding/bool', { <ide> setup: function() { <del> MyApp = SC.Object.create({ <del> foo: SC.Object.create({ value: 'FOO' }), <del> bar: SC.Object.create({ value: 'BAR' }) <del> }); <add> MyApp = { <add> foo: { value: 'FOO' }, <add> bar: { value: 'BAR' } <add> }; <ide> <ide> SC.bind(MyApp, 'bar.value', 'foo.value').bool(); <ide> }, <ide> testBool('', false); <ide> <ide> module('system/binding/not', { <ide> setup: function() { <del> MyApp = SC.Object.create({ <del> foo: SC.Object.create({ value: 'FOO' }), <del> bar: SC.Object.create({ value: 'BAR' }) <del> }); <add> MyApp = { <add> foo: { value: 'FOO' }, <add> bar: { value: 'BAR' } <add> }; <ide> <ide> SC.bind(MyApp, 'bar.value', 'foo.value').not(); <ide> }, <ide><path>packages/sproutcore-metal/tests/binding/connect_test.js <ide> function performTest(binding, a, b, get, set, skipFirst) { <ide> } <ide> <ide> testBoth('Connecting a binding between two properties', function(get, set) { <del> var a = SC.Object.create({ foo: 'FOO', bar: 'BAR' }); <add> var a = { foo: 'FOO', bar: 'BAR' }; <ide> <ide> // a.bar -> a.foo <ide> var binding = new SC.Binding('foo', 'bar'); <ide> testBoth('Connecting a binding between two properties', function(get, set) { <ide> }); <ide> <ide> testBoth('Connecting a binding between two objects', function(get, set) { <del> var b = SC.Object.create({ bar: 'BAR' }); <del> var a = SC.Object.create({ foo: 'FOO', b: b }); <add> var b = { bar: 'BAR' }; <add> var a = { foo: 'FOO', b: b }; <ide> <ide> // b.bar -> a.foo <ide> var binding = new SC.Binding('foo', 'b.bar'); <ide> testBoth('Connecting a binding between two objects', function(get, set) { <ide> }); <ide> <ide> testBoth('Connecting a binding to path', function(get, set) { <del> var a = SC.Object.create({ foo: 'FOO' }); <del> GlobalB = SC.Object.create({ <del> b: SC.Object.create({ bar: 'BAR' }) <del> }) ; <add> var a = { foo: 'FOO' }; <add> GlobalB = { <add> b: { bar: 'BAR' } <add> }; <ide> <ide> var b = get(GlobalB, 'b'); <ide> <ide> testBoth('Connecting a binding to path', function(get, set) { <ide> performTest(binding, a, b, get, set); <ide> <ide> // make sure modifications update <del> b = SC.Object.create({ bar: 'BIFF' }); <add> b = { bar: 'BIFF' }; <ide> set(GlobalB, 'b', b); <ide> SC.run.sync(); <ide> equals(get(a, 'foo'), 'BIFF', 'a should have changed'); <ide> <ide> }); <ide> <ide> testBoth('Calling connect more than once', function(get, set) { <del> var b = SC.Object.create({ bar: 'BAR' }); <del> var a = SC.Object.create({ foo: 'FOO', b: b }); <add> var b = { bar: 'BAR' }; <add> var a = { foo: 'FOO', b: b }; <ide> <ide> // b.bar -> a.foo <ide> var binding = new SC.Binding('foo', 'b.bar'); <ide> testBoth('Bindings should be inherited', function(get, set) { <ide> <ide> test('inherited bindings should sync on create', function() { <ide> <del> var A = SC.Object.extend({ <del> fooBinding: 'bar.baz' <del> }); <add> var A = function() { <add> SC.bind(this, 'foo', 'bar.baz'); <add> }; <ide> <del> var a = A.create({ <del> bar: SC.Object.create({ baz: 'BAZ' }) <del> }); <add> var a = new A(); <add> SC.set(a, 'bar', { baz: 'BAZ' }); <ide> <ide> SC.run.sync(); <ide> equals(SC.get(a, 'foo'), 'BAZ', 'should have synced binding on new obj'); <ide><path>packages/sproutcore-metal/tests/binding/multiple_test.js <ide> <ide> module('system/binding/multiple', { <ide> setup: function() { <del> MyApp = SC.Object.create({ <del> foo: SC.Object.create({ value: 'FOO' }), <del> bar: SC.Object.create({ value: 'BAR' }) <del> }); <add> MyApp = { <add> foo: { value: 'FOO' }, <add> bar: { value: 'BAR' } <add> }; <ide> }, <ide> <ide> teardown: function() { <ide><path>packages/sproutcore-metal/tests/binding/notEmpty_test.js <ide> <ide> module('system/binding/notEmpty', { <ide> setup: function() { <del> MyApp = SC.Object.create({ <del> foo: SC.Object.create({ value: 'FOO' }), <del> bar: SC.Object.create({ value: 'BAR' }) <del> }); <add> MyApp = { <add> foo: { value: 'FOO' }, <add> bar: { value: 'BAR' } <add> }; <ide> }, <ide> <ide> teardown: function() { <ide><path>packages/sproutcore-metal/tests/binding/notNull_test.js <ide> <ide> module('system/binding/notNull', { <ide> setup: function() { <del> MyApp = SC.Object.create({ <del> foo: SC.Object.create({ value: 'FOO' }), <del> bar: SC.Object.create({ value: 'BAR' }) <del> }); <add> MyApp = { <add> foo: { value: 'FOO' }, <add> bar: { value: 'BAR' } <add> }; <ide> }, <ide> <ide> teardown: function() { <ide><path>packages/sproutcore-metal/tests/binding/oneWay_test.js <ide> <ide> module('system/mixin/binding/oneWay_test', { <ide> setup: function() { <del> MyApp = SC.Object.create({ <del> foo: SC.Object.create({ value: 'FOO' }), <del> bar: SC.Object.create({ value: 'BAR' }) <add> MyApp = { <add> foo: { value: 'FOO' }, <add> bar: { value: 'BAR' } <ide> }); <ide> }, <ide> <ide><path>packages/sproutcore-metal/tests/binding/single_test.js <ide> <ide> module('system/binding/single', { <ide> setup: function() { <del> MyApp = SC.Object.create({ <del> foo: SC.Object.create({ value: 'FOO' }), <del> bar: SC.Object.create({ value: 'BAR' }) <del> }); <add> MyApp = { <add> foo: { value: 'FOO' }, <add> bar: { value: 'BAR' } <add> }; <ide> }, <ide> <ide> teardown: function() {
8
Text
Text
fix markdown error in airflow readme
6e592ad7565d4f8a7371dea71ce6e74e512dec11
<ide><path>dev/README_RELEASE_AIRFLOW.md <ide> - [Prepare the Apache Airflow Package RC](#prepare-the-apache-airflow-package-rc) <ide> - [Update the milestone](#update-the-milestone) <ide> - [Build RC artifacts](#build-rc-artifacts) <del> - [[\Optional\] Prepare new release branches and cache](#%5Coptional%5C-prepare-new-release-branches-and-cache) <add> - [Prepare new release branches and cache - optional when first minor version is released](#prepare-new-release-branches-and-cache---optional-when-first-minor-version-is-released) <ide> - [Prepare PyPI convenience "snapshot" packages](#prepare-pypi-convenience-snapshot-packages) <ide> - [Prepare production Docker Image RC](#prepare-production-docker-image-rc) <ide> - [Prepare issue for testing status of rc](#prepare-issue-for-testing-status-of-rc) <ide> The Release Candidate artifacts we vote upon should be the exact ones we vote ag <ide> <ide> - Check out the 'test' branch <ide> <del> For major/minor version release, please follow the instructions at [Prepare new release branches and cache](#%5Coptional%5C-prepare-new-release-branches-and-cache) to create the 'test' and 'stable' branches. <add> For major/minor version release, please follow the instructions at <add> [Prepare new release branches and cache](#prepare-new-release-branches-and-cache---optional-when-first-minor-version-is-released) <add> to create the 'test' and 'stable' branches. <ide> <ide> ```shell script <ide> git checkout v${VERSION_BRANCH}-test <ide> The Release Candidate artifacts we vote upon should be the exact ones we vote ag <ide> svn commit -m "Add artifacts for Airflow ${VERSION}" <ide> ``` <ide> <del>## [\Optional\] Prepare new release branches and cache <add>## Prepare new release branches and cache - optional when first minor version is released <ide> <ide> When you just released the `X.Y.0` version (first release of new minor version) you need to create release <ide> branches: `vX-Y-test` and `vX-Y-stable` (for example with `2.1.0rc1` release you need to create v2-1-test and
1
Python
Python
add lxccontainerdriver class
f70cd3d5364d1976f3d1b957b8b2143747ed3dd8
<ide><path>libcloud/container/drivers/lxc.py <add>""" <add>Module for handling LXC containers <add>""" <add>from libcloud.container.base import (Container, ContainerDriver, ContainerImage) <add> <add>class LXCContainerDriver(ContainerDriver): <add> """ <add> Driver for LXC containers <add> """ <add> pass <ide>\ No newline at end of file
1
Javascript
Javascript
exclude the e2e test that fails on safari
f0c94ea292d214c873eaa82a901ca5c2abc26f66
<ide><path>src/ng/filter/limitTo.js <ide> 'use strict'; <ide> <del>* <add>/* <ide> * @ngdoc filter <ide> * @name limitTo <ide> * @kind function <ide> }); <ide> </file> <ide> </example> <del> <add>*/ <ide> function limitToFilter(){ <ide> return function(input, limit) { <ide> if (isNumber(input)) input = input.toString();
1
Javascript
Javascript
fix typo in view.js
a7da457e6bdf474c0abc820c359f094475819cfd
<ide><path>packages/react-devtools-scheduling-profiler/src/view-base/View.js <ide> export class View { <ide> _needsDisplay = true; <ide> <ide> /** <del> * Whether the heirarchy below this view has subviews that need display. <add> * Whether the hierarchy below this view has subviews that need display. <ide> * <ide> * NOTE: Do not set directly! Use `setSubviewsNeedDisplay`. <ide> *
1
PHP
PHP
update doc block
a7213b2e6451b45a9801e8ca4060641c6848a196
<ide><path>lib/Cake/Error/exceptions.php <ide> class CakeBaseException extends RuntimeException { <ide> * - an array of string headers is also accepted <ide> * @param string $value. The header value. <ide> * @return array <del> * @see CakeResponse::header() See also <add> * @see CakeResponse::header() <ide> */ <ide> public function responseHeader($header = null, $value = null) { <ide> if ($header) {
1
PHP
PHP
fix logical operators
22b72f03a22e5d7a96eb7d77c6f17cbdc5d8fd74
<ide><path>src/Collection/CollectionTrait.php <ide> public function cartesianProduct(callable $operation = null, callable $filter = <ide> $currentIndexes = array_fill(0, $lastIndex + 1, 0); <ide> $changeIndex = $lastIndex; <ide> <del> while (!($changeIndex === 0 AND $currentIndexes[0] === $counts[0])) { <add> while (!($changeIndex === 0 && $currentIndexes[0] === $counts[0])) { <ide> $currentCombination = array_map(function ($arr, $index) { <ide> return $arr[$index]; <ide> }, $allArr, $currentIndexes); <ide> <del> if ($filter === null OR $filter(...$currentCombination)) { <add> if ($filter === null || $filter(...$currentCombination)) { <ide> $result[] = ($operation === null) ? $currentCombination : $operation(...$currentCombination); <ide> } <ide> <ide> $currentIndexes[$lastIndex]++; <ide> <del> for ($changeIndex = $lastIndex; $currentIndexes[$changeIndex] === $counts[$changeIndex] AND $changeIndex > 0; $changeIndex--) { <add> for ($changeIndex = $lastIndex; $currentIndexes[$changeIndex] === $counts[$changeIndex] && $changeIndex > 0; $changeIndex--) { <ide> $currentIndexes[$changeIndex] = 0; <ide> $currentIndexes[$changeIndex - 1]++; <ide> }
1
Text
Text
add kitematic to readme.md
7bd250c74d1dbc64be2ccb0978e1babd55d18afa
<ide><path>README.md <ide> There are a number of projects under development that are based on Docker's <ide> core technology. These projects expand the tooling built around the <ide> Docker platform to broaden its application and utility. <ide> <del>If you know of another project underway that should be listed here, please help <del>us keep this list up-to-date by submitting a PR. <del> <ide> * [Docker Registry](https://github.com/docker/distribution): Registry <ide> server for Docker (hosting/delivery of repositories and images) <ide> * [Docker Machine](https://github.com/docker/machine): Machine management <ide> for a container-centric world <ide> system <ide> * [Docker Compose](https://github.com/docker/compose) (formerly Fig): <ide> Define and run multi-container apps <add>* [Kitematic](https://github.com/kitematic/kitematic): The easiest way to use <add>Docker on a Mac <ide> <add>If you know of another project underway that should be listed here, please help <add>us keep this list up-to-date by submitting a PR.
1
Text
Text
address comments on original pr
a0fe85542f8c17a85bbd857f319a7faa816dd961
<ide><path>CONTRIBUTING.md <ide> git clone https://github.com/your-username/redux.git <ide> ### Building <ide> <ide> #### Build Redux <del>To build Redux: <add> <add>Running the `build` task will create both a CommonJS module-per-module build and a UMD build. <ide> ``` <ide> npm run build <ide> ``` <ide> <del>To build the lib: <add>To create just a CommonJS module-per-module build: <ide> ``` <ide> npm run build:lib <ide> ``` <ide> <del>For a UMD build: <add>To create just a UMD build: <ide> ``` <ide> npm run build:umd <ide> npm run build:umd:min <ide> npm run lint <ide> ``` <ide> <ide> ### Docs <add> <add>Improvements to the documentation are always welcome. In the docs we abide by typographic rules, so <add>instead of ' you should use ’, same for “ ” and dashes (—) where appropriate. These rules only apply to the text, not to code blocks. <add> <ide> #### Preparing to build the documentation <del>To install the latest version of `gitbooks` and prepare to build the documentation, run the following: <add>To install the latest version of `gitbook` and prepare to build the documentation, run the following: <ide> ``` <ide> npm run docs:prepare <ide> ``` <ide> npm run docs:clean <ide> ### Examples <ide> Redux comes with [official examples](http://rackt.github.io/redux/docs/introduction/Examples.html) to demonstrate various concepts and best practices. <ide> <del>When adding a new example, please adhere to the style and format of the existing examples, and try to reuse as much code as possible. For example, `index.html`, `server.js`, and `webpack.config.js` can typically be reused. <add>When adding a new example, please adhere to the style and format of the existing examples, and try to reuse as much code as possible. For example, `index.html`, `server.js`, and `webpack.config.js` can typically be reused. <add> <add>>For ease of development, the webpack configs for the examples are set up so that the `redux` module is aliased to the project `src` folder when inside of the Redux folder. If an example is moved out of the Redux folder, they will instead use the version of Redux from `node_modules`. <ide> <ide> #### Building and testing the examples <ide> To build and test the official Redux examples, run the following: <ide> npm run test:examples <ide> <ide> Please visit the [Examples page](http://rackt.github.io/redux/docs/introduction/Examples.html) for information on running an individual example. <ide> <add>###New Features <add>Please open an issue with a proposal for a new feature or refactoring before starting on the work. We don't want you to waste your efforts on a pull request that we won't want to accept. <add> <add>###Style <add>[rackt](https://github.com/rackt) is trying to keep a standard style across its various projects, which can be found over in [eslint-config-rackt](https://github.com/rackt/eslint-config-rackt). If you have a style change proposal, it should first be proposed there. If accepted, we will be happy to accept a PR to implement it here. <add> <ide> ## Submitting Changes <ide> * Open a new issue in the [Issue tracker](https://github.com/rackt/redux/issues). <ide> * Fork the repo. <ide> * Create a new feature branch based off the `master` branch. <ide> * Make sure all tests pass and there are no linting errors. <del>* Submit a pull request, referencing any issues it addresses. <ide>\ No newline at end of file <add>* Submit a pull request, referencing any issues it addresses. <add> <add>Please try to keep your pull request focused in scope and avoid including unrelated commits. <add> <add>After you have submitted your pull request, we'll try to get back to you as soon as possible. We may suggest some changes or improvements. <add> <add>Thank you for contributing!
1
Javascript
Javascript
allow querystring for assets, fixes #217
6e7bd0c60b5a6f32b2ccddf35ea95238ced31ebd
<ide><path>lib/Compiler.js <ide> Compiler.prototype.emitAssets = function(compilation, callback) { <ide> <ide> require("async").forEach(Object.keys(compilation.assets), function(file, callback) { <ide> <del> if(file.indexOf("/") >= 0) { <del> var idx = file.lastIndexOf("/"); <del> var dir = file.substr(0, idx); <add> var targetFile = file; <add> var queryStringIdx = targetFile.indexOf("?") <add> if(queryStringIdx >= 0) { <add> targetFile = targetFile.substr(0, queryStringIdx); <add> } <add> if(targetFile.indexOf("/") >= 0) { <add> var idx = targetFile.lastIndexOf("/"); <add> var dir = targetFile.substr(0, idx); <ide> this.outputFileSystem.mkdirp(this.outputFileSystem.join(outputPath, dir), writeOut.bind(this)); <ide> } else writeOut.call(this); <ide> function writeOut(err) { <ide> if(err) return callback(err); <del> var targetPath = this.outputFileSystem.join(outputPath, file); <add> var targetPath = this.outputFileSystem.join(outputPath, targetFile); <ide> var source = compilation.assets[file]; <ide> if(source.existsAt === targetPath) { <ide> source.emitted = false; <ide><path>test/browsertest/build.js <ide> var library1 = cp.spawn("node", join(["../../bin/webpack.js", "--output-pathinfo <ide> bindOutput(library1); <ide> library1.on("exit", function(code) { <ide> if(code === 0) { <del> // node ../../bin/webpack --output-pathinfo --colors --resolve-alias vm=vm-browserify --output-public-path js/ --module-bind json --module-bind css=style!css --module-bind less=style!css!less --module-bind coffee --module-bind jade --prefetch ./lib/stylesheet.less --optimize-dedupe --labeled-modules ./lib/index js/web.js <add> // node ../../bin/webpack --output-pathinfo --colors --resolve-alias vm=vm-browserify --output-public-path js/ --module-bind json --module-bind css=style!css --module-bind less=style!css!less --module-bind coffee --module-bind jade --prefetch ./lib/stylesheet.less --optimize-dedupe --labeled-modules ./lib/index "js/web.js?h=[hash]" <ide> var main = cp.spawn("node", join(["../../bin/webpack.js", "--output-pathinfo", "--colors", "--resolve-alias", "vm=vm-browserify", "--workers", <del> "--output-public-path", "js/", "--module-bind", "json", "--module-bind", "css=style!css", "--module-bind", "less=style/url!file?postfix=.css&string!less", "--module-bind", "coffee", "--module-bind", "jade", "--prefetch", "./lib/stylesheet.less", "--optimize-dedupe", "--labeled-modules", "./lib/index", "js/web.js", "--progress"], extraArgs)); <add> "--output-public-path", "js/", "--module-bind", "json", "--module-bind", "css=style!css", "--module-bind", "less=style/url!file?postfix=.css&string!less", "--module-bind", "coffee", "--module-bind", "jade", "--prefetch", "./lib/stylesheet.less", "--optimize-dedupe", "--labeled-modules", "./lib/index", "js/web.js?h=[hash]", "--progress"], extraArgs)); <ide> bindOutput(main); <ide> } <ide> });
2
Python
Python
add unit testing
81b97607339ac68b27cf72ba7923345d58e2895e
<ide><path>numpy/array_api/tests/test_asarray.py <add>import numpy as np <add> <add> <add>def test_fast_return(): <add> """""" <add> a = np.array([1, 2, 3], dtype='i') <add> assert np.asarray(a) is a <add> assert np.asarray(a, dtype='i') is a <add> # This may produce a new view or a copy, but is never the same object. <add> assert np.asarray(a, dtype='l') is not a <add> <add> unequal_type = np.dtype('i', metadata={'spam': True}) <add> b = np.asarray(a, dtype=unequal_type) <add> assert b is not a <add> assert b.base is a <add> <add> equivalent_requirement = np.dtype('i', metadata={'spam': True}) <add> c = np.asarray(b, dtype=equivalent_requirement) <add> # A quirk of the metadata test is that equivalent metadata dicts are still <add> # separate objects and so don't evaluate as the same array type description. <add> assert unequal_type == equivalent_requirement <add> assert unequal_type is not equivalent_requirement <add> assert c is not b <add> assert c.dtype is equivalent_requirement
1
PHP
PHP
add a new exception class for routing errors
ac16ff1bbc179865e24f8102b99f50d9461b5fbf
<ide><path>src/Routing/Router.php <ide> <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <del>use Cake\Error; <ide> use Cake\Network\Request; <add>use Cake\Routing\Error\MissingRouteException; <ide> use Cake\Routing\ScopedRouteCollection; <ide> use Cake\Routing\Route\Route; <ide> use Cake\Utility\Inflector; <ide> public static function prefixes() { <ide> * <ide> * @param string $url URL to be parsed <ide> * @return array Parsed elements from URL <del> * @throws \Cake\Error\Exception When a route cannot be handled <add> * @throws \Cake\Routing\Error\MissingRouteException When a route cannot be handled <ide> */ <ide> public static function parse($url) { <ide> if (!static::$initialized) { <ide> public static function parse($url) { <ide> return $collection->parse($url); <ide> } <ide> } <del> // TODO improve this with a custom exception. <del> throw new Error\Exception('No routes match the given URL.'); <add> throw new MissingRouteException($url); <ide> } <ide> <ide> /** <ide> protected static function _match($url) { <ide> } <ide> } <ide> <del> // TODO improve with custom exception <del> throw new Error\Exception(sprintf( <del> 'Unable to find a matching route for %s', <del> var_export($url, true) <del> )); <add> throw new MissingRouteException(var_export($url, true)); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testUrlGenerationNamedRoute() { <ide> /** <ide> * Test that using invalid names causes exceptions. <ide> * <del> * @expectedException \Cake\Error\Exception <add> * @expectedException \Cake\Routing\Error\MissingRouteException <ide> * @return void <ide> */ <ide> public function testNamedRouteException() { <ide> public function testParsingWithPatternOnAction() { <ide> /** <ide> * Test url() works with patterns on :action <ide> * <del> * @expectedException Cake\Error\Exception <add> * @expectedException Cake\Routing\Error\MissingRouteException <ide> * @return void <ide> */ <ide> public function testUrlPatterOnAction() { <ide> public function testRegexRouteMatching() { <ide> /** <ide> * testRegexRouteMatching method <ide> * <del> * @expectedException Cake\Error\Exception <add> * @expectedException Cake\Routing\Error\MissingRouteException <ide> * @return void <ide> */ <ide> public function testRegexRouteMatchUrl() {
2
Javascript
Javascript
fix path to uiexplorer examples
f15031a37499701dc8cdbbfbd1b7d376c34cb398
<ide><path>website/server/extractDocs.js <ide> function getPlatformFromPath(filepath) { <ide> } <ide> <ide> function getExamplePaths(componentName, componentPlatform) { <del> const componentExample = '../Examples/UIExplorer/' + componentName + 'Example.'; <add> const componentExample = '../Examples/UIExplorer/js/' + componentName + 'Example.'; <ide> let pathsToCheck = [ <ide> componentExample + 'js', <ide> componentExample + componentPlatform + '.js',
1
PHP
PHP
update projecttask, fixes
72de81ce74fc216a2b4b49d5c480444e02439064
<ide><path>cake/console/libs/tasks/project.php <ide> function __buildDirLayout($path) { <ide> } <ide> <ide> if (!$Folder->chmod($path . DS . 'tmp', 0777)) { <del> $this->err('Could path set permissions on '. $project . DS .'tmp' . DS . '*'); <add> $this->err('Could not set permissions on '. $path . DS .'tmp'); <ide> $this->out('You must manually check that these directories can be wrote to by the server'); <ide> } <ide> } else {
1
PHP
PHP
move view error binding to a new booted event
16f9cf75b9d0e869bc1995741d4bddf91267fe21
<ide><path>src/Illuminate/Foundation/Application.php <ide> class Application extends Container implements HttpKernelInterface { <ide> protected $booted = false; <ide> <ide> /** <del> * Get the booting callbacks. <add> * The array of booting callbacks. <ide> * <ide> * @var array <ide> */ <ide> protected $bootingCallbacks = array(); <ide> <add> /** <add> * The array of booted callbacks. <add> * <add> * @var array <add> */ <add> protected $bootedCallbacks = array(); <add> <ide> /** <ide> * All of the registered service providers. <ide> * <ide> public function boot() <ide> $provider->boot(); <ide> } <ide> <del> $this->fireBootingCallbacks(); <add> $this->fireAppCallbacks($this->bootingCallbacks); <ide> <add> // Once the application has booted we will also fire some "booted" callbacks <add> // for any listeners that need to do work after this initial booting gets <add> // finished. This is useful when ordering the boot-up processes we run. <ide> $this->booted = true; <add> <add> $this->fireAppCallbacks($this->bootedCallbacks); <ide> } <ide> <ide> /** <ide> public function booting($callback) <ide> $this->bootingCallbacks[] = $callback; <ide> } <ide> <add> /** <add> * Register a new "booted" listener. <add> * <add> * @param mixed $callback <add> * @return void <add> */ <add> public function booted($callback) <add> { <add> $this->bootedCallbacks[] = $callback; <add> } <add> <ide> /** <ide> * Call the booting callbacks for the application. <ide> * <ide> * @return void <ide> */ <del> protected function fireBootingCallbacks() <add> protected function fireAppCallbacks(array $callbacks) <ide> { <del> foreach ($this->bootingCallbacks as $callback) <add> foreach ($callbacks as $callback) <ide> { <ide> call_user_func($callback, $this); <ide> } <ide><path>src/Illuminate/View/ViewServiceProvider.php <ide> protected function registerSessionBinder() <ide> { <ide> list($app, $me) = array($this->app, $this); <ide> <del> $app->before(function() use ($app, $me) <add> $app->booted(function() use ($app, $me) <ide> { <ide> // If the current session has an "errors" variable bound to it, we will share <ide> // its value with all view instances so the views can easily access errors <ide> public function sessionHasErrors($app) <ide> <ide> } <ide> <del>} <add>}
2
Javascript
Javascript
introduce macro backdoor
630e1e95d3155696d66cb72e5665c566b28cf195
<ide><path>packages/ember-glimmer/lib/syntax.js <ide> function refineBlockSyntax(sexp, builder) { <ide> return false; <ide> } <ide> <add>let experimentalMacros = []; <add> <add>// This is a private API to allow for expiremental macros <add>// to be created in user space. Registering a macro should <add>// should be done in an initializer. <add>export function registerMacros(macro) { <add> experimentalMacros.push(macro); <add>} <add> <ide> export function populateMacros(blocks, inlines) { <ide> inlines.add('outlet', outletMacro); <ide> inlines.add('component', inlineComponentMacro); <ide> export function populateMacros(blocks, inlines) { <ide> blocks.add('-with-dynamic-vars', _withDynamicVarsMacro); <ide> blocks.add('-in-element', _inElementMacro); <ide> blocks.addMissing(refineBlockSyntax); <add> <add> for (let i = 0; i < experimentalMacros.length; i++) { <add> let macro = experimentalMacros[i]; <add> macro(blocks, inlines); <add> } <ide> return { blocks, inlines }; <ide> }
1
Ruby
Ruby
bring comment in line with rest of initializers
e50ea481dd4ee2e82e947835dff849f28130c2c2
<ide><path>railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb <del>## Change renderer defaults here. <del># <add># Be sure to restart your server when you modify this file. <add> <ide> # ApplicationController.renderer.defaults.merge!( <ide> # http_host: 'example.org', <ide> # https: false
1
Javascript
Javascript
prefer single quotes + some whitespaces
6f91ffeb914e3a3670d675397cbdbff5cf590edd
<ide><path>test/BinderSpec.js <ide> describe('Binder', function() { <ide> })); <ide> <ide> it('ReplaceBindingInTextWithSpan preserve surounding text', function() { <del> expect(this.compileToHtml("<b>a{{b}}c</b>")).toBe('<b>a<span ng:bind="b"></span>c</b>'); <add> expect(this.compileToHtml('<b>a{{b}}c</b>')).toBe('<b>a<span ng:bind="b"></span>c</b>'); <ide> }); <ide> <ide> it('ReplaceBindingInTextWithSpan', function() { <del> expect(this.compileToHtml("<b>{{b}}</b>")).toBe('<b><span ng:bind="b"></span></b>'); <add> expect(this.compileToHtml('<b>{{b}}</b>')).toBe('<b><span ng:bind="b"></span></b>'); <ide> }); <ide> <ide> it('BindingSpaceConfusesIE', inject(function($rootScope, $compile) { <ide> if (!msie) return; <del> var span = document.createElement("span"); <add> var span = document.createElement('span'); <ide> span.innerHTML = '&nbsp;'; <ide> var nbsp = span.firstChild.nodeValue; <del> expect(this.compileToHtml("<b>{{a}} {{b}}</b>")). <add> expect(this.compileToHtml('<b>{{a}} {{b}}</b>')). <ide> toBe('<b><span ng:bind="a"></span><span>' + nbsp + '</span><span ng:bind="b"></span></b>'); <ide> dealoc(($rootScope)); <del> expect(this.compileToHtml("<b>{{A}} x {{B}} ({{C}})</b>")). <add> expect(this.compileToHtml('<b>{{A}} x {{B}} ({{C}})</b>')). <ide> toBe('<b><span ng:bind="A"></span><span>' + nbsp + 'x </span><span ng:bind="B"></span>' + <ide> '<span>' + nbsp + '(</span><span ng:bind="C"></span>)</b>'); <ide> })); <ide> <ide> it('BindingOfAttributes', inject(function($rootScope, $compile) { <del> var element = $compile("<a href='http://s/a{{b}}c' foo='x'></a>")($rootScope); <del> var attrbinding = element.attr("ng:bind-attr"); <add> var element = $compile('<a href="http://s/a{{b}}c" foo="x"></a>')($rootScope); <add> var attrbinding = element.attr('ng:bind-attr'); <ide> var bindings = fromJson(attrbinding); <del> expect(decodeURI(bindings.href)).toBe("http://s/a{{b}}c"); <add> expect(decodeURI(bindings.href)).toBe('http://s/a{{b}}c'); <ide> expect(bindings.foo).toBeFalsy(); <ide> })); <ide> <ide> it('MarkMultipleAttributes', inject(function($rootScope, $compile) { <ide> var element = $compile('<a href="http://s/a{{b}}c" foo="{{d}}"></a>')($rootScope); <del> var attrbinding = element.attr("ng:bind-attr"); <add> var attrbinding = element.attr('ng:bind-attr'); <ide> var bindings = fromJson(attrbinding); <del> expect(bindings.foo).toBe("{{d}}"); <del> expect(decodeURI(bindings.href)).toBe("http://s/a{{b}}c"); <add> expect(bindings.foo).toBe('{{d}}'); <add> expect(decodeURI(bindings.href)).toBe('http://s/a{{b}}c'); <ide> })); <ide> <ide> it('AttributesNoneBound', inject(function($rootScope, $compile) { <del> var a = $compile("<a href='abc' foo='def'></a>")($rootScope); <del> expect(a[0].nodeName).toBe("A"); <del> expect(a.attr("ng:bind-attr")).toBeFalsy(); <add> var a = $compile('<a href="abc" foo="def"></a>')($rootScope); <add> expect(a[0].nodeName).toBe('A'); <add> expect(a.attr('ng:bind-attr')).toBeFalsy(); <ide> })); <ide> <ide> it('ExistingAttrbindingIsAppended', inject(function($rootScope, $compile) { <del> var a = $compile("<a href='http://s/{{abc}}' ng:bind-attr='{\"b\":\"{{def}}\"}'></a>")($rootScope); <add> var a = $compile('<a href="http://s/{{abc}}" ng:bind-attr="{\'b\':\'{{def}}\'}"></a>')($rootScope); <ide> expect(a.attr('ng:bind-attr')).toBe('{"b":"{{def}}","href":"http://s/{{abc}}"}'); <ide> })); <ide> <ide> describe('Binder', function() { <ide> })); <ide> <ide> it('InputTypeButtonActionExecutesInScope2', inject(function($rootScope, $compile) { <del> var log = ""; <add> var log = ''; <ide> var element = $compile('<input type="image" ng:click="action()">')($rootScope); <ide> $rootScope.action = function() { <ide> log += 'click;'; <ide> describe('Binder', function() { <ide> '<ul>' + <ide> '<LI ng:repeat="item in model.items" ng:bind="item.a"></LI>' + <ide> '</ul>')($rootScope); <del> var items = [{a:"A"}, {a:"B"}]; <del> $rootScope.model = {items:items}; <add> var items = [{a: 'A'}, {a: 'B'}]; <add> $rootScope.model = {items: items}; <ide> <ide> $rootScope.$apply(); <ide> expect(sortedHtml(form)).toBe( <ide> describe('Binder', function() { <ide> '<li ng:bind="item.a">B</li>' + <ide> '</ul>'); <ide> <del> items.unshift({a:'C'}); <add> items.unshift({a: 'C'}); <ide> $rootScope.$apply(); <ide> expect(sortedHtml(form)).toBe( <ide> '<ul>' + <ide> describe('Binder', function() { <ide> '<ul>' + <ide> '<LI ng:repeat="item in model.items"><span ng:bind="item.a"></span></li>' + <ide> '</ul>')($rootScope); <del> $rootScope.model = {items:[{a:"A"}]}; <add> $rootScope.model = {items: [{a: 'A'}]}; <ide> $rootScope.$apply(); <ide> expect(sortedHtml(element)).toBe( <ide> '<ul>' + <ide> describe('Binder', function() { <ide> <ide> it('RepeaterAdd', inject(function($rootScope, $compile, $browser) { <ide> var element = $compile('<div><input type="text" ng:model="item.x" ng:repeat="item in items"></div>')($rootScope); <del> $rootScope.items = [{x:'a'}, {x:'b'}]; <add> $rootScope.items = [{x: 'a'}, {x: 'b'}]; <ide> $rootScope.$apply(); <ide> var first = childNode(element, 1); <ide> var second = childNode(element, 2); <ide> describe('Binder', function() { <ide> $rootScope.$apply(); <ide> expect(element[0].childNodes.length - 1).toEqual(0); <ide> <del> items.name = "misko"; <add> items.name = 'misko'; <ide> $rootScope.$apply(); <ide> expect(element[0].childNodes.length - 1).toEqual(1); <ide> <ide> describe('Binder', function() { <ide> var errorLogs = $exceptionHandler.errors; <ide> <ide> $rootScope.error = { <del> 'throw': function() {throw "ErrorMsg1";} <add> 'throw': function() {throw 'ErrorMsg1';} <ide> }; <ide> $rootScope.$apply(); <ide> <del> $rootScope.error['throw'] = function() {throw "MyError";}; <add> $rootScope.error['throw'] = function() {throw 'MyError';}; <ide> errorLogs.length = 0; <ide> $rootScope.$apply(); <ide> expect(errorLogs.shift()).toBe('MyError'); <ide> <del> $rootScope.error['throw'] = function() {return "ok";}; <add> $rootScope.error['throw'] = function() {return 'ok';}; <ide> $rootScope.$apply(); <ide> expect(errorLogs.length).toBe(0); <ide> }) <ide> describe('Binder', function() { <ide> var count = 0; <ide> <ide> $rootScope.error = { <del> 'throw': function() {throw new Error("ErrorMsg" + (++count));} <add> 'throw': function() {throw new Error('ErrorMsg' + (++count));} <ide> }; <ide> $rootScope.$apply(); <ide> expect(errorLogs.length).not.toEqual(0); <ide> describe('Binder', function() { <ide> $rootScope.$eval('style={height: "10px"}'); <ide> $rootScope.$apply(); <ide> <del> expect(element.css('height')).toBe("10px"); <add> expect(element.css('height')).toBe('10px'); <ide> <ide> $rootScope.$eval('style={}'); <ide> $rootScope.$apply(); <ide> describe('Binder', function() { <ide> <ide> it('ShoulIgnoreVbNonBindable', inject(function($rootScope, $compile) { <ide> var element = $compile( <del> "<div>{{a}}" + <del> "<div ng:non-bindable>{{a}}</div>" + <del> "<div ng:non-bindable=''>{{b}}</div>" + <del> "<div ng:non-bindable='true'>{{c}}</div>" + <del> "</div>")($rootScope); <add> '<div>{{a}}' + <add> '<div ng:non-bindable>{{a}}</div>' + <add> '<div ng:non-bindable="">{{b}}</div>' + <add> '<div ng:non-bindable="true">{{c}}</div>' + <add> '</div>')($rootScope); <ide> $rootScope.a = 123; <ide> $rootScope.$apply(); <ide> expect(element.text()).toBe('123{{a}}{{b}}{{c}}'); <ide> })); <ide> <ide> it('ShouldTemplateBindPreElements', inject(function ($rootScope, $compile) { <ide> var element = $compile('<pre>Hello {{name}}!</pre>')($rootScope); <del> $rootScope.name = "World"; <add> $rootScope.name = 'World'; <ide> $rootScope.$apply(); <ide> <ide> expect( sortedHtml(element)).toBe( <ide> describe('Binder', function() { <ide> var errorLogs = $log.error.logs; <ide> <ide> browserTrigger(first, 'click'); <del> expect($rootScope.greeting).toBe("ABC"); <add> expect($rootScope.greeting).toBe('ABC'); <ide> expect(errorLogs).toEqual([]); <ide> <ide> browserTrigger(second, 'click'); <ide> describe('Binder', function() { <ide> var male = jqLite(element[0].childNodes[1]); <ide> <ide> browserTrigger(female); <del> expect($rootScope.sex).toBe("female"); <add> expect($rootScope.sex).toBe('female'); <ide> expect(female[0].checked).toBe(true); <ide> expect(male[0].checked).toBe(false); <del> expect(female.val()).toBe("female"); <add> expect(female.val()).toBe('female'); <ide> <ide> browserTrigger(male); <del> expect($rootScope.sex).toBe("male"); <add> expect($rootScope.sex).toBe('male'); <ide> expect(female[0].checked).toBe(false); <ide> expect(male[0].checked).toBe(true); <del> expect(male.val()).toBe("male"); <add> expect(male.val()).toBe('male'); <ide> })); <ide> <ide> it('ItShouldRepeatOnHashes', inject(function($rootScope, $compile) { <ide> describe('Binder', function() { <ide> <ide> it('ItShouldFireChangeListenersBeforeUpdate', inject(function($rootScope, $compile) { <ide> var element = $compile('<div ng:bind="name"></div>')($rootScope); <del> $rootScope.name = ""; <del> $rootScope.$watch("watched", "name=123"); <del> $rootScope.watched = "change"; <add> $rootScope.name = ''; <add> $rootScope.$watch('watched', 'name=123'); <add> $rootScope.watched = 'change'; <ide> $rootScope.$apply(); <ide> expect($rootScope.name).toBe(123); <ide> expect(sortedHtml(element)).toBe('<div ng:bind="name">123</div>'); <ide> describe('Binder', function() { <ide> it('ItShouldHandleMultilineBindings', inject(function($rootScope, $compile) { <ide> var element = $compile('<div>{{\n 1 \n + \n 2 \n}}</div>')($rootScope); <ide> $rootScope.$apply(); <del> expect(element.text()).toBe("3"); <add> expect(element.text()).toBe('3'); <ide> })); <ide> <ide> }); <ide><path>test/JsonSpec.js <ide> describe('json', function() { <ide> expect(toJson(null)).toEqual('null'); <ide> expect(toJson(true)).toEqual('true'); <ide> expect(toJson(false)).toEqual('false'); <del> expect(toJson(123.45)).toEqual("123.45"); <del> expect(toJson("abc")).toEqual('"abc"'); <del> expect(toJson("a \t \n \r b \\")).toEqual('"a \\t \\n \\r b \\\\"'); <add> expect(toJson(123.45)).toEqual('123.45'); <add> expect(toJson('abc')).toEqual('"abc"'); <add> expect(toJson('a \t \n \r b \\')).toEqual('"a \\t \\n \\r b \\\\"'); <ide> }); <ide> <ide> it('should not serialize $$properties', function() { <ide> describe('json', function() { <ide> }); <ide> <ide> it('should serialize objects', function() { <del> expect(toJson({a:1,b:2})).toEqual('{"a":1,"b":2}'); <del> expect(toJson({a:{b:2}})).toEqual('{"a":{"b":2}}'); <del> expect(toJson({a:{b:{c:0}}})).toEqual('{"a":{"b":{"c":0}}}'); <del> expect(toJson({a:{b:0/0}})).toEqual('{"a":{"b":null}}'); <add> expect(toJson({a: 1, b: 2})).toEqual('{"a":1,"b":2}'); <add> expect(toJson({a: {b: 2}})).toEqual('{"a":{"b":2}}'); <add> expect(toJson({a: {b: {c: 0}}})).toEqual('{"a":{"b":{"c":0}}}'); <add> expect(toJson({a: {b: 0/0}})).toEqual('{"a":{"b":null}}'); <ide> }); <ide> <ide> it('should format objects pretty', function() { <del> expect(toJson({a:1,b:2}, true)).toEqual('{\n "a":1,\n "b":2}'); <del> expect(toJson({a:{b:2}}, true)).toEqual('{\n "a":{\n "b":2}}'); <add> expect(toJson({a: 1, b: 2}, true)).toEqual('{\n "a":1,\n "b":2}'); <add> expect(toJson({a: {b: 2}}, true)).toEqual('{\n "a":{\n "b":2}}'); <ide> }); <ide> <ide> it('should serialize array', function() { <ide> expect(toJson([])).toEqual('[]'); <del> expect(toJson([1,"b"])).toEqual('[1,"b"]'); <add> expect(toJson([1, 'b'])).toEqual('[1,"b"]'); <ide> }); <ide> <ide> it('should serialize RegExp', function() { <ide> expect(toJson(/foo/)).toEqual('"/foo/"'); <del> expect(toJson([1,new RegExp("foo")])).toEqual('[1,"/foo/"]'); <add> expect(toJson([1, new RegExp('foo')])).toEqual('[1,"/foo/"]'); <ide> }); <ide> <ide> it('should ignore functions', function() { <ide> describe('json', function() { <ide> }); <ide> <ide> it('should parse null', function() { <del> expect(fromJson("null")).toBeNull(); <add> expect(fromJson('null')).toBeNull(); <ide> }); <ide> <ide> it('should parse boolean', function() { <del> expect(fromJson("true")).toBeTruthy(); <del> expect(fromJson("false")).toBeFalsy(); <add> expect(fromJson('true')).toBeTruthy(); <add> expect(fromJson('false')).toBeFalsy(); <ide> }); <ide> <ide> it('should serialize array with empty items', function() { <ide> var a = []; <del> a[1] = "X"; <add> a[1] = 'X'; <ide> expect(toJson(a)).toEqual('[null,"X"]'); <ide> }); <ide> <ide> it('should escape unicode', function() { <del> expect("\u00a0".length).toEqual(1); <del> expect(toJson("\u00a0").length).toEqual(8); <del> expect(fromJson(toJson("\u00a0")).length).toEqual(1); <add> expect('\u00a0'.length).toEqual(1); <add> expect(toJson('\u00a0').length).toEqual(8); <add> expect(fromJson(toJson('\u00a0')).length).toEqual(1); <ide> }); <ide> <ide> it('should serialize UTC dates', function() { <del> var date = jsonStringToDate("2009-10-09T01:02:03.027Z"); <add> var date = jsonStringToDate('2009-10-09T01:02:03.027Z'); <ide> expect(toJson(date)).toEqual('"2009-10-09T01:02:03.027Z"'); <ide> expect(fromJson('"2009-10-09T01:02:03.027Z"').getTime()).toEqual(date.getTime()); <ide> }); <ide> <ide> it('should prevent recursion', function() { <del> var obj = {a:'b'}; <add> var obj = {a: 'b'}; <ide> obj.recursion = obj; <ide> expect(angular.toJson(obj)).toEqual('{"a":"b","recursion":RECURSION}'); <ide> }); <ide> describe('json', function() { <ide> }); <ide> <ide> it('should not allow assignments', function() { <del> expect(function() {fromJson("{a:1, b:[1]=1, c:1}");}).toThrow(); <del> expect(function() {fromJson("{a:1, b:=1, c:1}");}).toThrow(); <del> expect(function() {fromJson("{a:1, b:x=1, c:1}");}).toThrow(); <add> expect(function() {fromJson('{a:1, b:[1]=1, c:1}');}).toThrow(); <add> expect(function() {fromJson('{a:1, b:=1, c:1}');}).toThrow(); <add> expect(function() {fromJson('{a:1, b:x=1, c:1}');}).toThrow(); <ide> }); <ide> <ide> }); <ide> <ide> <ide> it('should read/write to date', function() { <del> var date = new Date("Sep 10 2003 13:02:03 GMT"); <del> expect(jsonDateToString(date)).toBe("2003-09-10T13:02:03.000Z"); <add> var date = new Date('Sep 10 2003 13:02:03 GMT'); <add> expect(jsonDateToString(date)).toBe('2003-09-10T13:02:03.000Z'); <ide> expect(jsonStringToDate(jsonDateToString(date)).getTime()).toBe(date.getTime()); <ide> }); <ide> <ide> <ide> it('should convert to date', function() { <ide> //full ISO8061 <del> expect(jsonStringToDate("2003-09-10T13:02:03.000Z")). <del> toEqual(new Date("Sep 10 2003 13:02:03 GMT")); <add> expect(jsonStringToDate('2003-09-10T13:02:03.000Z')). <add> toEqual(new Date('Sep 10 2003 13:02:03 GMT')); <ide> <ide> //no millis <del> expect(jsonStringToDate("2003-09-10T13:02:03Z")). <del> toEqual(new Date("Sep 10 2003 13:02:03 GMT")); <add> expect(jsonStringToDate('2003-09-10T13:02:03Z')). <add> toEqual(new Date('Sep 10 2003 13:02:03 GMT')); <ide> <ide> //no seconds <del> expect(jsonStringToDate("2003-09-10T13:02Z")). <del> toEqual(new Date("Sep 10 2003 13:02:00 GMT")); <add> expect(jsonStringToDate('2003-09-10T13:02Z')). <add> toEqual(new Date('Sep 10 2003 13:02:00 GMT')); <ide> <ide> //no minutes <del> expect(jsonStringToDate("2003-09-10T13Z")). <del> toEqual(new Date("Sep 10 2003 13:00:00 GMT")); <add> expect(jsonStringToDate('2003-09-10T13Z')). <add> toEqual(new Date('Sep 10 2003 13:00:00 GMT')); <ide> <ide> //no time <del> expect(jsonStringToDate("2003-09-10")). <del> toEqual(new Date("Sep 10 2003 00:00:00 GMT")); <add> expect(jsonStringToDate('2003-09-10')). <add> toEqual(new Date('Sep 10 2003 00:00:00 GMT')); <ide> }); <ide> <ide> <ide> it('should parse date', function() { <del> var date = jsonStringToDate("2003-09-10T13:02:03.000Z"); <del> expect(jsonDateToString(date)).toBe("2003-09-10T13:02:03.000Z"); <del> expect(jsonStringToDate("str")).toBe("str"); <add> var date = jsonStringToDate('2003-09-10T13:02:03.000Z'); <add> expect(jsonDateToString(date)).toBe('2003-09-10T13:02:03.000Z'); <add> expect(jsonStringToDate('str')).toBe('str'); <ide> }); <ide> <ide>
2
Ruby
Ruby
fix disable_joins when using an enum sti type
207747ec2d07699c30cd06c1bcf5bacd567c9417
<ide><path>activerecord/lib/active_record/associations/disable_joins_association_scope.rb <ide> def last_scope_chain(reverse_chain, owner) <ide> <ide> def add_constraints(reflection, key, join_ids, owner, ordered) <ide> scope = reflection.build_scope(reflection.aliased_table).where(key => join_ids) <add> <add> relation = reflection.klass.scope_for_association <add> scope.merge!( <add> relation.except(:select, :create_with, :includes, :preload, :eager_load, :joins, :left_outer_joins) <add> ) <add> <ide> scope = reflection.constraints.inject(scope) do |memo, scope_chain_item| <ide> item = eval_scope(reflection, scope_chain_item, owner) <ide> scope.unscope!(*item.unscope_values) <ide><path>activerecord/test/cases/associations/has_one_through_disable_joins_associations_test.rb <ide> require "models/developer" <ide> require "models/company" <ide> require "models/computer" <add>require "models/club" <add>require "models/membership" <ide> <ide> class HasOneThroughDisableJoinsAssociationsTest < ActiveRecord::TestCase <del> fixtures :members, :organizations, :projects, :developers, :companies <add> fixtures :members, :organizations, :projects, :developers, :companies, :clubs, :memberships <ide> <ide> def setup <ide> @member = members(:groucho) <ide> def test_has_one_through_with_belongs_to_on_disable_joins <ide> assert_no_match(/INNER JOIN/, nj) <ide> end <ide> end <add> <add> def test_disable_joins_through_with_enum_type <add> joins = capture_sql { @member.club } <add> no_joins = capture_sql { @member.club_without_joins } <add> <add> assert_equal 1, joins.size <add> assert_equal 2, no_joins.size <add> <add> assert_match(/INNER JOIN/, joins.first) <add> no_joins.each do |nj| <add> assert_no_match(/INNER JOIN/, nj) <add> end <add> <add> if current_adapter?(:Mysql2Adapter) <add> assert_match(/`memberships`.`type`/, no_joins.first) <add> else <add> assert_match(/"memberships"."type"/, no_joins.first) <add> end <add> end <ide> end <ide><path>activerecord/test/models/member.rb <ide> class Member < ActiveRecord::Base <ide> has_one :selected_membership <ide> has_one :membership <ide> has_one :club, through: :current_membership <add> has_one :club_without_joins, through: :current_membership, source: :club, disable_joins: true <ide> has_one :selected_club, through: :selected_membership, source: :club <ide> has_one :favorite_club, -> { where "memberships.favorite = ?", true }, through: :membership, source: :club <ide> has_one :hairy_club, -> { where clubs: { name: "Moustache and Eyebrow Fancier Club" } }, through: :membership, source: :club
3
Javascript
Javascript
add mac to test-os
76ada45342db20947ec638659276e39762b22c15
<ide><path>test/simple/test-os.js <ide> switch (platform) { <ide> var filter = function(e) { return e.address == '127.0.0.1'; }; <ide> var actual = interfaces.lo.filter(filter); <ide> var expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', <del> family: 'IPv4', internal: true }]; <add> mac: '00:00:00:00:00:00', family: 'IPv4', <add> internal: true }]; <ide> assert.deepEqual(actual, expected); <ide> break; <ide> case 'win32': <ide> switch (platform) { <ide> // default to /32 here. We could put in a special case to force <ide> // to /8 if desired. <ide> var expected = [{ address: '127.0.0.1', netmask: '255.255.255.255', <del> family: 'IPv4', internal: true }]; <add> mac: '00:00:00:00:00:00', family: 'IPv4', <add> internal: true }]; <ide> assert.deepEqual(actual, expected); <ide> break; <ide> }
1
Ruby
Ruby
deprecate the env method on controller instances
05934d24aff62d66fc62621aa38dae6456e276be
<ide><path>actionpack/lib/action_controller/metal.rb <ide> require 'active_support/core_ext/array/extract_options' <ide> require 'action_dispatch/middleware/stack' <add>require 'active_support/deprecation' <ide> <ide> module ActionController <ide> # Extend ActionDispatch middleware stack to make it aware of options <ide> class Metal < AbstractController::Base <ide> def env <ide> @_request.env <ide> end <add> deprecate :env <ide> <ide> # Returns the last part of the controller's name, underscored, without the ending <ide> # <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>. <ide><path>actionpack/lib/action_controller/metal/streaming.rb <ide> module Streaming <ide> def _process_options(options) #:nodoc: <ide> super <ide> if options[:stream] <del> if env["HTTP_VERSION"] == "HTTP/1.0" <add> if request.version == "HTTP/1.0" <ide> options.delete(:stream) <ide> else <ide> headers["Cache-Control"] ||= "no-cache" <ide><path>actionpack/lib/action_dispatch/http/request.rb <ide> class Request < Rack::Request <ide> HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING <ide> HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM <ide> HTTP_NEGOTIATE HTTP_PRAGMA HTTP_CLIENT_IP <del> HTTP_X_FORWARDED_FOR <add> HTTP_X_FORWARDED_FOR HTTP_VERSION <ide> ].freeze <ide> <ide> ENV_METHODS.each do |env|
3
Ruby
Ruby
fix string#blank? on binary strings
0c58f39c2c7ff590e854772e41f6d10117a51c53
<ide><path>activesupport/lib/active_support/core_ext/object/blank.rb <ide> class String <ide> # " something here ".blank? # => false <ide> # <ide> def blank? <del> self !~ NON_WHITESPACE_REGEXP <add> # 1.8 does not takes [:space:] properly <add> if encoding_aware? <add> self !~ /[^[:space:]]/ <add> else <add> self !~ NON_WHITESPACE_REGEXP <add> end <ide> end <ide> end <ide>
1
Text
Text
replace text "помутнение" on "непрозрачность"
1d162bf8a7fd9b88737173d74baf3e3f2118f243
<ide><path>guide/russian/css/colors/index.md <ide> Hex-коды нечувствительны к регистру, что озна <ide> <ide> Кроме того, имеется 16 777 216 возможных цветовых комбинаций с использованием шестнадцатеричного кода. <ide> <del>### помутнение <add>### Непрозрачность <ide> <ide> Свойство opacity CSS3 задает непрозрачность для всего элемента (оба цвета фона и текст будут непрозрачными / прозрачными). В отличие от альфа-значений, заданных с помощью rgba и hsla, непрозрачность наследуется дочерними элементами. <ide> <ide> body { <ide> <ide> #### Дополнительная информация: <ide> <del>[Adobe Color CC](https://color.adobe.com/) [ColorPick Eyedropper в Интернет-магазине Chrome](https://chrome.google.com/webstore/detail/colorpick-eyedropper/ohcpnigalekghcmgcdcenkpelffpdolg?hl=en) [Добавление ColorZilla для Firefox](https://addons.mozilla.org/en-US/firefox/addon/colorzilla/) [Исследуйте разные цвета Hex](http://www.colorhexa.com/) [Проверка соответствия цвета WebAIM](https://webaim.org/resources/contrastchecker/) <ide>\ No newline at end of file <add>[Adobe Color CC](https://color.adobe.com/) [ColorPick Eyedropper в Интернет-магазине Chrome](https://chrome.google.com/webstore/detail/colorpick-eyedropper/ohcpnigalekghcmgcdcenkpelffpdolg?hl=en) [Добавление ColorZilla для Firefox](https://addons.mozilla.org/en-US/firefox/addon/colorzilla/) [Исследуйте разные цвета Hex](http://www.colorhexa.com/) [Проверка соответствия цвета WebAIM](https://webaim.org/resources/contrastchecker/)
1
PHP
PHP
use cleaner api for mocking model events
c6eff0f8dcd480985ca7788afa1d98bf5d62983c
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php <ide> protected function withoutModelEvents() <ide> * <ide> * These events will be mocked, so that handlers will not actually be executed. <ide> * <add> * @param string $model <ide> * @param array|string $events <ide> * @return $this <ide> * <ide> * @throws \Exception <ide> */ <del> public function expectsModelEvents($events) <add> public function expectsModelEvents($model, $events) <ide> { <del> $events = is_array($events) ? $events : func_get_args(); <add> $events = $this->formatModelEvents($model, $events); <ide> <ide> $this->withoutModelEvents(); <ide> <ide> public function expectsModelEvents($events) <ide> * <ide> * These events will be mocked, so that handlers will not actually be executed. <ide> * <add> * @param string $model <ide> * @param array|string $events <ide> * @return $this <add> * <add> * @throws \Exception <ide> */ <del> public function doesntExpectModelEvents($events) <add> public function doesntExpectModelEvents($model, $events) <ide> { <del> $events = is_array($events) ? $events : func_get_args(); <add> $events = $this->formatModelEvents($model, $events); <ide> <ide> $this->withoutModelEvents(); <ide> <ide> public function doesntExpectModelEvents($events) <ide> return $this; <ide> } <ide> <add> /** <add> * Turn a model and a list of events into the format used by eloquent <add> * <add> * @param string $model <add> * @param array|string $events <add> * @return string[] <add> * <add> * @throws \Exception <add> */ <add> private function formatModelEvents($model, $events) <add> { <add> $events = (array) $events; <add> <add> return array_map(function ($event) use ($model) { <add> return "eloquent.{$event}: {$model}"; <add> }, (array) $events); <add> } <add> <ide> /** <ide> * Specify a list of observers that will not run for the given operation. <ide> * <ide><path>tests/Foundation/FoundationExpectsModelEventsTest.php <ide> class FoundationExpectsModelEventsTest extends TestCase <ide> { <ide> public function createApplication() <ide> { <add> Model::clearBootedModels(); <add> <ide> $app = new Application; <ide> <ide> $db = new DB; <ide> public function a_mock_replaces_the_event_dispatcher_when_calling_expects_model_ <ide> <ide> $this->assertNotInstanceOf(Mock::class, Model::getEventDispatcher()); <ide> <del> $this->expectsModelEvents([]); <add> $this->expectsModelEvents(EloquentTestModel::class, []); <ide> <ide> $this->assertNotInstanceOf(Dispatcher::class, Model::getEventDispatcher()); <ide> $this->assertInstanceOf(Mock::class, Model::getEventDispatcher()); <ide> public function a_mock_does_not_carry_over_between_tests() <ide> /** @test */ <ide> public function fired_events_can_be_checked_for() <ide> { <del> $this->expectsModelEvents([ <del> 'eloquent.booting: EloquentTestModel', <del> 'eloquent.booted: EloquentTestModel', <add> $this->expectsModelEvents(EloquentTestModel::class, [ <add> 'booting', <add> 'booted', <add> <add> 'creating', <add> 'created', <ide> <del> 'eloquent.creating: EloquentTestModel', <del> 'eloquent.created: EloquentTestModel', <add> 'saving', <add> 'saved', <ide> <del> 'eloquent.saving: EloquentTestModel', <del> 'eloquent.saved: EloquentTestModel', <add> 'updating', <add> 'updated', <add> <add> 'deleting', <add> 'deleted', <add> ]); <ide> <del> 'eloquent.updating: EloquentTestModel', <del> 'eloquent.updated: EloquentTestModel', <add> $model = EloquentTestModel::create(['field' => 1]); <add> $model->field = 2; <add> $model->save(); <add> $model->delete(); <add> } <add> <add> /** @test */ <add> public function using_expects_model_events_multiple_times_works() <add> { <add> $this->expectsModelEvents(EloquentTestModel::class, [ <add> 'booting', <add> 'booted', <add> ]); <ide> <del> 'eloquent.deleting: EloquentTestModel', <del> 'eloquent.deleted: EloquentTestModel', <add> $this->expectsModelEvents(EloquentTestModel::class, [ <add> 'creating', <add> 'created', <ide> ]); <ide> <ide> $model = EloquentTestModel::create(['field' => 1]); <ide> public function fired_events_can_be_checked_for() <ide> $model->delete(); <ide> } <ide> <add> /** @test */ <add> public function expects_model_events_can_take_a_string_as_the_event_name() <add> { <add> $this->expectsModelEvents(EloquentTestModel::class, "booting"); <add> <add> EloquentTestModel::create(['field' => 1]); <add> } <add> <add> /** @test */ <add> public function unfired_events_can_be_checked_for() <add> { <add> $this->doesntExpectModelEvents(EloquentTestModel::class, [ <add> 'updating', <add> 'updated', <add> <add> 'deleting', <add> 'deleted', <add> ]); <add> <add> EloquentTestModel::create(['field' => 1]); <add> } <add> <add> /** @test */ <add> public function using_doesnt_expect_model_events_multiple_times_works() <add> { <add> $this->doesntExpectModelEvents(EloquentTestModel::class, [ <add> 'updating', <add> 'updated', <add> ]); <add> <add> $this->doesntExpectModelEvents(EloquentTestModel::class, [ <add> 'deleting', <add> 'deleted', <add> ]); <add> <add> EloquentTestModel::create(['field' => 1]); <add> } <add> <add> /** @test */ <add> public function doesnt_expect_model_events_can_take_a_string_as_the_event_name() <add> { <add> $this->doesntExpectModelEvents(EloquentTestModel::class, "deleting"); <add> <add> EloquentTestModel::create(['field' => 1]); <add> } <add> <ide> /** @test */ <ide> public function observers_do_not_fire_when_mocking_events() <ide> { <del> $this->expectsModelEvents([ <del> 'eloquent.saving: EloquentTestModel', <del> 'eloquent.saved: EloquentTestModel', <add> $this->expectsModelEvents(EloquentTestModel::class, [ <add> 'saving', <add> 'saved', <add> ]); <add> <add> $this->doesntExpectModelEvents(EloquentTestModel::class, [ <add> 'deleting', <add> 'deleted', <ide> ]); <ide> <ide> EloquentTestModel::observe(new EloquentTestModelFailingObserver); <ide> public function saved() <ide> { <ide> PHPUnit_Framework_Assert::fail('The [saved] method should not be called on '.static::class); <ide> } <add> <add> public function deleting() <add> { <add> PHPUnit_Framework_Assert::fail('The [deleting] method should not be called on '.static::class); <add> } <add> <add> public function deleted() <add> { <add> PHPUnit_Framework_Assert::fail('The [deleted] method should not be called on '.static::class); <add> } <ide> }
2
Ruby
Ruby
add tests for associations without counter_cache
543523045112c5f5920c486e6fcf2d7e1ffedf5a
<ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb <ide> require 'models/line_item' <ide> require 'models/column' <ide> require 'models/record' <add>require 'models/ship' <add>require 'models/treasure' <add>require 'models/parrot' <ide> <ide> class BelongsToAssociationsTest < ActiveRecord::TestCase <ide> fixtures :accounts, :companies, :developers, :projects, :topics, <ide> def test_with_select <ide> assert_equal 1, Company.all.merge!(:includes => :firm_with_select ).find(2).firm_with_select.attributes.size <ide> end <ide> <add> def test_belongs_to_without_counter_cache_option <add> # Ship has a conventionally named `treasures_count` column, but the counter_cache <add> # option is not given on the association. <add> ship = Ship.create(name: 'Countless') <add> <add> assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do <add> treasure = Treasure.new(name: 'Gold', ship: ship) <add> treasure.save <add> end <add> <add> assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do <add> treasure = ship.treasures.first <add> treasure.destroy <add> end <add> end <add> <ide> def test_belongs_to_counter <ide> debate = Topic.create("title" => "debate") <ide> assert_equal 0, debate.read_attribute("replies_count"), "No replies yet" <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> require 'models/pirate' <ide> require 'models/ship' <ide> require 'models/ship_part' <add>require 'models/treasure' <add>require 'models/parrot' <ide> require 'models/tyre' <ide> require 'models/subscriber' <ide> require 'models/subscription' <ide> def test_deleting_before_save <ide> assert_equal 0, new_firm.clients_of_firm.size <ide> end <ide> <add> def test_has_many_without_counter_cache_option <add> # Ship has a conventionally named `treasures_count` column, but the counter_cache <add> # option is not given on the association. <add> ship = Ship.create(name: 'Countless', treasures_count: 10) <add> <add> assert_not ship.treasures.instance_variable_get('@association').send(:has_cached_counter?) <add> <add> # Count should come from sql count() of treasures rather than treasures_count attribute <add> assert_equal ship.treasures.size, 0 <add> <add> assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed" do <add> ship.treasures.create(name: 'Gold') <add> end <add> <add> assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed" do <add> ship.treasures.destroy_all <add> end <add> end <add> <ide> def test_deleting_updates_counter_cache <ide> topic = Topic.order("id ASC").first <ide> assert_equal topic.replies.to_a.size, topic.replies_count <ide><path>activerecord/test/models/treasure.rb <ide> class Treasure < ActiveRecord::Base <ide> has_and_belongs_to_many :parrots <ide> belongs_to :looter, :polymorphic => true <add> # No counter_cache option given <ide> belongs_to :ship <ide> <ide> has_many :price_estimates, :as => :estimate_of <ide><path>activerecord/test/schema/schema.rb <ide> def except(adapter_names_to_exclude) <ide> t.string :name <ide> t.integer :pirate_id <ide> t.integer :update_only_pirate_id <add> # Conventionally named column for counter_cache <add> t.integer :treasures_count, default: 0 <ide> t.datetime :created_at <ide> t.datetime :created_on <ide> t.datetime :updated_at
4
Text
Text
add ricky zhou to collaborators
e1eb56fc94f4a345dfde51847e551b132cf98da8
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Pranshu Srivastava** &lt;[email protected]&gt; (he/him) <ide> * [richardlau](https://github.com/richardlau) - <ide> **Richard Lau** &lt;[email protected]&gt; <add>* [rickyes](https://github.com/rickyes) - <add>**Ricky Zhou** &lt;[email protected]&gt; (he/him) <ide> * [ronag](https://github.com/ronag) - <ide> **Robert Nagy** &lt;[email protected]&gt; <ide> * [ronkorving](https://github.com/ronkorving) -
1
Mixed
Javascript
remove more upstream modules that aren't used
3525d01b9b9e0e635fd1a76777abf510ee64275a
<ide><path>src/vendor/immutable/Immutable.js <del>/** <del> * Copyright 2013-2015, Facebook, Inc. <del> * All rights reserved. <del> * <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. <del> * <del> * @providesModule Immutable <del> */ <del> <del>var assign = require('Object.assign'); <del>var invariant = require('invariant'); <del>var isNode = require('isNode'); <del>var keyOf = require('keyOf'); <del> <del>var SECRET_KEY = keyOf({_DONT_EVER_TYPE_THIS_SECRET_KEY: null}); <del> <del>/** <del> * `Immutable` provides a guarantee of immutability at developer time when <del> * strict mode is used. The extra computations required to enforce immutability <del> * are stripped out in production for performance reasons. `Immutable` <del> * guarantees to enforce immutability for enumerable, own properties. This <del> * allows easy wrapping of `Immutable` with the ability to store non-enumerable <del> * properties on the instance that only your static methods reason about. In <del> * order to achieve IE8 compatibility (which doesn't have the ability to define <del> * non-enumerable properties), modules that want to build their own reasoning <del> * of `Immutable`s and store computations can define their non-enumerable <del> * properties under the name `toString`, and in IE8 only define a standard <del> * property called `toString` which will mistakenly be considered not <del> * enumerable due to its name (but only in IE8). The only limitation is that no <del> * one can store their own `toString` property. <del> * https://developer.mozilla.org/en-US/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug <del> */ <del>class Immutable { <del> /** <del> * An instance of `Immutable` appears to be a plain JavaScript object, except <del> * `instanceof Immutable` evaluates to `true`, and it is deeply frozen in <del> * development mode. <del> * <del> * @param {number} secret Ensures this isn't accidentally constructed outside <del> * of convenience constructors. If created outside of a convenience <del> * constructor, may not be frozen. Forbidding that use case for now until we <del> * have a better API. <del> */ <del> constructor(secret) { <del> invariant( <del> secret === Immutable[SECRET_KEY], <del> 'Only certain classes should create instances of `Immutable`.' + <del> 'You probably want something like ImmutableObject.create.' <del> ); <del> } <del> <del> /** <del> * Helper method for classes that make use of `Immutable`. <del> * @param {Immutable} immutable Object to merge properties into. <del> * @param {array<object>} propertyObjects List of objects to merge into <del> * `destination`. <del> */ <del> static mergeAllPropertiesInto(destination, propertyObjects) { <del> var argLength = propertyObjects.length; <del> for (var i = 0; i < argLength; i++) { <del> assign(destination, propertyObjects[i]); <del> } <del> } <del> <del> <del> /** <del> * Freezes the supplied object deeply. Other classes may implement their own <del> * version based on this. <del> * <del> * @param {*} object The object to freeze. <del> */ <del> static deepFreezeRootNode(object) { <del> if (isNode(object)) { <del> return; // Don't try to freeze DOM nodes. <del> } <del> Object.freeze(object); // First freeze the object. <del> for (var prop in object) { <del> if (object.hasOwnProperty(prop)) { <del> Immutable.recurseDeepFreeze(object[prop]); <del> } <del> } <del> Object.seal(object); <del> } <del> <del> /** <del> * Differs from `deepFreezeRootNode`, in that we first check if this is a <del> * necessary recursion. If the object is already an `Immutable`, then the <del> * recursion is unnecessary as it is already frozen. That check obviously <del> * wouldn't work for the root node version `deepFreezeRootNode`! <del> */ <del> static recurseDeepFreeze(object) { <del> if (isNode(object) || !Immutable.shouldRecurseFreeze(object)) { <del> return; // Don't try to freeze DOM nodes. <del> } <del> Object.freeze(object); // First freeze the object. <del> for (var prop in object) { <del> if (object.hasOwnProperty(prop)) { <del> Immutable.recurseDeepFreeze(object[prop]); <del> } <del> } <del> Object.seal(object); <del> } <del> <del> /** <del> * Checks if an object should be deep frozen. Instances of `Immutable` are <del> * assumed to have already been deep frozen, so we can have large `__DEV__` <del> * time savings by skipping freezing of them. <del> * <del> * @param {*} object The object to check. <del> * @return {boolean} Whether or not deep freeze is needed. <del> */ <del> static shouldRecurseFreeze(object) { <del> return ( <del> typeof object === 'object' && <del> !(object instanceof Immutable) && <del> object !== null <del> ); <del> } <del>} <del> <del>Immutable._DONT_EVER_TYPE_THIS_SECRET_KEY = Math.random(); <del> <del>module.exports = Immutable; <ide><path>src/vendor/immutable/ImmutableObject.js <del>/** <del> * Copyright 2013-2015, Facebook, Inc. <del> * All rights reserved. <del> * <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. <del> * <del> * @providesModule ImmutableObject <del> */ <del> <del>"use strict"; <del> <del>var Immutable = require('Immutable'); <del> <del>var invariant = require('invariant'); <del>var keyOf = require('keyOf'); <del>var mergeHelpers = require('mergeHelpers'); <del> <del>var checkMergeObjectArgs = mergeHelpers.checkMergeObjectArgs; <del>var isTerminal = mergeHelpers.isTerminal; <del> <del>var SECRET_KEY = keyOf({_DONT_EVER_TYPE_THIS_SECRET_KEY: null}); <del> <del>/** <del> * Static methods creating and operating on instances of `Immutable`. <del> */ <del>function assertImmutable(immutable) { <del> invariant( <del> immutable instanceof Immutable, <del> 'ImmutableObject: Attempted to set fields on an object that is not an ' + <del> 'instance of Immutable.' <del> ); <del>} <del> <del>/** <del> * Static methods for reasoning about instances of `ImmutableObject`. Execute <del> * the freeze commands in `__DEV__` mode to alert the programmer that something <del> * is attempting to mutate. Since freezing is very expensive, we avoid doing it <del> * at all in production. <del> */ <del>class ImmutableObject extends Immutable { <del> /** <del> * @arguments {array<object>} The arguments is an array of objects that, when <del> * merged together, will form the immutable objects. <del> */ <del> constructor() { <del> super(Immutable[SECRET_KEY]); <del> Immutable.mergeAllPropertiesInto(this, arguments); <del> if (__DEV__) { <del> Immutable.deepFreezeRootNode(this); <del> } <del> } <del> <del> /** <del> * DEPRECATED - prefer to instantiate with new ImmutableObject(). <del> * <del> * @arguments {array<object>} The arguments is an array of objects that, when <del> * merged together, will form the immutable objects. <del> */ <del> static create() { <del> var obj = Object.create(ImmutableObject.prototype); <del> ImmutableObject.apply(obj, arguments); <del> return obj; <del> } <del> <del> /** <del> * Returns a new `Immutable` that is identical to the supplied `Immutable` <del> * but with the specified changes, `put`. Any keys that are in the <del> * intersection of `immutable` and `put` retain the ordering of `immutable. <del> * New keys are placed after keys that exist in `immutable`. <del> * <del> * @param {Immutable} immutable Starting object. <del> * @param {?object} put Fields to merge into the object. <del> * @return {Immutable} The result of merging in `put` fields. <del> */ <del> static set(immutable, put) { <del> assertImmutable(immutable); <del> invariant( <del> typeof put === 'object' && put !== undefined && !Array.isArray(put), <del> 'Invalid ImmutableMap.set argument `put`' <del> ); <del> return new ImmutableObject(immutable, put); <del> } <del> <del> /** <del> * Sugar for `ImmutableObject.set(ImmutableObject, {fieldName: putField})`. <del> * Look out for key crushing: Use `keyOf()` to guard against it. <del> * <del> * @param {Immutable} immutable Object on which to set properties. <del> * @param {string} fieldName Name of the field to set. <del> * @param {*} putField Value of the field to set. <del> * @return {Immutable} new Immutable as described in `set`. <del> */ <del> static setProperty(immutableObject, fieldName, putField) { <del> var put = {}; <del> put[fieldName] = putField; <del> return ImmutableObject.set(immutableObject, put); <del> } <del> <del> /** <del> * Returns a new `Immutable` that is identical to the supplied object but <del> * with the supplied changes recursively applied. <del> * <del> * Experimental. Likely does not handle `Arrays` correctly. <del> * <del> * @param {Immutable} immutable Object on which to set fields. <del> * @param {object} put Fields to merge into the object. <del> * @return {Immutable} The result of merging in `put` fields. <del> */ <del> static setDeep(immutable, put) { <del> assertImmutable(immutable); <del> return _setDeep(immutable, put); <del> } <del>} <del> <del>function _setDeep(obj, put) { <del> checkMergeObjectArgs(obj, put); <del> var totalNewFields = {}; <del> <del> // To maintain the order of the keys, copy the base object's entries first. <del> var keys = Object.keys(obj); <del> for (var ii = 0; ii < keys.length; ii++) { <del> var key = keys[ii]; <del> if (!put.hasOwnProperty(key)) { <del> totalNewFields[key] = obj[key]; <del> } else if (isTerminal(obj[key]) || isTerminal(put[key])) { <del> totalNewFields[key] = put[key]; <del> } else { <del> totalNewFields[key] = _setDeep(obj[key], put[key]); <del> } <del> } <del> <del> // Apply any new keys that the base obj didn't have. <del> var newKeys = Object.keys(put); <del> for (ii = 0; ii < newKeys.length; ii++) { <del> var newKey = newKeys[ii]; <del> if (obj.hasOwnProperty(newKey)) { <del> continue; <del> } <del> totalNewFields[newKey] = put[newKey]; <del> } <del> <del> return ( <del> obj instanceof Immutable ? new ImmutableObject(totalNewFields) : <del> put instanceof Immutable ? new ImmutableObject(totalNewFields) : <del> totalNewFields <del> ); <del>} <del> <del>module.exports = ImmutableObject; <ide><path>src/vendor_deprecated/README.md <del>The files in this directory are modified from their original implementation. At some point the files here were included in the React package shipped to npm and used by other projects. <del> <del>We removed all uses of these files inside React itself but would like to provide a sane deprecation notice for other consumers. We made no promises about the files here; they were always "use at your own risk". <ide><path>src/vendor_deprecated/core/copyProperties.js <del>/** <del> * Copyright 2013-2015, Facebook, Inc. <del> * All rights reserved. <del> * <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. <del> * <del> * @providesModule copyProperties <del> */ <del> <del>"use strict"; <del> <del>/** <del> * Copy properties from one or more objects (up to 5) into the first object. <del> * This is a shallow copy. It mutates the first object and also returns it. <del> * <del> * NOTE: `arguments` has a very significant performance penalty, which is why <del> * we don't support unlimited arguments. <del> */ <del>function copyProperties(obj, a, b, c, d, e, f) { <del> obj = obj || {}; <del> <del> if (__DEV__) { <del> if (f) { <del> throw new Error('Too many arguments passed to copyProperties'); <del> } <del> } <del> <del> var args = [a, b, c, d, e]; <del> var ii = 0, v; <del> while (args[ii]) { <del> v = args[ii++]; <del> for (var k in v) { <del> obj[k] = v[k]; <del> } <del> <del> // IE ignores toString in object iteration.. See: <del> // webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html <del> if (v.hasOwnProperty && v.hasOwnProperty('toString') && <del> (typeof v.toString != 'undefined') && (obj.toString !== v.toString)) { <del> obj.toString = v.toString; <del> } <del> } <del> <del> return obj; <del>} <del> <del>module.exports = copyProperties; <del> <del>// deprecation notice <del>console.warn( <del> 'react/lib/copyProperties has been deprecated and will be removed in the ' + <del> 'next version of React. All uses can be replaced with ' + <del> 'Object.assign(obj, a, b, ...) or _.extend(obj, a, b, ...).' <del>); <ide><path>src/vendor_deprecated/core/merge.js <del>/** <del> * Copyright 2013-2015, Facebook, Inc. <del> * All rights reserved. <del> * <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. <del> * <del> * @providesModule merge <del> */ <del> <del>"use strict"; <del> <del>var assign = require('Object.assign'); <del> <del>/** <del> * Shallow merges two structures into a return value, without mutating either. <del> * <del> * @param {?object} one Optional object with properties to merge from. <del> * @param {?object} two Optional object with properties to merge from. <del> * @return {object} The shallow extension of one by two. <del> */ <del>var merge = function(one, two) { <del> return assign({}, one, two); <del>}; <del> <del>module.exports = merge; <del> <del>// deprecation notice <del>console.warn( <del> 'react/lib/merge has been deprecated and will be removed in the ' + <del> 'next version of React. All uses can be replaced with ' + <del> 'Object.assign({}, a, b) or _.extend({}, a, b).' <del>); <ide><path>src/vendor_deprecated/core/mergeInto.js <del>/** <del> * Copyright 2013-2015, Facebook, Inc. <del> * All rights reserved. <del> * <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. <del> * <del> * @providesModule mergeInto <del> * @typechecks static-only <del> */ <del> <del>"use strict"; <del> <del>var assign = require('Object.assign'); <del> <del>module.exports = assign; <del> <del>// deprecation notice <del>console.warn( <del> 'react/lib/mergeInto has been deprecated and will be removed in the ' + <del> 'next version of React. All uses can be replaced with ' + <del> 'Object.assign(a, b, c, ...) or _.extend(a, b, c, ...).' <del>);
6
Ruby
Ruby
improve warning when db is missing
5e9d52e7fe6ba8a0938e500c8b8ad86193287324
<ide><path>activerecord/lib/active_record/errors.rb <ide> def initialize(message = nil) <ide> class << self <ide> def db_error(db_name) <ide> NoDatabaseError.new(<<~MSG) <del> We could not find your database: #{db_name}. Which can be found in the database configuration file located at config/database.yml. <add> We could not find your database: #{db_name}. Available database configurations can be found in config/database.yml file. <ide> <del> To resolve this issue: <add> To resolve this error: <ide> <ide> - Did you create the database for this app, or delete it? You may need to create your database. <ide> - Has the database name changed? Check your database.yml config has the correct database name.
1
Python
Python
add type annotations for bert and copies
bb69d154c52b7c530bc002c7c02675f58c5620e5
<ide><path>src/transformers/models/bert/modeling_bert.py <ide> import os <ide> import warnings <ide> from dataclasses import dataclass <del>from typing import Optional, Tuple <add>from typing import List, Optional, Tuple, Union <ide> <ide> import torch <ide> import torch.utils.checkpoint <ide> class PreTrainedModel <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> encoder_hidden_states=None, <del> encoder_attention_mask=None, <del> past_key_values=None, <del> use_cache=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> encoder_hidden_states: Optional[torch.Tensor] = None, <add> encoder_attention_mask: Optional[torch.Tensor] = None, <add> past_key_values: Optional[List[torch.FloatTensor]] = None, <add> use_cache: Optional[bool] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]: <ide> r""" <ide> encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): <ide> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if <ide> def set_output_embeddings(self, new_embeddings): <ide> @replace_return_docstrings(output_type=BertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> next_sentence_label=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> next_sentence_label: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, BertForPreTrainingOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., <ide> def set_output_embeddings(self, new_embeddings): <ide> @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> encoder_hidden_states=None, <del> encoder_attention_mask=None, <del> labels=None, <del> past_key_values=None, <del> use_cache=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> encoder_hidden_states: Optional[torch.Tensor] = None, <add> encoder_attention_mask: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> past_key_values: Optional[List[torch.Tensor]] = None, <add> use_cache: Optional[bool] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]: <ide> r""" <ide> encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): <ide> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention <ide> def set_output_embeddings(self, new_embeddings): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> encoder_hidden_states=None, <del> encoder_attention_mask=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> encoder_hidden_states: Optional[torch.Tensor] = None, <add> encoder_attention_mask: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, MaskedLMOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., <ide> def __init__(self, config): <ide> @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <ide> **kwargs, <del> ): <add> ) -> Union[Tuple, NextSentencePredictorOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, SequenceClassifierOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, MultipleChoiceModelOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, TokenClassifierOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> start_positions=None, <del> end_positions=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> start_positions: Optional[torch.Tensor] = None, <add> end_positions: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, QuestionAnsweringModelOutput]: <ide> r""" <ide> start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for position (index) of the start of the labelled span for computing the token classification loss. <ide><path>src/transformers/models/data2vec/modeling_data2vec_text.py <ide> """PyTorch Data2VecText model.""" <ide> <ide> import math <add>from typing import List, Optional, Tuple, Union <ide> <ide> import torch <ide> import torch.utils.checkpoint <ide> class PreTrainedModel <ide> # Copied from transformers.models.bert.modeling_bert.BertModel.forward <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> encoder_hidden_states=None, <del> encoder_attention_mask=None, <del> past_key_values=None, <del> use_cache=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> encoder_hidden_states: Optional[torch.Tensor] = None, <add> encoder_attention_mask: Optional[torch.Tensor] = None, <add> past_key_values: Optional[List[torch.FloatTensor]] = None, <add> use_cache: Optional[bool] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]: <ide> r""" <ide> encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): <ide> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if <ide><path>src/transformers/models/mobilebert/modeling_mobilebert.py <ide> import os <ide> import warnings <ide> from dataclasses import dataclass <del>from typing import Optional, Tuple <add>from typing import Optional, Tuple, Union <ide> <ide> import torch <ide> from torch import nn <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, SequenceClassifierOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> start_positions=None, <del> end_positions=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> start_positions: Optional[torch.Tensor] = None, <add> end_positions: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, QuestionAnsweringModelOutput]: <ide> r""" <ide> start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for position (index) of the start of the labelled span for computing the token classification loss. <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, MultipleChoiceModelOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., <ide> def __init__(self, config): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> labels: Optional[torch.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, TokenClassifierOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. <ide><path>src/transformers/models/roberta/modeling_roberta.py <ide> """PyTorch RoBERTa model.""" <ide> <ide> import math <add>from typing import List, Optional, Tuple, Union <ide> <ide> import torch <ide> import torch.utils.checkpoint <ide> class PreTrainedModel <ide> # Copied from transformers.models.bert.modeling_bert.BertModel.forward <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> encoder_hidden_states=None, <del> encoder_attention_mask=None, <del> past_key_values=None, <del> use_cache=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> encoder_hidden_states: Optional[torch.Tensor] = None, <add> encoder_attention_mask: Optional[torch.Tensor] = None, <add> past_key_values: Optional[List[torch.FloatTensor]] = None, <add> use_cache: Optional[bool] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]: <ide> r""" <ide> encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): <ide> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if <ide><path>src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py <ide> """PyTorch XLM RoBERTa xl,xxl model.""" <ide> <ide> import math <add>from typing import List, Optional, Tuple, Union <ide> <ide> import torch <ide> import torch.utils.checkpoint <ide> class PreTrainedModel <ide> # Copied from transformers.models.bert.modeling_bert.BertModel.forward <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> encoder_hidden_states=None, <del> encoder_attention_mask=None, <del> past_key_values=None, <del> use_cache=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.Tensor] = None, <add> attention_mask: Optional[torch.Tensor] = None, <add> token_type_ids: Optional[torch.Tensor] = None, <add> position_ids: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> inputs_embeds: Optional[torch.Tensor] = None, <add> encoder_hidden_states: Optional[torch.Tensor] = None, <add> encoder_attention_mask: Optional[torch.Tensor] = None, <add> past_key_values: Optional[List[torch.FloatTensor]] = None, <add> use_cache: Optional[bool] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]: <ide> r""" <ide> encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): <ide> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
5
Text
Text
use serial comma in tls docs
58d8d69f12cc0646cca8ff352b0305bd1e7f2629
<ide><path>doc/api/tls.md <ide> changes: <ide> * `socket` {stream.Duplex} Establish secure connection on a given socket <ide> rather than creating a new socket. Typically, this is an instance of <ide> [`net.Socket`][], but any `Duplex` stream is allowed. <del> If this option is specified, `path`, `host` and `port` are ignored, <add> If this option is specified, `path`, `host`, and `port` are ignored, <ide> except for certificate validation. Usually, a socket is already connected <ide> when passed to `tls.connect()`, but it can be connected later. <ide> Connection/disconnection/destruction of `socket` is the user's <ide> changes: <ide> More information can be found in the [RFC 4279][]. <ide> * `ALPNProtocols`: {string\[]|Buffer\[]|TypedArray\[]|DataView\[]|Buffer| <ide> TypedArray|DataView} <del> An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a <del> single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN <add> An array of strings, `Buffer`s, `TypedArray`s, or `DataView`s, or a <add> single `Buffer`, `TypedArray`, or `DataView` containing the supported ALPN <ide> protocols. `Buffer`s should have the format `[len][name][len][name]...` <ide> e.g. `'\x08http/1.1\x08http/1.0'`, where the `len` byte is the length of the <ide> next protocol name. Passing an array is usually much simpler, e.g. <ide> changes: <ide> * `options` {Object} <ide> * `ALPNProtocols`: {string\[]|Buffer\[]|TypedArray\[]|DataView\[]|Buffer| <ide> TypedArray|DataView} <del> An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single <del> `Buffer` or `TypedArray` or `DataView` containing the supported ALPN <add> An array of strings, `Buffer`s, `TypedArray`s, or `DataView`s, or a single <add> `Buffer`, `TypedArray`, or `DataView` containing the supported ALPN <ide> protocols. `Buffer`s should have the format `[len][name][len][name]...` <ide> e.g. `0x05hello0x05world`, where the first byte is the length of the next <ide> protocol name. Passing an array is usually much simpler, e.g. <ide> changes: <ide> in TLS 1.3. Upon failing to set pskIdentityHint `'tlsClientError'` will be <ide> emitted with `'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'` code. <ide> * ...: Any [`tls.createSecureContext()`][] option can be provided. For <del> servers, the identity options (`pfx`, `key`/`cert` or `pskCallback`) <add> servers, the identity options (`pfx`, `key`/`cert`, or `pskCallback`) <ide> are usually required. <ide> * ...: Any [`net.createServer()`][] option can be provided. <ide> * `secureConnectionListener` {Function}
1
Python
Python
avoid nested dispatch in numpy.core.shape_base
8f9ec01afa2b2dee209010f6155da27af02de96d
<ide><path>numpy/core/shape_base.py <ide> def atleast_2d(*arys): <ide> if ary.ndim == 0: <ide> result = ary.reshape(1, 1) <ide> elif ary.ndim == 1: <del> result = ary[newaxis,:] <add> result = ary[newaxis, :] <ide> else: <ide> result = ary <ide> res.append(result) <ide> def atleast_3d(*arys): <ide> if ary.ndim == 0: <ide> result = ary.reshape(1, 1, 1) <ide> elif ary.ndim == 1: <del> result = ary[newaxis,:, newaxis] <add> result = ary[newaxis, :, newaxis] <ide> elif ary.ndim == 2: <del> result = ary[:,:, newaxis] <add> result = ary[:, :, newaxis] <ide> else: <ide> result = ary <ide> res.append(result) <ide> def stack(arrays, axis=0, out=None): <ide> return _nx.concatenate(expanded_arrays, axis=axis, out=out) <ide> <ide> <add># Internal functions to eliminate the overhead of repeated dispatch in one of <add># the two possible paths inside np.block. <add># Use getattr to protect against __array_function__ being disabled. <add>_size = getattr(_nx.size, '__wrapped__', _nx.size) <add>_ndim = getattr(_nx.ndim, '__wrapped__', _nx.ndim) <add>_concatenate = getattr(_nx.concatenate, '__wrapped__', _nx.concatenate) <add> <add> <ide> def _block_format_index(index): <ide> """ <ide> Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``. <ide> def _block_check_depths_match(arrays, parent_index=[]): <ide> return parent_index + [None], 0, 0 <ide> else: <ide> # We've 'bottomed out' - arrays is either a scalar or an array <del> size = _nx.size(arrays) <del> return parent_index, _nx.ndim(arrays), size <add> size = _size(arrays) <add> return parent_index, _ndim(arrays), size <ide> <ide> <ide> def _atleast_nd(a, ndim): <ide> def _block(arrays, max_depth, result_ndim, depth=0): <ide> if depth < max_depth: <ide> arrs = [_block(arr, max_depth, result_ndim, depth+1) <ide> for arr in arrays] <del> return _nx.concatenate(arrs, axis=-(max_depth-depth)) <add> return _concatenate(arrs, axis=-(max_depth-depth)) <ide> else: <ide> # We've 'bottomed out' - arrays is either a scalar or an array <ide> # type(arrays) is not list <ide> def _block_slicing(arrays, list_ndim, result_ndim): <ide> <ide> # Test preferring F only in the case that all input arrays are F <ide> F_order = all(arr.flags['F_CONTIGUOUS'] for arr in arrays) <del> C_order = all(arr.flags['C_CONTIGUOUS'] for arr in arrays) <add> C_order = all(arr.flags['C_CONTIGUOUS'] for arr in arrays) <ide> order = 'F' if F_order and not C_order else 'C' <ide> result = _nx.empty(shape=shape, dtype=dtype, order=order) <ide> # Note: In a c implementation, the function
1
Javascript
Javascript
convert `appmodule()` to `setupapptest()` helper
c6202fcd7cd006bef785c626ae4abdc2699e26d1
<ide><path>tests/node/app-boot-test.js <del>var appModule = require('./helpers/app-module'); <add>const setupAppTest = require('./helpers/setup-app'); <ide> <ide> require('./helpers/assert-html-matches').register(); <ide> <del>appModule('App Boot'); <add>QUnit.module('App Boot', function(hooks) { <add> setupAppTest(hooks); <ide> <del>QUnit.test('App boots and routes to a URL', function(assert) { <del> this.visit('/'); <del> assert.ok(this.app); <del>}); <del> <del>QUnit.test('nested {{component}}', function(assert) { <del> this.template('index', '{{root-component}}'); <del> <del> this.template( <del> 'components/root-component', <del> "\ <del> <h1>Hello {{#if hasExistence}}{{location}}{{/if}}</h1>\ <del> <div>{{component 'foo-bar'}}</div>\ <del>" <del> ); <del> <del> this.component('root-component', { <del> location: 'World', <del> hasExistence: true, <add> QUnit.test('App boots and routes to a URL', function(assert) { <add> this.visit('/'); <add> assert.ok(this.app); <ide> }); <ide> <del> this.template('components/foo-bar', '\ <del> <p>The files are *inside* the computer?!</p>\ <del>'); <add> QUnit.test('nested {{component}}', function(assert) { <add> this.template('index', '{{root-component}}'); <ide> <del> return this.renderToHTML('/').then(function(html) { <del> assert.htmlMatches( <del> html, <del> '<body><div id="EMBER_ID" class="ember-view"><div id="EMBER_ID" class="ember-view"><h1>Hello World</h1><div><div id="EMBER_ID" class="ember-view"><p>The files are *inside* the computer?!</p></div></div></div></div></body>' <add> this.template( <add> 'components/root-component', <add> "\ <add> <h1>Hello {{#if hasExistence}}{{location}}{{/if}}</h1>\ <add> <div>{{component 'foo-bar'}}</div>\ <add> " <ide> ); <del> }); <del>}); <ide> <del>QUnit.test('{{link-to}}', function(assert) { <del> this.template('application', "<h1>{{#link-to 'photos'}}Go to photos{{/link-to}}</h1>"); <del> this.routes(function() { <del> this.route('photos'); <del> }); <add> this.component('root-component', { <add> location: 'World', <add> hasExistence: true, <add> }); <ide> <del> return this.renderToHTML('/').then(function(html) { <del> assert.htmlMatches( <del> html, <del> '<body><div id="EMBER_ID" class="ember-view"><h1><a id="EMBER_ID" href="/photos" class="ember-view">Go to photos</a></h1></div></body>' <del> ); <del> }); <del>}); <add> this.template('components/foo-bar', '\ <add> <p>The files are *inside* the computer?!</p>\ <add> '); <ide> <del>QUnit.test('non-escaped content', function(assert) { <del> this.routes(function() { <del> this.route('photos'); <add> return this.renderToHTML('/').then(function(html) { <add> assert.htmlMatches( <add> html, <add> '<body><div id="EMBER_ID" class="ember-view"><div id="EMBER_ID" class="ember-view"><h1>Hello World</h1><div><div id="EMBER_ID" class="ember-view"><p>The files are *inside* the computer?!</p></div></div></div></div></body>' <add> ); <add> }); <ide> }); <ide> <del> this.template('application', '<h1>{{{title}}}</h1>'); <del> this.controller('application', { <del> title: '<b>Hello world</b>', <del> }); <add> QUnit.test('{{link-to}}', function(assert) { <add> this.template('application', "<h1>{{#link-to 'photos'}}Go to photos{{/link-to}}</h1>"); <add> this.routes(function() { <add> this.route('photos'); <add> }); <ide> <del> return this.renderToHTML('/').then(function(html) { <del> assert.htmlMatches( <del> html, <del> '<body><div id="EMBER_ID" class="ember-view"><h1><b>Hello world</b></h1></div></body>' <del> ); <add> return this.renderToHTML('/').then(function(html) { <add> assert.htmlMatches( <add> html, <add> '<body><div id="EMBER_ID" class="ember-view"><h1><a id="EMBER_ID" href="/photos" class="ember-view">Go to photos</a></h1></div></body>' <add> ); <add> }); <ide> }); <del>}); <ide> <del>QUnit.test('outlets', function(assert) { <del> this.routes(function() { <del> this.route('photos'); <del> }); <add> QUnit.test('non-escaped content', function(assert) { <add> this.routes(function() { <add> this.route('photos'); <add> }); <ide> <del> this.template('application', '<p>{{outlet}}</p>'); <del> this.template('index', '<span>index</span>'); <del> this.template('photos', '<em>photos</em>'); <add> this.template('application', '<h1>{{{title}}}</h1>'); <add> this.controller('application', { <add> title: '<b>Hello world</b>', <add> }); <ide> <del> var promises = []; <del> promises.push( <del> this.renderToHTML('/').then(function(html) { <add> return this.renderToHTML('/').then(function(html) { <ide> assert.htmlMatches( <ide> html, <del> '<body><div id="EMBER_ID" class="ember-view"><p><span>index</span></p></div></body>' <add> '<body><div id="EMBER_ID" class="ember-view"><h1><b>Hello world</b></h1></div></body>' <ide> ); <del> }) <del> ); <add> }); <add> }); <ide> <del> promises.push( <del> this.renderToHTML('/photos').then(function(html) { <del> assert.htmlMatches( <del> html, <del> '<body><div id="EMBER_ID" class="ember-view"><p><em>photos</em></p></div></body>' <del> ); <del> }) <del> ); <add> QUnit.test('outlets', function(assert) { <add> this.routes(function() { <add> this.route('photos'); <add> }); <add> <add> this.template('application', '<p>{{outlet}}</p>'); <add> this.template('index', '<span>index</span>'); <add> this.template('photos', '<em>photos</em>'); <add> <add> var promises = []; <add> promises.push( <add> this.renderToHTML('/').then(function(html) { <add> assert.htmlMatches( <add> html, <add> '<body><div id="EMBER_ID" class="ember-view"><p><span>index</span></p></div></body>' <add> ); <add> }) <add> ); <ide> <del> return this.all(promises); <del>}); <add> promises.push( <add> this.renderToHTML('/photos').then(function(html) { <add> assert.htmlMatches( <add> html, <add> '<body><div id="EMBER_ID" class="ember-view"><p><em>photos</em></p></div></body>' <add> ); <add> }) <add> ); <ide> <del>QUnit.test('lifecycle hooks disabled', function(assert) { <del> assert.expect(1); <del> <del> this.template('application', "{{my-component foo='bar'}}{{outlet}}"); <del> <del> this.component('my-component', { <del> didReceiveAttrs() { <del> assert.ok(true, 'should trigger didReceiveAttrs hook'); <del> }, <del> willRender() { <del> assert.ok(false, 'should not trigger willRender hook'); <del> }, <del> didRender() { <del> assert.ok(false, 'should not trigger didRender hook'); <del> }, <del> willInsertElement() { <del> assert.ok(false, 'should not trigger willInsertElement hook'); <del> }, <del> didInsertElement() { <del> assert.ok(false, 'should not trigger didInsertElement hook'); <del> }, <add> return this.all(promises); <ide> }); <ide> <del> return this.renderToHTML('/'); <del>}); <add> QUnit.test('lifecycle hooks disabled', function(assert) { <add> assert.expect(1); <add> <add> this.template('application', "{{my-component foo='bar'}}{{outlet}}"); <add> <add> this.component('my-component', { <add> didReceiveAttrs() { <add> assert.ok(true, 'should trigger didReceiveAttrs hook'); <add> }, <add> willRender() { <add> assert.ok(false, 'should not trigger willRender hook'); <add> }, <add> didRender() { <add> assert.ok(false, 'should not trigger didRender hook'); <add> }, <add> willInsertElement() { <add> assert.ok(false, 'should not trigger willInsertElement hook'); <add> }, <add> didInsertElement() { <add> assert.ok(false, 'should not trigger didInsertElement hook'); <add> }, <add> }); <add> <add> return this.renderToHTML('/'); <add> }); <ide> <del>QUnit.test('Should not attempt to render element modifiers GH#14220', function(assert) { <del> assert.expect(1); <add> QUnit.test('Should not attempt to render element modifiers GH#14220', function(assert) { <add> assert.expect(1); <ide> <del> this.template('application', "<div {{action 'foo'}}></div>"); <add> this.template('application', "<div {{action 'foo'}}></div>"); <ide> <del> return this.renderToHTML('/').then(function(html) { <del> assert.htmlMatches( <del> html, <del> '<body><div id="EMBER_ID" class="ember-view"><div></div></div></body>' <del> ); <add> return this.renderToHTML('/').then(function(html) { <add> assert.htmlMatches( <add> html, <add> '<body><div id="EMBER_ID" class="ember-view"><div></div></div></body>' <add> ); <add> }); <ide> }); <ide> }); <add><path>tests/node/helpers/setup-app.js <del><path>tests/node/helpers/app-module.js <ide> var SimpleDOM = require('simple-dom'); <ide> * }); <ide> */ <ide> <del>module.exports = function(moduleName) { <del> QUnit.module(moduleName, { <del> beforeEach: function() { <del> var Ember = (this.Ember = require(emberPath)); <del> <del> Ember.testing = true; <del> <del> var precompile = require(templateCompilerPath).precompile; <del> this.compile = function(templateString, options) { <del> var templateSpec = precompile(templateString, options); <del> var template = new Function('return ' + templateSpec)(); <del> <del> return Ember.HTMLBars.template(template); <del> }; <del> <del> this.run = Ember.run; <del> this.all = Ember.RSVP.all; <del> <del> this.visit = visit; <del> this.createApplication = createApplication; <del> this.register = register; <del> this.template = registerTemplate; <del> this.component = registerComponent; <del> this.controller = registerController; <del> this.route = registerRoute; <del> this.service = registerService; <del> this.routes = registerRoutes; <del> this.registry = {}; <del> this.renderToHTML = renderToHTML; <del> }, <add>module.exports = function(hooks) { <add> hooks.beforeEach(function() { <add> var Ember = (this.Ember = require(emberPath)); <add> <add> Ember.testing = true; <add> <add> var precompile = require(templateCompilerPath).precompile; <add> this.compile = function(templateString, options) { <add> var templateSpec = precompile(templateString, options); <add> var template = new Function('return ' + templateSpec)(); <add> <add> return Ember.HTMLBars.template(template); <add> }; <add> <add> this.run = Ember.run; <add> this.all = Ember.RSVP.all; <add> <add> this.visit = visit; <add> this.createApplication = createApplication; <add> this.register = register; <add> this.template = registerTemplate; <add> this.component = registerComponent; <add> this.controller = registerController; <add> this.route = registerRoute; <add> this.service = registerService; <add> this.routes = registerRoutes; <add> this.registry = {}; <add> this.renderToHTML = renderToHTML; <add> }); <ide> <del> afterEach: function() { <del> this.run(this.app, 'destroy'); <add> hooks.afterEach(function() { <add> this.run(this.app, 'destroy'); <ide> <del> delete global.Ember; <add> delete global.Ember; <ide> <del> // clear the previously cached version of this module <del> delete require.cache[emberPath + '.js']; <del> delete require.cache[templateCompilerPath + '.js']; <del> }, <add> // clear the previously cached version of this module <add> delete require.cache[emberPath + '.js']; <add> delete require.cache[templateCompilerPath + '.js']; <ide> }); <ide> }; <ide> <ide><path>tests/node/visit-test.js <ide> var SimpleDOM = require('simple-dom'); <del>var appModule = require('./helpers/app-module'); <add>var setupAppTest = require('./helpers/setup-app'); <ide> <ide> function assertHTMLMatches(assert, actualHTML, expectedHTML) { <ide> assert.ok(actualHTML.match(expectedHTML), actualHTML + ' matches ' + expectedHTML); <ide> function assertFastbootResult(assert, expected) { <ide> }; <ide> } <ide> <del>appModule('Ember.Application - visit() Integration Tests'); <add>QUnit.module('Ember.Application - visit() Integration Tests', function(hooks) { <add> setupAppTest(hooks); <ide> <del>QUnit.test('FastBoot: basic', function(assert) { <del> this.routes(function() { <del> this.route('a'); <del> this.route('b'); <del> }); <add> QUnit.test('FastBoot: basic', function(assert) { <add> this.routes(function() { <add> this.route('a'); <add> this.route('b'); <add> }); <ide> <del> this.template('application', '<h1>Hello world</h1>\n{{outlet}}'); <del> this.template('a', '<h2>Welcome to {{x-foo page="A"}}</h2>'); <del> this.template('b', '<h2>{{x-foo page="B"}}</h2>'); <del> this.template('components/x-foo', 'Page {{page}}'); <del> <del> var initCalled = false; <del> var didInsertElementCalled = false; <del> <del> this.component('x-foo', { <del> tagName: 'span', <del> init: function() { <del> this._super(); <del> initCalled = true; <del> }, <del> didInsertElement: function() { <del> didInsertElementCalled = true; <del> }, <del> }); <add> this.template('application', '<h1>Hello world</h1>\n{{outlet}}'); <add> this.template('a', '<h2>Welcome to {{x-foo page="A"}}</h2>'); <add> this.template('b', '<h2>{{x-foo page="B"}}</h2>'); <add> this.template('components/x-foo', 'Page {{page}}'); <ide> <del> var App = this.createApplication(); <del> <del> return Promise.all([ <del> fastbootVisit(App, '/a').then( <del> assertFastbootResult(assert, { <del> url: '/a', <del> body: <del> '<h1>Hello world</h1>\n<h2>Welcome to <span id=".+" class="ember-view">Page A</span></h2>', <del> }), <del> handleError(assert) <del> ), <del> fastbootVisit(App, '/b').then( <del> assertFastbootResult(assert, { <del> url: '/b', <del> body: '<h1>Hello world</h1>\n<h2><span id=".+" class="ember-view">Page B</span></h2>', <del> }), <del> handleError <del> ), <del> ]).then(function() { <del> assert.ok(initCalled, 'Component#init should be called'); <del> assert.ok(!didInsertElementCalled, 'Component#didInsertElement should not be called'); <del> }); <del>}); <add> var initCalled = false; <add> var didInsertElementCalled = false; <ide> <del>QUnit.test('FastBoot: redirect', function(assert) { <del> this.routes(function() { <del> this.route('a'); <del> this.route('b'); <del> this.route('c'); <add> this.component('x-foo', { <add> tagName: 'span', <add> init: function() { <add> this._super(); <add> initCalled = true; <add> }, <add> didInsertElement: function() { <add> didInsertElementCalled = true; <add> }, <add> }); <add> <add> var App = this.createApplication(); <add> <add> return Promise.all([ <add> fastbootVisit(App, '/a').then( <add> assertFastbootResult(assert, { <add> url: '/a', <add> body: <add> '<h1>Hello world</h1>\n<h2>Welcome to <span id=".+" class="ember-view">Page A</span></h2>', <add> }), <add> handleError(assert) <add> ), <add> fastbootVisit(App, '/b').then( <add> assertFastbootResult(assert, { <add> url: '/b', <add> body: '<h1>Hello world</h1>\n<h2><span id=".+" class="ember-view">Page B</span></h2>', <add> }), <add> handleError <add> ), <add> ]).then(function() { <add> assert.ok(initCalled, 'Component#init should be called'); <add> assert.ok(!didInsertElementCalled, 'Component#didInsertElement should not be called'); <add> }); <ide> }); <ide> <del> this.template('a', '<h1>Hello from A</h1>'); <del> this.template('b', '<h1>Hello from B</h1>'); <del> this.template('c', '<h1>Hello from C</h1>'); <add> QUnit.test('FastBoot: redirect', function(assert) { <add> this.routes(function() { <add> this.route('a'); <add> this.route('b'); <add> this.route('c'); <add> }); <ide> <del> this.route('a', { <del> beforeModel: function() { <del> this.replaceWith('b'); <del> }, <del> }); <add> this.template('a', '<h1>Hello from A</h1>'); <add> this.template('b', '<h1>Hello from B</h1>'); <add> this.template('c', '<h1>Hello from C</h1>'); <add> <add> this.route('a', { <add> beforeModel: function() { <add> this.replaceWith('b'); <add> }, <add> }); <ide> <del> this.route('b', { <del> afterModel: function() { <del> this.transitionTo('c'); <del> }, <add> this.route('b', { <add> afterModel: function() { <add> this.transitionTo('c'); <add> }, <add> }); <add> <add> var App = this.createApplication(); <add> <add> return Promise.all([ <add> fastbootVisit(App, '/a').then( <add> assertFastbootResult(assert, { <add> url: '/c', <add> body: '<h1>Hello from C</h1>', <add> }), <add> handleError(assert) <add> ), <add> fastbootVisit(App, '/b').then( <add> assertFastbootResult(assert, { <add> url: '/c', <add> body: '<h1>Hello from C</h1>', <add> }), <add> handleError(assert) <add> ), <add> ]); <ide> }); <ide> <del> var App = this.createApplication(); <del> <del> return Promise.all([ <del> fastbootVisit(App, '/a').then( <del> assertFastbootResult(assert, { <del> url: '/c', <del> body: '<h1>Hello from C</h1>', <del> }), <del> handleError(assert) <del> ), <del> fastbootVisit(App, '/b').then( <del> assertFastbootResult(assert, { <del> url: '/c', <del> body: '<h1>Hello from C</h1>', <del> }), <del> handleError(assert) <del> ), <del> ]); <del>}); <add> QUnit.test('FastBoot: attributes are sanitized', function(assert) { <add> this.template('application', '<a href={{test}}></a>'); <ide> <del>QUnit.test('FastBoot: attributes are sanitized', function(assert) { <del> this.template('application', '<a href={{test}}></a>'); <add> this.controller('application', { <add> test: 'javascript:alert("hello")', <add> }); <ide> <del> this.controller('application', { <del> test: 'javascript:alert("hello")', <add> var App = this.createApplication(); <add> <add> return Promise.all([ <add> fastbootVisit(App, '/').then( <add> assertFastbootResult(assert, { <add> url: '/', <add> body: '<a href="unsafe:javascript:alert\\(&quot;hello&quot;\\)"></a>', <add> }), <add> handleError(assert) <add> ), <add> ]); <ide> }); <ide> <del> var App = this.createApplication(); <del> <del> return Promise.all([ <del> fastbootVisit(App, '/').then( <del> assertFastbootResult(assert, { <del> url: '/', <del> body: '<a href="unsafe:javascript:alert\\(&quot;hello&quot;\\)"></a>', <del> }), <del> handleError(assert) <del> ), <del> ]); <del>}); <add> QUnit.test('FastBoot: route error', function(assert) { <add> this.routes(function() { <add> this.route('a'); <add> this.route('b'); <add> }); <ide> <del>QUnit.test('FastBoot: route error', function(assert) { <del> this.routes(function() { <del> this.route('a'); <del> this.route('b'); <del> }); <add> this.template('a', '<h1>Hello from A</h1>'); <add> this.template('b', '<h1>Hello from B</h1>'); <ide> <del> this.template('a', '<h1>Hello from A</h1>'); <del> this.template('b', '<h1>Hello from B</h1>'); <add> this.route('a', { <add> beforeModel: function() { <add> throw new Error('Error from A'); <add> }, <add> }); <ide> <del> this.route('a', { <del> beforeModel: function() { <del> throw new Error('Error from A'); <del> }, <add> this.route('b', { <add> afterModel: function() { <add> throw new Error('Error from B'); <add> }, <add> }); <add> <add> var App = this.createApplication(); <add> <add> return Promise.all([ <add> fastbootVisit(App, '/a').then( <add> function(instance) { <add> assert.ok(false, 'It should not render'); <add> instance.destroy(); <add> }, <add> function(error) { <add> assert.equal(error.message, 'Error from A'); <add> } <add> ), <add> fastbootVisit(App, '/b').then( <add> function(instance) { <add> assert.ok(false, 'It should not render'); <add> instance.destroy(); <add> }, <add> function(error) { <add> assert.equal(error.message, 'Error from B'); <add> } <add> ), <add> ]); <ide> }); <ide> <del> this.route('b', { <del> afterModel: function() { <del> throw new Error('Error from B'); <del> }, <del> }); <add> QUnit.test('FastBoot: route error template', function(assert) { <add> this.routes(function() { <add> this.route('a'); <add> }); <ide> <del> var App = this.createApplication(); <add> this.template('error', '<p>Error template rendered!</p>'); <add> this.template('a', '<h1>Hello from A</h1>'); <ide> <del> return Promise.all([ <del> fastbootVisit(App, '/a').then( <del> function(instance) { <del> assert.ok(false, 'It should not render'); <del> instance.destroy(); <add> this.route('a', { <add> model: function() { <add> throw new Error('Error from A'); <ide> }, <del> function(error) { <del> assert.equal(error.message, 'Error from A'); <del> } <del> ), <del> fastbootVisit(App, '/b').then( <del> function(instance) { <del> assert.ok(false, 'It should not render'); <del> instance.destroy(); <del> }, <del> function(error) { <del> assert.equal(error.message, 'Error from B'); <del> } <del> ), <del> ]); <del>}); <del> <del>QUnit.test('FastBoot: route error template', function(assert) { <del> this.routes(function() { <del> this.route('a'); <add> }); <add> <add> var App = this.createApplication(); <add> <add> return Promise.all([ <add> fastbootVisit(App, '/a').then( <add> assertFastbootResult(assert, { <add> url: '/a', <add> body: '<p>Error template rendered!</p>', <add> }), <add> handleError(assert) <add> ), <add> ]); <ide> }); <ide> <del> this.template('error', '<p>Error template rendered!</p>'); <del> this.template('a', '<h1>Hello from A</h1>'); <add> QUnit.test('Resource-discovery setup', function(assert) { <add> this.service('network', { <add> init: function() { <add> this.set('requests', []); <add> }, <ide> <del> this.route('a', { <del> model: function() { <del> throw new Error('Error from A'); <del> }, <del> }); <add> fetch: function(url) { <add> this.get('requests').push(url); <add> return Promise.resolve(); <add> }, <add> }); <add> <add> this.routes(function() { <add> this.route('a'); <add> this.route('b'); <add> this.route('c'); <add> this.route('d'); <add> this.route('e'); <add> }); <add> <add> this.route('a', { <add> model: function() { <add> return this.network.fetch('/a'); <add> }, <add> afterModel: function() { <add> this.replaceWith('b'); <add> }, <add> }); <ide> <del> var App = this.createApplication(); <del> <del> return Promise.all([ <del> fastbootVisit(App, '/a').then( <del> assertFastbootResult(assert, { <del> url: '/a', <del> body: '<p>Error template rendered!</p>', <del> }), <del> handleError(assert) <del> ), <del> ]); <del>}); <add> this.route('b', { <add> model: function() { <add> return this.network.fetch('/b'); <add> }, <add> afterModel: function() { <add> this.replaceWith('c'); <add> }, <add> }); <ide> <del>QUnit.test('Resource-discovery setup', function(assert) { <del> this.service('network', { <del> init: function() { <del> this.set('requests', []); <del> }, <add> this.route('c', { <add> model: function() { <add> return this.network.fetch('/c'); <add> }, <add> }); <ide> <del> fetch: function(url) { <del> this.get('requests').push(url); <del> return Promise.resolve(); <del> }, <del> }); <add> this.route('d', { <add> model: function() { <add> return this.network.fetch('/d'); <add> }, <add> afterModel: function() { <add> this.replaceWith('e'); <add> }, <add> }); <ide> <del> this.routes(function() { <del> this.route('a'); <del> this.route('b'); <del> this.route('c'); <del> this.route('d'); <del> this.route('e'); <del> }); <add> this.route('e', { <add> model: function() { <add> return this.network.fetch('/e'); <add> }, <add> }); <ide> <del> this.route('a', { <del> model: function() { <del> return this.network.fetch('/a'); <del> }, <del> afterModel: function() { <del> this.replaceWith('b'); <del> }, <del> }); <add> this.template('a', '{{x-foo}}'); <add> this.template('b', '{{x-foo}}'); <add> this.template('c', '{{x-foo}}'); <add> this.template('d', '{{x-foo}}'); <add> this.template('e', '{{x-foo}}'); <ide> <del> this.route('b', { <del> model: function() { <del> return this.network.fetch('/b'); <del> }, <del> afterModel: function() { <del> this.replaceWith('c'); <del> }, <del> }); <add> var xFooInstances = 0; <ide> <del> this.route('c', { <del> model: function() { <del> return this.network.fetch('/c'); <del> }, <del> }); <add> this.component('x-foo', { <add> init: function() { <add> this._super(); <add> xFooInstances++; <add> }, <add> }); <ide> <del> this.route('d', { <del> model: function() { <del> return this.network.fetch('/d'); <del> }, <del> afterModel: function() { <del> this.replaceWith('e'); <del> }, <del> }); <add> var App = this.createApplication(); <ide> <del> this.route('e', { <del> model: function() { <del> return this.network.fetch('/e'); <del> }, <del> }); <add> App.inject('route', 'network', 'service:network'); <ide> <del> this.template('a', '{{x-foo}}'); <del> this.template('b', '{{x-foo}}'); <del> this.template('c', '{{x-foo}}'); <del> this.template('d', '{{x-foo}}'); <del> this.template('e', '{{x-foo}}'); <add> function assertResources(url, resources) { <add> return App.visit(url, { isBrowser: false, shouldRender: false }).then(function(instance) { <add> try { <add> var viewRegistry = instance.lookup('-view-registry:main'); <add> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views'); <ide> <del> var xFooInstances = 0; <add> var networkService = instance.lookup('service:network'); <add> assert.deepEqual(networkService.get('requests'), resources); <add> } finally { <add> instance.destroy(); <add> } <add> }, handleError(assert)); <add> } <ide> <del> this.component('x-foo', { <del> init: function() { <del> this._super(); <del> xFooInstances++; <del> }, <add> return Promise.all([ <add> assertResources('/a', ['/a', '/b', '/c']), <add> assertResources('/b', ['/b', '/c']), <add> assertResources('/c', ['/c']), <add> assertResources('/d', ['/d', '/e']), <add> assertResources('/e', ['/e']), <add> ]).then(function() { <add> assert.strictEqual(xFooInstances, 0, 'it should not create any x-foo components'); <add> }); <ide> }); <ide> <del> var App = this.createApplication(); <del> <del> App.inject('route', 'network', 'service:network'); <del> <del> function assertResources(url, resources) { <del> return App.visit(url, { isBrowser: false, shouldRender: false }).then(function(instance) { <del> try { <del> var viewRegistry = instance.lookup('-view-registry:main'); <del> assert.strictEqual(Object.keys(viewRegistry).length, 0, 'did not create any views'); <del> <del> var networkService = instance.lookup('service:network'); <del> assert.deepEqual(networkService.get('requests'), resources); <del> } finally { <del> instance.destroy(); <del> } <del> }, handleError(assert)); <del> } <del> <del> return Promise.all([ <del> assertResources('/a', ['/a', '/b', '/c']), <del> assertResources('/b', ['/b', '/c']), <del> assertResources('/c', ['/c']), <del> assertResources('/d', ['/d', '/e']), <del> assertResources('/e', ['/e']), <del> ]).then(function() { <del> assert.strictEqual(xFooInstances, 0, 'it should not create any x-foo components'); <add> QUnit.test('FastBoot: tagless components can render', function(assert) { <add> this.template('application', "<div class='my-context'>{{my-component}}</div>"); <add> this.component('my-component', { tagName: '' }); <add> this.template('components/my-component', '<h1>hello world</h1>'); <add> <add> var App = this.createApplication(); <add> <add> return Promise.all([ <add> fastbootVisit(App, '/').then( <add> assertFastbootResult(assert, { <add> url: '/', <add> body: /<div class="my-context"><h1>hello world<\/h1><\/div>/, <add> }), <add> handleError(assert) <add> ), <add> ]); <ide> }); <ide> }); <del> <del>QUnit.test('FastBoot: tagless components can render', function(assert) { <del> this.template('application', "<div class='my-context'>{{my-component}}</div>"); <del> this.component('my-component', { tagName: '' }); <del> this.template('components/my-component', '<h1>hello world</h1>'); <del> <del> var App = this.createApplication(); <del> <del> return Promise.all([ <del> fastbootVisit(App, '/').then( <del> assertFastbootResult(assert, { <del> url: '/', <del> body: /<div class="my-context"><h1>hello world<\/h1><\/div>/, <del> }), <del> handleError(assert) <del> ), <del> ]); <del>});
3
Text
Text
add postmark to the ingress lists [ci skip]
9edc84cdfa8908a436901d85309cadf65d457d8f
<ide><path>actionmailbox/README.md <ide> # Action Mailbox <ide> <del>Action Mailbox routes incoming emails to controller-like mailboxes for processing in Rails. It ships with ingresses for Amazon SES, Mailgun, Mandrill, and SendGrid. You can also handle inbound mails directly via the built-in Postfix ingress. <add>Action Mailbox routes incoming emails to controller-like mailboxes for processing in Rails. It ships with ingresses for Amazon SES, Mailgun, Mandrill, Postmark, and SendGrid. You can also handle inbound mails directly via the built-in Postfix ingress. <ide> <ide> The inbound emails are turned into `InboundEmail` records using Active Record and feature lifecycle tracking, storage of the original email on cloud storage via Active Storage, and responsible data handling with on-by-default incineration. <ide> <ide><path>guides/source/action_mailbox_basics.md <ide> Introduction <ide> <ide> Action Mailbox routes incoming emails to controller-like mailboxes for <ide> processing in Rails. It ships with ingresses for Amazon SES, Mailgun, Mandrill, <del>and SendGrid. You can also handle inbound mails directly via the built-in <del>Postfix ingress. <add>Postmark, and SendGrid. You can also handle inbound mails directly via the <add>built-in Postfix ingress. <ide> <ide> The inbound emails are turned into `InboundEmail` records using Active Record <ide> and feature lifecycle tracking, storage of the original email on cloud storage
2
PHP
PHP
fix cs errors
0e6bd00b66c3dd81baac598f44f6b0d97d326c1f
<ide><path>src/Mailer/Message.php <ide> protected function createBoundary(): void <ide> /** <ide> * Generate full message. <ide> * <del> * @return void <add> * @return array <ide> */ <ide> protected function generateMessage() <ide> { <ide><path>src/Mailer/Renderer.php <ide> */ <ide> namespace Cake\Mailer; <ide> <del>use Cake\Core\Configure; <del>use Cake\Http\Client\FormDataPart; <del>use Cake\Utility\Hash; <del>use Cake\Utility\Security; <del>use Cake\Utility\Text; <ide> use Cake\View\ViewVarsTrait; <ide> <ide> /** <ide> class Renderer <ide> * of the text content types for the email. <ide> * <ide> * @param string|null $content The content. <add> * @param array $types Content types to render. <ide> * @return array The rendered content with "html" and/or "text" keys. <ide> */ <ide> public function getContent(?string $content = null, array $types = []): array
2
PHP
PHP
fix bug in fluent class
6f49fc29697fa1a33320bfbc465e71a685a41190
<ide><path>src/Illuminate/Support/Fluent.php <ide> public function __construct($attributes = array()) <ide> { <ide> foreach ($attributes as $key => $value) <ide> { <del> $this->$key = $value; <add> $this->attributes[$key] = $value; <ide> } <ide> } <ide>
1
PHP
PHP
fix some phpdoc inconsistencies
b05f46a0500349dadda6886178c043d3b72fc392
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> protected function invalidOperatorAndValue($operator, $value) <ide> /** <ide> * Add an "or where" clause to the query. <ide> * <del> * @param string|\Closure $column <add> * @param \Closure|string $column <ide> * @param string $operator <ide> * @param mixed $value <ide> * @return \Illuminate\Database\Query\Builder|static <ide><path>src/Illuminate/View/Factory.php <ide> public function doneRendering() <ide> /** <ide> * Add new loop to the stack. <ide> * <del> * @param array|\Countable $data <add> * @param \Countable|array $data <ide> * @return void <ide> */ <ide> public function addLoop($data)
2
Python
Python
fix test_ccompiler_opt when path contains dots
6f2f26e08c6e0d476593c82ad31d13847f30cbf4
<ide><path>numpy/distutils/tests/test_ccompiler_opt.py <ide> def get_targets(self, targets, groups, **kwargs): <ide> gflags = {} <ide> fake_objects = opt.try_dispatch([file]) <ide> for source, flags in fake_objects: <del> gtar = source.split('.')[1:-1] <add> gtar = path.basename(source).split('.')[1:-1] <ide> glen = len(gtar) <ide> if glen == 0: <ide> gtar = "baseline"
1
Python
Python
fix .descr of aligned structures
3cf31df5d76acf7ff31c23d6a387824fce68e9df
<ide><path>numpy/core/_internal.py <ide> def _array_descr(descriptor): <ide> offset = 0 <ide> for field in ordered_fields: <ide> if field[1] > offset: <del> result.append(('','|V%d' % (field[1]-offset))) <add> num = field[1] - offset <add> result.append(('','|V%d' % num)) <add> offset += num <ide> if len(field) > 3: <ide> name = (field[2],field[3]) <ide> else:
1
Javascript
Javascript
add localetitle to the challenge schema
65094d13e4f040c042baa1076df388ca4cfbf396
<ide><path>curriculum/schema/challengeSchema.js <ide> const Joi = require('joi'); <ide> Joi.objectId = require('joi-objectid')(Joi); <add>const path = require('path'); <add>require('dotenv').config({ path: path.resolve(__dirname, '../../.env') }); <ide> <del>const schema = Joi.object().keys({ <add>const { LOCALE: lang = 'english' } = process.env; <add> <add>let schema = Joi.object().keys({ <ide> block: Joi.string(), <ide> blockId: Joi.objectId(), <ide> challengeOrder: Joi.number(), <ide> const schema = Joi.object().keys({ <ide> title: Joi.string().required() <ide> }); <ide> <add>if (lang !== 'english') { <add> schema = schema.append({ <add> localeTitle: Joi.string().required() <add> }); <add>} <add> <ide> exports.validateChallenge = function validateChallenge(challenge) { <ide> return Joi.validate(challenge, schema); <ide> };
1
Javascript
Javascript
make test work on all platforms
cd907e6a5f978333a763338a6801495efd38a5b0
<ide><path>test/binCases/config-name/not-found/test.js <ide> "use strict"; <ide> <ide> module.exports = function testAssertions(code, stdout, stderr) { <del> code.should.be.exactly(255); <del> <add> code.should.not.eql(0); <ide> stdout.should.be.empty(); <ide> stderr[0].should.containEql("Configuration with name \'foo\' was not found."); <ide> };
1
Python
Python
remove code duplication
59fc36e334c845d5079d5db69afbb07a4e0e310b
<ide><path>glances/plugins/glances_processlist.py <ide> def msg_curse(self, args=None): <ide> return ret <ide> <ide> # Compute the sort key <del> if glances_processes.getmanualsortkey() is None: <del> process_sort_key = glances_processes.getautosortkey() <del> else: <del> process_sort_key = glances_processes.getmanualsortkey() <add> process_sort_key = glances_processes.getsortkey() <ide> sort_style = 'SORT' <ide> <ide> # Header
1
Javascript
Javascript
adapt tests to new expando name
ee8fae8c0f1680428b0eb84d1306b55bebf44074
<ide><path>test/AngularSpec.js <ide> describe('angular', function() { <ide> expect(function () { <ide> angular.bootstrap(element); <ide> }).toThrowMatching( <del> /\[ng:btstrpd\] App Already Bootstrapped with this Element '<div class="?ng\-scope"?( ng\-[0-9]+="?[0-9]+"?)?>'/i <add> /\[ng:btstrpd\] App Already Bootstrapped with this Element '<div class="?ng\-scope"?( ng[0-9]+="?[0-9]+"?)?>'/i <ide> ); <ide> <ide> dealoc(element); <ide><path>test/helpers/testabilityPatch.js <ide> function sortedHtml(element, showNgClass) { <ide> attr.name !='style' && <ide> attr.name.substr(0, 6) != 'jQuery') { <ide> // in IE we need to check for all of these. <del> if (/ng-\d+/.exec(attr.name) || <add> if (/ng\d+/.exec(attr.name) || <ide> attr.name == 'getElementById' || <ide> // IE7 has `selected` in attributes <ide> attr.name == 'selected' ||
2
Python
Python
delay the creation of ssh proxy until get_conn()
129b4d2ac2ce09d42fb487f8a9aaac7eb7901a05
<ide><path>airflow/providers/ssh/hooks/ssh.py <ide> # under the License. <ide> """Hook for SSH connections.""" <ide> import os <add>import sys <ide> import warnings <ide> from base64 import decodebytes <ide> from io import StringIO <ide> from paramiko.config import SSH_PORT <ide> from sshtunnel import SSHTunnelForwarder <ide> <add>if sys.version_info >= (3, 8): <add> from functools import cached_property <add>else: <add> from cached_property import cached_property <add> <ide> from airflow.exceptions import AirflowException <ide> from airflow.hooks.base import BaseHook <ide> <ide> def __init__( <ide> self.timeout = timeout <ide> self.conn_timeout = conn_timeout <ide> self.keepalive_interval = keepalive_interval <add> self.host_proxy_cmd = None <ide> <ide> # Default values, overridable from Connection <ide> self.compress = True <ide> self.no_host_key_check = True <ide> self.allow_host_key_change = False <del> self.host_proxy = None <ide> self.host_key = None <ide> self.look_for_keys = True <ide> <ide> def __init__( <ide> ssh_conf.parse(config_fd) <ide> host_info = ssh_conf.lookup(self.remote_host) <ide> if host_info and host_info.get('proxycommand'): <del> self.host_proxy = paramiko.ProxyCommand(host_info['proxycommand']) <add> self.host_proxy_cmd = host_info['proxycommand'] <ide> <ide> if not (self.password or self.key_file): <ide> if host_info and host_info.get('identityfile'): <ide> self.key_file = host_info['identityfile'][0] <ide> <ide> self.port = self.port or SSH_PORT <ide> <add> @cached_property <add> def host_proxy(self) -> Optional[paramiko.ProxyCommand]: <add> cmd = self.host_proxy_cmd <add> return paramiko.ProxyCommand(cmd) if cmd else None <add> <ide> def get_conn(self) -> paramiko.SSHClient: <ide> """ <ide> Opens a ssh connection to the remote host.
1
Python
Python
improve task_id to pod name conversion
eee3df457063df04d0fa2e57431786c6f223f700
<ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py <ide> from airflow.utils.context import Context <ide> <ide> <add>def _task_id_to_pod_name(val: str) -> str: <add> """ <add> Given a task_id, convert it to a pod name. <add> Adds a 0 if start or end char is invalid. <add> Replaces any other invalid char with `-`. <add> <add> :param val: non-empty string, presumed to be a task id <add> :return valid kubernetes object name. <add> """ <add> if not val: <add> raise ValueError("_task_id_to_pod_name requires non-empty string.") <add> val = val.lower() <add> if not re.match(r"[a-z0-9]", val[0]): <add> val = f"0{val}" <add> if not re.match(r"[a-z0-9]", val[-1]): <add> val = f"{val}0" <add> val = re.sub(r"[^a-z0-9\-.]", "-", val) <add> if len(val) > 253: <add> raise ValueError( <add> f"Pod name {val} is longer than 253 characters. " <add> "See https://kubernetes.io/docs/concepts/overview/working-with-objects/names/." <add> ) <add> return val <add> <add> <ide> class PodReattachFailure(AirflowException): <ide> """When we expect to be able to find a pod but cannot.""" <ide> <ide> def build_pod_request_obj(self, context: Context | None = None) -> k8s.V1Pod: <ide> pod = PodGenerator.reconcile_pods(pod_template, pod) <ide> <ide> if not pod.metadata.name: <del> pod.metadata.name = self.task_id <add> pod.metadata.name = _task_id_to_pod_name(self.task_id) <ide> <ide> if self.random_name_suffix: <ide> pod.metadata.name = PodGenerator.make_unique_pod_id(pod.metadata.name) <ide><path>tests/providers/cncf/kubernetes/operators/test_kubernetes_pod.py <ide> from airflow.exceptions import AirflowException <ide> from airflow.models import DAG, DagModel, DagRun, TaskInstance <ide> from airflow.models.xcom import XCom <del>from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator, _suppress <add>from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import ( <add> KubernetesPodOperator, <add> _suppress, <add> _task_id_to_pod_name, <add>) <ide> from airflow.utils import timezone <ide> from airflow.utils.session import create_session <ide> from airflow.utils.types import DagRunType <ide> def test_mark_checked_if_not_deleted(self, mock_patch_already_checked, mock_dele <ide> mock_patch_already_checked.assert_called_once() <ide> mock_delete_pod.assert_not_called() <ide> <add> def test_task_id_as_name(self): <add> k = KubernetesPodOperator( <add> task_id=".hi.-_09HI", <add> random_name_suffix=False, <add> ) <add> pod = k.build_pod_request_obj({}) <add> assert pod.metadata.name == "0.hi.--09hi" <add> <add> def test_task_id_as_name_with_suffix(self): <add> k = KubernetesPodOperator( <add> task_id=".hi.-_09HI", <add> random_name_suffix=True, <add> ) <add> pod = k.build_pod_request_obj({}) <add> expected = "0.hi.--09hi" <add> assert pod.metadata.name.startswith(expected) <add> assert re.match(rf"{expected}-[a-z0-9-]+", pod.metadata.name) is not None <add> <add> def test_task_id_as_name_with_suffix_very_long(self): <add> k = KubernetesPodOperator( <add> task_id="a" * 250, <add> random_name_suffix=True, <add> ) <add> pod = k.build_pod_request_obj({}) <add> assert re.match(r"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-[a-z0-9-]+", pod.metadata.name) is not None <add> <add> def test_task_id_as_name_dag_id_is_ignored(self): <add> dag = DAG(dag_id="this_is_a_dag_name", start_date=pendulum.now()) <add> k = KubernetesPodOperator( <add> task_id="a_very_reasonable_task_name", <add> dag=dag, <add> ) <add> pod = k.build_pod_request_obj({}) <add> assert re.match(r"a-very-reasonable-task-name-[a-z0-9-]+", pod.metadata.name) is not None <add> <ide> <ide> def test__suppress(caplog): <ide> with _suppress(ValueError): <ide> raise ValueError("failure") <ide> <ide> assert "ValueError: failure" in caplog.text <add> <add> <add>@pytest.mark.parametrize( <add> "val, expected", <add> [ <add> ("task-id", "task-id"), # no problem <add> ("task_id", "task-id"), # underscores <add> ("task.id", "task.id"), # dots ok <add> (".task.id", "0.task.id"), # leading dot invalid <add> ("-90Abc*&", "0-90abc--0"), # invalid ends <add> ("90AçLbˆˆç˙ßߘ˜˙c*a", "90a-lb---------c-a"), # weird unicode <add> ], <add>) <add>def test_task_id_to_pod_name(val, expected): <add> assert _task_id_to_pod_name(val) == expected <add> <add> <add>def test_task_id_to_pod_name_long(): <add> with pytest.raises(ValueError, match="longer than 253"): <add> _task_id_to_pod_name("0" * 254)
2
Text
Text
centralize discussion of behavior label and env
39a71acf7e18c2d00d32b01db3daaebc7392d92a
<ide><path>docs/reference/logging/fluentd.md <ide> the log tag format. <ide> <ide> ### labels and env <ide> <del>The `labels` and `env` options takes a comma-separated list of keys. If there is collision between `label` and `env` keys, the value of the `env` takes precedence. <add>The `labels` and `env` options each take a comma-separated list of keys. If there is collision between `label` and `env` keys, the value of the `env` takes precedence. Both options add additional fields to the extra attributes of a logging message. <ide> <del>To use attributes, specify them when you start the Docker daemon. <del> <del>``` <del>docker daemon --log-driver=fluentd --log-opt labels=foo --log-opt env=foo,fizz <del>``` <del> <del>Then, run a container and specify values for the `labels` or `env`. For example, you might use this: <del> <del>``` <del>docker run --label foo=bar -e fizz=buzz -d -P training/webapp python app.py <del>```` <del> <del>This adds additional fields to the extra attributes of a logging message. <ide> <ide> ## Fluentd daemon management with Docker <ide> <ide> aggregate store. <ide> <source> <ide> @type forward <ide> </source> <del> <add> <ide> <match docker.**> <ide> @type stdout <ide> </match> <ide><path>docs/reference/logging/journald.md <ide> journald logging driver options. <ide> <ide> ### labels and env <ide> <del>The `labels` and `env` options takes a comma-separated list of keys. If there is collision between `label` and `env` keys, the value of the `env` takes precedence. <del> <del>To use attributes, specify them when you start the Docker daemon. <del> <del>``` <del>docker daemon --log-driver=journald --log-opt labels=foo --log-opt env=foo,fizz <del>``` <del> <del>Then, run a container and specify values for the `labels` or `env`. For example, you might use this: <del> <del>``` <del>docker run --label foo=bar -e fizz=buzz -d -P training/webapp python app.py <del>```` <del> <del>This adds additional metadata in the journal with each message, one <del>for each key that matches. <del> <add>The `labels` and `env` options each take a comma-separated list of keys. If there is collision between `label` and `env` keys, the value of the `env` takes precedence. Both options add additional metadata in the journal with each message. <ide> <ide> ## Note regarding container names <ide> <ide> logs: <ide> <ide> for msg in reader: <ide> print '{CONTAINER_ID_FULL}: {MESSAGE}'.format(**msg) <del> <ide><path>docs/reference/logging/overview.md <ide> container's logging driver. The following options are supported: <ide> <ide> The `docker logs`command is available only for the `json-file` logging driver. <ide> <del> <del>## json-file options <del> <del>The following logging options are supported for the `json-file` logging driver: <del> <del> --log-opt max-size=[0-9+][k|m|g] <del> --log-opt max-file=[0-9+] <del> --log-opt labels=label1,label2 <del> --log-opt env=env1,env2 <del> <del>Logs that reach `max-size` are rolled over. You can set the size in kilobytes(k), megabytes(m), or gigabytes(g). eg `--log-opt max-size=50m`. If `max-size` is not set, then logs are not rolled over. <del> <del> <del>`max-file` specifies the maximum number of files that a log is rolled over before being discarded. eg `--log-opt max-file=100`. If `max-size` is not set, then `max-file` is not honored. <del> <del>If `max-size` and `max-file` are set, `docker logs` only returns the log lines from the newest log file. <del> <del>The `labels` and `env` options add additional attributes for use with logging drivers that accept them. Each of these options takes a comma-separated list of keys. If there is collision between `label` and `env` keys, the value of the `env` takes precedence. <add>The `labels` and `env` options add additional attributes for use with logging drivers that accept them. Each option takes a comma-separated list of keys. If there is collision between `label` and `env` keys, the value of the `env` takes precedence. <ide> <ide> To use attributes, specify them when you start the Docker daemon. <ide> <ide> Then, run a container and specify values for the `labels` or `env`. For example <ide> docker run --label foo=bar -e fizz=buzz -d -P training/webapp python app.py <ide> ```` <ide> <del>This adds additional fields depending on the driver, e.g. for <add>This adds additional fields to the log depending on the driver, e.g. for <ide> `json-file` that looks like: <ide> <ide> "attrs":{"fizz":"buzz","foo":"bar"} <ide> <ide> <add>## json-file options <add> <add>The following logging options are supported for the `json-file` logging driver: <add> <add> --log-opt max-size=[0-9+][k|m|g] <add> --log-opt max-file=[0-9+] <add> --log-opt labels=label1,label2 <add> --log-opt env=env1,env2 <add> <add>Logs that reach `max-size` are rolled over. You can set the size in kilobytes(k), megabytes(m), or gigabytes(g). eg `--log-opt max-size=50m`. If `max-size` is not set, then logs are not rolled over. <add> <add>`max-file` specifies the maximum number of files that a log is rolled over before being discarded. eg `--log-opt max-file=100`. If `max-size` is not set, then `max-file` is not honored. <add> <add>If `max-size` and `max-file` are set, `docker logs` only returns the log lines from the newest log file. <add> <add> <ide> ## syslog options <ide> <ide> The following logging options are supported for the `syslog` logging driver:
3
PHP
PHP
unify templated tags
f990e73ffa6fa880a89a3bc9c340c8713ec3b607
<ide><path>src/View/Helper/HtmlHelper.php <ide> class HtmlHelper extends Helper { <ide> 'parastart' => '<p{{attrs}}>', <ide> 'css' => '<link rel="{{rel}}" href="{{url}}"{{attrs}}/>', <ide> 'style' => '<style{{attrs}}>{{content}}</style>', <del> 'charset' => '<meta http-equiv="Content-Type" content="text/html; charset={{charset}}" />', <add> 'charset' => '<meta http-equiv="Content-Type" content="text/html; charset={{charset}}"/>', <ide> 'ul' => '<ul{{attrs}}>{{content}}</ul>', <ide> 'ol' => '<ol{{attrs}}>{{content}}</ol>', <ide> 'li' => '<li{{attrs}}>{{content}}</li>',
1
Text
Text
drop core team member
82b9511abc3af9bd7e97b06b786df0fd92bbb170
<ide><path>README.md <ide> If you have discovered a 🐜 or have a feature suggestion, feel free to create <ide> <br> <ide> <p>Founder of the core team</p> <ide> </td> <del> <td align="center" valign="top"> <del> <img width="150" height="150" src="https://github.com/bebraw.png?s=150"> <del> <br> <del> <a href="https://github.com/bebraw">Juho Vepsäläinen</a> <del> <p>Documentation</p> <del> <br> <del> <p>Author</p> <del> <a href="https://leanpub.com/survivejs-webpack"> <del> <img height="15" src="https://cloud.githubusercontent.com/assets/1365881/20286923/93e325c0-aac9-11e6-964d-cabe218c584c.png"> <del> </a> <del> <br> <del> </td> <ide> <td align="center" valign="top"> <ide> <img width="150" height="150" src="https://github.com/spacek33z.png?s=150"> <ide> <br>
1
Mixed
Text
update readme to latest release
e6f00a11d7fa34215184e3c797e19e6c7debe0fe
<ide><path>README.md <ide> Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih. <ide> 1. **[Megatron-GPT2](https://huggingface.co/docs/transformers/model_doc/megatron_gpt2)** (from NVIDIA) released with the paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro. <ide> 1. **[MPNet](https://huggingface.co/docs/transformers/model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu. <ide> 1. **[MT5](https://huggingface.co/docs/transformers/model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel. <del>1. **[Nyströmformer](https://huggingface.co/docs/transformers/main/model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh. <add>1. **[Nyströmformer](https://huggingface.co/docs/transformers/model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh. <ide> 1. **[Pegasus](https://huggingface.co/docs/transformers/model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu. <ide> 1. **[Perceiver IO](https://huggingface.co/docs/transformers/model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira. <ide> 1. **[PhoBERT](https://huggingface.co/docs/transformers/model_doc/phobert)** (from VinAI Research) released with the paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) by Dat Quoc Nguyen and Anh Tuan Nguyen. <del>1. **[PLBart](https://huggingface.co/docs/transformers/main/model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang. <del>1. **[PoolFormer](https://huggingface.co/docs/transformers/main/model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng. <add>1. **[PLBart](https://huggingface.co/docs/transformers/model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang. <add>1. **[PoolFormer](https://huggingface.co/docs/transformers/model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng. <ide> 1. **[ProphetNet](https://huggingface.co/docs/transformers/model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. <ide> 1. **[QDQBert](https://huggingface.co/docs/transformers/model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius. <ide> 1. **[REALM](https://huggingface.co/docs/transformers/model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang. <ide> 1. **[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya. <ide> 1. **[RemBERT](https://huggingface.co/docs/transformers/model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder. <ide> 1. **[RegNet](https://huggingface.co/docs/transformers/main/model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár. <del>1. **[ResNet](https://huggingface.co/docs/transformers/main/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. <add>1. **[ResNet](https://huggingface.co/docs/transformers/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. <ide> 1. **[RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov. <ide> 1. **[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu. <ide> 1. **[SegFormer](https://huggingface.co/docs/transformers/model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo. <ide> Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih. <ide> 1. **[SpeechToTextTransformer2](https://huggingface.co/docs/transformers/model_doc/speech_to_text_2)** (from Facebook), released together with the paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau. <ide> 1. **[Splinter](https://huggingface.co/docs/transformers/model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy. <ide> 1. **[SqueezeBert](https://huggingface.co/docs/transformers/model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer. <del>1. **[Swin Transformer](https://huggingface.co/docs/transformers/main/model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. <add>1. **[Swin Transformer](https://huggingface.co/docs/transformers/model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. <ide> 1. **[T5](https://huggingface.co/docs/transformers/model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. <ide> 1. **[T5v1.1](https://huggingface.co/docs/transformers/model_doc/t5v1.1)** (from Google AI) released in the repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. <ide> 1. **[TAPAS](https://huggingface.co/docs/transformers/model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos. <ide> Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih. <ide> 1. **[UniSpeech](https://huggingface.co/docs/transformers/model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang. <ide> 1. **[UniSpeechSat](https://huggingface.co/docs/transformers/model_doc/unispeech-sat)** (from Microsoft Research) released with the paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER <ide> AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu. <del>1. **[VAN](https://huggingface.co/docs/transformers/main/model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. <del>1. **[ViLT](https://huggingface.co/docs/transformers/main/model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim. <add>1. **[VAN](https://huggingface.co/docs/transformers/model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. <add>1. **[ViLT](https://huggingface.co/docs/transformers/model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim. <ide> 1. **[Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby. <del>1. **[ViTMAE](https://huggingface.co/docs/transformers/main/model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick. <add>1. **[ViTMAE](https://huggingface.co/docs/transformers/model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick. <ide> 1. **[VisualBERT](https://huggingface.co/docs/transformers/model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang. <del>1. **[WavLM](https://huggingface.co/docs/transformers/main/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. <add>1. **[WavLM](https://huggingface.co/docs/transformers/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. <ide> 1. **[Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli. <ide> 1. **[Wav2Vec2Phoneme](https://huggingface.co/docs/transformers/model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli. <ide> 1. **[XGLM](https://huggingface.co/docs/transformers/model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li. <ide> AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) by Sanyuan Chen, Yu Wu, Ch <ide> 1. **[XLNet](https://huggingface.co/docs/transformers/model_doc/xlnet)** (from Google/CMU) released with the paper [​XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le. <ide> 1. **[XLSR-Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli. <ide> 1. **[XLS-R](https://huggingface.co/docs/transformers/model_doc/xls_r)** (from Facebook AI) released with the paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296) by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli. <del>1. **[YOSO](https://huggingface.co/docs/transformers/main/model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh. <add>1. **[YOSO](https://huggingface.co/docs/transformers/model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh. <ide> 1. Want to contribute a new model? We have added a **detailed guide and templates** to guide you in the process of adding a new model. You can find them in the [`templates`](./templates) folder of the repository. Be sure to check the [contributing guidelines](./CONTRIBUTING.md) and contact the maintainers or open an issue to collect feedbacks before starting your PR. <ide> <ide> To check if each model has an implementation in Flax, PyTorch or TensorFlow, or has an associated tokenizer backed by the 🤗 Tokenizers library, refer to [this table](https://huggingface.co/docs/transformers/index#supported-frameworks). <ide><path>README_ko.md <ide> Flax, PyTorch, TensorFlow 설치 페이지에서 이들을 conda로 설치하는 <ide> 1. **[mLUKE](https://huggingface.co/docs/transformers/model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka. <ide> 1. **[MPNet](https://huggingface.co/docs/transformers/model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu. <ide> 1. **[MT5](https://huggingface.co/docs/transformers/model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel. <del>1. **[Nyströmformer](https://huggingface.co/docs/transformers/main/model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh. <add>1. **[Nyströmformer](https://huggingface.co/docs/transformers/model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh. <ide> 1. **[Pegasus](https://huggingface.co/docs/transformers/model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu. <ide> 1. **[Perceiver IO](https://huggingface.co/docs/transformers/model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira. <ide> 1. **[PhoBERT](https://huggingface.co/docs/transformers/model_doc/phobert)** (from VinAI Research) released with the paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) by Dat Quoc Nguyen and Anh Tuan Nguyen. <del>1. **[PLBart](https://huggingface.co/docs/transformers/main/model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang. <del>1. **[PoolFormer](https://huggingface.co/docs/transformers/main/model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng. <add>1. **[PLBart](https://huggingface.co/docs/transformers/model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang. <add>1. **[PoolFormer](https://huggingface.co/docs/transformers/model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng. <ide> 1. **[ProphetNet](https://huggingface.co/docs/transformers/model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. <ide> 1. **[QDQBert](https://huggingface.co/docs/transformers/model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius. <ide> 1. **[REALM](https://huggingface.co/docs/transformers/model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang. <ide> 1. **[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya. <ide> 1. **[RegNet](https://huggingface.co/docs/transformers/main/model_doc/regnet)** (from META Research) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár. <ide> 1. **[RemBERT](https://huggingface.co/docs/transformers/model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/pdf/2010.12821.pdf) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder. <del>1. **[ResNet](https://huggingface.co/docs/transformers/main/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. <add>1. **[ResNet](https://huggingface.co/docs/transformers/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. <ide> 1. **[RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta)** (from Facebook), released together with the paper a [Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov. <ide> 1. **[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper a [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/pdf/2104.09864v1.pdf) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu. <ide> 1. **[SegFormer](https://huggingface.co/docs/transformers/model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo. <ide> Flax, PyTorch, TensorFlow 설치 페이지에서 이들을 conda로 설치하는 <ide> 1. **[SpeechToTextTransformer2](https://huggingface.co/docs/transformers/model_doc/speech_to_text_2)** (from Facebook), released together with the paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau. <ide> 1. **[Splinter](https://huggingface.co/docs/transformers/model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy. <ide> 1. **[SqueezeBert](https://huggingface.co/docs/transformers/model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer. <del>1. **[Swin Transformer](https://huggingface.co/docs/transformers/main/model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. <add>1. **[Swin Transformer](https://huggingface.co/docs/transformers/model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. <ide> 1. **[T5](https://huggingface.co/docs/transformers/model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. <ide> 1. **[T5v1.1](https://huggingface.co/docs/transformers/model_doc/t5v1.1)** (from Google AI) released in the repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. <ide> 1. **[TAPAS](https://huggingface.co/docs/transformers/model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos. <ide> Flax, PyTorch, TensorFlow 설치 페이지에서 이들을 conda로 설치하는 <ide> 1. **[TrOCR](https://huggingface.co/docs/transformers/model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei. <ide> 1. **[UniSpeech](https://huggingface.co/docs/transformers/model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang. <ide> 1. **[UniSpeechSat](https://huggingface.co/docs/transformers/model_doc/unispeech-sat)** (from Microsoft Research) released with the paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu. <del>1. **[VAN](https://huggingface.co/docs/transformers/main/model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/pdf/2202.09741.pdf) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. <del>1. **[ViLT](https://huggingface.co/docs/transformers/main/model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim. <add>1. **[VAN](https://huggingface.co/docs/transformers/model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/pdf/2202.09741.pdf) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. <add>1. **[ViLT](https://huggingface.co/docs/transformers/model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim. <ide> 1. **[Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby. <ide> 1. **[VisualBERT](https://huggingface.co/docs/transformers/model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang. <del>1. **[ViTMAE](https://huggingface.co/docs/transformers/main/model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick. <add>1. **[ViTMAE](https://huggingface.co/docs/transformers/model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick. <ide> 1. **[Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli. <ide> 1. **[Wav2Vec2Phoneme](https://huggingface.co/docs/transformers/model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli. <del>1. **[WavLM](https://huggingface.co/docs/transformers/main/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. <add>1. **[WavLM](https://huggingface.co/docs/transformers/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. <ide> 1. **[XGLM](https://huggingface.co/docs/transformers/model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li. <ide> 1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau. <ide> 1. **[XLM-ProphetNet](https://huggingface.co/docs/transformers/model_doc/xlm-prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. <ide> Flax, PyTorch, TensorFlow 설치 페이지에서 이들을 conda로 설치하는 <ide> 1. **[XLNet](https://huggingface.co/docs/transformers/model_doc/xlnet)** (from Google/CMU) released with the paper [​XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le. <ide> 1. **[XLS-R](https://huggingface.co/docs/transformers/model_doc/xls_r)** (from Facebook AI) released with the paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296) by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli. <ide> 1. **[XLSR-Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli. <del>1. **[YOSO](https://huggingface.co/docs/transformers/main/model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh. <add>1. **[YOSO](https://huggingface.co/docs/transformers/model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh. <ide> 1. 새로운 모델을 올리고 싶나요? 우리가 **상세한 가이드와 템플릿** 으로 새로운 모델을 올리도록 도와드릴게요. 가이드와 템플릿은 이 저장소의 [`templates`](./templates) 폴더에서 확인하실 수 있습니다. [컨트리뷰션 가이드라인](./CONTRIBUTING.md)을 꼭 확인해주시고, PR을 올리기 전에 메인테이너에게 연락하거나 이슈를 오픈해 피드백을 받으시길 바랍니다. <ide> <ide> 각 모델이 Flax, PyTorch, TensorFlow으로 구현되었는지 또는 🤗 Tokenizers 라이브러리가 지원하는 토크나이저를 사용하는지 확인하려면, [이 표](https://huggingface.co/docs/transformers/index#supported-frameworks)를 확인하세요. <ide><path>README_zh-hans.md <ide> conda install -c huggingface transformers <ide> 1. **[mLUKE](https://huggingface.co/docs/transformers/model_doc/mluke)** (来自 Studio Ousia) 伴随论文 [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) 由 Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka 发布。 <ide> 1. **[MPNet](https://huggingface.co/docs/transformers/model_doc/mpnet)** (来自 Microsoft Research) 伴随论文 [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) 由 Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu 发布。 <ide> 1. **[MT5](https://huggingface.co/docs/transformers/model_doc/mt5)** (来自 Google AI) 伴随论文 [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) 由 Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel 发布。 <del>1. **[Nyströmformer](https://huggingface.co/docs/transformers/main/model_doc/nystromformer)** (来自 the University of Wisconsin - Madison) 伴随论文 [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) 由 Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh 发布。 <add>1. **[Nyströmformer](https://huggingface.co/docs/transformers/model_doc/nystromformer)** (来自 the University of Wisconsin - Madison) 伴随论文 [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) 由 Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh 发布。 <ide> 1. **[Pegasus](https://huggingface.co/docs/transformers/model_doc/pegasus)** (来自 Google) 伴随论文 [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) 由 Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu 发布。 <ide> 1. **[Perceiver IO](https://huggingface.co/docs/transformers/model_doc/perceiver)** (来自 Deepmind) 伴随论文 [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) 由 Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira 发布。 <ide> 1. **[PhoBERT](https://huggingface.co/docs/transformers/model_doc/phobert)** (来自 VinAI Research) 伴随论文 [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) 由 Dat Quoc Nguyen and Anh Tuan Nguyen 发布。 <del>1. **[PLBart](https://huggingface.co/docs/transformers/main/model_doc/plbart)** (来自 UCLA NLP) 伴随论文 [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) 由 Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang 发布。 <del>1. **[PoolFormer](https://huggingface.co/docs/transformers/main/model_doc/poolformer)** (来自 Sea AI Labs) 伴随论文 [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) 由 Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng 发布。 <add>1. **[PLBart](https://huggingface.co/docs/transformers/model_doc/plbart)** (来自 UCLA NLP) 伴随论文 [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) 由 Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang 发布。 <add>1. **[PoolFormer](https://huggingface.co/docs/transformers/model_doc/poolformer)** (来自 Sea AI Labs) 伴随论文 [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) 由 Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng 发布。 <ide> 1. **[ProphetNet](https://huggingface.co/docs/transformers/model_doc/prophetnet)** (来自 Microsoft Research) 伴随论文 [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) 由 Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou 发布。 <ide> 1. **[QDQBert](https://huggingface.co/docs/transformers/model_doc/qdqbert)** (来自 NVIDIA) 伴随论文 [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) 由 Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius 发布。 <ide> 1. **[REALM](https://huggingface.co/docs/transformers/model_doc/realm.html)** (来自 Google Research) 伴随论文 [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) 由 Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang 发布。 <ide> 1. **[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer)** (来自 Google Research) 伴随论文 [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) 由 Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya 发布。 <ide> 1. **[RegNet](https://huggingface.co/docs/transformers/main/model_doc/regnet)** (from META Research) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár. <ide> 1. **[RemBERT](https://huggingface.co/docs/transformers/model_doc/rembert)** (来自 Google Research) 伴随论文 [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/pdf/2010.12821.pdf) 由 Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder 发布。 <del>1. **[ResNet](https://huggingface.co/docs/transformers/main/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. <add>1. **[ResNet](https://huggingface.co/docs/transformers/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. <ide> 1. **[RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta)** (来自 Facebook), 伴随论文 [Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) 由 Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov 发布。 <ide> 1. **[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer)** (来自 ZhuiyiTechnology), 伴随论文 [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/pdf/2104.09864v1.pdf) 由 Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu 发布。 <ide> 1. **[SegFormer](https://huggingface.co/docs/transformers/model_doc/segformer)** (来自 NVIDIA) 伴随论文 [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) 由 Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo 发布。 <ide> conda install -c huggingface transformers <ide> 1. **[SpeechToTextTransformer2](https://huggingface.co/docs/transformers/model_doc/speech_to_text_2)** (来自 Facebook) 伴随论文 [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) 由 Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau 发布。 <ide> 1. **[Splinter](https://huggingface.co/docs/transformers/model_doc/splinter)** (来自 Tel Aviv University) 伴随论文 [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) 由 Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy 发布。 <ide> 1. **[SqueezeBert](https://huggingface.co/docs/transformers/model_doc/squeezebert)** (来自 Berkeley) 伴随论文 [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) 由 Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer 发布。 <del>1. **[Swin Transformer](https://huggingface.co/docs/transformers/main/model_doc/swin)** (来自 Microsoft) 伴随论文 [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) 由 Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo 发布。 <add>1. **[Swin Transformer](https://huggingface.co/docs/transformers/model_doc/swin)** (来自 Microsoft) 伴随论文 [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) 由 Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo 发布。 <ide> 1. **[T5](https://huggingface.co/docs/transformers/model_doc/t5)** (来自 Google AI) 伴随论文 [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) 由 Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu 发布。 <ide> 1. **[T5v1.1](https://huggingface.co/docs/transformers/model_doc/t5v1.1)** (来自 Google AI) 伴随论文 [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) 由 Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu 发布。 <ide> 1. **[TAPAS](https://huggingface.co/docs/transformers/model_doc/tapas)** (来自 Google AI) 伴随论文 [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) 由 Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos 发布。 <ide> conda install -c huggingface transformers <ide> 1. **[TrOCR](https://huggingface.co/docs/transformers/model_doc/trocr)** (来自 Microsoft) 伴随论文 [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) 由 Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei 发布。 <ide> 1. **[UniSpeech](https://huggingface.co/docs/transformers/model_doc/unispeech)** (来自 Microsoft Research) 伴随论文 [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) 由 Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang 发布。 <ide> 1. **[UniSpeechSat](https://huggingface.co/docs/transformers/model_doc/unispeech-sat)** (来自 Microsoft Research) 伴随论文 [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) 由 Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu 发布。 <del>1. **[VAN](https://huggingface.co/docs/transformers/main/model_doc/van)** (来自 Tsinghua University and Nankai University) 伴随论文 [Visual Attention Network](https://arxiv.org/pdf/2202.09741.pdf) 由 Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu 发布。 <del>1. **[ViLT](https://huggingface.co/docs/transformers/main/model_doc/vilt)** (来自 NAVER AI Lab/Kakao Enterprise/Kakao Brain) 伴随论文 [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) 由 Wonjae Kim, Bokyung Son, Ildoo Kim 发布。 <add>1. **[VAN](https://huggingface.co/docs/transformers/model_doc/van)** (来自 Tsinghua University and Nankai University) 伴随论文 [Visual Attention Network](https://arxiv.org/pdf/2202.09741.pdf) 由 Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu 发布。 <add>1. **[ViLT](https://huggingface.co/docs/transformers/model_doc/vilt)** (来自 NAVER AI Lab/Kakao Enterprise/Kakao Brain) 伴随论文 [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) 由 Wonjae Kim, Bokyung Son, Ildoo Kim 发布。 <ide> 1. **[Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit)** (来自 Google AI) 伴随论文 [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) 由 Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby 发布。 <ide> 1. **[VisualBERT](https://huggingface.co/docs/transformers/model_doc/visual_bert)** (来自 UCLA NLP) 伴随论文 [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) 由 Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang 发布。 <del>1. **[ViTMAE](https://huggingface.co/docs/transformers/main/model_doc/vit_mae)** (来自 Meta AI) 伴随论文 [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) 由 Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick 发布。 <add>1. **[ViTMAE](https://huggingface.co/docs/transformers/model_doc/vit_mae)** (来自 Meta AI) 伴随论文 [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) 由 Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick 发布。 <ide> 1. **[Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2)** (来自 Facebook AI) 伴随论文 [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) 由 Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli 发布。 <ide> 1. **[Wav2Vec2Phoneme](https://huggingface.co/docs/transformers/model_doc/wav2vec2_phoneme)** (来自 Facebook AI) 伴随论文 [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) 由 Qiantong Xu, Alexei Baevski, Michael Auli 发布。 <del>1. **[WavLM](https://huggingface.co/docs/transformers/main/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. <add>1. **[WavLM](https://huggingface.co/docs/transformers/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. <ide> 1. **[XGLM](https://huggingface.co/docs/transformers/model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li. <ide> 1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (来自 Facebook) 伴随论文 [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) 由 Guillaume Lample and Alexis Conneau 发布。 <ide> 1. **[XLM-ProphetNet](https://huggingface.co/docs/transformers/model_doc/xlm-prophetnet)** (来自 Microsoft Research) 伴随论文 [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) 由 Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou 发布。 <ide> conda install -c huggingface transformers <ide> 1. **[XLNet](https://huggingface.co/docs/transformers/model_doc/xlnet)** (来自 Google/CMU) 伴随论文 [XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) 由 Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le 发布。 <ide> 1. **[XLS-R](https://huggingface.co/docs/transformers/model_doc/xls_r)** (来自 Facebook AI) 伴随论文 [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296) 由 Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli 发布。 <ide> 1. **[XLSR-Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/xlsr_wav2vec2)** (来自 Facebook AI) 伴随论文 [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) 由 Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli 发布。 <del>1. **[YOSO](https://huggingface.co/docs/transformers/main/model_doc/yoso)** (来自 the University of Wisconsin - Madison) 伴随论文 [You Only Sample (Almost) 由 Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh 发布。 <add>1. **[YOSO](https://huggingface.co/docs/transformers/model_doc/yoso)** (来自 the University of Wisconsin - Madison) 伴随论文 [You Only Sample (Almost) 由 Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh 发布。 <ide> 1. 想要贡献新的模型?我们这里有一份**详细指引和模板**来引导你添加新的模型。你可以在 [`templates`](./templates) 目录中找到他们。记得查看 [贡献指南](./CONTRIBUTING.md) 并在开始写 PR 前联系维护人员或开一个新的 issue 来获得反馈。 <ide> <ide> 要检查某个模型是否已有 Flax、PyTorch 或 TensorFlow 的实现,或其是否在 🤗 Tokenizers 库中有对应词符化器(tokenizer),敬请参阅[此表](https://huggingface.co/docs/transformers/index#supported-frameworks)。 <ide><path>README_zh-hant.md <ide> conda install -c huggingface transformers <ide> 1. **[mLUKE](https://huggingface.co/docs/transformers/model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka. <ide> 1. **[MPNet](https://huggingface.co/docs/transformers/model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu. <ide> 1. **[MT5](https://huggingface.co/docs/transformers/model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel. <del>1. **[Nyströmformer](https://huggingface.co/docs/transformers/main/model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh. <add>1. **[Nyströmformer](https://huggingface.co/docs/transformers/model_doc/nystromformer)** (from the University of Wisconsin - Madison) released with the paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh. <ide> 1. **[Pegasus](https://huggingface.co/docs/transformers/model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu. <ide> 1. **[Perceiver IO](https://huggingface.co/docs/transformers/model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira. <ide> 1. **[PhoBERT](https://huggingface.co/docs/transformers/model_doc/phobert)** (from VinAI Research) released with the paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) by Dat Quoc Nguyen and Anh Tuan Nguyen. <del>1. **[PLBart](https://huggingface.co/docs/transformers/main/model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang. <del>1. **[PoolFormer](https://huggingface.co/docs/transformers/main/model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng. <add>1. **[PLBart](https://huggingface.co/docs/transformers/model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang. <add>1. **[PoolFormer](https://huggingface.co/docs/transformers/model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng. <ide> 1. **[ProphetNet](https://huggingface.co/docs/transformers/model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. <ide> 1. **[QDQBert](https://huggingface.co/docs/transformers/model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius. <ide> 1. **[REALM](https://huggingface.co/docs/transformers/model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang. <ide> 1. **[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya. <ide> 1. **[RegNet](https://huggingface.co/docs/transformers/main/model_doc/regnet)** (from META Research) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár. <ide> 1. **[RemBERT](https://huggingface.co/docs/transformers/model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/pdf/2010.12821.pdf) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder. <del>1. **[ResNet](https://huggingface.co/docs/transformers/main/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. <add>1. **[ResNet](https://huggingface.co/docs/transformers/model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. <ide> 1. **[RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta)** (from Facebook), released together with the paper a [Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov. <ide> 1. **[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper a [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/pdf/2104.09864v1.pdf) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu. <ide> 1. **[SegFormer](https://huggingface.co/docs/transformers/model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo. <ide> conda install -c huggingface transformers <ide> 1. **[SpeechToTextTransformer2](https://huggingface.co/docs/transformers/model_doc/speech_to_text_2)** (from Facebook) released with the paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau. <ide> 1. **[Splinter](https://huggingface.co/docs/transformers/model_doc/splinter)** (from Tel Aviv University) released with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy. <ide> 1. **[SqueezeBert](https://huggingface.co/docs/transformers/model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer. <del>1. **[Swin Transformer](https://huggingface.co/docs/transformers/main/model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. <add>1. **[Swin Transformer](https://huggingface.co/docs/transformers/model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo. <ide> 1. **[T5](https://huggingface.co/docs/transformers/model_doc/t5)** (from Google AI) released with the paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. <ide> 1. **[T5v1.1](https://huggingface.co/docs/transformers/model_doc/t5v1.1)** (from Google AI) released with the paper [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu. <ide> 1. **[TAPAS](https://huggingface.co/docs/transformers/model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos. <ide> conda install -c huggingface transformers <ide> 1. **[TrOCR](https://huggingface.co/docs/transformers/model_doc/trocr)** (from Microsoft) released with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei. <ide> 1. **[UniSpeech](https://huggingface.co/docs/transformers/model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang. <ide> 1. **[UniSpeechSat](https://huggingface.co/docs/transformers/model_doc/unispeech-sat)** (from Microsoft Research) released with the paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu. <del>1. **[VAN](https://huggingface.co/docs/transformers/main/model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/pdf/2202.09741.pdf) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. <del>1. **[ViLT](https://huggingface.co/docs/transformers/main/model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim. <add>1. **[VAN](https://huggingface.co/docs/transformers/model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/pdf/2202.09741.pdf) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu. <add>1. **[ViLT](https://huggingface.co/docs/transformers/model_doc/vilt)** (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim. <ide> 1. **[Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit)** (from Google AI) released with the paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby. <ide> 1. **[VisualBERT](https://huggingface.co/docs/transformers/model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang. <del>1. **[ViTMAE](https://huggingface.co/docs/transformers/main/model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick. <add>1. **[ViTMAE](https://huggingface.co/docs/transformers/model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick. <ide> 1. **[Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2)** (from Facebook AI) released with the paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli. <ide> 1. **[Wav2Vec2Phoneme](https://huggingface.co/docs/transformers/model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli. <del>1. **[WavLM](https://huggingface.co/docs/transformers/main/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. <add>1. **[WavLM](https://huggingface.co/docs/transformers/model_doc/wavlm)** (from Microsoft Research) released with the paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei. <ide> 1. **[XGLM](https://huggingface.co/docs/transformers/model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668) by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O'Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li. <ide> 1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau. <ide> 1. **[XLM-ProphetNet](https://huggingface.co/docs/transformers/model_doc/xlm-prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou. <ide> conda install -c huggingface transformers <ide> 1. **[XLNet](https://huggingface.co/docs/transformers/model_doc/xlnet)** (from Google/CMU) released with the paper [​XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le. <ide> 1. **[XLS-R](https://huggingface.co/docs/transformers/model_doc/xls_r)** (from Facebook AI) released with the paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296) by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli. <ide> 1. **[XLSR-Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli. <del>1. **[YOSO](https://huggingface.co/docs/transformers/main/model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh. <add>1. **[YOSO](https://huggingface.co/docs/transformers/model_doc/yoso)** (from the University of Wisconsin - Madison) released with the paper [You Only Sample (Almost) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh. <ide> 1. 想要貢獻新的模型?我們這裡有一份**詳細指引和模板**來引導你加入新的模型。你可以在 [`templates`](./templates) 目錄中找到它們。記得查看[貢獻指引](./CONTRIBUTING.md)並在開始寫 PR 前聯繫維護人員或開一個新的 issue 來獲得 feedbacks。 <ide> <ide> 要檢查某個模型是否已有 Flax、PyTorch 或 TensorFlow 的實作,或其是否在🤗 Tokenizers 函式庫中有對應的 tokenizer,敬請參閱[此表](https://huggingface.co/docs/transformers/index#supported-frameworks)。 <ide><path>setup.py <ide> <ide> 1. Run `make pre-release` (or `make pre-patch` for a patch release) then run `make fix-copies` to fix the index of the <ide> documentation. <add> <add> If releasing on a special branch, copy the updated README.md on the main branch for your the commit you will make <add> for the post-release and run `make fix-copies` on the main branch as well. <ide> <ide> 2. Run Tests for Amazon Sagemaker. The documentation is located in `./tests/sagemaker/README.md`, otherwise @philschmid. <ide>
5
Javascript
Javascript
fix flow from
65c137768abf696ee1c79a026d6df3a166dd8553
<ide><path>packages/react-dom/src/events/isEventSupported.js <ide> function isEventSupported(eventNameSuffix: string): boolean { <ide> if (!isSupported) { <ide> const element = document.createElement('div'); <ide> element.setAttribute(eventName, 'return;'); <del> isSupported = typeof element[eventName] === 'function'; <add> isSupported = typeof (element: any)[eventName] === 'function'; <ide> } <ide> <ide> return isSupported; <ide><path>packages/react-dom/src/events/plugins/ModernSimpleEventPlugin.js <ide> function extractEvents( <ide> // Firefox creates a keypress event for function keys too. This removes <ide> // the unwanted keypress events. Enter is however both printable and <ide> // non-printable. One would expect Tab to be as well (but it isn't). <del> if (getEventCharCode(nativeEvent) === 0) { <add> if (getEventCharCode(((nativeEvent: any): KeyboardEvent)) === 0) { <ide> return; <ide> } <ide> /* falls through */
2
Javascript
Javascript
fix language, meridiem and days of week
6c814f3c59daf24023c10cd0b7b18d5a13e9c393
<ide><path>src/locale/ne.js <ide> export default moment.defineLocale('ne', { <ide> monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'), <ide> weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'), <ide> weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'), <del> weekdaysMin : 'आइ._सो._मङ्_बु._बि._शु._श.'.split('_'), <add> weekdaysMin : 'आ._सो._मं._बु._बि._शु._श.'.split('_'), <ide> longDateFormat : { <ide> LT : 'Aको h:mm बजे', <ide> LTS : 'Aको h:mm:ss बजे', <ide> export default moment.defineLocale('ne', { <ide> return symbolMap[match]; <ide> }); <ide> }, <del> meridiemParse: /राती|बिहान|दिउँसो|बेलुका|साँझ|राती/, <add> meridiemParse: /राति|बिहान|दिउँसो|साँझ/, <ide> meridiemHour : function (hour, meridiem) { <ide> if (hour === 12) { <ide> hour = 0; <ide> } <del> if (meridiem === 'राती') { <del> return hour < 3 ? hour : hour + 12; <add> if (meridiem === 'राति') { <add> return hour < 4 ? hour : hour + 12; <ide> } else if (meridiem === 'बिहान') { <ide> return hour; <ide> } else if (meridiem === 'दिउँसो') { <ide> return hour >= 10 ? hour : hour + 12; <del> } else if (meridiem === 'बेलुका' || meridiem === 'साँझ') { <add> } else if (meridiem === 'साँझ') { <ide> return hour + 12; <ide> } <ide> }, <ide> meridiem : function (hour, minute, isLower) { <ide> if (hour < 3) { <del> return 'राती'; <del> } else if (hour < 10) { <add> return 'राति'; <add> } else if (hour < 12) { <ide> return 'बिहान'; <del> } else if (hour < 15) { <add> } else if (hour < 16) { <ide> return 'दिउँसो'; <del> } else if (hour < 18) { <del> return 'बेलुका'; <ide> } else if (hour < 20) { <ide> return 'साँझ'; <ide> } else { <del> return 'राती'; <add> return 'राति'; <ide> } <ide> }, <ide> calendar : { <ide> sameDay : '[आज] LT', <del> nextDay : '[भोली] LT', <add> nextDay : '[भोलि] LT', <ide> nextWeek : '[आउँदो] dddd[,] LT', <ide> lastDay : '[हिजो] LT', <ide> lastWeek : '[गएको] dddd[,] LT', <ide> sameElse : 'L' <ide> }, <ide> relativeTime : { <ide> future : '%sमा', <del> past : '%s अगाडी', <del> s : 'केही समय', <add> past : '%s अगाडि', <add> s : 'केही क्षण', <ide> m : 'एक मिनेट', <ide> mm : '%d मिनेट', <ide> h : 'एक घण्टा', <ide> export default moment.defineLocale('ne', { <ide> yy : '%d बर्ष' <ide> }, <ide> week : { <del> dow : 1, // Monday is the first day of the week. <del> doy : 7 // The week that contains Jan 1st is the first week of the year. <add> dow : 0, // Sunday is the first day of the week. <add> doy : 6 // The week that contains Jan 1st is the first week of the year. <ide> } <ide> }); <ide> <ide><path>src/test/locale/ne.js <ide> test('parse', function (assert) { <ide> <ide> test('format', function (assert) { <ide> var a = [ <del> ['dddd, Do MMMM YYYY, aको h:mm:ss बजे', 'आइतबार, १४ फेब्रुवरी २०१०, बेलुकाको ३:२५:५० बजे'], <del> ['ddd, aको h बजे', 'आइत., बेलुकाको ३ बजे'], <add> ['dddd, Do MMMM YYYY, aको h:mm:ss बजे', 'आइतबार, १४ फेब्रुवरी २०१०, दिउँसोको ३:२५:५० बजे'], <add> ['ddd, aको h बजे', 'आइत., दिउँसोको ३ बजे'], <ide> ['M Mo MM MMMM MMM', '२ २ ०२ फेब्रुवरी फेब्रु.'], <ide> ['YYYY YY', '२०१० १०'], <ide> ['D Do DD', '१४ १४ १४'], <del> ['d do dddd ddd dd', '० ० आइतबार आइत. आइ.'], <add> ['d do dddd ddd dd', '० ० आइतबार आइत. आ.'], <ide> ['DDD DDDo DDDD', '४५ ४५ ०४५'], <del> ['w wo ww', '७ ७ ०७'], <add> ['w wo ww', '८ ८ ०८'], <ide> ['h hh', '३ ०३'], <ide> ['H HH', '१५ १५'], <ide> ['m mm', '२५ २५'], <ide> ['s ss', '५० ५०'], <del> ['a A', 'बेलुका बेलुका'], <del> ['LTS', 'बेलुकाको ३:२५:५० बजे'], <add> ['a A', 'दिउँसो दिउँसो'], <add> ['LTS', 'दिउँसोको ३:२५:५० बजे'], <ide> ['L', '१४/०२/२०१०'], <ide> ['LL', '१४ फेब्रुवरी २०१०'], <del> ['LLL', '१४ फेब्रुवरी २०१०, बेलुकाको ३:२५ बजे'], <del> ['LLLL', 'आइतबार, १४ फेब्रुवरी २०१०, बेलुकाको ३:२५ बजे'], <add> ['LLL', '१४ फेब्रुवरी २०१०, दिउँसोको ३:२५ बजे'], <add> ['LLLL', 'आइतबार, १४ फेब्रुवरी २०१०, दिउँसोको ३:२५ बजे'], <ide> ['l', '१४/२/२०१०'], <ide> ['ll', '१४ फेब्रु. २०१०'], <del> ['lll', '१४ फेब्रु. २०१०, बेलुकाको ३:२५ बजे'], <del> ['llll', 'आइत., १४ फेब्रु. २०१०, बेलुकाको ३:२५ बजे'] <add> ['lll', '१४ फेब्रु. २०१०, दिउँसोको ३:२५ बजे'], <add> ['llll', 'आइत., १४ फेब्रु. २०१०, दिउँसोको ३:२५ बजे'] <ide> ], <ide> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <ide> i; <ide> test('format month', function (assert) { <ide> }); <ide> <ide> test('format week', function (assert) { <del> var expected = 'आइतबार आइत. आइ._सोमबार सोम. सो._मङ्गलबार मङ्गल. मङ्_बुधबार बुध. बु._बिहिबार बिहि. बि._शुक्रबार शुक्र. शु._शनिबार शनि. श.'.split('_'), i; <add> var expected = 'आइतबार आइत. आ._सोमबार सोम. सो._मङ्गलबार मङ्गल. मं._बुधबार बुध. बु._बिहिबार बिहि. बि._शुक्रबार शुक्र. शु._शनिबार शनि. श.'.split('_'), i; <ide> for (i = 0; i < expected.length; i++) { <ide> assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); <ide> } <ide> }); <ide> <ide> test('from', function (assert) { <ide> var start = moment([2007, 1, 28]); <del> assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'केही समय', '44 seconds = a few seconds'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'केही क्षण', '44 seconds = a few seconds'); <ide> assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'एक मिनेट', '45 seconds = a minute'); <ide> assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'एक मिनेट', '89 seconds = a minute'); <ide> assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '२ मिनेट', '90 seconds = 2 minutes'); <ide> test('from', function (assert) { <ide> }); <ide> <ide> test('suffix', function (assert) { <del> assert.equal(moment(30000).from(0), 'केही समयमा', 'prefix'); <del> assert.equal(moment(0).from(30000), 'केही समय अगाडी', 'suffix'); <add> assert.equal(moment(30000).from(0), 'केही क्षणमा', 'prefix'); <add> assert.equal(moment(0).from(30000), 'केही क्षण अगाडि', 'suffix'); <ide> }); <ide> <ide> test('now from now', function (assert) { <del> assert.equal(moment().fromNow(), 'केही समय अगाडी', 'now from now should display as in the past'); <add> assert.equal(moment().fromNow(), 'केही क्षण अगाडि', 'now from now should display as in the past'); <ide> }); <ide> <ide> test('fromNow', function (assert) { <del> assert.equal(moment().add({s: 30}).fromNow(), 'केही समयमा', 'केही समयमा'); <add> assert.equal(moment().add({s: 30}).fromNow(), 'केही क्षणमा', 'केही क्षणमा'); <ide> assert.equal(moment().add({d: 5}).fromNow(), '५ दिनमा', '५ दिनमा'); <ide> }); <ide> <ide> test('calendar day', function (assert) { <ide> var a = moment().hours(2).minutes(0).seconds(0); <ide> <del> assert.equal(moment(a).calendar(), 'आज रातीको २:०० बजे', 'today at the same time'); <del> assert.equal(moment(a).add({m: 25}).calendar(), 'आज रातीको २:२५ बजे', 'Now plus 25 min'); <add> assert.equal(moment(a).calendar(), 'आज रातिको २:०० बजे', 'today at the same time'); <add> assert.equal(moment(a).add({m: 25}).calendar(), 'आज रातिको २:२५ बजे', 'Now plus 25 min'); <ide> assert.equal(moment(a).add({h: 1}).calendar(), 'आज बिहानको ३:०० बजे', 'Now plus 1 hour'); <del> assert.equal(moment(a).add({d: 1}).calendar(), 'भोली रातीको २:०० बजे', 'tomorrow at the same time'); <del> assert.equal(moment(a).subtract({h: 1}).calendar(), 'आज रातीको १:०० बजे', 'Now minus 1 hour'); <del> assert.equal(moment(a).subtract({d: 1}).calendar(), 'हिजो रातीको २:०० बजे', 'yesterday at the same time'); <add> assert.equal(moment(a).add({d: 1}).calendar(), 'भोलि रातिको २:०० बजे', 'tomorrow at the same time'); <add> assert.equal(moment(a).subtract({h: 1}).calendar(), 'आज रातिको १:०० बजे', 'Now minus 1 hour'); <add> assert.equal(moment(a).subtract({d: 1}).calendar(), 'हिजो रातिको २:०० बजे', 'yesterday at the same time'); <ide> }); <ide> <ide> test('calendar next week', function (assert) { <ide> test('calendar all else', function (assert) { <ide> }); <ide> <ide> test('meridiem', function (assert) { <del> assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), 'राती', 'before dawn'); <add> assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), 'राति', 'before dawn'); <ide> assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), 'बिहान', 'morning'); <ide> assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), 'दिउँसो', 'during day'); <del> assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), 'बेलुका', 'evening'); <add> assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), 'साँझ', 'evening'); <ide> assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), 'साँझ', 'late evening'); <del> assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), 'राती', 'night'); <add> assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), 'राति', 'night'); <ide> <del> assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), 'राती', 'before dawn'); <add> assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), 'राति', 'before dawn'); <ide> assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), 'बिहान', 'morning'); <ide> assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), 'दिउँसो', 'during day'); <del> assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), 'बेलुका', 'evening'); <add> assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), 'साँझ', 'evening'); <ide> assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), 'साँझ', 'late evening'); <del> assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), 'राती', 'night'); <add> assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), 'राति', 'night'); <ide> }); <ide> <ide> test('weeks year starting sunday', function (assert) { <del> assert.equal(moment([2011, 11, 26]).week(), 1, 'Dec 26 2011 should be week 1'); <del> assert.equal(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1'); <del> assert.equal(moment([2012, 0, 2]).week(), 2, 'Jan 2 2012 should be week 2'); <del> assert.equal(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2'); <del> assert.equal(moment([2012, 0, 9]).week(), 3, 'Jan 9 2012 should be week 3'); <add> assert.equal(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1'); <add> assert.equal(moment([2012, 0, 7]).week(), 1, 'Jan 7 2012 should be week 1'); <add> assert.equal(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2'); <add> assert.equal(moment([2012, 0, 14]).week(), 2, 'Jan 14 2012 should be week 2'); <add> assert.equal(moment([2012, 0, 15]).week(), 3, 'Jan 15 2012 should be week 3'); <ide> }); <ide> <ide> test('weeks year starting monday', function (assert) { <del> assert.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1'); <del> assert.equal(moment([2007, 0, 7]).week(), 1, 'Jan 7 2007 should be week 1'); <del> assert.equal(moment([2007, 0, 8]).week(), 2, 'Jan 8 2007 should be week 2'); <del> assert.equal(moment([2007, 0, 14]).week(), 2, 'Jan 14 2007 should be week 2'); <del> assert.equal(moment([2007, 0, 15]).week(), 3, 'Jan 15 2007 should be week 3'); <add> assert.equal(moment([2006, 11, 31]).week(), 1, 'Dec 31 2006 should be week 1'); <add> assert.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1'); <add> assert.equal(moment([2007, 0, 6]).week(), 1, 'Jan 6 2007 should be week 1'); <add> assert.equal(moment([2007, 0, 7]).week(), 2, 'Jan 7 2007 should be week 2'); <add> assert.equal(moment([2007, 0, 13]).week(), 2, 'Jan 13 2007 should be week 2'); <add> assert.equal(moment([2007, 0, 14]).week(), 3, 'Jan 14 2007 should be week 3'); <ide> }); <ide> <ide> test('weeks year starting tuesday', function (assert) { <del> assert.equal(moment([2007, 11, 31]).week(), 1, 'Dec 31 2007 should be week 1'); <add> assert.equal(moment([2007, 11, 29]).week(), 52, 'Dec 29 2007 should be week 52'); <ide> assert.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1'); <del> assert.equal(moment([2008, 0, 6]).week(), 1, 'Jan 6 2008 should be week 1'); <del> assert.equal(moment([2008, 0, 7]).week(), 2, 'Jan 7 2008 should be week 2'); <del> assert.equal(moment([2008, 0, 13]).week(), 2, 'Jan 13 2008 should be week 2'); <del> assert.equal(moment([2008, 0, 14]).week(), 3, 'Jan 14 2008 should be week 3'); <add> assert.equal(moment([2008, 0, 5]).week(), 1, 'Jan 5 2008 should be week 1'); <add> assert.equal(moment([2008, 0, 6]).week(), 2, 'Jan 6 2008 should be week 2'); <add> assert.equal(moment([2008, 0, 12]).week(), 2, 'Jan 12 2008 should be week 2'); <add> assert.equal(moment([2008, 0, 13]).week(), 3, 'Jan 13 2008 should be week 3'); <ide> }); <ide> <ide> test('weeks year starting wednesday', function (assert) { <del> assert.equal(moment([2002, 11, 30]).week(), 1, 'Dec 30 2002 should be week 1'); <add> assert.equal(moment([2002, 11, 29]).week(), 1, 'Dec 29 2002 should be week 1'); <ide> assert.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1'); <del> assert.equal(moment([2003, 0, 5]).week(), 1, 'Jan 5 2003 should be week 1'); <del> assert.equal(moment([2003, 0, 6]).week(), 2, 'Jan 6 2003 should be week 2'); <del> assert.equal(moment([2003, 0, 12]).week(), 2, 'Jan 12 2003 should be week 2'); <del> assert.equal(moment([2003, 0, 13]).week(), 3, 'Jan 13 2003 should be week 3'); <add> assert.equal(moment([2003, 0, 4]).week(), 1, 'Jan 4 2003 should be week 1'); <add> assert.equal(moment([2003, 0, 5]).week(), 2, 'Jan 5 2003 should be week 2'); <add> assert.equal(moment([2003, 0, 11]).week(), 2, 'Jan 11 2003 should be week 2'); <add> assert.equal(moment([2003, 0, 12]).week(), 3, 'Jan 12 2003 should be week 3'); <ide> }); <ide> <ide> test('weeks year starting thursday', function (assert) { <del> assert.equal(moment([2008, 11, 29]).week(), 1, 'Dec 29 2008 should be week 1'); <add> assert.equal(moment([2008, 11, 28]).week(), 1, 'Dec 28 2008 should be week 1'); <ide> assert.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1'); <del> assert.equal(moment([2009, 0, 4]).week(), 1, 'Jan 4 2009 should be week 1'); <del> assert.equal(moment([2009, 0, 5]).week(), 2, 'Jan 5 2009 should be week 2'); <del> assert.equal(moment([2009, 0, 11]).week(), 2, 'Jan 11 2009 should be week 2'); <del> assert.equal(moment([2009, 0, 12]).week(), 3, 'Jan 12 2009 should be week 3'); <add> assert.equal(moment([2009, 0, 3]).week(), 1, 'Jan 3 2009 should be week 1'); <add> assert.equal(moment([2009, 0, 4]).week(), 2, 'Jan 4 2009 should be week 2'); <add> assert.equal(moment([2009, 0, 10]).week(), 2, 'Jan 10 2009 should be week 2'); <add> assert.equal(moment([2009, 0, 11]).week(), 3, 'Jan 11 2009 should be week 3'); <ide> }); <ide> <ide> test('weeks year starting friday', function (assert) { <del> assert.equal(moment([2009, 11, 28]).week(), 1, 'Dec 28 2009 should be week 1'); <add> assert.equal(moment([2009, 11, 27]).week(), 1, 'Dec 27 2009 should be week 1'); <ide> assert.equal(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1'); <del> assert.equal(moment([2010, 0, 3]).week(), 1, 'Jan 3 2010 should be week 1'); <del> assert.equal(moment([2010, 0, 4]).week(), 2, 'Jan 4 2010 should be week 2'); <del> assert.equal(moment([2010, 0, 10]).week(), 2, 'Jan 10 2010 should be week 2'); <del> assert.equal(moment([2010, 0, 11]).week(), 3, 'Jan 11 2010 should be week 3'); <add> assert.equal(moment([2010, 0, 2]).week(), 1, 'Jan 2 2010 should be week 1'); <add> assert.equal(moment([2010, 0, 3]).week(), 2, 'Jan 3 2010 should be week 2'); <add> assert.equal(moment([2010, 0, 9]).week(), 2, 'Jan 9 2010 should be week 2'); <add> assert.equal(moment([2010, 0, 10]).week(), 3, 'Jan 10 2010 should be week 3'); <ide> }); <ide> <ide> test('weeks year starting saturday', function (assert) { <del> assert.equal(moment([2010, 11, 27]).week(), 1, 'Dec 27 2010 should be week 1'); <add> assert.equal(moment([2010, 11, 26]).week(), 1, 'Dec 26 2010 should be week 1'); <ide> assert.equal(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1'); <del> assert.equal(moment([2011, 0, 2]).week(), 1, 'Jan 2 2011 should be week 1'); <del> assert.equal(moment([2011, 0, 3]).week(), 2, 'Jan 3 2011 should be week 2'); <del> assert.equal(moment([2011, 0, 9]).week(), 2, 'Jan 9 2011 should be week 2'); <del> assert.equal(moment([2011, 0, 10]).week(), 3, 'Jan 10 2011 should be week 3'); <add> assert.equal(moment([2011, 0, 2]).week(), 2, 'Jan 2 2011 should be week 2'); <add> assert.equal(moment([2011, 0, 8]).week(), 2, 'Jan 8 2011 should be week 2'); <add> assert.equal(moment([2011, 0, 9]).week(), 3, 'Jan 9 2011 should be week 3'); <ide> }); <ide> <add> <ide> test('weeks year starting sunday formatted', function (assert) { <del> assert.equal(moment([2011, 11, 26]).format('w ww wo'), '१ ०१ १', 'Dec 26 2011 should be week 1'); <add> assert.equal(moment([2011, 11, 26]).format('w ww wo'), '५३ ५३ ५३', 'Dec 26 2011 should be week 53'); <ide> assert.equal(moment([2012, 0, 1]).format('w ww wo'), '१ ०१ १', 'Jan 1 2012 should be week 1'); <del> assert.equal(moment([2012, 0, 2]).format('w ww wo'), '२ ०२ २', 'Jan 2 2012 should be week 2'); <add> assert.equal(moment([2012, 0, 2]).format('w ww wo'), '१ ०१ १', 'Jan 2 2012 should be week 1'); <ide> assert.equal(moment([2012, 0, 8]).format('w ww wo'), '२ ०२ २', 'Jan 8 2012 should be week 2'); <del> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '३ ०३ ३', 'Jan 9 2012 should be week 3'); <add> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '२ ०२ २', 'Jan 9 2012 should be week 2'); <ide> }); <ide> <ide> test('lenient ordinal parsing', function (assert) {
2
Text
Text
add section on pooling
6caff8ec377cc2d16fe66da4bc48721dcb1df055
<ide><path>guide/english/machine-learning/neural-networks/convolutional-neural-networks/index.md <ide> Convolutional Neural Networks (ConvNets or CNNs) are a category of Neural Networ <ide> <ide> CNNs are biologically inspired models on how mammals visually perceive things. When we see something a layer of neurons are activated in our brain. The very same concept is working here too. The birth of CNN is inspired by Local connection, layering, spatial invariance. Compared to the similar size of feed forward neural network the CNN only require much fewer connections and parameters, hence they are easier to train and also the time consumption is less. CNN is effective for both the high level and low level features in dataset. Another important factor of CNN is the depth of the layers. <ide> <add>### Pooling <add> <add>Many effective CNN models add pooling layers between each convolution layer. A pooling layer subsamples the image in some way, effectively making the image "fuzzier" between convolution layers. One example is called "max pooling," where you run a kernel (can be any size, 2x2 or 3x3 are common choices) over the input layer that only passes the highest value into the next layer. This destroys a lot of information, but reduces computational load and forces the CNN to learn more general relationships (translational invariance) as the number of parameters are reduced. Pooling layers do not have associated weights. <add> <ide> ### Suggested links : <ide> - Stanford CS231n [Lecture 5 Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) <ide> - Stanford CS231n [Lecture 9 CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y&t=2384s)
1
Python
Python
add disambiguation code to load
4d2dd4b763a33fb48129190377a759bf394db386
<ide><path>io.py <ide> <ide> __all__ = ['savetxt', 'loadtxt', <ide> 'load', 'loads', <del> 'save', 'savez', <add> 'save', 'savez', <ide> 'packbits', 'unpackbits', <ide> 'DataSource', <ide> ] <ide> <ide> _file = file <ide> <add>class _bagobj(object): <add> def __init__(self, **kwds): <add> self.__dict__.update(kwds) <add> <add>class _npz_obj(dict): <add> pass <add> <ide> def load(file): <ide> """Load a binary file. <ide> <del> Read a binary file (either a pickle or a binary NumPy array file .npy) and <del> return the resulting arrays. <add> Read a binary file (either a pickle, or a binary .npy/.npz file) and <add> return the result. <ide> <ide> Parameters <ide> ---------- <ide> file : file-like object or string <del> the file to read <add> the file to read. It must support seek and read methods <ide> <ide> Returns <ide> ------- <ide> result : array, tuple, dict, etc. <ide> data stored in the file. <ide> If file contains pickle data, then whatever is stored in the pickle is returned. <ide> If the file is .npy file than an array is returned. <del> If the file is .npz file than a dictionary-like object is returned which returns the <del> an array for each name in the file. <add> If the file is .npz file than a dictionary-like object is returned which has a <add> key:name, value:array pair for every name in the file. <ide> """ <ide> if isinstance(file, type("")): <del> file = _file(file,"rb") <del> # Code to distinguish from pickle and NumPy binary <add> fid = _file(file,"rb") <add> else: <add> fid = file <add> # Code to distinguish from NumPy binary files and pickles. <ide> # <add> magic = fid.read(6) <add> fid.seek(-6,1) # back-up <add> if magic == 'PK\x03\x04': # zip-file (assume .npz) <add> return _zip_load(fid) <add> elif magic == '\x93NUMPY': # .npy file <add> return _npy_load(fid) <add> else: # Try a pickle <add> try: <add> return _cload(fid) <add> except: <add> raise IOError, "Failure to interpret file %s as a pickle" % repr(file) <ide> <del> # if pickle: <del> return _cload(file) <del> <del> <del> <del>class _bagobj(object): <del> def __init__(self, **kwds): <del> self.__dict__.update(kwds) <del> <del>class _npz_obj(dict): <del> pass <ide> <ide> def save(file, arr): <ide> """Save an array to a binary file (specified as a string or file-like object).
1
Mixed
Javascript
add recursive watch to linux
17ae2ab7509c8379e842e606a011f688fcbcf7f2
<ide><path>doc/api/fs.md <ide> The `atime` and `mtime` arguments follow these rules: <ide> <!-- YAML <ide> added: v0.5.10 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/45098 <add> description: Added recursive support for Linux, AIX and IBMi. <ide> - version: <ide> - v15.9.0 <ide> - v14.17.0 <ide> the returned {fs.FSWatcher}. <ide> The `fs.watch` API is not 100% consistent across platforms, and is <ide> unavailable in some situations. <ide> <del>The recursive option is only supported on macOS and Windows. <del>An `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` exception will be thrown <del>when the option is used on a platform that does not support it. <del> <ide> On Windows, no events will be emitted if the watched directory is moved or <ide> renamed. An `EPERM` error is reported when the watched directory is deleted. <ide> <ide><path>lib/fs.js <ide> const { <ide> <ide> const pathModule = require('path'); <ide> const { isArrayBufferView } = require('internal/util/types'); <add>const nonNativeWatcher = require('internal/fs/recursive_watch'); <ide> <ide> // We need to get the statValues from the binding at the callsite since <ide> // it's re-initialized after deserialization. <ide> const { <ide> codes: { <ide> ERR_FS_FILE_TOO_LARGE, <ide> ERR_INVALID_ARG_VALUE, <del> ERR_FEATURE_UNAVAILABLE_ON_PLATFORM, <ide> }, <ide> AbortError, <ide> uvErrmapGet, <ide> let FileWriteStream; <ide> const isWindows = process.platform === 'win32'; <ide> const isOSX = process.platform === 'darwin'; <ide> <del> <ide> function showTruncateDeprecation() { <ide> if (truncateWarn) { <ide> process.emitWarning( <ide> function watch(filename, options, listener) { <ide> <ide> if (options.persistent === undefined) options.persistent = true; <ide> if (options.recursive === undefined) options.recursive = false; <del> if (options.recursive && !(isOSX || isWindows)) <del> throw new ERR_FEATURE_UNAVAILABLE_ON_PLATFORM('watch recursively'); <del> const watcher = new watchers.FSWatcher(); <del> watcher[watchers.kFSWatchStart](filename, <del> options.persistent, <del> options.recursive, <del> options.encoding); <add> <add> let watcher; <add> <add> // TODO(anonrig): Remove this when/if libuv supports it. <add> // As of November 2022, libuv does not support recursive file watch on all platforms, <add> // e.g. Linux due to the limitations of inotify. <add> if (options.recursive && !isOSX && !isWindows) { <add> watcher = new nonNativeWatcher.FSWatcher(options); <add> watcher[watchers.kFSWatchStart](filename); <add> } else { <add> watcher = new watchers.FSWatcher(); <add> watcher[watchers.kFSWatchStart](filename, <add> options.persistent, <add> options.recursive, <add> options.encoding); <add> } <ide> <ide> if (listener) { <ide> watcher.addListener('change', listener); <ide><path>lib/internal/fs/promises.js <ide> const { <ide> } = require('internal/util'); <ide> const { EventEmitterMixin } = require('internal/event_target'); <ide> const { StringDecoder } = require('string_decoder'); <del>const { watch } = require('internal/fs/watchers'); <add>const { kFSWatchStart, watch } = require('internal/fs/watchers'); <add>const nonNativeWatcher = require('internal/fs/recursive_watch'); <ide> const { isIterable } = require('internal/streams/utils'); <ide> const assert = require('internal/assert'); <ide> <ide> const getDirectoryEntriesPromise = promisify(getDirents); <ide> const validateRmOptionsPromise = promisify(validateRmOptions); <ide> <ide> const isWindows = process.platform === 'win32'; <add>const isOSX = process.platform === 'darwin'; <ide> <ide> let cpPromises; <ide> function lazyLoadCpPromises() { <ide> async function readFile(path, options) { <ide> return handleFdClose(readFileHandle(fd, options), fd.close); <ide> } <ide> <add>async function* _watch(filename, options = kEmptyObject) { <add> validateObject(options, 'options'); <add> <add> if (options.recursive != null) { <add> validateBoolean(options.recursive, 'options.recursive'); <add> <add> // TODO(anonrig): Remove this when/if libuv supports it. <add> // As of November 2022, libuv does not support recursive file watch on all platforms, <add> // e.g. Linux due to the limitations of inotify. <add> if (options.recursive && !isOSX && !isWindows) { <add> const watcher = new nonNativeWatcher.FSWatcher(options); <add> await watcher[kFSWatchStart](filename); <add> yield* watcher; <add> return; <add> } <add> } <add> <add> yield* watch(filename, options); <add>} <add> <ide> module.exports = { <ide> exports: { <ide> access, <ide> module.exports = { <ide> writeFile, <ide> appendFile, <ide> readFile, <del> watch, <add> watch: !isOSX && !isWindows ? _watch : watch, <ide> constants, <ide> }, <ide> <ide><path>lib/internal/fs/recursive_watch.js <add>'use strict'; <add> <add>const { <add> ArrayPrototypePush, <add> SafePromiseAllReturnVoid, <add> Promise, <add> PromisePrototypeThen, <add> SafeMap, <add> SafeSet, <add> StringPrototypeStartsWith, <add> SymbolAsyncIterator, <add>} = primordials; <add> <add>const { EventEmitter } = require('events'); <add>const assert = require('internal/assert'); <add>const { <add> AbortError, <add> codes: { <add> ERR_INVALID_ARG_VALUE, <add> }, <add>} = require('internal/errors'); <add>const { getValidatedPath } = require('internal/fs/utils'); <add>const { kFSWatchStart, StatWatcher } = require('internal/fs/watchers'); <add>const { kEmptyObject } = require('internal/util'); <add>const { validateBoolean, validateAbortSignal } = require('internal/validators'); <add>const path = require('path'); <add> <add>let internalSync; <add>let internalPromises; <add> <add>function lazyLoadFsPromises() { <add> internalPromises ??= require('fs/promises'); <add> return internalPromises; <add>} <add> <add>function lazyLoadFsSync() { <add> internalSync ??= require('fs'); <add> return internalSync; <add>} <add> <add>async function traverse(dir, files = new SafeMap(), symbolicLinks = new SafeSet()) { <add> const { opendir } = lazyLoadFsPromises(); <add> <add> const filenames = await opendir(dir); <add> const subdirectories = []; <add> <add> for await (const file of filenames) { <add> const f = path.join(dir, file.name); <add> <add> files.set(f, file); <add> <add> // Do not follow symbolic links <add> if (file.isSymbolicLink()) { <add> symbolicLinks.add(f); <add> } else if (file.isDirectory()) { <add> ArrayPrototypePush(subdirectories, traverse(f, files)); <add> } <add> } <add> <add> await SafePromiseAllReturnVoid(subdirectories); <add> <add> return files; <add>} <add> <add>class FSWatcher extends EventEmitter { <add> #options = null; <add> #closed = false; <add> #files = new SafeMap(); <add> #symbolicFiles = new SafeSet(); <add> #rootPath = path.resolve(); <add> #watchingFile = false; <add> <add> constructor(options = kEmptyObject) { <add> super(); <add> <add> assert(typeof options === 'object'); <add> <add> const { persistent, recursive, signal, encoding } = options; <add> <add> // TODO(anonrig): Add non-recursive support to non-native-watcher for IBMi & AIX support. <add> if (recursive != null) { <add> validateBoolean(recursive, 'options.recursive'); <add> } <add> <add> if (persistent != null) { <add> validateBoolean(persistent, 'options.persistent'); <add> } <add> <add> if (signal != null) { <add> validateAbortSignal(signal, 'options.signal'); <add> } <add> <add> if (encoding != null) { <add> // This is required since on macOS and Windows it throws ERR_INVALID_ARG_VALUE <add> if (typeof encoding !== 'string') { <add> throw new ERR_INVALID_ARG_VALUE(encoding, 'options.encoding'); <add> } <add> } <add> <add> this.#options = { persistent, recursive, signal, encoding }; <add> } <add> <add> close() { <add> if (this.#closed) { <add> return; <add> } <add> <add> const { unwatchFile } = lazyLoadFsSync(); <add> this.#closed = true; <add> <add> for (const file of this.#files.keys()) { <add> unwatchFile(file); <add> } <add> <add> this.#files.clear(); <add> this.#symbolicFiles.clear(); <add> this.emit('close'); <add> } <add> <add> #unwatchFiles(file) { <add> const { unwatchFile } = lazyLoadFsSync(); <add> <add> this.#symbolicFiles.delete(file); <add> <add> for (const filename of this.#files.keys()) { <add> if (StringPrototypeStartsWith(filename, file)) { <add> unwatchFile(filename); <add> } <add> } <add> } <add> <add> async #watchFolder(folder) { <add> const { opendir } = lazyLoadFsPromises(); <add> <add> try { <add> const files = await opendir(folder); <add> <add> for await (const file of files) { <add> if (this.#closed) { <add> break; <add> } <add> <add> const f = path.join(folder, file.name); <add> <add> if (!this.#files.has(f)) { <add> this.emit('change', 'rename', path.relative(this.#rootPath, f)); <add> <add> if (file.isSymbolicLink()) { <add> this.#symbolicFiles.add(f); <add> } <add> <add> if (file.isFile()) { <add> this.#watchFile(f); <add> } else { <add> this.#files.set(f, file); <add> <add> if (file.isDirectory() && !file.isSymbolicLink()) { <add> await this.#watchFolder(f); <add> } <add> } <add> } <add> } <add> } catch (error) { <add> this.emit('error', error); <add> } <add> } <add> <add> #watchFile(file) { <add> if (this.#closed) { <add> return; <add> } <add> <add> const { watchFile } = lazyLoadFsSync(); <add> const existingStat = this.#files.get(file); <add> <add> watchFile(file, { <add> persistent: this.#options.persistent, <add> }, (currentStats, previousStats) => { <add> if (existingStat && !existingStat.isDirectory() && <add> currentStats.nlink !== 0 && existingStat.mtimeMs === currentStats.mtimeMs) { <add> return; <add> } <add> <add> this.#files.set(file, currentStats); <add> <add> if (currentStats.birthtimeMs === 0 && previousStats.birthtimeMs !== 0) { <add> // The file is now deleted <add> this.#files.delete(file); <add> this.emit('change', 'rename', path.relative(this.#rootPath, file)); <add> this.#unwatchFiles(file); <add> } else if (file === this.#rootPath && this.#watchingFile) { <add> // This case will only be triggered when watching a file with fs.watch <add> this.emit('change', 'change', path.basename(file)); <add> } else if (this.#symbolicFiles.has(file)) { <add> // Stats from watchFile does not return correct value for currentStats.isSymbolicLink() <add> // Since it is only valid when using fs.lstat(). Therefore, check the existing symbolic files. <add> this.emit('change', 'rename', path.relative(this.#rootPath, file)); <add> } else if (currentStats.isDirectory()) { <add> this.#watchFolder(file); <add> } <add> }); <add> } <add> <add> [kFSWatchStart](filename) { <add> filename = path.resolve(getValidatedPath(filename)); <add> <add> try { <add> const file = lazyLoadFsSync().statSync(filename); <add> <add> this.#rootPath = filename; <add> this.#closed = false; <add> this.#watchingFile = file.isFile(); <add> <add> if (file.isDirectory()) { <add> this.#files.set(filename, file); <add> <add> PromisePrototypeThen( <add> traverse(filename, this.#files, this.#symbolicFiles), <add> () => { <add> for (const f of this.#files.keys()) { <add> this.#watchFile(f); <add> } <add> }, <add> ); <add> } else { <add> this.#watchFile(filename); <add> } <add> } catch (error) { <add> if (error.code === 'ENOENT') { <add> error.filename = filename; <add> throw error; <add> } <add> } <add> <add> } <add> <add> ref() { <add> this.#files.forEach((file) => { <add> if (file instanceof StatWatcher) { <add> file.ref(); <add> } <add> }); <add> } <add> <add> unref() { <add> this.#files.forEach((file) => { <add> if (file instanceof StatWatcher) { <add> file.unref(); <add> } <add> }); <add> } <add> <add> [SymbolAsyncIterator]() { <add> const { signal } = this.#options; <add> const promiseExecutor = signal == null ? <add> (resolve) => { <add> this.once('change', (eventType, filename) => { <add> resolve({ __proto__: null, value: { eventType, filename } }); <add> }); <add> } : (resolve, reject) => { <add> const onAbort = () => reject(new AbortError(undefined, { cause: signal.reason })); <add> if (signal.aborted) return onAbort(); <add> signal.addEventListener('abort', onAbort, { __proto__: null, once: true }); <add> this.once('change', (eventType, filename) => { <add> signal.removeEventListener('abort', onAbort); <add> resolve({ __proto__: null, value: { eventType, filename } }); <add> }); <add> }; <add> return { <add> next: () => (this.#closed ? <add> { __proto__: null, done: true } : <add> new Promise(promiseExecutor)), <add> [SymbolAsyncIterator]() { return this; }, <add> }; <add> } <add>} <add> <add>module.exports = { <add> FSWatcher, <add> kFSWatchStart, <add>}; <ide><path>test/parallel/test-bootstrap-modules.js <ide> const expectedModules = new Set([ <ide> 'NativeModule internal/fs/dir', <ide> 'NativeModule internal/fs/promises', <ide> 'NativeModule internal/fs/read_file_context', <add> 'NativeModule internal/fs/recursive_watch', <ide> 'NativeModule internal/fs/rimraf', <ide> 'NativeModule internal/fs/utils', <ide> 'NativeModule internal/fs/watchers', <ide><path>test/parallel/test-fs-watch-close-when-destroyed.js <ide> <ide> const common = require('../common'); <ide> <add>// fs-watch on folders have limited capability in AIX. <add>// The testcase makes use of folder watching, and causes <add>// hang. This behavior is documented. Skip this for AIX. <add> <add>if (common.isAIX) <add> common.skip('folder watch capability is limited in AIX.'); <add> <ide> if (common.isIBMi) <ide> common.skip('IBMi does not support `fs.watch()`'); <ide> <ide><path>test/parallel/test-fs-watch-encoding.js <ide> const common = require('../common'); <ide> if (common.isAIX) <ide> common.skip('folder watch capability is limited in AIX.'); <ide> <add>if (common.isIBMi) <add> common.skip('IBMi does not support `fs.watch()`'); <add> <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> <ide><path>test/parallel/test-fs-watch-enoent.js <ide> tmpdir.refresh(); <ide> const validateError = (err) => { <ide> assert.strictEqual(err.path, nonexistentFile); <ide> assert.strictEqual(err.filename, nonexistentFile); <del> assert.strictEqual(err.syscall, 'watch'); <add> assert.ok(err.syscall === 'watch' || err.syscall === 'stat'); <ide> if (err.code === 'ENOENT') { <del> assert.strictEqual( <del> err.message, <del> `ENOENT: no such file or directory, watch '${nonexistentFile}'`); <add> assert.ok(err.message.startsWith('ENOENT: no such file or directory')); <ide> assert.strictEqual(err.errno, UV_ENOENT); <ide> assert.strictEqual(err.code, 'ENOENT'); <ide> } else { // AIX <ide> tmpdir.refresh(); <ide> } <ide> <ide> { <del> const file = path.join(tmpdir.path, 'file-to-watch'); <del> fs.writeFileSync(file, 'test'); <del> const watcher = fs.watch(file, common.mustNotCall()); <add> if (common.isOSX || common.isWindows) { <add> const file = path.join(tmpdir.path, 'file-to-watch'); <add> fs.writeFileSync(file, 'test'); <add> const watcher = fs.watch(file, common.mustNotCall()); <ide> <del> const validateError = (err) => { <del> assert.strictEqual(err.path, nonexistentFile); <del> assert.strictEqual(err.filename, nonexistentFile); <del> assert.strictEqual( <del> err.message, <del> `ENOENT: no such file or directory, watch '${nonexistentFile}'`); <del> assert.strictEqual(err.errno, UV_ENOENT); <del> assert.strictEqual(err.code, 'ENOENT'); <del> assert.strictEqual(err.syscall, 'watch'); <del> fs.unlinkSync(file); <del> return true; <del> }; <add> const validateError = (err) => { <add> assert.strictEqual(err.path, nonexistentFile); <add> assert.strictEqual(err.filename, nonexistentFile); <add> assert.strictEqual( <add> err.message, <add> `ENOENT: no such file or directory, watch '${nonexistentFile}'`); <add> assert.strictEqual(err.errno, UV_ENOENT); <add> assert.strictEqual(err.code, 'ENOENT'); <add> assert.strictEqual(err.syscall, 'watch'); <add> fs.unlinkSync(file); <add> return true; <add> }; <ide> <del> watcher.on('error', common.mustCall(validateError)); <add> watcher.on('error', common.mustCall(validateError)); <ide> <del> // Simulate the invocation from the binding <del> watcher._handle.onchange(UV_ENOENT, 'ENOENT', nonexistentFile); <add> // Simulate the invocation from the binding <add> watcher._handle.onchange(UV_ENOENT, 'ENOENT', nonexistentFile); <add> } <ide> } <ide><path>test/parallel/test-fs-watch-recursive-promise.js <add>'use strict'; <add> <add>const common = require('../common'); <add> <add>if (common.isIBMi) <add> common.skip('IBMi does not support `fs.watch()`'); <add> <add>// fs-watch on folders have limited capability in AIX. <add>// The testcase makes use of folder watching, and causes <add>// hang. This behavior is documented. Skip this for AIX. <add> <add>if (common.isAIX) <add> common.skip('folder watch capability is limited in AIX.'); <add> <add>const assert = require('assert'); <add>const path = require('path'); <add>const fs = require('fs/promises'); <add>const fsSync = require('fs'); <add> <add>const tmpdir = require('../common/tmpdir'); <add>const testDir = tmpdir.path; <add>tmpdir.refresh(); <add> <add>(async function run() { <add> // Add a file to already watching folder <add> <add> const testsubdir = await fs.mkdtemp(testDir + path.sep); <add> const file = '1.txt'; <add> const filePath = path.join(testsubdir, file); <add> const watcher = fs.watch(testsubdir, { recursive: true }); <add> <add> let interval; <add> <add> process.on('exit', function() { <add> assert.ok(interval === null, 'watcher Object was not closed'); <add> }); <add> <add> process.nextTick(common.mustCall(() => { <add> interval = setInterval(() => { <add> fsSync.writeFileSync(filePath, 'world'); <add> }, 500); <add> })); <add> <add> for await (const payload of watcher) { <add> const { eventType, filename } = payload; <add> <add> assert.ok(eventType === 'change' || eventType === 'rename'); <add> <add> if (filename === file) { <add> break; <add> } <add> } <add> <add> clearInterval(interval); <add> interval = null; <add>})().then(common.mustCall()); <add> <add>(async function() { <add> // Test that aborted AbortSignal are reported. <add> const testsubdir = await fs.mkdtemp(testDir + path.sep); <add> const error = new Error(); <add> const watcher = fs.watch(testsubdir, { recursive: true, signal: AbortSignal.abort(error) }); <add> await assert.rejects(async () => { <add> // eslint-disable-next-line no-unused-vars <add> for await (const _ of watcher); <add> }, { code: 'ABORT_ERR', cause: error }); <add>})().then(common.mustCall()); <add> <add>(async function() { <add> // Test that with AbortController. <add> const testsubdir = await fs.mkdtemp(testDir + path.sep); <add> const file = '2.txt'; <add> const filePath = path.join(testsubdir, file); <add> const error = new Error(); <add> const ac = new AbortController(); <add> const watcher = fs.watch(testsubdir, { recursive: true, signal: ac.signal }); <add> let interval; <add> process.on('exit', function() { <add> assert.ok(interval === null, 'watcher Object was not closed'); <add> }); <add> process.nextTick(common.mustCall(() => { <add> interval = setInterval(() => { <add> fsSync.writeFileSync(filePath, 'world'); <add> }, 50); <add> ac.abort(error); <add> })); <add> await assert.rejects(async () => { <add> for await (const { eventType } of watcher) { <add> assert.ok(eventType === 'change' || eventType === 'rename'); <add> } <add> }, { code: 'ABORT_ERR', cause: error }); <add> clearInterval(interval); <add> interval = null; <add>})().then(common.mustCall()); <ide><path>test/parallel/test-fs-watch-recursive-symlink.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const { setTimeout } = require('timers/promises'); <add> <add>if (common.isIBMi) <add> common.skip('IBMi does not support `fs.watch()`'); <add> <add>// fs-watch on folders have limited capability in AIX. <add>// The testcase makes use of folder watching, and causes <add>// hang. This behavior is documented. Skip this for AIX. <add> <add>if (common.isAIX) <add> common.skip('folder watch capability is limited in AIX.'); <add> <add>const assert = require('assert'); <add>const path = require('path'); <add>const fs = require('fs'); <add> <add>const tmpdir = require('../common/tmpdir'); <add>const testDir = tmpdir.path; <add>tmpdir.refresh(); <add> <add>(async () => { <add> // Add a recursive symlink to the parent folder <add> <add> const testDirectory = fs.mkdtempSync(testDir + path.sep); <add> <add> // Do not use `testDirectory` as base. It will hang the tests. <add> const rootDirectory = path.join(testDirectory, 'test-1'); <add> fs.mkdirSync(rootDirectory); <add> <add> const filePath = path.join(rootDirectory, 'file.txt'); <add> <add> const symlinkFolder = path.join(rootDirectory, 'symlink-folder'); <add> fs.symlinkSync(rootDirectory, symlinkFolder); <add> <add> <add> const watcher = fs.watch(rootDirectory, { recursive: true }); <add> let watcherClosed = false; <add> watcher.on('change', function(event, filename) { <add> assert.ok(event === 'rename', `Received ${event}`); <add> assert.ok(filename === path.basename(symlinkFolder) || filename === path.basename(filePath), `Received ${filename}`); <add> <add> if (filename === path.basename(filePath)) { <add> watcher.close(); <add> watcherClosed = true; <add> } <add> }); <add> <add> await setTimeout(common.platformTimeout(100)); <add> fs.writeFileSync(filePath, 'world'); <add> <add> process.once('exit', function() { <add> assert(watcherClosed, 'watcher Object was not closed'); <add> }); <add>})().then(common.mustCall()); <add> <add>(async () => { <add> // This test checks how a symlink to outside the tracking folder can trigger change <add> // tmp/sub-directory/tracking-folder/symlink-folder -> tmp/sub-directory <add> <add> const rootDirectory = fs.mkdtempSync(testDir + path.sep); <add> <add> const subDirectory = path.join(rootDirectory, 'sub-directory'); <add> fs.mkdirSync(subDirectory); <add> <add> const trackingSubDirectory = path.join(subDirectory, 'tracking-folder'); <add> fs.mkdirSync(trackingSubDirectory); <add> <add> const symlinkFolder = path.join(trackingSubDirectory, 'symlink-folder'); <add> fs.symlinkSync(subDirectory, symlinkFolder); <add> <add> const forbiddenFile = path.join(subDirectory, 'forbidden.txt'); <add> const acceptableFile = path.join(trackingSubDirectory, 'acceptable.txt'); <add> <add> const watcher = fs.watch(trackingSubDirectory, { recursive: true }); <add> let watcherClosed = false; <add> watcher.on('change', function(event, filename) { <add> // macOS will only change the following events: <add> // { event: 'rename', filename: 'symlink-folder' } <add> // { event: 'rename', filename: 'acceptable.txt' } <add> assert.ok(event === 'rename', `Received ${event}`); <add> assert.ok(filename === path.basename(symlinkFolder) || filename === path.basename(acceptableFile), `Received ${filename}`); <add> <add> if (filename === path.basename(acceptableFile)) { <add> watcher.close(); <add> watcherClosed = true; <add> } <add> }); <add> <add> await setTimeout(common.platformTimeout(100)); <add> fs.writeFileSync(forbiddenFile, 'world'); <add> await setTimeout(common.platformTimeout(100)); <add> fs.writeFileSync(acceptableFile, 'acceptable'); <add> <add> process.once('exit', function() { <add> assert(watcherClosed, 'watcher Object was not closed'); <add> }); <add>})().then(common.mustCall()); <ide><path>test/parallel/test-fs-watch-recursive.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>const { setTimeout } = require('timers/promises'); <ide> <add>if (common.isIBMi) <add> common.skip('IBMi does not support `fs.watch()`'); <add> <add>// fs-watch on folders have limited capability in AIX. <add>// The testcase makes use of folder watching, and causes <add>// hang. This behavior is documented. Skip this for AIX. <add> <add>if (common.isAIX) <add> common.skip('folder watch capability is limited in AIX.'); <ide> <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> const fs = require('fs'); <add>const { pathToFileURL } = require('url'); <ide> <ide> const tmpdir = require('../common/tmpdir'); <del> <ide> const testDir = tmpdir.path; <del>const filenameOne = 'watch.txt'; <del> <ide> tmpdir.refresh(); <ide> <del>const testsubdir = fs.mkdtempSync(testDir + path.sep); <del>const relativePathOne = path.join(path.basename(testsubdir), filenameOne); <del>const filepathOne = path.join(testsubdir, filenameOne); <add>(async () => { <add> // Add a file to already watching folder <add> <add> const rootDirectory = fs.mkdtempSync(testDir + path.sep); <add> const testDirectory = path.join(rootDirectory, 'test-1'); <add> fs.mkdirSync(testDirectory); <add> <add> const testFile = path.join(testDirectory, 'file-1.txt'); <add> <add> const watcher = fs.watch(testDirectory, { recursive: true }); <add> let watcherClosed = false; <add> watcher.on('change', function(event, filename) { <add> assert.ok(event === 'rename'); <add> <add> if (filename === path.basename(testFile)) { <add> watcher.close(); <add> watcherClosed = true; <add> } <add> }); <add> <add> await setTimeout(common.platformTimeout(100)); <add> fs.writeFileSync(testFile, 'world'); <add> <add> process.once('exit', function() { <add> assert(watcherClosed, 'watcher Object was not closed'); <add> }); <add>})().then(common.mustCall()); <add> <add>(async () => { <add> // Add a folder to already watching folder <add> <add> const rootDirectory = fs.mkdtempSync(testDir + path.sep); <add> const testDirectory = path.join(rootDirectory, 'test-2'); <add> fs.mkdirSync(testDirectory); <add> <add> const testFile = path.join(testDirectory, 'folder-2'); <add> <add> const watcher = fs.watch(testDirectory, { recursive: true }); <add> let watcherClosed = false; <add> watcher.on('change', function(event, filename) { <add> assert.ok(event === 'rename'); <add> <add> if (filename === path.basename(testFile)) { <add> watcher.close(); <add> watcherClosed = true; <add> } <add> }); <add> <add> await setTimeout(common.platformTimeout(100)); <add> fs.mkdirSync(testFile); <add> <add> process.once('exit', function() { <add> assert(watcherClosed, 'watcher Object was not closed'); <add> }); <add>})().then(common.mustCall()); <add> <add>(async () => { <add> // Add a file to newly created folder to already watching folder <add> <add> const rootDirectory = fs.mkdtempSync(testDir + path.sep); <add> const testDirectory = path.join(rootDirectory, 'test-3'); <add> fs.mkdirSync(testDirectory); <add> <add> const filePath = path.join(testDirectory, 'folder-3'); <add> <add> const childrenFile = 'file-4.txt'; <add> const childrenAbsolutePath = path.join(filePath, childrenFile); <add> const childrenRelativePath = path.join(path.basename(filePath), childrenFile); <add> <add> const watcher = fs.watch(testDirectory, { recursive: true }); <add> let watcherClosed = false; <add> watcher.on('change', function(event, filename) { <add> assert.ok(event === 'rename'); <add> assert.ok(filename === path.basename(filePath) || filename === childrenRelativePath); <add> <add> if (filename === childrenRelativePath) { <add> watcher.close(); <add> watcherClosed = true; <add> } <add> }); <add> <add> await setTimeout(common.platformTimeout(100)); <add> fs.mkdirSync(filePath); <add> await setTimeout(common.platformTimeout(100)); <add> fs.writeFileSync(childrenAbsolutePath, 'world'); <add> <add> process.once('exit', function() { <add> assert(watcherClosed, 'watcher Object was not closed'); <add> }); <add>})().then(common.mustCall()); <add> <add>(async () => { <add> // Add a file to subfolder of a watching folder <add> <add> const rootDirectory = fs.mkdtempSync(testDir + path.sep); <add> const testDirectory = path.join(rootDirectory, 'test-4'); <add> fs.mkdirSync(testDirectory); <add> <add> const file = 'folder-5'; <add> const filePath = path.join(testDirectory, file); <add> fs.mkdirSync(filePath); <add> <add> const subfolderPath = path.join(filePath, 'subfolder-6'); <add> fs.mkdirSync(subfolderPath); <add> <add> const childrenFile = 'file-7.txt'; <add> const childrenAbsolutePath = path.join(subfolderPath, childrenFile); <add> const relativePath = path.join(file, path.basename(subfolderPath), childrenFile); <add> <add> const watcher = fs.watch(testDirectory, { recursive: true }); <add> let watcherClosed = false; <add> watcher.on('change', function(event, filename) { <add> assert.ok(event === 'rename'); <add> <add> if (filename === relativePath) { <add> watcher.close(); <add> watcherClosed = true; <add> } <add> }); <add> <add> await setTimeout(common.platformTimeout(100)); <add> fs.writeFileSync(childrenAbsolutePath, 'world'); <add> <add> process.once('exit', function() { <add> assert(watcherClosed, 'watcher Object was not closed'); <add> }); <add>})().then(common.mustCall()); <add> <add>(async () => { <add> // Add a file to already watching folder, and use URL as the path <add> <add> const rootDirectory = fs.mkdtempSync(testDir + path.sep); <add> const testDirectory = path.join(rootDirectory, 'test-5'); <add> fs.mkdirSync(testDirectory); <add> <add> const filePath = path.join(testDirectory, 'file-8.txt'); <add> const url = pathToFileURL(testDirectory); <add> <add> const watcher = fs.watch(url, { recursive: true }); <add> let watcherClosed = false; <add> watcher.on('change', function(event, filename) { <add> assert.ok(event === 'rename'); <add> <add> if (filename === path.basename(filePath)) { <add> watcher.close(); <add> watcherClosed = true; <add> } <add> }); <add> <add> await setTimeout(common.platformTimeout(100)); <add> fs.writeFileSync(filePath, 'world'); <add> <add> process.on('exit', function() { <add> assert(watcherClosed, 'watcher Object was not closed'); <add> }); <add>})().then(common.mustCall()); <add> <add>(async () => { <add> // Watch a file (not a folder) using fs.watch <add> <add> const rootDirectory = fs.mkdtempSync(testDir + path.sep); <add> const testDirectory = path.join(rootDirectory, 'test-6'); <add> fs.mkdirSync(testDirectory); <add> <add> const filePath = path.join(testDirectory, 'only-file.txt'); <add> fs.writeFileSync(filePath, 'hello'); <add> <add> const watcher = fs.watch(filePath, { recursive: true }); <add> let watcherClosed = false; <add> let interval; <add> watcher.on('change', function(event, filename) { <add> assert.ok(event === 'change'); <add> <add> if (filename === path.basename(filePath)) { <add> clearInterval(interval); <add> interval = null; <add> watcher.close(); <add> watcherClosed = true; <add> } <add> }); <ide> <del>if (!common.isOSX && !common.isWindows) { <del> assert.throws(() => { fs.watch(testDir, { recursive: true }); }, <del> { code: 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM' }); <del> return; <del>} <del>const watcher = fs.watch(testDir, { recursive: true }); <add> interval = setInterval(() => { <add> fs.writeFileSync(filePath, 'world'); <add> }, common.platformTimeout(10)); <ide> <del>let watcherClosed = false; <del>watcher.on('change', function(event, filename) { <del> assert.ok(event === 'change' || event === 'rename'); <add> process.on('exit', function() { <add> assert(watcherClosed, 'watcher Object was not closed'); <add> assert.ok(interval === null, 'interval should have been null'); <add> }); <add>})().then(common.mustCall()); <ide> <del> // Ignore stale events generated by mkdir and other tests <del> if (filename !== relativePathOne) <del> return; <add>(async () => { <add> // Handle non-boolean values for options.recursive <ide> <del> if (common.isOSX) { <del> clearInterval(interval); <add> if (!common.isWindows && !common.isOSX) { <add> assert.throws(() => { <add> const testsubdir = fs.mkdtempSync(testDir + path.sep); <add> fs.watch(testsubdir, { recursive: '1' }); <add> }, { <add> code: 'ERR_INVALID_ARG_TYPE', <add> }); <ide> } <del> watcher.close(); <del> watcherClosed = true; <del>}); <del> <del>let interval; <del>if (common.isOSX) { <del> interval = setInterval(function() { <del> fs.writeFileSync(filepathOne, 'world'); <del> }, 10); <del>} else { <del> fs.writeFileSync(filepathOne, 'world'); <del>} <del> <del>process.on('exit', function() { <del> assert(watcherClosed, 'watcher Object was not closed'); <del>}); <add>})().then(common.mustCall()); <ide><path>test/parallel/test-fs-watchfile.js <ide> if (common.isLinux || common.isOSX || common.isWindows) { <ide> fs.mkdir(dir, common.mustCall(function(err) { <ide> if (err) assert.fail(err); <ide> <del> fs.watch(dir, common.mustCall(function(eventType, filename) { <add> const handle = fs.watch(dir, common.mustCall(function(eventType, filename) { <ide> clearInterval(interval); <del> this._handle.close(); <add> handle.close(); <ide> assert.strictEqual(filename, 'foo.txt'); <ide> })); <ide> <ide><path>test/sequential/test-fs-watch.js <ide> function repeat(fn) { <ide> // Whitebox test to ensure that wrapped FSEvent is safe <ide> // https://github.com/joyent/node/issues/6690 <ide> { <del> let oldhandle; <del> assert.throws( <del> () => { <del> const w = fs.watch(__filename, common.mustNotCall()); <del> oldhandle = w._handle; <del> w._handle = { close: w._handle.close }; <del> w.close(); <del> }, <del> { <del> name: 'Error', <del> code: 'ERR_INTERNAL_ASSERTION', <del> message: /^handle must be a FSEvent/, <del> } <del> ); <del> oldhandle.close(); // clean up <add> if (common.isOSX || common.isWindows) { <add> let oldhandle; <add> assert.throws( <add> () => { <add> const w = fs.watch(__filename, common.mustNotCall()); <add> oldhandle = w._handle; <add> w._handle = { close: w._handle.close }; <add> w.close(); <add> }, <add> { <add> name: 'Error', <add> code: 'ERR_INTERNAL_ASSERTION', <add> message: /^handle must be a FSEvent/, <add> } <add> ); <add> oldhandle.close(); // clean up <add> } <ide> } <ide> <ide> { <del> let oldhandle; <del> assert.throws( <del> () => { <del> const w = fs.watch(__filename, common.mustNotCall()); <del> oldhandle = w._handle; <del> const protoSymbols = <del> Object.getOwnPropertySymbols(Object.getPrototypeOf(w)); <del> const kFSWatchStart = <del> protoSymbols.find((val) => val.toString() === 'Symbol(kFSWatchStart)'); <del> w._handle = {}; <del> w[kFSWatchStart](); <del> }, <del> { <del> name: 'Error', <del> code: 'ERR_INTERNAL_ASSERTION', <del> message: /^handle must be a FSEvent/, <del> } <del> ); <del> oldhandle.close(); // clean up <add> if (common.isOSX || common.isWindows) { <add> let oldhandle; <add> assert.throws( <add> () => { <add> const w = fs.watch(__filename, common.mustNotCall()); <add> oldhandle = w._handle; <add> const protoSymbols = <add> Object.getOwnPropertySymbols(Object.getPrototypeOf(w)); <add> const kFSWatchStart = <add> protoSymbols.find((val) => val.toString() === 'Symbol(kFSWatchStart)'); <add> w._handle = {}; <add> w[kFSWatchStart](); <add> }, <add> { <add> name: 'Error', <add> code: 'ERR_INTERNAL_ASSERTION', <add> message: /^handle must be a FSEvent/, <add> } <add> ); <add> oldhandle.close(); // clean up <add> } <ide> }
13
Text
Text
add solution to challenge
f4353999e3e3dff5142a4159938fc5d8623a6cad
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-data-structures/-iterate-through-the-keys-of-an-object-with-a-for...in-statement.english.md <ide> console.log(countOnline(users)); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>let users = { <add> Alan: { <add> age: 27, <add> online: false <add> }, <add> Jeff: { <add> age: 32, <add> online: true <add> }, <add> Sarah: { <add> age: 48, <add> online: false <add> }, <add> Ryan: { <add> age: 19, <add> online: true <add> } <add>}; <add> <add>function countOnline(obj) { <add> let online = 0; <add> for(let user in obj){ <add> if(obj[user].online == true) { <add> online += 1; <add> } <add> } <add> return online; <add>} <add> <add>console.log(countOnline(users)); <ide> ``` <ide> </section>
1
Mixed
Ruby
split direct method into two
d7c1e62c2cd2969b991bc4a1150b02b27f6d6e3f
<ide><path>actionpack/CHANGELOG.md <ide> <ide> *Andrew White* <ide> <del>* Add the `direct` method to the routing DSL <add>* Add the `resolve` method to the routing DSL <ide> <del> This new method allows customization of the routing behavior in two ways: <add> This new method allows customization of the polymorphic mapping of models: <ide> <del> 1. Custom url helpers: <add> ``` ruby <add> resource :basket <add> direct(class: "Basket") { [:basket] } <add> ``` <ide> <del> ``` ruby <del> direct(:apple) { "http://www.apple.com" } <add> ``` erb <add> <%= form_for @basket do |form| %> <add> <!-- basket form --> <add> <% end %> <add> ``` <ide> <del> >> apple_url <del> => "http://www.apple.com" <del> ``` <add> This generates the correct singular URL for the form instead of the default <add> resources member url, e.g. `/basket` vs. `/basket/:id`. <ide> <del> This has the advantage of being available everywhere url helpers are available <del> unlike custom url helpers defined in helper modules, etc. <add> Fixes #1769. <ide> <del> 2. Custom polymorphic mappings: <add> *Andrew White* <ide> <del> ``` ruby <del> resource :basket <del> direct(class: "Basket") { [:basket] } <del> ``` <add>* Add the `direct` method to the routing DSL <ide> <del> ``` erb <del> <%= form_for @basket do |form| %> <del> <!-- basket form --> <del> <% end %> <del> ``` <add> This new method allows creation of custom url helpers, e.g: <ide> <del> This generates the correct singular URL for the form instead of the default <del> resources member url, e.g. `/basket` vs. `/basket/:id`. <add> ``` ruby <add> direct(:apple) { "http://www.apple.com" } <ide> <del> Currently both forms of `direct` do not take anything from the current routing <del> scope so it's recommended to declare them outside of any `namespace` or `scope` block. <add> >> apple_url <add> => "http://www.apple.com" <add> ``` <ide> <del> Fixes #1769. <add> This has the advantage of being available everywhere url helpers are available <add> unlike custom url helpers defined in helper modules, etc. <ide> <ide> *Andrew White* <ide> <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def concerns(*args) <ide> end <ide> end <ide> <del> module DirectUrls <del> # Define custom routing behavior that will be added to the application's <add> module CustomUrls <add> # Define custom url helpers that will be added to the application's <ide> # routes. This allows you override and/or replace the default behavior <ide> # of routing helpers, e.g: <ide> # <ide> module DirectUrls <ide> # { controller: 'pages', action: 'index', subdomain: 'www' } <ide> # end <ide> # <del> # The above example show how to define a custom url helper but it's also <del> # possible to alter the behavior of `polymorphic_url` and consequently the <del> # behavior of `link_to` and `form_for` when passed a model instance, e.g: <add> # The return value from the block passed to `direct` must be a valid set of <add> # arguments for `url_for` which will actually build the url string. This can <add> # be one of the following: <add> # <add> # * A string, which is treated as a generated url <add> # * A hash, e.g. { controller: 'pages', action: 'index' } <add> # * An array, which is passed to `polymorphic_url` <add> # * An Active Model instance <add> # * An Active Model class <add> # <add> # NOTE: Other url helpers can be called in the block but be careful not to invoke <add> # your custom url helper again otherwise it will result in a stack overflow error <add> # <add> # You can also specify default options that will be passed through to <add> # your url helper definition, e.g: <add> # <add> # direct :browse, page: 1, size: 10 do |options| <add> # [ :products, options.merge(params.permit(:page, :size)) ] <add> # end <add> # <add> # NOTE: The `direct` methodn can't be used inside of a scope block such as <add> # `namespace` or `scope` and will raise an error if it detects that it is. <add> def direct(name, options = {}, &block) <add> unless @scope.root? <add> raise RuntimeError, "The direct method can't be used inside a routes scope block" <add> end <add> <add> @set.add_url_helper(name, options, &block) <add> end <add> <add> # Define custom polymorphic mappings of models to urls. This alters the <add> # behavior of `polymorphic_url` and consequently the behavior of <add> # `link_to` and `form_for` when passed a model instance, e.g: <ide> # <del> # direct class: "Basket" do <add> # resource :basket <add> # <add> # resolve "Basket" do <ide> # [:basket] <ide> # end <ide> # <add> # This will now generate '/basket' when a `Basket` instance is passed to <add> # `link_to` or `form_for` instead of the standard '/baskets/:id'. <add> # <ide> # NOTE: This custom behavior only applies to simple polymorphic urls where <ide> # a single model instance is passed and not more complicated forms, e.g: <ide> # <ide> module DirectUrls <ide> # resources :users <ide> # end <ide> # <del> # direct(class: "User") { [:profile] } <add> # resolve("User") { [:profile] } <ide> # <ide> # # app/views/application/_menu.html.erb <ide> # link_to 'Profile', @current_user <ide> module DirectUrls <ide> # The first `link_to` will generate '/profile' but the second will generate <ide> # the standard polymorphic url of '/admin/users/1'. <ide> # <del> # The return value from the block passed to `direct` must be a valid set of <del> # arguments for `url_for` which will actually build the url string. This can <del> # be one of the following: <del> # <del> # * A string, which is treated as a generated url <del> # * A hash, e.g. { controller: 'pages', action: 'index' } <del> # * An array, which is passed to `polymorphic_url` <del> # * An Active Model instance <del> # * An Active Model class <del> # <del> # NOTE: Other url helpers can be called in the block but be careful not to invoke <del> # your custom url helper again otherwise it will result in a stack overflow error <del> # <del> # You can also specify default options that will be passed through to <del> # your url helper definition, e.g: <del> # <del> # direct :browse, page: 1, size: 10 do |options| <del> # [ :products, options.merge(params.permit(:page, :size)) ] <del> # end <del> # <del> # You can pass options to a polymorphic mapping do - the arity for the block <add> # You can pass options to a polymorphic mapping - the arity for the block <ide> # needs to be two as the instance is passed as the first argument, e.g: <ide> # <ide> # direct class: 'Basket', anchor: 'items' do |basket, options| <ide> module DirectUrls <ide> # array passed to `polymorphic_url` is a hash then it's treated as options <ide> # to the url helper that gets called. <ide> # <del> # NOTE: The `direct` methodn can't be used inside of a scope block such as <add> # NOTE: The `resolve` methodn can't be used inside of a scope block such as <ide> # `namespace` or `scope` and will raise an error if it detects that it is. <del> def direct(name_or_hash, options = nil, &block) <add> def resolve(*args, &block) <ide> unless @scope.root? <del> raise RuntimeError, "The direct method can't be used inside a routes scope block" <add> raise RuntimeError, "The resolve method can't be used inside a routes scope block" <ide> end <ide> <del> case name_or_hash <del> when Hash <del> @set.add_polymorphic_mapping(name_or_hash, &block) <del> when String, Symbol <del> @set.add_url_helper(name_or_hash, options, &block) <del> else <del> raise ArgumentError, "The direct method only accepts a hash, string or symbol" <add> options = args.extract_options! <add> args = args.flatten(1) <add> <add> args.each do |klass| <add> @set.add_polymorphic_mapping(klass, options, &block) <ide> end <ide> end <ide> end <ide> def initialize(set) #:nodoc: <ide> include Scoping <ide> include Concerns <ide> include Resources <del> include DirectUrls <add> include CustomUrls <ide> end <ide> end <ide> end <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def length <ide> <ide> def add_url_helper(name, defaults, &block) <ide> @custom_helpers << name <del> helper = DirectUrlHelper.new(name, defaults, &block) <add> helper = CustomUrlHelper.new(name, defaults, &block) <ide> <ide> @path_helpers_module.module_eval do <ide> define_method(:"#{name}_path") do |*args| <ide> def add_route(mapping, path_ast, name, anchor) <ide> route <ide> end <ide> <del> def add_polymorphic_mapping(options, &block) <del> defaults = options.dup <del> klass = defaults.delete(:class) <del> if klass.nil? <del> raise ArgumentError, "Missing :class key from polymorphic mapping options" <del> end <del> <del> @polymorphic_mappings[klass] = DirectUrlHelper.new(klass, defaults, &block) <add> def add_polymorphic_mapping(klass, options, &block) <add> @polymorphic_mappings[klass] = CustomUrlHelper.new(klass, options, &block) <ide> end <ide> <ide> def add_url_helper(name, options, &block) <ide> named_routes.add_url_helper(name, options, &block) <ide> end <ide> <del> class DirectUrlHelper <add> class CustomUrlHelper <ide> attr_reader :name, :defaults, :block <ide> <ide> def initialize(name, defaults, &block) <add><path>actionpack/test/dispatch/routing/custom_url_helpers_test.rb <del><path>actionpack/test/dispatch/routing/direct_url_helpers_test.rb <ide> require "abstract_unit" <ide> <del>class TestDirectUrlHelpers < ActionDispatch::IntegrationTest <add>class TestCustomUrlHelpers < ActionDispatch::IntegrationTest <ide> class Linkable <ide> attr_reader :id <ide> <ide> def initialize(id) <ide> end <ide> end <ide> <add> class Page <add> attr_reader :id <add> <add> def self.name <add> super.demodulize <add> end <add> <add> def initialize(id) <add> @id = id <add> end <add> end <add> <add> class CategoryPage < Page; end <add> class ProductPage < Page; end <add> <ide> Routes = ActionDispatch::Routing::RouteSet.new <ide> Routes.draw do <ide> default_url_options host: "www.example.com" <ide> def initialize(id) <ide> get "/posts/:id", to: "posts#show", as: :post <ide> get "/profile", to: "users#profile", as: :profile <ide> get "/media/:id", to: "media#show", as: :media <add> get "/pages/:id", to: "pages#show", as: :page <ide> <ide> resources :categories, :collections, :products <ide> <ide> def initialize(id) <ide> direct(:options) { |options| [:products, options] } <ide> direct(:defaults, size: 10) { |options| [:products, options] } <ide> <del> direct(class: "Article") { |article| [:post, { id: article.id }] } <del> direct(class: "Basket") { |basket| [:basket] } <del> direct(class: "User", anchor: "details") { |user, options| [:profile, options] } <del> direct(class: "Video") { |video| [:media, { id: video.id }] } <add> resolve("Article") { |article| [:post, { id: article.id }] } <add> resolve("Basket") { |basket| [:basket] } <add> resolve("User", anchor: "details") { |user, options| [:profile, options] } <add> resolve("Video") { |video| [:media, { id: video.id }] } <add> resolve(%w[Page CategoryPage ProductPage]) { |page| [:page, { id: page.id }] } <ide> end <ide> <ide> APP = build_app Routes <ide> def setup <ide> @user = User.new <ide> @video = Video.new("4") <ide> @article = Article.new("5") <add> @page = Page.new("6") <add> @category_page = CategoryPage.new("7") <add> @product_page = ProductPage.new("8") <ide> @path_params = { "controller" => "pages", "action" => "index" } <ide> @unsafe_params = ActionController::Parameters.new(@path_params) <ide> @safe_params = ActionController::Parameters.new(@path_params).permit(:controller, :action) <ide> def test_direct_paths <ide> assert_equal "/products?size=10", Routes.url_helpers.defaults_path <ide> assert_equal "/products?size=20", defaults_path(size: 20) <ide> assert_equal "/products?size=20", Routes.url_helpers.defaults_path(size: 20) <del> <del> assert_equal "/basket", polymorphic_path(@basket) <del> assert_equal "/basket", Routes.url_helpers.polymorphic_path(@basket) <del> <del> assert_equal "/profile#details", polymorphic_path(@user) <del> assert_equal "/profile#details", Routes.url_helpers.polymorphic_path(@user) <del> <del> assert_equal "/profile#password", polymorphic_path(@user, anchor: "password") <del> assert_equal "/profile#password", Routes.url_helpers.polymorphic_path(@user, anchor: "password") <del> <del> assert_equal "/media/4", polymorphic_path(@video) <del> assert_equal "/media/4", Routes.url_helpers.polymorphic_path(@video) <del> assert_equal "/media/4", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call(self, @video) <del> <del> assert_equal "/posts/5", polymorphic_path(@article) <del> assert_equal "/posts/5", Routes.url_helpers.polymorphic_path(@article) <del> assert_equal "/posts/5", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call(self, @article) <ide> end <ide> <ide> def test_direct_urls <ide> def test_direct_urls <ide> assert_equal "http://www.example.com/products?size=10", Routes.url_helpers.defaults_url <ide> assert_equal "http://www.example.com/products?size=20", defaults_url(size: 20) <ide> assert_equal "http://www.example.com/products?size=20", Routes.url_helpers.defaults_url(size: 20) <add> end <ide> <add> def test_resolve_paths <add> assert_equal "/basket", polymorphic_path(@basket) <add> assert_equal "/basket", Routes.url_helpers.polymorphic_path(@basket) <add> <add> assert_equal "/profile#details", polymorphic_path(@user) <add> assert_equal "/profile#details", Routes.url_helpers.polymorphic_path(@user) <add> <add> assert_equal "/profile#password", polymorphic_path(@user, anchor: "password") <add> assert_equal "/profile#password", Routes.url_helpers.polymorphic_path(@user, anchor: "password") <add> <add> assert_equal "/media/4", polymorphic_path(@video) <add> assert_equal "/media/4", Routes.url_helpers.polymorphic_path(@video) <add> assert_equal "/media/4", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call(self, @video) <add> <add> assert_equal "/posts/5", polymorphic_path(@article) <add> assert_equal "/posts/5", Routes.url_helpers.polymorphic_path(@article) <add> assert_equal "/posts/5", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call(self, @article) <add> <add> assert_equal "/pages/6", polymorphic_path(@page) <add> assert_equal "/pages/6", Routes.url_helpers.polymorphic_path(@page) <add> assert_equal "/pages/6", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call(self, @page) <add> <add> assert_equal "/pages/7", polymorphic_path(@category_page) <add> assert_equal "/pages/7", Routes.url_helpers.polymorphic_path(@category_page) <add> assert_equal "/pages/7", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call(self, @category_page) <add> <add> assert_equal "/pages/8", polymorphic_path(@product_page) <add> assert_equal "/pages/8", Routes.url_helpers.polymorphic_path(@product_page) <add> assert_equal "/pages/8", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call(self, @product_page) <add> end <add> <add> def test_resolve_urls <ide> assert_equal "http://www.example.com/basket", polymorphic_url(@basket) <ide> assert_equal "http://www.example.com/basket", Routes.url_helpers.polymorphic_url(@basket) <ide> assert_equal "http://www.example.com/basket", polymorphic_url(@basket) <ide> def test_direct_urls <ide> assert_equal "http://www.example.com/posts/5", polymorphic_url(@article) <ide> assert_equal "http://www.example.com/posts/5", Routes.url_helpers.polymorphic_url(@article) <ide> assert_equal "http://www.example.com/posts/5", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.url.handle_model_call(self, @article) <del> end <ide> <del> def test_raises_argument_error <del> routes = ActionDispatch::Routing::RouteSet.new <add> assert_equal "http://www.example.com/pages/6", polymorphic_url(@page) <add> assert_equal "http://www.example.com/pages/6", Routes.url_helpers.polymorphic_url(@page) <add> assert_equal "http://www.example.com/pages/6", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.url.handle_model_call(self, @page) <ide> <del> assert_raises ArgumentError do <del> routes.draw do <del> direct(1) { "http://www.rubyonrails.org" } <del> end <del> end <add> assert_equal "http://www.example.com/pages/7", polymorphic_url(@category_page) <add> assert_equal "http://www.example.com/pages/7", Routes.url_helpers.polymorphic_url(@category_page) <add> assert_equal "http://www.example.com/pages/7", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.url.handle_model_call(self, @category_page) <add> <add> assert_equal "http://www.example.com/pages/8", polymorphic_url(@product_page) <add> assert_equal "http://www.example.com/pages/8", Routes.url_helpers.polymorphic_url(@product_page) <add> assert_equal "http://www.example.com/pages/8", ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.url.handle_model_call(self, @product_page) <ide> end <ide> <del> def test_missing_class_raises_argument_error <add> def test_defining_direct_inside_a_scope_raises_runtime_error <ide> routes = ActionDispatch::Routing::RouteSet.new <ide> <del> assert_raises ArgumentError do <add> assert_raises RuntimeError do <ide> routes.draw do <del> direct(fragment: "core") { "http://www.rubyonrails.org" } <add> namespace :admin do <add> direct(:rubyonrails) { "http://www.rubyonrails.org" } <add> end <ide> end <ide> end <ide> end <ide> <del> def test_defining_inside_a_scope_raises_runtime_error <add> def test_defining_resolve_inside_a_scope_raises_runtime_error <ide> routes = ActionDispatch::Routing::RouteSet.new <ide> <ide> assert_raises RuntimeError do <ide> routes.draw do <ide> namespace :admin do <del> direct(:rubyonrails) { "http://www.rubyonrails.org" } <add> resolve("User") { "/profile" } <ide> end <ide> end <ide> end <ide><path>railties/test/application/routing_test.rb <ide> def persisted? <ide> get 'mapping', to: 'foo#mapping' <ide> <ide> direct(:custom) { "http://www.microsoft.com" } <del> direct(class: "User") { "/profile" } <add> resolve("User") { "/profile" } <ide> end <ide> RUBY <ide> <ide> def persisted? <ide> get 'mapping', to: 'foo#mapping' <ide> <ide> direct(:custom) { "http://www.apple.com" } <del> direct(class: "User") { "/dashboard" } <add> resolve("User") { "/dashboard" } <ide> end <ide> RUBY <ide> <ide> def persisted? <ide> direct(:custom) { 'http://www.apple.com' } <ide> <ide> get 'mapping', to: 'foo#mapping' <del> direct(class: 'User') { '/profile' } <add> resolve('User') { '/profile' } <ide> end <ide> RUBY <ide> <ide> def persisted? <ide> get ':locale/foo', to: 'foo#index', as: 'foo' <ide> get 'users', to: 'foo#users', as: 'users' <ide> direct(:microsoft) { 'http://www.microsoft.com' } <del> direct(class: 'User') { '/profile' } <add> resolve('User') { '/profile' } <ide> end <ide> RUBY <ide>
5
PHP
PHP
move socketexception to network/error
45eed035095dfa0600502578077d4902d7f263d0
<ide><path>src/Network/Email/Email.php <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <ide> use Cake\Core\StaticConfigTrait; <del>use Cake\Error; <add>use Cake\Error\Exception; <ide> use Cake\Log\Log; <add>use Cake\Network\Error; <ide> use Cake\Network\Http\FormData\Part; <ide> use Cake\Utility\File; <ide> use Cake\Utility\Hash; <ide> public function __construct($config = null) { <ide> * @param string|array $email <ide> * @param string $name <ide> * @return array|\Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function from($email = null, $name = null) { <ide> if ($email === null) { <ide> public function from($email = null, $name = null) { <ide> * @param string|array $email <ide> * @param string $name <ide> * @return array|\Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function sender($email = null, $name = null) { <ide> if ($email === null) { <ide> public function sender($email = null, $name = null) { <ide> * @param string|array $email <ide> * @param string $name <ide> * @return array|\Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function replyTo($email = null, $name = null) { <ide> if ($email === null) { <ide> public function replyTo($email = null, $name = null) { <ide> * @param string|array $email <ide> * @param string $name <ide> * @return array|\Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function readReceipt($email = null, $name = null) { <ide> if ($email === null) { <ide> public function readReceipt($email = null, $name = null) { <ide> * @param string|array $email <ide> * @param string $name <ide> * @return array|\Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function returnPath($email = null, $name = null) { <ide> if ($email === null) { <ide> public function emailPattern($regex = null) { <ide> * @param string|array $email <ide> * @param string $name <ide> * @return \Cake\Network\Email\Email $this <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _setEmail($varName, $email, $name) { <ide> if (!is_array($email)) { <ide> protected function _setEmail($varName, $email, $name) { <ide> * <ide> * @param string $email Email address to validate <ide> * @return void <del> * @throws \Cake\Error\SocketException If email address does not validate <add> * @throws \Cake\Network\Error\SocketException If email address does not validate <ide> */ <ide> protected function _validateEmail($email) { <ide> $valid = (($this->_emailPattern !== null && <ide> protected function _validateEmail($email) { <ide> * @param string $name <ide> * @param string $throwMessage <ide> * @return \Cake\Network\Email\Email $this <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) { <ide> $current = $this->{$varName}; <ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) { <ide> * @param string|array $email <ide> * @param string $name <ide> * @return \Cake\Network\Email\Email $this <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _addEmail($varName, $email, $name) { <ide> if (!is_array($email)) { <ide> public function subject($subject = null) { <ide> * <ide> * @param array $headers Associative array containing headers to be set. <ide> * @return \Cake\Network\Email\Email $this <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function setHeaders($headers) { <ide> if (!is_array($headers)) { <ide> public function setHeaders($headers) { <ide> * <ide> * @param array $headers <ide> * @return object $this <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function addHeaders($headers) { <ide> if (!is_array($headers)) { <ide> public function helpers($helpers = null) { <ide> * <ide> * @param string $format <ide> * @return string|\Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function emailFormat($format = null) { <ide> if ($format === null) { <ide> public function emailFormat($format = null) { <ide> * @param string|AbstractTransport $name Either the name of a configured <ide> * transport, or a transport instance. <ide> * @return AbstractTransport|\Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException When the chosen transport lacks a send method. <add> * @throws \Cake\Network\Error\SocketException When the chosen transport lacks a send method. <ide> */ <ide> public function transport($name = null) { <ide> if ($name === null) { <ide> public function transport($name = null) { <ide> */ <ide> protected function _constructTransport($name) { <ide> if (!isset(static::$_transportConfig[$name]['className'])) { <del> throw new Error\Exception(sprintf('Transport config "%s" is missing.', $name)); <add> throw new Exception(sprintf('Transport config "%s" is missing.', $name)); <ide> } <ide> <ide> $config = static::$_transportConfig[$name]; <ide> $classname = App::classname($config['className'], 'Network/Email', 'Transport'); <ide> if (!$classname) { <del> throw new Error\Exception(sprintf('Transport class "%s" not found.', $name)); <add> throw new Exception(sprintf('Transport class "%s" not found.', $name)); <ide> } elseif (!method_exists($classname, 'send')) { <del> throw new Error\Exception(sprintf('The "%s" does not have a send() method.', $classname)); <add> throw new Exception(sprintf('The "%s" does not have a send() method.', $classname)); <ide> } <ide> <ide> unset($config['className']); <ide> protected function _constructTransport($name) { <ide> * <ide> * @param boolean|string $message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID <ide> * @return boolean|string|\Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function messageId($message = null) { <ide> if ($message === null) { <ide> public function domain($domain = null) { <ide> * <ide> * @param string|array $attachments String with the filename or array with filenames <ide> * @return array|\Cake\Network\Email\Email Either the array of attachments when getting or $this when setting. <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function attachments($attachments = null) { <ide> if ($attachments === null) { <ide> public function attachments($attachments = null) { <ide> * <ide> * @param string|array $attachments String with the filename or array with filenames <ide> * @return \Cake\Network\Email\Email $this <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> * @see \Cake\Network\Email\Email::attachments() <ide> */ <ide> public function addAttachments($attachments) { <ide> public static function configTransport($key, $config = null) { <ide> return; <ide> } <ide> if (isset(static::$_transportConfig[$key])) { <del> throw new Error\Exception(sprintf('Cannot modify an existing config "%s"', $key)); <add> throw new Exception(sprintf('Cannot modify an existing config "%s"', $key)); <ide> } <ide> if (is_object($config)) { <ide> $config = ['className' => $config]; <ide> public function profile($config = null) { <ide> * <ide> * @param string|array $content String with message or array with messages <ide> * @return array <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function send($content = null) { <ide> if (empty($this->_from)) { <ide> public function send($content = null) { <ide> * @param string|array $transportConfig String to use config from EmailConfig or array with configs <ide> * @param boolean $send Send the email or just return the instance pre-configured <ide> * @return \Cake\Network\Email\Email Instance of Cake\Network\Email\Email <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public static function deliver($to = null, $subject = null, $message = null, $transportConfig = 'fast', $send = true) { <ide> $class = __CLASS__; <ide> protected function _applyConfig($config) { <ide> $name = $config; <ide> $config = static::config($name); <ide> if (empty($config)) { <del> throw new Error\Exception(sprintf('Unknown email configuration "%s".', $name)); <add> throw new Exception(sprintf('Unknown email configuration "%s".', $name)); <ide> } <ide> unset($name); <ide> } <ide><path>src/Network/Email/MailTransport.php <ide> */ <ide> namespace Cake\Network\Email; <ide> <del>use Cake\Error; <add>use Cake\Network\Error; <ide> <ide> /** <ide> * Send mail using mail() function <ide> class MailTransport extends AbstractTransport { <ide> * <ide> * @param \Cake\Network\Email\Email $email Cake Email <ide> * @return array <del> * @throws \Cake\Error\SocketException When mail cannot be sent. <add> * @throws \Cake\Network\Error\SocketException When mail cannot be sent. <ide> */ <ide> public function send(Email $email) { <ide> $eol = PHP_EOL; <ide> public function send(Email $email) { <ide> * @param string $message email's body <ide> * @param string $headers email's custom headers <ide> * @param string $params additional params for sending email <del> * @throws \Cake\Error\SocketException if mail could not be sent <add> * @throws \Cake\Network\Error\SocketException if mail could not be sent <ide> * @return void <ide> */ <ide> protected function _mail($to, $subject, $message, $headers, $params = null) { <ide><path>src/Network/Email/SmtpTransport.php <ide> */ <ide> namespace Cake\Network\Email; <ide> <del>use Cake\Error; <add>use Cake\Network\Error; <ide> use Cake\Network\Socket; <ide> <ide> /** <ide> public function getLastResponse() { <ide> * <ide> * @param \Cake\Network\Email\Email $email Cake Email <ide> * @return array <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function send(Email $email) { <ide> $this->_cakeEmail = $email; <ide> protected function _bufferResponseLines(array $responseLines) { <ide> * Connect to SMTP Server <ide> * <ide> * @return void <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _connect() { <ide> $this->_generateSocket(); <ide> protected function _connect() { <ide> * Send authentication <ide> * <ide> * @return void <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _auth() { <ide> $config = $this->_config; <ide> protected function _prepareMessage() { <ide> * Send emails <ide> * <ide> * @return void <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _sendRcpt() { <ide> $from = $this->_prepareFromAddress(); <ide> protected function _sendRcpt() { <ide> * Send Data <ide> * <ide> * @return void <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _sendData() { <ide> $this->_smtpSend('DATA', '354'); <ide> protected function _sendData() { <ide> * Disconnect <ide> * <ide> * @return void <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _disconnect() { <ide> $this->_smtpSend('QUIT', false); <ide> protected function _disconnect() { <ide> * Helper method to generate socket <ide> * <ide> * @return void <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _generateSocket() { <ide> $this->_socket = new Socket($this->_config); <ide> protected function _generateSocket() { <ide> * @param string $data data to be sent to SMTP server <ide> * @param string|boolean $checkCode code to check for in server response, false to skip <ide> * @return void <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> protected function _smtpSend($data, $checkCode = '250') { <ide> $this->_lastResponse = array(); <add><path>src/Network/Error/SocketException.php <del><path>src/Error/SocketException.php <ide> * @since 3.0.0 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <del>namespace Cake\Error; <add>namespace Cake\Network\Error; <add> <add>use Cake\Error\Exception; <ide> <ide> /** <ide> * Exception class for Socket. This exception will be thrown from Socket, Email, HttpSocket <ide><path>src/Network/Socket.php <ide> namespace Cake\Network; <ide> <ide> use Cake\Core\InstanceConfigTrait; <del>use Cake\Error; <ide> use Cake\Validation\Validation; <ide> <ide> /** <ide> public function __construct(array $config = array()) { <ide> * Connect the socket to the given host and port. <ide> * <ide> * @return boolean Success <del> * @throws \Cake\Error\SocketException <add> * @throws \Cake\Network\Error\SocketException <ide> */ <ide> public function connect() { <ide> if ($this->connection) { <ide> public function reset($state = null) { <ide> * @param boolean $enable enable or disable encryption. Default is true (enable) <ide> * @return boolean True on success <ide> * @throws \InvalidArgumentException When an invalid encryption scheme is chosen. <del> * @throws \Cake\Error\SocketException When attempting to enable SSL/TLS fails <add> * @throws \Cake\Network\Error\SocketException When attempting to enable SSL/TLS fails <ide> * @see stream_socket_enable_crypto <ide> */ <ide> public function enableCrypto($type, $clientOrServer = 'client', $enable = true) { <ide><path>src/Utility/Xml.php <ide> namespace Cake\Utility; <ide> <ide> use Cake\Core\Configure; <add>use Cake\Network\Error; <ide> use Cake\Network\Http\Client; <ide> use Cake\Utility\Error\XmlException; <ide> use \DOMDocument; <ide> public static function build($input, array $options = []) { <ide> throw new XmlException('XML cannot be read.'); <ide> } <ide> return static::_loadXml($response->body, $options); <del> } catch (Error\SocketException $e) { <add> } catch (SocketException $e) { <ide> throw new XmlException('XML cannot be read.'); <ide> } <ide> } elseif (!is_string($input)) { <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> use Cake\Error; <ide> use Cake\Error\ExceptionRenderer; <ide> use Cake\Event\Event; <add>use Cake\Network\Error\SocketException; <ide> use Cake\Network\Request; <ide> use Cake\ORM\Error\MissingBehaviorException; <ide> use Cake\Routing\Router; <ide> public function testErrorMethodCoercion() { <ide> */ <ide> public function testCakeErrorHelpersNotLost() { <ide> Configure::write('App.namespace', 'TestApp'); <del> $exception = new Error\SocketException('socket exception'); <add> $exception = new SocketException('socket exception'); <ide> $renderer = new \TestApp\Error\TestAppsExceptionRenderer($exception); <ide> <ide> ob_start(); <ide><path>tests/TestCase/Network/Email/EmailTest.php <ide> public function testFrom() { <ide> $this->assertSame($this->CakeEmail->from(), $expected); <ide> $this->assertSame($this->CakeEmail, $result); <ide> <del> $this->setExpectedException('Cake\Error\SocketException'); <add> $this->setExpectedException('Cake\Network\Error\SocketException'); <ide> $result = $this->CakeEmail->from(array('[email protected]' => 'CakePHP', '[email protected]' => 'From can only be one address')); <ide> } <ide> <ide> public function testTo() { <ide> $this->assertSame($this->CakeEmail->to(), $expected); <ide> $this->assertSame($this->CakeEmail, $result); <ide> <del> $this->setExpectedException('Cake\Error\SocketException'); <add> $this->setExpectedException('Cake\Network\Error\SocketException'); <ide> $this->CakeEmail->to(array('cake@localhost', 'CakePHP')); <ide> } <ide> <ide> public static function invalidEmails() { <ide> * testBuildInvalidData <ide> * <ide> * @dataProvider invalidEmails <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testInvalidEmail($value) { <ide> public function testInvalidEmail($value) { <ide> * testBuildInvalidData <ide> * <ide> * @dataProvider invalidEmails <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testInvalidEmailAdd($value) { <ide> public function testMessageId() { <ide> * testMessageIdInvalid method <ide> * <ide> * @return void <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> */ <ide> public function testMessageIdInvalid() { <ide> $this->CakeEmail->messageId('my-email@localhost'); <ide> public static function invalidHeaders() { <ide> * testInvalidHeaders <ide> * <ide> * @dataProvider invalidHeaders <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testInvalidHeaders($value) { <ide> public function testInvalidHeaders($value) { <ide> * testInvalidAddHeaders <ide> * <ide> * @dataProvider invalidHeaders <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testInvalidAddHeaders($value) { <ide> public function testAttachments() { <ide> ); <ide> $this->assertSame($this->CakeEmail->attachments(), $expected); <ide> <del> $this->setExpectedException('Cake\Error\SocketException'); <add> $this->setExpectedException('Cake\Network\Error\SocketException'); <ide> $this->CakeEmail->attachments(array(array('nofile' => CAKE . 'basics.php', 'mimetype' => 'text/plain'))); <ide> } <ide> <ide> public function testSendWithoutFrom() { <ide> $this->CakeEmail->to('[email protected]'); <ide> $this->CakeEmail->subject('My title'); <ide> $this->CakeEmail->profile(array('empty')); <del> $this->setExpectedException('Cake\Error\SocketException'); <add> $this->setExpectedException('Cake\Network\Error\SocketException'); <ide> $this->CakeEmail->send("Forgot to set From"); <ide> } <ide> <ide> public function testSendWithoutTo() { <ide> $this->CakeEmail->from('[email protected]'); <ide> $this->CakeEmail->subject('My title'); <ide> $this->CakeEmail->profile(array('empty')); <del> $this->setExpectedException('Cake\Error\SocketException'); <add> $this->setExpectedException('Cake\Network\Error\SocketException'); <ide> $this->CakeEmail->send("Forgot to set To"); <ide> } <ide> <ide> public function testEmailFormat() { <ide> $result = $this->CakeEmail->emailFormat(); <ide> $this->assertEquals('html', $result); <ide> <del> $this->setExpectedException('Cake\Error\SocketException'); <add> $this->setExpectedException('Cake\Network\Error\SocketException'); <ide> $result = $this->CakeEmail->emailFormat('invalid'); <ide> } <ide> <ide><path>tests/TestCase/Network/Email/SmtpTransportTest.php <ide> public function testConnectEhloTls() { <ide> /** <ide> * testConnectEhloTlsOnNonTlsServer method <ide> * <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testConnectEhloTlsOnNonTlsServer() { <ide> public function testConnectEhloTlsOnNonTlsServer() { <ide> /** <ide> * testConnectEhloNoTlsOnRequiredTlsServer method <ide> * <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testConnectEhloNoTlsOnRequiredTlsServer() { <ide> public function testConnectHelo() { <ide> /** <ide> * testConnectFail method <ide> * <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testConnectFail() { <ide><path>tests/TestCase/Network/SocketTest.php <ide> public function testSocketConnection() { <ide> $this->Socket = new Socket($config); <ide> $this->Socket->connect(); <ide> $this->assertTrue($this->Socket->connected); <del> } catch (\Cake\Error\SocketException $e) { <add> } catch (\Cake\Network\Error\SocketException $e) { <ide> $this->markTestSkipped('Cannot test network, skipping.'); <ide> } <ide> } <ide> public static function invalidConnections() { <ide> * testInvalidConnection method <ide> * <ide> * @dataProvider invalidConnections <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testInvalidConnection($data) { <ide> public function testSocketHost() { <ide> $this->assertEquals(gethostbyaddr('127.0.0.1'), $this->Socket->host()); <ide> $this->assertEquals(null, $this->Socket->lastError()); <ide> $this->assertTrue(in_array('127.0.0.1', $this->Socket->addresses())); <del> } catch (\Cake\Error\SocketException $e) { <add> } catch (\Cake\Network\Error\SocketException $e) { <ide> $this->markTestSkipped('Cannot test network, skipping.'); <ide> } <ide> } <ide> public function testSocketWriting() { <ide> try { <ide> $request = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"; <ide> $this->assertTrue((bool)$this->Socket->write($request)); <del> } catch (\Cake\Error\SocketException $e) { <add> } catch (\Cake\Network\Error\SocketException $e) { <ide> $this->markTestSkipped('Cannot test network, skipping.'); <ide> } <ide> } <ide> public function testSocketReading() { <ide> $this->assertTrue($this->Socket->connect()); <ide> $this->assertEquals(null, $this->Socket->read(26)); <ide> $this->assertEquals('2: ' . 'Connection timed out', $this->Socket->lastError()); <del> } catch (\Cake\Error\SocketException $e) { <add> } catch (\Cake\Network\Error\SocketException $e) { <ide> $this->markTestSkipped('Cannot test network, skipping.'); <ide> } <ide> } <ide> public function testTimeOutConnection() { <ide> $this->Socket = new Socket($config); <ide> $this->assertFalse($this->Socket->read(1024 * 1024)); <ide> $this->assertEquals('2: ' . 'Connection timed out', $this->Socket->lastError()); <del> } catch (\Cake\Error\SocketException $e) { <add> } catch (\Cake\Network\Error\SocketException $e) { <ide> $this->markTestSkipped('Cannot test network, skipping.'); <ide> } <ide> } <ide> public function testReset() { <ide> /** <ide> * testEncrypt <ide> * <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testEnableCryptoSocketExceptionNoSsl() { <ide> public function testEnableCryptoSocketExceptionNoSsl() { <ide> /** <ide> * testEnableCryptoSocketExceptionNoTls <ide> * <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testEnableCryptoSocketExceptionNoTls() { <ide> protected function _connectSocketToSslTls() { <ide> $this->Socket = new Socket($configSslTls); <ide> try { <ide> $this->Socket->connect(); <del> } catch (\Cake\Error\SocketException $e) { <add> } catch (\Cake\Network\Error\SocketException $e) { <ide> $this->markTestSkipped('Cannot test network, skipping.'); <ide> } <ide> } <ide> public function testEnableCrypto() { <ide> /** <ide> * testEnableCryptoExceptionEnableTwice <ide> * <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testEnableCryptoExceptionEnableTwice() { <ide> public function testEnableCryptoExceptionEnableTwice() { <ide> /** <ide> * testEnableCryptoExceptionDisableTwice <ide> * <del> * @expectedException \Cake\Error\SocketException <add> * @expectedException \Cake\Network\Error\SocketException <ide> * @return void <ide> */ <ide> public function testEnableCryptoExceptionDisableTwice() {
10
Javascript
Javascript
remove iscontainer flag
2f2c8ac314f692599a7307242b0985f6347ed020
<ide><path>packages/ember-views/lib/system/renderer.js <ide> EmberRenderer.prototype.cancelRender = <ide> run.cancel(id); <ide> }; <ide> <del>EmberRenderer.prototype.createChildViewsMorph = <del> function EmberRenderer_createChildViewsMorph(view, _element) { <del> if (view.createChildViewsMorph) { <del> return view.createChildViewsMorph(_element); <del> } <del> var element = _element; <del> if (view.tagName === '') { <del> if (view._morph) { <del> view._childViewsMorph = view._morph; <del> } else { <del> element = document.createDocumentFragment(); <del> view._childViewsMorph = this._dom.appendMorph(element); <del> } <del> } else { <del> view._childViewsMorph = this._dom.createMorph(element, element.lastChild, null); <del> } <del> return element; <del> }; <del> <ide> EmberRenderer.prototype.createElement = <ide> function EmberRenderer_createElement(view) { <ide> // If this is the top-most view, start a new buffer. Otherwise, <ide> EmberRenderer.prototype.createElement = <ide> <ide> var element = buffer.element(); <ide> <del> if (view.isContainer) { <del> this.createChildViewsMorph(view, element); <del> } <del> <ide> view.buffer = null; <ide> if (element && element.nodeType === 1) { <ide> // We have hooks, we shouldn't make element observable <ide><path>packages/ember-views/lib/views/container_view.js <ide> var states = cloneStates(EmberViewStates); <ide> @extends Ember.View <ide> */ <ide> var ContainerView = View.extend(MutableArray, { <del> isContainer: true, <ide> _states: states, <ide> <ide> willWatchProperty: function(prop){ <ide> var ContainerView = View.extend(MutableArray, { <ide> @param {Ember.RenderBuffer} buffer the buffer to render to <ide> */ <ide> render: function(buffer) { <add> var element = buffer.element(); <add> var dom = buffer.dom; <add> <add> if (this.tagName === '') { <add> if (this._morph) { <add> this._childViewsMorph = this._morph; <add> } else { <add> element = dom.createDocumentFragment(); <add> this._childViewsMorph = dom.appendMorph(element); <add> } <add> } else { <add> this._childViewsMorph = dom.createMorph(element, element.lastChild, null); <add> } <add> <add> return element; <ide> }, <ide> <ide> instrumentName: 'container', <ide><path>packages/ember-views/lib/views/core_view.js <ide> import { instrument } from "ember-metal/instrumentation"; <ide> var CoreView = EmberObject.extend(Evented, ActionHandler, { <ide> isView: true, <ide> isVirtual: false, <del> isContainer: false, <ide> <ide> _states: cloneStates(states), <ide> <ide><path>packages/ember-views/tests/system/event_dispatcher_test.js <ide> test("should dispatch events to views", function() { <ide> var childKeyDownCalled = 0; <ide> var parentKeyDownCalled = 0; <ide> <del> view = ContainerView.createWithMixins({ <del> childViews: ['child'], <del> <del> child: View.extend({ <del> render: function(buffer) { <del> buffer.push('<span id="wot">ewot</span>'); <del> }, <add> var childView = View.createWithMixins({ <add> render: function(buffer) { <add> buffer.push('<span id="wot">ewot</span>'); <add> }, <ide> <del> keyDown: function(evt) { <del> childKeyDownCalled++; <add> keyDown: function(evt) { <add> childKeyDownCalled++; <ide> <del> return false; <del> } <del> }), <add> return false; <add> } <add> }); <ide> <add> view = View.createWithMixins({ <ide> render: function(buffer) { <ide> buffer.push('some <span id="awesome">awesome</span> content'); <del> this._super(buffer); <add> this.appendChild(childView); <ide> }, <ide> <ide> mouseDown: function(evt) {
4
Javascript
Javascript
add handlebars to benchmark runner
25b38af12370c8be97cb75d19cb244ebaee0df85
<ide><path>benchmarks/runner.js <ide> function makeiframe(emberPath, suitePath, profile, callback) { <ide> write("<title>" + name + "</title>"); <ide> write("<script src='../lib/jquery-1.7.2.js'></script>"); <ide> write("<script>ENV = {VIEW_PRESERVES_CONTEXT: true};</script>"); <add> write("<script src='../lib/handlebars-1.0.0.beta.6.js'></script>"); <ide> write("<script src='" + emberPath + "'></script>"); <ide> write("<script src='benchmark.js'></script>"); <ide> write("<script src='iframe_runner.js'></script>");
1
Go
Go
fix typo in comments
ae6cf966f9ed4bc98d07619fde3344be7cbffc99
<ide><path>layer/layer.go <ide> type RWLayer interface { <ide> Parent() Layer <ide> <ide> // Mount mounts the RWLayer and returns the filesystem path <del> // the to the writable layer. <add> // to the writable layer. <ide> Mount(mountLabel string) (containerfs.ContainerFS, error) <ide> <ide> // Unmount unmounts the RWLayer. This should be called
1