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 |
|---|---|---|---|---|---|
Ruby | Ruby | use a semaphore to signal message availability | 604fd2cb227d92bed1b738e71feb4ff5360f4491 | <ide><path>actioncable/test/client_test.rb
<ide> def initialize(port)
<ide> @ws = Faye::WebSocket::Client.new("ws://127.0.0.1:#{port}/")
<ide> @messages = Queue.new
<ide> @closed = Concurrent::Event.new
<del> @has_messages = Concurrent::Event.new
<add> @has_messages = Concurrent::Semaphore.new(0)
<ide> @pings = 0
<ide>
<ide> open = Concurrent::Event.new
<ide> def initialize(port)
<ide> @pings += 1
<ide> else
<ide> @messages << hash
<del> @has_messages.set
<add> @has_messages.release
<ide> end
<ide> end
<ide>
<ide> def initialize(port)
<ide> end
<ide>
<ide> def read_message
<del> @has_messages.wait(WAIT_WHEN_EXPECTING_EVENT) if @messages.empty?
<del> @has_messages.reset if @messages.size < 2
<add> @has_messages.try_acquire(1, WAIT_WHEN_EXPECTING_EVENT)
<ide>
<ide> msg = @messages.pop(true)
<ide> raise msg if msg.is_a?(Exception)
<ide> def read_message
<ide> def read_messages(expected_size = 0)
<ide> list = []
<ide> loop do
<del> @has_messages.wait(list.size < expected_size ? WAIT_WHEN_EXPECTING_EVENT : WAIT_WHEN_NOT_EXPECTING_EVENT)
<del> if @has_messages.set?
<del> list << read_message
<add> if @has_messages.try_acquire(1, list.size < expected_size ? WAIT_WHEN_EXPECTING_EVENT : WAIT_WHEN_NOT_EXPECTING_EVENT)
<add> msg = @messages.pop(true)
<add> raise msg if msg.is_a?(Exception)
<add>
<add> list << msg
<ide> else
<ide> break
<ide> end | 1 |
PHP | PHP | fix incorrect doc block in cakesession | ba02cf7a9a60a79b107c884e06656984de3e1507 | <ide><path>lib/Cake/Model/Datasource/CakeSession.php
<ide> class CakeSession {
<ide>
<ide> /**
<ide> * Number of requests that can occur during a session time without the session being renewed.
<del> * This feature is only used when `Session.harden` is set to true.
<add> * This feature is only used when `Session.autoRegenerate` is set to true.
<ide> *
<ide> * @var integer
<ide> * @see CakeSession::_checkValid() | 1 |
Python | Python | evaluate content at function start | 66fa40c300b4d3e768b4a7993f020056c44fdda3 | <ide><path>rest_framework/utils/formatting.py
<ide> def dedent(content):
<ide> as it fails to dedent multiline docstrings that include
<ide> unindented text on the initial line.
<ide> """
<add> content = unicode(content)
<ide> whitespace_counts = [len(line) - len(line.lstrip(' '))
<ide> for line in content.splitlines()[1:] if line.lstrip()]
<ide>
<ide> # unindent the content if needed
<ide> if whitespace_counts:
<ide> whitespace_pattern = '^' + (' ' * min(whitespace_counts))
<del> content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', unicode(content))
<add> content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
<ide>
<ide> return content.strip()
<ide> | 1 |
Python | Python | fix minor typos | 108d01a0a4eea38ed5b8e88de34ee2d0324fec65 | <ide><path>doc/summarize.py
<ide>
<ide> import os, glob, re, sys, inspect, optparse
<ide> try:
<del> # Accessing collections abstact classes from collections
<add> # Accessing collections abstract classes from collections
<ide> # has been deprecated since Python 3.3
<ide> import collections.abc as collections_abc
<ide> except ImportError:
<ide><path>numpy/core/numeric.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> try:
<del> # Accessing collections abstact classes from collections
<add> # Accessing collections abstract classes from collections
<ide> # has been deprecated since Python 3.3
<ide> import collections.abc as collections_abc
<ide> except ImportError:
<ide><path>numpy/core/tests/test_multiarray.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> try:
<del> # Accessing collections abstact classes from collections
<add> # Accessing collections abstract classes from collections
<ide> # has been deprecated since Python 3.3
<ide> import collections.abc as collections_abc
<ide> except ImportError:
<ide><path>numpy/core/tests/test_records.py
<ide>
<ide> import sys
<ide> try:
<del> # Accessing collections abstact classes from collections
<add> # Accessing collections abstract classes from collections
<ide> # has been deprecated since Python 3.3
<ide> import collections.abc as collections_abc
<ide> except ImportError:
<ide><path>numpy/core/tests/test_ufunc.py
<ide> def test_axes_argument(self):
<ide> assert_array_equal(c, (a * b).sum(0))
<ide> c = in1d(a, b, axes=[0, 2])
<ide> assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1))
<del> # Check errors for inproperly constructed axes arguments.
<add> # Check errors for improperly constructed axes arguments.
<ide> # should have list.
<ide> assert_raises(TypeError, in1d, a, b, axes=-1)
<ide> # needs enough elements
<ide> def test_axes_argument(self):
<ide> d = mm(a, b, out=c, axes=[(-2, -1), (-2, -1), (3, 0)])
<ide> assert_(c is d)
<ide> assert_array_equal(c, np.matmul(a, b).transpose(3, 0, 1, 2))
<del> # Check errors for inproperly constructed axes arguments.
<add> # Check errors for improperly constructed axes arguments.
<ide> # wrong argument
<ide> assert_raises(TypeError, mm, a, b, axis=1)
<ide> # axes should be list
<ide><path>numpy/doc/subclassing.py
<ide> def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
<ide>
<ide> Prior to numpy 1.13, the behaviour of ufuncs could only be tuned using
<ide> ``__array_wrap__`` and ``__array_prepare__``. These two allowed one to
<del>change the output type of a ufunc, but, in constrast to
<add>change the output type of a ufunc, but, in contrast to
<ide> ``__array_ufunc__``, did not allow one to make any changes to the inputs.
<ide> It is hoped to eventually deprecate these, but ``__array_wrap__`` is also
<ide> used by other numpy functions and methods, such as ``squeeze``, so at the
<ide><path>numpy/f2py/crackfortran.py
<ide> def readfortrancode(ffile, dowithline=show, istop=1):
<ide> def split_by_unquoted(line, characters):
<ide> """
<ide> Splits the line into (line[:i], line[i:]),
<del> where i is the index of first occurence of one of the characters
<add> where i is the index of first occurrence of one of the characters
<ide> not within quotes, or len(line) if no such index exists
<ide> """
<ide> assert not (set('"\'') & set(characters)), "cannot split by unquoted quotes"
<ide><path>numpy/matrixlib/tests/test_defmatrix.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> try:
<del> # Accessing collections abstact classes from collections
<add> # Accessing collections abstract classes from collections
<ide> # has been deprecated since Python 3.3
<ide> import collections.abc as collections_abc
<ide> except ImportError:
<ide><path>numpy/testing/_private/decorators.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> try:
<del> # Accessing collections abstact classes from collections
<add> # Accessing collections abstract classes from collections
<ide> # has been deprecated since Python 3.3
<ide> import collections.abc as collections_abc
<ide> except ImportError:
<ide><path>numpy/testing/pytest_tools/decorators.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> try:
<del> # Accessing collections abstact classes from collections
<add> # Accessing collections abstract classes from collections
<ide> # has been deprecated since Python 3.3
<ide> import collections.abc as collections_abc
<ide> except ImportError: | 10 |
Javascript | Javascript | simplify field flag handling | 375229d6b9fd6368fb3d216e80a05a130fbd6f02 | <ide><path>src/core/annotation.js
<ide> var WidgetAnnotation = (function WidgetAnnotationClosure() {
<ide> *
<ide> * @public
<ide> * @memberof WidgetAnnotation
<del> * @param {number} flag - Bit position, numbered from one instead of
<del> * zero, to check
<add> * @param {number} flag - Hexadecimal representation for an annotation
<add> * field characteristic
<ide> * @return {boolean}
<ide> * @see {@link shared/util.js}
<ide> */
<ide> hasFieldFlag: function WidgetAnnotation_hasFieldFlag(flag) {
<del> var mask = 1 << (flag - 1);
<del> return !!(this.data.fieldFlags & mask);
<add> return !!(this.data.fieldFlags & flag);
<ide> },
<ide> });
<ide>
<ide><path>src/shared/util.js
<ide> var AnnotationFlag = {
<ide> };
<ide>
<ide> var AnnotationFieldFlag = {
<del> READONLY: 1,
<del> REQUIRED: 2,
<del> NOEXPORT: 3,
<del> MULTILINE: 13,
<del> PASSWORD: 14,
<del> NOTOGGLETOOFF: 15,
<del> RADIO: 16,
<del> PUSHBUTTON: 17,
<del> COMBO: 18,
<del> EDIT: 19,
<del> SORT: 20,
<del> FILESELECT: 21,
<del> MULTISELECT: 22,
<del> DONOTSPELLCHECK: 23,
<del> DONOTSCROLL: 24,
<del> COMB: 25,
<del> RICHTEXT: 26,
<del> RADIOSINUNISON: 26,
<del> COMMITONSELCHANGE: 27,
<add> READONLY: 0x0000001,
<add> REQUIRED: 0x0000002,
<add> NOEXPORT: 0x0000004,
<add> MULTILINE: 0x0001000,
<add> PASSWORD: 0x0002000,
<add> NOTOGGLETOOFF: 0x0004000,
<add> RADIO: 0x0008000,
<add> PUSHBUTTON: 0x0010000,
<add> COMBO: 0x0020000,
<add> EDIT: 0x0040000,
<add> SORT: 0x0080000,
<add> FILESELECT: 0x0100000,
<add> MULTISELECT: 0x0200000,
<add> DONOTSPELLCHECK: 0x0400000,
<add> DONOTSCROLL: 0x0800000,
<add> COMB: 0x1000000,
<add> RICHTEXT: 0x2000000,
<add> RADIOSINUNISON: 0x2000000,
<add> COMMITONSELCHANGE: 0x4000000,
<ide> };
<ide>
<ide> var AnnotationBorderStyleType = {
<ide><path>test/unit/annotation_layer_spec.js
<ide> describe('Annotation layer', function() {
<ide>
<ide> it('should set valid text alignment, maximum length and flags',
<ide> function() {
<del> var flags = 0;
<del> flags |= 1 << (AnnotationFieldFlag.READONLY - 1);
<del> flags |= 1 << (AnnotationFieldFlag.MULTILINE - 1);
<del>
<ide> textWidgetDict.set('Q', 1);
<ide> textWidgetDict.set('MaxLen', 20);
<del> textWidgetDict.set('Ff', flags);
<add> textWidgetDict.set('Ff', AnnotationFieldFlag.READONLY +
<add> AnnotationFieldFlag.MULTILINE);
<ide>
<ide> var textWidgetRef = new Ref(84, 0);
<ide> var xref = new XRefMock([
<ide> describe('Annotation layer', function() {
<ide> });
<ide>
<ide> it('should reject comb fields without a maximum length', function() {
<del> var flags = 0;
<del> flags |= 1 << (AnnotationFieldFlag.COMB - 1);
<del>
<del> textWidgetDict.set('Ff', flags);
<add> textWidgetDict.set('Ff', AnnotationFieldFlag.COMB);
<ide>
<ide> var textWidgetRef = new Ref(46, 0);
<ide> var xref = new XRefMock([
<ide> describe('Annotation layer', function() {
<ide> });
<ide>
<ide> it('should accept comb fields with a maximum length', function() {
<del> var flags = 0;
<del> flags |= 1 << (AnnotationFieldFlag.COMB - 1);
<del>
<ide> textWidgetDict.set('MaxLen', 20);
<del> textWidgetDict.set('Ff', flags);
<add> textWidgetDict.set('Ff', AnnotationFieldFlag.COMB);
<ide>
<ide> var textWidgetRef = new Ref(46, 0);
<ide> var xref = new XRefMock([
<ide> describe('Annotation layer', function() {
<ide>
<ide> it('should only accept comb fields when the flags are valid', function() {
<ide> var invalidFieldFlags = [
<del> AnnotationFieldFlag.MULTILINE,
<del> AnnotationFieldFlag.PASSWORD,
<add> AnnotationFieldFlag.MULTILINE, AnnotationFieldFlag.PASSWORD,
<ide> AnnotationFieldFlag.FILESELECT
<ide> ];
<ide>
<del> // The field may not use combs until all invalid flags are unset.
<del> for (var i = 0, ii = invalidFieldFlags.length; i <= ii; i++) {
<del> var flags = 0;
<del> flags |= 1 << (AnnotationFieldFlag.COMB - 1);
<del>
<del> for (var j = 0, jj = invalidFieldFlags.length; j < jj; j++) {
<del> flags |= 1 << (invalidFieldFlags[j] - 1);
<del> }
<add> // Start with all invalid flags set and remove them one by one.
<add> // The field may only use combs when all invalid flags are unset.
<add> var flags = AnnotationFieldFlag.COMB + AnnotationFieldFlag.MULTILINE +
<add> AnnotationFieldFlag.PASSWORD + AnnotationFieldFlag.FILESELECT;
<ide>
<add> for (var i = 0, ii = invalidFieldFlags.length; i <= ii; i++) {
<ide> textWidgetDict.set('MaxLen', 20);
<ide> textWidgetDict.set('Ff', flags);
<ide>
<ide> describe('Annotation layer', function() {
<ide>
<ide> // Remove the last invalid flag for the next iteration.
<ide> if (!valid) {
<del> invalidFieldFlags.splice(-1, 1);
<add> flags -= invalidFieldFlags.splice(-1, 1);
<ide> }
<ide> }
<ide> }); | 3 |
Text | Text | remove inaccessible fields from anon test | 315bfb07f13b5f56474bc453bff03e39053fa573 | <ide><path>curriculum/challenges/english/09-information-security/information-security-projects/anonymous-message-board.md
<ide> async (getUserInput) => {
<ide> assert.isNotNull(parsed[0]._id);
<ide> assert.equal(new Date(parsed[0].created_on).toDateString(), date.toDateString());
<ide> assert.equal(parsed[0].bumped_on, parsed[0].created_on);
<del> assert.isBoolean(parsed[0].reported);
<del> assert.equal(parsed[0].delete_password, deletePassword);
<ide> assert.isArray(parsed[0].replies);
<ide> } catch (err) {
<ide> throw new Error(err.responseText || err.message); | 1 |
Javascript | Javascript | wrap empty string test in try catch | 47dab76b58c01227de72bf99c1df3062d21e550a | <ide><path>test/moment/is_valid.js
<ide> exports.is_valid = {
<ide> test.equal(moment("null", "X").isValid(), false, 'string null');
<ide> test.equal(moment([], "X").isValid(), false, 'array');
<ide> test.equal(moment("{}", "X").isValid(), false, 'object');
<del> test.equal(moment("", "X").isValid(), false, 'string empty');
<add> try {
<add> test.equal(moment("", "X").isValid(), false, 'string empty');
<add> } catch (e) {
<add> test.ok(true, 'string empty');
<add> }
<add>
<ide> test.equal(moment(" ", "X").isValid(), false, 'string space');
<ide> test.done();
<ide> } | 1 |
Javascript | Javascript | add babel-node to seed | e17b838c800ce98de7e853ae8595107d45f6208d | <ide><path>seed/index.js
<ide> /* eslint-disable no-process-exit */
<add>require('babel/register');
<ide> require('dotenv').load();
<ide> var fs = require('fs'),
<ide> path = require('path'), | 1 |
PHP | PHP | fix more typehint issues | d8f81dc6d892a400de8faccedc48f00d7f464b19 | <ide><path>src/TestSuite/Stub/ConsoleOutput.php
<ide> class ConsoleOutput extends ConsoleOutputBase
<ide> * @param int $newlines Number of newlines to append
<ide> * @return void
<ide> */
<del> public function write($message, $newlines = 1)
<add> public function write($message, int $newlines = 1)
<ide> {
<ide> foreach ((array)$message as $line) {
<ide> $this->_out[] = $line;
<ide> public function write($message, $newlines = 1)
<ide> *
<ide> * @return array
<ide> */
<del> public function messages()
<add> public function messages(): array
<ide> {
<ide> return $this->_out;
<ide> }
<ide><path>tests/test_app/TestApp/Shell/ShellTestShell.php
<ide> class ShellTestShell extends Shell
<ide> * @param int $status
<ide> * @return void
<ide> */
<del> protected function _stop($status = Shell::CODE_SUCCESS): void
<add> protected function _stop(int $status = Shell::CODE_SUCCESS): void
<ide> {
<ide> $this->stopped = $status;
<ide> }
<ide><path>tests/test_app/TestApp/Shell/TestingDispatchShell.php
<ide> protected function _welcome()
<ide> $this->out('<info>Welcome to CakePHP Console</info>');
<ide> }
<ide>
<del> public function out($message = null, $newlines = 1, $level = Shell::NORMAL)
<add> public function out($message = null, int $newlines = 1, int $level = Shell::NORMAL)
<ide> {
<ide> echo $message . "\n";
<ide> } | 3 |
PHP | PHP | add actiondispatcher to new http lib | 71623f576daf2c7de8daddac2aac0a4ed61c6df9 | <ide><path>src/Http/ActionDispatcher.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Http;
<add>
<add>use Cake\Controller\Controller;
<add>use Cake\Event\EventDispatcherTrait;
<add>use Cake\Event\EventListenerInterface;
<add>use Cake\Http\ControllerFactory;
<add>use Cake\Network\Request;
<add>use Cake\Network\Response;
<add>use Cake\Routing\DispatcherFactory;
<add>use Cake\Routing\Exception\MissingControllerException;
<add>use Cake\Routing\Router;
<add>use LogicException;
<add>
<add>/**
<add> * This class provides compatibility with dispatcher filters
<add> * and interacting with the controller layers.
<add> *
<add> * Long term this should just be the controller dispatcher, but
<add> * for now it will do a bit more than that.
<add> */
<add>class ActionDispatcher
<add>{
<add> use EventDispatcherTrait;
<add>
<add> /**
<add> * Attached routing filters
<add> *
<add> * @var array
<add> */
<add> protected $filters = [];
<add>
<add> /**
<add> * Controller factory instance.
<add> *
<add> * @var \Cake\Http\ControllerFactory
<add> */
<add> protected $factory;
<add>
<add> /**
<add> * Constructor
<add> *
<add> * @param \Cake\Http\ControllerFactory $factory A controller factory instance.
<add> */
<add> public function __construct($factory = null)
<add> {
<add> // Compatibility with DispatcherFilters.
<add> foreach (DispatcherFactory::filters() as $filter) {
<add> $this->addFilter($filter);
<add> }
<add> $this->factory = $factory ?: new ControllerFactory();
<add> }
<add>
<add> /**
<add> * Dispatches a Request & Response
<add> *
<add> * @param \Cake\Network\Request $request The request to dispatch.
<add> * @param \Cake\Network\Response $response The response to dispatch.
<add> * @return \Cake\Network\Response a modified/replaced response.
<add> */
<add> public function dispatch(Request $request, Response $response)
<add> {
<add> Router::pushRequest($request);
<add> $beforeEvent = $this->dispatchEvent('Dispatcher.beforeDispatch', compact('request', 'response'));
<add>
<add> $request = $beforeEvent->data['request'];
<add> if ($beforeEvent->result instanceof Response) {
<add> return $beforeEvent->result;
<add> }
<add> $controller = $this->factory->create($request, $response);
<add> $response = $this->_invoke($controller);
<add> if (isset($request->params['return'])) {
<add> return $response;
<add> }
<add>
<add> $afterEvent = $this->dispatchEvent('Dispatcher.afterDispatch', compact('request', 'response'));
<add> return $afterEvent->data['response'];
<add> }
<add>
<add> /**
<add> * Invoke a controller's action and wrapping methods.
<add> *
<add> * @param \Cake\Controller\Controller $controller The controller to invoke.
<add> * @return \Cake\Network\Response The response
<add> * @throw \LogicException If the controller action returns a non-response value.
<add> */
<add> protected function _invoke(Controller $controller)
<add> {
<add> $result = $controller->startupProcess();
<add> if ($result instanceof Response) {
<add> return $result;
<add> }
<add>
<add> $response = $controller->invokeAction();
<add> if ($response !== null && !($response instanceof Response)) {
<add> throw new LogicException('Controller actions can only Cake\Network\Response instances');
<add> }
<add>
<add> if (!$response && $controller->autoRender) {
<add> $response = $controller->render();
<add> } elseif (!$response) {
<add> $response = $controller->response;
<add> }
<add>
<add> $result = $controller->shutdownProcess();
<add> if ($result instanceof Response) {
<add> return $result;
<add> }
<add>
<add> return $response;
<add> }
<add>
<add> /**
<add> * Add a filter to this dispatcher.
<add> *
<add> * The added filter will be attached to the event manager used
<add> * by this dispatcher.
<add> *
<add> * @param \Cake\Event\EventListenerInterface $filter The filter to connect. Can be
<add> * any EventListenerInterface. Typically an instance of \Cake\Routing\DispatcherFilter.
<add> * @return void
<add> * @deprecated This is only available for backwards compatibility with DispatchFilters
<add> */
<add> public function addFilter(EventListenerInterface $filter)
<add> {
<add> $this->filters[] = $filter;
<add> $this->eventManager()->on($filter);
<add> }
<add>
<add> /**
<add> * Get the connected filters.
<add> *
<add> * @return array
<add> */
<add> public function getFilters()
<add> {
<add> return $this->filters;
<add> }
<add>}
<ide><path>tests/TestCase/Http/ActionDispatcherTest.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since 3.3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Test\TestCase\Http;
<add>
<add>use Cake\Core\Configure;
<add>use Cake\Http\ActionDispatcher;
<add>use Cake\Network\Request;
<add>use Cake\Network\Response;
<add>use Cake\Network\Session;
<add>use Cake\Routing\DispatcherFactory;
<add>use Cake\Routing\Filter\ControllerFactoryFilter;
<add>use Cake\Routing\Router;
<add>use Cake\TestSuite\TestCase;
<add>
<add>/**
<add> * Test case for the ActionDispatcher.
<add> */
<add>class ActionDispatcherTest extends TestCase
<add>{
<add> /**
<add> * Setup
<add> *
<add> * @return void
<add> */
<add> public function setUp()
<add> {
<add> parent::setUp();
<add> Router::reload();
<add> Configure::write('App.namespace', 'TestApp');
<add> $this->dispatcher = new ActionDispatcher();
<add> $this->dispatcher->addFilter(new ControllerFactoryFilter());
<add> }
<add>
<add> /**
<add> * Teardown
<add> *
<add> * @return void
<add> */
<add> public function tearDown()
<add> {
<add> parent::tearDown();
<add> DispatcherFactory::clear();
<add> }
<add>
<add> /**
<add> * Ensure that filters connected to the DispatcherFactory are
<add> * also applied
<add> */
<add> public function testDispatcherFactoryCompat()
<add> {
<add> $filter = $this->getMock(
<add> 'Cake\Routing\DispatcherFilter',
<add> ['beforeDispatch', 'afterDispatch']
<add> );
<add> DispatcherFactory::add($filter);
<add> $dispatcher = new ActionDispatcher();
<add> $this->assertCount(1, $dispatcher->getFilters());
<add> $this->assertSame($filter, $dispatcher->getFilters()[0]);
<add> }
<add>
<add> /**
<add> * Test adding routing filters
<add> *
<add> * @return void
<add> */
<add> public function testAddFilter()
<add> {
<add> $this->assertCount(1, $this->dispatcher->getFilters());
<add> $events = $this->dispatcher->eventManager();
<add> $this->assertCount(1, $events->listeners('Dispatcher.beforeDispatch'));
<add> $this->assertCount(1, $events->listeners('Dispatcher.afterDispatch'));
<add>
<add> $filter = $this->getMock(
<add> 'Cake\Routing\DispatcherFilter',
<add> ['beforeDispatch', 'afterDispatch']
<add> );
<add> $this->dispatcher->addFilter($filter);
<add>
<add> $this->assertCount(2, $this->dispatcher->getFilters());
<add> $this->assertCount(2, $events->listeners('Dispatcher.beforeDispatch'));
<add> $this->assertCount(2, $events->listeners('Dispatcher.afterDispatch'));
<add> }
<add>
<add> /**
<add> * Ensure that aborting in the beforeDispatch doesn't invoke the controller
<add> *
<add> * @return void
<add> */
<add> public function testBeforeDispatchEventAbort()
<add> {
<add> $response = new Response();
<add> $dispatcher = new ActionDispatcher();
<add> $filter = $this->getMock(
<add> 'Cake\Routing\DispatcherFilter',
<add> ['beforeDispatch', 'afterDispatch']
<add> );
<add> $filter->expects($this->once())
<add> ->method('beforeDispatch')
<add> ->will($this->returnValue($response));
<add>
<add> $req = new Request();
<add> $res = new Response();
<add> $dispatcher->addFilter($filter);
<add> $result = $dispatcher->dispatch($req, $res);
<add> $this->assertSame($response, $result, 'Should be response from filter.');
<add> }
<add>
<add> /**
<add> * Ensure afterDispatch can replace the response
<add> *
<add> * @return void
<add> */
<add> public function testDispatchAfterDispatchEventModifyResponse()
<add> {
<add> $filter = $this->getMock(
<add> 'Cake\Routing\DispatcherFilter',
<add> ['beforeDispatch', 'afterDispatch']
<add> );
<add> $filter->expects($this->once())
<add> ->method('afterDispatch')
<add> ->will($this->returnCallback(function ($event) {
<add> $event->data['response']->body('Filter body');
<add> }));
<add>
<add> $req = new Request([
<add> 'url' => '/cakes',
<add> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => 'Cakes',
<add> 'action' => 'index',
<add> 'pass' => [],
<add> ],
<add> 'session' => new Session
<add> ]);
<add> $res = new Response();
<add> $this->dispatcher->addFilter($filter);
<add> $result = $this->dispatcher->dispatch($req, $res);
<add> $this->assertSame('Filter body', $result->body(), 'Should be response from filter.');
<add> }
<add>
<add> /**
<add> * Test that a controller action returning a response
<add> * results in no afterDispatch event.
<add> *
<add> * @return void
<add> */
<add> public function testDispatchActionReturnResponseNoAfterDispatch()
<add> {
<add> $filter = $this->getMock(
<add> 'Cake\Routing\DispatcherFilter',
<add> ['beforeDispatch', 'afterDispatch']
<add> );
<add> $filter->expects($this->never())
<add> ->method('afterDispatch');
<add>
<add> $req = new Request([
<add> 'url' => '/cakes',
<add> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => 'Cakes',
<add> 'action' => 'index',
<add> 'pass' => [],
<add> 'return' => true,
<add> ],
<add> ]);
<add> $res = new Response();
<add> $this->dispatcher->addFilter($filter);
<add> $result = $this->dispatcher->dispatch($req, $res);
<add> $this->assertSame('Hello Jane', $result->body(), 'Response from controller.');
<add> }
<add>
<add> /**
<add> * Test that dispatching sets the Router request state.
<add> *
<add> * @return void
<add> */
<add> public function testDispatchSetsRequestContext()
<add> {
<add> $this->assertNull(Router::getRequest());
<add> $req = new Request([
<add> 'url' => '/cakes',
<add> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => 'Cakes',
<add> 'action' => 'index',
<add> 'pass' => [],
<add> 'return' => true,
<add> ],
<add> ]);
<add> $res = new Response();
<add> $this->dispatcher->dispatch($req, $res);
<add> $this->assertSame($req, Router::getRequest(true));
<add> }
<add>
<add> /**
<add> * test invalid response from dispatch process.
<add> *
<add> * @expectedException \LogicException
<add> * @expectedExceptionMessage Controller actions can only Cake\Network\Response instances
<add> * @return void
<add> */
<add> public function testDispatchInvalidResponse()
<add> {
<add> $req = new Request([
<add> 'url' => '/cakes',
<add> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => 'Cakes',
<add> 'action' => 'invalid',
<add> 'pass' => [],
<add> ],
<add> ]);
<add> $res = new Response();
<add> $result = $this->dispatcher->dispatch($req, $res);
<add> }
<add>
<add> /**
<add> * Test dispatch with autorender
<add> *
<add> * @return void
<add> */
<add> public function testDispatchAutoRender()
<add> {
<add> $request = new Request([
<add> 'url' => 'posts',
<add> 'params' => [
<add> 'controller' => 'Posts',
<add> 'action' => 'index',
<add> 'pass' => [],
<add> ]
<add> ]);
<add> $response = new Response();
<add> $result = $this->dispatcher->dispatch($request, $response);
<add> $this->assertInstanceOf('Cake\Network\Response', $result);
<add> $this->assertContains('posts index', $result->body());
<add> }
<add>
<add> /**
<add> * Test dispatch with autorender=false
<add> *
<add> * @return void
<add> */
<add> public function testDispatchAutoRenderFalse()
<add> {
<add> $request = new Request([
<add> 'url' => 'posts',
<add> 'params' => [
<add> 'controller' => 'Cakes',
<add> 'action' => 'noRender',
<add> 'pass' => [],
<add> ]
<add> ]);
<add> $response = new Response();
<add> $result = $this->dispatcher->dispatch($request, $response);
<add> $this->assertInstanceOf('Cake\Network\Response', $result);
<add> $this->assertContains('autoRender false body', $result->body());
<add> }
<add>
<add> /**
<add> * testMissingController method
<add> *
<add> * @expectedException \Cake\Routing\Exception\MissingControllerException
<add> * @expectedExceptionMessage Controller class SomeController could not be found.
<add> * @return void
<add> */
<add> public function testMissingController()
<add> {
<add> $request = new Request([
<add> 'url' => 'some_controller/home',
<add> 'params' => [
<add> 'controller' => 'SomeController',
<add> 'action' => 'home',
<add> ]
<add> ]);
<add> $response = $this->getMock('Cake\Network\Response');
<add> $this->dispatcher->dispatch($request, $response);
<add> }
<add>
<add> /**
<add> * testMissingControllerInterface method
<add> *
<add> * @expectedException \Cake\Routing\Exception\MissingControllerException
<add> * @expectedExceptionMessage Controller class Interface could not be found.
<add> * @return void
<add> */
<add> public function testMissingControllerInterface()
<add> {
<add> $request = new Request([
<add> 'url' => 'interface/index',
<add> 'params' => [
<add> 'controller' => 'Interface',
<add> 'action' => 'index',
<add> ]
<add> ]);
<add> $response = $this->getMock('Cake\Network\Response');
<add> $this->dispatcher->dispatch($request, $response);
<add> }
<add>
<add> /**
<add> * testMissingControllerInterface method
<add> *
<add> * @expectedException \Cake\Routing\Exception\MissingControllerException
<add> * @expectedExceptionMessage Controller class Abstract could not be found.
<add> * @return void
<add> */
<add> public function testMissingControllerAbstract()
<add> {
<add> $request = new Request([
<add> 'url' => 'abstract/index',
<add> 'params' => [
<add> 'controller' => 'Abstract',
<add> 'action' => 'index',
<add> ]
<add> ]);
<add> $response = $this->getMock('Cake\Network\Response');
<add> $this->dispatcher->dispatch($request, $response);
<add> }
<add>
<add> /**
<add> * Test that lowercase controller names result in missing controller errors.
<add> *
<add> * In case-insensitive file systems, lowercase controller names will kind of work.
<add> * This causes annoying deployment issues for lots of folks.
<add> *
<add> * @expectedException \Cake\Routing\Exception\MissingControllerException
<add> * @expectedExceptionMessage Controller class somepages could not be found.
<add> * @return void
<add> */
<add> public function testMissingControllerLowercase()
<add> {
<add> $request = new Request([
<add> 'url' => 'pages/home',
<add> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => 'somepages',
<add> 'action' => 'display',
<add> 'pass' => ['home'],
<add> ]
<add> ]);
<add> $response = $this->getMock('Cake\Network\Response');
<add> $this->dispatcher->dispatch($request, $response);
<add> }
<add>
<add> /**
<add> * Ensure that a controller's startup event can stop the request.
<add> *
<add> * @return void
<add> */
<add> public function testStartupProcessAbort()
<add> {
<add> $request = new Request([
<add> 'url' => 'cakes/index',
<add> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => 'Cakes',
<add> 'action' => 'index',
<add> 'stop' => 'startup',
<add> 'pass' => [],
<add> ]
<add> ]);
<add> $response = new Response();
<add> $result = $this->dispatcher->dispatch($request, $response);
<add> $this->assertSame('startup stop', $result->body());
<add> }
<add>
<add> /**
<add> * Ensure that a controllers startup process can emit a response
<add> *
<add> * @return void
<add> */
<add> public function testShutdownProcessResponse()
<add> {
<add> $request = new Request([
<add> 'url' => 'cakes/index',
<add> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => 'Cakes',
<add> 'action' => 'index',
<add> 'stop' => 'shutdown',
<add> 'pass' => [],
<add> ]
<add> ]);
<add> $response = new Response();
<add> $result = $this->dispatcher->dispatch($request, $response);
<add> $this->assertSame('shutdown stop', $result->body());
<add> }
<add>}
<ide><path>tests/test_app/TestApp/Controller/CakesController.php
<ide> public function index()
<ide> return $this->response;
<ide> }
<ide>
<add> /**
<add> * No autoRender
<add> *
<add> * @return void
<add> */
<add> public function noRender()
<add> {
<add> $this->autoRender = false;
<add> $this->response->body('autoRender false body');
<add> }
<add>
<ide> /**
<ide> * invalid method
<ide> *
<ide> public function invalid()
<ide> {
<ide> return 'Some string';
<ide> }
<add>
<add> /**
<add> * startup process.
<add> */
<add> public function startupProcess()
<add> {
<add> parent::startupProcess();
<add> if ($this->request->param('stop') === 'startup') {
<add> $this->response->body('startup stop');
<add> return $this->response;
<add> }
<add> }
<add>
<add> /**
<add> * shutdown process.
<add> */
<add> public function shutdownProcess()
<add> {
<add> parent::shutdownProcess();
<add> if ($this->request->param('stop') === 'shutdown') {
<add> $this->response->body('shutdown stop');
<add> return $this->response;
<add> }
<add> }
<ide> } | 3 |
PHP | PHP | add controller and controller_action to route | 21a51b7cf95fc02b327d65afa0fbba1387800c0e | <ide><path>laravel/routing/controller.php
<ide> public static function call($destination, $parameters = array())
<ide> // improve speed since the bundle is not loaded on every request.
<ide> Bundle::start($bundle);
<ide>
<del> list($controller_name, $method) = explode('@', $destination);
<add> list($name, $method) = explode('@', $destination);
<ide>
<del> $controller = static::resolve($bundle, $controller_name);
<del>
<del> $controller->bundle = $bundle;
<del> $controller->name = $controller_name;
<del> $controller->action = $method;
<add> $controller = static::resolve($bundle, $name);
<add>
<add> // For convenience we will set the current controller and action on the
<add> // Request's route instance so they can be easily accessed from the
<add> // application. This is sometimes useful for dynamic situations.
<add> if ( ! is_null($route = Request::route()))
<add> {
<add> $route->controller = $name;
<add>
<add> $route->controller_action = $method;
<add> }
<ide>
<ide> // If the controller could not be resolved, we're out of options and
<ide> // will return the 404 error response. If we found the controller,
<ide><path>laravel/routing/route.php
<ide> class Route {
<ide> */
<ide> public $bundle;
<ide>
<add> /**
<add> * The name of the controller used by the route.
<add> *
<add> * @var string
<add> */
<add> public $controller;
<add>
<add> /**
<add> * The name of the controller action used by the route.
<add> *
<add> * @var string
<add> */
<add> public $controller_action;
<add>
<ide> /**
<ide> * The action that is assigned to the route.
<ide> * | 2 |
Ruby | Ruby | consider missing links to cellar | 8634f19107d98e56fa12165e92800a2120e9b13e | <ide><path>Library/Homebrew/linkage_checker.rb
<ide> def check_undeclared_deps
<ide> end
<ide> missing = []
<ide> @broken_dylibs.each do |str|
<del> next unless str.start_with? "#{HOMEBREW_PREFIX}/opt"
<del> missing << str.sub("#{HOMEBREW_PREFIX}/opt/", "").split("/")[0]
<add> next unless str.start_with?("#{HOMEBREW_PREFIX}/opt", HOMEBREW_CELLAR)
<add> missing << str.sub("#{HOMEBREW_PREFIX}/opt/", "").sub("#{HOMEBREW_CELLAR}/", "").split("/")[0]
<ide> end
<ide> unnecessary_deps -= missing
<ide> [indirect_deps, undeclared_deps, unnecessary_deps] | 1 |
PHP | PHP | allow string in some builder param types | 6690c2c0f1887475712569cbe902e93be12ccb1a | <ide><path>src/Illuminate/Database/Concerns/BuildsQueries.php
<ide> public function eachById(callable $callback, $count = 1000, $column = null, $ali
<ide> /**
<ide> * Execute the query and get the first result.
<ide> *
<del> * @param array $columns
<add> * @param array|string $columns
<ide> * @return \Illuminate\Database\Eloquent\Model|object|static|null
<ide> */
<ide> public function first($columns = ['*'])
<ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function value($column)
<ide> /**
<ide> * Execute the query as a "select" statement.
<ide> *
<del> * @param array $columns
<add> * @param array|string $columns
<ide> * @return \Illuminate\Database\Eloquent\Collection|static[]
<ide> */
<ide> public function get($columns = ['*'])
<ide> public function get($columns = ['*'])
<ide> /**
<ide> * Get the hydrated models without eager loading.
<ide> *
<del> * @param array $columns
<add> * @param array|string $columns
<ide> * @return \Illuminate\Database\Eloquent\Model[]|static[]
<ide> */
<ide> public function getModels($columns = ['*']) | 2 |
Javascript | Javascript | minize flash state | 6c5a13f053b5f9856fcd13958037af88a095a31b | <ide><path>common/app/Flash/redux/index.js
<ide> export const alertTypes = _.keyBy(_.identity)([
<ide> 'warning',
<ide> 'danger'
<ide> ]);
<del>export const normalizeAlertType = _.get(alertTypes, 'info');
<add>export const normalizeAlertType = alertType => alertTypes[alertType] || 'info';
<ide>
<ide> export const getFlashAction = _.flow(
<ide> _.property('meta'),
<ide> export const expressToStack = _.flow(
<ide> })))
<ide> );
<ide>
<del>const defaultState = {
<del> stack: [{ alertType: 'danger', message: 'foo nar' }]
<del>};
<add>const defaultState = [];
<ide>
<ide> const getNS = _.property(ns);
<ide>
<ide> export const latestMessageSelector = _.flow(
<ide> getNS,
<del> _.property('stack'),
<ide> _.head,
<ide> _.defaultTo({})
<ide> );
<ide> export default composeReducers(
<ide> ns,
<ide> handleActions(
<ide> () => ({
<del> [types.clickOnClose]: (state) => ({
<add> [types.clickOnClose]: _.tail,
<add> [types.messagesFoundOnBoot]: (state, { payload }) => [
<ide> ...state,
<del> stack: _.tail(state.stack)
<del> }),
<del> [types.messagesFoundOnBoot]: (state, { payload }) => ({
<del> ...state,
<del> stack: [...state.stack, ...expressToStack(payload)]
<del> })
<add> ...expressToStack(payload)
<add> ]
<ide> }),
<ide> defaultState,
<ide> ),
<ide> function metaReducer(state = defaultState, action) {
<ide> if (isFlashAction(action)) {
<ide> const { payload: { alertType, message } } = getFlashAction(action);
<del> return {
<add> return [
<ide> ...state,
<del> stack: [
<del> ...state.stack,
<del> {
<del> alertType: normalizeAlertType(alertType),
<del> message: _.escape(message)
<del> }
<del> ]
<del> };
<add> {
<add> alertType: normalizeAlertType(alertType),
<add> message: _.escape(message)
<add> }
<add> ];
<ide> }
<ide> return state;
<ide> } | 1 |
Text | Text | add tests and solution | 4a9559ad98e95514eeffdf9413a108e899668031 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-79-passcode-derivation.md
<ide> dashedName: problem-79-passcode-derivation
<ide>
<ide> # --description--
<ide>
<del>A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317.
<add>A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was `531278`, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: `317`.
<ide>
<del>The array, `keylog`, contains fifty successful login attempts.
<add>The arrays, `keylog1`, `keylog2`, and `keylog3`, contains fifty successful login attempts.
<ide>
<ide> Given that the three characters are always asked for in order, analyze the array so as to determine the shortest possible secret passcode of unknown length.
<ide>
<ide> # --hints--
<ide>
<del>`passcodeDerivation(keylog)` should return a number.
<add>`passcodeDerivation(keylog1)` should return a number.
<ide>
<ide> ```js
<del>assert(typeof passcodeDerivation(keylog) === 'number');
<add>assert(typeof passcodeDerivation(_keylog1) === 'number');
<ide> ```
<ide>
<del>`passcodeDerivation(keylog)` should return 73162890.
<add>`passcodeDerivation(keylog1)` should return `531278`.
<ide>
<ide> ```js
<del>assert.strictEqual(passcodeDerivation(keylog), 73162890);
<add>assert.strictEqual(passcodeDerivation(_keylog1), 531278);
<add>```
<add>
<add>`passcodeDerivation(keylog2)` should return `1230567`.
<add>
<add>```js
<add>assert.strictEqual(passcodeDerivation(_keylog2), 1230567);
<add>```
<add>
<add>`passcodeDerivation(keylog3)` should return `73162890`.
<add>
<add>```js
<add>assert.strictEqual(passcodeDerivation(_keylog3), 73162890);
<ide> ```
<ide>
<ide> # --seed--
<ide>
<add>## --after-user-code--
<add>
<add>```js
<add>const _keylog1 = [
<add> 127,327,178,528,537,538,532,328,127,178,537,127,317,328,512,278,328,327,178,327,578,317,527,178,128,328,517,312,531,128,128,317,527,312,328,532,512,518,317,127,537,528,537,527,327,278,532,128, 318,517
<add>];
<add>const _keylog2 = [
<add> 305,367,256,123,357,120,125,307,236,256,356,267,357,256,356,136,257,107,126,567,567,105,120,237,367,120,367,135,207,167,367,367,307,125,120,130,367,230,106,356,126,106,130,123,307,127,306,167,136,126
<add>];
<add>const _keylog3 = [
<add> 319,680,180,690,129,620,762,689,762,318,368,710,720,710,629,168,160,689,716,731,736,729,316,729,729,710,769,290,719,680,318,389,162,289,162,718,729,319,790,680,890,362,319,760,316,729,380,319,728,716,
<add>];
<add>```
<add>
<ide> ## --seed-contents--
<ide>
<ide> ```js
<ide> function passcodeDerivation(arr) {
<ide>
<ide> // Only change code above this line
<ide>
<del>const keylog = [
<add>const keylog1 = [
<ide> 319,680,180,690,129,620,762,689,762,318,368,710,720,710,629,168,160,689,716,731,736,729,316,729,729,710,769,290,719,680,318,389,162,289,162,718,729,319,790,680,890,362,319,760,316,729,380,319,728,716,
<ide> ];
<ide>
<del>passcodeDerivation(keylog);
<add>passcodeDerivation(keylog1);
<ide> ```
<ide>
<ide> # --solutions--
<ide>
<ide> ```js
<del>// solution required
<add>function passcodeDerivation(arr) {
<add> const numbersInPasscode = [];
<add> const relativePositions = new Array(10)
<add> .fill()
<add> .map(() => new Array(10).fill(0));
<add>
<add> for (let i = 0; i < arr.length; i++) {
<add> const curAttempt = arr[i]
<add> .toString()
<add> .split('')
<add> .map(key => parseInt(key, 10));
<add> for (let j = 0; j < curAttempt.length; j++) {
<add> if (numbersInPasscode.indexOf(curAttempt[j]) === -1) {
<add> numbersInPasscode.push(curAttempt[j]);
<add> }
<add> for (let k = j + 1; k < curAttempt.length; k++) {
<add> relativePositions[curAttempt[j]][curAttempt[k]] += 1;
<add> }
<add> }
<add> }
<add>
<add> const ranks = {};
<add> for (let i = 0; i < numbersInPasscode.length; i++) {
<add> const curNumber = numbersInPasscode[i];
<add> ranks[curNumber] = relativePositions[curNumber].filter(
<add> count => count > 0
<add> ).length;
<add> }
<add>
<add> const passcode = numbersInPasscode
<add> .sort((i, j) => ranks[i] - ranks[j])
<add> .reverse()
<add> .join('');
<add>
<add> return parseInt(passcode, 10);
<add>}
<ide> ``` | 1 |
Javascript | Javascript | fix unmount crash when using sticky headers | 7005f54ab5f0b15326ff61d706abae93df2f5a56 | <ide><path>Libraries/CustomComponents/Lists/VirtualizedList.js
<ide> class VirtualizedList extends React.PureComponent<OptionalProps, Props, State> {
<ide> index={ii}
<ide> item={item}
<ide> key={key}
<del> onLayout={this._onCellLayout}
<add> onCellLayout={this._onCellLayout}
<ide> onUnmount={this._onCellUnmount}
<ide> parentProps={this.props}
<ide> />
<ide> class CellRenderer extends React.Component {
<ide> cellKey: string,
<ide> index: number,
<ide> item: Item,
<del> onLayout: (event: Object, cellKey: string, index: number) => void,
<add> onCellLayout: (event: Object, cellKey: string, index: number) => void,
<ide> onUnmount: (cellKey: string) => void,
<ide> parentProps: {
<ide> renderItem: renderItemType,
<ide> class CellRenderer extends React.Component {
<ide> },
<ide> };
<ide> _onLayout = (e) => {
<del> this.props.onLayout(e, this.props.cellKey, this.props.index);
<add> this.props.onCellLayout(e, this.props.cellKey, this.props.index);
<ide> }
<ide> componentWillUnmount() {
<ide> this.props.onUnmount(this.props.cellKey); | 1 |
PHP | PHP | make missingrouteexception a 404 | 8be90f58b6e19576b00ae4f5af4f05e9b10d3667 | <ide><path>src/Routing/Error/MissingRouteException.php
<ide> */
<ide> class MissingRouteException extends Exception {
<ide>
<add>/**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'A route matching "%s" could not be found.';
<ide>
<add>/**
<add> * {@inheritDoc}
<add> */
<add> public function __construct($message, $code = 404) {
<add> parent::__construct($message, $code);
<add> }
<add>
<ide> } | 1 |
Javascript | Javascript | bring the stub atomwindow up to date | db2f8302bf025f4e20e0232138fafd2581d74069 | <ide><path>spec/main-process/atom-application.new.test.js
<ide> class StubWindow extends EventEmitter {
<ide> this._position = {x, y}
<ide> }
<ide>
<del> hasProjectPath () {
<add> hasProjectPaths () {
<ide> return this._rootPaths.size > 0
<ide> }
<ide>
<del> containsPaths (paths) {
<del> return paths.every(p => this.containsPath(p))
<add> containsLocations (locations) {
<add> return locations.every(location => this.containsLocation(location))
<ide> }
<ide>
<del> containsPath (pathToCheck) {
<del> if (!pathToCheck) return false
<del> const stat = fs.statSyncNoException(pathToCheck)
<add> containsLocation (location) {
<add> if (!location.pathToOpen) return false
<add>
<ide> return Array.from(this._rootPaths).some(projectPath => {
<del> if (pathToCheck === projectPath) return true
<del> if (!pathToCheck.startsWith(path.join(projectPath, path.sep))) return false
<del> return !stat || !stat.isDirectory()
<add> if (location.pathToOpen === projectPath) return true
<add> if (location.pathToOpen.startsWith(path.join(projectPath, path.sep))) {
<add> if (!location.exists) return true
<add> if (!location.isDirectory) return true
<add> }
<add> return false
<ide> })
<ide> }
<ide> | 1 |
Java | Java | add marble diagrams to a few single.doonx methods. | fbba23e3dfa99e195ceda68cd7fef7bfc41fccc6 | <ide><path>src/main/java/io/reactivex/Single.java
<ide> public final Single<T> doAfterTerminate(Action onAfterTerminate) {
<ide> * is executed once per subscription.
<ide> * <p>Note that the {@code onFinally} action is shared between subscriptions and as such
<ide> * should be thread-safe.
<add> * <p>
<add> * <img width="640" height="291" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doFinally.png" alt="">
<add> * </p>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> doFinally(Action onFinally) {
<ide> /**
<ide> * Calls the shared consumer with the Disposable sent through the onSubscribe for each
<ide> * SingleObserver that subscribes to the current Single.
<add> * <p>
<add> * <img width="640" height="347" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnSubscribe.png" alt="">
<add> * </p>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doOnSubscribe} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> doOnSubscribe(final Consumer<? super Disposable> onSubscr
<ide> /**
<ide> * Calls the shared consumer with the success value sent via onSuccess for each
<ide> * SingleObserver that subscribes to the current Single.
<add> * <p>
<add> * <img width="640" height="347" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnSuccess.2.png" alt="">
<add> * </p>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doOnSuccess} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> doOnEvent(final BiConsumer<? super T, ? super Throwable>
<ide> /**
<ide> * Calls the shared consumer with the error sent via onError for each
<ide> * SingleObserver that subscribes to the current Single.
<add> * <p>
<add> * <img width="640" height="349" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnError.2.png" alt="">
<add> * </p>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doOnError} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> doOnError(final Consumer<? super Throwable> onError) {
<ide> /**
<ide> * Calls the shared {@code Action} if a SingleObserver subscribed to the current Single
<ide> * disposes the common Disposable it received via onSubscribe.
<add> * <p>
<add> * <img width="640" height="332" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnDispose.png" alt="">
<add> * </p>
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doOnDispose} does not operate by default on a particular {@link Scheduler}.</dd> | 1 |
PHP | PHP | add support for engines to blueprint | d43d866448c3b360e21f575182fd305470c62918 | <ide><path>src/Illuminate/Database/Schema/Blueprint.php
<ide> class Blueprint {
<ide> */
<ide> protected $commands = array();
<ide>
<add> /**
<add> * The storage engine that should be used for the table.
<add> *
<add> * @var string
<add> */
<add> protected $engine;
<add>
<ide> /**
<ide> * Create a new schema blueprint.
<ide> *
<ide><path>src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php
<ide> public function compileCreate(Blueprint $blueprint, Fluent $command, Connection
<ide>
<ide> $sql = 'create table '.$this->wrapTable($blueprint)." ($columns)";
<ide>
<del> return $this->compileCreateEncoding($sql, $connection);
<add> // Once we have the primary SQL, we can add the encoding option to the SQL for
<add> // the table. Then, we can check if a storage engine has been supplied for
<add> // the table. If so, we will add the engine declaration to the SQL query.
<add> $sql = $this->compileCreateEncoding($sql, $connection);
<add>
<add> if (isset($blueprint->engine))
<add> {
<add> $sql .= ' engine = '.$blueprint->engine;
<add> }
<add>
<add> return $sql;
<ide> }
<ide>
<ide> /** | 2 |
Python | Python | add test for #600 fix | 0dbf6c323e2bf49fd8a6c31b805807c92a983650 | <ide><path>numpy/core/tests/test_regression.py
<ide> def rs():
<ide> x |= y
<ide> self.failUnlessRaises(TypeError,rs)
<ide>
<add> def check_unicode_scalar(self, level=rlevel):
<add> """Ticket #600"""
<add> import cPickle
<add> x = N.array(["DROND", "DROND1"], dtype="U6")
<add> el = x[1]
<add> new = cPickle.loads(cPickle.dumps(el))
<add> assert_equal(new, el)
<add>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run() | 1 |
Java | Java | use computeifabsent in resourcebundlemessagesource | 311b3338145038ea92c693bb2a8babec9580deda | <ide><path>spring-context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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> protected MessageFormat resolveCode(String code, Locale locale) {
<ide>
<ide>
<ide> /**
<del> * Return a ResourceBundle for the given basename and code,
<del> * fetching already generated MessageFormats from the cache.
<add> * Return a ResourceBundle for the given basename and Locale,
<add> * fetching already generated ResourceBundle from the cache.
<ide> * @param basename the basename of the ResourceBundle
<ide> * @param locale the Locale to find the ResourceBundle for
<ide> * @return the resulting ResourceBundle, or {@code null} if none
<ide> protected ResourceBundle getResourceBundle(String basename, Locale locale) {
<ide> try {
<ide> ResourceBundle bundle = doGetBundle(basename, locale);
<ide> if (localeMap == null) {
<del> localeMap = new ConcurrentHashMap<>();
<del> Map<Locale, ResourceBundle> existing = this.cachedResourceBundles.putIfAbsent(basename, localeMap);
<del> if (existing != null) {
<del> localeMap = existing;
<del> }
<add> localeMap = this.cachedResourceBundles.computeIfAbsent(basename, bn -> new ConcurrentHashMap<>());
<ide> }
<ide> localeMap.put(locale, bundle);
<ide> return bundle; | 1 |
Python | Python | avoid unneeded call in masked array std method | 65ed5ebfeac3fb6ff8896bf624e1e08113901b76 | <ide><path>numpy/ma/core.py
<ide> def std(self, axis=None, dtype=None, out=None, ddof=0):
<ide> ""
<ide> dvar = self.var(axis=axis, dtype=dtype, out=out, ddof=ddof)
<ide> if dvar is not masked:
<del> dvar = sqrt(dvar)
<ide> if out is not None:
<ide> np.power(out, 0.5, out=out, casting='unsafe')
<ide> return out
<add> dvar = sqrt(dvar)
<ide> return dvar
<ide> std.__doc__ = np.std.__doc__
<ide> | 1 |
Javascript | Javascript | fix the example | b94fb5c8c1a96dae771fa36814ed7e2d54c73b8a | <ide><path>src/ngResource/resource.js
<ide> });
<ide>
<ide> // We can retrieve a collection from the server
<del> var cards = CreditCard.query();
<del> // GET: /user/123/card
<del> // server returns: [ {id:456, number:'1234', name:'Smith'} ];
<del>
<del> var card = cards[0];
<del> // each item is an instance of CreditCard
<del> expect(card instanceof CreditCard).toEqual(true);
<del> card.name = "J. Smith";
<del> // non GET methods are mapped onto the instances
<del> card.$save();
<del> // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
<del> // server returns: {id:456, number:'1234', name: 'J. Smith'};
<del>
<del> // our custom method is mapped as well.
<del> card.$charge({amount:9.99});
<del> // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
<del> // server returns: {id:456, number:'1234', name: 'J. Smith'};
<add> var cards = CreditCard.query(function() {
<add> // GET: /user/123/card
<add> // server returns: [ {id:456, number:'1234', name:'Smith'} ];
<add>
<add> var card = cards[0];
<add> // each item is an instance of CreditCard
<add> expect(card instanceof CreditCard).toEqual(true);
<add> card.name = "J. Smith";
<add> // non GET methods are mapped onto the instances
<add> card.$save();
<add> // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
<add> // server returns: {id:456, number:'1234', name: 'J. Smith'};
<add>
<add> // our custom method is mapped as well.
<add> card.$charge({amount:9.99});
<add> // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
<add> });
<ide>
<ide> // we can create an instance as well
<ide> var newCard = new CreditCard({number:'0123'}); | 1 |
PHP | PHP | fix psalm errors | 6f352d5cd842bd36c1b58575780c8b854df2aaa3 | <ide><path>src/TestSuite/Fixture/TestFixture.php
<ide> class TestFixture implements ConstraintsInterface, FixtureInterface, TableSchema
<ide> /**
<ide> * Instantiate the fixture.
<ide> *
<del> * @throws \Cake\Core\Exception\Exception on invalid datasource usage.
<add> * @throws \Cake\Core\Exception\CakeException on invalid datasource usage.
<ide> */
<ide> public function __construct()
<ide> {
<ide> protected function _schemaFromFields(): void
<ide> * Build fixture schema from a table in another datasource.
<ide> *
<ide> * @return void
<del> * @throws \Cake\Core\Exception\Exception when trying to import from an empty table.
<add> * @throws \Cake\Core\Exception\CakeException when trying to import from an empty table.
<ide> */
<ide> protected function _schemaFromImport(): void
<ide> {
<ide> protected function _schemaFromImport(): void
<ide> * Build fixture schema directly from the datasource
<ide> *
<ide> * @return void
<del> * @throws \Cake\Core\Exception\Exception when trying to reflect a table that does not exist
<add> * @throws \Cake\Core\Exception\CakeException when trying to reflect a table that does not exist
<ide> */
<ide> protected function _schemaFromReflection(): void
<ide> { | 1 |
Python | Python | simplify computation of npy format headers | 340cf9875b911ba858fe6e99147ed29f5e7f0df3 | <ide><path>numpy/lib/format.py
<ide>
<ide> # difference between version 1.0 and 2.0 is a 4 byte (I) header length
<ide> # instead of 2 bytes (H) allowing storage of large structured arrays
<add>_header_size_formats = {
<add> (1, 0): '<H',
<add> (2, 0): '<I',
<add>}
<add>
<ide>
<ide> def _check_version(version):
<ide> if version not in [(1, 0), (2, 0), None]:
<ide> def header_data_from_array_1_0(array):
<ide> d['descr'] = dtype_to_descr(array.dtype)
<ide> return d
<ide>
<add>
<add>def _wrap_header(header, version):
<add> """
<add> Takes a stringified header, and attaches the prefix and padding to it
<add> """
<add> import struct
<add> assert version is not None
<add> header = asbytes(header)
<add> fmt = _header_size_formats[version]
<add> hlen = len(header) + 1
<add> padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN)
<add> try:
<add> header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen)
<add> except struct.error:
<add> msg = "Header length {} too big for version={}".format(hlen, version)
<add> raise ValueError(msg)
<add>
<add> # Pad the header with spaces and a final newline such that the magic
<add> # string, the header-length short and the header are aligned on a
<add> # ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes
<add> # aligned up to ARRAY_ALIGN on systems like Linux where mmap()
<add> # offset must be page-aligned (i.e. the beginning of the file).
<add> return header_prefix + header + b' '*padlen + b'\n'
<add>
<add>
<add>def _wrap_header_guess_version(header):
<add> """
<add> Like `_wrap_header`, but chooses an appropriate version given the contents
<add> """
<add> try:
<add> return _wrap_header(header, (1, 0))
<add> except ValueError:
<add> pass
<add> header = _wrap_header(header, (2, 0))
<add> warnings.warn("Stored array in format 2.0. It can only be"
<add> "read by NumPy >= 1.9", UserWarning, stacklevel=2)
<add> return header
<add>
<add>
<ide> def _write_array_header(fp, d, version=None):
<ide> """ Write the header for an array and returns the version used
<ide>
<ide> def _write_array_header(fp, d, version=None):
<ide> None means use oldest that works
<ide> explicit version will raise a ValueError if the format does not
<ide> allow saving this data. Default: None
<del> Returns
<del> -------
<del> version : tuple of int
<del> the file version which needs to be used to store the data
<ide> """
<del> import struct
<ide> header = ["{"]
<ide> for key, value in sorted(d.items()):
<ide> # Need to use repr here, since we eval these when reading
<ide> header.append("'%s': %s, " % (key, repr(value)))
<ide> header.append("}")
<ide> header = "".join(header)
<del> header = asbytes(_filter_header(header))
<del>
<del> hlen = len(header) + 1 # 1 for newline
<del> padlen_v1 = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize('<H') + hlen) % ARRAY_ALIGN)
<del> padlen_v2 = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize('<I') + hlen) % ARRAY_ALIGN)
<del>
<del> # Which version(s) we write depends on the total header size; v1 has a max of 65535
<del> if hlen + padlen_v1 < 2**16 and version in (None, (1, 0)):
<del> version = (1, 0)
<del> header_prefix = magic(1, 0) + struct.pack('<H', hlen + padlen_v1)
<del> topad = padlen_v1
<del> elif hlen + padlen_v2 < 2**32 and version in (None, (2, 0)):
<del> version = (2, 0)
<del> header_prefix = magic(2, 0) + struct.pack('<I', hlen + padlen_v2)
<del> topad = padlen_v2
<add> header = _filter_header(header)
<add> if version is None:
<add> header = _wrap_header_guess_version(header)
<ide> else:
<del> msg = "Header length %s too big for version=%s"
<del> msg %= (hlen, version)
<del> raise ValueError(msg)
<del>
<del> # Pad the header with spaces and a final newline such that the magic
<del> # string, the header-length short and the header are aligned on a
<del> # ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes
<del> # aligned up to ARRAY_ALIGN on systems like Linux where mmap()
<del> # offset must be page-aligned (i.e. the beginning of the file).
<del> header = header + b' '*topad + b'\n'
<del>
<del> fp.write(header_prefix)
<add> header = _wrap_header(header, version)
<ide> fp.write(header)
<del> return version
<ide>
<ide> def write_array_header_1_0(fp, d):
<ide> """ Write the header for an array using the 1.0 format.
<ide> def _read_array_header(fp, version):
<ide> # Read an unsigned, little-endian short int which has the length of the
<ide> # header.
<ide> import struct
<del> if version == (1, 0):
<del> hlength_type = '<H'
<del> elif version == (2, 0):
<del> hlength_type = '<I'
<del> else:
<add> hlength_type = _header_size_formats.get(version)
<add> if hlength_type is None:
<ide> raise ValueError("Invalid version {!r}".format(version))
<ide>
<ide> hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), "array header length")
<ide> def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None):
<ide>
<ide> """
<ide> _check_version(version)
<del> used_ver = _write_array_header(fp, header_data_from_array_1_0(array),
<del> version)
<del> # this warning can be removed when 1.9 has aged enough
<del> if version != (2, 0) and used_ver == (2, 0):
<del> warnings.warn("Stored array in format 2.0. It can only be"
<del> "read by NumPy >= 1.9", UserWarning, stacklevel=2)
<add> _write_array_header(fp, header_data_from_array_1_0(array), version)
<ide>
<ide> if array.itemsize == 0:
<ide> buffersize = 0
<ide> def open_memmap(filename, mode='r+', dtype=None, shape=None,
<ide> # If we got here, then it should be safe to create the file.
<ide> fp = open(os_fspath(filename), mode+'b')
<ide> try:
<del> used_ver = _write_array_header(fp, d, version)
<del> # this warning can be removed when 1.9 has aged enough
<del> if version != (2, 0) and used_ver == (2, 0):
<del> warnings.warn("Stored array in format 2.0. It can only be"
<del> "read by NumPy >= 1.9", UserWarning, stacklevel=2)
<add> _write_array_header(fp, d, version)
<ide> offset = fp.tell()
<ide> finally:
<ide> fp.close() | 1 |
Ruby | Ruby | fix weird comment. [ci skip] | eeed9d59b2f1a792f1f1760255921e39d10720db | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def handle_options(options) #:nodoc:
<ide> end
<ide> end
<ide>
<del> # Sets the cookie named +name+. The second argument may be the very cookie
<del> # value, or a hash of options as documented above.
<add> # Sets the cookie named +name+. The second argument may be the cookie's
<add> # value or a hash of options as documented above.
<ide> def []=(name, options)
<ide> if options.is_a?(Hash)
<ide> options.symbolize_keys! | 1 |
Python | Python | use pytest.param in pytest.mark.parametrized | 37cc115d30dc17cf474a6eff04aad056cb6adef4 | <ide><path>tests/models/test_taskinstance.py
<ide> import pendulum
<ide> import pytest
<ide> from freezegun import freeze_time
<del>from parameterized import param
<ide> from sqlalchemy.orm.session import Session
<ide>
<ide> from airflow import models, settings
<ide> def get_test_ti(session, execution_date: pendulum.DateTime, state: str) -> TI:
<ide>
<ide> return ret
<ide>
<del> _prev_dates_param_list = (
<del> param('cron/catchup', '0 0 * * * ', True),
<del> param('cron/no-catchup', '0 0 * * *', False),
<del> param('no-sched/catchup', None, True),
<del> param('no-sched/no-catchup', None, False),
<del> param('timedelta/catchup', datetime.timedelta(days=1), True),
<del> param('timedelta/no-catchup', datetime.timedelta(days=1), False),
<del> )
<add> _prev_dates_param_list = [
<add> pytest.param('0 0 * * * ', True, id='cron/catchup'),
<add> pytest.param('0 0 * * *', False, id='cron/no-catchup'),
<add> pytest.param(None, True, id='no-sched/catchup'),
<add> pytest.param(None, False, id='no-sched/no-catchup'),
<add> pytest.param(datetime.timedelta(days=1), True, id='timedelta/catchup'),
<add> pytest.param(datetime.timedelta(days=1), False, id='timedelta/no-catchup'),
<add> ]
<ide>
<ide> @pytest.mark.parametrize("schedule_interval, catchup", _prev_dates_param_list)
<ide> def test_previous_ti(self, schedule_interval, catchup, dag_maker) -> None: | 1 |
Python | Python | fix an infallible test of triggerer job | ff99a379da56f6439a43c963ec2c651ef5546364 | <ide><path>tests/jobs/test_triggerer_job.py
<ide> def test_capacity_decode():
<ide> ]
<ide> for input_str in variants:
<ide> job = TriggererJob(capacity=input_str)
<del> assert job.capacity == input_str or 1000
<add> assert job.capacity == input_str or job.capacity == 1000
<ide>
<ide> # Negative cases
<ide> variants = [ | 1 |
Ruby | Ruby | serialize regexp into html attribute | d2e07395b3cbb6fb184797335bf0c1fa6edb5f38 | <ide><path>actionview/lib/action_view/helpers/tag_helper.rb
<ide> def tag_option(key, value, escape)
<ide> when Array, Hash
<ide> value = TagHelper.build_tag_values(value) if key.to_s == "class"
<ide> value = escape ? safe_join(value, " ") : value.join(" ")
<add> when Regexp
<add> value = escape ? ERB::Util.unwrapped_html_escape(value.source) : value.source
<ide> else
<ide> value = escape ? ERB::Util.unwrapped_html_escape(value) : value.to_s
<ide> end
<ide><path>actionview/test/template/tag_helper_test.rb
<ide> def test_tag_builder_with_content
<ide> tag.p("<script>evil_js</script>")
<ide> assert_equal "<p><script>evil_js</script></p>",
<ide> tag.p("<script>evil_js</script>", escape_attributes: false)
<add> assert_equal '<input pattern="\w+">', tag.input(pattern: /\w+/)
<ide> end
<ide>
<ide> def test_tag_builder_nested | 2 |
Javascript | Javascript | specify options.name in validatekeycert | e10cb7fdda85bdf3204ae40843d64e56cf07e5a8 | <ide><path>lib/_tls_common.js
<ide> function SecureContext(secureProtocol, secureOptions, context) {
<ide> if (secureOptions) this.context.setOptions(secureOptions);
<ide> }
<ide>
<del>function validateKeyCert(value, type) {
<add>function validateKeyCert(name, value) {
<ide> if (typeof value !== 'string' && !isArrayBufferView(value)) {
<ide> throw new ERR_INVALID_ARG_TYPE(
<del> // TODO(BridgeAR): Change this to `options.${type}`
<del> type,
<add> `options.${name}`,
<ide> ['string', 'Buffer', 'TypedArray', 'DataView'],
<ide> value
<ide> );
<ide> exports.createSecureContext = function createSecureContext(options, context) {
<ide> if (Array.isArray(ca)) {
<ide> for (i = 0; i < ca.length; ++i) {
<ide> val = ca[i];
<del> validateKeyCert(val, 'ca');
<add> validateKeyCert('ca', val);
<ide> c.context.addCACert(val);
<ide> }
<ide> } else {
<del> validateKeyCert(ca, 'ca');
<add> validateKeyCert('ca', ca);
<ide> c.context.addCACert(ca);
<ide> }
<ide> } else {
<ide> exports.createSecureContext = function createSecureContext(options, context) {
<ide> if (Array.isArray(cert)) {
<ide> for (i = 0; i < cert.length; ++i) {
<ide> val = cert[i];
<del> validateKeyCert(val, 'cert');
<add> validateKeyCert('cert', val);
<ide> c.context.setCert(val);
<ide> }
<ide> } else {
<del> validateKeyCert(cert, 'cert');
<add> validateKeyCert('cert', cert);
<ide> c.context.setCert(cert);
<ide> }
<ide> }
<ide> exports.createSecureContext = function createSecureContext(options, context) {
<ide> val = key[i];
<ide> // eslint-disable-next-line eqeqeq
<ide> const pem = (val != undefined && val.pem !== undefined ? val.pem : val);
<del> validateKeyCert(pem, 'key');
<add> validateKeyCert('key', pem);
<ide> c.context.setKey(pem, val.passphrase || passphrase);
<ide> }
<ide> } else {
<del> validateKeyCert(key, 'key');
<add> validateKeyCert('key', key);
<ide> c.context.setKey(key, passphrase);
<ide> }
<ide> }
<ide><path>test/parallel/test-https-options-boolean-check.js
<ide> const caArrDataView = toDataView(caCert);
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]',
<del> message: 'The "key" argument must be one of type string, Buffer, ' +
<add> message: 'The "options.key" property must be one of type string, Buffer, ' +
<ide> `TypedArray, or DataView. Received type ${type}`
<ide> });
<ide> });
<ide> const caArrDataView = toDataView(caCert);
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]',
<del> message: 'The "cert" argument must be one of type string, Buffer, ' +
<del> `TypedArray, or DataView. Received type ${type}`
<add> message: 'The "options.cert" property must be one of type string, Buffer,' +
<add> ` TypedArray, or DataView. Received type ${type}`
<ide> });
<ide> });
<ide>
<ide> const caArrDataView = toDataView(caCert);
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> name: 'TypeError [ERR_INVALID_ARG_TYPE]',
<del> message: 'The "ca" argument must be one of type string, Buffer, ' +
<add> message: 'The "options.ca" property must be one of type string, Buffer, ' +
<ide> `TypedArray, or DataView. Received type ${type}`
<ide> });
<ide> });
<ide><path>test/parallel/test-tls-options-boolean-check.js
<ide> const caArrDataView = toDataView(caCert);
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "key" argument must be one of type string, Buffer, ' +
<add> message: 'The "options.key" property must be one of type string, Buffer, ' +
<ide> `TypedArray, or DataView. Received type ${type}`
<ide> });
<ide> });
<ide> const caArrDataView = toDataView(caCert);
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "cert" argument must be one of type string, Buffer, ' +
<del> `TypedArray, or DataView. Received type ${type}`
<add> message: 'The "options.cert" property must be one of type string, Buffer,' +
<add> ` TypedArray, or DataView. Received type ${type}`
<ide> });
<ide> });
<ide>
<ide> const caArrDataView = toDataView(caCert);
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "ca" argument must be one of type string, Buffer, ' +
<add> message: 'The "options.ca" property must be one of type string, Buffer, ' +
<ide> `TypedArray, or DataView. Received type ${type}`
<ide> });
<ide> }); | 3 |
Ruby | Ruby | pull iterator allocation in to a factory method | 6539657a3c7bb205e9c0812d6c73a2326699ec52 | <ide><path>actionview/lib/action_view/renderer/partial_renderer.rb
<ide> def render(context, options, block)
<ide> end
<ide>
<ide> private
<add> def build_collection_iterator(collection, path, as, context)
<add> if path
<add> SameCollectionIterator.new(collection, path, retrieve_variable(path, as))
<add> else
<add> paths = collection.map { |o| partial_path(o, context) }
<add>
<add> if paths.uniq.length == 1
<add> @path = paths.first
<add> build_collection_iterator(collection, @path, as, context)
<add> else
<add> paths.map! { |path| retrieve_variable(path, as).unshift(path) }
<add> @path = nil
<add> MixedCollectionIterator.new(collection, paths)
<add> end
<add> end
<add> end
<add>
<ide> def template_keys(path, as)
<del> if @has_object || @collection
<add> if @has_object
<ide> @locals.keys + retrieve_variable(path, as)
<ide> else
<ide> @locals.keys
<ide> class CollectionIterator # :nodoc:
<ide>
<ide> attr_reader :collection
<ide>
<del> def initialize(collection, path, variables)
<add> def initialize(collection)
<ide> @collection = collection
<del> @path = path
<del> @variables = variables
<del> end
<del>
<del> def from_collection(collection)
<del> return collection if collection == self
<del>
<del> self.class.new(collection, @path, @variables)
<ide> end
<ide>
<ide> def each(&blk)
<ide> @collection.each(&blk)
<ide> end
<ide>
<del> def each_with_info
<del> return enum_for(:each_with_info) unless block_given?
<del>
<del> variables = [@path] + @variables
<del> @collection.each { |o| yield(o, variables) }
<del> end
<del>
<ide> def size
<ide> @collection.size
<ide> end
<ide> end
<ide>
<del> class MixedCollectionIterator # :nodoc:
<del> include Enumerable
<del>
<del> def initialize(collection, paths)
<del> @collection = collection
<del> @paths = paths
<add> class SameCollectionIterator < CollectionIterator # :nodoc:
<add> def initialize(collection, path, variables)
<add> super(collection)
<add> @path = path
<add> @variables = variables
<ide> end
<ide>
<del> def each(&blk)
<del> @collection.each(&blk)
<add> def from_collection(collection)
<add> return collection if collection == self
<add> self.class.new(collection, @path, @variables)
<ide> end
<ide>
<ide> def each_with_info
<ide> return enum_for(:each_with_info) unless block_given?
<del> @collection.each_with_index { |o, i| yield(o, @paths[i]) }
<add> variables = [@path] + @variables
<add> @collection.each { |o| yield(o, variables) }
<ide> end
<add> end
<ide>
<del> def size
<del> @collection.size
<add> class MixedCollectionIterator < CollectionIterator # :nodoc:
<add> def initialize(collection, paths)
<add> super(collection)
<add> @paths = paths
<add> end
<add>
<add> def each_with_info
<add> return enum_for(:each_with_info) unless block_given?
<add> collection.each_with_index { |o, i| yield(o, @paths[i]) }
<ide> end
<ide> end
<ide>
<ide> def setup(context, options, as)
<ide>
<ide> if @collection
<ide> @has_object = true
<del> @collection = CollectionIterator.new(@collection, @path, retrieve_variable(@path, as))
<add> @collection = build_collection_iterator(@collection, @path, as, context)
<ide> end
<add>
<ide> else
<ide> @has_object = true
<ide> @object = partial
<ide> @collection = collection_from_object || collection_from_options
<ide>
<ide> if @collection
<del> paths = @collection.map { |o| partial_path(o, context) }
<del> if paths.uniq.length == 1
<del> @path = paths.first
<del> @collection = CollectionIterator.new(@collection, @path, retrieve_variable(@path, as))
<del> else
<del> paths.map! { |path| retrieve_variable(path, as).unshift(path) }
<del> @path = nil
<del> @collection = MixedCollectionIterator.new(@collection, paths)
<del> end
<add> @collection = build_collection_iterator(@collection, nil, as, context)
<ide> else
<ide> @path = partial_path(@object, context)
<ide> end | 1 |
Python | Python | add salesforce_default to list connection | 6d69dd062f079a8fbf72563fd218017208bfe6c1 | <ide><path>airflow/utils/db.py
<ide> def create_default_connections(session: Session = NEW_SESSION):
<ide> ),
<ide> session,
<ide> )
<add> merge_conn(
<add> Connection(
<add> conn_id="salesforce_default",
<add> conn_type="salesforce",
<add> login="username",
<add> password="password",
<add> extra='{"security_token": "security_token"}',
<add> ),
<add> session,
<add> )
<ide> merge_conn(
<ide> Connection(
<ide> conn_id="segment_default", | 1 |
Text | Text | add watchman permission errors | 750c633940c026b66ae4e947d9731c435d72b12d | <ide><path>docs/Troubleshooting.md
<ide> If you are using a non-QWERTY/AZERTY keyboard layout you can use the `Hardware >
<ide>
<ide> Something is probably already running on port 8081. You can either kill it or try to change which port the packager is listening to.
<ide>
<del>### Kill process on port 8081
<add>##### Kill process on port 8081
<ide> `$ sudo lsof -n -i4TCP:8081 | grep LISTEN`
<ide>
<ide> then
<ide> then
<ide>
<ide>
<ide>
<del>### Change the port in Xcode
<add>##### Change the port in Xcode
<ide> Edit `AppDelegate.m` to use a different port.
<ide> ```
<ide> // OPTION 1
<ide> Edit `AppDelegate.m` to use a different port.
<ide> // iOS device are on the same Wi-Fi network.
<ide> jsCodeLocation = [NSURL URLWithString:@"http://localhost:9381/index.ios.bundle"];
<ide> ```
<add>
<add>
<add>## Watchman took too long to load
<add>Permission settings prevent Wathcman to load. A recent update solves this, get a HEAD install of Watchman if you are experiening this error.
<add>
<add>```
<add>brew uninstall watchman
<add>brew install --HEAD watchman
<add>``` | 1 |
Javascript | Javascript | move wpo to the minify step | f546dc3790edd4e0b310caccdc273f31a717258c | <ide><path>packager/react-packager/src/Bundler/Bundle.js
<ide> class Bundle {
<ide> }
<ide>
<ide> this._source = _.pluck(this._modules, 'code').join('\n');
<del>
<del> if (dev) {
<del> return this._source;
<del> }
<del>
<del> const wpoActivity = Activity.startEvent('Whole Program Optimisations');
<del> const result = require('babel-core').transform(this._source, {
<del> retainLines: true,
<del> compact: true,
<del> plugins: require('../transforms/whole-program-optimisations'),
<del> inputSourceMap: this.getSourceMap(),
<del> });
<del>
<del> this._source = result.code;
<del> this._sourceMap = result.map;
<del>
<del> Activity.endEvent(wpoActivity);
<del>
<ide> return this._source;
<ide> }
<ide>
<ide> class Bundle {
<ide> return this._minifiedSourceAndMap;
<ide> }
<ide>
<del> const source = this._getSource(dev);
<add> let source = this._getSource(dev);
<add> let map = this.getSourceMap();
<add>
<add> if (!dev) {
<add> const wpoActivity = Activity.startEvent('Whole Program Optimisations');
<add> const wpoResult = require('babel-core').transform(source, {
<add> retainLines: true,
<add> compact: true,
<add> plugins: require('../transforms/whole-program-optimisations'),
<add> inputSourceMap: map,
<add> });
<add> Activity.endEvent(wpoActivity);
<add>
<add> source = wpoResult.code;
<add> map = wpoResult.map;
<add> }
<add>
<ide> try {
<ide> const minifyActivity = Activity.startEvent('minify');
<ide> this._minifiedSourceAndMap = UglifyJS.minify(source, {
<ide> fromString: true,
<ide> outSourceMap: this._sourceMapUrl,
<del> inSourceMap: this.getSourceMap(),
<add> inSourceMap: map,
<ide> output: {ascii_only: true},
<ide> });
<ide> Activity.endEvent(minifyActivity); | 1 |
Ruby | Ruby | remove order_clauses since we do not use it | 55c0071ce3685a78b4f039be24b2ab40b8779467 | <ide><path>lib/arel/select_manager.rb
<ide> def join_sql
<ide> Nodes::SqlLiteral.new sql
<ide> end
<ide>
<del> def order_clauses
<del> visitor = Visitors::OrderClauses.new(@engine.connection)
<del> visitor.accept(@ast).map { |x|
<del> Nodes::SqlLiteral.new x
<del> }
<del> end
<del>
<ide> def join_sources
<ide> @ctx.source.right
<ide> end
<ide><path>lib/arel/visitors.rb
<ide> require 'arel/visitors/oracle'
<ide> require 'arel/visitors/join_sql'
<ide> require 'arel/visitors/where_sql'
<del>require 'arel/visitors/order_clauses'
<ide> require 'arel/visitors/dot'
<ide> require 'arel/visitors/ibm_db'
<ide> require 'arel/visitors/informix'
<ide><path>lib/arel/visitors/order_clauses.rb
<del>module Arel
<del> module Visitors
<del> class OrderClauses < Arel::Visitors::ToSql
<del> private
<del>
<del> def visit_Arel_Nodes_SelectStatement o
<del> o.orders.map { |x| visit x }
<del> end
<del> end
<del> end
<del>end
<ide><path>test/test_select_manager.rb
<ide> def test_manager_stores_bind_values
<ide> end
<ide> end
<ide>
<del> describe 'order_clauses' do
<del> it 'returns order clauses as a list' do
<del> table = Table.new :users
<del> manager = Arel::SelectManager.new Table.engine
<del> manager.from table
<del> manager.order table[:id]
<del> manager.order_clauses.first.must_be_like %{ "users"."id" }
<del> end
<del> end
<del>
<ide> describe 'group' do
<ide> it 'takes an attribute' do
<ide> table = Table.new :users | 4 |
Python | Python | remove legacy monkeypatching of gzipfile | 7d6aa8c721d5274ac57d0c87685d472cb1fd7948 | <ide><path>numpy/lib/npyio.py
<ide> ]
<ide>
<ide>
<del>def seek_gzip_factory(f):
<del> """Use this factory to produce the class so that we can do a lazy
<del> import on gzip.
<del>
<del> """
<del> import gzip
<del>
<del> class GzipFile(gzip.GzipFile):
<del>
<del> def seek(self, offset, whence=0):
<del> # figure out new position (we can only seek forwards)
<del> if whence == 1:
<del> offset = self.offset + offset
<del>
<del> if whence not in [0, 1]:
<del> raise IOError("Illegal argument")
<del>
<del> if offset < self.offset:
<del> # for negative seek, rewind and do positive seek
<del> self.rewind()
<del> count = offset - self.offset
<del> for i in range(count // 1024):
<del> self.read(1024)
<del> self.read(count % 1024)
<del>
<del> def tell(self):
<del> return self.offset
<del>
<del> if isinstance(f, str):
<del> f = GzipFile(f)
<del> elif isinstance(f, gzip.GzipFile):
<del> # cast to our GzipFile if its already a gzip.GzipFile
<del>
<del> try:
<del> name = f.name
<del> except AttributeError:
<del> # Backward compatibility for <= 2.5
<del> name = f.filename
<del> mode = f.mode
<del>
<del> f = GzipFile(fileobj=f.fileobj, filename=name)
<del> f.mode = mode
<del>
<del> return f
<del>
<del>
<ide> class BagObj(object):
<ide> """
<ide> BagObj(obj)
<ide> def load(file, mmap_mode=None, allow_pickle=True, fix_imports=True,
<ide> if isinstance(file, basestring):
<ide> fid = open(file, "rb")
<ide> own_fid = True
<del> elif isinstance(file, gzip.GzipFile):
<del> fid = seek_gzip_factory(file)
<ide> else:
<ide> fid = file
<ide>
<ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> if _is_string_like(fname):
<ide> fown = True
<ide> if fname.endswith('.gz'):
<del> fh = iter(seek_gzip_factory(fname))
<add> import gzip
<add> fh = iter(gzip.GzipFile(fname))
<ide> elif fname.endswith('.bz2'):
<ide> import bz2
<ide> fh = iter(bz2.BZ2File(fname)) | 1 |
Text | Text | add callback parameters of worker.terminate() | ab6ddc063469efd55c8b9f51a46b0f9d99369914 | <ide><path>doc/api/worker_threads.md
<ide> added: v10.5.0
<ide> -->
<ide>
<ide> * `callback` {Function}
<add> * `err` {Error}
<add> * `exitCode` {integer}
<ide>
<ide> Stop all JavaScript execution in the worker thread as soon as possible.
<ide> `callback` is an optional function that is invoked once this operation is known | 1 |
Text | Text | add cpuset and examples to run.md | a5cbb5c3aec0d5c717581b2b60b9ae89b2c6fd05 | <ide><path>docs/sources/reference/run.md
<ide> Note:
<ide>
<ide> You would have to write policy defining a `svirt_apache_t` type.
<ide>
<del>## Runtime constraints on CPU and memory
<add>## Runtime constraints on resources
<ide>
<ide> The operator can also adjust the performance parameters of the
<ide> container:
<ide>
<del> -m="": Memory limit (format: <number><optional unit>, where unit = b, k, m or g)
<add> -m, --memory="": Memory limit (format: <number><optional unit>, where unit = b, k, m or g)
<ide> -memory-swap="": Total memory limit (memory + swap, format: <number><optional unit>, where unit = b, k, m or g)
<ide> -c, --cpu-shares=0: CPU shares (relative weight)
<add> --cpuset-cpus="": CPUs in which to allow execution (0-3, 0,1)
<ide>
<ide> ### Memory constraints
<ide>
<ide> division of CPU shares:
<ide> 101 {C1} 1 100% of CPU1
<ide> 102 {C1} 2 100% of CPU2
<ide>
<add>### Cpuset constraint
<add>
<add>We can set cpus in which to allow execution for containers.
<add>
<add>Examples:
<add>
<add> $ sudo docker run -ti --cpuset-cpus="1,3" ubuntu:14.04 /bin/bash
<add>
<add>This means processes in container can be executed on cpu 1 and cpu 3.
<add>
<add> $ sudo docker run -ti --cpuset-cpus="0-2" ubuntu:14.04 /bin/bash
<add>
<add>This means processes in container can be executed on cpu 0, cpu 1 and cpu 2.
<add>
<ide> ## Runtime privilege, Linux capabilities, and LXC configuration
<ide>
<ide> --cap-add: Add Linux capabilities | 1 |
Text | Text | use relative path for example | 5c6c3851006a2fd43a8ec9518c1be7f723bbf2e3 | <ide><path>docs/basic-features/eslint.md
<ide> If you're using `eslint-plugin-next` in a project where Next.js isn't installed
<ide> "extends": "next",
<ide> "settings": {
<ide> "next": {
<del> "rootDir": "/packages/my-app/"
<add> "rootDir": "packages/my-app/"
<ide> }
<ide> }
<ide> }
<ide> ```
<ide>
<del>`rootDir` can be a path (relative or absolute), a glob (i.e. `"/packages/*/"`), or an array of paths and/or globs.
<add>`rootDir` can be a path (relative or absolute), a glob (i.e. `"packages/*/"`), or an array of paths and/or globs.
<ide>
<ide> ## Linting Custom Directories and Files
<ide>
<ide><path>errors/no-html-link-for-pages.md
<ide> In some cases, you may also need to configure this rule directly by providing a
<ide> ```json
<ide> {
<ide> "rules": {
<del> "@next/next/no-html-link-for-pages": ["error", "/my-app/pages/"]
<add> "@next/next/no-html-link-for-pages": ["error", "packages/my-app/pages/"]
<ide> }
<ide> }
<ide> ``` | 2 |
Python | Python | add fallback path for apex used in modeling.py | 3b0a14b7614d5a1741dbd5288f6ab1e38d4a3103 | <ide><path>pytorch_pretrained_bert/modeling.py
<ide> import torch
<ide> from torch import nn
<ide> from torch.nn import CrossEntropyLoss
<del>try:
<del> from apex.normalization.fused_layer_norm import FusedLayerNorm
<del>except ImportError:
<del> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to run this.")
<ide>
<ide> from .file_utils import cached_path
<ide>
<ide> def to_json_string(self):
<ide> """Serializes this instance to a JSON string."""
<ide> return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
<ide>
<del>
<del>class BertLayerNorm(nn.Module):
<del> def __init__(self, config, variance_epsilon=1e-12):
<del> """Construct a layernorm module in the TF style (epsilon inside the square root).
<del> """
<del> super(BertLayerNorm, self).__init__()
<del> self.gamma = nn.Parameter(torch.ones(config.hidden_size))
<del> self.beta = nn.Parameter(torch.zeros(config.hidden_size))
<del> self.variance_epsilon = variance_epsilon
<del>
<del> def forward(self, x):
<del> u = x.mean(-1, keepdim=True)
<del> s = (x - u).pow(2).mean(-1, keepdim=True)
<del> x = (x - u) / torch.sqrt(s + self.variance_epsilon)
<del> return self.gamma * x + self.beta
<del>
<add>try:
<add> from apex.normalization.fused_layer_norm import FusedLayerNorm as BertLayerNorm
<add>except ImportError:
<add> print("Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex.")
<add> class BertLayerNorm(nn.Module):
<add> def __init__(self, hidden_size, eps=1e-12):
<add> """Construct a layernorm module in the TF style (epsilon inside the square root).
<add> """
<add> super(BertLayerNorm, self).__init__()
<add> self.weight = nn.Parameter(torch.ones(hidden_size))
<add> self.bias = nn.Parameter(torch.zeros(hidden_size))
<add> self.variance_epsilon = eps
<add>
<add> def forward(self, x):
<add> u = x.mean(-1, keepdim=True)
<add> s = (x - u).pow(2).mean(-1, keepdim=True)
<add> x = (x - u) / torch.sqrt(s + self.variance_epsilon)
<add> return self.weight * x + self.bias
<ide>
<ide> class BertEmbeddings(nn.Module):
<ide> """Construct the embeddings from word, position and token_type embeddings.
<ide> def __init__(self, config):
<ide>
<ide> # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
<ide> # any TensorFlow checkpoint file
<del> self.LayerNorm = FusedLayerNorm(config.hidden_size, eps=1e-12)
<add> self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
<ide> self.dropout = nn.Dropout(config.hidden_dropout_prob)
<ide>
<ide> def forward(self, input_ids, token_type_ids=None):
<ide> class BertSelfOutput(nn.Module):
<ide> def __init__(self, config):
<ide> super(BertSelfOutput, self).__init__()
<ide> self.dense = nn.Linear(config.hidden_size, config.hidden_size)
<del> self.LayerNorm = FusedLayerNorm(config.hidden_size, eps=1e-12)
<add> self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
<ide> self.dropout = nn.Dropout(config.hidden_dropout_prob)
<ide>
<ide> def forward(self, hidden_states, input_tensor):
<ide> class BertOutput(nn.Module):
<ide> def __init__(self, config):
<ide> super(BertOutput, self).__init__()
<ide> self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
<del> self.LayerNorm = FusedLayerNorm(config.hidden_size, eps=1e-12)
<add> self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
<ide> self.dropout = nn.Dropout(config.hidden_dropout_prob)
<ide>
<ide> def forward(self, hidden_states, input_tensor):
<ide> def __init__(self, config):
<ide> self.dense = nn.Linear(config.hidden_size, config.hidden_size)
<ide> self.transform_act_fn = ACT2FN[config.hidden_act] \
<ide> if isinstance(config.hidden_act, str) else config.hidden_act
<del> self.LayerNorm = FusedLayerNorm(config.hidden_size, eps=1e-12)
<add> self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
<ide>
<ide> def forward(self, hidden_states):
<ide> hidden_states = self.dense(hidden_states)
<ide> def init_bert_weights(self, module):
<ide> # Slightly different from the TF version which uses truncated_normal for initialization
<ide> # cf https://github.com/pytorch/pytorch/pull/5617
<ide> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
<del> elif isinstance(module, FusedLayerNorm):
<add> elif isinstance(module, BertLayerNorm):
<ide> module.bias.data.normal_(mean=0.0, std=self.config.initializer_range)
<ide> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
<del> elif isinstance(module, BertLayerNorm):
<del> module.beta.data.normal_(mean=0.0, std=self.config.initializer_range)
<del> module.gamma.data.normal_(mean=0.0, std=self.config.initializer_range)
<ide> if isinstance(module, nn.Linear) and module.bias is not None:
<ide> module.bias.data.zero_()
<ide> | 1 |
Python | Python | remove todo note | 080066ae74c10d5ef2a61eb123ad608b354a1103 | <ide><path>spacy/scorer.py
<ide> def score_links(
<ide> negative_labels (Iterable[str]): The string values that refer to no annotation (e.g. "NIL")
<ide> RETURNS (Dict[str, Any]): A dictionary containing the scores.
<ide>
<del> DOCS (TODO): https://nightly.spacy.io/api/scorer#score_links
<add> DOCS: https://nightly.spacy.io/api/scorer#score_links
<ide> """
<ide> f_per_type = {}
<ide> for example in examples: | 1 |
PHP | PHP | remove extra whitespace in config/cache.php | 82357a563a2b8a50031f00f07353c4657718de04 | <ide><path>config/cache.php
<ide> 'memcached' => [
<ide> 'driver' => 'memcached',
<ide> 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
<del> 'sasl' => [
<add> 'sasl' => [
<ide> env('MEMCACHED_USERNAME'),
<ide> env('MEMCACHED_PASSWORD'),
<ide> ],
<del> 'options' => [
<add> 'options' => [
<ide> // Memcached::OPT_CONNECT_TIMEOUT => 2000,
<ide> ],
<ide> 'servers' => [ | 1 |
Text | Text | fix link to animations docs | ac8142b4dc37154ee266f44dc541932a87c34fac | <ide><path>docs/docs/developers/api.md
<ide> myLineChart.update(); // Calling update now animates the position of March from
<ide>
<ide> > **Note:** replacing the data reference (e.g. `myLineChart.data = {datasets: [...]}` only works starting **version 2.6**. Prior that, replacing the entire data object could be achieved with the following workaround: `myLineChart.config.data = {datasets: [...]}`.
<ide>
<del>A `mode` string can be provided to indicate what should be updated and what animation configuration should be used. Core calls this method using any of `'active'`, `'hide'`, `'reset'`, `'resize'`, `'show'` or `undefined`. `'none'` is also a supported mode for skipping animations for single update. Please see [animations](../configuration/animations.md) docs for more details.
<add>A `mode` string can be provided to indicate what should be updated and what animation configuration should be used. Core calls this method using any of `'active'`, `'hide'`, `'reset'`, `'resize'`, `'show'` or `undefined`. `'none'` is also a supported mode for skipping animations for single update. Please see [animations](../configuration/animations.mdx) docs for more details.
<ide>
<ide> Example:
<ide>
<ide> var visible = chart.getDataVisibility(2);
<ide>
<ide> ## hide(datasetIndex)
<ide>
<del>Sets the visibility for the given dataset to false. Updates the chart and animates the dataset with `'hide'` mode. This animation can be configured under the `hide` key in animation options. Please see [animations](../configuration/animations.md) docs for more details.
<add>Sets the visibility for the given dataset to false. Updates the chart and animates the dataset with `'hide'` mode. This animation can be configured under the `hide` key in animation options. Please see [animations](../configuration/animations.mdx) docs for more details.
<ide>
<ide> ```javascript
<ide> chart.hide(1); // hides dataset at index 1 and does 'hide' animation.
<ide> ```
<ide>
<ide> ## show(datasetIndex)
<ide>
<del>Sets the visibility for the given dataset to true. Updates the chart and animates the dataset with `'show'` mode. This animation can be configured under the `show` key in animation options. Please see [animations](../configuration/animations.md) docs for more details.
<add>Sets the visibility for the given dataset to true. Updates the chart and animates the dataset with `'show'` mode. This animation can be configured under the `show` key in animation options. Please see [animations](../configuration/animations.mdx) docs for more details.
<ide>
<ide> ```javascript
<ide> chart.show(1); // shows dataset at index 1 and does 'show' animation.
<ide><path>docs/docs/getting-started/v3-migration.md
<ide> options: {
<ide>
<ide> #### Animations
<ide>
<del>Animation system was completely rewritten in Chart.js v3. Each property can now be animated separately. Please see [animations](../configuration/animations.md) docs for details.
<add>Animation system was completely rewritten in Chart.js v3. Each property can now be animated separately. Please see [animations](../configuration/animations.mdx) docs for details.
<ide>
<ide> #### Customizability
<ide> | 2 |
Javascript | Javascript | add missing space in test | a8c1d9c97804f7df98150456c2702fd39e3a22f0 | <ide><path>src/Angular.js
<ide> function isArrayLike(obj) {
<ide> angular.forEach(values, function(value, key){
<ide> this.push(key + ': ' + value);
<ide> }, log);
<del> expect(log).toEqual(['name: misko', 'gender:male']);
<add> expect(log).toEqual(['name: misko', 'gender: male']);
<ide> </pre>
<ide> *
<ide> * @param {Object|Array} obj Object to iterate over. | 1 |
Ruby | Ruby | minimize spring.watch calls | 272df8fcedcb8ff6b36b3e8953d17f552e1fc624 | <ide><path>railties/lib/rails/generators/rails/app/templates/config/spring.rb
<del>%w[
<del> .ruby-version
<del> .rbenv-vars
<del> tmp/restart.txt
<del> tmp/caching-dev.txt
<del>].each { |path| Spring.watch(path) }
<add>Spring.watch(
<add> ".ruby-version",
<add> ".rbenv-vars",
<add> "tmp/restart.txt",
<add> "tmp/caching-dev.txt"
<add>) | 1 |
Javascript | Javascript | remove comment referring to deferredmixin | d7948a4202959a1831872ec579249138534dabc8 | <ide><path>packages/ember/tests/routing/basic_test.js
<ide> asyncTest("The Special page returning an error fires the error hook on SpecialRo
<ide>
<ide> var menuItem;
<ide>
<del> App.MenuItem = Ember.Object.extend(Ember.DeferredMixin);
<add> App.MenuItem = Ember.Object.extend();
<ide> App.MenuItem.reopenClass({
<ide> find: function(id) {
<ide> menuItem = App.MenuItem.create({ id: id }); | 1 |
Text | Text | add docs for `docker network create --attachable` | 7433d3acf61142bb1abbf7928ff0e20acf3eda56 | <ide><path>docs/reference/commandline/network_create.md
<ide> Usage: docker network create [OPTIONS] NETWORK
<ide> Create a network
<ide>
<ide> Options:
<add> --attachable Enable manual container attachment
<ide> --aux-address value Auxiliary IPv4 or IPv6 addresses used by Network
<ide> driver (default map[])
<ide> -d, --driver string Driver to manage the Network (default "bridge")
<ide><path>man/docker-network-create.1.md
<ide> docker-network-create - create a new network
<ide>
<ide> # SYNOPSIS
<ide> **docker network create**
<add>[**--attachable**]
<ide> [**--aux-address**=*map[]*]
<ide> [**-d**|**--driver**=*DRIVER*]
<ide> [**--gateway**=*[]*]
<ide> to create an externally isolated `overlay` network, you can specify the
<ide> `--internal` option.
<ide>
<ide> # OPTIONS
<add>**--attachable**
<add> Enable manual container attachment
<add>
<ide> **--aux-address**=map[]
<ide> Auxiliary IPv4 or IPv6 addresses used by network driver
<ide> | 2 |
Python | Python | fix purge_inactive_dag_warnings filter | fab2913d1aad0f076d35f3c424cb128016e08330 | <ide><path>airflow/models/dagwarning.py
<ide> from enum import Enum
<ide>
<ide> from sqlalchemy import Column, ForeignKeyConstraint, String, Text, false
<add>from sqlalchemy.orm import Session
<ide>
<ide> from airflow.models.base import Base, StringID
<ide> from airflow.utils import timezone
<ide> class DagWarning(Base):
<ide> ),
<ide> )
<ide>
<del> def __init__(self, dag_id, error_type, message, **kwargs):
<add> def __init__(self, dag_id: str, error_type: str, message: str, **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.dag_id = dag_id
<ide> self.warning_type = DagWarningType(error_type).value # make sure valid type
<ide> self.message = message
<ide>
<del> def __eq__(self, other):
<add> def __eq__(self, other) -> bool:
<ide> return self.dag_id == other.dag_id and self.warning_type == other.warning_type
<ide>
<del> def __hash__(self):
<add> def __hash__(self) -> int:
<ide> return hash((self.dag_id, self.warning_type))
<ide>
<ide> @classmethod
<ide> @provide_session
<del> def purge_inactive_dag_warnings(cls, session=NEW_SESSION):
<add> def purge_inactive_dag_warnings(cls, session: Session = NEW_SESSION) -> None:
<ide> """
<ide> Deactivate DagWarning records for inactive dags.
<ide>
<ide> def purge_inactive_dag_warnings(cls, session=NEW_SESSION):
<ide> from airflow.models.dag import DagModel
<ide>
<ide> if session.get_bind().dialect.name == 'sqlite':
<del> dag_ids = session.query(DagModel).filter(DagModel.is_active == false()).all()
<del> session.query(cls).filter(cls.dag_id.in_(dag_ids)).delete(synchronize_session=False)
<add> dag_ids = session.query(DagModel.dag_id).filter(DagModel.is_active == false())
<add> query = session.query(cls).filter(cls.dag_id.in_(dag_ids))
<ide> else:
<del> session.query(cls).filter(cls.dag_id == DagModel.dag_id, DagModel.is_active == false()).delete(
<del> synchronize_session=False
<del> )
<add> query = session.query(cls).filter(cls.dag_id == DagModel.dag_id, DagModel.is_active == false())
<add> query.delete(synchronize_session=False)
<ide> session.commit()
<ide>
<ide> | 1 |
PHP | PHP | move registration of cakeplugin | 205d75587ce26bf87c4792d64b8eff277c1901df | <ide><path>lib/Cake/Core/App.php
<ide> public static function init() {
<ide> self::$_map += (array)Cache::read('file_map', '_cake_core_');
<ide> self::$_objects += (array)Cache::read('object_map', '_cake_core_');
<ide> register_shutdown_function(array('App', 'shutdown'));
<del> self::uses('CakePlugin', 'Core');
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/bootstrap.php
<ide>
<ide> App::uses('ErrorHandler', 'Error');
<ide> App::uses('Configure', 'Core');
<add>App::uses('CakePlugin', 'Core');
<ide> App::uses('Cache', 'Cache');
<ide> App::uses('Object', 'Core');
<ide> App::$bootstrapping = true; | 2 |
Ruby | Ruby | fix output when listing guesses | a24477dad64ed8c7069811b6f0e3390973b9c9cf | <ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def bump_formula_pr
<ide> if guesses.count == 1
<ide> formula = guesses.shift
<ide> elsif guesses.count > 1
<del> odie "Couldn't guess formula for sure; could be one of these:\n#{guesses}"
<add> odie "Couldn't guess formula for sure; could be one of these:\n#{guesses.map(&:name).join(", ")}"
<ide> end
<ide> end
<ide> raise FormulaUnspecifiedError unless formula | 1 |
Ruby | Ruby | add dodeca-core for 2018 mbps | 92c6e72a4a5d339e3fec5dfa881facfc2b3572e9 | <ide><path>Library/Homebrew/hardware.rb
<ide> def self.cores_as_words
<ide> when 4 then "quad"
<ide> when 6 then "hexa"
<ide> when 8 then "octa"
<add> when 12 then "dodeca"
<ide> else
<ide> Hardware::CPU.cores
<ide> end | 1 |
Python | Python | update examples/neural_doodle.py based on issues | d9c4d8a76af48f9be4ed9f25f6f5feaf4146ae8f | <ide><path>examples/neural_doodle.py
<ide> ref_img = imread(target_mask_path)
<ide> img_nrows, img_ncols = ref_img.shape[:2]
<ide>
<del>total_variation_weight = 8.5e-5
<add>total_variation_weight = 50.
<ide> style_weight = 1.
<ide> content_weight = 0.1 if use_content_img else 0
<ide>
<ide> def region_style_loss(style_image, target_image, style_mask, target_mask):
<ide> if K.image_dim_ordering() == 'th':
<ide> masked_style = style_image * style_mask
<ide> masked_target = target_image * target_mask
<add> nb_channels = K.shape(style_image)[0]
<ide> else:
<ide> masked_style = K.permute_dimensions(
<ide> style_image, (2, 0, 1)) * style_mask
<ide> masked_target = K.permute_dimensions(
<ide> target_image, (2, 0, 1)) * target_mask
<del> s = gram_matrix(masked_style) * K.sum(style_mask)
<del> c = gram_matrix(masked_target) * K.sum(target_mask)
<del> return K.sum(K.square(s - c))
<add> nb_channels = K.shape(style_image)[-1]
<add> s = gram_matrix(masked_style) / K.mean(style_mask) / nb_channels
<add> c = gram_matrix(masked_target) / K.mean(target_mask) / nb_channels
<add> return K.mean(K.square(s - c))
<ide>
<ide>
<ide> def style_loss(style_image, target_image, style_masks, target_masks):
<ide> def style_loss(style_image, target_image, style_masks, target_masks):
<ide> target_mask = target_masks[:, :, i]
<ide> loss += region_style_loss(style_image,
<ide> target_image, style_mask, target_mask)
<del> size = img_nrows * img_ncols
<del> return loss / (4. * nb_colors**2 * size**2)
<add> return loss
<ide>
<ide>
<ide> def content_loss(content_image, target_image):
<ide> def grads(self, x):
<ide> else:
<ide> x = np.random.uniform(0, 255, (1, img_nrows, img_ncols, 3)) - 128.
<ide>
<del>for i in range(100):
<add>for i in range(50):
<ide> print('Start of iteration', i)
<ide> start_time = time.time()
<ide> x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(), | 1 |
Javascript | Javascript | fix jsdoc tags | 6a6db5b383d41d33c3c0c978f773122bf1007bc8 | <ide><path>packages/ember-states/lib/state_manager.js
<ide> require('ember-states/state');
<ide>
<ide> **/
<ide> Ember.StateManager = Ember.State.extend(
<del>/** @scope Ember.State.prototype */ {
<add>/** @scope Ember.StateManager.prototype */ {
<ide>
<ide> /**
<ide> When creating a new statemanager, look for a default state to transition
<ide> Ember.StateManager = Ember.State.extend(
<ide> currentState: null,
<ide>
<ide> /**
<del> @property
<del>
<ide> If set to true, `errorOnUnhandledEvents` will cause an exception to be
<ide> raised if you attempt to send an event to a state manager that is not
<ide> handled by the current state or any of its parent states.
<add>
<add> @property {Boolean}
<ide> */
<ide> errorOnUnhandledEvent: true,
<ide>
<ide><path>packages/ember-viewstates/lib/state_manager.js
<ide> var get = Ember.get, set = Ember.set, getPath = Ember.getPath, fmt = Ember.Strin
<ide> `view` that references the `Ember.View` object that was interacted with.
<ide>
<ide> **/
<del>
<del>Ember.StateManager.reopen({
<add>Ember.StateManager.reopen(
<add>/** @scope Ember.StateManager.prototype */ {
<ide>
<ide> /**
<del> @property
<del>
<ide> If the current state is a view state or the descendent of a view state,
<ide> this property will be the view associated with it. If there is no
<ide> view state active in this state manager, this value will be null.
<add>
<add> @property
<ide> */
<ide> currentView: Ember.computed(function() {
<ide> var currentState = get(this, 'currentState'), | 2 |
Go | Go | fix version struct on old versions | 229b599259b24b30fdecbb70bdbba417a81e9723 | <ide><path>api/server/server.go
<ide> func (s *Server) postAuth(version version.Version, w http.ResponseWriter, r *htt
<ide>
<ide> func (s *Server) getVersion(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> v := &types.Version{
<del> Version: dockerversion.VERSION,
<del> ApiVersion: api.APIVERSION,
<del> GitCommit: dockerversion.GITCOMMIT,
<del> GoVersion: runtime.Version(),
<del> Os: runtime.GOOS,
<del> Arch: runtime.GOARCH,
<del> Experimental: utils.ExperimentalBuild(),
<add> Version: dockerversion.VERSION,
<add> ApiVersion: api.APIVERSION,
<add> GitCommit: dockerversion.GITCOMMIT,
<add> GoVersion: runtime.Version(),
<add> Os: runtime.GOOS,
<add> Arch: runtime.GOARCH,
<ide> }
<add>
<add> if version.GreaterThanOrEqualTo("1.19") {
<add> v.Experimental = utils.ExperimentalBuild()
<add> }
<add>
<ide> if kernelVersion, err := kernel.GetKernelVersion(); err == nil {
<ide> v.KernelVersion = kernelVersion.String()
<ide> }
<ide><path>api/types/types.go
<ide> type Version struct {
<ide> Os string
<ide> Arch string
<ide> KernelVersion string `json:",omitempty"`
<del> Experimental bool
<add> Experimental bool `json:",omitempty"`
<ide> }
<ide>
<ide> // GET "/info" | 2 |
Text | Text | fix documentation for sharded dbs | 22584d0cbf14d5b66c57fd84d4097dd1442c323b | <ide><path>guides/source/active_record_multiple_databases.md
<ide> using sharding both a `role` and `shard` must be passed:
<ide>
<ide> ```ruby
<ide> ActiveRecord::Base.connected_to(role: :writing, shard: :default) do
<del> @id = Person.create! # creates a record in shard one
<add> @id = Person.create! # Creates a record in shard default
<ide> end
<ide>
<ide> ActiveRecord::Base.connected_to(role: :writing, shard: :shard_one) do
<del> Person.find(@id) # can't find record, doesn't exist
<add> Person.find(@id) # Can't find record, doesn't exist because it was created
<add> # in the default shard
<ide> end
<ide> ```
<ide>
<ide> role and the shard with the `connected_to` API.
<ide>
<ide> ```ruby
<ide> ActiveRecord::Base.connected_to(role: :reading, shard: :shard_one) do
<del> Person.first # lookup record from read replica of shard one
<add> Person.first # Lookup record from read replica of shard one
<ide> end
<ide> ```
<ide> | 1 |
Text | Text | remove child factories | 42c837e4ddc32550b0a7f59401f4a3f4a3731445 | <ide><path>docs/docs/09.1-animation.md
<ide> This is called when the `willEnter` `callback` is called.
<ide>
<ide> This is called when the child has been removed from the `ReactTransitionGroup`. Though the child has been removed, `ReactTransitionGroup` will keep it in the DOM until `callback` is called.
<ide>
<del>Note that because the child has been removed you can no longer send it reactive updates. If you need this functionality, see the section on Child Factories below.
<del>
<ide> ### `componentDidLeave()`
<ide>
<ide> This is called when the `willLeave` `callback` is called (at the same time as `componentWillUnmount`).
<ide> By default `ReactTransitionGroup` renders as a `span`. You can change this behav
<ide> ```
<ide>
<ide> Every DOM component is under `React.DOM`. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself!
<del>
<del>### Advanced Feature: Child Factories
<del>
<del>`ReactTransitionGroup` is unique because when a child leaves `ReactTransitionGroup` it may stay in the DOM after the child is removed from the group. This means that you can't send it reactive updates anymore. If you need to send it updates, you can provide a `childFactory` callback prop which will take the original child instance (even after it has left the group) and return a React component to render in its place.
<del>
<del>Normally you do not need to think about this feature. If you do, the easiest way to understand how this works is to look at the source for `ReactCSSTransitionGroup`. | 1 |
Javascript | Javascript | remove unused type import | 146f23bbde639513cb36c36bc3be12b1e07638da | <ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js
<ide> const HarmonyExports = require("./HarmonyExports");
<ide> const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency");
<ide> const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency");
<ide>
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */
<ide> /** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */
<ide> /** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */ | 1 |
Javascript | Javascript | add more spec | 3c02ab36212699dc27a6345c091dbeb37b0b4fa1 | <ide><path>spec/config-spec.js
<ide> describe('Config', () => {
<ide> expect(atom.config.get('value')).toEqual({array: [1, {b: 2}, 3]})
<ide> })
<ide>
<add> it('gets scoped values correctly', () => {
<add> atom.config.set('foo', 'bam', {scope: ['second']})
<add> expect(atom.config.get('foo', {'scopeSelector': 'second'})).toBe('bam')
<add> atom.config.resetProjectSettings({'*': {'foo': 'baz'}, 'second': {'foo': 'bar'}}, dummyPath)
<add> expect(atom.config.get('foo', {'scopeSelector': 'second'})).toBe('baz')
<add> atom.config.clearProjectSettings()
<add> expect(atom.config.get('foo', {'scopeSelector': 'second'})).toBe('bam')
<add> })
<add>
<ide> it('clears project settings correctly', () => {
<ide> atom.config.set('foo', 'bar')
<ide> expect(atom.config.get('foo')).toBe('bar')
<ide> atom.config.resetProjectSettings({'*': {'foo': 'baz'}, 'second': {'foo': 'bar'}}, dummyPath)
<del>
<ide> expect(atom.config.get('foo')).toBe('baz')
<ide> expect(atom.config.getSources().length).toBe(1)
<ide> atom.config.clearProjectSettings() | 1 |
Text | Text | add scipy link to conv layer docs | ec450f429ee40c8aa093c2a1add942018950fffa | <ide><path>docs/sources/layers/convolutional.md
<ide> Convolution operator for filtering windows of two-dimensional inputs.
<ide> - __init__: name of initialization function for the weights of the layer (see: [initializations](../initializations.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument.
<ide> - __activation__: name of activation function to use (see: [activations](../activations.md)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x).
<ide> - __weights__: list of numpy arrays to set as initial weights.
<del> - __border_mode__: 'valid', 'full', or 'same'. See scipy.signal.convolve2d.
<add> - __border_mode__: 'valid', 'full', or 'same'. [See scipy.signal.convolve2d](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html).
<ide> - __subsample__: tuple of length 2. Factor by which to subsample output. Also called strides elsewhere.
<ide> - __W_regularizer__: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the main weights matrix.
<ide> - __b_regularizer__: instance of [WeightRegularizer](../regularizers.md), applied to the bias. | 1 |
Python | Python | add recursive flag to glob in filesystem sensor | 789e0eaee8fa9dc35b27c49cc50a62ea4f635978 | <ide><path>airflow/sensors/filesystem.py
<ide> class FileSensor(BaseSensorOperator):
<ide> :param filepath: File or folder name (relative to
<ide> the base path set within the connection), can be a glob.
<ide> :type filepath: str
<add> :param recursive: when set to ``True``, enables recursive directory matching behavior of
<add> ``**`` in glob filepath parameter. Defaults to ``False``.
<add> :type recursive: bool
<ide> """
<ide>
<ide> template_fields = ('filepath',)
<ide> ui_color = '#91818a'
<ide>
<del> def __init__(self, *, filepath, fs_conn_id='fs_default', **kwargs):
<add> def __init__(self, *, filepath, fs_conn_id='fs_default', recursive=False, **kwargs):
<ide> super().__init__(**kwargs)
<ide> self.filepath = filepath
<ide> self.fs_conn_id = fs_conn_id
<add> self.recursive = recursive
<ide>
<ide> def poke(self, context):
<ide> hook = FSHook(self.fs_conn_id)
<ide> basepath = hook.get_path()
<ide> full_path = os.path.join(basepath, self.filepath)
<ide> self.log.info('Poking for file %s', full_path)
<ide>
<del> for path in glob(full_path):
<add> for path in glob(full_path, recursive=self.recursive):
<ide> if os.path.isfile(path):
<ide> mod_time = os.path.getmtime(path)
<ide> mod_time = datetime.datetime.fromtimestamp(mod_time).strftime('%Y%m%d%H%M%S')
<ide><path>tests/sensors/test_filesystem.py
<ide> def test_wildcard_file(self):
<ide> task._hook = self.hook
<ide> task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
<ide>
<add> def test_wildcared_directory(self):
<add> temp_dir = tempfile.mkdtemp()
<add> subdir = tempfile.mkdtemp(dir=temp_dir)
<add> task = FileSensor(
<add> task_id='test',
<add> filepath=temp_dir + "/**",
<add> fs_conn_id='fs_default',
<add> dag=self.dag,
<add> timeout=0,
<add> poke_interval=1,
<add> recursive=True,
<add> )
<add> task._hook = self.hook
<add>
<add> try:
<add> # `touch` the dir
<add> open(subdir + "/file", "a").close()
<add> task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
<add> finally:
<add> shutil.rmtree(temp_dir)
<add>
<ide> def test_subdirectory_not_empty(self):
<ide> suffix = '.txt'
<ide> temp_dir = tempfile.mkdtemp() | 2 |
Go | Go | ignore empty branch (staticcheck) | 41cfcac7fc93a932b10f0e97f4b1d53f43dcb7dd | <ide><path>daemon/graphdriver/graphtest/graphbench_unix.go
<ide> func DriverBenchDiffApplyN(b *testing.B, fileCount int, drivername string, drive
<ide> b.StopTimer()
<ide> arch.Close()
<ide>
<add> // suppressing "SA9003: empty branch (staticcheck)" instead of commenting-out/removing
<add> // these lines because removing/commenting these lines causes a ripple effect
<add> // of changes, and there's still a to-do below
<add> //nolint:staticcheck
<ide> if applyDiffSize != diffSize {
<ide> // TODO: enforce this
<ide> //b.Fatalf("Apply diff size different, got %d, expected %s", applyDiffSize, diffSize) | 1 |
Text | Text | resolve incorrect doesntexist method name | 6a5ab45714f928484dd09aa3330d32312f2cdb61 | <ide><path>CHANGELOG-5.5.md
<ide> ## v5.5.33 (2018-01-30)
<ide>
<ide> ### Added
<del>- Added `notExists()` method to query builder ([#22836](https://github.com/laravel/framework/pull/22836), [9d2a7ca](https://github.com/laravel/framework/commit/9d2a7ca049e71d39e453ba8c34addb657b71b237))
<add>- Added `doesntExist()` method to query builder ([#22836](https://github.com/laravel/framework/pull/22836), [9d2a7ca](https://github.com/laravel/framework/commit/9d2a7ca049e71d39e453ba8c34addb657b71b237))
<ide> - Added `assertHeaderMissing()` assertion ([#22849](https://github.com/laravel/framework/pull/22849), [#22866](https://github.com/laravel/framework/pull/22866))
<ide> - Added support for higher order unique ([#22851](https://github.com/laravel/framework/pull/22851))
<ide> - Added boolean toggle to `withTrashed()` ([#22888](https://github.com/laravel/framework/pull/22888)) | 1 |
Ruby | Ruby | register trackers on extensions, not handlers | ec23296eb607d7974c7281d520b543640024418f | <ide><path>actionpack/lib/action_view/dependency_tracker.rb
<ide> def self.find_dependencies(name, template)
<ide> end
<ide> end
<ide>
<del> def self.register_tracker(handler, tracker)
<add> def self.register_tracker(extension, tracker)
<add> handler = Template.handler_for_extension(extension)
<ide> @trackers[handler] = tracker
<ide> end
<ide>
<ide> class ERBTracker
<ide> /x
<ide>
<ide> def self.call(name, template)
<del> new(name, template).call
<add> new(name, template).dependencies
<ide> end
<ide>
<ide> def initialize(name, template)
<ide> @name, @template = name, template
<ide> end
<ide>
<del> def call
<add> def dependencies
<ide> render_dependencies + explicit_dependencies
<ide> end
<ide>
<ide> private
<ide> attr_reader :name, :template
<ide>
<add> def source
<add> template.source
<add> end
<add>
<ide> def directory
<ide> name.split("/")[0..-2].join("/")
<ide> end
<ide>
<ide> def render_dependencies
<del> template.source.scan(RENDER_DEPENDENCY).
<add> source.scan(RENDER_DEPENDENCY).
<ide> collect(&:second).uniq.
<ide>
<ide> # render(@topic) => render("topics/topic")
<ide> def render_dependencies
<ide> end
<ide>
<ide> def explicit_dependencies
<del> template.source.scan(EXPLICIT_DEPENDENCY).flatten.uniq
<add> source.scan(EXPLICIT_DEPENDENCY).flatten.uniq
<ide> end
<ide> end
<ide>
<del> register_tracker Template::Handlers::ERB, ERBTracker
<add> register_tracker :erb, ERBTracker
<ide> end
<ide> end
<ide><path>actionpack/test/template/dependency_tracker_test.rb
<ide> require 'action_view/dependency_tracker'
<ide>
<ide> class DependencyTrackerTest < ActionView::TestCase
<del> Neckbeard = Class.new
<del> Bowtie = Class.new
<add> Neckbeard = lambda {|template| template.source }
<add> Bowtie = lambda {|template| template.source }
<ide>
<ide> class NeckbeardTracker
<ide> def self.call(name, template)
<ide> def tracker
<ide> end
<ide>
<ide> def setup
<del> tracker.register_tracker(Neckbeard, NeckbeardTracker)
<add> ActionView::Template.register_template_handler :neckbeard, Neckbeard
<add> tracker.register_tracker(:neckbeard, NeckbeardTracker)
<ide> end
<ide>
<ide> def teardown
<del> tracker.remove_tracker(Neckbeard)
<add> tracker.remove_tracker(:neckbeard)
<ide> end
<ide>
<ide> def test_finds_tracker_by_template_handler
<ide><path>actionpack/test/template/digestor_test.rb
<ide> class FixtureTemplate
<ide>
<ide> def initialize(template_path)
<ide> @source = File.read(template_path)
<del> @handler = ActionView::Template::Handlers::ERB
<add> @handler = ActionView::Template.handler_for_extension(:erb)
<ide> rescue Errno::ENOENT
<ide> raise ActionView::MissingTemplate.new([], "", [], true, [])
<ide> end | 3 |
PHP | PHP | allow character classes in attribute patterns | 246c09ae4030c1bbded2f4ad3d56fb971ca60eca | <ide><path>lib/Cake/Test/Case/Utility/HashTest.php
<ide> public function testExtractAttributePattern() {
<ide> $result = Hash::extract($data, '{n}.Article[title=/^First/]');
<ide> $expected = array($data[0]['Article']);
<ide> $this->assertEquals($expected, $result);
<add>
<add> $result = Hash::extract($data, '{n}.Article[title=/^Fir[a-z]+/]');
<add> $expected = array($data[0]['Article']);
<add> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Utility/Hash.php
<ide> protected static function _matchToken($key, $token) {
<ide> */
<ide> protected static function _matches(array $data, $selector) {
<ide> preg_match_all(
<del> '/(\[ (?<attr>[^=><!]+?) (\s* (?<op>[><!]?[=]|[><]) \s* (?<val>[^\]]+) )? \])/x',
<add> '/(\[ (?<attr>[^=><!]+?) (\s* (?<op>[><!]?[=]|[><]) \s* (?<val>(?:\/.*?\/ | [^\]]+)) )? \])/x',
<ide> $selector,
<ide> $conditions,
<ide> PREG_SET_ORDER | 2 |
Python | Python | remove workaround for fixed issue | 845c48979a4c0b1343037f944a139b88849c6285 | <ide><path>numpy/lib/function_base.py
<ide> def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
<ide> n = np.array(False, dtype=bool)
<ide>
<ide> r = take(ap, indices, axis=0, out=out)
<del> if out is not None:
<del> r = out # workaround for gh-16276
<ide>
<ide> else:
<ide> # weight the points above and below the indices | 1 |
Ruby | Ruby | remove hack to support bigdecimal in ruby 1.9 | 7926ab1004d2ec9118516445d32c75c9aaacba79 | <ide><path>activesupport/lib/active_support/core_ext/object/duplicable.rb
<ide> def duplicable?
<ide>
<ide> require 'bigdecimal'
<ide> class BigDecimal
<del> # Needed to support Ruby 1.9.x, as it doesn't allow dup on BigDecimal, instead
<del> # raises TypeError exception. Checking here on the runtime whether BigDecimal
<del> # will allow dup or not.
<del> begin
<del> BigDecimal.new('4.56').dup
<del>
<del> def duplicable?
<del> true
<del> end
<del> rescue TypeError
<del> # can't dup, so use superclass implementation
<add> def duplicable?
<add> true
<ide> end
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/object/duplicable_test.rb
<ide> class DuplicableTest < ActiveSupport::TestCase
<ide> RAISE_DUP = [nil, false, true, :symbol, 1, 2.3, method(:puts)]
<ide> ALLOW_DUP = ['1', Object.new, /foo/, [], {}, Time.now, Class.new, Module.new]
<del>
<del> # Needed to support Ruby 1.9.x, as it doesn't allow dup on BigDecimal, instead
<del> # raises TypeError exception. Checking here on the runtime whether BigDecimal
<del> # will allow dup or not.
<del> begin
<del> bd = BigDecimal.new('4.56')
<del> ALLOW_DUP << bd.dup
<del> rescue TypeError
<del> RAISE_DUP << bd
<del> end
<add> ALLOW_DUP << BigDecimal.new('4.56')
<ide>
<ide> def test_duplicable
<ide> RAISE_DUP.each do |v| | 2 |
Text | Text | remove file and directory | a8f4019693ed447ad834bb53af4e954e6e8ad7a7 | <ide><path>docs/README.md
<ide> You can also require many of these classes in your package via:
<ide> The classes available from `require 'atom'` are:
<ide> * [BufferedProcess][BufferedProcess]
<ide> * [BufferedNodeProcess][BufferedNodeProcess]
<del> * [Directory][Directory]
<ide> * [EditorView][EditorView]
<del> * [File][File]
<ide> * [Git][Git]
<ide> * [Point][Point]
<ide> * [Range][Range]
<ide> Atom ships with node 0.11.10 and the comprehensive node API docs are available
<ide> [Atom]: ../classes/Atom.html
<ide> [BufferedProcess]: ../classes/BufferedProcess.html
<ide> [BufferedNodeProcess]: ../classes/BufferedNodeProcess.html
<del>[Directory]: ../classes/Directory.html
<ide> [Editor]: ../classes/Editor.html
<ide> [EditorView]: ../classes/EditorView.html
<del>[File]: ../classes/File.html
<ide> [Git]: ../classes/Git.html
<ide> [Point]: ../classes/Point.html
<ide> [Range]: ../classes/Range.html | 1 |
PHP | PHP | add notifiable trait to default user | 9575714700fd1c1796f7376a4bdc65d3683409ff | <ide><path>app/User.php
<ide>
<ide> namespace App;
<ide>
<add>use Illuminate\Notifications\Notifiable;
<ide> use Illuminate\Foundation\Auth\User as Authenticatable;
<ide>
<ide> class User extends Authenticatable
<ide> {
<add> use Notifiable;
<add>
<ide> /**
<ide> * The attributes that are mass assignable.
<ide> * | 1 |
Ruby | Ruby | simplify route score | 0334eb6dfa0db87b3996f168c852c272ee4daf1a | <ide><path>actionpack/lib/action_dispatch/journey/route.rb
<ide> def required_keys
<ide> end
<ide>
<ide> def score(supplied_keys)
<del> required_keys = path.required_names
<del>
<del> required_keys.each do |k|
<add> path.required_names.each do |k|
<ide> return -1 unless supplied_keys.include?(k)
<ide> end
<ide>
<del> score = 0
<del> path.names.each do |k|
<del> score += 1 if supplied_keys.include?(k)
<del> end
<del>
<del> score + (required_defaults.length * 2)
<add> (required_defaults.length * 2) + path.names.count { |k| supplied_keys.include?(k) }
<ide> end
<ide>
<ide> def parts | 1 |
Ruby | Ruby | remove useless conditionals | 89448a7f5c21729568eaa12250447f313197a30d | <ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb
<ide> def each_element(object)
<ide> end
<ide>
<ide> def fields_for_style?(object)
<del> (object.is_a?(Hash) || object.is_a?(Parameters)) &&
<add> object.is_a?(Parameters) &&
<ide> object.to_unsafe_h.all? { |k, v| k =~ /\A-?\d+\z/ && v.is_a?(Hash) }
<ide> end
<ide>
<ide> def hash_filter(params, filter)
<ide> else
<ide> # Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
<ide> params[key] = each_element(value) do |element|
<del> if element.is_a?(Hash) || element.is_a?(Parameters)
<add> if element.is_a?(Parameters)
<ide> element = self.class.new(element) unless element.respond_to?(:permit)
<ide> element.permit(*Array.wrap(filter[key]))
<ide> end | 1 |
Javascript | Javascript | fix incorrect handling of empty keys | a811a4a13042a4b3ba019fbe1221f4c83b02a699 | <ide><path>lib/querystring.js
<ide> QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
<ide> kstr = x.substring(0, idx),
<ide> vstr = x.substring(idx + 1), k, v;
<ide>
<add> if (kstr === '' && vstr !== '') {
<add> kstr = vstr;
<add> vstr = '';
<add> }
<add>
<ide> try {
<ide> k = decodeURIComponent(kstr);
<ide> v = decodeURIComponent(vstr);
<ide><path>test/simple/test-querystring.js
<ide> var qsTestCases = [
<ide> { hasOwnProperty: 'x',
<ide> toString: 'foo',
<ide> valueOf: 'bar',
<del> __defineGetter__: 'baz' }]
<add> __defineGetter__: 'baz' }],
<add> // See: https://github.com/joyent/node/issues/3058
<add> ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }]
<ide> ];
<ide>
<ide> // [ wonkyQS, canonicalQS, obj ] | 2 |
Javascript | Javascript | remove tooltip opacity from core-controller | 8398d26d10ee030339cafb77519a98857ce9dd66 | <ide><path>src/core/core.controller.js
<ide>
<ide> // The usual updates
<ide> this.tooltip.initialize();
<del>
<del> // Active
<del> if (this.tooltipActive.length) {
<del> this.tooltip._model.opacity = 1;
<del>
<del> helpers.extend(this.tooltip, {
<del> _active: this.tooltipActive,
<del> });
<del>
<del> } else {
<del> // Inactive
<del> this.tooltip._model.opacity = 0;
<del> }
<del> this.tooltip.update();
<add> this.tooltip._active = this.tooltipActive;
<ide> }
<ide>
<ide> // Hover animations | 1 |
Ruby | Ruby | use quiet_safe_system to silence cvs updates | 37c08393dbd482c4cfc37a0ec346564f8532257b | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def clone_repo
<ide> end
<ide>
<ide> def update
<del> @clone.cd { safe_system cvspath, "up" }
<add> @clone.cd { quiet_safe_system cvspath, { :quiet_flag => "-Q" }, "up" }
<ide> end
<ide>
<ide> def split_url(in_url) | 1 |
Python | Python | add list_deployments method on kubernetes driver | 1e54a6c0aef8ec28d4d0ee8a347650d03df083c0 | <ide><path>libcloud/container/drivers/kubernetes.py
<ide> def sum_resources(self, *resource_dicts):
<ide> return {"cpu": to_cpu_str(total_cpu), "memory": to_memory_str(total_memory)}
<ide>
<ide>
<add>class KubernetesDeployment:
<add> def __init__(self, id, name, namespace, created_at,
<add> replicas, selector, extra=None):
<add> self.id = id
<add> self.name = name
<add> self.namespace = namespace
<add> self.created_at = created_at
<add> self.replicas = replicas
<add> self.selector = selector
<add> self.extra = extra or {}
<add>
<add> def __repr__(self):
<add> return ('<KubernetesDeployment name=%s namespace=%s replicas=%s>' %
<add> (self.name, self.namespace, self.replicas))
<add>
<add>
<ide> class KubernetesPod(object):
<ide> def __init__(
<ide> self,
<ide> def ex_list_services(self):
<ide> ROOT_URL + "v1/services", enforce_unicode_response=True
<ide> ).object["items"]
<ide>
<add> def ex_list_deployments(self):
<add> items = self.connection.request(
<add> "/apis/apps/v1/deployments",
<add> enforce_unicode_response=True).object['items']
<add> return [self._to_deployment(item) for item in items]
<add>
<add> def _to_deployment(self, data):
<add> id_ = data['metadata']['uid']
<add> name = data['metadata']['name']
<add> namespace = data['metadata']['namespace']
<add> created_at = data['metadata']['creationTimestamp']
<add> replicas = data['spec']['replicas']
<add> selector = data['spec']['selector']
<add>
<add> extra = {
<add> 'labels': data['metadata']['labels'],
<add> 'strategy': data['spec']['strategy']['type'],
<add> 'total_replicas': data['status']['replicas'],
<add> 'updated_replicas': data['status']['updatedReplicas'],
<add> 'ready_replicas': data['status']['readyReplicas'],
<add> 'available_replicas': data['status']['availableReplicas'],
<add> 'conditions': data['status']['conditions'],
<add> }
<add> return KubernetesDeployment(id=id_,
<add> name=name,
<add> namespace=namespace,
<add> created_at=created_at,
<add> replicas=replicas,
<add> selector=selector,
<add> extra=extra)
<add>
<ide> def _to_node(self, data):
<ide> """
<ide> Convert an API node data object to a `Node` object | 1 |
Java | Java | fix path matching for paths containing spaces | 3c92ddc94b04f1dc057125d336e5220c92351442 | <ide><path>spring-core/src/main/java/org/springframework/util/AntPathMatcher.java
<ide> public class AntPathMatcher implements PathMatcher {
<ide>
<ide> private boolean caseSensitive = true;
<ide>
<del> private boolean trimTokens = true;
<add> private boolean trimTokens = false;
<ide>
<ide> private volatile Boolean cachePatterns;
<ide>
<ide> else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
<ide> }
<ide>
<ide> private boolean isPotentialMatch(String path, String[] pattDirs) {
<del> char[] pathChars = path.toCharArray();
<del> int pos = 0;
<del> for (String pattDir : pattDirs) {
<del> int skipped = skipSeparator(path, pos, this.pathSeparator);
<del> pos += skipped;
<del> skipped = skipSegment(pathChars, pos, pattDir);
<del> if (skipped < pattDir.length()) {
<del> if (skipped > 0) {
<del> return true;
<add> if (!this.trimTokens) {
<add> char[] pathChars = path.toCharArray();
<add> int pos = 0;
<add> for (String pattDir : pattDirs) {
<add> int skipped = skipSeparator(path, pos, this.pathSeparator);
<add> pos += skipped;
<add> skipped = skipSegment(pathChars, pos, pattDir);
<add> if (skipped < pattDir.length()) {
<add> if (skipped > 0) {
<add> return true;
<add> }
<add> return (pattDir.length() > 0) && isWildcardChar(pattDir.charAt(0));
<ide> }
<del> return (pattDir.length() > 0) && isWildcardChar(pattDir.charAt(0));
<add> pos += skipped;
<ide> }
<del> pos += skipped;
<ide> }
<ide> return true;
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java
<ide> public void match() {
<ide> assertTrue(pathMatcher.match("/{bla}.*", "/testing.html"));
<ide> }
<ide>
<add> // SPR-14247
<add> @Test
<add> public void matchWithTrimTokensEnabled() throws Exception {
<add> pathMatcher.setTrimTokens(true);
<add>
<add> assertTrue(pathMatcher.match("/foo/bar", "/foo /bar"));
<add> }
<add>
<ide> @Test
<ide> public void withMatchStart() {
<ide> // test exact matching | 2 |
Javascript | Javascript | run method sorting codemod | f3f939dde4c06eb7be88dfac671d015d3724e2be | <ide><path>lib/app.js
<ide> import { execOnce, warn, loadGetInitialProps } from './utils'
<ide> import { makePublicRouterInstance } from './router'
<ide>
<ide> export default class App extends Component {
<add> static childContextTypes = {
<add> _containerProps: PropTypes.any,
<add> headManager: PropTypes.object,
<add> router: PropTypes.object
<add> }
<add>
<ide> static displayName = 'App'
<ide>
<ide> static async getInitialProps ({ Component, router, ctx }) {
<ide> const pageProps = await loadGetInitialProps(Component, ctx)
<ide> return {pageProps}
<ide> }
<ide>
<del> static childContextTypes = {
<del> _containerProps: PropTypes.any,
<del> headManager: PropTypes.object,
<del> router: PropTypes.object
<del> }
<del>
<ide> getChildContext () {
<ide> const { headManager } = this.props
<ide> return {
<ide> export class Container extends Component {
<ide> this.scrollToHash()
<ide> }
<ide>
<add> shouldComponentUpdate (nextProps) {
<add> // need this check not to rerender component which has already thrown an error
<add> return !shallowEquals(this.props, nextProps)
<add> }
<add>
<ide> componentDidUpdate () {
<ide> this.scrollToHash()
<ide> }
<ide> export class Container extends Component {
<ide> setTimeout(() => el.scrollIntoView(), 0)
<ide> }
<ide>
<del> shouldComponentUpdate (nextProps) {
<del> // need this check not to rerender component which has already thrown an error
<del> return !shallowEquals(this.props, nextProps)
<del> }
<del>
<ide> render () {
<ide> const {children} = this.props
<ide> return <>{children}</>
<ide><path>lib/link.js
<ide> function isLocal (href) {
<ide> const warnLink = execOnce(warn)
<ide>
<ide> class Link extends Component {
<del> constructor (props, ...rest) {
<del> super(props, ...rest)
<del> this.formatUrls(props)
<del> }
<del>
<ide> static propTypes = exact({
<ide> href: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
<ide> as: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
<ide> class Link extends Component {
<ide> ]).isRequired
<ide> })
<ide>
<add> constructor (props, ...rest) {
<add> super(props, ...rest)
<add> this.formatUrls(props)
<add> }
<add>
<add> componentDidMount () {
<add> this.prefetch()
<add> }
<add>
<add> componentDidUpdate (prevProps) {
<add> if (JSON.stringify(this.props.href) !== JSON.stringify(prevProps.href)) {
<add> this.prefetch()
<add> }
<add> }
<add>
<ide> // eslint-disable-next-line camelcase
<ide> UNSAFE_componentWillReceiveProps (nextProps) {
<ide> this.formatUrls(nextProps)
<ide> }
<ide>
<add> // We accept both 'href' and 'as' as objects which we can pass to `url.format`.
<add> // We'll handle it here.
<add> formatUrls (props) {
<add> this.href = props.href && typeof props.href === 'object'
<add> ? format(props.href)
<add> : props.href
<add> this.as = props.as && typeof props.as === 'object'
<add> ? format(props.as)
<add> : props.as
<add> }
<add>
<ide> linkClicked = e => {
<ide> const { nodeName, target } = e.currentTarget
<ide> if (nodeName === 'A' &&
<ide> class Link extends Component {
<ide> Router.prefetch(href)
<ide> }
<ide>
<del> componentDidMount () {
<del> this.prefetch()
<del> }
<del>
<del> componentDidUpdate (prevProps) {
<del> if (JSON.stringify(this.props.href) !== JSON.stringify(prevProps.href)) {
<del> this.prefetch()
<del> }
<del> }
<del>
<del> // We accept both 'href' and 'as' as objects which we can pass to `url.format`.
<del> // We'll handle it here.
<del> formatUrls (props) {
<del> this.href = props.href && typeof props.href === 'object'
<del> ? format(props.href)
<del> : props.href
<del> this.as = props.as && typeof props.as === 'object'
<del> ? format(props.as)
<del> : props.as
<del> }
<del>
<ide> render () {
<ide> let { children } = this.props
<ide> let { href, as } = this
<ide><path>lib/side-effect.js
<ide> export default function withSideEffect (reduceComponentsToState, handleStateChan
<ide> }
<ide>
<ide> class SideEffect extends Component {
<del> // Try to use displayName of wrapped component
<del> static displayName = `SideEffect(${getDisplayName(WrappedComponent)})`
<add> // Expose canUseDOM so tests can monkeypatch it
<add> static canUseDOM = typeof window !== 'undefined'
<ide>
<ide> static contextTypes = WrappedComponent.contextTypes
<ide>
<del> // Expose canUseDOM so tests can monkeypatch it
<del> static canUseDOM = typeof window !== 'undefined'
<add> // Try to use displayName of wrapped component
<add> static displayName = `SideEffect(${getDisplayName(WrappedComponent)})`
<ide>
<ide> static peek () {
<ide> return state
<ide> export default function withSideEffect (reduceComponentsToState, handleStateChan
<ide> return recordedState
<ide> }
<ide>
<del> // eslint-disable-next-line camelcase
<del> UNSAFE_componentWillMount () {
<del> mountedInstances.add(this)
<del> emitChange(this)
<del> }
<del>
<ide> componentDidUpdate () {
<ide> emitChange(this)
<ide> }
<ide> export default function withSideEffect (reduceComponentsToState, handleStateChan
<ide> emitChange(this)
<ide> }
<ide>
<add> // eslint-disable-next-line camelcase
<add> UNSAFE_componentWillMount () {
<add> mountedInstances.add(this)
<add> emitChange(this)
<add> }
<add>
<ide> render () {
<ide> return <WrappedComponent>{ this.props.children }</WrappedComponent>
<ide> }
<ide><path>server/document.js
<ide> const Fragment = React.Fragment || function Fragment ({ children }) {
<ide> }
<ide>
<ide> export default class Document extends Component {
<add> static childContextTypes = {
<add> _documentProps: PropTypes.any
<add> }
<add>
<ide> static getInitialProps ({ renderPage }) {
<ide> const { html, head, errorHtml, buildManifest } = renderPage()
<ide> const styles = flush()
<ide> return { html, head, errorHtml, styles, buildManifest }
<ide> }
<ide>
<del> static childContextTypes = {
<del> _documentProps: PropTypes.any
<del> }
<del>
<ide> getChildContext () {
<ide> return { _documentProps: this.props }
<ide> }
<ide> export class Head extends Component {
<ide> nonce: PropTypes.string
<ide> }
<ide>
<del> getPreloadMainLinks () {
<add> getCssLinks () {
<ide> const { assetPrefix, files } = this.context._documentProps
<ide> if(!files || files.length === 0) {
<ide> return null
<ide> }
<ide>
<ide> return files.map((file) => {
<del> // Only render .js files here
<del> if(!/\.js$/.exec(file)) {
<add> // Only render .css files here
<add> if(!/\.css$/.exec(file)) {
<ide> return null
<ide> }
<ide>
<ide> return <link
<ide> key={file}
<ide> nonce={this.props.nonce}
<del> rel='preload'
<add> rel='stylesheet'
<ide> href={`${assetPrefix}/_next/${file}`}
<add> />
<add> })
<add> }
<add>
<add> getPreloadDynamicChunks () {
<add> const { dynamicImports, assetPrefix } = this.context._documentProps
<add> return dynamicImports.map((bundle) => {
<add> return <script
<add> async
<add> key={bundle.file}
<add> src={`${assetPrefix}/_next/${bundle.file}`}
<ide> as='script'
<add> nonce={this.props.nonce}
<ide> />
<ide> })
<ide> }
<ide>
<del> getCssLinks () {
<add> getPreloadMainLinks () {
<ide> const { assetPrefix, files } = this.context._documentProps
<ide> if(!files || files.length === 0) {
<ide> return null
<ide> }
<ide>
<ide> return files.map((file) => {
<del> // Only render .css files here
<del> if(!/\.css$/.exec(file)) {
<add> // Only render .js files here
<add> if(!/\.js$/.exec(file)) {
<ide> return null
<ide> }
<ide>
<ide> return <link
<ide> key={file}
<ide> nonce={this.props.nonce}
<del> rel='stylesheet'
<add> rel='preload'
<ide> href={`${assetPrefix}/_next/${file}`}
<del> />
<del> })
<del> }
<del>
<del> getPreloadDynamicChunks () {
<del> const { dynamicImports, assetPrefix } = this.context._documentProps
<del> return dynamicImports.map((bundle) => {
<del> return <script
<del> async
<del> key={bundle.file}
<del> src={`${assetPrefix}/_next/${bundle.file}`}
<ide> as='script'
<del> nonce={this.props.nonce}
<ide> />
<ide> })
<ide> }
<ide> export class Main extends Component {
<ide> }
<ide>
<ide> export class NextScript extends Component {
<add> static contextTypes = {
<add> _documentProps: PropTypes.any
<add> }
<add>
<ide> static propTypes = {
<ide> nonce: PropTypes.string
<ide> }
<ide>
<del> static contextTypes = {
<del> _documentProps: PropTypes.any
<add> getDynamicChunks () {
<add> const { dynamicImports, assetPrefix } = this.context._documentProps
<add> return dynamicImports.map((bundle) => {
<add> return <script
<add> async
<add> key={bundle.file}
<add> src={`${assetPrefix}/_next/${bundle.file}`}
<add> nonce={this.props.nonce}
<add> />
<add> })
<ide> }
<ide>
<ide> getScripts () {
<ide> export class NextScript extends Component {
<ide> })
<ide> }
<ide>
<del> getDynamicChunks () {
<del> const { dynamicImports, assetPrefix } = this.context._documentProps
<del> return dynamicImports.map((bundle) => {
<del> return <script
<del> async
<del> key={bundle.file}
<del> src={`${assetPrefix}/_next/${bundle.file}`}
<del> nonce={this.props.nonce}
<del> />
<del> })
<del> }
<del>
<ide> render () {
<ide> const { staticMarkup, assetPrefix, __NEXT_DATA__ } = this.context._documentProps
<ide> const { page, pathname, buildId } = __NEXT_DATA__
<ide><path>test/integration/basic/pages/dynamic/bundle.js
<ide> const HelloBundle = dynamic({
<ide> })
<ide>
<ide> export default class Bundle extends React.Component {
<del> static getInitialProps ({ query }) {
<del> return { showMore: Boolean(query.showMore) }
<del> }
<del>
<ide> static childContextTypes = {
<ide> data: PropTypes.object
<ide> }
<ide>
<add> static getInitialProps ({ query }) {
<add> return { showMore: Boolean(query.showMore) }
<add> }
<add>
<ide> getChildContext () {
<ide> return {
<ide> data: { title: 'ZEIT Rocks' }
<ide><path>test/integration/basic/pages/nav/shallow-routing.js
<ide> export default class extends Component {
<ide> return { getInitialPropsRunCount }
<ide> }
<ide>
<add> getCurrentCounter () {
<add> const { url } = this.props
<add> return url.query.counter ? parseInt(url.query.counter) : 0
<add> }
<add>
<ide> increase () {
<ide> const counter = this.getCurrentCounter()
<ide> const href = `/nav/shallow-routing?counter=${counter + 1}`
<ide> Router.push(href, href, { shallow: true })
<ide> }
<ide>
<del> getCurrentCounter () {
<del> const { url } = this.props
<del> return url.query.counter ? parseInt(url.query.counter) : 0
<del> }
<del>
<ide> render () {
<ide> return (
<ide> <div className='shallow-routing'>
<ide><path>test/integration/production/pages/dynamic/bundle.js
<ide> const HelloBundle = dynamic({
<ide> })
<ide>
<ide> export default class Bundle extends React.Component {
<del> static getInitialProps ({ query }) {
<del> return { showMore: Boolean(query.showMore) }
<del> }
<del>
<ide> static childContextTypes = {
<ide> data: PropTypes.object
<ide> }
<ide>
<add> static getInitialProps ({ query }) {
<add> return { showMore: Boolean(query.showMore) }
<add> }
<add>
<ide> getChildContext () {
<ide> return {
<ide> data: { title: 'ZEIT Rocks' }
<ide><path>test/integration/static/pages/dynamic.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<ide> export default class DynamicPage extends React.Component {
<del> state = {}
<del>
<ide> static getInitialProps ({ query }) {
<ide> return { text: query.text }
<ide> }
<ide>
<add> state = {}
<add>
<ide> componentDidMount () {
<ide> const [, hash] = location.href.split('#')
<ide> this.setState({ hash })
<ide><path>test/integration/with-router/components/header-nav.js
<ide> class HeaderNav extends React.Component {
<ide> this.props.router.events.off('routeChangeComplete', this.handleRouteChange)
<ide> }
<ide>
<del> handleRouteChangeTopLevelRouterDeprecatedBehavior = url => {
<add> handleRouteChange = url => {
<ide> this.setState({
<del> activeURLTopLevelRouterDeprecatedBehavior: url
<add> activeURL: url
<ide> })
<ide> };
<ide>
<ide> class HeaderNav extends React.Component {
<ide> })
<ide> };
<ide>
<del> handleRouteChange = url => {
<add> handleRouteChangeTopLevelRouterDeprecatedBehavior = url => {
<ide> this.setState({
<del> activeURL: url
<add> activeURLTopLevelRouterDeprecatedBehavior: url
<ide> })
<ide> };
<ide> | 9 |
Ruby | Ruby | add mime support for problem detail | 0d3bc8ec673fcb799e6e1f522d9dbf011e2a367b | <ide><path>actionpack/lib/action_dispatch/http/mime_types.rb
<ide>
<ide> # https://www.ietf.org/rfc/rfc4627.txt
<ide> # http://www.json.org/JSONRequest.html
<del>Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest )
<add># https://www.ietf.org/rfc/rfc7807.txt
<add>Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest application/problem+json )
<ide>
<ide> Mime::Type.register "application/pdf", :pdf, [], %w(pdf)
<ide> Mime::Type.register "application/zip", :zip, [], %w(zip)
<ide><path>actionpack/test/dispatch/request/json_params_parsing_test.rb
<ide> def teardown
<ide> )
<ide> end
<ide>
<add> test "parses json params for application problem+json" do
<add> assert_parses(
<add> { "person" => { "name" => "David" } },
<add> "{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/problem+json"
<add> )
<add> end
<add>
<ide> test "does not parse unregistered media types such as application/vnd.api+json" do
<ide> assert_parses(
<ide> {},
<ide> def teardown
<ide> )
<ide> end
<ide>
<add> test "parses json params for application problem+json" do
<add> assert_parses(
<add> { "user" => { "username" => "sikachu" }, "username" => "sikachu" },
<add> "{\"username\": \"sikachu\"}", "CONTENT_TYPE" => "application/problem+json"
<add> )
<add> end
<add>
<ide> test "parses json with non-object JSON content" do
<ide> assert_parses(
<ide> { "user" => { "_json" => "string content" }, "_json" => "string content" }, | 2 |
Ruby | Ruby | fix some typos in comments | d2660c8cadd973b7a7c8b09fa03888631f9eea4b | <ide><path>actionpack/lib/action_controller/metal/renderers.rb
<ide> module ClassMethods
<ide> #
<ide> # Both <tt>ActionController::Base</tt> and <tt>ActionController::API</tt>
<ide> # include <tt>ActionController::Renderers::All</tt>, making all renderers
<del> # avaialable in the controller. See <tt>Renderers::RENDERERS</tt> and <tt>Renderers.add</tt>.
<add> # available in the controller. See <tt>Renderers::RENDERERS</tt> and <tt>Renderers.add</tt>.
<ide> #
<ide> # Since <tt>ActionController::Metal</tt> controllers cannot render, the controller
<ide> # must include <tt>AbstractController::Rendering</tt>, <tt>ActionController::Rendering</tt>,
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def table_structure_with_collation(table_name, basic_structure)
<ide> result = exec_query(sql, 'SCHEMA').first
<ide>
<ide> if result
<del> # Splitting with left parantheses and picking up last will return all
<add> # Splitting with left parentheses and picking up last will return all
<ide> # columns separated with comma(,).
<ide> columns_string = result["sql"].split('(').last
<ide>
<ide><path>activerecord/test/cases/connection_adapters/type_lookup_test.rb
<ide> require "cases/helper"
<ide>
<del>unless current_adapter?(:PostgreSQLAdapter) # PostgreSQL does not use type strigns for lookup
<add>unless current_adapter?(:PostgreSQLAdapter) # PostgreSQL does not use type strings for lookup
<ide> module ActiveRecord
<ide> module ConnectionAdapters
<ide> class TypeLookupTest < ActiveRecord::TestCase
<ide><path>activerecord/test/cases/scoping/named_scoping_test.rb
<ide> def pro; end
<ide> :relation, # private class method on AR::Base
<ide> :new, # redefined class method on AR::Base
<ide> :all, # a default scope
<del> :public, # some imporant methods on Module and Class
<add> :public, # some important methods on Module and Class
<ide> :protected,
<ide> :private,
<ide> :name,
<ide><path>activesupport/test/core_ext/object/json_gem_encoding_test.rb
<ide>
<ide> # The AS::JSON encoder requires the BigDecimal core_ext, which, unfortunately,
<ide> # changes the BigDecimal#to_s output, and consequently the JSON gem output. So
<del># we need to require this unfront to ensure we don't get a false failure, but
<add># we need to require this upfront to ensure we don't get a false failure, but
<ide> # ideally we should just fix the BigDecimal core_ext to not change to_s without
<ide> # arguments.
<ide> require 'active_support/core_ext/big_decimal'
<ide><path>ci/travis.rb
<ide> def rake(*tasks)
<ide>
<ide> def env
<ide> if activesupport? && !isolated?
<del> # There is a known issue with the listen tests that casuses files to be
<add> # There is a known issue with the listen tests that causes files to be
<ide> # incorrectly GC'ed even when they are still in-use. The current is to
<ide> # only run them in isolation to avoid randomly failing our test suite.
<ide> { 'LISTEN' => '0' }
<ide><path>railties/lib/rails/engine.rb
<ide> module Rails
<ide> # The next thing that changes in isolated engines is the behavior of routes.
<ide> # Normally, when you namespace your controllers, you also need to namespace
<ide> # the related routes. With an isolated engine, the engine's namespace is
<del> # automatically applied, so you don't need to specify it explicity in your
<add> # automatically applied, so you don't need to specify it explicitly in your
<ide> # routes:
<ide> #
<ide> # MyEngine::Engine.routes.draw do
<ide><path>railties/test/application/configuration_test.rb
<ide> def update
<ide>
<ide> private
<ide>
<del> def form_authenticity_token(*args); token; end # stub the authenticy token
<add> def form_authenticity_token(*args); token; end # stub the authenticity token
<ide> end
<ide> RUBY
<ide> | 8 |
Python | Python | correct restful unitest for the previous commit | f5d157a7cfef6110c18d59e2fb6920c5202bcfb5 | <ide><path>unitest-restful.py
<ide> import shlex
<ide> import subprocess
<ide> import time
<add>import numbers
<ide> import unittest
<ide>
<ide> from glances import __version__
<ide> def test_004_items(self):
<ide> req = requests.get("%s/%s/%s" % (URL, method, i))
<ide> self.assertTrue(req.ok)
<ide> self.assertIsInstance(req.json(), dict)
<del> self.assertIsInstance(req.json()[i], float)
<add> print req.json()[i]
<add> self.assertIsInstance(req.json()[i], numbers.Number)
<ide>
<ide> def test_005_values(self):
<ide> """Values.""" | 1 |
Javascript | Javascript | add android version of kakapo | 4095394982fdd70a8142439e2f38161739396c2d | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> author: 'HS Schaaf',
<ide> },
<ide> {
<del> name: 'Kakapo',
<add> name: 'Kakapo - Android',
<add> icon: 'https://lh3.googleusercontent.com/xDc0D136JB8IvRsct9u4VTGh4nK1QwsZSRuEe-UxWd_JFtvNTrcaO5fEhcj4rGxv60pX=w300-rw',
<add> link: 'https://play.google.com/store/apps/details?id=com.kakaponative',
<add> author: 'Daniel Levitt',
<add> },
<add> {
<add> name: 'Kakapo - iOS',
<ide> icon: 'http://a2.mzstatic.com/eu/r30/Purple3/v4/12/ab/2a/12ab2a01-3a3c-9482-b8df-ab38ad281165/icon175x175.png',
<ide> link: 'https://itunes.apple.com/gb/app/kakapo/id1046673139?ls=1&mt=8',
<ide> author: 'Daniel Levitt', | 1 |
Text | Text | add chengelog entry to | 15175fdad7e2203e3d20b197f7b9aeb14c29d4d2 | <ide><path>activerecord/CHANGELOG.md
<add>* Avoid loading records from database when they are already loaded using
<add> the `pluck` method on a collection.
<add>
<add> Fixes #25921.
<add>
<add> *Ryuta Kamizono*
<add>
<ide> * Remove text default treated as an empty string in non-strict mode for
<ide> consistency with other types.
<ide> | 1 |
Javascript | Javascript | allow overriding native .click() suppression | a120bbbfae81daccf801fcf8deb0bc77d865e27f | <ide><path>src/event.js
<ide> jQuery.event = {
<ide> // If nobody prevented the default action, do it now
<ide> if ( !onlyHandlers && !event.isDefaultPrevented() ) {
<ide>
<del> if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
<del> !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
<add> if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
<add> jQuery.acceptData( elem ) ) {
<ide>
<ide> // Call a native DOM method on the target with the same name name as the event.
<ide> // Don't do default actions on window, that's where global variables be (#6170)
<ide> jQuery.event = {
<ide> // Prevent triggered image.load events from bubbling to window.load
<ide> noBubble: true
<ide> },
<del> click: {
<del> // For checkbox, fire native event so checked state will be right
<del> trigger: function() {
<del> if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
<del> this.click();
<del> return false;
<del> }
<del> }
<del> },
<ide> focus: {
<ide> // Fire native event if possible so blur/focus sequence is correct
<ide> trigger: function() {
<ide> jQuery.event = {
<ide> },
<ide> delegateType: "focusout"
<ide> },
<add> click: {
<add> // For checkbox, fire native event so checked state will be right
<add> trigger: function() {
<add> if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
<add> this.click();
<add> return false;
<add> }
<add> },
<add>
<add> // For cross-browser consistency, don't fire native .click() on links
<add> _default: function( event ) {
<add> return jQuery.nodeName( event.target, "a" );
<add> }
<add> },
<ide>
<ide> beforeunload: {
<ide> postDispatch: function( event ) {
<ide><path>test/unit/event.js
<ide> test("on(), multiple events at once and namespaces", function() {
<ide> test("on(), namespace with special add", function() {
<ide> expect(27);
<ide>
<del> var div = jQuery("<div/>").on("test", function(e) {
<del> ok( true, "Test event fired." );
<del> });
<del>
<del> var i = 0;
<add> var i = 0,
<add> div = jQuery("<div/>").appendTo("#qunit-fixture").on( "test", function(e) {
<add> ok( true, "Test event fired." );
<add> });
<ide>
<ide> jQuery.event.special["test"] = {
<del> _default: function(e, data) {
<del> equal( this, document, "Make sure we're at the top of the chain." );
<del> equal( e.type, "test", "And that we're still dealing with a test event." );
<del> equal( e.target, div[0], "And that the target is correct." );
<del> ok( data !== undefined , "And that trigger data was passed." );
<add> _default: function( e, data ) {
<add> equal( e.type, "test", "Make sure we're dealing with a test event." );
<add> ok( data, "And that trigger data was passed." );
<add> strictEqual( e.target, div[0], "And that the target is correct." );
<add> equal( this, window, "And that the context is correct." );
<ide> },
<del> setup: function(){},
<del> teardown: function(){
<del> ok(true, "Teardown called.");
<add> setup: function() {},
<add> teardown: function() {
<add> ok( true, "Teardown called." );
<ide> },
<ide> add: function( handleObj ) {
<ide> var handler = handleObj.handler;
<del> handleObj.handler = function(e) {
<add> handleObj.handler = function( e ) {
<ide> e.xyz = ++i;
<ide> handler.apply( this, arguments );
<ide> };
<ide> },
<ide> remove: function() {
<del> ok(true, "Remove called.");
<add> ok( true, "Remove called." );
<ide> }
<ide> };
<ide>
<del> div.on("test.a", {"x": 1}, function(e) {
<add> div.on( "test.a", { x: 1 }, function( e ) {
<ide> ok( !!e.xyz, "Make sure that the data is getting passed through." );
<ide> equal( e.data["x"], 1, "Make sure data is attached properly." );
<ide> });
<ide>
<del> div.on("test.b", {"x": 2}, function(e) {
<add> div.on( "test.b", { x: 2 }, function( e ) {
<ide> ok( !!e.xyz, "Make sure that the data is getting passed through." );
<ide> equal( e.data["x"], 2, "Make sure data is attached properly." );
<ide> });
<ide>
<ide> // Should trigger 5
<del> div.trigger("test", 33.33);
<add> div.trigger( "test", 33.33 );
<ide>
<ide> // Should trigger 2
<del> div.trigger("test.a", "George Harrison");
<add> div.trigger( "test.a", "George Harrison" );
<ide>
<ide> // Should trigger 2
<del> div.trigger("test.b", { year: 1982 });
<add> div.trigger( "test.b", { year: 1982 } );
<ide>
<ide> // Should trigger 4
<ide> div.off("test");
<ide>
<del> div = jQuery("<div/>").on("test", function(e) {
<add> div = jQuery("<div/>").on( "test", function( e ) {
<ide> ok( true, "Test event fired." );
<ide> });
<ide> | 2 |
Python | Python | fix convergence issues for mlperf. | 64710c051f26a2778c03fc15ef29c4bcae01df32 | <ide><path>official/recommendation/data_async_generation.py
<ide> import contextlib
<ide> import datetime
<ide> import gc
<del>import functools
<ide> import multiprocessing
<ide> import json
<ide> import os
<ide> def get_cycle_folder_name(i):
<ide> return "cycle_{}".format(str(i).zfill(5))
<ide>
<ide>
<del>def _process_shard(shard_path, num_items, num_neg):
<del> # type: (str, int, int) -> (np.ndarray, np.ndarray, np.ndarray)
<add>def _process_shard(args):
<add> # type: ((str, int, int, int)) -> (np.ndarray, np.ndarray, np.ndarray)
<ide> """Read a shard of training data and return training vectors.
<ide>
<ide> Args:
<ide> def _process_shard(shard_path, num_items, num_neg):
<ide> num_neg: The number of negatives to generate per positive example.
<ide> seed: Random seed to be used when generating negatives.
<ide> """
<add> shard_path, num_items, num_neg, seed = args
<add> np.random.seed(seed)
<ide>
<ide> # The choice to store the training shards in files rather than in memory
<ide> # is motivated by the fact that multiprocessing serializes arguments,
<ide> def _construct_training_records(
<ide> num_carryover = carryover[0].shape[0]
<ide> num_pts = num_carryover + num_train_positives * (1 + num_neg)
<ide>
<del> map_args = [i for i in training_shards * epochs_per_cycle]
<del> map_fn = functools.partial(_process_shard, num_neg=num_neg,
<del> num_items=num_items)
<add> # We choose a different random seed for each process, so that the processes
<add> # will not all choose the same random numbers.
<add> process_seeds = [np.random.randint(2**32)
<add> for _ in training_shards * epochs_per_cycle]
<add> map_args = [(shard, num_items, num_neg, process_seeds[i])
<add> for i, shard in enumerate(training_shards * epochs_per_cycle)]
<ide>
<ide> with contextlib.closing(multiprocessing.Pool(
<ide> processes=num_workers, initializer=init_worker)) as pool:
<del> data_generator = pool.imap_unordered(map_fn, map_args) # pylint: disable=no-member
<add> data_generator = pool.imap_unordered(_process_shard, map_args) # pylint: disable=no-member
<ide> data = [
<ide> np.zeros(shape=(num_pts,), dtype=np.int32) - 1,
<ide> np.zeros(shape=(num_pts,), dtype=np.uint16),
<ide><path>official/recommendation/data_preprocessing.py
<ide> def __init__(self, user_map, item_map, num_data_readers, cache_paths,
<ide> self.num_train_positives = num_train_positives
<ide>
<ide>
<del>def _filter_index_sort(raw_rating_path):
<del> # type: (str) -> (pd.DataFrame, dict, dict)
<add>def _filter_index_sort(raw_rating_path, match_mlperf):
<add> # type: (str, bool) -> (pd.DataFrame, dict, dict)
<ide> """Read in data CSV, and output structured data.
<ide>
<ide> This function reads in the raw CSV of positive items, and performs three
<ide> def _filter_index_sort(raw_rating_path):
<ide>
<ide> Args:
<ide> raw_rating_path: The path to the CSV which contains the raw dataset.
<add> match_mlperf: If True, change the sorting algorithm to match the MLPerf
<add> reference implementation.
<ide>
<ide> Returns:
<ide> A filtered, zero-index remapped, sorted dataframe, a dict mapping raw user
<ide> def _filter_index_sort(raw_rating_path):
<ide> # This sort is used to shard the dataframe by user, and later to select
<ide> # the last item for a user to be used in validation.
<ide> tf.logging.info("Sorting by user, timestamp...")
<del> df.sort_values([movielens.USER_COLUMN, movielens.TIMESTAMP_COLUMN],
<del> inplace=True)
<add>
<add> if match_mlperf:
<add> # This sort is equivalent to the non-MLPerf sort, except that the order of
<add> # items with the same user and timestamp are sometimes different. For some
<add> # reason, this sort results in a better hit-rate during evaluation, matching
<add> # the performance of the MLPerf reference implementation.
<add> df.sort_values(by=movielens.TIMESTAMP_COLUMN, inplace=True)
<add> df.sort_values([movielens.USER_COLUMN, movielens.TIMESTAMP_COLUMN],
<add> inplace=True, kind="mergesort")
<add> else:
<add> df.sort_values([movielens.USER_COLUMN, movielens.TIMESTAMP_COLUMN],
<add> inplace=True)
<ide>
<ide> df = df.reset_index() # The dataframe does not reconstruct indicies in the
<ide> # sort or filter steps.
<ide> def _train_eval_map_fn(args):
<ide> which validation negatives should be drawn.
<ide> cache_paths: rconst.Paths object containing locations for various cache
<ide> files.
<add> seed: Random seed to be used when generating testing negatives.
<add> match_mlperf: If True, sample eval negative with replacements, which the
<add> MLPerf reference implementation does.
<ide>
<ide> Returns:
<ide> A dict containing the evaluation data for a given shard.
<ide> """
<ide>
<del> shard, shard_id, num_items, cache_paths = args
<add> shard, shard_id, num_items, cache_paths, seed, match_mlperf = args
<add> np.random.seed(seed)
<ide>
<ide> users = shard[movielens.USER_COLUMN]
<ide> items = shard[movielens.ITEM_COLUMN]
<ide> def _train_eval_map_fn(args):
<ide>
<ide> test_negatives = stat_utils.sample_with_exclusion(
<ide> num_items=num_items, positive_set=set(block_items),
<del> n=rconst.NUM_EVAL_NEGATIVES, replacement=False)
<add> n=rconst.NUM_EVAL_NEGATIVES, replacement=match_mlperf)
<ide> test_blocks.append((
<ide> block_user[0] * np.ones((rconst.NUM_EVAL_NEGATIVES + 1,),
<ide> dtype=np.int32),
<ide> def _train_eval_map_fn(args):
<ide> }
<ide>
<ide>
<del>def generate_train_eval_data(df, approx_num_shards, num_items, cache_paths):
<del> # type: (pd.DataFrame, int, int, rconst.Paths) -> None
<add>def generate_train_eval_data(df, approx_num_shards, num_items, cache_paths,
<add> match_mlperf):
<add> # type: (pd.DataFrame, int, int, rconst.Paths, bool) -> None
<ide> """Construct training and evaluation datasets.
<ide>
<ide> This function manages dataset construction and validation that the
<ide> def generate_train_eval_data(df, approx_num_shards, num_items, cache_paths):
<ide> num_items: The cardinality of the item set.
<ide> cache_paths: rconst.Paths object containing locations for various cache
<ide> files.
<add> match_mlperf: If True, sample eval negative with replacements, which the
<add> MLPerf reference implementation does.
<ide> """
<ide>
<ide> num_rows = len(df)
<ide> def generate_train_eval_data(df, approx_num_shards, num_items, cache_paths):
<ide> tf.logging.info("Splitting train and test data and generating {} test "
<ide> "negatives per user...".format(rconst.NUM_EVAL_NEGATIVES))
<ide> tf.gfile.MakeDirs(cache_paths.train_shard_subdir)
<del> map_args = [(shards[i], i, num_items, cache_paths)
<del> for i in range(approx_num_shards)]
<ide>
<add> # We choose a different random seed for each process, so that the processes
<add> # will not all choose the same random numbers.
<add> process_seeds = [np.random.randint(2**32) for _ in range(approx_num_shards)]
<add> map_args = [(shards[i], i, num_items, cache_paths, process_seeds[i],
<add> match_mlperf)
<add> for i in range(approx_num_shards)]
<ide> with contextlib.closing(
<ide> multiprocessing.Pool(multiprocessing.cpu_count())) as pool:
<ide> test_shards = pool.map(_train_eval_map_fn, map_args) # pylint: disable=no-member
<ide> def generate_train_eval_data(df, approx_num_shards, num_items, cache_paths):
<ide> pickle.dump(eval_data, f, protocol=pickle.HIGHEST_PROTOCOL)
<ide>
<ide>
<del>def construct_cache(dataset, data_dir, num_data_readers):
<del> # type: (str, str, int, int, bool) -> NCFDataset
<add>def construct_cache(dataset, data_dir, num_data_readers, match_mlperf):
<add> # type: (str, str, int, bool) -> NCFDataset
<ide> """Load and digest data CSV into a usable form.
<ide>
<ide> Args:
<ide> dataset: The name of the dataset to be used.
<ide> data_dir: The root directory of the dataset.
<ide> num_data_readers: The number of parallel processes which will request
<ide> data during training.
<add> match_mlperf: If True, change the behavior of the cache construction to
<add> match the MLPerf reference implementation.
<ide> """
<ide> cache_paths = rconst.Paths(data_dir=data_dir)
<ide> num_data_readers = (num_data_readers or int(multiprocessing.cpu_count() / 2)
<ide> def construct_cache(dataset, data_dir, num_data_readers):
<ide> tf.gfile.MakeDirs(cache_paths.cache_root)
<ide>
<ide> raw_rating_path = os.path.join(data_dir, dataset, movielens.RATINGS_FILE)
<del> df, user_map, item_map = _filter_index_sort(raw_rating_path)
<add> df, user_map, item_map = _filter_index_sort(raw_rating_path, match_mlperf)
<ide>
<ide> generate_train_eval_data(df=df, approx_num_shards=approx_num_shards,
<del> num_items=len(item_map), cache_paths=cache_paths)
<add> num_items=len(item_map), cache_paths=cache_paths,
<add> match_mlperf=match_mlperf)
<ide> del approx_num_shards # value may have changed.
<ide>
<ide> ncf_dataset = NCFDataset(user_map=user_map, item_map=item_map,
<ide> def _shutdown(proc):
<ide>
<ide>
<ide> def instantiate_pipeline(dataset, data_dir, batch_size, eval_batch_size,
<del> num_data_readers=None, num_neg=4, epochs_per_cycle=1):
<add> num_data_readers=None, num_neg=4, epochs_per_cycle=1,
<add> match_mlperf=False):
<ide> """Preprocess data and start negative generation subprocess."""
<ide>
<ide> tf.logging.info("Beginning data preprocessing.")
<ide> ncf_dataset = construct_cache(dataset=dataset, data_dir=data_dir,
<del> num_data_readers=num_data_readers)
<add> num_data_readers=num_data_readers,
<add> match_mlperf=match_mlperf)
<ide>
<ide> tf.logging.info("Creating training file subprocess.")
<ide>
<ide><path>official/recommendation/data_test.py
<ide> from __future__ import print_function
<ide>
<ide> import os
<add>import pickle
<ide> import time
<ide>
<ide> import numpy as np
<add>import pandas as pd
<ide> import tensorflow as tf
<ide>
<ide> from official.datasets import movielens
<ide> def test_preprocessing(self):
<ide> # For the most part the necessary checks are performed within
<ide> # construct_cache()
<ide> ncf_dataset = data_preprocessing.construct_cache(
<del> dataset=DATASET, data_dir=self.temp_data_dir, num_data_readers=2)
<add> dataset=DATASET, data_dir=self.temp_data_dir, num_data_readers=2,
<add> match_mlperf=False)
<add> assert ncf_dataset.num_users == NUM_USERS
<add> assert ncf_dataset.num_items == NUM_ITEMS
<add>
<add> time.sleep(1) # Ensure we create the next cache in a new directory.
<add> ncf_dataset = data_preprocessing.construct_cache(
<add> dataset=DATASET, data_dir=self.temp_data_dir, num_data_readers=2,
<add> match_mlperf=True)
<ide> assert ncf_dataset.num_users == NUM_USERS
<ide> assert ncf_dataset.num_items == NUM_ITEMS
<ide>
<ide> def test_end_to_end(self):
<ide> # replacement. It only checks that negative generation is reasonably random.
<ide> assert len(train_examples[False]) / NUM_NEG / num_positives_seen > 0.9
<ide>
<add> def test_shard_randomness(self):
<add> users = [0, 0, 0, 0, 1, 1, 1, 1]
<add> items = [0, 2, 4, 6, 0, 2, 4, 6]
<add> times = [1, 2, 3, 4, 1, 2, 3, 4]
<add> df = pd.DataFrame({movielens.USER_COLUMN: users,
<add> movielens.ITEM_COLUMN: items,
<add> movielens.TIMESTAMP_COLUMN: times})
<add> cache_paths = rconst.Paths(data_dir=self.temp_data_dir)
<add> np.random.seed(1)
<add> data_preprocessing.generate_train_eval_data(df, approx_num_shards=2,
<add> num_items=10,
<add> cache_paths=cache_paths,
<add> match_mlperf=True)
<add> with tf.gfile.Open(cache_paths.eval_raw_file, "rb") as f:
<add> eval_data = pickle.load(f)
<add> eval_items_per_user = rconst.NUM_EVAL_NEGATIVES + 1
<add> self.assertAllClose(eval_data[0][movielens.USER_COLUMN],
<add> [0] * eval_items_per_user + [1] * eval_items_per_user)
<add>
<add> # Each shard process should generate different random items.
<add> self.assertNotAllClose(
<add> eval_data[0][movielens.ITEM_COLUMN][:eval_items_per_user],
<add> eval_data[0][movielens.ITEM_COLUMN][eval_items_per_user:])
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide><path>official/recommendation/ncf_main.py
<ide> _NDCG_KEY = "NDCG"
<ide>
<ide>
<add>def get_hit_rate_and_ndcg(predicted_scores_by_user, items_by_user, top_k=_TOP_K,
<add> match_mlperf=False):
<add> """Returns the hit rate and the normalized DCG for evaluation.
<add>
<add> `predicted_scores_by_user` and `items_by_user` are parallel NumPy arrays with
<add> shape (num_users, num_items) such that `predicted_scores_by_user[i, j]` is the
<add> predicted score that user `i` would rate item `items_by_user[i][j]`.
<add>
<add> `items_by_user[i, 0]` is the item that user `i` interacted with, while
<add> `items_by_user[i, 1:] are items that user `i` did not interact with. The goal
<add> of the NCF model to give a high score for `predicted_scores_by_user[i, 0]`
<add> compared to `predicted_scores_by_user[i, 1:]`, and the returned HR and NDCG
<add> will be higher the more successful the model is at this goal.
<add>
<add> If `match_mlperf` is True, then the HR and NDCG computations are done in a
<add> slightly unusual way to match the MLPerf reference implementation.
<add> Specifically, if `items_by_user[i, :]` contains duplicate items, it will be
<add> treated as if the item only appeared once. Effectively, for duplicate items in
<add> a row, the predicted score for all but one of the items will be set to
<add> -infinity
<add>
<add> For example, suppose we have that following inputs:
<add> predicted_scores_by_user: [[ 2, 3, 3],
<add> [ 5, 4, 4]]
<add>
<add> items_by_user: [[10, 20, 20],
<add> [30, 40, 40]]
<add>
<add> top_k: 2
<add>
<add> Then with match_mlperf=True, the HR would be 2/2 = 1.0. With
<add> match_mlperf=False, the HR would be 1/2 = 0.5. This is because each user has
<add> predicted scores for only 2 unique items: 10 and 20 for the first user, and 30
<add> and 40 for the second. Therefore, with match_mlperf=True, it's guarenteed the
<add> first item's score is in the top 2. With match_mlperf=False, this function
<add> would compute the first user's first item is not in the top 2, because item 20
<add> has a higher score, and item 20 occurs twice.
<add>
<add> Args:
<add> predicted_scores_by_user: 2D Numpy array of the predicted scores.
<add> `predicted_scores_by_user[i, j]` is the predicted score that user `i`
<add> would rate item `items_by_user[i][j]`.
<add> items_by_user: 2d numpy array of the item IDs. For user `i`,
<add> `items_by_user[i][0]` is the itme that user `i` interacted with, while
<add> `predicted_scores_by_user[i, 1:] are items that user `i` did not interact
<add> with.
<add> top_k: Only consider the highest rated `top_k` items per user. The HR and
<add> NDCG for that user will only be nonzero if the predicted score for that
<add> user's first item is in the `top_k` top scores.
<add> match_mlperf: If True, compute HR and NDCG slightly differently to match the
<add> MLPerf reference implementation.
<add>
<add> Returns:
<add> (hr, ndcg) tuple of floats, averaged across all users.
<add> """
<add> num_users = predicted_scores_by_user.shape[0]
<add> zero_indices = np.zeros((num_users, 1), dtype=np.int32)
<add>
<add> if match_mlperf:
<add> predicted_scores_by_user = predicted_scores_by_user.copy()
<add> items_by_user = items_by_user.copy()
<add>
<add> # For each user, sort the items and predictions by increasing item number.
<add> # We use mergesort since it's the only stable sort, which we need to be
<add> # equivalent to the MLPerf reference implementation.
<add> sorted_items_indices = items_by_user.argsort(kind="mergesort")
<add> sorted_items = items_by_user[
<add> np.arange(num_users)[:, np.newaxis], sorted_items_indices]
<add> sorted_predictions = predicted_scores_by_user[
<add> np.arange(num_users)[:, np.newaxis], sorted_items_indices]
<add>
<add> # For items that occur more than once in a user's row, set the predicted
<add> # score of the subsequent occurrences to -infinity, which effectively
<add> # removes them from the array.
<add> diffs = sorted_items[:, :-1] - sorted_items[:, 1:]
<add> diffs = np.concatenate(
<add> [np.ones((diffs.shape[0], 1), dtype=diffs.dtype), diffs], axis=1)
<add> predicted_scores_by_user = np.where(diffs, sorted_predictions, -np.inf)
<add>
<add> # After this block, `zero_indices` will be a (num_users, 1) shaped array
<add> # indicating, for each user, the index of item of value 0 in
<add> # `sorted_items_indices`. This item is the one we want to check if it is in
<add> # the top_k items.
<add> zero_indices = np.array(np.where(sorted_items_indices == 0))
<add> assert np.array_equal(zero_indices[0, :], np.arange(num_users))
<add> zero_indices = zero_indices[1, :, np.newaxis]
<add>
<add> # NumPy has an np.argparition() method, however log(1000) is so small that
<add> # sorting the whole array is simpler and fast enough.
<add> top_indicies = np.argsort(predicted_scores_by_user, axis=1)[:, -top_k:]
<add> top_indicies = np.flip(top_indicies, axis=1)
<add>
<add> # Both HR and NDCG vectorized computation takes advantage of the fact that if
<add> # the positive example for a user is not in the top k, that index does not
<add> # appear. That is to say: hit_ind.shape[0] <= num_users
<add> hit_ind = np.argwhere(np.equal(top_indicies, zero_indices))
<add> hr = hit_ind.shape[0] / num_users
<add> ndcg = np.sum(np.log(2) / np.log(hit_ind[:, 1] + 2)) / num_users
<add> return hr, ndcg
<add>
<add>
<ide> def evaluate_model(estimator, ncf_dataset, pred_input_fn):
<ide> # type: (tf.estimator.Estimator, prepare.NCFDataset, typing.Callable) -> dict
<ide> """Model evaluation with HR and NDCG metrics.
<ide> def evaluate_model(estimator, ncf_dataset, pred_input_fn):
<ide> # Get predictions
<ide> predictions = estimator.predict(input_fn=pred_input_fn,
<ide> yield_single_examples=False)
<add> predictions = list(predictions)
<ide>
<ide> prediction_batches = [p[movielens.RATING_COLUMN] for p in predictions]
<add> item_batches = [p[movielens.ITEM_COLUMN] for p in predictions]
<ide>
<del> # Reshape the predicted scores and each user takes one row
<add> # Reshape the predicted scores and items. Each user takes one row.
<ide> prediction_with_padding = np.concatenate(prediction_batches, axis=0)
<ide> predicted_scores_by_user = prediction_with_padding[
<ide> :ncf_dataset.num_users * (1 + rconst.NUM_EVAL_NEGATIVES)]\
<ide> .reshape(ncf_dataset.num_users, -1)
<add> item_with_padding = np.concatenate(item_batches, axis=0)
<add> items_by_user = item_with_padding[
<add> :ncf_dataset.num_users * (1 + rconst.NUM_EVAL_NEGATIVES)]\
<add> .reshape(ncf_dataset.num_users, -1)
<ide>
<ide> tf.logging.info("Computing metrics...")
<ide>
<del> # NumPy has an np.argparition() method, however log(1000) is so small that
<del> # sorting the whole array is simpler and fast enough.
<del> top_indicies = np.argsort(predicted_scores_by_user, axis=1)[:, -_TOP_K:]
<del> top_indicies = np.flip(top_indicies, axis=1)
<del>
<del> # Both HR and NDCG vectorized computation takes advantage of the fact that if
<del> # the positive example for a user is not in the top k, that index does not
<del> # appear. That is to say: hit_ind.shape[0] <= num_users
<del> hit_ind = np.argwhere(np.equal(top_indicies, 0))
<del> hr = hit_ind.shape[0] / ncf_dataset.num_users
<del> ndcg = np.sum(np.log(2) / np.log(hit_ind[:, 1] + 2)) / ncf_dataset.num_users
<add> hr, ndcg = get_hit_rate_and_ndcg(predicted_scores_by_user, items_by_user,
<add> match_mlperf=FLAGS.ml_perf)
<ide>
<ide> global_step = estimator.get_variable_value(tf.GraphKeys.GLOBAL_STEP)
<ide> eval_results = {
<ide> def run_ncf(_):
<ide> batch_size=batch_size,
<ide> eval_batch_size=eval_batch_size,
<ide> num_neg=FLAGS.num_neg,
<del> epochs_per_cycle=FLAGS.epochs_between_evals)
<add> epochs_per_cycle=FLAGS.epochs_between_evals,
<add> match_mlperf=FLAGS.ml_perf)
<ide>
<ide> model_helpers.apply_clean(flags.FLAGS)
<ide>
<ide> def define_ncf_flags():
<ide> "For dataset ml-20m, the threshold can be set as 0.95 which is "
<ide> "achieved by MLPerf implementation."))
<ide>
<add> flags.DEFINE_bool(
<add> name="ml_perf", default=None,
<add> help=flags_core.help_wrap(
<add> "If set, changes the behavior of the model slightly to match the "
<add> "MLPerf reference implementations here: \n"
<add> "https://github.com/mlperf/reference/tree/master/recommendation/"
<add> "pytorch\n"
<add> "The two changes are:\n"
<add> "1. When computing the HR and NDCG during evaluation, remove "
<add> "duplicate user-item pairs before the computation. This results in "
<add> "better HRs and NDCGs.\n"
<add> "2. Use a different soring algorithm when sorting the input data, "
<add> "which performs better due to the fact the sorting algorithms are "
<add> "not stable."))
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide><path>official/recommendation/ncf_test.py
<add># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Tests NCF."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import math
<add>
<add>import numpy as np
<add>import tensorflow as tf
<add>
<add>from official.recommendation import ncf_main
<add>
<add>
<add>class NcfTest(tf.test.TestCase):
<add> def test_hit_rate_and_ndcg(self):
<add> # Test with no duplicate items
<add> predictions = np.array([
<add> [1., 2., 0.], # In top 2
<add> [2., 1., 0.], # In top 1
<add> [0., 2., 1.], # In top 3
<add> [2., 3., 4.] # In top 3
<add> ])
<add> items = np.array([
<add> [1, 2, 3],
<add> [2, 3, 1],
<add> [3, 2, 1],
<add> [2, 1, 3],
<add> ])
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 1)
<add> self.assertAlmostEqual(hr, 1 / 4)
<add> self.assertAlmostEqual(ndcg, 1 / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 2)
<add> self.assertAlmostEqual(hr, 2 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 3)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3) +
<add> 2 * math.log(2) / math.log(4)) / 4)
<add>
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 1,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 1 / 4)
<add> self.assertAlmostEqual(ndcg, 1 / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 2,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 2 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 3,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3) +
<add> 2 * math.log(2) / math.log(4)) / 4)
<add>
<add> # Test with duplicate items. In the MLPerf case, we treat the duplicates as
<add> # a single item. Otherwise, we treat the duplicates as separate items.
<add> predictions = np.array([
<add> [1., 2., 2., 3.], # In top 4. MLPerf: In top 3
<add> [3., 1., 0., 2.], # In top 1. MLPerf: In top 1
<add> [0., 2., 3., 2.], # In top 4. MLPerf: In top 3
<add> [3., 2., 4., 2.] # In top 2. MLPerf: In top 2
<add> ])
<add> items = np.array([
<add> [1, 2, 2, 3],
<add> [1, 2, 3, 4],
<add> [1, 2, 3, 2],
<add> [4, 3, 2, 1],
<add> ])
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 1)
<add> self.assertAlmostEqual(hr, 1 / 4)
<add> self.assertAlmostEqual(ndcg, 1 / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 2)
<add> self.assertAlmostEqual(hr, 2 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 3)
<add> self.assertAlmostEqual(hr, 2 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 4)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3) +
<add> 2 * math.log(2) / math.log(5)) / 4)
<add>
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 1,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 1 / 4)
<add> self.assertAlmostEqual(ndcg, 1 / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 2,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 2 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 3,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3) +
<add> 2 * math.log(2) / math.log(4)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 4,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + math.log(2) / math.log(3) +
<add> 2 * math.log(2) / math.log(4)) / 4)
<add>
<add> # Test with duplicate items, where the predictions for the same item can
<add> # differ. In the MLPerf case, we should take the first prediction.
<add> predictions = np.array([
<add> [3., 2., 4., 4.], # In top 3. MLPerf: In top 2
<add> [3., 4., 2., 4.], # In top 3. MLPerf: In top 3
<add> [2., 3., 4., 1.], # In top 3. MLPerf: In top 2
<add> [4., 3., 5., 2.] # In top 2. MLPerf: In top 1
<add> ])
<add> items = np.array([
<add> [1, 2, 2, 3],
<add> [4, 3, 3, 2],
<add> [2, 1, 1, 1],
<add> [4, 2, 2, 1],
<add> ])
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 1)
<add> self.assertAlmostEqual(hr, 0 / 4)
<add> self.assertAlmostEqual(ndcg, 0 / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 2)
<add> self.assertAlmostEqual(hr, 1 / 4)
<add> self.assertAlmostEqual(ndcg, (math.log(2) / math.log(3)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 3)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (math.log(2) / math.log(3) +
<add> 3 * math.log(2) / math.log(4)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 4)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (math.log(2) / math.log(3) +
<add> 3 * math.log(2) / math.log(4)) / 4)
<add>
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 1,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 1 / 4)
<add> self.assertAlmostEqual(ndcg, 1 / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 2,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 3 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + 2 * math.log(2) / math.log(3)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 3,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + 2 * math.log(2) / math.log(3) +
<add> math.log(2) / math.log(4)) / 4)
<add> hr, ndcg = ncf_main.get_hit_rate_and_ndcg(predictions, items, 4,
<add> match_mlperf=True)
<add> self.assertAlmostEqual(hr, 4 / 4)
<add> self.assertAlmostEqual(ndcg, (1 + 2 * math.log(2) / math.log(3) +
<add> math.log(2) / math.log(4)) / 4)
<add>
<add>
<add>if __name__ == "__main__":
<add> tf.logging.set_verbosity(tf.logging.INFO)
<add> tf.test.main()
<ide><path>official/recommendation/neumf_model.py
<ide> def neumf_model_fn(features, labels, mode, params):
<ide>
<ide> if mode == tf.estimator.ModeKeys.PREDICT:
<ide> predictions = {
<add> movielens.ITEM_COLUMN: items,
<ide> movielens.RATING_COLUMN: logits,
<ide> }
<ide> | 6 |
Ruby | Ruby | use macos.locate to find svn | eb0be2ba4757f3da486e01af9885bbcbaf0e62b8 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def fetch_repo target, url, revision=nil, ignore_externals=false
<ide> def svn
<ide> return ENV['HOMEBREW_SVN'] if ENV['HOMEBREW_SVN']
<ide> return "#{HOMEBREW_PREFIX}/bin/svn" if File.exist? "#{HOMEBREW_PREFIX}/bin/svn"
<del> return '/usr/bin/svn'
<add> return MacOS.locate 'svn'
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | simplify paren wrap, continuation-detection | 9ef9a9dee54a464a46739b14e8a348bec673c5a5 | <ide><path>lib/repl.js
<ide> var rl = require('readline');
<ide> var Console = require('console').Console;
<ide> var EventEmitter = require('events').EventEmitter;
<ide> var domain = require('domain');
<add>var debug = util.debuglog('repl');
<ide>
<ide> // If obj.hasOwnProperty has been overridden, then calling
<ide> // obj.hasOwnProperty(prop) will break.
<ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
<ide> });
<ide> } catch (e) {
<ide> err = e;
<del> err._isSyntaxError = isSyntaxError(err);
<add> debug('parse error %j', code, e);
<ide> }
<add>
<ide> if (!err) {
<ide> try {
<ide> if (self.useGlobal) {
<ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
<ide> }
<ide> } catch (e) {
<ide> err = e;
<del> err._isSyntaxError = false;
<add> if (err && process.domain) {
<add> debug('not recoverable, send to domain');
<add> process.domain.emit('error', err);
<add> process.domain.exit();
<add> return;
<add> }
<ide> }
<ide> }
<del> if (err && process.domain && !err._isSyntaxError) {
<del> process.domain.emit('error', err);
<del> process.domain.exit();
<del> }
<del> else {
<del> cb(err, result);
<del> }
<add>
<add> cb(err, result);
<ide> }
<ide>
<ide> self.eval = self._domain.bind(eval_);
<ide>
<ide> self._domain.on('error', function(e) {
<add> debug('domain error');
<ide> self.outputStream.write((e.stack || e) + '\n');
<ide> self.bufferedCommand = '';
<ide> self.lines.level = [];
<ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
<ide> });
<ide>
<ide> rli.on('line', function(cmd) {
<add> debug('line %j', cmd);
<ide> sawSIGINT = false;
<ide> var skipCatchall = false;
<ide> cmd = trimWhitespace(cmd);
<ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
<ide> }
<ide>
<ide> if (!skipCatchall) {
<del> var evalCmd = self.bufferedCommand + cmd + '\n';
<del>
<del> // This try is for determining if the command is complete, or should
<del> // continue onto the next line.
<del> // We try to evaluate both expressions e.g.
<del> // '{ a : 1 }'
<del> // and statements e.g.
<del> // 'for (var i = 0; i < 10; i++) console.log(i);'
<del>
<del> // First we attempt to eval as expression with parens.
<del> // This catches '{a : 1}' properly.
<del> self.eval('(' + evalCmd + ')',
<del> self.context,
<del> 'repl',
<del> function(e, ret) {
<del> if (e && !e._isSyntaxError) return finish(e);
<del>
<del> if (util.isFunction(ret) &&
<del> /^[\r\n\s]*function/.test(evalCmd) || e) {
<del> // Now as statement without parens.
<del> self.eval(evalCmd, self.context, 'repl', finish);
<del> } else {
<del> finish(null, ret);
<del> }
<del> });
<add> var evalCmd = self.bufferedCommand + cmd;
<add> if (/^\s*\{/.test(evalCmd) && /\}\s*$/.test(evalCmd)) {
<add> // It's confusing for `{ a : 1 }` to be interpreted as a block
<add> // statement rather than an object literal. So, we first try
<add> // to wrap it in parentheses, so that it will be interpreted as
<add> // an expression.
<add> evalCmd = '(' + evalCmd + ')\n';
<add> } else {
<add> // otherwise we just append a \n so that it will be either
<add> // terminated, or continued onto the next expression if it's an
<add> // unexpected end of input.
<add> evalCmd = evalCmd + '\n';
<add> }
<ide>
<add> debug('eval %j', evalCmd);
<add> self.eval(evalCmd, self.context, 'repl', finish);
<ide> } else {
<ide> finish(null);
<ide> }
<ide>
<ide> function finish(e, ret) {
<del>
<add> debug('finish', e, ret);
<ide> self.memory(cmd);
<ide>
<add> if (e && !self.bufferedCommand && cmd.trim().match(/^npm /)) {
<add> self.outputStream.write('npm should be run outside of the ' +
<add> 'node repl, in your normal shell.\n' +
<add> '(Press Control-D to exit.)\n');
<add> self.bufferedCommand = '';
<add> self.displayPrompt();
<add> return;
<add> }
<add>
<ide> // If error was SyntaxError and not JSON.parse error
<del> if (e && e._isSyntaxError) {
<del> if (!self.bufferedCommand && cmd.trim().match(/^npm /)) {
<del> self.outputStream.write('npm should be run outside of the ' +
<del> 'node repl, in your normal shell.\n' +
<del> '(Press Control-D to exit.)\n');
<del> self.bufferedCommand = '';
<add> if (e) {
<add> if (isRecoverableError(e)) {
<add> // Start buffering data like that:
<add> // {
<add> // ... x: 1
<add> // ... }
<add> self.bufferedCommand += cmd + '\n';
<ide> self.displayPrompt();
<ide> return;
<add> } else {
<add> self._domain.emit('error', e);
<ide> }
<del>
<del> // Start buffering data like that:
<del> // {
<del> // ... x: 1
<del> // ... }
<del> self.bufferedCommand += cmd + '\n';
<del> self.displayPrompt();
<del> return;
<del> } else if (e) {
<del> self._domain.emit('error', e);
<ide> }
<ide>
<ide> // Clear buffer if no SyntaxErrors
<ide> REPLServer.prototype.convertToContext = function(cmd) {
<ide> };
<ide>
<ide>
<del>/**
<del> * Returns `true` if "e" is a SyntaxError, `false` otherwise.
<del> * filters out strict-mode errors, which are not recoverable
<del> */
<del>function isSyntaxError(e) {
<del> // Convert error to string
<del> e = e && (e.stack || e.toString());
<del> return e && e.match(/^SyntaxError/) &&
<del> // "strict mode" syntax errors
<del> !e.match(/^SyntaxError: .*strict mode.*/i) &&
<del> !e.match(/^SyntaxError: Assignment to constant variable/i);
<add>// If the error is that we've unexpectedly ended the input,
<add>// then let the user try to recover by adding more input.
<add>function isRecoverableError(e) {
<add> return e &&
<add> e.name === 'SyntaxError' &&
<add> /^Unexpected end of input/.test(e.message);
<ide> } | 1 |
Text | Text | update some links to and text for react router | 088dd515a7922d57a6a76d075d5645b2c42f2ecf | <ide><path>docs/introduction/Ecosystem.md
<ide> Makes integration and unit testing of sagas a breeze
<ide> ## Routing
<ide>
<ide> **[supasate/connected-react-router](https://github.com/supasate/connected-react-router)**
<del>Synchronize React Router 4 state with your Redux store.
<add>Synchronize React Router v4+ state with your Redux store.
<ide>
<ide> **[faceyspacey/redux-first-router](https://github.com/faceyspacey/redux-first-router)** <br />
<ide> Seamless Redux-first routing. Think of your app in states, not routes, not components, while keeping the address bar in sync. Everything is state. Connect your components and just dispatch flux standard actions.
<ide><path>docs/tutorials/essentials/part-4-using-data.md
<ide> import { DetailedExplanation } from '../../components/DetailedExplanation'
<ide> :::info Prerequisites
<ide>
<ide> - Understanding the [Redux data flow and React-Redux APIs from Part 3](./part-3-data-flow.md)
<del>- Familiarity with [the React Router `<Link>` and `<Route>` components for page routing](https://reacttraining.com/react-router/web/api)
<add>- Familiarity with [the React Router `<Link>` and `<Route>` components for page routing](https://reactrouter.com/docs/en/v6/getting-started/overview)
<ide>
<ide> :::
<ide>
<ide><path>docs/usage/ServerRendering.md
<ide> Because the client side executes ongoing code, it can start with an empty initia
<ide>
<ide> The only input for server side code is the request made when loading up a page in your app in your browser. You may choose to configure the server during its boot (such as when you are running in a development vs. production environment), but that configuration is static.
<ide>
<del>The request contains information about the URL requested, including any query parameters, which will be useful when using something like [React Router](https://github.com/ReactTraining/react-router). It can also contain headers with inputs like cookies or authorization, or POST body data. Let's see how we can set the initial counter state based on a query parameter.
<add>The request contains information about the URL requested, including any query parameters, which will be useful when using something like [React Router](https://github.com/remix-run/react-router). It can also contain headers with inputs like cookies or authorization, or POST body data. Let's see how we can set the initial counter state based on a query parameter.
<ide>
<ide> #### `server.js`
<ide>
<ide> Furthermore, you can add additional layers of security by sanitizing your state
<ide>
<ide> You may want to read [Redux Fundamentals Part 6: Async Logic and Data Fetching](../tutorials/fundamentals/part-6-async-logic.md) to learn more about expressing asynchronous flow in Redux with async primitives such as Promises and thunks. Keep in mind that anything you learn there can also be applied to universal rendering.
<ide>
<del>If you use something like [React Router](https://github.com/ReactTraining/react-router), you might also want to express your data fetching dependencies as static `fetchData()` methods on your route handler components. They may return [thunks](../tutorials/fundamentals/part-6-async-logic.md), so that your `handleRender` function can match the route to the route handler component classes, dispatch `fetchData()` result for each of them, and render only after the Promises have resolved. This way the specific API calls required for different routes are colocated with the route handler component definitions. You can also use the same technique on the client side to prevent the router from switching the page until its data has been loaded.
<add>If you use something like [React Router](https://github.com/remix-run/react-router), you might also want to express your data fetching dependencies as static `fetchData()` methods on your route handler components. They may return [thunks](../tutorials/fundamentals/part-6-async-logic.md), so that your `handleRender` function can match the route to the route handler component classes, dispatch `fetchData()` result for each of them, and render only after the Promises have resolved. This way the specific API calls required for different routes are colocated with the route handler component definitions. You can also use the same technique on the client side to prevent the router from switching the page until its data has been loaded. | 3 |
Javascript | Javascript | fix the last imports of `'invariant'` | eb531943aab37ec59c9e160f8b602313b4aa954f | <ide><path>Libraries/NavigationExperimental/NavigationAbstractPanResponder.js
<ide>
<ide> const PanResponder = require('PanResponder');
<ide>
<del>const invariant = require('invariant');
<add>const invariant = require('fbjs/lib/invariant');
<ide>
<ide> const EmptyPanHandlers = {
<ide> onMoveShouldSetPanResponder: null,
<ide><path>Libraries/NavigationExperimental/NavigationStateUtils.js
<ide> */
<ide> 'use strict';
<ide>
<del>const invariant = require('invariant');
<add>const invariant = require('fbjs/lib/invariant');
<ide>
<ide> export type NavigationState = {
<ide> key: string; | 2 |
Javascript | Javascript | add datetime to the profiling export filename | 962865e5bf8974d1651305ed406bfd146bc76f3e | <ide><path>src/devtools/views/Profiler/ProfilingImportExportButtons.js
<ide> export default function ProfilingImportExportButtons() {
<ide>
<ide> if (profilingData !== null) {
<ide> const profilingDataExport = prepareProfilingDataExport(profilingData);
<add> const date = new Date();
<add> const dateString = date
<add> .toLocaleDateString(undefined, {
<add> year: 'numeric',
<add> month: '2-digit',
<add> day: '2-digit',
<add> })
<add> .replace(/\//g, '-');
<add> const timeString = date
<add> .toLocaleTimeString(undefined, {
<add> hour12: false,
<add> })
<add> .replace(/:/g, '-');
<ide> downloadFile(
<del> 'profile-data.json',
<add> `profiling-data.${dateString}.${timeString}.json`,
<ide> JSON.stringify(profilingDataExport, null, 2)
<ide> );
<ide> } | 1 |
Ruby | Ruby | build fix for app_generator_test.rb | 62e0337db11ad224997f7460e8f00fa7bc0f18ae | <ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_inclusion_of_javascript_runtime
<ide> if defined?(JRUBY_VERSION)
<ide> assert_file "Gemfile", /gem\s+["']therubyrhino["']$/
<ide> else
<del> assert_file "Gemfile", /# gem\s+["']therubyracer["']$/
<add> assert_file "Gemfile", /# gem\s+["']therubyracer["']+, :platform => :ruby$/
<ide> end
<ide> end
<ide> | 1 |
Text | Text | remove reference to a deprecated package | 86636a8bab4682ca514c7111edd6fa48326492b3 | <ide><path>docs/faq/OrganizingState.md
<ide> Some common rules of thumb for determining what kind of data should be put into
<ide> - Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
<ide> - Do you want to keep this data consistent while hot-reloading UI components (which may lose their internal state when swapped)?
<ide>
<del>There are a number of community packages that implement various approaches for storing per-component state in a Redux store instead, such as [redux-ui](https://github.com/tonyhb/redux-ui), [redux-component](https://github.com/tomchentw/redux-component), [redux-react-local](https://github.com/threepointone/redux-react-local), and more. It's also possible to apply Redux's principles and concept of reducers to the task of updating local component state as well, along the lines of `this.setState( (previousState) => reducer(previousState, someAction))`.
<add>There are a number of community packages that implement various approaches for storing per-component state in a Redux store instead, such as [redux-component](https://github.com/tomchentw/redux-component), [redux-react-local](https://github.com/threepointone/redux-react-local), and more. It's also possible to apply Redux's principles and concept of reducers to the task of updating local component state as well, along the lines of `this.setState( (previousState) => reducer(previousState, someAction))`.
<ide>
<ide> #### Further information
<ide> | 1 |
Text | Text | fix typo in assert code example | 929fd4a892bb3e380ee58153ca04f070c38d9f27 | <ide><path>doc/api/assert.md
<ide> assert.notStrictEqual(1, 2);
<ide> // OK
<ide>
<ide> assert.notStrictEqual(1, 1);
<del>// AssertionError: 1 != 1
<add>// AssertionError: 1 !== 1
<ide>
<ide> assert.notStrictEqual(1, '1');
<ide> // OK | 1 |
Text | Text | improve testing section | 88cb9af59487171d1e2728800dcd45f66057517e | <ide><path>DEVELOPERS.md
<ide> # Developing AngularJS
<ide>
<ide> * [Development Setup](#setup)
<add>* [Running Tests](#tests)
<ide> * [Coding Rules](#rules)
<ide> * [Commit Message Guidelines](#commits)
<ide> * [Writing Documentation](#documentation)
<ide> HTTP server. For this purpose, we have made available a local web server based o
<ide> http://localhost:8000/build/docs/
<ide> ```
<ide>
<add>## <a name="tests"> Running Tests
<add>
<ide> ### <a name="unit-tests"></a> Running the Unit Test Suite
<ide>
<ide> We write unit and integration tests with Jasmine and execute them with Karma. To run all of the
<ide> tests once on Chrome run:
<ide> yarn grunt test:unit
<ide> ```
<ide>
<del>To run the tests on other browsers (Chrome, ChromeCanary, Firefox and Safari are pre-configured) use:
<add>To run the tests on other browsers (Chrome and Firefox are pre-configured) use:
<ide>
<ide> ```shell
<ide> yarn grunt test:unit --browsers=Chrome,Firefox
<ide> ```
<ide>
<ide> **Note:** there should be _no spaces between browsers_. `Chrome, Firefox` is INVALID.
<ide>
<add>If you want to test locally on Safari, Internet Explorer, or Edge, you must install
<add>the respective `karma-<browser>-launcher` from npm.
<add>
<ide> If you have a Saucelabs or Browserstack account, you can also run the unit tests on these services
<del>via our pre-defined customLaunchers.
<add>via our pre-defined customLaunchers. See the [karma config file](/karma-shared.conf.js) for all pre-configured browsers.
<ide>
<del>For example, to run the whole unit test suite:
<add>For example, to run the whole unit test suite on selected browsers:
<ide>
<ide> ```shell
<ide> # Browserstack
<del>yarn grunt test:unit --browsers=BS_Chrome,BS_Firefox,BS_Safari,BS_IE_9,BS_IE_10,BS_IE_11,BS_EDGE,BS_iOS_8,BS_iOS_9,BS_iOS_10
<add>yarn grunt test:unit --browsers=BS_Chrome,BS_Firefox,BS_Safari,BS_IE_9,BS_IE_10,BS_IE_11,BS_EDGE,BS_iOS_10
<ide> # Saucelabs
<del>yarn grunt test:unit --browsers=BS_Chrome,BS_Firefox,BS_Safari,BS_IE_9,BS_IE_10,BS_IE_11,BS_EDGE,BS_iOS_8,BS_iOS_9,BS_iOS_10
<add>yarn grunt test:unit --browsers=SL_Chrome,SL_Firefox,SL_Safari,SL_IE_9,SL_IE_10,SL_IE_11,SL_EDGE,SL_iOS_10
<ide> ```
<ide>
<ide> Running these commands requires you to set up [Karma Browserstack][karma-browserstack] or
<ide> You can see an example of a well-defined example [in the `ngRepeat` documentatio
<ide> [karma-browserstack]: https://github.com/karma-runner/karma-browserstack-launcher
<ide> [karma-saucelabs]: https://github.com/karma-runner/karma-sauce-launcher
<ide> [unit-testing]: https://docs.angularjs.org/guide/unit-testing
<del>[yarn-install]: https://yarnpkg.com/en/docs/install
<ide>\ No newline at end of file
<add>[yarn-install]: https://yarnpkg.com/en/docs/install | 1 |
Javascript | Javascript | flowify some libraries | e4bf45beee71db3f42be343779ff77ef9fe9e026 | <ide><path>Libraries/ActionSheetIOS/ActionSheetIOS.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ActionSheetIOS
<add> * @flow
<ide> */
<ide> 'use strict';
<ide>
<ide> var RCTActionSheetManager = require('NativeModules').ActionSheetManager;
<ide> var invariant = require('invariant');
<ide>
<ide> var ActionSheetIOS = {
<del> showActionSheetWithOptions(options, callback) {
<add> showActionSheetWithOptions(options: Object, callback: Function) {
<ide> invariant(
<ide> typeof options === 'object' && options !== null,
<ide> 'Options must a valid object'
<ide> var ActionSheetIOS = {
<ide> );
<ide> },
<ide>
<del> showShareActionSheetWithOptions(options, failureCallback, successCallback) {
<add> showShareActionSheetWithOptions(
<add> options: Object,
<add> failureCallback: Function,
<add> successCallback: Function
<add> ) {
<ide> invariant(
<ide> typeof options === 'object' && options !== null,
<ide> 'Options must a valid object'
<ide><path>Libraries/AdSupport/AdSupportIOS.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule AdSupportIOS
<add> * @flow
<ide> */
<ide> 'use strict';
<ide>
<ide> var AdSupport = require('NativeModules').AdSupport;
<ide>
<ide> module.exports = {
<del> getAdvertisingId: function(onSuccess, onFailure) {
<add> getAdvertisingId: function(onSuccess: Function, onFailure: Function) {
<ide> AdSupport.getAdvertisingId(onSuccess, onFailure);
<ide> },
<ide>
<del> getAdvertisingTrackingEnabled: function(onSuccess, onFailure) {
<add> getAdvertisingTrackingEnabled: function(onSuccess: Function, onFailure: Function) {
<ide> AdSupport.getAdvertisingTrackingEnabled(onSuccess, onFailure);
<ide> },
<ide> };
<ide><path>Libraries/Animation/LayoutAnimation.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule LayoutAnimation
<add> * @flow
<ide> */
<ide> 'use strict';
<ide>
<ide> var animChecker = createStrictShapeTypeChecker({
<ide> ),
<ide> });
<ide>
<add>type Anim = {
<add> duration?: number;
<add> delay?: number;
<add> springDamping?: number;
<add> initialVelocity?: number;
<add> type?: $Enum<typeof Types>;
<add> property?: $Enum<typeof Properties>;
<add>}
<add>
<ide> var configChecker = createStrictShapeTypeChecker({
<ide> duration: PropTypes.number.isRequired,
<ide> create: animChecker,
<ide> update: animChecker,
<ide> delete: animChecker,
<ide> });
<ide>
<add>type Config = {
<add> duration: number;
<add> create?: Anim;
<add> update?: Anim;
<add> delete?: Anim;
<add>}
<add>
<add>function configureNext(config: Config, onAnimationDidEnd?: Function, onError?: Function) {
<add> configChecker({config}, 'config', 'LayoutAnimation.configureNext');
<add> RCTUIManager.configureNextLayoutAnimation(config, onAnimationDidEnd, onError);
<add>}
<add>
<add>function create(duration: number, type, creationProp): Config {
<add> return {
<add> duration,
<add> create: {
<add> type,
<add> property: creationProp,
<add> },
<add> update: {
<add> type,
<add> },
<add> };
<add>}
<add>
<ide> var LayoutAnimation = {
<del> configureNext(config, onAnimationDidEnd, onError) {
<del> configChecker({config}, 'config', 'LayoutAnimation.configureNext');
<del> RCTUIManager.configureNextLayoutAnimation(config, onAnimationDidEnd, onError);
<del> },
<del> create(duration, type, creationProp) {
<del> return {
<del> duration,
<add> configureNext,
<add> create,
<add> Types,
<add> Properties,
<add> configChecker: configChecker,
<add> Presets: {
<add> easeInEaseOut: create(
<add> 0.3, Types.easeInEaseOut, Properties.opacity
<add> ),
<add> linear: create(
<add> 0.5, Types.linear, Properties.opacity
<add> ),
<add> spring: {
<add> duration: 0.7,
<ide> create: {
<del> type,
<del> property: creationProp,
<add> type: Types.linear,
<add> property: Properties.opacity,
<ide> },
<ide> update: {
<del> type,
<add> type: Types.spring,
<add> springDamping: 0.4,
<ide> },
<del> };
<del> },
<del> Types: Types,
<del> Properties: Properties,
<del> configChecker: configChecker,
<del>};
<del>
<del>LayoutAnimation.Presets = {
<del> easeInEaseOut: LayoutAnimation.create(
<del> 0.3, Types.easeInEaseOut, Properties.opacity
<del> ),
<del> linear: LayoutAnimation.create(
<del> 0.5, Types.linear, Properties.opacity
<del> ),
<del> spring: {
<del> duration: 0.7,
<del> create: {
<del> type: Types.linear,
<del> property: Properties.opacity,
<del> },
<del> update: {
<del> type: Types.spring,
<del> springDamping: 0.4,
<ide> },
<del> },
<add> }
<ide> };
<ide>
<ide> module.exports = LayoutAnimation;
<ide><path>Libraries/AppRegistry/AppRegistry.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule AppRegistry
<add> * @flow
<ide> */
<ide> 'use strict';
<ide>
<ide> if (__DEV__) {
<ide>
<ide> var runnables = {};
<ide>
<add>type AppConfig = {
<add> appKey: string;
<add> component: ReactClass<any, any, any>;
<add> run?: Function;
<add>};
<add>
<ide> /**
<ide> * `AppRegistry` is the JS entry point to running all React Native apps. App
<ide> * root components should register themselves with
<ide> var runnables = {};
<ide> * `require`d.
<ide> */
<ide> var AppRegistry = {
<del> registerConfig: function(config) {
<add> registerConfig: function(config: Array<AppConfig>) {
<ide> for (var i = 0; i < config.length; ++i) {
<del> if (config[i].run) {
<del> AppRegistry.registerRunnable(config[i].appKey, config[i].run);
<add> var appConfig = config[i];
<add> if (appConfig.run) {
<add> AppRegistry.registerRunnable(appConfig.appKey, appConfig.run);
<ide> } else {
<del> AppRegistry.registerComponent(config[i].appKey, config[i].component);
<add> AppRegistry.registerComponent(appConfig.appKey, appConfig.component);
<ide> }
<ide> }
<ide> },
<ide>
<del> registerComponent: function(appKey, getComponentFunc) {
<add> registerComponent: function(appKey: string, getComponentFunc: Function): string {
<ide> runnables[appKey] = {
<ide> run: (appParameters) =>
<ide> renderApplication(getComponentFunc(), appParameters.initialProps, appParameters.rootTag)
<ide> };
<ide> return appKey;
<ide> },
<ide>
<del> registerRunnable: function(appKey, func) {
<add> registerRunnable: function(appKey: string, func: Function): string {
<ide> runnables[appKey] = {run: func};
<ide> return appKey;
<ide> },
<ide>
<del> runApplication: function(appKey, appParameters) {
<add> runApplication: function(appKey: string, appParameters: any): void {
<ide> console.log(
<ide> 'Running application "' + appKey + '" with appParams: ' +
<ide> JSON.stringify(appParameters) + '. ' +
<ide><path>Libraries/AppStateIOS/AppStateIOS.android.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule AppStateIOS
<add> * @flow
<ide> */
<ide> 'use strict';
<ide>
<ide><path>Libraries/AppStateIOS/AppStateIOS.ios.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule AppStateIOS
<add> * @flow
<ide> */
<ide> 'use strict';
<ide> | 6 |
Python | Python | remove duplicated entry | 78d1b473828d096591968ac9b97f0917b081a958 | <ide><path>contrib/scrape-ec2-sizes.py
<ide> "country": "Hong Kong",
<ide> "signature_version": "2",
<ide> },
<del> "Asia Pacific (Hong Kong)": {
<del> "id": "ap-east-1",
<del> "endpoint": "ec2.ap-east-1.amazonaws.com",
<del> "api_name": "ec2_ap_east",
<del> "country": "Hong Kong",
<del> "signature_version": "2",
<del> },
<ide> # Not in JSON
<ide> "China (Beijing)": {
<ide> "id": "cn-north-1", | 1 |
Text | Text | fix tiny grammar | f2fcd3a000f70cc520b9267e82184ab87fea7f80 | <ide><path>actioncable/README.md
<ide> can be reached as remote procedure calls via a subscription's `perform` method.
<ide>
<ide> The appearance example was all about exposing server functionality to client-side invocation over the WebSocket connection.
<ide> But the great thing about WebSockets is that it's a two-way street. So now let's show an example where the server invokes
<del>action on the client.
<add>an action on the client.
<ide>
<ide> This is a web notification channel that allows you to trigger client-side web notifications when you broadcast to the right
<ide> streams: | 1 |
PHP | PHP | apply fixes from styleci | c161b14ee0bfd0dd7a247c5709b39c5cdfe9de6c | <ide><path>database/factories/UserFactory.php
<ide> |
<ide> */
<ide>
<del>/** @var \Illuminate\Database\Eloquent\Factory $factory */
<add>/* @var \Illuminate\Database\Eloquent\Factory $factory */
<ide> $factory->define(User::class, function (Faker $faker) {
<ide> static $password;
<ide> | 1 |
Java | Java | remove soloadershim, use soloader | fc6dd78935a41106aa6a44058c1abb7d0ba0fa24 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/fresco/FrescoModule.java
<ide> import android.support.annotation.Nullable;
<ide>
<ide> import com.facebook.common.logging.FLog;
<del>import com.facebook.common.soloader.SoLoaderShim;
<ide> import com.facebook.drawee.backends.pipeline.Fresco;
<ide> import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory;
<ide> import com.facebook.imagepipeline.core.ImagePipelineConfig;
<ide> public void initialize() {
<ide> super.initialize();
<ide> getReactApplicationContext().addLifecycleEventListener(this);
<ide> if (!hasBeenInitialized()) {
<del> // Make sure the SoLoaderShim is configured to use our loader for native libraries.
<del> // This code can be removed if using Fresco from Maven rather than from source
<del> SoLoaderShim.setHandler(new FrescoHandler());
<ide> if (mConfig == null) {
<ide> mConfig = getDefaultConfig(getReactApplicationContext());
<ide> }
<ide> public void onHostDestroy() {
<ide> Fresco.getImagePipeline().clearMemoryCaches();
<ide> }
<ide> }
<del>
<del> private static class FrescoHandler implements SoLoaderShim.Handler {
<del> @Override
<del> public void loadLibrary(String libraryName) {
<del> SoLoader.loadLibrary(libraryName);
<del> }
<del> }
<ide> } | 1 |
Javascript | Javascript | fix global detection in tests | 0e5f12b4b2ba489f0bb8e1b632e2bc068369c89b | <ide><path>locale/af.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('af', {
<ide><path>locale/ar-ma.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('ar-ma', {
<ide><path>locale/ar-sa.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/ar.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/az.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var suffixes = {
<ide><path>locale/be.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function plural(word, num) {
<ide><path>locale/bg.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('bg', {
<ide><path>locale/bn.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/bo.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/br.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function relativeTimeWithMutation(number, withoutSuffix, key) {
<ide><path>locale/bs.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function translate(number, withoutSuffix, key) {
<ide><path>locale/ca.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('ca', {
<ide><path>locale/cs.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var months = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'),
<ide><path>locale/cv.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('cv', {
<ide><path>locale/cy.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('cy', {
<ide><path>locale/da.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('da', {
<ide><path>locale/de-at.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function processRelativeTime(number, withoutSuffix, key, isFuture) {
<ide><path>locale/de.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function processRelativeTime(number, withoutSuffix, key, isFuture) {
<ide><path>locale/el.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('el', {
<ide><path>locale/en-au.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('en-au', {
<ide><path>locale/en-ca.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('en-ca', {
<ide><path>locale/en-gb.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('en-gb', {
<ide><path>locale/eo.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('eo', {
<ide><path>locale/es.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),
<ide><path>locale/et.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function processRelativeTime(number, withoutSuffix, key, isFuture) {
<ide><path>locale/eu.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('eu', {
<ide><path>locale/fa.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/fi.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '),
<ide><path>locale/fo.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('fo', {
<ide><path>locale/fr-ca.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('fr-ca', {
<ide><path>locale/fr.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('fr', {
<ide><path>locale/gl.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('gl', {
<ide><path>locale/he.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('he', {
<ide><path>locale/hi.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/hr.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function translate(number, withoutSuffix, key) {
<ide><path>locale/hu.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' ');
<ide><path>locale/hy-am.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function monthsCaseReplace(m, format) {
<ide><path>locale/id.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('id', {
<ide><path>locale/is.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function plural(n) {
<ide><path>locale/it.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('it', {
<ide><path>locale/ja.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('ja', {
<ide><path>locale/ka.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function monthsCaseReplace(m, format) {
<ide><path>locale/km.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('km', {
<ide><path>locale/ko.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('ko', {
<ide><path>locale/lb.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function processRelativeTime(number, withoutSuffix, key, isFuture) {
<ide><path>locale/lt.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var units = {
<ide><path>locale/lv.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var units = {
<ide><path>locale/mk.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('mk', {
<ide><path>locale/ml.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('ml', {
<ide><path>locale/mr.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/ms-my.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('ms-my', {
<ide><path>locale/my.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/nb.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('nb', {
<ide><path>locale/ne.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var symbolMap = {
<ide><path>locale/nl.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),
<ide><path>locale/nn.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('nn', {
<ide><path>locale/pl.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'),
<ide><path>locale/pt-br.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('pt-br', {
<ide><path>locale/pt.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('pt', {
<ide><path>locale/ro.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function relativeTimeWithPlural(number, withoutSuffix, key) {
<ide><path>locale/ru.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function plural(word, num) {
<ide><path>locale/sk.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var months = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'),
<ide><path>locale/sl.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function translate(number, withoutSuffix, key) {
<ide><path>locale/sq.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('sq', {
<ide><path>locale/sr-cyrl.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var translator = {
<ide><path>locale/sr.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var translator = {
<ide><path>locale/sv.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('sv', {
<ide><path>locale/ta.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> /*var symbolMap = {
<ide><path>locale/th.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('th', {
<ide><path>locale/tl-ph.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('tl-ph', {
<ide><path>locale/tr.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> var suffixes = {
<ide><path>locale/tzm-latn.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('tzm-latn', {
<ide><path>locale/tzm.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('tzm', {
<ide><path>locale/uk.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> function plural(word, num) {
<ide><path>locale/uz.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('uz', {
<ide><path>locale/vi.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('vi', {
<ide><path>locale/zh-cn.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('zh-cn', {
<ide><path>locale/zh-tw.js
<ide> } else if (typeof exports === 'object') {
<ide> module.exports = factory(require('../moment')); // Node
<ide> } else {
<del> factory((typeof global !== undefined ? global : this).moment); // node or other global
<add> factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
<ide> }
<ide> }(function (moment) {
<ide> return moment.defineLocale('zh-tw', { | 78 |
Ruby | Ruby | add pour_bottle? method to formula | 599b012702127b821826d3e9f5c5f5521b82fd16 | <ide><path>Library/Homebrew/bottles.rb
<ide> def install_bottle? f
<ide> and f.downloader.local_bottle_path
<ide> not ARGV.build_from_source? \
<ide> and MacOS.bottles_supported? \
<add> and f.pour_bottle? \
<ide> and f.build.used_options.empty? \
<ide> and bottle_current?(f)
<ide> end
<ide><path>Library/Homebrew/formula.rb
<ide> def cached_download
<ide> @downloader.cached_location
<ide> end
<ide>
<add> # Can be overridden to selectively disable bottles from formulae.
<add> # Defaults to true so overridden version does not have to check if bottles
<add> # are supported.
<add> def pour_bottle?
<add> true
<add> end
<add>
<ide> # tell the user about any caveats regarding this package, return a string
<ide> def caveats; nil end
<ide> | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.