content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Python
Python
fix improper usage of warning filters in the tests
a2bb1cc9b6fc37583494d9a3e14b0ace59d210a5
<ide><path>numpy/core/tests/test_maskna.py <ide> from numpy.compat import asbytes <ide> from numpy.testing import * <ide> import sys, warnings <del> <add>from numpy.testing.utils import WarningManager <ide> <ide> def test_array_maskna_flags(): <ide> a = np.arange(3) <ide> def test_array_maskna_astype(): <ide> dtdst.append(np.dtype('datetime64[D]')) <ide> dtdst.append(np.dtype('timedelta64[s]')) <ide> <add> warn_ctx = WarningManager() <add> warn_ctx.__enter__() <ide> try: <ide> warnings.simplefilter("ignore", np.ComplexWarning) <ide> for dt1 in dtsrc: <ide> def test_array_maskna_astype(): <ide> assert_(b.flags.ownmaskna, msg) <ide> assert_(np.isna(b[1]), msg) <ide> finally: <del> warnings.simplefilter("default", np.ComplexWarning) <add> warn_ctx.__exit__() <ide> <ide> <ide> def test_array_maskna_repr(): <ide><path>numpy/core/tests/test_memmap.py <ide> from tempfile import NamedTemporaryFile, mktemp <ide> import os <del>import warnings <ide> <ide> from numpy import memmap <ide> from numpy import arange, allclose <ide><path>numpy/core/tests/test_multiarray.py <ide> from numpy.core import * <ide> from numpy.core.multiarray_tests import test_neighborhood_iterator, test_neighborhood_iterator_oob <ide> <add>import warnings <add>from numpy.testing.utils import WarningManager <add> <ide> # Need to test an object that does not fully implement math interface <ide> from datetime import timedelta <ide> <ide> def test_simple_strict_within(self): <ide> <ide> class TestWarnings(object): <ide> def test_complex_warning(self): <del> import warnings <del> <ide> x = np.array([1,2]) <ide> y = np.array([1-2j,1+2j]) <ide> <del> warnings.simplefilter("error", np.ComplexWarning) <del> assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y) <del> assert_equal(x, [1,2]) <del> warnings.simplefilter("default", np.ComplexWarning) <add> warn_ctx = WarningManager() <add> warn_ctx.__enter__() <add> try: <add> warnings.simplefilter("error", np.ComplexWarning) <add> assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y) <add> assert_equal(x, [1,2]) <add> finally: <add> warn_ctx.__exit__() <ide> <ide> if sys.version_info >= (2, 6): <ide> <ide><path>numpy/core/tests/test_regression.py <ide> def test_complex_scalar_warning(self): <ide> for tp in [np.csingle, np.cdouble, np.clongdouble]: <ide> x = tp(1+2j) <ide> assert_warns(np.ComplexWarning, float, x) <del> ctx = WarningManager() <del> ctx.__enter__() <del> warnings.simplefilter('ignore') <del> assert_equal(float(x), float(x.real)) <del> ctx.__exit__() <add> warn_ctx = WarningManager() <add> warn_ctx.__enter__() <add> try: <add> warnings.simplefilter('ignore') <add> assert_equal(float(x), float(x.real)) <add> finally: <add> warn_ctx.__exit__() <ide> <ide> def test_complex_scalar_complex_cast(self): <ide> for tp in [np.csingle, np.cdouble, np.clongdouble]: <ide><path>numpy/lib/tests/test_io.py <ide> import time <ide> from datetime import datetime <ide> import warnings <add>from numpy.testing.utils import WarningManager <ide> <ide> import numpy as np <ide> import numpy.ma as ma <ide> def test_3d_shaped_dtype(self): <ide> assert_array_equal(x, a) <ide> <ide> def test_empty_file(self): <del> warnings.filterwarnings("ignore", message="loadtxt: Empty input file:") <del> c = StringIO() <del> x = np.loadtxt(c) <del> assert_equal(x.shape, (0,)) <del> x = np.loadtxt(c, dtype=np.int64) <del> assert_equal(x.shape, (0,)) <del> assert_(x.dtype == np.int64) <add> warn_ctx = WarningManager() <add> warn_ctx.__enter__() <add> try: <add> warnings.filterwarnings("ignore", <add> message="loadtxt: Empty input file:") <add> c = StringIO() <add> x = np.loadtxt(c) <add> assert_equal(x.shape, (0,)) <add> x = np.loadtxt(c, dtype=np.int64) <add> assert_equal(x.shape, (0,)) <add> assert_(x.dtype == np.int64) <add> finally: <add> warn_ctx.__exit__() <ide> <ide> <ide> def test_unused_converter(self): <ide> def test_skip_footer(self): <ide> assert_equal(test, ctrl) <ide> <ide> def test_skip_footer_with_invalid(self): <del> basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n' <del> warnings.filterwarnings("ignore") <del> # Footer too small to get rid of all invalid values <del> assert_raises(ValueError, np.genfromtxt, <del> StringIO(basestr), skip_footer=1) <del># except ValueError: <del># pass <del> a = np.genfromtxt(StringIO(basestr), skip_footer=1, invalid_raise=False) <del> assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])) <del> # <del> a = np.genfromtxt(StringIO(basestr), skip_footer=3) <del> assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])) <del> # <del> basestr = '1 1\n2 \n3 3\n4 4\n5 \n6 6\n7 7\n' <del> a = np.genfromtxt(StringIO(basestr), skip_footer=1, invalid_raise=False) <del> assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]])) <del> a = np.genfromtxt(StringIO(basestr), skip_footer=3, invalid_raise=False) <del> assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]])) <del> warnings.resetwarnings() <add> warn_ctx = WarningManager() <add> warn_ctx.__enter__() <add> try: <add> basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n' <add> warnings.filterwarnings("ignore") <add> # Footer too small to get rid of all invalid values <add> assert_raises(ValueError, np.genfromtxt, <add> StringIO(basestr), skip_footer=1) <add> # except ValueError: <add> # pass <add> a = np.genfromtxt(StringIO(basestr), skip_footer=1, invalid_raise=False) <add> assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])) <add> # <add> a = np.genfromtxt(StringIO(basestr), skip_footer=3) <add> assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])) <add> # <add> basestr = '1 1\n2 \n3 3\n4 4\n5 \n6 6\n7 7\n' <add> a = np.genfromtxt(StringIO(basestr), skip_footer=1, invalid_raise=False) <add> assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]])) <add> a = np.genfromtxt(StringIO(basestr), skip_footer=3, invalid_raise=False) <add> assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]])) <add> finally: <add> warn_ctx.__exit__() <ide> <ide> <ide> def test_header(self): <ide> def test_usecols_with_named_columns(self): <ide> <ide> def test_empty_file(self): <ide> "Test that an empty file raises the proper warning." <del> warnings.filterwarnings("ignore", message="genfromtxt: Empty input file:") <del> data = StringIO() <del> test = np.genfromtxt(data) <del> assert_equal(test, np.array([])) <add> warn_ctx = WarningManager() <add> warn_ctx.__enter__() <add> try: <add> warnings.filterwarnings("ignore", message="genfromtxt: Empty input file:") <add> data = StringIO() <add> test = np.genfromtxt(data) <add> assert_equal(test, np.array([])) <add> finally: <add> warn_ctx.__exit__() <ide> <ide> def test_fancy_dtype_alt(self): <ide> "Check that a nested dtype isn't MIA" <ide><path>numpy/ma/tests/test_core.py <ide> from numpy.ma.core import * <ide> <ide> from numpy.compat import asbytes, asbytes_nested <add>from numpy.testing.utils import WarningManager <ide> <ide> pi = np.pi <ide> <ide> def test_topython(self): <ide> assert_equal(1.0, float(array([[1]]))) <ide> self.assertRaises(TypeError, float, array([1, 1])) <ide> # <del> warnings.simplefilter('ignore', UserWarning) <del> assert_(np.isnan(float(array([1], mask=[1])))) <del> warnings.simplefilter('default', UserWarning) <add> warn_ctx = WarningManager() <add> warn_ctx.__enter__() <add> try: <add> warnings.simplefilter('ignore', UserWarning) <add> assert_(np.isnan(float(array([1], mask=[1])))) <add> finally: <add> warn_ctx.__exit__() <ide> # <ide> a = array([1, 2, 3], mask=[1, 0, 0]) <ide> self.assertRaises(TypeError, lambda:float(a)) <ide><path>numpy/ma/tests/test_mrecords.py <ide> import numpy.ma as ma <ide> from numpy.ma import masked, nomask <ide> <add>import warnings <add>from numpy.testing.utils import WarningManager <add> <ide> from numpy.ma.mrecords import MaskedRecords, mrecarray, fromarrays, \ <ide> fromtextfile, fromrecords, addfield <ide> <ide> def test_set_fields(self): <ide> rdata = data.view(MaskedRecords) <ide> val = ma.array([10,20,30], mask=[1,0,0]) <ide> # <del> import warnings <del> warnings.simplefilter("ignore") <del> rdata['num'] = val <del> assert_equal(rdata.num, val) <del> assert_equal(rdata.num.mask, [1,0,0]) <add> warn_ctx = WarningManager() <add> warn_ctx.__enter__() <add> try: <add> warnings.simplefilter("ignore") <add> rdata['num'] = val <add> assert_equal(rdata.num, val) <add> assert_equal(rdata.num.mask, [1,0,0]) <add> finally: <add> warn_ctx.__exit__() <ide> <ide> def test_set_fields_mask(self): <ide> "Tests setting the mask of a field."
7
Ruby
Ruby
remove unused attr
7804d2d5f3f0250b7f6d693476791be5bb0e597c
<ide><path>Library/Homebrew/resource.rb <ide> class Resource <ide> # This is the resource name <ide> attr_reader :name <ide> <del> # This is the associated formula name <del> attr_reader :owner_name <del> <ide> def initialize name, spec <ide> @name = name <ide> @spec = spec
1
Text
Text
fix broken link to section
b35b00990c639493364f3dc3fd690462948e2942
<ide><path>CONTRIBUTING.md <ide> These are just guidelines, not rules, use your best judgment and feel free to pr <ide> <ide> #### Table Of Contents <ide> <del>[What should I know before I get started?](#introduction) <add>[What should I know before I get started?](#what-should-i-know-before-i-get-started) <ide> * [Code of Conduct](#code-of-conduct) <ide> * [Atom and Packages](#atom-and-packages) <ide>
1
Text
Text
use oxford comma in crypto docs
e4dfe5466f8fef8aeeceb579432d494c54377174
<ide><path>doc/api/crypto.md <ide> once will result in an error being thrown. <ide> added: v1.0.0 <ide> --> <ide> <del>* Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM` <add>* Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM`, <ide> and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a <ide> [`Buffer`][] containing the _authentication tag_ that has been computed from <ide> the given data. <ide> added: v1.0.0 <ide> * `encoding` {string} The string encoding to use when `buffer` is a string. <ide> * Returns: {Cipher} for method chaining. <ide> <del>When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are <add>When using an authenticated encryption mode (`GCM`, `CCM`, and `OCB` are <ide> currently supported), the `cipher.setAAD()` method sets the value used for the <ide> _additional authenticated data_ (AAD) input parameter. <ide> <ide> changes: <ide> * `encoding` {string} String encoding to use when `buffer` is a string. <ide> * Returns: {Decipher} for method chaining. <ide> <del>When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are <add>When using an authenticated encryption mode (`GCM`, `CCM`, and `OCB` are <ide> currently supported), the `decipher.setAAD()` method sets the value used for the <ide> _additional authenticated data_ (AAD) input parameter. <ide> <ide> changes: <ide> * `encoding` {string} String encoding to use when `buffer` is a string. <ide> * Returns: {Decipher} for method chaining. <ide> <del>When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are <add>When using an authenticated encryption mode (`GCM`, `CCM`, and `OCB` are <ide> currently supported), the `decipher.setAuthTag()` method is used to pass in the <ide> received _authentication tag_. If no tag is provided, or if the cipher text <ide> has been tampered with, [`decipher.final()`][] will throw, indicating that the
1
Javascript
Javascript
add macedonian language
b6413bf9b49786e52ff5c1c724b66110a71df642
<ide><path>lang/mk.js <add>// moment.js language configuration <add>// language : macedonian (mk) <add>// author : Borislav Mickov : https://github.com/B0k0 <add> <add>(function (factory) { <add> if (typeof define === 'function' && define.amd) { <add> define(['moment'], factory); // AMD <add> } else if (typeof exports === 'object') { <add> module.exports = factory(require('../moment')); // Node <add> } else { <add> factory(window.moment); // Browser global <add> } <add>}(function (moment) { <add> return moment.lang('mk', { <add> months : "јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември".split("_"), <add> monthsShort : "јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек".split("_"), <add> weekdays : "недела_понеделник_вторник_среда_четврток_петок_сабота".split("_"), <add> weekdaysShort : "нед_пон_вто_сре_чет_пет_саб".split("_"), <add> weekdaysMin : "нe_пo_вт_ср_че_пе_сa".split("_"), <add> longDateFormat : { <add> LT : "H:mm", <add> L : "D.MM.YYYY", <add> LL : "D MMMM YYYY", <add> LLL : "D MMMM YYYY LT", <add> LLLL : "dddd, D MMMM YYYY LT" <add> }, <add> calendar : { <add> sameDay : '[Денес во] LT', <add> nextDay : '[Утре во] LT', <add> nextWeek : 'dddd [во] LT', <add> lastDay : '[Вчера во] LT', <add> lastWeek : function () { <add> switch (this.day()) { <add> case 0: <add> case 3: <add> case 6: <add> return '[Во изминатата] dddd [во] LT'; <add> case 1: <add> case 2: <add> case 4: <add> case 5: <add> return '[Во изминатиот] dddd [во] LT'; <add> } <add> }, <add> sameElse : 'L' <add> }, <add> relativeTime : { <add> future : "после %s", <add> past : "пред %s", <add> s : "неколку секунди", <add> m : "минута", <add> mm : "%d минути", <add> h : "час", <add> hh : "%d часа", <add> d : "ден", <add> dd : "%d дена", <add> M : "месец", <add> MM : "%d месеци", <add> y : "година", <add> yy : "%d години" <add> }, <add> ordinal : function (number) { <add> var lastDigit = number % 10, <add> last2Digits = number % 100; <add> if (number === 0) { <add> return number + '-ев'; <add> } else if (last2Digits === 0) { <add> return number + '-ен'; <add> } else if (last2Digits > 10 && last2Digits < 20) { <add> return number + '-ти'; <add> } else if (lastDigit === 1) { <add> return number + '-ви'; <add> } else if (lastDigit === 2) { <add> return number + '-ри'; <add> } else if (lastDigit === 7 || lastDigit === 8) { <add> return number + '-ми'; <add> } else { <add> return number + '-ти'; <add> } <add> }, <add> week : { <add> dow : 1, // Monday is the first day of the week. <add> doy : 7 // The week that contains Jan 1st is the first week of the year. <add> } <add> }); <add>})); <ide><path>test/lang/mk.js <add>var moment = require("../../moment"); <add> <add> <add> /************************************************** <add> Macedonian <add> *************************************************/ <add> <add>exports["lang:mk"] = { <add> "setUp" : function (cb) { <add> moment.lang('mk'); <add> cb(); <add> }, <add> <add> "tearDown" : function (cb) { <add> moment.lang('en'); <add> cb(); <add> }, <add> <add> "parse" : function (test) { <add> test.expect(96); <add> var tests = 'јануари јан_февруари фев_март мар_април апр_мај мај_јуни јун_јули јул_август авг_септември сеп_октомври окт_ноември ное_декември дек'.split("_"), i; <add> function equalTest(input, mmm, i) { <add> test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); <add> } <add> for (i = 0; i < 12; i++) { <add> tests[i] = tests[i].split(' '); <add> equalTest(tests[i][0], 'MMM', i); <add> equalTest(tests[i][1], 'MMM', i); <add> equalTest(tests[i][0], 'MMMM', i); <add> equalTest(tests[i][1], 'MMMM', i); <add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); <add> } <add> test.done(); <add> }, <add> <add> "format" : function (test) { <add> test.expect(22); <add> var a = [ <add> ['dddd, MMMM Do YYYY, H:mm:ss', 'недела, февруари 14-ти 2010, 15:25:50'], <add> ['ddd, hA', 'нед, 3PM'], <add> ['M Mo MM MMMM MMM', '2 2-ри 02 февруари фев'], <add> ['YYYY YY', '2010 10'], <add> ['D Do DD', '14 14-ти 14'], <add> ['d do dddd ddd dd', '0 0-ев недела нед нe'], <add> ['DDD DDDo DDDD', '45 45-ти 045'], <add> ['w wo ww', '7 7-ми 07'], <add> ['h hh', '3 03'], <add> ['H HH', '15 15'], <add> ['m mm', '25 25'], <add> ['s ss', '50 50'], <add> ['a A', 'pm PM'], <add> ['[the] DDDo [day of the year]', 'the 45-ти day of the year'], <add> ['L', '14.02.2010'], <add> ['LL', '14 февруари 2010'], <add> ['LLL', '14 февруари 2010 15:25'], <add> ['LLLL', 'недела, 14 февруари 2010 15:25'], <add> ['l', '14.2.2010'], <add> ['ll', '14 фев 2010'], <add> ['lll', '14 фев 2010 15:25'], <add> ['llll', 'нед, 14 фев 2010 15:25'] <add> ], <add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <add> i; <add> for (i = 0; i < a.length; i++) { <add> test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); <add> } <add> test.done(); <add> }, <add> <add> "format ordinal" : function (test) { <add> test.expect(31); <add> test.equal(moment([2011, 0, 1]).format('DDDo'), '1-ви', '1-ви'); <add> test.equal(moment([2011, 0, 2]).format('DDDo'), '2-ри', '2-ри'); <add> test.equal(moment([2011, 0, 3]).format('DDDo'), '3-ти', '3-ти'); <add> test.equal(moment([2011, 0, 4]).format('DDDo'), '4-ти', '4-ти'); <add> test.equal(moment([2011, 0, 5]).format('DDDo'), '5-ти', '5-ти'); <add> test.equal(moment([2011, 0, 6]).format('DDDo'), '6-ти', '6-ти'); <add> test.equal(moment([2011, 0, 7]).format('DDDo'), '7-ми', '7-ми'); <add> test.equal(moment([2011, 0, 8]).format('DDDo'), '8-ми', '8-ми'); <add> test.equal(moment([2011, 0, 9]).format('DDDo'), '9-ти', '9-ти'); <add> test.equal(moment([2011, 0, 10]).format('DDDo'), '10-ти', '10-ти'); <add> <add> test.equal(moment([2011, 0, 11]).format('DDDo'), '11-ти', '11-ти'); <add> test.equal(moment([2011, 0, 12]).format('DDDo'), '12-ти', '12-ти'); <add> test.equal(moment([2011, 0, 13]).format('DDDo'), '13-ти', '13-ти'); <add> test.equal(moment([2011, 0, 14]).format('DDDo'), '14-ти', '14-ти'); <add> test.equal(moment([2011, 0, 15]).format('DDDo'), '15-ти', '15-ти'); <add> test.equal(moment([2011, 0, 16]).format('DDDo'), '16-ти', '16-ти'); <add> test.equal(moment([2011, 0, 17]).format('DDDo'), '17-ти', '17-ти'); <add> test.equal(moment([2011, 0, 18]).format('DDDo'), '18-ти', '18-ти'); <add> test.equal(moment([2011, 0, 19]).format('DDDo'), '19-ти', '19-ти'); <add> test.equal(moment([2011, 0, 20]).format('DDDo'), '20-ти', '20-ти'); <add> <add> test.equal(moment([2011, 0, 21]).format('DDDo'), '21-ви', '21-ви'); <add> test.equal(moment([2011, 0, 22]).format('DDDo'), '22-ри', '22-ри'); <add> test.equal(moment([2011, 0, 23]).format('DDDo'), '23-ти', '23-ти'); <add> test.equal(moment([2011, 0, 24]).format('DDDo'), '24-ти', '24-ти'); <add> test.equal(moment([2011, 0, 25]).format('DDDo'), '25-ти', '25-ти'); <add> test.equal(moment([2011, 0, 26]).format('DDDo'), '26-ти', '26-ти'); <add> test.equal(moment([2011, 0, 27]).format('DDDo'), '27-ми', '27-ми'); <add> test.equal(moment([2011, 0, 28]).format('DDDo'), '28-ми', '28-ми'); <add> test.equal(moment([2011, 0, 29]).format('DDDo'), '29-ти', '29-ти'); <add> test.equal(moment([2011, 0, 30]).format('DDDo'), '30-ти', '30-ти'); <add> <add> test.equal(moment([2011, 0, 31]).format('DDDo'), '31-ви', '31-ви'); <add> test.done(); <add> }, <add> <add> "format month" : function (test) { <add> test.expect(12); <add> var expected = 'јануари јан_февруари фев_март мар_април апр_мај мај_јуни јун_јули јул_август авг_септември сеп_октомври окт_ноември ное_декември дек'.split("_"), i; <add> for (i = 0; i < expected.length; i++) { <add> test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); <add> } <add> test.done(); <add> }, <add> <add> "format week" : function (test) { <add> test.expect(7); <add> var expected = 'недела нед нe_понеделник пон пo_вторник вто вт_среда сре ср_четврток чет че_петок пет пе_сабота саб сa'.split("_"), i; <add> for (i = 0; i < expected.length; i++) { <add> test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); <add> } <add> test.done(); <add> }, <add> <add> "from" : function (test) { <add> test.expect(30); <add> var start = moment([2007, 1, 28]); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "неколку секунди", "44 seconds = a few seconds"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "минута", "45 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), "минута", "89 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), "2 минути", "90 seconds = 2 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), "44 минути", "44 minutes = 44 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), "час", "45 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), "час", "89 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), "2 часа", "90 minutes = 2 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), "5 часа", "5 hours = 5 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), "21 часа", "21 hours = 21 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), "ден", "22 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), "ден", "35 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), "2 дена", "36 hours = 2 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), "ден", "1 day = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), "5 дена", "5 days = 5 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "25 дена", "25 days = 25 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "месец", "26 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "месец", "30 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 45}), true), "месец", "45 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "2 месеци", "46 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "2 месеци", "75 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "3 месеци", "76 days = 3 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "месец", "1 month = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "5 месеци", "5 months = 5 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 344}), true), "11 месеци", "344 days = 11 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "година", "345 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 547}), true), "година", "547 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "2 години", "548 days = 2 years"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "година", "1 year = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "5 години", "5 years = 5 years"); <add> test.done(); <add> }, <add> <add> "suffix" : function (test) { <add> test.expect(2); <add> test.equal(moment(30000).from(0), "после неколку секунди", "prefix"); <add> test.equal(moment(0).from(30000), "пред неколку секунди", "suffix"); <add> test.done(); <add> }, <add> <add> "now from now" : function (test) { <add> test.expect(1); <add> test.equal(moment().fromNow(), "пред неколку секунди", "now from now should display as in the past"); <add> test.done(); <add> }, <add> <add> "fromNow" : function (test) { <add> test.expect(2); <add> test.equal(moment().add({s: 30}).fromNow(), "после неколку секунди", "in a few seconds"); <add> test.equal(moment().add({d: 5}).fromNow(), "после 5 дена", "in 5 days"); <add> test.done(); <add> }, <add> <add> "calendar day" : function (test) { <add> test.expect(6); <add> <add> var a = moment().hours(2).minutes(0).seconds(0); <add> <add> test.equal(moment(a).calendar(), "Денес во 2:00", "today at the same time"); <add> test.equal(moment(a).add({ m: 25 }).calendar(), "Денес во 2:25", "Now plus 25 min"); <add> test.equal(moment(a).add({ h: 1 }).calendar(), "Денес во 3:00", "Now plus 1 hour"); <add> test.equal(moment(a).add({ d: 1 }).calendar(), "Утре во 2:00", "tomorrow at the same time"); <add> test.equal(moment(a).subtract({ h: 1 }).calendar(), "Денес во 1:00", "Now minus 1 hour"); <add> test.equal(moment(a).subtract({ d: 1 }).calendar(), "Вчера во 2:00", "yesterday at the same time"); <add> test.done(); <add> }, <add> <add> "calendar next week" : function (test) { <add> test.expect(15); <add> <add> var i, m; <add> for (i = 2; i < 7; i++) { <add> m = moment().add({ d: i }); <add> test.equal(m.calendar(), m.format('dddd [во] LT'), "Today + " + i + " days current time"); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> test.equal(m.calendar(), m.format('dddd [во] LT'), "Today + " + i + " days beginning of day"); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> test.equal(m.calendar(), m.format('dddd [во] LT'), "Today + " + i + " days end of day"); <add> } <add> test.done(); <add> }, <add> <add> "calendar last week" : function (test) { <add> test.expect(15); <add> <add> var i, m; <add> <add> function makeFormat(d) { <add> switch (d.day()) { <add> case 0: <add> case 3: <add> case 6: <add> return '[Во изминатата] dddd [во] LT'; <add> case 1: <add> case 2: <add> case 4: <add> case 5: <add> return '[Во изминатиот] dddd [во] LT'; <add> } <add> } <add> <add> for (i = 2; i < 7; i++) { <add> m = moment().subtract({ d: i }); <add> test.equal(m.calendar(), m.format(makeFormat(m)), "Today - " + i + " days current time"); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> test.equal(m.calendar(), m.format(makeFormat(m)), "Today - " + i + " days beginning of day"); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> test.equal(m.calendar(), m.format(makeFormat(m)), "Today - " + i + " days end of day"); <add> } <add> test.done(); <add> }, <add> <add> "calendar all else" : function (test) { <add> test.expect(4); <add> var weeksAgo = moment().subtract({ w: 1 }), <add> weeksFromNow = moment().add({ w: 1 }); <add> <add> test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 week ago"); <add> test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 1 week"); <add> <add> weeksAgo = moment().subtract({ w: 2 }); <add> weeksFromNow = moment().add({ w: 2 }); <add> <add> test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 weeks ago"); <add> test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 2 weeks"); <add> test.done(); <add> }, <add> <add> // Monday is the first day of the week. <add> // The week that contains Jan 1st is the first week of the year. <add> <add> "weeks year starting sunday" : function (test) { <add> test.expect(5); <add> <add> test.equal(moment([2011, 11, 26]).week(), 1, "Dec 26 2011 should be week 1"); <add> test.equal(moment([2012, 0, 1]).week(), 1, "Jan 1 2012 should be week 1"); <add> test.equal(moment([2012, 0, 2]).week(), 2, "Jan 2 2012 should be week 2"); <add> test.equal(moment([2012, 0, 8]).week(), 2, "Jan 8 2012 should be week 2"); <add> test.equal(moment([2012, 0, 9]).week(), 3, "Jan 9 2012 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting monday" : function (test) { <add> test.expect(5); <add> <add> test.equal(moment([2007, 0, 1]).week(), 1, "Jan 1 2007 should be week 1"); <add> test.equal(moment([2007, 0, 7]).week(), 1, "Jan 7 2007 should be week 1"); <add> test.equal(moment([2007, 0, 8]).week(), 2, "Jan 8 2007 should be week 2"); <add> test.equal(moment([2007, 0, 14]).week(), 2, "Jan 14 2007 should be week 2"); <add> test.equal(moment([2007, 0, 15]).week(), 3, "Jan 15 2007 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting tuesday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2007, 11, 31]).week(), 1, "Dec 31 2007 should be week 1"); <add> test.equal(moment([2008, 0, 1]).week(), 1, "Jan 1 2008 should be week 1"); <add> test.equal(moment([2008, 0, 6]).week(), 1, "Jan 6 2008 should be week 1"); <add> test.equal(moment([2008, 0, 7]).week(), 2, "Jan 7 2008 should be week 2"); <add> test.equal(moment([2008, 0, 13]).week(), 2, "Jan 13 2008 should be week 2"); <add> test.equal(moment([2008, 0, 14]).week(), 3, "Jan 14 2008 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting wednesday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2002, 11, 30]).week(), 1, "Dec 30 2002 should be week 1"); <add> test.equal(moment([2003, 0, 1]).week(), 1, "Jan 1 2003 should be week 1"); <add> test.equal(moment([2003, 0, 5]).week(), 1, "Jan 5 2003 should be week 1"); <add> test.equal(moment([2003, 0, 6]).week(), 2, "Jan 6 2003 should be week 2"); <add> test.equal(moment([2003, 0, 12]).week(), 2, "Jan 12 2003 should be week 2"); <add> test.equal(moment([2003, 0, 13]).week(), 3, "Jan 13 2003 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting thursday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2008, 11, 29]).week(), 1, "Dec 29 2008 should be week 1"); <add> test.equal(moment([2009, 0, 1]).week(), 1, "Jan 1 2009 should be week 1"); <add> test.equal(moment([2009, 0, 4]).week(), 1, "Jan 4 2009 should be week 1"); <add> test.equal(moment([2009, 0, 5]).week(), 2, "Jan 5 2009 should be week 2"); <add> test.equal(moment([2009, 0, 11]).week(), 2, "Jan 11 2009 should be week 2"); <add> test.equal(moment([2009, 0, 12]).week(), 3, "Jan 12 2009 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting friday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2009, 11, 28]).week(), 1, "Dec 28 2009 should be week 1"); <add> test.equal(moment([2010, 0, 1]).week(), 1, "Jan 1 2010 should be week 1"); <add> test.equal(moment([2010, 0, 3]).week(), 1, "Jan 3 2010 should be week 1"); <add> test.equal(moment([2010, 0, 4]).week(), 2, "Jan 4 2010 should be week 2"); <add> test.equal(moment([2010, 0, 10]).week(), 2, "Jan 10 2010 should be week 2"); <add> test.equal(moment([2010, 0, 11]).week(), 3, "Jan 11 2010 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting saturday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2010, 11, 27]).week(), 1, "Dec 27 2010 should be week 1"); <add> test.equal(moment([2011, 0, 1]).week(), 1, "Jan 1 2011 should be week 1"); <add> test.equal(moment([2011, 0, 2]).week(), 1, "Jan 2 2011 should be week 1"); <add> test.equal(moment([2011, 0, 3]).week(), 2, "Jan 3 2011 should be week 2"); <add> test.equal(moment([2011, 0, 9]).week(), 2, "Jan 9 2011 should be week 2"); <add> test.equal(moment([2011, 0, 10]).week(), 3, "Jan 10 2011 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting sunday formatted" : function (test) { <add> test.expect(5); <add> <add> test.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-ви', "Dec 26 2011 should be week 1"); <add> test.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-ви', "Jan 1 2012 should be week 1"); <add> test.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-ри', "Jan 2 2012 should be week 2"); <add> test.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-ри', "Jan 8 2012 should be week 2"); <add> test.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-ти', "Jan 9 2012 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "returns the name of the language" : function (test) { <add> if (typeof module !== 'undefined' && module.exports) { <add> test.equal(require('../../lang/mk'), 'mk', "module should export mk"); <add> } <add> <add> test.done(); <add> } <add>};
2
Mixed
Ruby
fix broken handling of unknown http methods
1f9a5dd36bd0dcba8ad7692322e79d6ce14c064d
<ide><path>actionpack/lib/action_dispatch/http/request.rb <ide> def key?(key) <ide> HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym <ide> } <ide> <add> alias raw_request_method request_method # :nodoc: <add> <ide> # Returns the HTTP \method that the application should see. <ide> # In the case where the \method was overridden by a middleware <ide> # (for instance, if a HEAD request was converted to a GET, <ide><path>railties/CHANGELOG.md <add>* Return a 405 Method Not Allowed response when a request uses an unknown HTTP method. <add> <add> Fixes #38998. <add> <add> *Loren Norman* <add> <ide> * Make railsrc file location xdg-specification compliant <ide> <ide> `rails new` will now look for the default `railsrc` file at <ide><path>railties/lib/rails/rack/logger.rb <ide> def call_app(request, env) # :doc: <ide> # Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700 <ide> def started_request_message(request) # :doc: <ide> 'Started %s "%s" for %s at %s' % [ <del> request.request_method, <add> request.raw_request_method, <ide> request.filtered_path, <ide> request.remote_ip, <ide> Time.now.to_default_s ] <ide><path>railties/test/application/middleware/exceptions_test.rb <ide> def index <ide> assert_equal 404, last_response.status <ide> end <ide> <add> test "renders unknown http methods as 405" do <add> request "/", { "REQUEST_METHOD" => "NOT_AN_HTTP_METHOD" } <add> assert_equal 405, last_response.status <add> end <add> <ide> test "uses custom exceptions app" do <ide> add_to_config <<-RUBY <ide> config.exceptions_app = lambda do |env|
4
PHP
PHP
add missing return and remove else statements
9e62a46a9b1ec1bcab31e41e102e692d9e6a4c80
<ide><path>Cake/ORM/Association/BelongsToMany.php <ide> public function cascadeDelete(Entity $entity, $options = []) { <ide> foreach ($table->find('all')->where($conditions) as $related) { <ide> $table->delete($related, $options); <ide> } <del> } else { <del> return $table->deleteAll($conditions); <add> return true; <ide> } <add> return $table->deleteAll($conditions); <ide> } <ide> <ide> /** <ide><path>Cake/ORM/Association/DependentDeleteTrait.php <ide> public function cascadeDelete(Entity $entity, $options = []) { <ide> foreach ($table->find('all')->where($conditions) as $related) { <ide> $table->delete($related, $options); <ide> } <del> } else { <del> $table->deleteAll($conditions); <add> return true; <ide> } <del> return true; <add> return $table->deleteAll($conditions); <ide> } <ide> }
2
Python
Python
change version number
07e319edaa2c21c9300acdefa60f4b719b44af12
<ide><path>numpy/version.py <del>version='0.9.9' <add>version='1.0' <ide> <ide> import os <ide> svn_version_file = os.path.join(os.path.dirname(__file__),
1
Javascript
Javascript
check error type from net.server.listen()
8059393934c2ed0e3e7a179f619b803291804344
<ide><path>test/parallel/test-net-server-try-ports.js <ide> var connections = 0; <ide> <ide> var server1listening = false; <ide> var server2listening = false; <add>var server2eaddrinuse = false; <ide> <ide> var server1 = net.Server(function(socket) { <ide> connections++; <ide> var server2 = net.Server(function(socket) { <ide> }); <ide> <ide> var server2errors = 0; <del>server2.on('error', function() { <add>server2.on('error', function(e) { <ide> server2errors++; <ide> console.error('server2 error'); <add> <add> if (e.code == 'EADDRINUSE') { <add> server2eaddrinuse = true; <add> } <add> <add> server2.listen(common.PORT + 1, function() { <add> console.error('server2 listening'); <add> server2listening = true; <add> <add> server1.close(); <add> server2.close(); <add> }); <ide> }); <ide> <ide> <ide> server1.listen(common.PORT, function() { <ide> server1listening = true; <ide> // This should make server2 emit EADDRINUSE <ide> server2.listen(common.PORT); <del> <del> // Wait a bit, now try again. <del> // TODO, the listen callback should report if there was an error. <del> // Then we could avoid this very unlikely but potential race condition <del> // here. <del> setTimeout(function() { <del> server2.listen(common.PORT + 1, function() { <del> console.error('server2 listening'); <del> server2listening = true; <del> <del> server1.close(); <del> server2.close(); <del> }); <del> }, 100); <ide> }); <ide> <ide> <ide> process.on('exit', function() { <ide> assert.equal(1, server2errors); <add> assert.ok(server2eaddrinuse); <ide> assert.ok(server2listening); <ide> assert.ok(server1listening); <ide> });
1
PHP
PHP
indicate defer property removal
8cb5ae73b8ecb649abd38f2548362f0145dc1da5
<ide><path>src/Illuminate/Support/ServiceProvider.php <ide> abstract class ServiceProvider <ide> /** <ide> * Indicates if loading of the provider is deferred. <ide> * <del> * @deprecated 5.8 Implement the \Illuminate\Contracts\Support\DeferrableProvider interface instead. <add> * @deprecated Implement the \Illuminate\Contracts\Support\DeferrableProvider interface instead. Will be removed in Laravel 5.9. <ide> * <ide> * @var bool <ide> */
1
Python
Python
add note about array_like being optional
3f18d8fab26fb473e495f2e82600ce170d1c577c
<ide><path>numpy/core/_add_newdocs.py <ide> dtype : dtype, optional <ide> The type of the output array. If `dtype` is not given, infer the data <ide> type from the other input arguments. <del> ${ARRAY_FUNCTION_LIKE} This is an optional argument. <add> ${ARRAY_FUNCTION_LIKE} <ide> <ide> .. versionadded:: 1.20.0 <ide> <ide><path>numpy/core/overrides.py <ide> int(os.environ.get('NUMPY_EXPERIMENTAL_ARRAY_FUNCTION', 1))) <ide> <ide> array_function_like_doc = ( <del> """like : array_like <add> """like : array_like, optional <ide> Reference object to allow the creation of arrays which are not <ide> NumPy arrays. If an array-like passed in as ``like`` supports <ide> the ``__array_function__`` protocol, the result will be defined
2
Text
Text
add yarn add webpack-cli step
64db3064c76b52dec070e113998415b9b5e65430
<ide><path>examples/README.md <ide> If you think an example is missing, please report it as issue. :) <ide> <ide> # Building an Example <del>1. Run `npm install` in the root of the project. <del>2. Run `npm link webpack` in the root of the project. <del>3. Run `node build.js` in the specific example directory. (Ex: `cd examples/commonjs && node build.js`) <add>1. Run `yarn` in the root of the project. <add>2. Run `yarn link webpack` in the root of the project. <add>3. Run `yarn add --dev webpack-cli` in the root of the project. <add>4. Run `node build.js` in the specific example directory. (Ex: `cd examples/commonjs && node build.js`) <ide> <ide> Note: To build all examples run `npm run build:examples`
1
Java
Java
consolidate okhttpclient creation
07c8854a1cbe32d38857cf2001b16e2549058d93
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java <ide> public interface ResponseHandler { <ide> private final List<ResponseHandler> mResponseHandlers = new ArrayList<>(); <ide> private boolean mShuttingDown; <ide> <del> /* package */ NetworkingModule( <add> public NetworkingModule( <ide> ReactApplicationContext reactContext, <ide> @Nullable String defaultUserAgent, <ide> OkHttpClient client,
1
Python
Python
prefer app named "app"
7e824d62e309e0dfe3ed1c823c689f875e95356a
<ide><path>celery/bin/base.py <ide> def find_app(self, app): <ide> sym = import_from_cwd(app) <ide> if isinstance(sym, ModuleType): <ide> try: <del> return sym.celery <add> return sym.app <ide> except AttributeError: <del> if getattr(sym, '__path__', None): <del> try: <del> return self.find_app('{0}.celery:'.format( <del> app.replace(':', ''))) <del> except ImportError: <del> pass <del> for suspect in values(vars(sym)): <del> if isinstance(suspect, Celery): <del> return suspect <del> raise <add> try: <add> return sym.celery <add> except AttributeError: <add> if getattr(sym, '__path__', None): <add> try: <add> return self.find_app( <add> '{0}.celery:'.format(app.replace(':', '')), <add> ) <add> except ImportError: <add> pass <add> for suspect in values(vars(sym)): <add> if isinstance(suspect, Celery): <add> return suspect <add> raise <ide> return sym <ide> <ide> def symbol_by_name(self, name):
1
Java
Java
use decode from a databuffer where feasible
f89d2ac14891d21714462e6ea4f8dc32d325f1cf
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/reactive/PayloadMethodArgumentResolver.java <ide> private Mono<Object> decodeContent(MethodParameter parameter, Message<?> message <ide> if (decoder.canDecode(elementType, mimeType)) { <ide> if (adapter != null && adapter.isMultiValue()) { <ide> Flux<?> flux = content <del> .concatMap(buffer -> decoder.decode(Mono.just(buffer), elementType, mimeType, hints)) <add> .map(buffer -> decoder.decode(buffer, elementType, mimeType, hints)) <ide> .onErrorResume(ex -> Flux.error(handleReadError(parameter, message, ex))); <ide> if (isContentRequired) { <ide> flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(parameter, message))); <ide> } <ide> if (validator != null) { <del> flux = flux.doOnNext(validator::accept); <add> flux = flux.doOnNext(validator); <ide> } <ide> return Mono.just(adapter.fromPublisher(flux)); <ide> } <ide> else { <ide> // Single-value (with or without reactive type wrapper) <del> Mono<?> mono = decoder <del> .decodeToMono(content.next(), targetType, mimeType, hints) <add> Mono<?> mono = content.next() <add> .map(buffer -> decoder.decode(buffer, elementType, mimeType, hints)) <ide> .onErrorResume(ex -> Mono.error(handleReadError(parameter, message, ex))); <ide> if (isContentRequired) { <ide> mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(parameter, message))); <ide> } <ide> if (validator != null) { <del> mono = mono.doOnNext(validator::accept); <add> mono = mono.doOnNext(validator); <ide> } <ide> return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono)); <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java <ide> private <T> Mono<T> retrieveMono(ResolvableType elementType) { <ide> } <ide> <ide> Decoder<?> decoder = strategies.decoder(elementType, dataMimeType); <del> return (Mono<T>) decoder.decodeToMono( <del> payloadMono.map(this::retainDataAndReleasePayload), elementType, dataMimeType, EMPTY_HINTS); <add> return (Mono<T>) payloadMono.map(this::retainDataAndReleasePayload) <add> .map(dataBuffer -> decoder.decode(dataBuffer, elementType, dataMimeType, EMPTY_HINTS)); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <ide> private <T> Flux<T> retrieveFlux(ResolvableType elementType) { <ide> <ide> Decoder<?> decoder = strategies.decoder(elementType, dataMimeType); <ide> <del> return payloadFlux.map(this::retainDataAndReleasePayload).concatMap(dataBuffer -> <del> (Mono<T>) decoder.decodeToMono(Mono.just(dataBuffer), elementType, dataMimeType, EMPTY_HINTS)); <add> return payloadFlux.map(this::retainDataAndReleasePayload).map(dataBuffer -> <add> (T) decoder.decode(dataBuffer, elementType, dataMimeType, EMPTY_HINTS)); <ide> } <ide> <ide> private DataBuffer retainDataAndReleasePayload(Payload payload) { <ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerSentEventHttpMessageReader.java <ide> public Flux<Object> read( <ide> <ide> return stringDecoder.decode(message.getBody(), STRING_TYPE, null, hints) <ide> .bufferUntil(line -> line.equals("")) <del> .concatMap(lines -> buildEvent(lines, valueType, shouldWrap, hints)); <add> .concatMap(lines -> Mono.justOrEmpty(buildEvent(lines, valueType, shouldWrap, hints))); <ide> } <ide> <del> private Mono<?> buildEvent(List<String> lines, ResolvableType valueType, boolean shouldWrap, <add> @Nullable <add> private Object buildEvent(List<String> lines, ResolvableType valueType, boolean shouldWrap, <ide> Map<String, Object> hints) { <ide> <ide> ServerSentEvent.Builder<Object> sseBuilder = shouldWrap ? ServerSentEvent.builder() : null; <ide> else if (line.startsWith(":")) { <ide> } <ide> } <ide> <del> Mono<?> decodedData = (data != null ? decodeData(data.toString(), valueType, hints) : Mono.empty()); <add> Object decodedData = data != null ? decodeData(data.toString(), valueType, hints) : null; <ide> <ide> if (shouldWrap) { <ide> if (comment != null) { <ide> sseBuilder.comment(comment.toString().substring(0, comment.length() - 1)); <ide> } <del> return decodedData.map(o -> { <del> sseBuilder.data(o); <del> return sseBuilder.build(); <del> }); <add> if (decodedData != null) { <add> sseBuilder.data(decodedData); <add> } <add> return sseBuilder.build(); <ide> } <ide> else { <ide> return decodedData; <ide> } <ide> } <ide> <del> private Mono<?> decodeData(String data, ResolvableType dataType, Map<String, Object> hints) { <add> private Object decodeData(String data, ResolvableType dataType, Map<String, Object> hints) { <ide> if (String.class == dataType.resolve()) { <del> return Mono.just(data.substring(0, data.length() - 1)); <add> return data.substring(0, data.length() - 1); <ide> } <del> <ide> if (this.decoder == null) { <del> return Mono.error(new CodecException("No SSE decoder configured and the data is not String.")); <add> throw new CodecException("No SSE decoder configured and the data is not String."); <ide> } <del> <ide> byte[] bytes = data.getBytes(StandardCharsets.UTF_8); <ide> DataBuffer buffer = bufferFactory.wrap(bytes); // wrapping only, no allocation <del> return this.decoder.decodeToMono(Mono.just(buffer), dataType, MediaType.TEXT_EVENT_STREAM, hints); <add> return this.decoder.decode(buffer, dataType, MediaType.TEXT_EVENT_STREAM, hints); <ide> } <ide> <ide> @Override
3
Python
Python
use getfullargspec for python 3. closes
c67de364262def9045cde5318a811d05adc169e5
<ide><path>celery/contrib/sphinx.py <ide> """ <ide> from __future__ import absolute_import <ide> <del>from inspect import formatargspec, getargspec <add>try: <add> from inspect import formatargspec, getfullargspec as getargspec <add>except ImportError: # Py2 <add> from inspect import formatargspec, getargspec # noqa <ide> <ide> from sphinx.domains.python import PyModulelevel <ide> from sphinx.ext.autodoc import FunctionDocumenter
1
Python
Python
disallow any dag tags longer than 100 char
4b28635b2085a07047c398be6cc1ac0252a691f7
<ide><path>airflow/models/dag.py <ide> DEFAULT_VIEW_PRESETS = ['grid', 'graph', 'duration', 'gantt', 'landing_times'] <ide> ORIENTATION_PRESETS = ['LR', 'TB', 'RL', 'BT'] <ide> <add>TAG_MAX_LEN = 100 <ide> <ide> DagStateChangeCallback = Callable[[Context], None] <ide> ScheduleInterval = Union[None, str, timedelta, relativedelta] <ide> def __init__( <ide> ): <ide> from airflow.utils.task_group import TaskGroup <ide> <add> if tags and any(len(tag) > TAG_MAX_LEN for tag in tags): <add> raise AirflowException(f"tag cannot be longer than {TAG_MAX_LEN} characters") <add> <ide> self.user_defined_macros = user_defined_macros <ide> self.user_defined_filters = user_defined_filters <ide> if default_args and not isinstance(default_args, dict): <ide> class DagTag(Base): <ide> """A tag name per dag, to allow quick filtering in the DAG view.""" <ide> <ide> __tablename__ = "dag_tag" <del> name = Column(String(100), primary_key=True) <add> name = Column(String(TAG_MAX_LEN), primary_key=True) <ide> dag_id = Column( <ide> String(ID_LEN), <ide> ForeignKey('dag.dag_id', name='dag_tag_dag_id_fkey', ondelete='CASCADE'), <ide><path>tests/models/test_dag.py <ide> def test__time_restriction(dag_maker, dag_date, tasks_date, restrict): <ide> assert dag._time_restriction == restrict <ide> <ide> <add>@pytest.mark.parametrize( <add> 'tags, should_pass', <add> [ <add> pytest.param([], True, id="empty tags"), <add> pytest.param(['a normal tag'], True, id="one tag"), <add> pytest.param(['a normal tag', 'another normal tag'], True, id="two tags"), <add> pytest.param(['a' * 100], True, id="a tag that's of just length 100"), <add> pytest.param(['a normal tag', 'a' * 101], False, id="two tags and one of them is of length > 100"), <add> ], <add>) <add>def test__tags_length(tags: List[str], should_pass: bool): <add> if should_pass: <add> models.DAG('test-dag', tags=tags) <add> else: <add> with pytest.raises(AirflowException): <add> models.DAG('test-dag', tags=tags) <add> <add> <ide> @pytest.fixture() <ide> def reset_dataset(): <ide> clear_db_datasets()
2
Java
Java
add genericconversionservice jmh benchmark
212bb7fef65a21fc367f5ee341d5f9f52c112d46
<ide><path>spring-core/src/jmh/java/org/springframework/core/convert/support/GenericConversionServiceBenchmark.java <add>/* <add> * Copyright 2002-2020 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://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> <add>package org.springframework.core.convert.support; <add> <add>import java.util.ArrayList; <add>import java.util.HashMap; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.stream.Collectors; <add>import java.util.stream.IntStream; <add> <add>import org.openjdk.jmh.annotations.Benchmark; <add>import org.openjdk.jmh.annotations.BenchmarkMode; <add>import org.openjdk.jmh.annotations.Level; <add>import org.openjdk.jmh.annotations.Mode; <add>import org.openjdk.jmh.annotations.Param; <add>import org.openjdk.jmh.annotations.Scope; <add>import org.openjdk.jmh.annotations.Setup; <add>import org.openjdk.jmh.annotations.State; <add>import org.openjdk.jmh.infra.Blackhole; <add> <add>import org.springframework.core.convert.TypeDescriptor; <add> <add>/** <add> * Benchmarks for {@link GenericConversionService}. <add> * @author Brian Clozel <add> */ <add>@BenchmarkMode(Mode.Throughput) <add>public class GenericConversionServiceBenchmark { <add> <add> @Benchmark <add> public void convertListOfStringToListOfIntegerWithConversionService(ListBenchmarkState state, Blackhole bh) { <add> TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(state.source); <add> bh.consume(state.conversionService.convert(state.source, sourceTypeDesc, state.targetTypeDesc)); <add> } <add> <add> @Benchmark <add> public void convertListOfStringToListOfIntegerBaseline(ListBenchmarkState state, Blackhole bh) { <add> List<Integer> target = new ArrayList<>(state.source.size()); <add> for (String element : state.source) { <add> target.add(Integer.valueOf(element)); <add> } <add> bh.consume(target); <add> } <add> <add> @State(Scope.Benchmark) <add> public static class ListBenchmarkState extends BenchmarkState { <add> <add> List<String> source; <add> <add> @Setup(Level.Trial) <add> public void setup() throws Exception { <add> this.source = IntStream.rangeClosed(1, collectionSize).mapToObj(String::valueOf).collect(Collectors.toList()); <add> List<Integer> target = new ArrayList<>(); <add> this.targetTypeDesc = TypeDescriptor.forObject(target); <add> } <add> } <add> <add> @Benchmark <add> public void convertMapOfStringToListOfIntegerWithConversionService(MapBenchmarkState state, Blackhole bh) { <add> TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(state.source); <add> bh.consume(state.conversionService.convert(state.source, sourceTypeDesc, state.targetTypeDesc)); <add> } <add> <add> @Benchmark <add> public void convertMapOfStringToListOfIntegerBaseline(MapBenchmarkState state, Blackhole bh) { <add> Map<String, Integer> target = new HashMap<>(state.source.size()); <add> state.source.forEach((k, v) -> target.put(k, Integer.valueOf(v))); <add> bh.consume(target); <add> } <add> <add> @State(Scope.Benchmark) <add> public static class MapBenchmarkState extends BenchmarkState { <add> <add> Map<String, String> source; <add> <add> @Setup(Level.Trial) <add> public void setup() throws Exception { <add> this.source = new HashMap<>(this.collectionSize); <add> Map<String, Integer> target = new HashMap<>(); <add> this.targetTypeDesc = TypeDescriptor.forObject(target); <add> this.source = IntStream.rangeClosed(1, collectionSize).mapToObj(String::valueOf) <add> .collect(Collectors.toMap(String::valueOf, String::valueOf)); <add> } <add> } <add> <add> @State(Scope.Benchmark) <add> public static class BenchmarkState { <add> <add> GenericConversionService conversionService = new GenericConversionService(); <add> <add> @Param({"10"}) <add> int collectionSize; <add> <add> TypeDescriptor targetTypeDesc; <add> <add> } <add>} <ide><path>spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java <ide> import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.LinkedHashMap; <del>import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <ide> import org.springframework.core.convert.converter.GenericConverter; <ide> import org.springframework.core.io.DescriptiveResource; <ide> import org.springframework.core.io.Resource; <del>import org.springframework.core.testfixture.EnabledForTestGroups; <ide> import org.springframework.lang.Nullable; <del>import org.springframework.util.StopWatch; <ide> import org.springframework.util.StringUtils; <ide> <ide> import static java.util.Comparator.naturalOrder; <ide> import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <ide> import static org.assertj.core.api.Assertions.assertThatIllegalStateException; <del>import static org.springframework.core.testfixture.TestGroup.PERFORMANCE; <ide> <ide> /** <ide> * Unit tests for {@link GenericConversionService}. <ide> void ignoreCopyConstructor() { <ide> assertThat(result).isSameAs(value); <ide> } <ide> <del> @Test <del> @EnabledForTestGroups(PERFORMANCE) <del> void testPerformance2() throws Exception { <del> StopWatch watch = new StopWatch("list<string> -> list<integer> conversionPerformance"); <del> watch.start("convert 4,000,000 with conversion service"); <del> List<String> source = new LinkedList<>(); <del> source.add("1"); <del> source.add("2"); <del> source.add("3"); <del> TypeDescriptor td = new TypeDescriptor(getClass().getField("list")); <del> for (int i = 0; i < 1000000; i++) { <del> conversionService.convert(source, TypeDescriptor.forObject(source), td); <del> } <del> watch.stop(); <del> watch.start("convert 4,000,000 manually"); <del> for (int i = 0; i < 4000000; i++) { <del> List<Integer> target = new ArrayList<>(source.size()); <del> for (String element : source) { <del> target.add(Integer.valueOf(element)); <del> } <del> } <del> watch.stop(); <del> // System.out.println(watch.prettyPrint()); <del> } <del> <del> @Test <del> @EnabledForTestGroups(PERFORMANCE) <del> void testPerformance3() throws Exception { <del> StopWatch watch = new StopWatch("map<string, string> -> map<string, integer> conversionPerformance"); <del> watch.start("convert 4,000,000 with conversion service"); <del> Map<String, String> source = new HashMap<>(); <del> source.put("1", "1"); <del> source.put("2", "2"); <del> source.put("3", "3"); <del> TypeDescriptor td = new TypeDescriptor(getClass().getField("map")); <del> for (int i = 0; i < 1000000; i++) { <del> conversionService.convert(source, TypeDescriptor.forObject(source), td); <del> } <del> watch.stop(); <del> watch.start("convert 4,000,000 manually"); <del> for (int i = 0; i < 4000000; i++) { <del> Map<String, Integer> target = new HashMap<>(source.size()); <del> source.forEach((k, v) -> target.put(k, Integer.valueOf(v))); <del> } <del> watch.stop(); <del> // System.out.println(watch.prettyPrint()); <del> } <del> <ide> @Test <ide> void emptyListToArray() { <ide> conversionService.addConverter(new CollectionToArrayConverter(conversionService)); <ide> void rawCollectionAsSource() throws Exception { <ide> @ExampleAnnotation(active = false) <ide> public Color inactiveColor; <ide> <del> public List<Integer> list; <del> <del> public Map<String, Integer> map; <del> <ide> public Map<String, ?> wildcardMap; <ide> <ide> @SuppressWarnings("rawtypes")
2
PHP
PHP
add missing public methods to interface
e4f477c42d3e24f6cdf44a45801c0db476ad2b91
<ide><path>src/Illuminate/Routing/CompiledRouteCollection.php <ide> public function add(Route $route) <ide> return $route; <ide> } <ide> <add> /** <add> * Refresh the name look-up table. <add> * <add> * This is done in case any names are fluently defined or if routes are overwritten. <add> * <add> * @return void <add> */ <add> public function refreshNameLookups() <add> { <add> // <add> } <add> <add> /** <add> * Refresh the action look-up table. <add> * <add> * This is done in case any actions are overwritten with new controllers. <add> * <add> * @return void <add> */ <add> public function refreshActionLookups() <add> { <add> // <add> } <add> <ide> /** <ide> * Find the first route matching a given request. <ide> * <ide><path>src/Illuminate/Routing/RouteCollectionInterface.php <ide> interface RouteCollectionInterface <ide> */ <ide> public function add(Route $route); <ide> <add> /** <add> * Refresh the name look-up table. <add> * <add> * This is done in case any names are fluently defined or if routes are overwritten. <add> * <add> * @return void <add> */ <add> public function refreshNameLookups(); <add> <add> /** <add> * Refresh the action look-up table. <add> * <add> * This is done in case any actions are overwritten with new controllers. <add> * <add> * @return void <add> */ <add> public function refreshActionLookups(); <add> <ide> /** <ide> * Find the first route matching a given request. <ide> *
2
Javascript
Javascript
remove ember from namespace list
507196da7be456628202e93525a30e13a2cc9a1d
<ide><path>packages/ember-extension-support/lib/container_debug_adapter.js <ide> export default EmberObject.extend({ <ide> let typeSuffixRegex = new RegExp(`${StringUtils.classify(type)}$`); <ide> <ide> namespaces.forEach(namespace => { <del> if (namespace.toString() !== 'Ember') { <del> for (let key in namespace) { <del> if (!namespace.hasOwnProperty(key)) { continue; } <del> if (typeSuffixRegex.test(key)) { <del> let klass = namespace[key]; <del> if (typeOf(klass) === 'class') { <del> types.push(StringUtils.dasherize(key.replace(typeSuffixRegex, ''))); <del> } <add> for (let key in namespace) { <add> if (!namespace.hasOwnProperty(key)) { continue; } <add> if (typeSuffixRegex.test(key)) { <add> let klass = namespace[key]; <add> if (typeOf(klass) === 'class') { <add> types.push(StringUtils.dasherize(key.replace(typeSuffixRegex, ''))); <ide> } <ide> } <ide> } <ide><path>packages/ember-runtime/lib/system/namespace.js <ide> @module ember <ide> */ <ide> import { guidFor } from 'ember-utils'; <del>import Ember, { <add>import { <ide> get, <ide> Mixin, <ide> hasUnprocessedMixins, <ide> const Namespace = EmberObject.extend({ <ide> }); <ide> <ide> Namespace.reopenClass({ <del> NAMESPACES: [Ember], <del> NAMESPACES_BY_ID: { <del> Ember <del> }, <add> NAMESPACES: [], <add> NAMESPACES_BY_ID: {}, <ide> PROCESSED: false, <ide> processAll: processAllNamespaces, <ide> byName(name) {
2
Python
Python
remove misleading message from ci
ac104025f45b54efff26407e460a5e4279c6495b
<ide><path>dev/breeze/src/airflow_breeze/utils/path_utils.py <ide> def create_volume_if_missing(volume_name: str): <ide> from airflow_breeze.utils.run_utils import run_command <ide> <ide> res_inspect = run_command( <del> cmd=["docker", "volume", "inspect", volume_name], stdout=subprocess.DEVNULL, check=False <add> cmd=["docker", "volume", "inspect", volume_name], <add> stdout=subprocess.DEVNULL, <add> stderr=subprocess.DEVNULL, <add> check=False, <ide> ) <ide> if res_inspect.returncode != 0: <del> run_command(cmd=["docker", "volume", "create", volume_name], check=True) <add> run_command( <add> cmd=["docker", "volume", "create", volume_name], <add> stdout=subprocess.DEVNULL, <add> stderr=subprocess.DEVNULL, <add> check=True, <add> ) <ide> <ide> <ide> def create_static_check_volumes():
1
Javascript
Javascript
update event names in pointer event platform tests
ff6c906a66037c423ff4b739d683e9fe1042b673
<ide><path>packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventAttributesHoverablePointers.js <ide> const UNINITIALIZED_LAYOUT: Layout = { <ide> height: NaN, <ide> }; <ide> <del>// TODO: remove number suffixes <ide> const eventList = [ <ide> 'pointerOver', <del> 'pointerEnter2', <del> 'pointerMove2', <add> 'pointerEnter', <add> 'pointerMove', <ide> 'pointerDown', <ide> 'pointerUp', <ide> 'pointerOut', <del> 'pointerLeave2', <add> 'pointerLeave', <ide> ]; <ide> <ide> function PointerEventAttributesHoverablePointersTestCase(
1
PHP
PHP
normalize paths better
5a728f4445238c40a763844037179da493d6bcf7
<ide><path>src/Core/functions.php <ide> function deprecationWarning(string $message, int $stackFrame = 1): void <ide> $frame += ['file' => '[internal]', 'line' => '??']; <ide> <ide> $patterns = (array)Configure::read('Error.disableDeprecations'); <del> $relative = substr($frame['file'], strlen(ROOT) + 1); <add> $relative = str_replace('/', DIRECTORY_SEPARATOR, substr($frame['file'], strlen(ROOT) + 1)); <ide> foreach ($patterns as $pattern) { <ide> $pattern = str_replace('/', DIRECTORY_SEPARATOR, $pattern); <ide> if (fnmatch($pattern, $relative)) { <ide> function deprecationWarning(string $message, int $stackFrame = 1): void <ide> $message = sprintf( <ide> '%s - %s, line: %s' . "\n" . <ide> ' You can disable deprecation warnings by setting `Error.errorLevel` to' . <del> " `E_ALL & ~E_USER_DEPRECATED`, or add `{$relative}` to " . <add> " `E_ALL & ~E_USER_DEPRECATED`, or add `%s` to " . <ide> ' `Error.disableDeprecations` in your `config/app.php` to mute deprecations.', <ide> $message, <ide> $frame['file'], <del> $frame['line'] <add> $frame['line'], <add> str_replace(DIRECTORY_SEPARATOR, '/', $relative) <ide> ); <ide> } <ide>
1
Javascript
Javascript
use stronger curves for keygen
8b2e861da1da827cf8c581efbfd126907df9b593
<ide><path>test/parallel/test-crypto-keygen.js <ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); <ide> // Test async elliptic curve key generation, e.g. for ECDSA, with an encrypted <ide> // private key. <ide> generateKeyPair('ec', { <del> namedCurve: 'P-192', <add> namedCurve: 'P-256', <ide> paramEncoding: 'named', <ide> publicKeyEncoding: { <ide> type: 'spki', <ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher); <ide> <ide> // It should recognize both NIST and standard curve names. <ide> generateKeyPair('ec', { <del> namedCurve: 'P-192', <add> namedCurve: 'P-256', <ide> publicKeyEncoding: { type: 'spki', format: 'pem' }, <ide> privateKeyEncoding: { type: 'pkcs8', format: 'pem' } <ide> }, common.mustCall((err, publicKey, privateKey) => { <ide> assert.ifError(err); <ide> })); <ide> <ide> generateKeyPair('ec', { <del> namedCurve: 'secp192k1', <add> namedCurve: 'secp256k1', <ide> publicKeyEncoding: { type: 'spki', format: 'pem' }, <ide> privateKeyEncoding: { type: 'pkcs8', format: 'pem' } <ide> }, common.mustCall((err, publicKey, privateKey) => {
1
Java
Java
optimize allocation in stringutils#cleanpath
8d3e8ca3a2d534f6ee872bb6a65a89c44e987cf6
<ide><path>spring-core/src/main/java/org/springframework/util/StringUtils.java <ide> public static String cleanPath(String path) { <ide> if (!hasLength(path)) { <ide> return path; <ide> } <del> String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); <add> <add> String normalizedPath = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); <add> String pathToUse = normalizedPath; <ide> <ide> // Shortcut if there is no work to do <ide> if (pathToUse.indexOf('.') == -1) { <ide> public static String cleanPath(String path) { <ide> } <ide> <ide> String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); <del> Deque<String> pathElements = new ArrayDeque<>(); <add> // we never require more elements than pathArray and in the common case the same number <add> Deque<String> pathElements = new ArrayDeque<>(pathArray.length); <ide> int tops = 0; <ide> <ide> for (int i = pathArray.length - 1; i >= 0; i--) { <ide> else if (TOP_PATH.equals(element)) { <ide> <ide> // All path elements stayed the same - shortcut <ide> if (pathArray.length == pathElements.size()) { <del> return prefix + pathToUse; <add> return normalizedPath; <ide> } <ide> // Remaining top paths need to be retained. <ide> for (int i = 0; i < tops; i++) { <ide> else if (TOP_PATH.equals(element)) { <ide> pathElements.addFirst(CURRENT_PATH); <ide> } <ide> <del> return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); <add> final String joined = joinStrings(pathElements, FOLDER_SEPARATOR); <add> // avoid string concatenation with empty prefix <add> return prefix.isEmpty() ? joined : prefix + joined; <add> } <add> <add> /** <add> * Convert a {@link Collection Collection&lt;String&gt;} to a delimited {@code String} (e.g. CSV). <add> * <p>This is an optimized variant of {@link #collectionToDelimitedString(Collection, String)}, which does not <add> * require dynamic resizing of the StringBuilder's backing array. <add> * @param coll the {@code Collection Collection&lt;String&gt;} to convert (potentially {@code null} or empty) <add> * @param delim the delimiter to use (typically a ",") <add> * @return the delimited {@code String} <add> */ <add> private static String joinStrings(@Nullable Collection<String> coll, String delim) { <add> <add> if (CollectionUtils.isEmpty(coll)) { <add> return ""; <add> } <add> <add> // precompute total length of resulting string <add> int totalLength = (coll.size() - 1) * delim.length(); <add> for (String str : coll) { <add> totalLength += str.length(); <add> } <add> <add> StringBuilder sb = new StringBuilder(totalLength); <add> Iterator<?> it = coll.iterator(); <add> while (it.hasNext()) { <add> sb.append(it.next()); <add> if (it.hasNext()) { <add> sb.append(delim); <add> } <add> } <add> return sb.toString(); <ide> } <ide> <ide> /** <ide><path>spring-core/src/test/java/org/springframework/util/StringUtilsTests.java <ide> void cleanPath() { <ide> assertThat(StringUtils.cleanPath("file:.././")).isEqualTo("file:../"); <ide> assertThat(StringUtils.cleanPath("file:/mypath/spring.factories")).isEqualTo("file:/mypath/spring.factories"); <ide> assertThat(StringUtils.cleanPath("file:///c:/some/../path/the%20file.txt")).isEqualTo("file:///c:/path/the%20file.txt"); <add> assertThat(StringUtils.cleanPath("jar:file:///c:\\some\\..\\path\\.\\the%20file.txt")).isEqualTo("jar:file:///c:/path/the%20file.txt"); <add> assertThat(StringUtils.cleanPath("jar:file:///c:/some/../path/./the%20file.txt")).isEqualTo("jar:file:///c:/path/the%20file.txt"); <ide> } <ide> <ide> @Test
2
Java
Java
fix cronexpression issue with zoneddatetime & dst
ab18ab60250e256da4b1502e1786b168c374a229
<ide><path>spring-context/src/main/java/org/springframework/scheduling/support/CronField.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public int checkValidValue(int value) { <ide> public <T extends Temporal & Comparable<? super T>> T elapseUntil(T temporal, int goal) { <ide> int current = get(temporal); <ide> if (current < goal) { <del> return this.field.getBaseUnit().addTo(temporal, goal - current); <add> T result = this.field.getBaseUnit().addTo(temporal, goal - current); <add> current = get(result); <add> if (current > goal) { // can occur due to daylight saving, see gh-26744 <add> result = this.field.getBaseUnit().addTo(result, goal - current); <add> } <add> return result; <ide> } <ide> else { <ide> ValueRange range = temporal.range(this.field); <ide><path>spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void sundayToFriday() { <ide> assertThat(actual.getDayOfWeek()).isEqualTo(SUNDAY); <ide> } <ide> <add> @Test <add> public void daylightSaving() { <add> CronExpression cronExpression = CronExpression.parse("0 0 9 * * *"); <add> <add> ZonedDateTime last = ZonedDateTime.parse("2021-03-27T09:00:00+01:00[Europe/Amsterdam]"); <add> ZonedDateTime expected = ZonedDateTime.parse("2021-03-28T09:00:00+01:00[Europe/Amsterdam]"); <add> ZonedDateTime actual = cronExpression.next(last); <add> assertThat(actual).isNotNull(); <add> assertThat(actual).isEqualTo(expected); <add> <add> last = ZonedDateTime.parse("2021-10-30T09:00:00+01:00[Europe/Amsterdam]"); <add> expected = ZonedDateTime.parse("2021-10-31T09:00:00+02:00[Europe/Amsterdam]"); <add> actual = cronExpression.next(last); <add> assertThat(actual).isNotNull(); <add> assertThat(actual).isEqualTo(expected); <add> } <add> <ide> <ide> <ide> }
2
Text
Text
release notes for 1.2.14 feisty-cryokinesis
729fb13c9ef4181cce0a2d96529ec3a8479601be
<ide><path>CHANGELOG.md <add><a name="1.2.14"></a> <add># 1.2.14 feisty-cryokinesis (2014-03-01) <add> <add> <add>## Bug Fixes <add> <add>- **$animate:** <add> - delegate down to addClass/removeClass if setClass is not found <add> ([18c41af0](https://github.com/angular/angular.js/commit/18c41af065006a804a3d38eecca7ae184103ece9), <add> [#6463](https://github.com/angular/angular.js/issues/6463)) <add> - ensure all comment nodes are removed during a leave animation <add> ([f4f1f43d](https://github.com/angular/angular.js/commit/f4f1f43d5140385bbf070510975f72b65196e08a), <add> [#6403](https://github.com/angular/angular.js/issues/6403)) <add> - only block keyframes if a stagger is set to occur <add> ([e71e7b6c](https://github.com/angular/angular.js/commit/e71e7b6cae57f25c5837dda98551c8e0a5cb720d), <add> [#4225](https://github.com/angular/angular.js/issues/4225)) <add> - ensure that animateable directives cancel expired leave animations <add> ([e9881991](https://github.com/angular/angular.js/commit/e9881991ca0a5019d3a4215477738ed247898ba0), <add> [#5886](https://github.com/angular/angular.js/issues/5886)) <add> - ensure all animated elements are taken care of during the closing timeout <add> ([99720fb5](https://github.com/angular/angular.js/commit/99720fb5ab7259af37f708bc4eeda7cbbe790a69), <add> [#6395](https://github.com/angular/angular.js/issues/6395)) <add> - fix for TypeError Cannot call method 'querySelectorAll' in cancelChildAnimations <add> ([c914cd99](https://github.com/angular/angular.js/commit/c914cd99b3aaf932e3c0e2a585eead7b76621f1b), <add> [#6205](https://github.com/angular/angular.js/issues/6205)) <add>- **$http:** <add> - do not add trailing question <add> ([c8e03e34](https://github.com/angular/angular.js/commit/c8e03e34b27a8449d8e1bfe0e3801d6a67ae2c49), <add> [#6342](https://github.com/angular/angular.js/issues/6342)) <add> - send GET requests by default <add> ([267b2173](https://github.com/angular/angular.js/commit/267b217376ed466e9f260ecfdfa15a8227c103ff), <add> [#5985](https://github.com/angular/angular.js/issues/5985), [#6401](https://github.com/angular/angular.js/issues/6401)) <add>- **$parse:** reduce false-positives in isElement tests <add> ([5fe1f39f](https://github.com/angular/angular.js/commit/5fe1f39f027c6f2c6a530975dd5389d788d3c0eb), <add> [#4805](https://github.com/angular/angular.js/issues/4805), [#5675](https://github.com/angular/angular.js/issues/5675)) <add>- **input:** use ValidityState to determine validity <add> ([c2d447e3](https://github.com/angular/angular.js/commit/c2d447e378dd72d1b955f476bd5bf249625b4dab), <add> [#4293](https://github.com/angular/angular.js/issues/4293), [#2144](https://github.com/angular/angular.js/issues/2144), [#4857](https://github.com/angular/angular.js/issues/4857), [#5120](https://github.com/angular/angular.js/issues/5120), [#4945](https://github.com/angular/angular.js/issues/4945), [#5500](https://github.com/angular/angular.js/issues/5500), [#5944](https://github.com/angular/angular.js/issues/5944)) <add>- **isElement:** reduce false-positives in isElement tests <add> ([75515852](https://github.com/angular/angular.js/commit/75515852ea9742d3d84a0f463c2a2c61ef2b7323)) <add>- **jqLite:** <add> - properly toggle multiple classes <add> ([4e73c80b](https://github.com/angular/angular.js/commit/4e73c80b17bd237a8491782bcf9e19f1889e12ed), <add> [#4467](https://github.com/angular/angular.js/issues/4467), [#6448](https://github.com/angular/angular.js/issues/6448)) <add> - make jqLite('<iframe src="someurl">').contents() return iframe document, as in jQuery <add> ([05fbed57](https://github.com/angular/angular.js/commit/05fbed5710b702c111c1425a9e241c40d13b0a54), <add> [#6320](https://github.com/angular/angular.js/issues/6320), [#6323](https://github.com/angular/angular.js/issues/6323)) <add>- **numberFilter:** convert all non-finite/non-numbers/non-numeric strings to the empty string <add> ([cceb455f](https://github.com/angular/angular.js/commit/cceb455fb167571e26341ded6b595dafd4d92bc6), <add> [#6188](https://github.com/angular/angular.js/issues/6188), [#6261](https://github.com/angular/angular.js/issues/6261)) <add>- **$parse:** support trailing commas in object & array literals <add> ([6b049c74](https://github.com/angular/angular.js/commit/6b049c74ccc9ee19688bb9bbe504c300e61776dc)) <add>- **ngHref:** bind ng-href to xlink:href for SVGAElement <add> ([2bce71e9](https://github.com/angular/angular.js/commit/2bce71e9dc10c8588f9eb599a0cd2e831440fc48), <add> [#5904](https://github.com/angular/angular.js/issues/5904)) <add> <add> <add>## Features <add> <add>- **$animate:** animate dirty, pristine, valid, invalid for form/fields <add> ([33443966](https://github.com/angular/angular.js/commit/33443966c8e8cac85a863bb181d4a4aff00baab4), <add> [#5378](https://github.com/angular/angular.js/issues/5378)) <add> <add> <add>## Performance Improvements <add> <add>- **$animate:** use rAF instead of timeouts to issue animation callbacks <add> ([4c4537e6](https://github.com/angular/angular.js/commit/4c4537e65e6cf911c9659b562d89e3330ce3ffae)) <add>- **$cacheFactory:** skip LRU bookkeeping for caches with unbound capacity <add> ([a4078fca](https://github.com/angular/angular.js/commit/a4078fcae4a33295675d769a1cd067837029da2f), <add> [#6193](https://github.com/angular/angular.js/issues/6193), [#6226](https://github.com/angular/angular.js/issues/6226)) <add> <add> <add> <ide> <a name="1.2.13"></a> <ide> # 1.2.13 romantic-transclusion (2014-02-14) <ide> <ide> The animation mock module has been renamed from `mock.animate` to `ngAnimateMock <ide> <ide> - **$http:** due to [e1cfb195](https://github.com/angular/angular.js/commit/e1cfb1957feaf89408bccf48fae6f529e57a82fe), <ide> it is now necessary to separately specify default HTTP headers for PUT, POST and PATCH requests, as these no longer share a single object. <del> <add> <ide> To migrate your code, follow the example below: <del> <add> <ide> Before: <del> <add> <ide> // Will apply to POST, PUT and PATCH methods <ide> $httpProvider.defaults.headers.post = { <ide> "X-MY-CSRF-HEADER": "..."
1
Mixed
Python
add scores to output in spancat
6029cfc3912ba331168fcac71147efd525b51ba6
<ide><path>spacy/pipeline/spancat.py <ide> def _make_span_group( <ide> spans = SpanGroup(doc, name=self.key) <ide> max_positive = self.cfg["max_positive"] <ide> threshold = self.cfg["threshold"] <add> <add> keeps = scores >= threshold <add> ranked = (scores * -1).argsort() <add> keeps[ranked[:, max_positive:]] = False <add> spans.attrs["scores"] = scores[keeps].flatten() <add> <add> indices = self.model.ops.to_numpy(indices) <add> keeps = self.model.ops.to_numpy(keeps) <add> <ide> for i in range(indices.shape[0]): <del> start = int(indices[i, 0]) <del> end = int(indices[i, 1]) <del> positives = [] <del> for j, score in enumerate(scores[i]): <del> if score >= threshold: <del> positives.append((score, start, end, labels[j])) <del> positives.sort(reverse=True) <del> if max_positive: <del> positives = positives[:max_positive] <del> for score, start, end, label in positives: <del> spans.append(Span(doc, start, end, label=label)) <add> start = indices[i, 0] <add> end = indices[i, 1] <add> <add> for j, keep in enumerate(keeps[i]): <add> if keep: <add> spans.append(Span(doc, start, end, label=labels[j])) <add> <ide> return spans <ide><path>spacy/tests/pipeline/test_spancat.py <ide> def test_simple_train(): <ide> doc = nlp("I like London and Berlin.") <ide> assert doc.spans[spancat.key] == doc.spans[SPAN_KEY] <ide> assert len(doc.spans[spancat.key]) == 2 <add> assert len(doc.spans[spancat.key].attrs["scores"]) == 2 <ide> assert doc.spans[spancat.key][0].text == "London" <ide> scores = nlp.evaluate(get_examples()) <ide> assert f"spans_{SPAN_KEY}_f" in scores <ide> assert scores[f"spans_{SPAN_KEY}_f"] == 1.0 <ide> <ide> <add> <ide> def test_ngram_suggester(en_tokenizer): <ide> # test different n-gram lengths <ide> for size in [1, 2, 3]: <ide><path>website/docs/api/spancategorizer.md <ide> A span categorizer consists of two parts: a [suggester function](#suggesters) <ide> that proposes candidate spans, which may or may not overlap, and a labeler model <ide> that predicts zero or more labels for each candidate. <ide> <add>Predicted spans will be saved in a [`SpanGroup`](/api/spangroup) on the doc. <add>Individual span scores can be found in `spangroup.attrs["scores"]`. <add> <add>## Assigned Attributes {#assigned-attributes} <add> <add>Predictions will be saved to `Doc.spans[spans_key]` as a <add>[`SpanGroup`](/api/spangroup). The scores for the spans in the `SpanGroup` will <add>be saved in `SpanGroup.attrs["scores"]`. <add> <add>`spans_key` defaults to `"sc"`, but can be passed as a parameter. <add> <add>| Location | Value | <add>| -------------------------------------- | -------------------------------------------------------- | <add>| `Doc.spans[spans_key]` | The annotated spans. ~~SpanGroup~~ | <add>| `Doc.spans[spans_key].attrs["scores"]` | The score for each span in the `SpanGroup`. ~~Floats1d~~ | <add> <ide> ## Config and implementation {#config} <ide> <ide> The default config is defined by the pipeline component factory and describes
3
Javascript
Javascript
add test cases for
e4dfd201f17db9885bee636d99d3fb169ad39450
<ide><path>test/configCases/plugins/define-plugin/index.js <ide> it("should define OBJECT.SUB.CODE", function() { <ide> sub.CODE.should.be.eql(3); <ide> }(OBJECT.SUB)); <ide> }); <add>it("should define OBJECT.SUB.STRING", function() { <add> (typeof OBJECT.SUB.STRING).should.be.eql("string"); <add> OBJECT.SUB.STRING.should.be.eql("string"); <add> if(OBJECT.SUB.STRING !== "string") require("fail"); <add> if(typeof OBJECT.SUB.STRING !== "string") require("fail"); <add> <add> (function(sub) { <add> // should not crash <add> sub.STRING.should.be.eql("string"); <add> }(OBJECT.SUB)); <add>}); <ide> it("should define process.env.DEFINED_NESTED_KEY", function() { <ide> (process.env.DEFINED_NESTED_KEY).should.be.eql(5); <ide> (typeof process.env.DEFINED_NESTED_KEY).should.be.eql("number"); <ide> it("should define process.env.DEFINED_NESTED_KEY", function() { <ide> var x = env.DEFINED_NESTED_KEY; <ide> x.should.be.eql(5); <ide> }(process.env)); <del>}); <ide>\ No newline at end of file <add>}); <add>it("should define process.env.DEFINED_NESTED_KEY_STRING", function() { <add> if(process.env.DEFINED_NESTED_KEY_STRING !== "string") require("fail"); <add>}) <ide><path>test/configCases/plugins/define-plugin/webpack.config.js <ide> module.exports = { <ide> UNDEFINED: undefined, <ide> FUNCTION: function(a) { return a + 1; }, <ide> CODE: "(1+2)", <del> REGEXP: /abc/i <add> REGEXP: /abc/i, <add> STRING: JSON.stringify("string") <ide> } <ide> }, <del> "process.env.DEFINED_NESTED_KEY": 5 <add> "process.env.DEFINED_NESTED_KEY": 5, <add> "process.env.DEFINED_NESTED_KEY_STRING": "\"string\"" <ide> }) <ide> ] <ide> }
2
Javascript
Javascript
fix $on listener signature doc
4ccd9eb88321f8554ee4dc41b7f8068ce2306765
<ide><path>src/ng/rootScope.js <ide> function $RootScopeProvider(){ <ide> * @param {function(event)} listener Function to call when the event is emitted. <ide> * @returns {function()} Returns a deregistration function for this listener. <ide> * <del> * The event listener function format is: `function(event)`. The `event` object passed into the <del> * listener has the following attributes <add> * The event listener function format is: `function(event, args...)`. The `event` object <add> * passed into the listener has the following attributes: <ide> * <ide> * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed. <ide> * - `currentScope` - {Scope}: the current scope which is handling the event.
1
Python
Python
remove unused import statement
79c133143297a37b630f791b02c88d58579e05ef
<ide><path>examples/imdb_fasttext.py <ide> from keras.layers import Embedding <ide> from keras.layers import GlobalAveragePooling1D <ide> from keras.datasets import imdb <del>from keras import backend as K <ide> <ide> <ide> def create_ngram_set(input_list, ngram_value=2):
1
Text
Text
retranslate the sentence from english to chinese
a558b1ca65063631edcae1371c28dda06da950c3
<ide><path>guide/chinese/swift/variables/index.md <ide> localeTitle: 变量 <ide> <ide> 变量将名称与特定类型的值相关联。在Swift中,有两种主要的方法来创建变量。 `let`和`var` 。要声明常量,请使用`let`关键字。要声明可变变量,请使用`var`关键字。 <ide> <del>在Swift中存储变量的两种方法的好处是防止变化应该是常量的变量的错误。 <add>Swift中使用两种方式储存变量的好处是防止“改变常量值”这种错误。 <ide> <del>\`\`\`斯威夫特 让daysInAWeek = 7 var amountOfMoney = 100 <add>``` <add>let daysInAWeek = 7 <add>var amountOfMoney = 100 <ide> <ide> amountOfMoney = 150 // amountOfMoney现在是150 <ide> <ide> daysInAWeek = 10 //这给了我们一个错误! <ide> <del>\`\`\` <add>``` <ide> <ide> 在这种情况下,变量`daysInAWeek`应该是常量,因为一周只有七天,而变量`amountOfMoney`应该是var,因为一个帐户中的金额变化。 <ide> <ide> daysInAWeek = 10 //这给了我们一个错误! <ide> <ide> #### 更多信息: <ide> <del>* [Swift编程语言](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID310) <ide>\ No newline at end of file <add>* [Swift编程语言](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID310)
1
Javascript
Javascript
remove redundant 'animate' in link
ba9fb82f187b375ee9baedd834837b3bc5dd6b8a
<ide><path>src/ngAnimate/module.js <ide> * @description <ide> * The ngAnimate `$animate` service documentation is the same for the core `$animate` service. <ide> * <del> * Click here {@link ng.$animate $animate to learn more about animations with `$animate`}. <add> * Click here {@link ng.$animate to learn more about animations with `$animate`}. <ide> */ <ide> angular.module('ngAnimate', []) <ide> .provider('$$body', $$BodyProvider)
1
Python
Python
normalize device names in multi_gpu_model
7144aeb796d7e1bc6523bca8688dd3160d54e810
<ide><path>keras/utils/training_utils.py <ide> def _get_available_devices(): <ide> return [x.name for x in local_device_protos] <ide> <ide> <add>def _normalize_device_name(name): <add> name = name.lower().replace('device:', '') <add> return name <add> <add> <ide> def multi_gpu_model(model, gpus): <ide> """Replicates a model on different GPUs. <ide> <ide> def multi_gpu_model(model, gpus): <ide> <ide> target_devices = ['/cpu:0'] + ['/gpu:%d' % i for i in range(gpus)] <ide> available_devices = _get_available_devices() <add> available_devices = [_normalize_device_name(name) for name in available_devices] <ide> for device in target_devices: <ide> if device not in available_devices: <ide> raise ValueError(
1
PHP
PHP
fix psalm errors
dfb498f18b705d0467f9889ec4ba70abe92f74eb
<ide><path>src/Command/PluginAssetsCopyCommand.php <ide> <ide> /** <ide> * Command for copying plugin assets to app's webroot. <add> * <add> * @psalm-suppress PropertyNotSetInConstructor <ide> */ <ide> class PluginAssetsCopyCommand extends Command <ide> { <ide> public function execute(Arguments $args, ConsoleIo $io): ?int <ide> $this->args = $args; <ide> <ide> $name = $args->getArgument('name'); <del> $overwrite = $args->getOption('overwrite'); <add> $overwrite = (bool)$args->getOption('overwrite'); <ide> $this->_process($this->_list($name), true, $overwrite); <ide> <ide> return static::CODE_SUCCESS; <ide><path>src/Command/PluginAssetsRemoveCommand.php <ide> <ide> /** <ide> * Command for removing plugin assets from app's webroot. <add> * <add> * @psalm-suppress PropertyNotSetInConstructor <ide> */ <ide> class PluginAssetsRemoveCommand extends Command <ide> { <ide><path>src/Command/PluginAssetsSymlinkCommand.php <ide> <ide> /** <ide> * Command for symlinking / copying plugin assets to app's webroot. <add> * <add> * @psalm-suppress PropertyNotSetInConstructor <ide> */ <ide> class PluginAssetsSymlinkCommand extends Command <ide> { <ide> public function execute(Arguments $args, ConsoleIo $io): ?int <ide> $this->args = $args; <ide> <ide> $name = $args->getArgument('name'); <del> $overwrite = $args->getOption('overwrite'); <add> $overwrite = (bool)$args->getOption('overwrite'); <ide> $this->_process($this->_list($name), false, $overwrite); <ide> <ide> return static::CODE_SUCCESS; <ide><path>src/Command/PluginLoadCommand.php <ide> <ide> /** <ide> * Command for loading plugins. <add> * <add> * @psalm-suppress PropertyNotSetInConstructor <ide> */ <ide> class PluginLoadCommand extends Command <ide> {
4
Go
Go
fix race on sending stdin close event
4e262f63876018ca78d54a98eee3f533352b0ac9
<ide><path>integration-cli/docker_cli_run_test.go <ide> import ( <ide> "bytes" <ide> "encoding/json" <ide> "fmt" <add> "io" <ide> "io/ioutil" <ide> "net" <ide> "os" <ide> func (s *DockerSuite) TestRunEmptyEnv(c *check.C) { <ide> c.Assert(err, checker.NotNil) <ide> c.Assert(out, checker.Contains, expectedOutput) <ide> } <add> <add>// #28658 <add>func (s *DockerSuite) TestSlowStdinClosing(c *check.C) { <add> name := "testslowstdinclosing" <add> repeat := 3 // regression happened 50% of the time <add> for i := 0; i < repeat; i++ { <add> cmd := exec.Command(dockerBinary, "run", "--rm", "--name", name, "-i", "busybox", "cat") <add> cmd.Stdin = &delayedReader{} <add> done := make(chan error, 1) <add> go func() { <add> _, err := runCommand(cmd) <add> done <- err <add> }() <add> <add> select { <add> case <-time.After(15 * time.Second): <add> c.Fatal("running container timed out") // cleanup in teardown <add> case err := <-done: <add> c.Assert(err, checker.IsNil) <add> } <add> } <add>} <add> <add>type delayedReader struct{} <add> <add>func (s *delayedReader) Read([]byte) (int, error) { <add> time.Sleep(500 * time.Millisecond) <add> return 0, io.EOF <add>} <ide><path>libcontainerd/container_unix.go <ide> func (ctr *container) start(checkpoint string, checkpointDir string, attachStdio <ide> stdinOnce.Do(func() { // on error from attach we don't know if stdin was already closed <ide> err = stdin.Close() <ide> go func() { <add> select { <add> case <-ready: <add> case <-ctx.Done(): <add> } <ide> select { <ide> case <-ready: <ide> if err := ctr.sendCloseStdin(); err != nil { <ide> logrus.Warnf("failed to close stdin: %+v", err) <ide> } <del> case <-ctx.Done(): <add> default: <ide> } <ide> }() <ide> })
2
Javascript
Javascript
remove check that is always true
b90552b9ca851bf8567acca5176597e6f316a68f
<ide><path>src/core/core.scale.js <ide> var Scale = Element.extend({ <ide> for (i = 0; i < ticksLength; ++i) { <ide> tick = ticks[i] || {}; <ide> <del> // autoskipper skipped this tick (#4635) <del> if (isNullOrUndef(tick.label) && i < ticks.length) { <del> continue; <del> } <del> <ide> if (i === me.zeroLineIndex && options.offset === offsetGridLines) { <ide> // Draw the first index specially <ide> lineWidth = gridLines.zeroLineWidth; <ide> var Scale = Element.extend({ <ide> tick = ticks[i]; <ide> label = tick.label; <ide> <del> // autoskipper skipped this tick (#4635) <del> if (isNullOrUndef(label)) { <del> continue; <del> } <del> <ide> pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset; <ide> font = tick.major ? fonts.major : fonts.minor; <ide> lineHeight = font.lineHeight;
1
Javascript
Javascript
fix misleading comment
fd18243a50cba987063187b3ff95a2407ed348fa
<ide><path>test/parallel/test-vm-function-declaration.js <ide> const assert = require('assert'); <ide> const vm = require('vm'); <ide> const o = vm.createContext({ console: console }); <ide> <del>// This triggers the setter callback in node_contextify.cc <add>// Function declaration and expression should both be copied to the <add>// sandboxed context. <ide> let code = 'var a = function() {};\n'; <del> <del>// but this does not, since function decls are defineProperties, <del>// not simple sets. <ide> code += 'function b(){}\n'; <ide> <ide> // Grab the global b function as the completion value, to ensure that
1
Javascript
Javascript
dump response when request is aborted
99a7e78e7789a1a0de31c493605abf0a0f35312a
<ide><path>lib/http.js <ide> ClientRequest.prototype._implicitHeader = function() { <ide> }; <ide> <ide> ClientRequest.prototype.abort = function() { <add> // If we're aborting, we don't care about any more response data. <add> if (this.res) <add> this.res._dump(); <add> else <add> this.once('response', function(res) { <add> res._dump(); <add> }); <add> <ide> if (this.socket) { <ide> // in-progress <ide> this.socket.destroy(); <ide><path>test/simple/test-http-abort-stream-end.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>var http = require('http'); <add> <add>var maxSize = 1024; <add>var size = 0; <add> <add>var s = http.createServer(function(req, res) { <add> this.close(); <add> <add> res.writeHead(200, {'Content-Type': 'text/plain'}); <add> for (var i = 0; i < maxSize; i++) { <add> res.write('x' + i); <add> } <add> res.end(); <add>}); <add> <add>var aborted = false; <add>s.listen(common.PORT, function() { <add> var req = http.get('http://localhost:' + common.PORT, function(res) { <add> res.on('data', function(chunk) { <add> size += chunk.length; <add> assert(!aborted, 'got data after abort'); <add> if (size > maxSize) { <add> aborted = true; <add> req.abort(); <add> size = maxSize; <add> } <add> }); <add> }); <add> <add> req.end(); <add>}); <add> <add>process.on('exit', function() { <add> assert(aborted); <add> assert.equal(size, maxSize); <add> console.log('ok'); <add>});
2
Go
Go
handle image metadata when drivers are switched
1b28cdc7f977f265d0d8de53e8ec1d773ed54db1
<ide><path>graph.go <ide> func (graph *Graph) restore() error { <ide> } <ide> for _, v := range dir { <ide> id := v.Name() <del> graph.idIndex.Add(id) <add> if graph.driver.Exists(id) { <add> graph.idIndex.Add(id) <add> } <ide> } <ide> return nil <ide> } <ide> func (graph *Graph) Register(jsonData []byte, layerData archive.Archive, img *Im <ide> if graph.Exists(img.ID) { <ide> return fmt.Errorf("Image %s already exists", img.ID) <ide> } <add> <add> // Ensure that the image root does not exist on the filesystem <add> // when it is not registered in the graph. <add> // This is common when you switch from one graph driver to another <add> if err := os.RemoveAll(graph.imageRoot(img.ID)); err != nil && !os.IsNotExist(err) { <add> return err <add> } <add> <ide> tmp, err := graph.Mktemp("") <ide> defer os.RemoveAll(tmp) <ide> if err != nil { <ide><path>graphdriver/aufs/migrate.go <ide> func pathExists(pth string) bool { <ide> // symlink. <ide> func (a *Driver) Migrate(pth string, setupInit func(p string) error) error { <ide> if pathExists(path.Join(pth, "graph")) { <add> if err := a.migrateRepositories(pth); err != nil { <add> return err <add> } <ide> if err := a.migrateImages(path.Join(pth, "graph")); err != nil { <ide> return err <ide> } <ide> func (a *Driver) Migrate(pth string, setupInit func(p string) error) error { <ide> return nil <ide> } <ide> <add>func (a *Driver) migrateRepositories(pth string) error { <add> name := path.Join(pth, "repositories") <add> if err := os.Rename(name, name+"-aufs"); err != nil && !os.IsNotExist(err) { <add> return err <add> } <add> return nil <add>} <add> <ide> func (a *Driver) migrateContainers(pth string, setupInit func(p string) error) error { <ide> fis, err := ioutil.ReadDir(pth) <ide> if err != nil { <ide><path>graphdriver/devmapper/driver.go <ide> func (d *Driver) unmount(id, mountPoint string) error { <ide> // Unmount the device <ide> return d.DeviceSet.UnmountDevice(id, mountPoint, true) <ide> } <add> <add>func (d *Driver) Exists(id string) bool { <add> return d.Devices[id] != nil <add>} <ide><path>graphdriver/driver.go <ide> type Driver interface { <ide> Remove(id string) error <ide> <ide> Get(id string) (dir string, err error) <add> Exists(id string) bool <ide> <ide> Status() [][2]string <ide> <ide><path>graphdriver/dummy/driver.go <ide> func (d *Driver) Get(id string) (string, error) { <ide> } <ide> return dir, nil <ide> } <add> <add>func (d *Driver) Exists(id string) bool { <add> _, err := os.Stat(d.dir(id)) <add> return err == nil <add>} <ide><path>runtime.go <ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) { <ide> if err != nil { <ide> return nil, err <ide> } <del> repositories, err := NewTagStore(path.Join(config.Root, "repositories"), g) <add> repositories, err := NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g) <ide> if err != nil { <ide> return nil, fmt.Errorf("Couldn't create Tag store: %s", err) <ide> }
6
Javascript
Javascript
use helper function to remove duplication
ef9db4b6a81fbc289ada8783f6ee9155db2bd9ce
<ide><path>packages/ember-handlebars/tests/handlebars_test.js <ide> test("should escape HTML in normal mustaches", function() { <ide> output: "you need to be more <b>bold</b>" <ide> }); <ide> <del> Ember.run(function() { view.appendTo('#qunit-fixture'); }); <add> appendView(); <ide> equal(view.$('b').length, 0, "does not create an element"); <ide> equal(view.$().text(), 'you need to be more <b>bold</b>', "inserts entities, not elements"); <ide> <ide> test("should not escape HTML in triple mustaches", function() { <ide> output: "you need to be more <b>bold</b>" <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$('b').length, 1, "creates an element"); <ide> <ide> test("should not escape HTML if string is a Handlebars.SafeString", function() { <ide> output: new Handlebars.SafeString("you need to be more <b>bold</b>") <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$('b').length, 1, "creates an element"); <ide> <ide> test("Ember.View should bind properties in the parent context", function() { <ide> template: Ember.Handlebars.compile('<h1 id="first">{{#with content}}{{wham}}-{{../blam}}{{/with}}</h1>') <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$('#first').text(), "bam-shazam", "renders parent properties"); <ide> }); <ide> test("Ember.View should bind properties in the grandparent context", function() <ide> template: Ember.Handlebars.compile('<h1 id="first">{{#with content}}{{#with thankYou}}{{value}}-{{../wham}}-{{../../blam}}{{/with}}{{/with}}</h1>') <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$('#first').text(), "ma'am-bam-shazam", "renders grandparent properties"); <ide> }); <ide> test("Ember.View should update when a property changes and the bind helper is us <ide> }) <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$('#first').text(), "bam", "precond - view renders Handlebars template"); <ide> <ide> test("Ember.View should not use keyword incorrectly - Issue #1315", function() { <ide> ]) <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$().text(), 'X-1:One 2:Two Y-1:One 2:Two '); <ide> }); <ide> test("Ember.View should update when a property changes and no bind helper is use <ide> }) <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$('#first').text(), "bam", "precond - view renders Handlebars template"); <ide> <ide> test("should allow standard Handlebars template usage", function() { <ide> template: Handlebars.compile("Hello, {{name}}") <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$().text(), "Hello, Erik"); <ide> }); <ide> test("should be able to use standard Handlebars #each helper", function() { <ide> template: Handlebars.compile("{{#each items}}{{this}}{{/each}}") <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$().html(), "abc"); <ide> }); <ide> test("should expose a controller keyword when present on the view", function() { <ide> template: Ember.Handlebars.compile(templateString) <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo("#qunit-fixture"); <del> }); <add> appendView(); <ide> <ide> equal(view.$().text(), "barbang", "renders values from controller and parent controller"); <ide> <ide> test("should expose a controller keyword when present on the view", function() { <ide> template: Ember.Handlebars.compile("{{controller}}") <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(view.$().text(), "aString", "renders the controller itself if no additional path is specified"); <ide> }); <ide> test("should expose a controller keyword that can be used in conditionals", func <ide> template: Ember.Handlebars.compile(templateString) <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo("#qunit-fixture"); <del> }); <add> appendView(); <ide> <ide> equal(view.$().text(), "bar", "renders values from controller and parent controller"); <ide> <ide> test("should expose a controller keyword that persists through Ember.ContainerVi <ide> template: Ember.Handlebars.compile(templateString) <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo("#qunit-fixture"); <del> }); <add> appendView(); <ide> <ide> var containerView = get(view, 'childViews.firstObject'); <ide> var viewInstanceToBeInserted = Ember.View.create({ <ide> test("should expose a view keyword", function() { <ide> template: Ember.Handlebars.compile(templateString) <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo("#qunit-fixture"); <del> }); <add> appendView(); <ide> <ide> equal(view.$().text(), "barbang", "renders values from view and child view"); <ide> }); <ide> test("Ember.Button targets should respect keywords", function() { <ide> } <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> var button = view.get('childViews').objectAt(0); <ide> equal(button.get('targetObject'), "bar", "resolves the target"); <ide> test("bindings should be relative to the current context", function() { <ide> template: Ember.Handlebars.compile('{{#if view.museumOpen}} {{view view.museumView nameBinding="view.museumDetails.name" dollarsBinding="view.museumDetails.price"}} {{/if}}') <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(Ember.$.trim(view.$().text()), "Name: SFMoMA Price: $20", "should print baz twice"); <ide> }); <ide> test("bindings should respect keywords", function() { <ide> template: Ember.Handlebars.compile('{{#if view.museumOpen}}{{view view.museumView nameBinding="controller.museumDetails.name" dollarsBinding="controller.museumDetails.price"}}{{/if}}') <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(Ember.$.trim(view.$().text()), "Name: SFMoMA Price: $20", "should print baz twice"); <ide> }); <ide> test("bindings can be 'this', in which case they *are* the current context", fun <ide> template: Ember.Handlebars.compile('{{#if view.museumOpen}} {{#with view.museumDetails}}{{view museumView museumBinding="this"}} {{/with}}{{/if}}') <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(Ember.$.trim(view.$().text()), "Name: SFMoMA Price: $20", "should print baz twice"); <ide> }); <ide> test("should update bound values after the view is removed and then re-appended" <ide> boundValue: "foo" <ide> }); <ide> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> equal(Ember.$.trim(view.$().text()), "foo"); <ide> Ember.run(function() { <ide> test("should update bound values after the view is removed and then re-appended" <ide> Ember.run(function() { <ide> set(view, 'showStuff', true); <ide> }); <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <add> appendView(); <ide> <ide> Ember.run(function() { <ide> set(view, 'boundValue', "bar");
1
Ruby
Ruby
refer to`homebrew/homebrew-cask-versions` properly
023261038192a4f55c95a4d2486873ec1c9a728a
<ide><path>Library/Homebrew/official_taps.rb <ide> <ide> OFFICIAL_CASK_TAPS = %w[ <ide> cask <del> versions <add> cask-versions <ide> ].freeze <ide> <ide> OFFICIAL_CMD_TAPS = {
1
Text
Text
add changes to changelog
01ddd1cecff3fabd1ecaeb86717612e757b74139
<ide><path>actionview/CHANGELOG.md <add>* Fix issues with scopes and engine on `current_page?` method. <add> <add> Fixes #29401. <add> <add> *Nikita Savrov* <add> <ide> * Generate field ids in `collection_check_boxes` and `collection_radio_buttons`. <ide> <ide> This makes sure that the labels are linked up with the fields.
1
Go
Go
add proper refcounting to zfs graphdriver
922986b76e2ac596faed6a724cebcf7082174980
<ide><path>daemon/graphdriver/zfs/zfs.go <ide> import ( <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> ) <ide> <add>type activeMount struct { <add> count int <add> path string <add> mounted bool <add>} <add> <ide> type zfsOptions struct { <ide> fsName string <ide> mountPath string <ide> func Init(base string, opt []string, uidMaps, gidMaps []idtools.IDMap) (graphdri <ide> dataset: rootDataset, <ide> options: options, <ide> filesystemsCache: filesystemsCache, <add> active: make(map[string]*activeMount), <ide> uidMaps: uidMaps, <ide> gidMaps: gidMaps, <ide> } <ide> type Driver struct { <ide> options zfsOptions <ide> sync.Mutex // protects filesystem cache against concurrent access <ide> filesystemsCache map[string]bool <add> active map[string]*activeMount <ide> uidMaps []idtools.IDMap <ide> gidMaps []idtools.IDMap <ide> } <ide> func (d *Driver) Remove(id string) error { <ide> <ide> // Get returns the mountpoint for the given id after creating the target directories if necessary. <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <add> d.Lock() <add> defer d.Unlock() <add> <add> mnt := d.active[id] <add> if mnt != nil { <add> mnt.count++ <add> return mnt.path, nil <add> } <add> <add> mnt = &activeMount{count: 1} <add> <ide> mountpoint := d.mountPath(id) <ide> filesystem := d.zfsPath(id) <ide> options := label.FormatMountLabel("", mountLabel) <ide> func (d *Driver) Get(id, mountLabel string) (string, error) { <ide> if err := os.Chown(mountpoint, rootUID, rootGID); err != nil { <ide> return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err) <ide> } <add> mnt.path = mountpoint <add> mnt.mounted = true <add> d.active[id] = mnt <ide> <ide> return mountpoint, nil <ide> } <ide> <ide> // Put removes the existing mountpoint for the given id if it exists. <ide> func (d *Driver) Put(id string) error { <del> mountpoint := d.mountPath(id) <del> logrus.Debugf(`[zfs] unmount("%s")`, mountpoint) <add> d.Lock() <add> defer d.Unlock() <add> <add> mnt := d.active[id] <add> if mnt == nil { <add> logrus.Debugf("[zfs] Put on a non-mounted device %s", id) <add> // but it might be still here <add> if d.Exists(id) { <add> err := mount.Unmount(d.mountPath(id)) <add> if err != nil { <add> logrus.Debugf("[zfs] Failed to unmount %s zfs fs: %v", id, err) <add> } <add> } <add> return nil <add> } <ide> <del> if err := mount.Unmount(mountpoint); err != nil { <del> return fmt.Errorf("error unmounting to %s: %v", mountpoint, err) <add> mnt.count-- <add> if mnt.count > 0 { <add> return nil <add> } <add> <add> defer delete(d.active, id) <add> if mnt.mounted { <add> logrus.Debugf(`[zfs] unmount("%s")`, mnt.path) <add> <add> if err := mount.Unmount(mnt.path); err != nil { <add> return fmt.Errorf("error unmounting to %s: %v", mnt.path, err) <add> } <ide> } <ide> return nil <ide> }
1
Javascript
Javascript
correct the buffersize to highwatermark
60958d235d6ad789b034a67a528a7d680ac1c727
<ide><path>benchmark/fs/read-stream-throughput.js <ide> function main(conf) { <ide> function runTest() { <ide> assert(fs.statSync(filename).size === filesize); <ide> var rs = fs.createReadStream(filename, { <del> bufferSize: size, <add> highWaterMark: size, <ide> encoding: encoding <ide> }); <ide>
1
Go
Go
avoid a head request for each layer in a v2 pull
39589800b4750bf28078efe57f7f1e74d971248f
<ide><path>distribution/pull_v2.go <ide> func (p *v2Puller) download(di *downloadInfo) { <ide> <ide> blobs := p.repo.Blobs(context.Background()) <ide> <del> desc, err := blobs.Stat(context.Background(), di.digest) <del> if err != nil { <del> logrus.Debugf("Error statting layer: %v", err) <del> di.err <- err <del> return <del> } <del> di.size = desc.Size <del> <ide> layerDownload, err := blobs.Open(context.Background(), di.digest) <ide> if err != nil { <ide> logrus.Debugf("Error fetching layer: %v", err) <ide> func (p *v2Puller) download(di *downloadInfo) { <ide> } <ide> defer layerDownload.Close() <ide> <add> di.size, err = layerDownload.Seek(0, os.SEEK_END) <add> if err != nil { <add> // Seek failed, perhaps because there was no Content-Length <add> // header. This shouldn't fail the download, because we can <add> // still continue without a progress bar. <add> di.size = 0 <add> } else { <add> // Restore the seek offset at the beginning of the stream. <add> _, err = layerDownload.Seek(0, os.SEEK_SET) <add> if err != nil { <add> di.err <- err <add> return <add> } <add> } <add> <ide> verifier, err := digest.NewDigestVerifier(di.digest) <ide> if err != nil { <ide> di.err <- err
1
PHP
PHP
return connection status in debug
c9e83a2dc3ba6f2c5e00d34fdd012b666c1a964c
<ide><path>src/Database/Driver.php <ide> public function __destruct() { <ide> * @return array <ide> */ <ide> public function __debugInfo() { <del> $secrets = [ <del> 'password' => '*****', <del> 'login' => '*****', <del> 'host' => '*****', <del> 'database' => '*****', <del> 'port' => '*****', <del> 'prefix' => '*****', <del> 'schema' => '*****' <del> ]; <del> $replace = array_intersect_key($secrets, $this->_config); <del> <ide> return [ <del> '_baseConfig' => $replace + $this->_baseConfig, <del> '_config' => $replace + $this->_config, <del> '_autoQuoting' => $this->_autoQuoting, <del> '_startQuote' => $this->_startQuote, <del> '_endQuote' => $this->_endQuote, <del> '_schemaDialect' => get_class($this->_schemaDialect) <add> 'connected' => $this->isConnected() <ide> ]; <ide> } <ide>
1
Text
Text
update version numbers in quickstart guide
fc7cebe1550da6ce92de72babdaab2d6ef838c0e
<ide><path>README.md <ide> Thanks to the awesome folks over at [Fastly](http://www.fastly.com/), there's a <ide> `<head>`: <ide> <ide> ```html <del><link href="http://vjs.zencdn.net/4.9/video-js.css" rel="stylesheet"> <del><script src="http://vjs.zencdn.net/4.9/video.js"></script> <add><link href="http://vjs.zencdn.net/4.10/video-js.css" rel="stylesheet"> <add><script src="http://vjs.zencdn.net/4.10/video.js"></script> <ide> ``` <ide> <ide> Then, whenever you want to use Video.js you can simply use the `<video>` element as your normally would, but with an additional `data-setup` attribute containing any Video.js options. These options
1
Go
Go
optimize changesdirs on linux
45c45a2c9a71528489a58fe633849f16e245631c
<ide><path>pkg/archive/changes.go <ide> import ( <ide> "bytes" <ide> "fmt" <ide> "io" <add> "io/ioutil" <ide> "os" <ide> "path/filepath" <ide> "sort" <ide> func newRootFileInfo() *FileInfo { <ide> return root <ide> } <ide> <del>func collectFileInfo(sourceDir string) (*FileInfo, error) { <del> root := newRootFileInfo() <del> <del> err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error { <del> if err != nil { <del> return err <del> } <del> <del> // Rebase path <del> relPath, err := filepath.Rel(sourceDir, path) <del> if err != nil { <del> return err <del> } <del> relPath = filepath.Join("/", relPath) <del> <del> if relPath == "/" { <del> return nil <del> } <del> <del> parent := root.LookUp(filepath.Dir(relPath)) <del> if parent == nil { <del> return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) <del> } <del> <del> info := &FileInfo{ <del> name: filepath.Base(relPath), <del> children: make(map[string]*FileInfo), <del> parent: parent, <del> } <del> <del> s, err := system.Lstat(path) <del> if err != nil { <del> return err <del> } <del> info.stat = s <del> <del> info.capability, _ = system.Lgetxattr(path, "security.capability") <del> <del> parent.children[info.name] = info <del> <del> return nil <del> }) <del> if err != nil { <del> return nil, err <del> } <del> return root, nil <del>} <del> <ide> // ChangesDirs compares two directories and generates an array of Change objects describing the changes. <ide> // If oldDir is "", then all files in newDir will be Add-Changes. <ide> func ChangesDirs(newDir, oldDir string) ([]Change, error) { <ide> var ( <ide> oldRoot, newRoot *FileInfo <del> err1, err2 error <del> errs = make(chan error, 2) <ide> ) <del> go func() { <del> if oldDir != "" { <del> oldRoot, err1 = collectFileInfo(oldDir) <del> } <del> errs <- err1 <del> }() <del> go func() { <del> newRoot, err2 = collectFileInfo(newDir) <del> errs <- err2 <del> }() <del> <del> // block until both routines have returned <del> for i := 0; i < 2; i++ { <del> if err := <-errs; err != nil { <add> if oldDir == "" { <add> emptyDir, err := ioutil.TempDir("", "empty") <add> if err != nil { <ide> return nil, err <ide> } <add> defer os.Remove(emptyDir) <add> oldDir = emptyDir <add> } <add> oldRoot, newRoot, err := collectFileInfoForChanges(oldDir, newDir) <add> if err != nil { <add> return nil, err <ide> } <ide> <ide> return newRoot.Changes(oldRoot), nil <ide><path>pkg/archive/changes_linux.go <add>package archive <add> <add>import ( <add> "bytes" <add> "fmt" <add> "os" <add> "path/filepath" <add> "sort" <add> "syscall" <add> "unsafe" <add> <add> "github.com/docker/docker/pkg/system" <add>) <add> <add>// walker is used to implement collectFileInfoForChanges on linux. Where this <add>// method in general returns the entire contents of two directory trees, we <add>// optimize some FS calls out on linux. In particular, we take advantage of the <add>// fact that getdents(2) returns the inode of each file in the directory being <add>// walked, which, when walking two trees in parallel to generate a list of <add>// changes, can be used to prune subtrees without ever having to lstat(2) them <add>// directly. Eliminating stat calls in this way can save up to seconds on large <add>// images. <add>type walker struct { <add> dir1 string <add> dir2 string <add> root1 *FileInfo <add> root2 *FileInfo <add>} <add> <add>// collectFileInfoForChanges returns a complete representation of the trees <add>// rooted at dir1 and dir2, with one important exception: any subtree or <add>// leaf where the inode and device numbers are an exact match between dir1 <add>// and dir2 will be pruned from the results. This method is *only* to be used <add>// to generating a list of changes between the two directories, as it does not <add>// reflect the full contents. <add>func collectFileInfoForChanges(dir1, dir2 string) (*FileInfo, *FileInfo, error) { <add> w := &walker{ <add> dir1: dir1, <add> dir2: dir2, <add> root1: newRootFileInfo(), <add> root2: newRootFileInfo(), <add> } <add> <add> i1, err := os.Lstat(w.dir1) <add> if err != nil { <add> return nil, nil, err <add> } <add> i2, err := os.Lstat(w.dir2) <add> if err != nil { <add> return nil, nil, err <add> } <add> <add> if err := w.walk("/", i1, i2); err != nil { <add> return nil, nil, err <add> } <add> <add> return w.root1, w.root2, nil <add>} <add> <add>// Given a FileInfo, its path info, and a reference to the root of the tree <add>// being constructed, register this file with the tree. <add>func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { <add> if fi == nil { <add> return nil <add> } <add> parent := root.LookUp(filepath.Dir(path)) <add> if parent == nil { <add> return fmt.Errorf("collectFileInfoForChanges: Unexpectedly no parent for %s", path) <add> } <add> info := &FileInfo{ <add> name: filepath.Base(path), <add> children: make(map[string]*FileInfo), <add> parent: parent, <add> } <add> cpath := filepath.Join(dir, path) <add> stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) <add> if err != nil { <add> return err <add> } <add> info.stat = stat <add> info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access <add> parent.children[info.name] = info <add> return nil <add>} <add> <add>// Walk a subtree rooted at the same path in both trees being iterated. For <add>// example, /docker/overlay/1234/a/b/c/d and /docker/overlay/8888/a/b/c/d <add>func (w *walker) walk(path string, i1, i2 os.FileInfo) (err error) { <add> // Register these nodes with the return trees, unless we're still at the <add> // (already-created) roots: <add> if path != "/" { <add> if err := walkchunk(path, i1, w.dir1, w.root1); err != nil { <add> return err <add> } <add> if err := walkchunk(path, i2, w.dir2, w.root2); err != nil { <add> return err <add> } <add> } <add> <add> is1Dir := i1 != nil && i1.IsDir() <add> is2Dir := i2 != nil && i2.IsDir() <add> <add> // If these files are both non-existent, or leaves (non-dirs), we are done. <add> if !is1Dir && !is2Dir { <add> return nil <add> } <add> <add> // Fetch the names of all the files contained in both directories being walked: <add> var names1, names2 []nameIno <add> if is1Dir { <add> names1, err = readdirnames(filepath.Join(w.dir1, path)) // getdents(2): fs access <add> if err != nil { <add> return err <add> } <add> } <add> if is2Dir { <add> names2, err = readdirnames(filepath.Join(w.dir2, path)) // getdents(2): fs access <add> if err != nil { <add> return err <add> } <add> } <add> <add> // We have lists of the files contained in both parallel directories, sorted <add> // in the same order. Walk them in parallel, generating a unique merged list <add> // of all items present in either or both directories. <add> var names []string <add> ix1 := 0 <add> ix2 := 0 <add> <add> for { <add> if ix1 >= len(names1) { <add> break <add> } <add> if ix2 >= len(names2) { <add> break <add> } <add> <add> ni1 := names1[ix1] <add> ni2 := names2[ix2] <add> <add> switch bytes.Compare([]byte(ni1.name), []byte(ni2.name)) { <add> case -1: // ni1 < ni2 -- advance ni1 <add> // we will not encounter ni1 in names2 <add> names = append(names, ni1.name) <add> ix1++ <add> case 0: // ni1 == ni2 <add> if ni1.ino != ni2.ino { <add> names = append(names, ni1.name) <add> } <add> ix1++ <add> ix2++ <add> case 1: // ni1 > ni2 -- advance ni2 <add> // we will not encounter ni2 in names1 <add> names = append(names, ni2.name) <add> ix2++ <add> } <add> } <add> for ix1 < len(names1) { <add> names = append(names, names1[ix1].name) <add> ix1++ <add> } <add> for ix2 < len(names2) { <add> names = append(names, names2[ix2].name) <add> ix2++ <add> } <add> <add> // For each of the names present in either or both of the directories being <add> // iterated, stat the name under each root, and recurse the pair of them: <add> for _, name := range names { <add> fname := filepath.Join(path, name) <add> var cInfo1, cInfo2 os.FileInfo <add> if is1Dir { <add> cInfo1, err = os.Lstat(filepath.Join(w.dir1, fname)) // lstat(2): fs access <add> if err != nil && !os.IsNotExist(err) { <add> return err <add> } <add> } <add> if is2Dir { <add> cInfo2, err = os.Lstat(filepath.Join(w.dir2, fname)) // lstat(2): fs access <add> if err != nil && !os.IsNotExist(err) { <add> return err <add> } <add> } <add> if err = w.walk(fname, cInfo1, cInfo2); err != nil { <add> return err <add> } <add> } <add> return nil <add>} <add> <add>// {name,inode} pairs used to support the early-pruning logic of the walker type <add>type nameIno struct { <add> name string <add> ino uint64 <add>} <add> <add>type nameInoSlice []nameIno <add> <add>func (s nameInoSlice) Len() int { return len(s) } <add>func (s nameInoSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } <add>func (s nameInoSlice) Less(i, j int) bool { return s[i].name < s[j].name } <add> <add>// readdirnames is a hacked-apart version of the Go stdlib code, exposing inode <add>// numbers further up the stack when reading directory contents. Unlike <add>// os.Readdirnames, which returns a list of filenames, this function returns a <add>// list of {filename,inode} pairs. <add>func readdirnames(dirname string) (names []nameIno, err error) { <add> var ( <add> size = 100 <add> buf = make([]byte, 4096) <add> nbuf int <add> bufp int <add> nb int <add> ) <add> <add> f, err := os.Open(dirname) <add> if err != nil { <add> return nil, err <add> } <add> defer f.Close() <add> <add> names = make([]nameIno, 0, size) // Empty with room to grow. <add> for { <add> // Refill the buffer if necessary <add> if bufp >= nbuf { <add> bufp = 0 <add> nbuf, err = syscall.ReadDirent(int(f.Fd()), buf) // getdents on linux <add> if nbuf < 0 { <add> nbuf = 0 <add> } <add> if err != nil { <add> return nil, os.NewSyscallError("readdirent", err) <add> } <add> if nbuf <= 0 { <add> break // EOF <add> } <add> } <add> <add> // Drain the buffer <add> nb, names = parseDirent(buf[bufp:nbuf], names) <add> bufp += nb <add> } <add> <add> sl := nameInoSlice(names) <add> sort.Sort(sl) <add> return sl, nil <add>} <add> <add>// parseDirent is a minor modification of syscall.ParseDirent (linux version) <add>// which returns {name,inode} pairs instead of just names. <add>func parseDirent(buf []byte, names []nameIno) (consumed int, newnames []nameIno) { <add> origlen := len(buf) <add> for len(buf) > 0 { <add> dirent := (*syscall.Dirent)(unsafe.Pointer(&buf[0])) <add> buf = buf[dirent.Reclen:] <add> if dirent.Ino == 0 { // File absent in directory. <add> continue <add> } <add> bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) <add> var name = string(bytes[0:clen(bytes[:])]) <add> if name == "." || name == ".." { // Useless names <add> continue <add> } <add> names = append(names, nameIno{name, dirent.Ino}) <add> } <add> return origlen - len(buf), names <add>} <add> <add>func clen(n []byte) int { <add> for i := 0; i < len(n); i++ { <add> if n[i] == 0 { <add> return i <add> } <add> } <add> return len(n) <add>} <ide><path>pkg/archive/changes_other.go <add>// +build !linux <add> <add>package archive <add> <add>import ( <add> "fmt" <add> "os" <add> "path/filepath" <add> <add> "github.com/docker/docker/pkg/system" <add>) <add> <add>func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, error) { <add> var ( <add> oldRoot, newRoot *FileInfo <add> err1, err2 error <add> errs = make(chan error, 2) <add> ) <add> go func() { <add> oldRoot, err1 = collectFileInfo(oldDir) <add> errs <- err1 <add> }() <add> go func() { <add> newRoot, err2 = collectFileInfo(newDir) <add> errs <- err2 <add> }() <add> <add> // block until both routines have returned <add> for i := 0; i < 2; i++ { <add> if err := <-errs; err != nil { <add> return nil, nil, err <add> } <add> } <add> <add> return oldRoot, newRoot, nil <add>} <add> <add>func collectFileInfo(sourceDir string) (*FileInfo, error) { <add> root := newRootFileInfo() <add> <add> err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error { <add> if err != nil { <add> return err <add> } <add> <add> // Rebase path <add> relPath, err := filepath.Rel(sourceDir, path) <add> if err != nil { <add> return err <add> } <add> relPath = filepath.Join("/", relPath) <add> <add> if relPath == "/" { <add> return nil <add> } <add> <add> parent := root.LookUp(filepath.Dir(relPath)) <add> if parent == nil { <add> return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) <add> } <add> <add> info := &FileInfo{ <add> name: filepath.Base(relPath), <add> children: make(map[string]*FileInfo), <add> parent: parent, <add> } <add> <add> s, err := system.Lstat(path) <add> if err != nil { <add> return err <add> } <add> info.stat = s <add> <add> info.capability, _ = system.Lgetxattr(path, "security.capability") <add> <add> parent.children[info.name] = info <add> <add> return nil <add> }) <add> if err != nil { <add> return nil, err <add> } <add> return root, nil <add>} <ide><path>pkg/system/stat_linux.go <ide> func fromStatT(s *syscall.Stat_t) (*Stat_t, error) { <ide> mtim: s.Mtim}, nil <ide> } <ide> <add>// FromStatT exists only on linux, and loads a system.Stat_t from a <add>// syscal.Stat_t. <add>func FromStatT(s *syscall.Stat_t) (*Stat_t, error) { <add> return fromStatT(s) <add>} <add> <ide> // Stat takes a path to a file and returns <ide> // a system.Stat_t type pertaining to that file. <ide> //
4
PHP
PHP
move method to trait
70052b2f5eec8859f1fdb0a84b7705ed464a74de
<ide><path>src/Illuminate/Http/Response.php <ide> public function setContent($content) <ide> return parent::setContent($content); <ide> } <ide> <del> /** <del> * Add an array of headers to the response. <del> * <del> * @param array $headers <del> * @return $this <del> */ <del> public function withHeaders(array $headers) <del> { <del> foreach ($headers as $key => $value) { <del> $this->headers->set($key, $value); <del> } <del> <del> return $this; <del> } <del> <ide> /** <ide> * Morph the given content into JSON. <ide> * <ide><path>src/Illuminate/Http/ResponseTrait.php <ide> public function header($key, $value, $replace = true) <ide> return $this; <ide> } <ide> <add> /** <add> * Add an array of headers to the response. <add> * <add> * @param array $headers <add> * @return $this <add> */ <add> public function withHeaders(array $headers) <add> { <add> foreach ($headers as $key => $value) { <add> $this->headers->set($key, $value); <add> } <add> <add> return $this; <add> } <add> <ide> /** <ide> * Add a cookie to the response. <ide> *
2
Ruby
Ruby
remove xmlsimple dependencies
4073a6d0a2f5926e10f06fe1702db7b1b7a20751
<ide><path>actionpack/test/controller/webservice_test.rb <ide> def test_post_xml_using_a_root_node_named_type <ide> end <ide> <ide> def test_post_xml_using_an_attributted_node_named_type <del> ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) } <add> ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } <ide> process('POST', 'application/xml', '<request><type type="string">Arial,12</type><z>3</z></request>') <ide> <ide> assert_equal 'type, z', @controller.response.body <ide> assert @controller.params.has_key?(:type) <del> assert_equal 'string', @controller.params['type']['type'] <del> assert_equal 'Arial,12', @controller.params['type']['content'] <del> assert_equal '3', @controller.params['z'] <add> assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect <add> assert_equal '3', @controller.params['z'], @controller.params.inspect <ide> end <ide> <ide> def test_register_and_use_yaml <ide> def test_register_and_use_yaml_as_symbol <ide> end <ide> <ide> def test_register_and_use_xml_simple <del> ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) } <add> ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } <ide> process('POST', 'application/xml', '<request><summary>content...</summary><title>SimpleXml</title></request>' ) <ide> assert_equal 'summary, title', @controller.response.body <ide> assert @controller.params.has_key?(:summary)
1
Go
Go
add service hierarchy to rest api
0912ecfc05ba5d1e3e38ca018e12af08bea8ffcd
<ide><path>libnetwork/api/api.go <ide> func (h *httpHandler) initRouter() { <ide> {"/networks/" + nwID + "/endpoints", []string{"partial-id", epPID}, procGetEndpoints}, <ide> {"/networks/" + nwID + "/endpoints", nil, procGetEndpoints}, <ide> {"/networks/" + nwID + "/endpoints/" + epID, nil, procGetEndpoint}, <add> {"/services", []string{"network", nwName}, procGetServices}, <add> {"/services", []string{"name", epName}, procGetServices}, <add> {"/services", []string{"partial-id", epPID}, procGetServices}, <add> {"/services", nil, procGetServices}, <add> {"/services/" + epID, nil, procGetService}, <ide> }, <ide> "POST": { <ide> {"/networks", nil, procCreateNetwork}, <ide> {"/networks/" + nwID + "/endpoints", nil, procCreateEndpoint}, <ide> {"/networks/" + nwID + "/endpoints/" + epID + "/containers", nil, procJoinEndpoint}, <add> {"/services", nil, procPublishService}, <add> {"/services/" + epID + "/backend", nil, procAttachBackend}, <ide> }, <ide> "DELETE": { <ide> {"/networks/" + nwID, nil, procDeleteNetwork}, <ide> {"/networks/" + nwID + "/endpoints/" + epID, nil, procDeleteEndpoint}, <ide> {"/networks/" + nwID + "/endpoints/" + epID + "/containers/" + cnID, nil, procLeaveEndpoint}, <add> {"/services/" + epID, nil, procUnpublishService}, <add> {"/services/" + epID + "/backend/" + cnID, nil, procDetachBackend}, <ide> }, <ide> } <ide> <ide> func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, bo <ide> list = append(list, buildEndpointResource(ep)) <ide> } <ide> } else if queryByPid { <del> // Return all the prefix-matching networks <add> // Return all the prefix-matching endpoints <ide> l := func(ep libnetwork.Endpoint) bool { <ide> if strings.HasPrefix(ep.ID(), shortID) { <ide> list = append(list, buildEndpointResource(ep)) <ide> func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, <ide> return nil, &successResponse <ide> } <ide> <add>/****************** <add> Service interface <add>*******************/ <add>func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <add> // Look for query filters and validate <add> nwName, filterByNwName := vars[urlNwName] <add> svName, queryBySvName := vars[urlEpName] <add> shortID, queryBySvPID := vars[urlEpPID] <add> <add> if filterByNwName && queryBySvName || filterByNwName && queryBySvPID || queryBySvName && queryBySvPID { <add> return nil, &badQueryResponse <add> } <add> <add> var list []*endpointResource <add> <add> switch { <add> case filterByNwName: <add> // return all service present on the specified network <add> nw, errRsp := findNetwork(c, nwName, byName) <add> if !errRsp.isOK() { <add> return list, &successResponse <add> } <add> for _, ep := range nw.Endpoints() { <add> epr := buildEndpointResource(ep) <add> list = append(list, epr) <add> } <add> case queryBySvName: <add> // Look in each network for the service with the specified name <add> l := func(ep libnetwork.Endpoint) bool { <add> if ep.Name() == svName { <add> list = append(list, buildEndpointResource(ep)) <add> return true <add> } <add> return false <add> } <add> for _, nw := range c.Networks() { <add> nw.WalkEndpoints(l) <add> } <add> case queryBySvPID: <add> // Return all the prefix-matching services <add> l := func(ep libnetwork.Endpoint) bool { <add> if strings.HasPrefix(ep.ID(), shortID) { <add> list = append(list, buildEndpointResource(ep)) <add> } <add> return false <add> } <add> for _, nw := range c.Networks() { <add> nw.WalkEndpoints(l) <add> } <add> default: <add> for _, nw := range c.Networks() { <add> for _, ep := range nw.Endpoints() { <add> epr := buildEndpointResource(ep) <add> list = append(list, epr) <add> } <add> } <add> } <add> <add> return list, &successResponse <add>} <add> <add>func procGetService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <add> epT, epBy := detectEndpointTarget(vars) <add> sv, errRsp := findService(c, epT, epBy) <add> if !errRsp.isOK() { <add> return nil, endpointToService(errRsp) <add> } <add> return buildEndpointResource(sv), &successResponse <add>} <add> <add>func procPublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <add> var sp servicePublish <add> <add> err := json.Unmarshal(body, &sp) <add> if err != nil { <add> return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <add> } <add> <add> n, errRsp := findNetwork(c, sp.Network, byName) <add> if !errRsp.isOK() { <add> return "", errRsp <add> } <add> <add> var setFctList []libnetwork.EndpointOption <add> if sp.ExposedPorts != nil { <add> setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(sp.ExposedPorts)) <add> } <add> if sp.PortMapping != nil { <add> setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(sp.PortMapping)) <add> } <add> <add> ep, err := n.CreateEndpoint(sp.Name, setFctList...) <add> if err != nil { <add> return "", endpointToService(convertNetworkError(err)) <add> } <add> <add> return ep.ID(), &createdResponse <add>} <add> <add>func procUnpublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <add> epT, epBy := detectEndpointTarget(vars) <add> sv, errRsp := findService(c, epT, epBy) <add> if !errRsp.isOK() { <add> return nil, errRsp <add> } <add> err := sv.Delete() <add> if err != nil { <add> return nil, endpointToService(convertNetworkError(err)) <add> } <add> return nil, &successResponse <add>} <add> <add>func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <add> var bk endpointJoin <add> err := json.Unmarshal(body, &bk) <add> if err != nil { <add> return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest} <add> } <add> <add> epT, epBy := detectEndpointTarget(vars) <add> sv, errRsp := findService(c, epT, epBy) <add> if !errRsp.isOK() { <add> return nil, errRsp <add> } <add> <add> err = sv.Join(bk.ContainerID, bk.parseOptions()...) <add> if err != nil { <add> return nil, convertNetworkError(err) <add> } <add> return sv.Info().SandboxKey(), &successResponse <add>} <add> <add>func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) { <add> epT, epBy := detectEndpointTarget(vars) <add> sv, errRsp := findService(c, epT, epBy) <add> if !errRsp.isOK() { <add> return nil, errRsp <add> } <add> <add> err := sv.Leave(vars[urlCnID]) <add> if err != nil { <add> return nil, convertNetworkError(err) <add> } <add> <add> return nil, &successResponse <add>} <add> <ide> /*********** <ide> Utilities <ide> ************/ <ide> func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.N <ide> panic(fmt.Sprintf("unexpected selector for network search: %d", by)) <ide> } <ide> if err != nil { <del> if _, ok := err.(libnetwork.ErrNoSuchNetwork); ok { <add> if _, ok := err.(types.NotFoundError); ok { <ide> return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound} <ide> } <ide> return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} <ide> func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) <ide> panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy)) <ide> } <ide> if err != nil { <del> if _, ok := err.(libnetwork.ErrNoSuchEndpoint); ok { <add> if _, ok := err.(types.NotFoundError); ok { <ide> return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound} <ide> } <ide> return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest} <ide> } <ide> return ep, &successResponse <ide> } <ide> <add>func findService(c libnetwork.NetworkController, svs string, svBy int) (libnetwork.Endpoint, *responseStatus) { <add> for _, nw := range c.Networks() { <add> var ( <add> ep libnetwork.Endpoint <add> err error <add> ) <add> switch svBy { <add> case byID: <add> ep, err = nw.EndpointByID(svs) <add> case byName: <add> ep, err = nw.EndpointByName(svs) <add> default: <add> panic(fmt.Sprintf("unexpected selector for service search: %d", svBy)) <add> } <add> if err == nil { <add> return ep, &successResponse <add> } else if _, ok := err.(types.NotFoundError); !ok { <add> return nil, convertNetworkError(err) <add> } <add> } <add> return nil, &responseStatus{Status: "Service not found", StatusCode: http.StatusNotFound} <add>} <add> <add>func endpointToService(rsp *responseStatus) *responseStatus { <add> rsp.Status = strings.Replace(rsp.Status, "endpoint", "service", -1) <add> return rsp <add>} <add> <ide> func convertNetworkError(err error) *responseStatus { <ide> var code int <ide> switch err.(type) { <ide><path>libnetwork/api/api_test.go <ide> func createTestNetwork(t *testing.T, network string) (libnetwork.NetworkControll <ide> t.Fatal(err) <ide> } <ide> <del> nw, err := c.NewNetwork(bridgeNetType, network, nil) <add> netOption := options.Generic{ <add> netlabel.GenericData: options.Generic{ <add> "BridgeName": network, <add> "AllowNonDefaultBridge": true, <add> }, <add> } <add> netGeneric := libnetwork.NetworkOptionGeneric(netOption) <add> nw, err := c.NewNetwork(bridgeNetType, network, netGeneric) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestGetNetworksAndEndpoints(t *testing.T) { <ide> } <ide> } <ide> <add>func TestProcGetServices(t *testing.T) { <add> defer netutils.SetupTestNetNS(t)() <add> <add> c, err := libnetwork.New("") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> err = c.ConfigureNetworkDriver(bridgeNetType, nil) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> // Create 2 networks <add> netName1 := "production" <add> netOption := options.Generic{ <add> netlabel.GenericData: options.Generic{ <add> "BridgeName": netName1, <add> "AllowNonDefaultBridge": true, <add> }, <add> } <add> nw1, err := c.NewNetwork(bridgeNetType, netName1, libnetwork.NetworkOptionGeneric(netOption)) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> netName2 := "work-dev" <add> netOption = options.Generic{ <add> netlabel.GenericData: options.Generic{ <add> "BridgeName": netName2, <add> "AllowNonDefaultBridge": true, <add> }, <add> } <add> nw2, err := c.NewNetwork(bridgeNetType, netName2, libnetwork.NetworkOptionGeneric(netOption)) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> vars := make(map[string]string) <add> li, errRsp := procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list := i2eL(li) <add> if len(list) != 0 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> <add> // Add a couple of services on one network and one on the other network <add> ep11, err := nw1.CreateEndpoint("db-prod") <add> if err != nil { <add> t.Fatal(err) <add> } <add> ep12, err := nw1.CreateEndpoint("web-prod") <add> if err != nil { <add> t.Fatal(err) <add> } <add> ep21, err := nw2.CreateEndpoint("db-dev") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 3 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> <add> // Filter by network <add> vars[urlNwName] = netName1 <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 2 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> <add> vars[urlNwName] = netName2 <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 1 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> <add> vars[urlNwName] = "unknown-network" <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 0 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> <add> // Query by name <add> delete(vars, urlNwName) <add> vars[urlEpName] = "db-prod" <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 1 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> <add> vars[urlEpName] = "no-service" <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 0 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> <add> // Query by id or partial id <add> delete(vars, urlEpName) <add> vars[urlEpPID] = ep12.ID() <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 1 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> if list[0].ID != ep12.ID() { <add> t.Fatalf("Unexpected element in response: %v", list) <add> } <add> <add> vars[urlEpPID] = "non-id" <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 0 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add> <add> delete(vars, urlEpPID) <add> err = ep11.Delete() <add> if err != nil { <add> t.Fatal(err) <add> } <add> err = ep12.Delete() <add> if err != nil { <add> t.Fatal(err) <add> } <add> err = ep21.Delete() <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> li, errRsp = procGetServices(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> list = i2eL(li) <add> if len(list) != 0 { <add> t.Fatalf("Unexpected services in response: %v", list) <add> } <add>} <add> <add>func TestProcGetService(t *testing.T) { <add> defer netutils.SetupTestNetNS(t)() <add> <add> c, nw := createTestNetwork(t, "network") <add> ep1, err := nw.CreateEndpoint("db") <add> if err != nil { <add> t.Fatal(err) <add> } <add> ep2, err := nw.CreateEndpoint("web") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> vars := map[string]string{urlEpID: ""} <add> _, errRsp := procGetService(c, vars, nil) <add> if errRsp.isOK() { <add> t.Fatalf("Expected failure, but suceeded") <add> } <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode) <add> } <add> <add> vars[urlEpID] = "unknown-service-id" <add> _, errRsp = procGetService(c, vars, nil) <add> if errRsp.isOK() { <add> t.Fatalf("Expected failure, but suceeded") <add> } <add> if errRsp.StatusCode != http.StatusNotFound { <add> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp) <add> } <add> <add> vars[urlEpID] = ep1.ID() <add> si, errRsp := procGetService(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> sv := i2e(si) <add> if sv.ID != ep1.ID() { <add> t.Fatalf("Unexpected service resource returned: %v", sv) <add> } <add> <add> vars[urlEpID] = ep2.ID() <add> si, errRsp = procGetService(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> sv = i2e(si) <add> if sv.ID != ep2.ID() { <add> t.Fatalf("Unexpected service resource returned: %v", sv) <add> } <add>} <add> <add>func TestProcPublishUnpublishService(t *testing.T) { <add> defer netutils.SetupTestNetNS(t)() <add> <add> c, _ := createTestNetwork(t, "network") <add> vars := make(map[string]string) <add> <add> vbad, err := json.Marshal("bad service create data") <add> if err != nil { <add> t.Fatal(err) <add> } <add> _, errRsp := procPublishService(c, vars, vbad) <add> if errRsp == &createdResponse { <add> t.Fatalf("Expected to fail but succeeded") <add> } <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <add> } <add> <add> b, err := json.Marshal(servicePublish{Name: ""}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> _, errRsp = procPublishService(c, vars, b) <add> if errRsp == &createdResponse { <add> t.Fatalf("Expected to fail but succeeded") <add> } <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <add> } <add> <add> b, err = json.Marshal(servicePublish{Name: "db"}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> _, errRsp = procPublishService(c, vars, b) <add> if errRsp == &createdResponse { <add> t.Fatalf("Expected to fail but succeeded") <add> } <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <add> } <add> <add> b, err = json.Marshal(servicePublish{Name: "db", Network: "unknown-network"}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> _, errRsp = procPublishService(c, vars, b) <add> if errRsp == &createdResponse { <add> t.Fatalf("Expected to fail but succeeded") <add> } <add> if errRsp.StatusCode != http.StatusNotFound { <add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <add> } <add> <add> b, err = json.Marshal(servicePublish{Name: "", Network: "network"}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> _, errRsp = procPublishService(c, vars, b) <add> if errRsp == &createdResponse { <add> t.Fatalf("Expected to fail but succeeded") <add> } <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <add> } <add> <add> b, err = json.Marshal(servicePublish{Name: "db", Network: "network"}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> _, errRsp = procPublishService(c, vars, b) <add> if errRsp != &createdResponse { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> <add> sp := servicePublish{ <add> Name: "web", <add> Network: "network", <add> ExposedPorts: []types.TransportPort{ <add> types.TransportPort{Proto: types.TCP, Port: uint16(6000)}, <add> types.TransportPort{Proto: types.UDP, Port: uint16(500)}, <add> types.TransportPort{Proto: types.TCP, Port: uint16(700)}, <add> }, <add> PortMapping: []types.PortBinding{ <add> types.PortBinding{Proto: types.TCP, Port: uint16(1230), HostPort: uint16(37000)}, <add> types.PortBinding{Proto: types.UDP, Port: uint16(1200), HostPort: uint16(36000)}, <add> types.PortBinding{Proto: types.TCP, Port: uint16(1120), HostPort: uint16(35000)}, <add> }, <add> } <add> b, err = json.Marshal(sp) <add> if err != nil { <add> t.Fatal(err) <add> } <add> si, errRsp := procPublishService(c, vars, b) <add> if errRsp != &createdResponse { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> sid := i2s(si) <add> <add> vars[urlEpID] = "" <add> _, errRsp = procUnpublishService(c, vars, nil) <add> if errRsp.isOK() { <add> t.Fatalf("Expected failure but succeeded") <add> } <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <add> } <add> <add> vars[urlEpID] = "unknown-service-id" <add> _, errRsp = procUnpublishService(c, vars, nil) <add> if errRsp.isOK() { <add> t.Fatalf("Expected failure but succeeded") <add> } <add> if errRsp.StatusCode != http.StatusNotFound { <add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <add> } <add> <add> vars[urlEpID] = sid <add> _, errRsp = procUnpublishService(c, vars, nil) <add> if !errRsp.isOK() { <add> t.Fatalf("Unexpected failure: %v", errRsp) <add> } <add> <add> _, errRsp = procGetService(c, vars, nil) <add> if errRsp.isOK() { <add> t.Fatalf("Expected failure, but suceeded") <add> } <add> if errRsp.StatusCode != http.StatusNotFound { <add> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp) <add> } <add>} <add> <add>func TestAttachDetachBackend(t *testing.T) { <add> defer netutils.SetupTestNetNS(t)() <add> <add> c, nw := createTestNetwork(t, "network") <add> ep1, err := nw.CreateEndpoint("db") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> vars := make(map[string]string) <add> <add> vbad, err := json.Marshal("bad data") <add> if err != nil { <add> t.Fatal(err) <add> } <add> _, errRsp := procAttachBackend(c, vars, vbad) <add> if errRsp == &successResponse { <add> t.Fatalf("Expected failure, got: %v", errRsp) <add> } <add> <add> vars[urlEpName] = "endpoint" <add> bad, err := json.Marshal(endpointJoin{}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> _, errRsp = procAttachBackend(c, vars, bad) <add> if errRsp == &successResponse { <add> t.Fatalf("Expected failure, got: %v", errRsp) <add> } <add> if errRsp.StatusCode != http.StatusNotFound { <add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <add> } <add> <add> vars[urlEpName] = "db" <add> _, errRsp = procAttachBackend(c, vars, bad) <add> if errRsp == &successResponse { <add> t.Fatalf("Expected failure, got: %v", errRsp) <add> } <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <add> } <add> <add> cid := "abcdefghi" <add> jl := endpointJoin{ContainerID: cid} <add> jlb, err := json.Marshal(jl) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> _, errRsp = procAttachBackend(c, vars, jlb) <add> if errRsp != &successResponse { <add> t.Fatalf("Unexpected failure, got: %v", errRsp) <add> } <add> <add> vars[urlEpName] = "endpoint" <add> _, errRsp = procDetachBackend(c, vars, nil) <add> if errRsp == &successResponse { <add> t.Fatalf("Expected failure, got: %v", errRsp) <add> } <add> if errRsp.StatusCode != http.StatusNotFound { <add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <add> } <add> <add> vars[urlEpName] = "db" <add> _, errRsp = procDetachBackend(c, vars, nil) <add> if errRsp == &successResponse { <add> t.Fatalf("Expected failure, got: %v", errRsp) <add> } <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <add> } <add> <add> vars[urlCnID] = cid <add> _, errRsp = procDetachBackend(c, vars, nil) <add> if errRsp != &successResponse { <add> t.Fatalf("Unexpected failure, got: %v", errRsp) <add> } <add> <add> err = ep1.Delete() <add> if err != nil { <add> t.Fatal(err) <add> } <add>} <add> <ide> func TestDetectGetNetworksInvalidQueryComposition(t *testing.T) { <ide> c, err := libnetwork.New("") <ide> if err != nil { <ide> func TestDetectGetEndpointsInvalidQueryComposition(t *testing.T) { <ide> } <ide> } <ide> <add>func TestDetectGetServicesInvalidQueryComposition(t *testing.T) { <add> defer netutils.SetupTestNetNS(t)() <add> <add> c, _ := createTestNetwork(t, "network") <add> <add> vars := map[string]string{urlNwName: "network", urlEpName: "x", urlEpPID: "y"} <add> _, errRsp := procGetServices(c, vars, nil) <add> if errRsp.StatusCode != http.StatusBadRequest { <add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <add> } <add>} <add> <add>func TestFindNetworkUtilPanic(t *testing.T) { <add> defer checkPanic(t) <add> findNetwork(nil, "", -1) <add>} <add> <ide> func TestFindNetworkUtil(t *testing.T) { <ide> defer netutils.SetupTestNetNS(t)() <ide> <ide> c, nw := createTestNetwork(t, "network") <ide> nid := nw.ID() <ide> <del> defer checkPanic(t) <del> findNetwork(c, "", -1) <del> <ide> _, errRsp := findNetwork(c, "", byName) <ide> if errRsp == &successResponse { <ide> t.Fatalf("Expected to fail but succeeded") <ide> func TestFindNetworkUtil(t *testing.T) { <ide> t.Fatalf("Incorrect libnetwork.Network resource. It has different name: %v", n) <ide> } <ide> <del> n.Delete() <add> if err := n.Delete(); err != nil { <add> t.Fatalf("Failed to delete the network: %s", err.Error()) <add> } <ide> <ide> _, errRsp = findNetwork(c, nid, byID) <ide> if errRsp == &successResponse { <ide> func TestJoinLeave(t *testing.T) { <ide> } <ide> } <ide> <add>func TestFindEndpointUtilPanic(t *testing.T) { <add> defer netutils.SetupTestNetNS(t)() <add> defer checkPanic(t) <add> c, nw := createTestNetwork(t, "network") <add> nid := nw.ID() <add> findEndpoint(c, nid, "", byID, -1) <add>} <add> <add>func TestFindServiceUtilPanic(t *testing.T) { <add> defer netutils.SetupTestNetNS(t)() <add> defer checkPanic(t) <add> c, _ := createTestNetwork(t, "network") <add> findService(c, "random_service", -1) <add>} <add> <ide> func TestFindEndpointUtil(t *testing.T) { <ide> defer netutils.SetupTestNetNS(t)() <ide> <ide> func TestFindEndpointUtil(t *testing.T) { <ide> } <ide> eid := ep.ID() <ide> <del> defer checkPanic(t) <del> findEndpoint(c, nid, "", byID, -1) <del> <ide> _, errRsp := findEndpoint(c, nid, "", byID, byName) <ide> if errRsp == &successResponse { <ide> t.Fatalf("Expected failure, but got: %v", errRsp) <ide> func TestFindEndpointUtil(t *testing.T) { <ide> t.Fatalf("Unexepected failure: %v", errRsp) <ide> } <ide> <del> ep1, errRsp := findEndpoint(c, "second", "secondEp", byName, byName) <add> ep1, errRsp := findEndpoint(c, "network", "secondEp", byName, byName) <ide> if errRsp != &successResponse { <ide> t.Fatalf("Unexepected failure: %v", errRsp) <ide> } <ide> func TestFindEndpointUtil(t *testing.T) { <ide> t.Fatalf("Unexepected failure: %v", errRsp) <ide> } <ide> <del> ep3, errRsp := findEndpoint(c, "second", eid, byName, byID) <add> ep3, errRsp := findEndpoint(c, "network", eid, byName, byID) <add> if errRsp != &successResponse { <add> t.Fatalf("Unexepected failure: %v", errRsp) <add> } <add> <add> ep4, errRsp := findService(c, "secondEp", byName) <add> if errRsp != &successResponse { <add> t.Fatalf("Unexepected failure: %v", errRsp) <add> } <add> <add> ep5, errRsp := findService(c, eid, byID) <ide> if errRsp != &successResponse { <ide> t.Fatalf("Unexepected failure: %v", errRsp) <ide> } <ide> <del> if ep0 != ep1 || ep0 != ep2 || ep0 != ep3 { <add> if ep0 != ep1 || ep0 != ep2 || ep0 != ep3 || ep0 != ep4 || ep0 != ep5 { <ide> t.Fatalf("Diffenrent queries returned different endpoints") <ide> } <ide> <ide> func TestFindEndpointUtil(t *testing.T) { <ide> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <ide> } <ide> <del> _, errRsp = findEndpoint(c, "second", "secondEp", byName, byName) <add> _, errRsp = findEndpoint(c, "network", "secondEp", byName, byName) <ide> if errRsp == &successResponse { <ide> t.Fatalf("Expected failure, but got: %v", errRsp) <ide> } <ide> func TestFindEndpointUtil(t *testing.T) { <ide> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <ide> } <ide> <del> _, errRsp = findEndpoint(c, "second", eid, byName, byID) <add> _, errRsp = findEndpoint(c, "network", eid, byName, byID) <ide> if errRsp == &successResponse { <ide> t.Fatalf("Expected failure, but got: %v", errRsp) <ide> } <ide> if errRsp.StatusCode != http.StatusNotFound { <ide> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <ide> } <add> <add> _, errRsp = findService(c, "secondEp", byName) <add> if errRsp == &successResponse { <add> t.Fatalf("Expected failure, but got: %v", errRsp) <add> } <add> if errRsp.StatusCode != http.StatusNotFound { <add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <add> } <add> <add> _, errRsp = findService(c, eid, byID) <add> if errRsp == &successResponse { <add> t.Fatalf("Expected failure, but got: %v", errRsp) <add> } <add> if errRsp.StatusCode != http.StatusNotFound { <add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <add> } <add>} <add> <add>func TestEndpointToService(t *testing.T) { <add> r := &responseStatus{Status: "this is one endpoint", StatusCode: http.StatusOK} <add> r = endpointToService(r) <add> if r.Status != "this is one service" { <add> t.Fatalf("endpointToService returned unexpected status string: %s", r.Status) <add> } <add> <add> r = &responseStatus{Status: "this is one network", StatusCode: http.StatusOK} <add> r = endpointToService(r) <add> if r.Status != "this is one network" { <add> t.Fatalf("endpointToService returned unexpected status string: %s", r.Status) <add> } <ide> } <ide> <ide> func checkPanic(t *testing.T) { <ide><path>libnetwork/api/types.go <ide> type endpointJoin struct { <ide> UseDefaultSandbox bool `json:"use_default_sandbox"` <ide> } <ide> <add>// servicePublish represents the body of the "publish service" http request message <add>type servicePublish struct { <add> Name string `json:"name"` <add> Network string `json:"network"` <add> ExposedPorts []types.TransportPort `json:"exposed_ports"` <add> PortMapping []types.PortBinding `json:"port_mapping"` <add>} <add> <ide> // EndpointExtraHost represents the extra host object <ide> type endpointExtraHost struct { <ide> Name string `json:"name"` <ide><path>libnetwork/error.go <ide> func (nsn ErrNoSuchNetwork) Error() string { <ide> return fmt.Sprintf("network %s not found", string(nsn)) <ide> } <ide> <del>// BadRequest denotes the type of this error <del>func (nsn ErrNoSuchNetwork) BadRequest() {} <add>// NotFound denotes the type of this error <add>func (nsn ErrNoSuchNetwork) NotFound() {} <ide> <ide> // ErrNoSuchEndpoint is returned when a endpoint query finds no result <ide> type ErrNoSuchEndpoint string <ide> func (nse ErrNoSuchEndpoint) Error() string { <ide> return fmt.Sprintf("endpoint %s not found", string(nse)) <ide> } <ide> <del>// BadRequest denotes the type of this error <del>func (nse ErrNoSuchEndpoint) BadRequest() {} <add>// NotFound denotes the type of this error <add>func (nse ErrNoSuchEndpoint) NotFound() {} <ide> <ide> // ErrInvalidNetworkDriver is returned if an invalid driver <ide> // name is passed.
4
Javascript
Javascript
ignore bogus rowspan=1 and colspan=1 in ie
35adade6ac0b4e485b75fe49e0af6338ff816213
<ide><path>test/testabilityPatch.js <ide> function sortedHtml(element, showNgClass) { <ide> attr.name !='style' && <ide> attr.name.substr(0, 6) != 'jQuery') { <ide> // in IE we need to check for all of these. <del> if (!/ng-\d+/.exec(attr.name) && <del> attr.name != 'getElementById' && <add> if (/ng-\d+/.exec(attr.name) || <add> attr.name == 'getElementById' || <ide> // IE7 has `selected` in attributes <del> attr.name !='selected' && <add> attr.name == 'selected' || <ide> // IE7 adds `value` attribute to all LI tags <del> (node.nodeName != 'LI' || attr.name != 'value')) <del> attrs.push(' ' + attr.name + '="' + attr.value + '"'); <add> (node.nodeName == 'LI' && attr.name == 'value') || <add> // IE8 adds bogus rowspan=1 and colspan=1 to TD elements <add> (node.nodeName == 'TD' && attr.name == 'rowSpan' && attr.value == '1') || <add> (node.nodeName == 'TD' && attr.name == 'colSpan' && attr.value == '1')) { <add> continue; <add> } <add> <add> attrs.push(' ' + attr.name + '="' + attr.value + '"'); <ide> } <ide> } <ide> attrs.sort();
1
Python
Python
add version option to cli.train
7fdfb78141a90d1f27ebd50406d0ba3591a1253f
<ide><path>spacy/cli/train.py <ide> no_parser=("Don't train parser", "flag", "P", bool), <ide> no_entities=("Don't train NER", "flag", "N", bool), <ide> gold_preproc=("Use gold preprocessing", "flag", "G", bool), <add> version=("Model version", "option", "v", str), <ide> meta_path=("Optional path to meta.json. All relevant properties will be overwritten.", "option", "m", Path) <ide> ) <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0, <ide> use_gpu=-1, vectors=None, no_tagger=False, no_parser=False, no_entities=False, <del> gold_preproc=False, meta_path=None): <add> gold_preproc=False, version="0.0.0", meta_path=None): <ide> """ <ide> Train a model. Expects data in spaCy's JSON format. <ide> """ <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0, <ide> meta['pipeline'] = pipeline <ide> meta['spacy_version'] = '>=%s' % about.__version__ <ide> meta.setdefault('name', 'model%d' % i) <del> meta.setdefault('version', '0.0.0') <add> meta.setdefault('version', version) <ide> <ide> with meta_loc.open('w') as file_: <ide> file_.write(json_dumps(meta))
1
Python
Python
add implementation of coulomb's law
57a7e5738b8224f58941019964da67ece679eab9
<ide><path>electronics/coulombs_law.py <add># https://en.wikipedia.org/wiki/Coulomb%27s_law <add> <add>from __future__ import annotations <add> <add>COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2 <add> <add> <add>def couloumbs_law( <add> force: float, charge1: float, charge2: float, distance: float <add>) -> dict[str, float]: <add> <add> """ <add> Apply Coulomb's Law on any three given values. These can be force, charge1, <add> charge2, or distance, and then in a Python dict return name/value pair of <add> the zero value. <add> <add> Coulomb's Law states that the magnitude of the electrostatic force of <add> attraction or repulsion between two point charges is directly proportional <add> to the product of the magnitudes of charges and inversely proportional to <add> the square of the distance between them. <add> <add> Reference <add> ---------- <add> Coulomb (1785) "Premier mémoire sur l’électricité et le magnétisme," <add> Histoire de l’Académie Royale des Sciences, pp. 569–577. <add> <add> Parameters <add> ---------- <add> force : float with units in Newtons <add> <add> charge1 : float with units in Coulombs <add> <add> charge2 : float with units in Coulombs <add> <add> distance : float with units in meters <add> <add> Returns <add> ------- <add> result : dict name/value pair of the zero value <add> <add> >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=2000) <add> {'force': 33705.0} <add> <add> >>> couloumbs_law(force=10, charge1=3, charge2=5, distance=0) <add> {'distance': 116112.01488218177} <add> <add> >>> couloumbs_law(force=10, charge1=0, charge2=5, distance=2000) <add> {'charge1': 0.0008900756564307966} <add> <add> >>> couloumbs_law(force=0, charge1=0, charge2=5, distance=2000) <add> Traceback (most recent call last): <add> ... <add> ValueError: One and only one argument must be 0 <add> <add> >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=-2000) <add> Traceback (most recent call last): <add> ... <add> ValueError: Distance cannot be negative <add> <add> """ <add> <add> charge_product = abs(charge1 * charge2) <add> <add> if (force, charge1, charge2, distance).count(0) != 1: <add> raise ValueError("One and only one argument must be 0") <add> if distance < 0: <add> raise ValueError("Distance cannot be negative") <add> if force == 0: <add> force = COULOMBS_CONSTANT * charge_product / (distance ** 2) <add> return {"force": force} <add> elif charge1 == 0: <add> charge1 = abs(force) * (distance ** 2) / (COULOMBS_CONSTANT * charge2) <add> return {"charge1": charge1} <add> elif charge2 == 0: <add> charge2 = abs(force) * (distance ** 2) / (COULOMBS_CONSTANT * charge1) <add> return {"charge2": charge2} <add> elif distance == 0: <add> distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5 <add> return {"distance": distance} <add> raise ValueError("Exactly one argument must be 0") <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
1
Text
Text
update best practises
a42675f7d6c91017d930dfd427f6f73bf5b61753
<ide><path>docs/New-Maintainer-Checklist.md <ide> First, send them the invitation email: <ide> <ide> ``` <ide> The Homebrew team and I really appreciate your help on issues, pull requests and <del>your contributions around $THEIR_CONTRIBUTIONS. <add>your contributions to Homebrew. <ide> <ide> We would like to invite you to have commit access and be a Homebrew maintainer. <ide> If you agree to be a maintainer, you should spend a significant proportion of <ide> issues that arise from your code in a timely fashion and reviewing user <ide> contributions. You should also be making contributions to Homebrew every month <ide> unless you are ill or on vacation (and please let another maintainer know if <ide> that's the case so we're aware you won't be able to help while you are out). <del>You will need to watch Homebrew/brew and/or Homebrew/homebrew-core. If you're <del>no longer able to perform all of these tasks, please continue to contribute to <del>Homebrew, but we will ask you to step down as a maintainer. <add> <add>You will need to watch Homebrew/brew and/or Homebrew/homebrew-core. Let us know <add>which (or both) so we can grant you commit access appropriately. <add> <add>If you're no longer able to perform all of these tasks, please continue to <add>contribute to Homebrew, but we will ask you to step down as a maintainer. <ide> <ide> A few requests: <ide> <ide> If they accept, follow a few steps to get them set up: <ide> - Add them to the [Jenkins' GitHub Pull Request Builder admin list](https://jenkins.brew.sh/configure) to enable `@BrewTestBot test this please` for them <ide> - Invite them to the [`homebrew-maintainers` private maintainers mailing list](https://lists.sfconservancy.org/mailman/admin/homebrew-maintainers/members/add) <ide> - Invite them to the [`machomebrew` private maintainers Slack](https://machomebrew.slack.com/admin/invites) (and ensure they've read the [communication guidelines](Maintainer-Guidelines.md#communication)) <del>- Add them to [Homebrew's README](https://github.com/Homebrew/brew/edit/master/README.md) <add>- Ask them to disable SMS as a 2FA device or fallback on their GitHub account in favour of using one of the other authentication methods. <add>- Ask them to (regularly) review remove any unneeded [GitHub personal access tokens](https://github.com/settings/tokens) <add>- Add them to [Homebrew/brew's README](https://github.com/Homebrew/brew/edit/master/README.md) <ide> <ide> If they are also interested in doing system administration work: <ide> <ide> If they want to consume raw anonymous aggregate analytics data (rather than use <ide> <ide> Once they have been active maintainers for at least a year and had some activity on more than one Homebrew organisation repository (or one repository and helped with system administration work): <ide> <del>- Homebrew's [Software Freedom Conservancy](https://sfconservancy.org) Project Leadership Committee can take a vote on whether to extend an offer to the maintainer to join the committee. If they accept, email their name, email and employer to homebrew@sfconservancy.org and make them [owners on the Homebrew GitHub organisation](https://github.com/orgs/Homebrew/people). <add>- Homebrew's [Software Freedom Conservancy](https://sfconservancy.org) Project Leadership Committee can take a vote on whether to extend an offer to the maintainer to join the committee. If they accept, email their name, email and employer to homebrew@sfconservancy.org, make them [owners on the Homebrew GitHub organisation](https://github.com/orgs/Homebrew/people) and add them to the relevant section of the [Homebrew/brew's README](https://github.com/Homebrew/brew/edit/master/README.md). <ide> <ide> If there are problems, ask them to step down as a maintainer and revoke their access to all of the above. <ide>
1
Javascript
Javascript
improve readability on conditional assignment
78d2620576386df9f037e87ef4b09c60e8694a77
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide, $$sanitizeUriProvider) { <ide> function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { <ide> var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn; <ide> <del> if (compileNode === linkNode) { <del> attrs = templateAttrs; <del> } else { <del> attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); <del> } <add> attrs = (compileNode === linkNode) <add> ? templateAttrs <add> : shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); <ide> $element = attrs.$$element; <ide> <ide> if (newIsolateScopeDirective) {
1
Text
Text
add style_guide (moved from nodejs/docs)
ca5215ebe37ced58baf1247ad931172ae3f9ca91
<ide><path>CONTRIBUTING.md <ide> Create a branch and start hacking: <ide> $ git checkout -b my-branch -t origin/master <ide> ``` <ide> <add>Any text you write should follow the [Style Guide](doc/STYLE_GUIDE.md), <add>including comments and API documentation. <add> <ide> ### Step 3: Commit <ide> <ide> Make sure git knows your name and email address: <ide><path>doc/STYLE-GUIDE.md <add># Style Guide <add> <add>* Documents are written in markdown files. <add>* Those files should be written in **`lowercase-with-dashes.md`.** <add> * Underscores in filenames are allowed only when they are present in the <add> topic the document will describe (e.g., `child_process`.) <add> * Filenames should be **lowercase**. <add> * Some files, such as top-level markdown files, are exceptions. <add> * Older files may use the `.markdown` extension. These may be ported to `.md` <add> at will. **Prefer `.md` for all new documents.** <add>* Documents should be word-wrapped at 80 characters. <add>* The formatting described in `.editorconfig` is preferred. <add> * A [plugin][] is available for some editors to automatically apply these rules. <add>* Mechanical issues, like spelling and grammar, should be identified by tools, <add> insofar as is possible. If not caught by a tool, they should be pointed out by <add> human reviewers. <add>* American English spelling is preferred. "Capitalize" vs. "Capitalise", <add> "color" vs. "colour", etc. <add>* Though controversial, the [Oxford comma][] is preferred for clarity's sake. <add>* Generally avoid personal pronouns in reference documentation ("I", "you", <add> "we".) <add> * Pronouns are acceptable in more colloquial documentation, like guides. <add> * Use **gender-neutral pronouns** and **mass nouns**. Non-comprehensive <add> examples: <add> * **OK**: "they", "their", "them", "folks", "people", "developers", "cats" <add> * **NOT OK**: "his", "hers", "him", "her", "guys", "dudes". <add>* When combining wrapping elements (parentheses and quotes), terminal <add> punctuation should be placed: <add> * Inside the wrapping element if the wrapping element contains a complete <add> clause — a subject, verb, and an object. <add> * Outside of the wrapping element if the wrapping element contains only a <add> fragment of a clause. <add>* Place end-of-sentence punctuation inside wrapping elements — periods go <add> inside parentheses and quotes, not after. <add>* Documents must start with a level-one heading. An example document will be <add> linked here eventually. <add>* Prefer affixing links to inlining links — prefer `[a link][]` to <add> `[a link](http://example.com)`. <add>* When documenting APIs, note the version the API was introduced in at <add> the end of the section. If an API has been deprecated, also note the first <add> version that the API appeared deprecated in. <add>* When using dashes, use emdashes ("—", Ctrl+Alt+"-" on OSX) surrounded by <add> spaces, per the New York Times usage. <add>* Including assets: <add> * If you wish to add an illustration or full program, add it to the <add> appropriate sub-directory in the `assets/` dir. <add> * Link to it like so: `[Asset](/assets/{subdir}/{filename})` for file-based <add> assets, and `![Asset](/assets/{subdir}/{filename})` for image-based assets. <add> * For illustrations, prefer SVG to other assets. When SVG is not feasible, <add> please keep a close eye on the filesize of the asset you're introducing. <add>* For code blocks: <add> * Use language aware fences. ("```js") <add> * Code need not be complete — treat code blocks as an illustration or aid to <add> your point, not as complete running programs. If a complete running program <add> is necessary, include it as an asset in `assets/code-examples` and link to <add> it. <add>* When using underscores, asterisks and backticks please use proper escaping (**\\\_**, **\\\*** and **\\\`** instead of **\_**, **\*** and **\`**) <add>* References to constructor functions should use PascalCase <add>* References to constructor instances should be camelCased <add>* References to methods should be used with parenthesis: `socket.end()` instead of `socket.end` <add> <add>[plugin]: http://editorconfig.org/#download <add>[Oxford comma]: https://en.wikipedia.org/wiki/Serial_comma
2
Java
Java
add httprequestbuilder default implementation
a6469baa4f84de1b9da0131db981e2f42b09969d
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/DefaultHttpRequestBuilder.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.client.reactive; <add> <add> <add>import java.net.URI; <add>import java.net.URISyntaxException; <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.List; <add>import java.util.Optional; <add>import java.util.stream.Collectors; <add> <add>import org.reactivestreams.Publisher; <add>import reactor.core.publisher.Flux; <add> <add>import org.springframework.core.ResolvableType; <add>import org.springframework.core.codec.Encoder; <add>import org.springframework.http.HttpCookie; <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.HttpMethod; <add>import org.springframework.http.MediaType; <add>import org.springframework.http.client.reactive.ClientHttpRequest; <add>import org.springframework.http.client.reactive.ClientHttpRequestFactory; <add>import org.springframework.web.client.RestClientException; <add> <add>/** <add> * Builds a {@link ClientHttpRequest} <add> * <add> * <p>See static factory methods in {@link HttpRequestBuilders} <add> * <add> * @author Brian Clozel <add> * @see HttpRequestBuilders <add> */ <add>public class DefaultHttpRequestBuilder implements HttpRequestBuilder { <add> <add> protected HttpMethod httpMethod; <add> <add> protected HttpHeaders httpHeaders; <add> <add> protected URI url; <add> <add> protected Flux contentPublisher; <add> <add> protected List<Encoder<?>> messageEncoders; <add> <add> protected final List<HttpCookie> cookies = new ArrayList<HttpCookie>(); <add> <add> protected DefaultHttpRequestBuilder() { <add> } <add> <add> public DefaultHttpRequestBuilder(HttpMethod httpMethod, String urlTemplate, Object... urlVariables) throws RestClientException { <add> this.httpMethod = httpMethod; <add> this.httpHeaders = new HttpHeaders(); <add> this.url = parseURI(urlTemplate); <add> } <add> <add> public DefaultHttpRequestBuilder(HttpMethod httpMethod, URI url) { <add> this.httpMethod = httpMethod; <add> this.httpHeaders = new HttpHeaders(); <add> this.url = url; <add> } <add> <add> protected DefaultHttpRequestBuilder setMessageEncoders(List<Encoder<?>> messageEncoders) { <add> this.messageEncoders = messageEncoders; <add> return this; <add> } <add> <add> private URI parseURI(String uri) throws RestClientException { <add> try { <add> return new URI(uri); <add> } <add> catch (URISyntaxException e) { <add> throw new RestClientException("could not parse URL template", e); <add> } <add> } <add> <add> public DefaultHttpRequestBuilder param(String name, String... values) { <add> return this; <add> } <add> <add> public DefaultHttpRequestBuilder header(String name, String... values) { <add> Arrays.stream(values).forEach(value -> this.httpHeaders.add(name, value)); <add> return this; <add> } <add> <add> public DefaultHttpRequestBuilder headers(HttpHeaders httpHeaders) { <add> this.httpHeaders = httpHeaders; <add> return this; <add> } <add> <add> public DefaultHttpRequestBuilder contentType(MediaType contentType) { <add> this.httpHeaders.setContentType(contentType); <add> return this; <add> } <add> <add> public DefaultHttpRequestBuilder contentType(String contentType) { <add> this.httpHeaders.setContentType(MediaType.parseMediaType(contentType)); <add> return this; <add> } <add> <add> public DefaultHttpRequestBuilder accept(MediaType... mediaTypes) { <add> this.httpHeaders.setAccept(Arrays.asList(mediaTypes)); <add> return this; <add> } <add> <add> public DefaultHttpRequestBuilder accept(String... mediaTypes) { <add> this.httpHeaders.setAccept(Arrays.stream(mediaTypes) <add> .map(type -> MediaType.parseMediaType(type)) <add> .collect(Collectors.toList())); <add> return this; <add> } <add> <add> public DefaultHttpRequestBuilder content(Object content) { <add> this.contentPublisher = Flux.just(content); <add> return this; <add> } <add> <add> public DefaultHttpRequestBuilder contentStream(Publisher content) { <add> this.contentPublisher = Flux.from(content); <add> return this; <add> } <add> <add> public ClientHttpRequest build(ClientHttpRequestFactory factory) { <add> ClientHttpRequest request = factory.createRequest(this.httpMethod, this.url, this.httpHeaders); <add> request.getHeaders().putAll(this.httpHeaders); <add> <add> if (this.contentPublisher != null) { <add> ResolvableType requestBodyType = ResolvableType.forInstance(this.contentPublisher); <add> MediaType mediaType = request.getHeaders().getContentType(); <add> <add> Optional<Encoder<?>> messageEncoder = resolveEncoder(requestBodyType, mediaType); <add> <add> if (messageEncoder.isPresent()) { <add> request.setBody(messageEncoder.get().encode(this.contentPublisher, requestBodyType, mediaType)); <add> } <add> else { <add> // TODO: wrap with client exception? <add> request.setBody(Flux.error(new IllegalStateException("Can't write request body" + <add> "of type '" + requestBodyType.toString() + <add> "' for content-type '" + mediaType.toString() + "'"))); <add> } <add> } <add> <add> return request; <add> } <add> <add> protected Optional<Encoder<?>> resolveEncoder(ResolvableType type, MediaType mediaType) { <add> return this.messageEncoders.stream() <add> .filter(e -> e.canEncode(type, mediaType)).findFirst(); <add> } <add> <add>} <ide>\ No newline at end of file <add><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/HttpRequestBuilder.java <del><path>spring-web-reactive/src/main/java/org/springframework/web/client/HttpRequestBuilder.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.client; <add>package org.springframework.web.client.reactive; <ide> <ide> import org.springframework.http.client.reactive.ClientHttpRequest; <ide> import org.springframework.http.client.reactive.ClientHttpRequestFactory; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/HttpRequestBuilders.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.client.reactive; <add> <add>import org.springframework.http.HttpMethod; <add> <add>/** <add> * Static factory methods for {@link DefaultHttpRequestBuilder RequestBuilders}. <add> * <add> * @author Brian Clozel <add> */ <add>public abstract class HttpRequestBuilders { <add> <add> /** <add> * Create a {@link DefaultHttpRequestBuilder} for a GET request. <add> * <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <add> */ <add> public static DefaultHttpRequestBuilder get(String urlTemplate, Object... urlVariables) { <add> return new DefaultHttpRequestBuilder(HttpMethod.GET, urlTemplate, urlVariables); <add> } <add> <add> /** <add> * Create a {@link DefaultHttpRequestBuilder} for a POST request. <add> * <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <add> */ <add> public static DefaultHttpRequestBuilder post(String urlTemplate, Object... urlVariables) { <add> return new DefaultHttpRequestBuilder(HttpMethod.POST, urlTemplate, urlVariables); <add> } <add> <add> <add> /** <add> * Create a {@link DefaultHttpRequestBuilder} for a PUT request. <add> * <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <add> */ <add> public static DefaultHttpRequestBuilder put(String urlTemplate, Object... urlVariables) { <add> return new DefaultHttpRequestBuilder(HttpMethod.PUT, urlTemplate, urlVariables); <add> } <add> <add> /** <add> * Create a {@link DefaultHttpRequestBuilder} for a PATCH request. <add> * <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <add> */ <add> public static DefaultHttpRequestBuilder patch(String urlTemplate, Object... urlVariables) { <add> return new DefaultHttpRequestBuilder(HttpMethod.PATCH, urlTemplate, urlVariables); <add> } <add> <add> /** <add> * Create a {@link DefaultHttpRequestBuilder} for a DELETE request. <add> * <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <add> */ <add> public static DefaultHttpRequestBuilder delete(String urlTemplate, Object... urlVariables) { <add> return new DefaultHttpRequestBuilder(HttpMethod.DELETE, urlTemplate, urlVariables); <add> } <add> <add> /** <add> * Create a {@link DefaultHttpRequestBuilder} for an OPTIONS request. <add> * <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <add> */ <add> public static DefaultHttpRequestBuilder options(String urlTemplate, Object... urlVariables) { <add> return new DefaultHttpRequestBuilder(HttpMethod.OPTIONS, urlTemplate, urlVariables); <add> } <add> <add> /** <add> * Create a {@link DefaultHttpRequestBuilder} for a HEAD request. <add> * <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <add> */ <add> public static DefaultHttpRequestBuilder head(String urlTemplate, Object... urlVariables) { <add> return new DefaultHttpRequestBuilder(HttpMethod.HEAD, urlTemplate, urlVariables); <add> } <add> <add> /** <add> * Create a {@link DefaultHttpRequestBuilder} for a request with the given HTTP method. <add> * <add> * @param httpMethod the HTTP method <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <add> */ <add> public static DefaultHttpRequestBuilder request(HttpMethod httpMethod, String urlTemplate, Object... urlVariables) { <add> return new DefaultHttpRequestBuilder(httpMethod, urlTemplate, urlVariables); <add> } <add> <add>} <ide>\ No newline at end of file
3
Javascript
Javascript
resolve the true entry point during tests
86715efa23c02dd156e61a4476f28045bb5f4654
<ide><path>packages/react-dom/src/__tests__/ReactDOMFiberAsync-test.js <ide> describe('ReactDOMFiberAsync', () => { <ide> expect(ops).toEqual(['BC', 'ABCD']); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('flushControlled flushes updates before yielding to browser', () => { <ide> let inst; <ide> class Counter extends React.Component { <ide> describe('ReactDOMFiberAsync', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('flushControlled does not flush until end of outermost batchedUpdates', () => { <ide> let inst; <ide> class Counter extends React.Component { <ide> describe('ReactDOMFiberAsync', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('flushControlled returns nothing', () => { <ide> // In the future, we may want to return a thenable "work" object. <ide> let inst; <ide><path>packages/react-dom/src/__tests__/ReactDOMServerPartialHydration-test.internal.js <ide> describe('ReactDOMServerPartialHydration', () => { <ide> expect(span.className).toBe('hi'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('blocks updates to hydrate the content first if props changed at idle priority', async () => { <ide> let suspend = false; <ide> let resolve; <ide> describe('ReactDOMServerPartialHydration', () => { <ide> expect(container.textContent).toBe('ALoading B'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('clears server boundaries when SuspenseList runs out of time hydrating', async () => { <ide> let suspend = false; <ide> let resolve; <ide> describe('ReactDOMServerPartialHydration', () => { <ide> document.body.removeChild(container); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('does not invoke an event on a hydrated event handle until it commits', async () => { <ide> const setClick = ReactDOM.unstable_createEventHandle('click'); <ide> let suspend = false; <ide> describe('ReactDOMServerPartialHydration', () => { <ide> document.body.removeChild(container); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('invokes discrete events on nested suspense boundaries in a root (createEventHandle)', async () => { <ide> let suspend = false; <ide> let isServerRendering = true; <ide> describe('ReactDOMServerPartialHydration', () => { <ide> expect(span.innerHTML).toBe('Hidden child'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('renders a hidden LegacyHidden component inside a Suspense boundary', async () => { <ide> const ref = React.createRef(); <ide> <ide> describe('ReactDOMServerPartialHydration', () => { <ide> expect(span.innerHTML).toBe('Hidden child'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('renders a visible LegacyHidden component', async () => { <ide> const ref = React.createRef(); <ide> <ide><path>packages/react-dom/src/__tests__/ReactDOMServerSelectiveHydration-test.internal.js <ide> describe('ReactDOMServerSelectiveHydration', () => { <ide> document.body.removeChild(container); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('hydrates the target boundary synchronously during a click (createEventHandle)', async () => { <ide> const setClick = ReactDOM.unstable_createEventHandle('click'); <ide> let isServerRendering = true; <ide> describe('ReactDOMServerSelectiveHydration', () => { <ide> document.body.removeChild(container); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('hydrates at higher pri if sync did not work first time (createEventHandle)', async () => { <ide> let suspend = false; <ide> let isServerRendering = true; <ide> describe('ReactDOMServerSelectiveHydration', () => { <ide> document.body.removeChild(container); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('hydrates at higher pri for secondary discrete events (createEventHandle)', async () => { <ide> const setClick = ReactDOM.unstable_createEventHandle('click'); <ide> let suspend = false; <ide> describe('ReactDOMServerSelectiveHydration', () => { <ide> document.body.removeChild(container); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('hydrates the last explicitly hydrated target at higher priority', async () => { <ide> function Child({text}) { <ide> Scheduler.unstable_yieldValue(text); <ide> describe('ReactDOMServerSelectiveHydration', () => { <ide> expect(Scheduler).toFlushAndYield(['App', 'C', 'B', 'A']); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('hydrates before an update even if hydration moves away from it', async () => { <ide> function Child({text}) { <ide> Scheduler.unstable_yieldValue(text); <ide><path>packages/react-dom/src/__tests__/ReactDOMTestSelectors-test.internal.js <ide> describe('ReactDOMTestSelectors', () => { <ide> }); <ide> <ide> describe('findAllNodes', () => { <add> // @gate www <ide> it('should support searching from the document root', () => { <ide> function Example() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('match'); <ide> }); <ide> <add> // @gate www <ide> it('should support searching from the container', () => { <ide> function Example() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('match'); <ide> }); <ide> <add> // @gate www <ide> it('should support searching from a previous match if the match had a data-testname', () => { <ide> function Outer() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('inner'); <ide> }); <ide> <add> // @gate www <ide> it('should not support searching from a previous match if the match did not have a data-testname', () => { <ide> function Outer() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> ); <ide> }); <ide> <add> // @gate www <ide> it('should support an multiple component types in the selector array', () => { <ide> function Outer() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('match3'); <ide> }); <ide> <add> // @gate www <ide> it('should find multiple matches', () => { <ide> function Example1() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> ]); <ide> }); <ide> <add> // @gate www <ide> it('should ignore nested matches', () => { <ide> function Example() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toEqual('match1'); <ide> }); <ide> <add> // @gate www <ide> it('should enforce the specific order of selectors', () => { <ide> function Outer() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> ).toHaveLength(0); <ide> }); <ide> <add> // @gate www <ide> it('should not search within hidden subtrees', () => { <ide> const ref1 = React.createRef(null); <ide> const ref2 = React.createRef(null); <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0]).toBe(ref2.current); <ide> }); <ide> <add> // @gate www <ide> it('should support filtering by display text', () => { <ide> function Example() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('match'); <ide> }); <ide> <add> // @gate www <ide> it('should support filtering by explicit accessibiliy role', () => { <ide> function Example() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('match'); <ide> }); <ide> <add> // @gate www <ide> it('should support filtering by explicit secondary accessibiliy role', () => { <ide> const ref = React.createRef(); <ide> <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0]).toBe(ref.current); <ide> }); <ide> <add> // @gate www <ide> it('should support filtering by implicit accessibiliy role', () => { <ide> function Example() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('match'); <ide> }); <ide> <add> // @gate www <ide> it('should support filtering by implicit accessibiliy role with attributes qualifications', () => { <ide> function Example() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('match'); <ide> }); <ide> <add> // @gate www <ide> it('should support searching ahead with the has() selector', () => { <ide> function Example() { <ide> return ( <ide> describe('ReactDOMTestSelectors', () => { <ide> expect(matches[0].id).toBe('match'); <ide> }); <ide> <add> // @gate www <ide> it('should throw if no container can be found', () => { <ide> expect(() => findAllNodes(document.body, [])).toThrow( <ide> 'Could not find React container within specified host subtree.', <ide> ); <ide> }); <ide> <add> // @gate www <ide> it('should throw if an invalid host root is specified', () => { <ide> const ref = React.createRef(); <ide> function Example() { <ide> describe('ReactDOMTestSelectors', () => { <ide> }); <ide> <ide> describe('getFindAllNodesFailureDescription', () => { <add> // @gate www <ide> it('should describe findAllNodes failures caused by the component type selector', () => { <ide> function Outer() { <ide> return <Middle />; <ide> No matching component was found for: <ide> ); <ide> }); <ide> <add> // @gate www <ide> it('should return null if findAllNodes was able to find a match', () => { <ide> function Example() { <ide> return ( <ide> No matching component was found for: <ide> }; <ide> } <ide> <add> // @gate www <ide> it('should return a single rect for a component that returns a single root host element', () => { <ide> const ref = React.createRef(); <ide> <ide> No matching component was found for: <ide> }); <ide> }); <ide> <add> // @gate www <ide> it('should return a multiple rects for multiple matches', () => { <ide> const outerRef = React.createRef(); <ide> const innerRef = React.createRef(); <ide> No matching component was found for: <ide> }); <ide> }); <ide> <add> // @gate www <ide> it('should return a multiple rects for single match that returns a fragment', () => { <ide> const refA = React.createRef(); <ide> const refB = React.createRef(); <ide> No matching component was found for: <ide> }); <ide> }); <ide> <add> // @gate www <ide> it('should merge overlapping rects', () => { <ide> const refA = React.createRef(); <ide> const refB = React.createRef(); <ide> No matching component was found for: <ide> }); <ide> }); <ide> <add> // @gate www <ide> it('should merge some types of adjacent rects (if they are the same in one dimension)', () => { <ide> const refA = React.createRef(); <ide> const refB = React.createRef(); <ide> No matching component was found for: <ide> }); <ide> }); <ide> <add> // @gate www <ide> it('should not search within hidden subtrees', () => { <ide> const refA = React.createRef(); <ide> const refB = React.createRef(); <ide> No matching component was found for: <ide> }); <ide> <ide> describe('focusWithin', () => { <add> // @gate www <ide> it('should return false if the specified component path has no matches', () => { <ide> function Example() { <ide> return <Child />; <ide> No matching component was found for: <ide> expect(didFocus).toBe(false); <ide> }); <ide> <add> // @gate www <ide> it('should return false if there are no focusable elements within the matched subtree', () => { <ide> function Example() { <ide> return <Child />; <ide> No matching component was found for: <ide> expect(didFocus).toBe(false); <ide> }); <ide> <add> // @gate www <ide> it('should return false if the only focusable elements are disabled', () => { <ide> function Example() { <ide> return ( <ide> No matching component was found for: <ide> expect(didFocus).toBe(false); <ide> }); <ide> <add> // @gate www <ide> it('should return false if the only focusable elements are hidden', () => { <ide> function Example() { <ide> return <button hidden={true}>not clickable</button>; <ide> No matching component was found for: <ide> expect(didFocus).toBe(false); <ide> }); <ide> <add> // @gate www <ide> it('should successfully focus the first focusable element within the tree', () => { <ide> const secondRef = React.createRef(null); <ide> <ide> No matching component was found for: <ide> expect(handleThirdFocus).not.toHaveBeenCalled(); <ide> }); <ide> <add> // @gate www <ide> it('should successfully focus the first focusable element even if application logic interferes', () => { <ide> const ref = React.createRef(null); <ide> <ide> No matching component was found for: <ide> expect(handleFocus).toHaveBeenCalledTimes(1); <ide> }); <ide> <add> // @gate www <ide> it('should not focus within hidden subtrees', () => { <ide> const secondRef = React.createRef(null); <ide> <ide> No matching component was found for: <ide> window.IntersectionObserver = IntersectionObserver; <ide> }); <ide> <add> // @gate www <ide> it('should notify a listener when the underlying instance intersection changes', () => { <ide> const ref = React.createRef(null); <ide> <ide> No matching component was found for: <ide> expect(handleVisibilityChange).toHaveBeenCalledWith([{rect, ratio: 0.5}]); <ide> }); <ide> <add> // @gate www <ide> it('should notify a listener of multiple targets when the underlying instance intersection changes', () => { <ide> const ref1 = React.createRef(null); <ide> const ref2 = React.createRef(null); <ide> No matching component was found for: <ide> ]); <ide> }); <ide> <add> // @gate www <ide> it('should stop listening when its disconnected', () => { <ide> const ref = React.createRef(null); <ide> <ide> No matching component was found for: <ide> }); <ide> <ide> // This test reuires gating because it relies on the __DEV__ only commit hook to work. <del> // @gate __DEV__ <add> // @gate www && __DEV__ <ide> it('should update which targets its listening to after a commit', () => { <ide> const ref1 = React.createRef(null); <ide> const ref2 = React.createRef(null); <ide> No matching component was found for: <ide> ]); <ide> }); <ide> <add> // @gate www <ide> it('should not observe components within hidden subtrees', () => { <ide> const ref1 = React.createRef(null); <ide> const ref2 = React.createRef(null); <ide><path>packages/react-dom/src/__tests__/ReactUpdates-test.js <ide> describe('ReactUpdates', () => { <ide> expect(ops).toEqual(['Foo', 'Bar', 'Baz']); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('delays sync updates inside hidden subtrees in Concurrent Mode', () => { <ide> const container = document.createElement('div'); <ide> <ide><path>packages/react-dom/src/__tests__/ReactWrongReturnPointer-test.js <ide> test('warns in DEV if return pointer is inconsistent', async () => { <ide> ); <ide> }); <ide> <del>// @gate experimental <ide> // @gate enableCache <ide> test('regression (#20932): return pointer is correct before entering deleted tree', async () => { <ide> // Based on a production bug. Designed to trigger a very specific <ide><path>packages/react-dom/src/events/__tests__/DOMPluginEventSystem-test.internal.js <ide> describe('DOMPluginEventSystem', () => { <ide> act = ReactTestUtils.unstable_concurrentAct; <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('can render correctly with the ReactDOMServer', () => { <ide> const clickEvent = jest.fn(); <ide> const setClick = ReactDOM.unstable_createEventHandle('click'); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(output).toBe(`<div>Hello world</div>`); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('can render correctly with the ReactDOMServer hydration', () => { <ide> const clickEvent = jest.fn(); <ide> const spanRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(clickEvent).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly work for a basic "click" listener', () => { <ide> let log = []; <ide> const clickEvent = jest.fn(event => { <ide> describe('DOMPluginEventSystem', () => { <ide> expect(clickEvent2).toBeCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly work for setting and clearing a basic "click" listener', () => { <ide> const clickEvent = jest.fn(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(clickEvent).toBeCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should handle the target being a text node', () => { <ide> const clickEvent = jest.fn(); <ide> const buttonRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(clickEvent).toBeCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle propagation of click events', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(log[3]).toEqual(['bubble', buttonElement]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle propagation of click events mixed with onClick events', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(log[5]).toEqual(['bubble', buttonElement]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly work for a basic "click" listener on the outer target', () => { <ide> const log = []; <ide> const clickEvent = jest.fn(event => { <ide> describe('DOMPluginEventSystem', () => { <ide> expect(clickEvent).toBeCalledTimes(2); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly handle many nested target listeners', () => { <ide> const buttonRef = React.createRef(); <ide> const targetListener1 = jest.fn(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(targetListener4).toHaveBeenCalledTimes(2); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly handle stopPropagation correctly for target events', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(clickEvent).toHaveBeenCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly handle stopPropagation correctly for many target events', () => { <ide> const buttonRef = React.createRef(); <ide> const targetListener1 = jest.fn(e => e.stopPropagation()); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(targetListener4).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly handle stopPropagation for mixed capture/bubbling target listeners', () => { <ide> const buttonRef = React.createRef(); <ide> const targetListener1 = jest.fn(e => e.stopPropagation()); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(targetListener4).toHaveBeenCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should work with concurrent mode updates', async () => { <ide> const log = []; <ide> const ref = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(log).toEqual([{counter: 1}]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly work for a basic "click" window listener', () => { <ide> const log = []; <ide> const clickEvent = jest.fn(event => { <ide> describe('DOMPluginEventSystem', () => { <ide> expect(clickEvent).toBeCalledTimes(2); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle propagation of click events on the window', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(log[5]).toEqual(['bubble', window]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly handle stopPropagation for mixed listeners', () => { <ide> const buttonRef = React.createRef(); <ide> const rootListener1 = jest.fn(e => e.stopPropagation()); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(rootListener2).toHaveBeenCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly handle stopPropagation for delegated listeners', () => { <ide> const buttonRef = React.createRef(); <ide> const rootListener1 = jest.fn(e => e.stopPropagation()); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(rootListener4).toHaveBeenCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle propagation of click events on the window and document', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> } <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('does not support custom user events', () => { <ide> // With eager listeners, supporting custom events via this API doesn't make sense <ide> // because we can't know a full list of them ahead of time. Let's check we throw <ide> describe('DOMPluginEventSystem', () => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('beforeblur and afterblur are called after a focused element is unmounted', () => { <ide> const log = []; <ide> // We have to persist here because we want to read relatedTarget later. <ide> describe('DOMPluginEventSystem', () => { <ide> expect(log).toEqual(['beforeblur', 'afterblur']); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('beforeblur and afterblur are called after a nested focused element is unmounted', () => { <ide> const log = []; <ide> // We have to persist here because we want to read relatedTarget later. <ide> describe('DOMPluginEventSystem', () => { <ide> expect(log).toEqual(['beforeblur', 'afterblur']); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('beforeblur should skip handlers from a deleted subtree after the focused element is unmounted', () => { <ide> const onBeforeBlur = jest.fn(); <ide> const innerRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(onBeforeBlur).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('beforeblur and afterblur are called after a focused element is suspended', () => { <ide> const log = []; <ide> // We have to persist here because we want to read relatedTarget later. <ide> describe('DOMPluginEventSystem', () => { <ide> document.body.removeChild(container2); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('beforeblur should skip handlers from a deleted subtree after the focused element is suspended', () => { <ide> const onBeforeBlur = jest.fn(); <ide> const innerRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> document.body.removeChild(container2); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('regression: does not fire beforeblur/afterblur if target is already hidden', () => { <ide> const Suspense = React.Suspense; <ide> let suspend = false; <ide> describe('DOMPluginEventSystem', () => { <ide> document.body.removeChild(container2); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle propagation of click events between disjointed comment roots', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(log[5]).toEqual(['bubble', buttonElement]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('propagates known createEventHandle events through portals without inner listeners', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> ReactDOMServer = require('react-dom/server'); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle propagation of click events on a scope', () => { <ide> const buttonRef = React.createRef(); <ide> const log = []; <ide> describe('DOMPluginEventSystem', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle mixed propagation of click events on a scope', () => { <ide> const buttonRef = React.createRef(); <ide> const divRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should not handle the target being a dangling text node within a scope', () => { <ide> const clickEvent = jest.fn(); <ide> const buttonRef = React.createRef(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(clickEvent).toBeCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle stopPropagation (inner) correctly between scopes', () => { <ide> const buttonRef = React.createRef(); <ide> const outerOnClick = jest.fn(); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(outerOnClick).toHaveBeenCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle stopPropagation (outer) correctly between scopes', () => { <ide> const buttonRef = React.createRef(); <ide> const outerOnClick = jest.fn(e => e.stopPropagation()); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(outerOnClick).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('handle stopPropagation (inner and outer) correctly between scopes', () => { <ide> const buttonRef = React.createRef(); <ide> const onClick = jest.fn(e => e.stopPropagation()); <ide> describe('DOMPluginEventSystem', () => { <ide> expect(onClick).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should be able to register handlers for events affected by the intervention', () => { <ide> const rootContainer = document.createElement('div'); <ide> container.appendChild(rootContainer); <ide><path>packages/react-fetch/src/__tests__/ReactFetchNode-test.js <ide> describe('ReactFetchNode', () => { <ide> server = null; <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('can fetch text from a server component', async () => { <ide> serverImpl = (req, res) => { <ide> res.write('mango'); <ide> describe('ReactFetchNode', () => { <ide> expect(text).toEqual('mango'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('can fetch json from a server component', async () => { <ide> serverImpl = (req, res) => { <ide> res.write(JSON.stringify({name: 'Sema'})); <ide> describe('ReactFetchNode', () => { <ide> expect(json).toEqual({name: 'Sema'}); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('provides response status', async () => { <ide> serverImpl = (req, res) => { <ide> res.write(JSON.stringify({name: 'Sema'})); <ide> describe('ReactFetchNode', () => { <ide> }); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('handles different paths', async () => { <ide> serverImpl = (req, res) => { <ide> switch (req.url) { <ide> describe('ReactFetchNode', () => { <ide> expect(outputs).toMatchObject(['banana', 'mango', 'orange']); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('can produce an error', async () => { <ide> serverImpl = (req, res) => {}; <ide> <ide><path>packages/react-interactions/events/src/dom/create-event-handle/__tests__/useFocus-test.internal.js <ide> function initializeModules(hasPointerEvents) { <ide> <ide> // TODO: This import throws outside of experimental mode. Figure out better <ide> // strategy for gated imports. <del> if (__EXPERIMENTAL__) { <add> if (__EXPERIMENTAL__ || global.__WWW__) { <ide> useFocus = require('react-interactions/events/focus').useFocus; <ide> } <ide> } <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> Scheduler.unstable_flushAll(); <ide> }; <ide> <del> // @gate experimental <add> // @gate www <ide> it('does not call callbacks', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> Scheduler.unstable_flushAll(); <ide> }; <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after "blur" event', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> Scheduler.unstable_flushAll(); <ide> }; <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after "focus" event', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> target.focus(); <ide> expect(onFocus).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is not called if descendants of target receive focus', () => { <ide> componentInit(); <ide> const target = createEventTarget(innerRef.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> Scheduler.unstable_flushAll(); <ide> }; <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after "blur" and "focus" events', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> expect(onFocusChange).toHaveBeenCalledWith(false); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is not called after "blur" and "focus" events on descendants', () => { <ide> componentInit(); <ide> const target = createEventTarget(innerRef.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> Scheduler.unstable_flushAll(); <ide> }; <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after "focus" and "blur" if keyboard navigation is active', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> expect(onFocusVisibleChange).toHaveBeenCalledWith(false); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called if non-keyboard event is dispatched on target previously focused with keyboard', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> expect(onFocusVisibleChange).toHaveBeenCalledTimes(2); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is not called after "focus" and "blur" events without keyboard', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> expect(onFocusVisibleChange).toHaveBeenCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is not called after "blur" and "focus" events on descendants', () => { <ide> componentInit(); <ide> const innerTarget = createEventTarget(innerRef.current); <ide> describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => { <ide> }); <ide> <ide> describe('nested Focus components', () => { <del> // @gate experimental <add> // @gate www <ide> it('propagates events in the correct order', () => { <ide> const events = []; <ide> const innerRef = React.createRef(); <ide><path>packages/react-interactions/events/src/dom/create-event-handle/__tests__/useFocusWithin-test.internal.js <ide> function initializeModules(hasPointerEvents) { <ide> <ide> // TODO: This import throws outside of experimental mode. Figure out better <ide> // strategy for gated imports. <del> if (__EXPERIMENTAL__) { <add> if (__EXPERIMENTAL__ || global.__WWW__) { <ide> useFocusWithin = require('react-interactions/events/focus').useFocusWithin; <ide> } <ide> } <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> Scheduler.unstable_flushAll(); <ide> }; <ide> <del> // @gate experimental <add> // @gate www <ide> it('prevents custom events being dispatched', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> Scheduler.unstable_flushAll(); <ide> }; <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after "blur" and "focus" events on focus target', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> expect(onFocusWithinChange).toHaveBeenCalledWith(false); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after "blur" and "focus" events on descendants', () => { <ide> componentInit(); <ide> const target = createEventTarget(innerRef.current); <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> expect(onFocusWithinChange).toHaveBeenCalledWith(false); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is only called once when focus moves within and outside the subtree', () => { <ide> componentInit(); <ide> const node = ref.current; <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> Scheduler.unstable_flushAll(); <ide> }; <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after "focus" and "blur" on focus target if keyboard was used', () => { <ide> componentInit(); <ide> const target = createEventTarget(ref.current); <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(false); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after "focus" and "blur" on descendants if keyboard was used', () => { <ide> componentInit(); <ide> const innerTarget = createEventTarget(innerRef.current); <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(false); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called if non-keyboard event is dispatched on target previously focused with keyboard', () => { <ide> componentInit(); <ide> const node = ref.current; <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(4); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is not called after "focus" and "blur" events without keyboard', () => { <ide> componentInit(); <ide> const innerTarget = createEventTarget(innerRef.current); <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(0); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is only called once when focus moves within and outside the subtree', () => { <ide> componentInit(); <ide> const node = ref.current; <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> }); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('should correctly handle focus visibility when typing into an input', () => { <ide> const onFocusWithinVisibleChange = jest.fn(); <ide> const ref = React.createRef(); <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> innerRef2 = React.createRef(); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after a focused element is unmounted', () => { <ide> const Component = ({show}) => { <ide> const focusWithinRef = useFocusWithin(ref, { <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after a nested focused element is unmounted', () => { <ide> const Component = ({show}) => { <ide> const focusWithinRef = useFocusWithin(ref, { <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after many elements are unmounted', () => { <ide> const buttonRef = React.createRef(); <ide> const inputRef = React.createRef(); <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> expect(onAfterBlurWithin).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after a nested focused element is unmounted (with scope query)', () => { <ide> const TestScope = React.unstable_Scope; <ide> const testScopeQuery = (type, props) => true; <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> expect(targetNodes).toEqual([targetNode]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after a focused suspended element is hidden', () => { <ide> const Suspense = React.Suspense; <ide> let suspend = false; <ide> describe.each(table)(`useFocus`, hasPointerEvents => { <ide> resolve(); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('is called after a focused suspended element is hidden then shown', () => { <ide> const Suspense = React.Suspense; <ide> let suspend = false; <ide><path>packages/react-reconciler/src/__tests__/DebugTracing-test.internal.js <ide> describe('DebugTracing', () => { <ide> }); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('should not log anything for sync render without suspends or state updates', () => { <ide> ReactTestRenderer.create( <ide> <React.unstable_DebugTracingMode> <ide> describe('DebugTracing', () => { <ide> expect(logs).toEqual([]); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('should not log anything for concurrent render without suspends or state updates', () => { <ide> ReactTestRenderer.create( <ide> <React.unstable_DebugTracingMode> <ide> describe('DebugTracing', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('should not log anything outside of a unstable_DebugTracingMode subtree', () => { <ide> function ExampleThatCascades() { <ide> const [didMount, setDidMount] = React.useState(false); <ide><path>packages/react-reconciler/src/__tests__/ReactCache-test.js <ide> describe('ReactCache', () => { <ide> } <ide> } <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('render Cache component', async () => { <ide> const root = ReactNoop.createRoot(); <ide> await ReactNoop.act(async () => { <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('Hi'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('mount new data', async () => { <ide> const root = ReactNoop.createRoot(); <ide> await ReactNoop.act(async () => { <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('root acts as implicit cache boundary', async () => { <ide> const root = ReactNoop.createRoot(); <ide> await ReactNoop.act(async () => { <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('multiple new Cache boundaries in the same update share the same, fresh cache', async () => { <ide> function App({text}) { <ide> return ( <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('AA'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test( <ide> 'nested cache boundaries share the same cache as the root during ' + <ide> 'the initial render', <ide> describe('ReactCache', () => { <ide> }, <ide> ); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('new content inside an existing Cache boundary should re-use already cached data', async () => { <ide> function App({showMore}) { <ide> return ( <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A [v1]A [v1]'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('a new Cache boundary uses fresh cache', async () => { <ide> // The only difference from the previous test is that the "Show More" <ide> // content is wrapped in a nested <Cache /> boundary <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A [v1]A [v2]'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('inner content uses same cache as shell if spawned by the same transition', async () => { <ide> const root = ReactNoop.createRoot(); <ide> <ide> describe('ReactCache', () => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('refresh a cache', async () => { <ide> let refresh; <ide> function App() { <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A [v2]'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('refresh the root cache', async () => { <ide> let refresh; <ide> function App() { <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A [v2]'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('refresh a cache with seed data', async () => { <ide> let refresh; <ide> function App() { <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A [v2]'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('refreshing a parent cache also refreshes its children', async () => { <ide> let refreshShell; <ide> function RefreshShell() { <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A [v3]A [v3]'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test( <ide> 'refreshing a cache boundary does not refresh the other boundaries ' + <ide> 'that mounted at the same time (i.e. the ones that share the same cache)', <ide> describe('ReactCache', () => { <ide> }, <ide> ); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test( <ide> 'mount a new Cache boundary in a sibling while simultaneously ' + <ide> 'resolving a Suspense boundary', <ide> describe('ReactCache', () => { <ide> }, <ide> ); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('cache pool is cleared once transitions that depend on it commit their shell', async () => { <ide> function Child({text}) { <ide> return ( <ide> describe('ReactCache', () => { <ide> expect(root).toMatchRenderedOutput('A [v1]A [v1]A [v2]'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('cache pool is not cleared by arbitrary commits', async () => { <ide> function App() { <ide> return ( <ide><path>packages/react-reconciler/src/__tests__/ReactContextPropagation-test.js <ide> describe('ReactLazyContextPropagation', () => { <ide> expect(root).toMatchRenderedOutput('BB'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('context is propagated through offscreen trees', async () => { <ide> const LegacyHidden = React.unstable_LegacyHidden; <ide> <ide> describe('ReactLazyContextPropagation', () => { <ide> expect(root).toMatchRenderedOutput('BB'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('multiple contexts are propagated across through offscreen trees', async () => { <ide> // Same as previous test, but with multiple context providers <ide> const LegacyHidden = React.unstable_LegacyHidden; <ide> describe('ReactLazyContextPropagation', () => { <ide> expect(root).toMatchRenderedOutput('BB'); <ide> }); <ide> <del> // @gate experimental <ide> // @gate enableCache <ide> test('nested bailouts across retries', async () => { <ide> // Lazy context propagation will stop propagating when it hits the first <ide> describe('ReactLazyContextPropagation', () => { <ide> expect(root).toMatchRenderedOutput('BB'); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> test('nested bailouts through offscreen trees', async () => { <ide> // Lazy context propagation will stop propagating when it hits the first <ide> // match. If we bail out again inside that tree, we must resume propagating. <ide><path>packages/react-reconciler/src/__tests__/ReactIncremental-test.js <ide> describe('ReactIncremental', () => { <ide> expect(inst.state).toEqual({text: 'bar', text2: 'baz'}); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('can deprioritize unfinished work and resume it later', () => { <ide> function Bar(props) { <ide> Scheduler.unstable_yieldValue('Bar'); <ide> describe('ReactIncremental', () => { <ide> expect(Scheduler).toFlushAndYield(['Middle', 'Middle']); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('can deprioritize a tree from without dropping work', () => { <ide> function Bar(props) { <ide> Scheduler.unstable_yieldValue('Bar'); <ide> describe('ReactIncremental', () => { <ide> }); <ide> } <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('provides context when reusing work', () => { <ide> class Intl extends React.Component { <ide> static childContextTypes = { <ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalErrorHandling-test.internal.js <ide> describe('ReactIncrementalErrorHandling', () => { <ide> expect(ReactNoop.getChildren()).toEqual([span('Everything is fine.')]); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('does not include offscreen work when retrying after an error', () => { <ide> function App(props) { <ide> if (props.isBroken) { <ide><path>packages/react-reconciler/src/__tests__/ReactIncrementalSideEffects-test.js <ide> describe('ReactIncrementalSideEffects', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('preserves a previously rendered node when deprioritized', () => { <ide> function Middle(props) { <ide> Scheduler.unstable_yieldValue('Middle'); <ide> describe('ReactIncrementalSideEffects', () => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('can reuse side-effects after being preempted', () => { <ide> function Bar(props) { <ide> Scheduler.unstable_yieldValue('Bar'); <ide> describe('ReactIncrementalSideEffects', () => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('can reuse side-effects after being preempted, if shouldComponentUpdate is false', () => { <ide> class Bar extends React.Component { <ide> shouldComponentUpdate(nextProps) { <ide> describe('ReactIncrementalSideEffects', () => { <ide> expect(ReactNoop.getChildrenAsJSX()).toEqual(<span prop={3} />); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('updates a child even though the old props is empty', () => { <ide> function Foo(props) { <ide> return ( <ide> describe('ReactIncrementalSideEffects', () => { <ide> expect(ops).toEqual(['Bar', 'Baz', 'Bar', 'Bar']); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('deprioritizes setStates that happens within a deprioritized tree', () => { <ide> const barInstances = []; <ide> <ide><path>packages/react-reconciler/src/__tests__/ReactNewContext-test.js <ide> describe('ReactNewContext', () => { <ide> expect(ReactNoop.getChildren()).toEqual([span(2), span(2)]); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it("context consumer doesn't bail out inside hidden subtree", () => { <ide> const Context = React.createContext('dark'); <ide> const Consumer = getConsumer(Context); <ide><path>packages/react-reconciler/src/__tests__/ReactOffscreen-test.js <ide> describe('ReactOffscreen', () => { <ide> return <span prop={props.text} />; <ide> } <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('unstable-defer-without-hiding should never toggle the visibility of its children', async () => { <ide> function App({mode}) { <ide> return ( <ide> describe('ReactOffscreen', () => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('does not defer in legacy mode', async () => { <ide> let setState; <ide> function Foo() { <ide> describe('ReactOffscreen', () => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('does defer in concurrent mode', async () => { <ide> let setState; <ide> function Foo() { <ide> describe('ReactOffscreen', () => { <ide> ); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> // @gate enableSuspenseLayoutEffectSemantics <ide> it('mounts without layout effects when hidden', async () => { <ide> function Child({text}) { <ide> describe('ReactOffscreen', () => { <ide> expect(root).toMatchRenderedOutput(<span prop="Child" />); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> // @gate enableSuspenseLayoutEffectSemantics <ide> it('mounts/unmounts layout effects when visibility changes (starting visible)', async () => { <ide> function Child({text}) { <ide> describe('ReactOffscreen', () => { <ide> expect(root).toMatchRenderedOutput(<span prop="Child" />); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> // @gate enableSuspenseLayoutEffectSemantics <ide> it('mounts/unmounts layout effects when visibility changes (starting hidden)', async () => { <ide> function Child({text}) { <ide><path>packages/react-reconciler/src/__tests__/ReactSchedulerIntegration-test.js <ide> describe('ReactSchedulerIntegration', () => { <ide> expect(Scheduler).toHaveYielded(['A', 'B', 'C']); <ide> }); <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('idle updates are not blocked by offscreen work', async () => { <ide> function Text({text}) { <ide> Scheduler.unstable_yieldValue(text); <ide><path>packages/react-reconciler/src/__tests__/ReactScope-test.internal.js <ide> describe('ReactScope', () => { <ide> container = null; <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('DO_NOT_USE_queryAllNodes() works as intended', () => { <ide> const testScopeQuery = (type, props) => true; <ide> const TestScope = React.unstable_Scope; <ide> describe('ReactScope', () => { <ide> expect(scopeRef.current).toBe(null); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('DO_NOT_USE_queryAllNodes() provides the correct host instance', () => { <ide> const testScopeQuery = (type, props) => type === 'div'; <ide> const TestScope = React.unstable_Scope; <ide> describe('ReactScope', () => { <ide> expect(scopeRef.current).toBe(null); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('DO_NOT_USE_queryFirstNode() works as intended', () => { <ide> const testScopeQuery = (type, props) => true; <ide> const TestScope = React.unstable_Scope; <ide> describe('ReactScope', () => { <ide> expect(scopeRef.current).toBe(null); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('containsNode() works as intended', () => { <ide> const TestScope = React.unstable_Scope; <ide> const scopeRef = React.createRef(); <ide> describe('ReactScope', () => { <ide> expect(scopeRef.current.containsNode(emRef.current)).toBe(false); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('scopes support server-side rendering and hydration', () => { <ide> const TestScope = React.unstable_Scope; <ide> const scopeRef = React.createRef(); <ide> describe('ReactScope', () => { <ide> expect(nodes).toEqual([divRef.current, spanRef.current, aRef.current]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('getChildContextValues() works as intended', () => { <ide> const TestContext = React.createContext(); <ide> const TestScope = React.unstable_Scope; <ide> describe('ReactScope', () => { <ide> expect(scopeRef.current).toBe(null); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('correctly works with suspended boundaries that are hydrated', async () => { <ide> let suspend = false; <ide> let resolve; <ide> describe('ReactScope', () => { <ide> ReactTestRenderer = require('react-test-renderer'); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('DO_NOT_USE_queryAllNodes() works as intended', () => { <ide> const testScopeQuery = (type, props) => true; <ide> const TestScope = React.unstable_Scope; <ide> describe('ReactScope', () => { <ide> expect(nodes).toEqual([aRef.current, divRef.current, spanRef.current]); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('DO_NOT_USE_queryFirstNode() works as intended', () => { <ide> const testScopeQuery = (type, props) => true; <ide> const TestScope = React.unstable_Scope; <ide> describe('ReactScope', () => { <ide> expect(node).toEqual(aRef.current); <ide> }); <ide> <del> // @gate experimental <add> // @gate www <ide> it('containsNode() works as intended', () => { <ide> const TestScope = React.unstable_Scope; <ide> const scopeRef = React.createRef(); <ide><path>packages/react-reconciler/src/__tests__/ReactSubtreeFlagsWarning-test.js <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> <ide> const resolveText = resolveMostRecentTextCache; <ide> <del> // @gate experimental <add> // @gate experimental || www <ide> it('regression: false positive for legacy suspense', async () => { <ide> // Wrapping in memo because regular function components go through the <ide> // mountIndeterminateComponent path, which acts like there's no `current` <ide><path>scripts/jest/TestFlags.js <ide> function getTestFlags() { <ide> <ide> ...featureFlags, <ide> ...environmentFlags, <del> <del> // FIXME: www-classic has enableCache on, but when running the source <del> // tests, Jest doesn't expose the API correctly. Fix then remove <del> // this override. <del> enableCache: __EXPERIMENTAL__, <ide> }, <ide> { <ide> get(flags, flagName) { <ide><path>scripts/jest/config.source-persistent.js <ide> <ide> const baseConfig = require('./config.base'); <ide> <del>const RELEASE_CHANNEL = process.env.RELEASE_CHANNEL; <del> <del>// Default to building in experimental mode. If the release channel is set via <del>// an environment variable, then check if it's "experimental". <del>const __EXPERIMENTAL__ = <del> typeof RELEASE_CHANNEL === 'string' <del> ? RELEASE_CHANNEL === 'experimental' <del> : true; <del> <del>const preferredExtension = __EXPERIMENTAL__ ? '.js' : '.stable.js'; <del> <del>const moduleNameMapper = {}; <del>moduleNameMapper[ <del> '^react$' <del>] = `<rootDir>/packages/react/index${preferredExtension}`; <del>moduleNameMapper[ <del> '^react-dom$' <del>] = `<rootDir>/packages/react-dom/index${preferredExtension}`; <del> <ide> module.exports = Object.assign({}, baseConfig, { <del> // Prefer the stable forks for tests. <del> moduleNameMapper, <ide> modulePathIgnorePatterns: [ <ide> ...baseConfig.modulePathIgnorePatterns, <ide> 'packages/react-devtools-shared', <ide><path>scripts/jest/config.source-www.js <ide> <ide> const baseConfig = require('./config.base'); <ide> <del>const RELEASE_CHANNEL = process.env.RELEASE_CHANNEL; <del> <del>// Default to building in experimental mode. If the release channel is set via <del>// an environment variable, then check if it's "experimental". <del>const __EXPERIMENTAL__ = <del> typeof RELEASE_CHANNEL === 'string' <del> ? RELEASE_CHANNEL === 'experimental' <del> : true; <del> <del>const preferredExtension = __EXPERIMENTAL__ ? '.js' : '.stable.js'; <del> <del>const moduleNameMapper = {}; <del>moduleNameMapper[ <del> '^react$' <del>] = `<rootDir>/packages/react/index${preferredExtension}`; <del>moduleNameMapper[ <del> '^react-dom$' <del>] = `<rootDir>/packages/react-dom/index${preferredExtension}`; <del> <ide> module.exports = Object.assign({}, baseConfig, { <del> // Prefer the stable forks for tests. <del> moduleNameMapper, <ide> modulePathIgnorePatterns: [ <ide> ...baseConfig.modulePathIgnorePatterns, <ide> 'packages/react-devtools-shared', <ide><path>scripts/jest/config.source.js <ide> <ide> const baseConfig = require('./config.base'); <ide> <del>const RELEASE_CHANNEL = process.env.RELEASE_CHANNEL; <del> <del>// Default to building in experimental mode. If the release channel is set via <del>// an environment variable, then check if it's "experimental". <del>const __EXPERIMENTAL__ = <del> typeof RELEASE_CHANNEL === 'string' <del> ? RELEASE_CHANNEL === 'experimental' <del> : true; <del> <del>const preferredExtension = __EXPERIMENTAL__ ? '.js' : '.stable.js'; <del> <del>const moduleNameMapper = {}; <del>moduleNameMapper[ <del> '^react$' <del>] = `<rootDir>/packages/react/index${preferredExtension}`; <del>moduleNameMapper[ <del> '^react-dom$' <del>] = `<rootDir>/packages/react-dom/index${preferredExtension}`; <del> <ide> module.exports = Object.assign({}, baseConfig, { <del> // Prefer the stable forks for tests. <del> moduleNameMapper, <ide> modulePathIgnorePatterns: [ <ide> ...baseConfig.modulePathIgnorePatterns, <ide> 'packages/react-devtools-shared', <ide><path>scripts/jest/setupHostConfigs.js <ide> 'use strict'; <ide> <add>const fs = require('fs'); <ide> const inlinedHostConfigs = require('../shared/inlinedHostConfigs'); <ide> <add>function resolveEntryFork(resolvedEntry, isFBBundle) { <add> // Pick which entry point fork to use: <add> // .modern.fb.js <add> // .classic.fb.js <add> // .fb.js <add> // .stable.js <add> // .experimental.js <add> // .js <add> <add> if (isFBBundle) { <add> if (__EXPERIMENTAL__) { <add> // We can't currently use the true modern entry point because too many tests fail. <add> // TODO: Fix tests to not use ReactDOM.render or gate them. Then we can remove this. <add> return resolvedEntry; <add> } <add> const resolvedFBEntry = resolvedEntry.replace( <add> '.js', <add> __EXPERIMENTAL__ ? '.modern.fb.js' : '.classic.fb.js' <add> ); <add> if (fs.existsSync(resolvedFBEntry)) { <add> return resolvedFBEntry; <add> } <add> const resolvedGenericFBEntry = resolvedEntry.replace('.js', '.fb.js'); <add> if (fs.existsSync(resolvedGenericFBEntry)) { <add> return resolvedGenericFBEntry; <add> } <add> // Even if it's a FB bundle we fallthrough to pick stable or experimental if we don't have an FB fork. <add> } <add> const resolvedForkedEntry = resolvedEntry.replace( <add> '.js', <add> __EXPERIMENTAL__ ? '.experimental.js' : '.stable.js' <add> ); <add> if (fs.existsSync(resolvedForkedEntry)) { <add> return resolvedForkedEntry; <add> } <add> // Just use the plain .js one. <add> return resolvedEntry; <add>} <add> <add>jest.mock('react', () => { <add> const resolvedEntryPoint = resolveEntryFork( <add> require.resolve('react'), <add> global.__WWW__ <add> ); <add> return jest.requireActual(resolvedEntryPoint); <add>}); <add> <ide> jest.mock('react-reconciler/src/ReactFiberReconciler', () => { <ide> return jest.requireActual( <ide> __VARIANT__ <ide> inlinedHostConfigs.forEach(rendererInfo => { <ide> rendererInfo.entryPoints.forEach(entryPoint => { <ide> jest.mock(entryPoint, () => { <ide> mockAllConfigs(rendererInfo); <del> return jest.requireActual(entryPoint); <add> const resolvedEntryPoint = resolveEntryFork( <add> require.resolve(entryPoint), <add> global.__WWW__ <add> ); <add> return jest.requireActual(resolvedEntryPoint); <ide> }); <ide> }); <ide> });
26
Javascript
Javascript
name anonymous function in _http_common.js
72624fdd53de106c8afdd400865b89ed5b24ca17
<ide><path>lib/_http_common.js <ide> function parserOnMessageComplete() { <ide> } <ide> <ide> <del>const parsers = new FreeList('parsers', 1000, function() { <add>const parsers = new FreeList('parsers', 1000, function parsersCb() { <ide> const parser = new HTTPParser(HTTPParser.REQUEST); <ide> <ide> parser._headers = [];
1
Javascript
Javascript
use new attributestylemap for elements
1276f6f85dc4e3403c549d4940d358915ecac321
<ide><path>src/text-editor-component.js <ide> class NodePool { <ide> <ide> if (element) { <ide> element.className = className || '' <del> element.styleMap.forEach((value, key) => { <add> element.attributeStyleMap.forEach((value, key) => { <ide> if (!style || style[key] == null) element.style[key] = '' <ide> }) <ide> if (style) Object.assign(element.style, style)
1
Python
Python
fix comment, simplify math
49f70f7c3a447c8e0bc9ba0d1be7e4df34f04f58
<ide><path>numpy/linalg/linalg.py <ide> def _multi_dot_three(A, B, C): <ide> than `_multi_dot_matrix_chain_order` <ide> <ide> """ <del> # cost1 = cost((AB)C) <del> cost1 = (A.shape[0] * A.shape[1] * B.shape[1] + # (AB) <del> A.shape[0] * B.shape[1] * C.shape[1]) # (--)C <del> # cost2 = cost((AB)C) <del> cost2 = (B.shape[0] * B.shape[1] * C.shape[1] + # (BC) <del> A.shape[0] * A.shape[1] * C.shape[1]) # A(--) <add> a0, a1b0 = A.shape <add> b1c0, c1 = C.shape <add> # cost1 = cost((AB)C) = a0*a1b0*b1c0 + a0*b1c0*c1 <add> cost1 = a0 * b1c0 * (a1b0 + c1) <add> # cost2 = cost(A(BC)) = a1b0*b1c0*c1 + a0*a1b0*c1 <add> cost2 = a1b0 * c1 * (a0 + b1c0) <ide> <ide> if cost1 < cost2: <ide> return dot(dot(A, B), C)
1
Go
Go
fix retry logic for out of sequence errors
157561e95ccaef883fe106a38741acb3d493879f
<ide><path>integration-cli/daemon_swarm.go <ide> func (d *SwarmDaemon) cmdRetryOutOfSequence(args ...string) (string, error) { <ide> for i := 0; ; i++ { <ide> out, err := d.Cmd(args...) <ide> if err != nil { <del> if strings.Contains(err.Error(), "update out of sequence") { <add> if strings.Contains(out, "update out of sequence") { <ide> if i < 10 { <ide> continue <ide> }
1
Python
Python
add compat.v1 to support tf 2.0 in mnist
9691ef7a2a64c39b3096c34a8fba0e168175cb82
<ide><path>official/mnist/dataset.py <ide> def read32(bytestream): <ide> <ide> def check_image_file_header(filename): <ide> """Validate that filename corresponds to images for the MNIST dataset.""" <del> with tf.gfile.Open(filename, 'rb') as f: <add> with tf.io.gfile.GFile(filename, 'rb') as f: <ide> magic = read32(f) <ide> read32(f) # num_images, unused <ide> rows = read32(f) <ide> def check_image_file_header(filename): <ide> <ide> def check_labels_file_header(filename): <ide> """Validate that filename corresponds to labels for the MNIST dataset.""" <del> with tf.gfile.Open(filename, 'rb') as f: <add> with tf.io.gfile.GFile(filename, 'rb') as f: <ide> magic = read32(f) <ide> read32(f) # num_items, unused <ide> if magic != 2049: <ide> def check_labels_file_header(filename): <ide> def download(directory, filename): <ide> """Download (and unzip) a file from the MNIST dataset if not already done.""" <ide> filepath = os.path.join(directory, filename) <del> if tf.gfile.Exists(filepath): <add> if tf.io.gfile.exists(filepath): <ide> return filepath <del> if not tf.gfile.Exists(directory): <del> tf.gfile.MakeDirs(directory) <add> if not tf.io.gfile.exists(directory): <add> tf.io.gfile.mkdir(directory) <ide> # CVDF mirror of http://yann.lecun.com/exdb/mnist/ <ide> url = 'https://storage.googleapis.com/cvdf-datasets/mnist/' + filename + '.gz' <ide> _, zipped_filepath = tempfile.mkstemp(suffix='.gz') <ide> print('Downloading %s to %s' % (url, zipped_filepath)) <ide> urllib.request.urlretrieve(url, zipped_filepath) <ide> with gzip.open(zipped_filepath, 'rb') as f_in, \ <del> tf.gfile.Open(filepath, 'wb') as f_out: <add> tf.io.gfile.GFile(filepath, 'wb') as f_out: <ide> shutil.copyfileobj(f_in, f_out) <ide> os.remove(zipped_filepath) <ide> return filepath <ide> def dataset(directory, images_file, labels_file): <ide> <ide> def decode_image(image): <ide> # Normalize from [0, 255] to [0.0, 1.0] <del> image = tf.decode_raw(image, tf.uint8) <add> image = tf.io.decode_raw(image, tf.uint8) <ide> image = tf.cast(image, tf.float32) <ide> image = tf.reshape(image, [784]) <ide> return image / 255.0 <ide> <ide> def decode_label(label): <del> label = tf.decode_raw(label, tf.uint8) # tf.string -> [tf.uint8] <add> label = tf.io.decode_raw(label, tf.uint8) # tf.string -> [tf.uint8] <ide> label = tf.reshape(label, []) # label is a scalar <ide> return tf.cast(label, tf.int32) <ide> <ide><path>official/mnist/mnist.py <ide> def model_fn(features, labels, mode, params): <ide> 'classify': tf.estimator.export.PredictOutput(predictions) <ide> }) <ide> if mode == tf.estimator.ModeKeys.TRAIN: <del> optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE) <add> optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=LEARNING_RATE) <ide> <ide> logits = model(image, training=True) <del> loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) <del> accuracy = tf.metrics.accuracy( <add> loss = tf.compat.v1.losses.sparse_softmax_cross_entropy(labels=labels, <add> logits=logits) <add> accuracy = tf.compat.v1.metrics.accuracy( <ide> labels=labels, predictions=tf.argmax(logits, axis=1)) <ide> <ide> # Name tensors to be logged with LoggingTensorHook. <ide> def model_fn(features, labels, mode, params): <ide> return tf.estimator.EstimatorSpec( <ide> mode=tf.estimator.ModeKeys.TRAIN, <ide> loss=loss, <del> train_op=optimizer.minimize(loss, tf.train.get_or_create_global_step())) <add> train_op=optimizer.minimize(loss, <add> tf.compat.v1.train.get_or_create_global_step())) <ide> if mode == tf.estimator.ModeKeys.EVAL: <ide> logits = model(image, training=False) <ide> loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) <ide> def run_mnist(flags_obj): <ide> model_helpers.apply_clean(flags_obj) <ide> model_function = model_fn <ide> <del> session_config = tf.ConfigProto( <add> session_config = tf.compat.v1.ConfigProto( <ide> inter_op_parallelism_threads=flags_obj.inter_op_parallelism_threads, <ide> intra_op_parallelism_threads=flags_obj.intra_op_parallelism_threads, <ide> allow_soft_placement=True) <ide> def eval_input_fn(): <ide> <ide> # Export the model <ide> if flags_obj.export_dir is not None: <del> image = tf.placeholder(tf.float32, [None, 28, 28]) <add> image = tf.compat.v1.placeholder(tf.float32, [None, 28, 28]) <ide> input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn({ <ide> 'image': image, <ide> }) <ide> def main(_): <ide> <ide> <ide> if __name__ == '__main__': <del> tf.logging.set_verbosity(tf.logging.INFO) <add> tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) <ide> define_mnist_flags() <ide> absl_app.run(main) <ide><path>official/mnist/mnist_test.py <ide> <ide> <ide> def dummy_input_fn(): <del> image = tf.random_uniform([BATCH_SIZE, 784]) <del> labels = tf.random_uniform([BATCH_SIZE, 1], maxval=9, dtype=tf.int32) <add> image = tf.random.uniform([BATCH_SIZE, 784]) <add> labels = tf.random.uniform([BATCH_SIZE, 1], maxval=9, dtype=tf.int32) <ide> return image, labels <ide> <ide> <ide> def test_mnist(self): <ide> self.assertEqual(2, global_step) <ide> self.assertEqual(accuracy.shape, ()) <ide> <del> input_fn = lambda: tf.random_uniform([3, 784]) <add> input_fn = lambda: tf.random.uniform([3, 784]) <ide> predictions_generator = classifier.predict(input_fn) <ide> for _ in range(3): <ide> predictions = next(predictions_generator)
3
PHP
PHP
make the rule work without parameters
169f9d414b256ae741bb5c69cf9ec6a9a298a3fb
<ide><path>src/Illuminate/Validation/Validator.php <ide> class Validator implements ValidatorContract <ide> */ <ide> protected $replacers = []; <ide> <add> /** <add> * The array of rules with asterisks. <add> * <add> * @var array <add> */ <add> protected $implicitAttributes = []; <add> <ide> /** <ide> * The size related validation rules. <ide> * <ide> public function each($attribute, $rules) <ide> if (Str::startsWith($key, $attribute) || (bool) preg_match('/^'.$pattern.'\z/', $key)) { <ide> foreach ((array) $rules as $ruleKey => $ruleValue) { <ide> if (! is_string($ruleKey) || Str::endsWith($key, $ruleKey)) { <add> $this->implicitAttributes[$attribute][] = $key; <ide> $this->mergeRules($key, $ruleValue); <ide> } <ide> } <ide> protected function validateNotIn($attribute, $value, $parameters) <ide> */ <ide> protected function validateNoDuplicates($attribute, $value, $parameters) <ide> { <add> $rawAttribute = ''; <add> <add> foreach ($this->implicitAttributes as $raw => $dataAttributes) { <add> if (in_array($attribute, $dataAttributes)) { <add> $rawAttribute = $raw; <add> break; <add> } <add> } <add> <ide> $data = []; <ide> <ide> foreach (Arr::dot($this->data) as $key => $val) { <del> if ($key != $attribute && Str::is($parameters[0], $key)) { <add> if ($key != $attribute && Str::is($rawAttribute, $key)) { <ide> $data[$key] = $val; <ide> } <ide> } <ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testValidateNoDuplicates() <ide> { <ide> $trans = $this->getRealTranslator(); <ide> <del> $v = new Validator($trans, ['foo' => ['foo', 'foo']], ['foo.*' => 'no_duplicates:foo.*']); <add> $v = new Validator($trans, ['foo' => ['foo', 'foo']], ['foo.*' => 'no_duplicates']); <ide> $this->assertFalse($v->passes()); <ide> <del> $v = new Validator($trans, ['foo' => ['foo', 'bar']], ['foo.*' => 'no_duplicates:foo.*']); <add> $v = new Validator($trans, ['foo' => ['foo', 'bar']], ['foo.*' => 'no_duplicates']); <ide> $this->assertTrue($v->passes()); <ide> <del> $v = new Validator($trans, ['foo' => [['id' => 1], ['id' => 1]]], ['foo.*.id' => 'no_duplicates:foo.*.id']); <add> $v = new Validator($trans, ['foo' => ['bar' => ['id' => 1], 'baz' => ['id' => 1]]], ['foo.*.id' => 'no_duplicates']); <ide> $this->assertFalse($v->passes()); <ide> <del> $v = new Validator($trans, ['foo' => [['id' => 1], ['id' => 2]]], ['foo.*.id' => 'no_duplicates:foo.*.id']); <add> $v = new Validator($trans, ['foo' => ['bar' => ['id' => 1], 'baz' => ['id' => 2]]], ['foo.*.id' => 'no_duplicates']); <ide> $this->assertTrue($v->passes()); <ide> <del> $v = new Validator($trans, ['foo' => ['foo', 'foo']], ['foo.*' => 'no_duplicates:foo.*'], ['foo.*.no_duplicates' => 'There is a duplication!']); <add> $v = new Validator($trans, ['foo' => [['id' => 1], ['id' => 1]]], ['foo.*.id' => 'no_duplicates']); <add> $this->assertFalse($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => [['id' => 1], ['id' => 2]]], ['foo.*.id' => 'no_duplicates']); <add> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['cat' => [['prod' => [['id' => 1]]], ['prod' => [['id' => 1]]]]], ['cat.*.prod.*.id' => 'no_duplicates']); <add> $this->assertFalse($v->passes()); <add> <add> $v = new Validator($trans, ['cat' => [['prod' => [['id' => 1]]], ['prod' => [['id' => 2]]]]], ['cat.*.prod.*.id' => 'no_duplicates']); <add> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => ['foo', 'foo']], ['foo.*' => 'no_duplicates'], ['foo.*.no_duplicates' => 'There is a duplication!']); <ide> $this->assertFalse($v->passes()); <ide> $v->messages()->setFormat(':message'); <ide> $this->assertEquals('There is a duplication!', $v->messages()->first('foo.0'));
2
Javascript
Javascript
fix jbig2 decoding issue
c03cf20d371e67ba6dfa222dca15abd552b52e57
<ide><path>src/core/jbig2.js <ide> var Jbig2Image = (function Jbig2ImageClosure() { <ide> } <ide> ]; <ide> <add> // See 6.2.5.7 Decoding the bitmap. <ide> var ReusedContexts = [ <del> 0x1CD3, // '00111001101' (template) + '0011' (at), <del> 0x079A, // '001111001101' + '0', <del> 0x00E3, // '001110001' + '1', <del> 0x018B // '011000101' + '1' <add> 0x9B25, // 10011 0110010 0101 <add> 0x0795, // 0011 110010 101 <add> 0x00E5, // 001 11001 01 <add> 0x0195 // 011001 0101 <ide> ]; <ide> <ide> var RefinementReusedContexts = [
1
Python
Python
prepare pypi release
12d068f67554f49707e34cca62981d1196c76aff
<ide><path>keras/__init__.py <ide> from . import optimizers <ide> from . import regularizers <ide> <del>__version__ = '1.1.2' <add>__version__ = '1.2.0' <ide><path>setup.py <ide> <ide> <ide> setup(name='Keras', <del> version='1.1.2', <add> version='1.2.0', <ide> description='Deep Learning for Python', <ide> author='Francois Chollet', <ide> author_email='francois.chollet@gmail.com', <ide> url='https://github.com/fchollet/keras', <del> download_url='https://github.com/fchollet/keras/tarball/1.1.2', <add> download_url='https://github.com/fchollet/keras/tarball/1.2.0', <ide> license='MIT', <ide> install_requires=['theano', 'pyyaml', 'six'], <ide> extras_require={
2
Javascript
Javascript
replace http to https of comment link urls
ee3416b055a3d877251c095981508e275d99f8c2
<ide><path>lib/_http_server.js <ide> function Server(options, requestListener) { <ide> <ide> // Similar option to this. Too lazy to write my own docs. <ide> // http://www.squid-cache.org/Doc/config/half_closed_clients/ <del> // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F <add> // https://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F <ide> this.httpAllowHalfOpen = false; <ide> <ide> this.on('connection', connectionListener); <ide><path>lib/https.js <ide> function Server(opts, requestListener) { <ide> <ide> if (!opts.ALPNProtocols) { <ide> // http/1.0 is not defined as Protocol IDs in IANA <del> // http://www.iana.org/assignments/tls-extensiontype-values <add> // https://www.iana.org/assignments/tls-extensiontype-values <ide> // /tls-extensiontype-values.xhtml#alpn-protocol-ids <ide> opts.ALPNProtocols = ['http/1.1']; <ide> } <ide><path>lib/internal/child_process.js <ide> function getValidStdio(stdio, sync) { <ide> // At least 3 stdio will be created <ide> // Don't concat() a new Array() because it would be sparse, and <ide> // stdio.reduce() would skip the sparse elements of stdio. <del> // See http://stackoverflow.com/a/5501711/3561 <add> // See https://stackoverflow.com/a/5501711/3561 <ide> while (stdio.length < 3) stdio.push(undefined); <ide> <ide> // Translate stdio into C++-readable form <ide><path>lib/internal/source_map/source_map.js <ide> class StringCharIterator { <ide> } <ide> <ide> /** <del> * Implements Source Map V3 model. See http://code.google.com/p/closure-compiler/wiki/SourceMaps <add> * Implements Source Map V3 model. <add> * See https://github.com/google/closure-compiler/wiki/Source-Maps <ide> * for format description. <ide> * @constructor <ide> * @param {string} sourceMappingURL <ide><path>lib/internal/tty.js <ide> function getColorDepth(env = process.env) { <ide> env.NO_COLOR !== undefined || <ide> // The "dumb" special terminal, as defined by terminfo, doesn't support <ide> // ANSI color control codes. <del> // See http://invisible-island.net/ncurses/terminfo.ti.html#toc-_Specials <add> // See https://invisible-island.net/ncurses/terminfo.ti.html#toc-_Specials <ide> env.TERM === 'dumb') { <ide> return COLORS_2; <ide> } <ide><path>lib/internal/util/inspect.js <ide> ObjectDefineProperty(inspect, 'defaultOptions', { <ide> } <ide> }); <ide> <del>// Set Graphics Rendition http://en.wikipedia.org/wiki/ANSI_escape_code#graphics <add>// Set Graphics Rendition https://en.wikipedia.org/wiki/ANSI_escape_code#graphics <ide> // Each color consists of an array with the color code as first entry and the <ide> // reset code as second entry. <ide> const defaultFG = 39; <ide> if (internalBinding('config').hasIntl) { <ide> */ <ide> const isFullWidthCodePoint = (code) => { <ide> // Code points are partially derived from: <del> // http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt <add> // https://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt <ide> return code >= 0x1100 && ( <ide> code <= 0x115f || // Hangul Jamo <ide> code === 0x2329 || // LEFT-POINTING ANGLE BRACKET <ide><path>lib/querystring.js <ide> const noEscape = [ <ide> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0 // 112 - 127 <ide> ]; <ide> // QueryString.escape() replaces encodeURIComponent() <del>// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4 <add>// https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4 <ide> function qsEscape(str) { <ide> if (typeof str !== 'string') { <ide> if (typeof str === 'object') <ide><path>lib/readline.js <ide> // Inspiration for this code comes from Salvatore Sanfilippo's linenoise. <ide> // https://github.com/antirez/linenoise <ide> // Reference: <del>// * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html <add>// * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html <ide> // * http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html <ide> <ide> 'use strict';
8
PHP
PHP
fix doc block
d3cdfda31827e998c3a1a92e724532fe93ef68a2
<ide><path>src/Illuminate/Foundation/Http/FormRequest.php <ide> class FormRequest extends Request implements ValidatesWhenResolved <ide> /** <ide> * The container instance. <ide> * <del> * @var \Illuminate\Container\Container <add> * @var \Illuminate\Contracts\Container\Container <ide> */ <ide> protected $container; <ide>
1
Ruby
Ruby
remove messages obviated by new arg parser
f0270a585cc37e5b84d70404bf434c6f69c7672d
<ide><path>Library/Homebrew/cmd/desc.rb <ide> def desc <ide> search_type << :either if args.search <ide> search_type << :name if args.name <ide> search_type << :desc if args.description <del> if search_type.size > 1 <del> odie "Pick one, and only one, of -s/--search, -n/--name, or -d/--description." <del> elsif search_type.present? && ARGV.named.empty? <del> odie "You must provide a search term." <del> end <add> odie "You must provide a search term." if search_type.present? && ARGV.named.empty? <ide> <ide> results = if search_type.empty? <ide> raise FormulaUnspecifiedError if ARGV.named.empty? <ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_args <ide> switch :verbose <ide> switch :debug <ide> conflicts "--only", "--except" <del> conflicts "--only-cops", "--except-cops" <add> conflicts "--only-cops", "--except-cops", "--strict" <add> conflicts "--only-cops", "--except-cops", "--only" <ide> end <ide> end <ide> <ide> def audit <ide> <ide> only_cops = args.only_cops <ide> except_cops = args.except_cops <del> <del> if only_cops && except_cops <del> odie "--only-cops and --except-cops cannot be used simultaneously!" <del> elsif (only_cops || except_cops) && (strict || args.only) <del> odie "--only-cops/--except-cops and --strict/--only cannot be used simultaneously!" <del> end <del> <ide> options = { fix: args.fix? } <ide> <ide> if only_cops <ide> def problem_if_output(output) <ide> def audit <ide> only_audits = @only <ide> except_audits = @except <del> odie "--only and --except cannot be used simultaneously!" if only_audits && except_audits <ide> <ide> methods.map(&:to_s).grep(/^audit_/).each do |audit_method_name| <ide> name = audit_method_name.gsub(/^audit_/, "")
2
PHP
PHP
add additional tests for making load()
3d9650593f7db113f924efe7a64b490f2a85a738
<ide><path>tests/TestCase/Core/ConfigureTest.php <ide> <?php <ide> /** <del> * ConfigureTest file <del> * <del> * Holds several tests <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> public function testLoadNoMerge() { <ide> $this->assertNull(Configure::read('Deep.Deeper.Deepest')); <ide> } <ide> <add>/** <add> * Test load() replacing existing data <add> * <add> * @return void <add> */ <add> public function testLoadWithExistingData() { <add> Configure::config('test', new PhpConfig(TEST_APP . 'TestApp/Config/')); <add> Configure::write('my_key', 'value'); <add> <add> Configure::load('var_test', 'test'); <add> $this->assertEquals('value', Configure::read('my_key'), 'Should not overwrite existing data.'); <add> $this->assertEquals('value', Configure::read('Read'), 'Should load new data.'); <add> } <add> <add>/** <add> * Test load() merging on top of existing data <add> * <add> * @return void <add> */ <add> public function testLoadMergeWithExistingData() { <add> Configure::config('test', new PhpConfig(TEST_APP . 'TestApp/Config/')); <add> Configure::write('my_key', 'value'); <add> Configure::write('Read', 'old'); <add> Configure::write('Deep.old', 'old'); <add> <add> Configure::load('var_test', 'test', true); <add> $this->assertEquals('value', Configure::read('Read'), 'Should load new data.'); <add> $this->assertEquals('buried', Configure::read('Deep.Deeper.Deepest'), 'Should load new data'); <add> $this->assertEquals('old', Configure::read('Deep.old'), 'Should not destroy old data.'); <add> $this->assertEquals('value', Configure::read('my_key'), 'Should not destroy data.'); <add> } <add> <ide> /** <ide> * testLoad method <ide> *
1
PHP
PHP
insertsub()
d50b93d7d1e18fafe7b99c03206d5c4c989f74bb
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function insertGetId(array $values, $sequence = null) <ide> */ <ide> public function insertSub(array $columns, $query) <ide> { <add> [$sql, $bindings] = $this->createSub($query); <add> <add> return $this->connection->insert( <add> $this->grammar->compileInsertSub($this, $columns, $sql), <add> $this->cleanBindings($bindings) <add> ); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php <ide> public function compileInsertGetId(Builder $query, $values, $sequence) <ide> return $this->compileInsert($query, $values); <ide> } <ide> <add> public function compileInsertSub(Builder $query, array $columns, string $sql) <add> { <add> $table = $this->wrapTable($query->from); <add> <add> $columns_string = $this->columnize($columns); <add> <add> return "insert into $table ($columns_string) $sql"; <add> } <add> <ide> /** <ide> * Compile an update statement into SQL. <ide> * <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testInsertMethod() <ide> public function testInsertSubMethod() <ide> { <ide> $builder = $this->getBuilder(); <del> $builder->getConnection()->shouldReceive('insert')->once()->with('insert into "users" ("email") select "address" from "emails" where "created_at" > ?', ['2018-01-01'])->andReturn(true); <del> $result = $builder->from('users')->insertSub( <del> ['email'], <add> $builder->getConnection()->shouldReceive('insert')->once()->with('insert into "table1" ("foo") select "bar" from "table2" where "foreign_id" = ?', [5])->andReturn(true); <add> $result = $builder->from('table1')->insertSub( <add> ['foo'], <ide> function (Builder $query) { <del> $query->from('emails')->select(['address'])->where('created_at', '>', '2018-01-01'); <add> $query->select(['bar'])->from('table2')->where('foreign_id', '=', 5); <ide> } <ide> ); <ide> $this->assertTrue($result);
3
Text
Text
fix links from toc to subsection for 4.8.x
5de722ab6d1039980d3bafef42496e3659461573
<ide><path>doc/changelogs/CHANGELOG_V4.md <ide> </tr> <ide> <tr> <ide> <td valign="top"> <del><a href="#4.8.1">4.8.3</a><br/> <del><a href="#4.8.1">4.8.2</a><br/> <add><a href="#4.8.3">4.8.3</a><br/> <add><a href="#4.8.2">4.8.2</a><br/> <ide> <a href="#4.8.1">4.8.1</a><br/> <ide> <a href="#4.8.0">4.8.0</a><br/> <ide> <a href="#4.7.3">4.7.3</a><br/>
1
Ruby
Ruby
show messages when (un)installing casks
3703ef1885ba4afce1ed4ae531dcb7ddc573b3c2
<ide><path>Library/Homebrew/cask/lib/hbc/installer.rb <ide> def install <ide> print_caveats <ide> fetch <ide> uninstall_if_neccessary <add> <add> oh1 "Installing Cask #{@cask}" <ide> stage <ide> install_artifacts <ide> enable_accessibility_access <ide> def save_caskfile <ide> end <ide> <ide> def uninstall <del> odebug "Hbc::Installer#uninstall" <add> oh1 "Uninstalling Cask #{@cask}" <ide> disable_accessibility_access <ide> uninstall_artifacts <ide> purge_versioned_files <ide><path>Library/Homebrew/test/cask/cli/install_spec.rb <ide> describe Hbc::CLI::Install, :cask do <add> it "displays the installation progress" do <add> output = Regexp.new <<-EOS.undent <add> ==> Downloading file:.*/caffeine.zip <add> ==> Verifying checksum for Cask local-caffeine <add> ==> Installing Cask local-caffeine <add> ==> Moving App 'Caffeine.app' to '.*/Caffeine.app'. <add> 🍺 local-caffeine was successfully installed! <add> EOS <add> <add> expect { <add> Hbc::CLI::Install.run("local-caffeine") <add> }.to output(output).to_stdout <add> end <add> <ide> it "allows staging and activation of multiple Casks at once" do <ide> shutup do <ide> Hbc::CLI::Install.run("local-transmission", "local-caffeine") <ide><path>Library/Homebrew/test/cask/cli/reinstall_spec.rb <ide> describe Hbc::CLI::Reinstall, :cask do <add> it "displays the reinstallation progress" do <add> caffeine = Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-caffeine.rb") <add> <add> shutup do <add> Hbc::Installer.new(caffeine).install <add> end <add> <add> output = Regexp.new <<-EOS.undent <add> ==> Downloading file:.*/caffeine.zip <add> Already downloaded: .*/local-caffeine--1.2.3.zip <add> ==> Verifying checksum for Cask local-caffeine <add> ==> Uninstalling Cask local-caffeine <add> ==> Removing App '.*/Caffeine.app'. <add> ==> Installing Cask local-caffeine <add> ==> Moving App 'Caffeine.app' to '.*/Caffeine.app'. <add> 🍺 local-caffeine was successfully installed! <add> EOS <add> <add> expect { <add> Hbc::CLI::Reinstall.run("local-caffeine") <add> }.to output(output).to_stdout <add> end <add> <ide> it "allows reinstalling a Cask" do <ide> shutup do <ide> Hbc::CLI::Install.run("local-transmission") <ide><path>Library/Homebrew/test/cask/cli/uninstall_spec.rb <ide> describe Hbc::CLI::Uninstall, :cask do <add> it "displays the uninstallation progress" do <add> caffeine = Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-caffeine.rb") <add> <add> shutup do <add> Hbc::Installer.new(caffeine).install <add> end <add> <add> output = Regexp.new <<-EOS.undent <add> ==> Uninstalling Cask local-caffeine <add> ==> Removing App '.*/Caffeine.app'. <add> EOS <add> <add> expect { <add> Hbc::CLI::Uninstall.run("local-caffeine") <add> }.to output(output).to_stdout <add> end <add> <ide> it "shows an error when a bad Cask is provided" do <ide> expect { <ide> Hbc::CLI::Uninstall.run("notacask")
4
Text
Text
add example to to_representation docs
b3a0b271cd21365d8167c9b581c7f7e7deab85d2
<ide><path>docs/api-guide/serializers.md <ide> The signatures for these methods are as follows: <ide> <ide> Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API. <ide> <add>May be overridden in order modify the representation style. For example: <add> <add> def to_representation(self, instance): <add> """Convert `username` to lowercase.""" <add> ret = super().to_representation(instance) <add> ret['username'] = ret['username'].lower() <add> return ret <add> <ide> #### ``.to_internal_value(self, data)`` <ide> <ide> Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
1
Text
Text
translate vue components to portuguese
b25cd5f5bb702fc2e6da528ae9ca4f6ad4e7b9b8
<ide><path>guide/portuguese/vue/components/index.md <add>--- <add>title: Components <add>localeTitle: Componentes <add>--- <add> <add>## Componentes <add> <add>Um problema comum enfrentado por desenvolvedores web é lidar com a replicação de código HTML, não no sentido de uma lista, por exemplo, mas sim quando quando você quer ser capaz de "importar" para usar o mesmo código em vários lugares diferentes. Bom, Vue.js te dá essa opção através de seus Componentes. <add> <add>Imagine que você está desenvolvendo uma landing page para o produto de sua empresa, precisando mostrar suas 4 principais características através da mesma estrutura de "card": ícone, título e uma breve descrição. <add> <add>```javascript <add>Vue.component('feature-card', { <add> props: ["iconSrc", "iconAltText", "featureTitle", "featureDescription"], <add> template: ` <add> <div class="card"> <add> <div class="icon-wrapper"> <add> <img <add> class="icon" <add> :src="iconSrc" <add> :alt="iconAltText"> <add> </div> <add> <h4 class="title"> <add> {{ featureTitle }} <add> </h4> <add> <p class="description"> <add> {{ featureDescription }} <add> </p> <add> </div> <add> ` <add>}); <add>``` <add> <add>> Repare que aqui usamos o atributo `src` de imagem com uma sintaxe diferente, `:src`. <add>Tal mudança não afeta coisa alguma, sendo simplesmente um açucar sintático para `v-bind:src` -- sempre que você quiser ligar algum atributo a uma variável, você pode fazer com que um `:` preceda o nome do atributo ao invés de usar a forma padrão `v-bind`. <add> <add> <add>Com esse código, fizemos várias coisas novas: <add>* criamos um novo componente chamado `feature-card` <add>* definimos a **estrutura** padrão de `feature-card` com o atributo `template` <add>* nós abrimos uma lista de propriedades que o componente pode aceitar com a lista `props` <add> <add> <add>Quando nós definimos o nome dos componentes, sempre que desejarmos reutilizá-los, podemos referenciá-los pelo uso de uma tag. No nosso exemplo, podemos usar a tag `<feature-card>`: <add> <add> <add>```html <add><div id="app"> <add> <feature-card <add> iconSrc="https://freedesignfile.com/upload/2017/08/rocket-icon-vector.png" <add> iconAltText="rocket" <add> featureTitle="Processing speed" <add> featureDescription="Our solution has astonishing benchmarks grades"> <add> </feature-card> <add></div> <add>``` <add> <add>Neste caso, usamos `<feature-card>` como se fosse uma tag já existente, além de definir `iconSrc` e `featureTitle` como se fossem atributos válidos. Esse é o propósito dos componentes de Vue.js: incrementar sua caixa de ferramentas com suas próprias ferramentas. <add> <add> <add>### Props <add> <add>Props são atributos personalizados que podem ser registrados em um componente. Quando um valor é passado para um atributo prop, ele se torna propriedade instanciada naquele componente. Para passar um título para o nosso componente relativo à postagem no blog, podemos incluí-lo na lista de props que esse componente aceita usando uma opção dos props: <add> <add> <add>```js <add>Vue.component('feature-card', { <add> props: ['title'], <add> template: '<h3>{{ title }}</h3>' <add>}) <add>``` <add>Um componente pode possuir quantos props sejam necessários e, por padrão, qualquer valor pode ser passado para qualquer prop. No template acima, você pode notar que podemos acessar tal valor no componente instanciado, assim como qualquer dado. <add> <add> <add>Uma vez que um prop é registrado, você pode passar dados para ele como um atributo personalizado, por exemplo: <add>```html <add><blog-post title="My journey with Vue"></blog-post> <add><blog-post title="Blogging with Vue"></blog-post> <add><blog-post title="Why Vue is so fun"></blog-post> <add>```
1
Javascript
Javascript
fix a lint warning and make example tests prettier
fdfd13fbc83f2843bd6420c48b9b39d5fa17113d
<ide><path>examples/testAll.js <ide> const fs = require('fs') <ide> const path = require('path') <ide> const { spawnSync } = require('child_process') <add>const chalk = require('chalk') <ide> <ide> const exampleDirs = fs.readdirSync(__dirname).filter((file) => { <ide> return fs.statSync(path.join(__dirname, file)).isDirectory() <ide> const cmdArgs = [ <ide> for (const dir of exampleDirs) { <ide> if (dir === 'counter-vanilla') continue <ide> <del> console.log('==> Testing %s...', dir) <add> console.log(chalk.bold.yellow('\n\n==> Testing %s...\n\n'), dir) <ide> for (const cmdArg of cmdArgs) { <ide> // declare opts in this scope to avoid https://github.com/joyent/node/issues/9158 <ide> const opts = { <ide><path>examples/todomvc/src/components/MainSection.spec.js <ide> describe('components', () => { <ide> <ide> it('should call completeAll on change', () => { <ide> const { output, props } = setup() <del> const [ toggle, label ] = output.props.children[0].props.children <add> const [ , label ] = output.props.children[0].props.children <ide> label.props.onClick({}) <ide> expect(props.actions.completeAll).toBeCalled() <ide> })
2
PHP
PHP
fix consoleoutput styles() api
43af5df64d19ffedf6ab3f26222fe17592f871c7
<ide><path>src/Console/ConsoleIo.php <ide> public function setOutputAs(int $mode): void <ide> } <ide> <ide> /** <del> * Add a new output style or get defined styles. <add> * @return array <add> * @see \Cake\Console\ConsoleOutput::styles() <add> */ <add> public function styles(): array <add> { <add> return $this->_out->styles(); <add> } <add> <add> /** <add> * Get defined styles. <add> * <add> * @param string $style <add> * @return array <add> * @see \Cake\Console\ConsoleOutput::getStyle() <add> */ <add> public function getStyle(string $style): array <add> { <add> return $this->_out->getStyle($style); <add> } <add> <add> /** <add> * Add a new output style or <ide> * <ide> * @param string|null $style The style to get or create. <ide> * @param array|false|null $definition The array definition of the style to change or create a style <ide> * or false to remove a style. <del> * @return array|true|null If you are getting styles, the style or null will be returned. If you are creating/modifying <del> * styles true will be returned. <del> * @see \Cake\Console\ConsoleOutput::styles() <add> * @return void <add> * @see \Cake\Console\ConsoleOutput::setStyle() <ide> */ <del> public function styles(?string $style = null, $definition = null) <add> public function setStyle(string $style, array $definition): void <ide> { <del> return $this->_out->styles($style, $definition); <add> $this->_out->setStyle($style, $definition); <ide> } <ide> <ide> /** <ide><path>src/Console/ConsoleOutput.php <ide> public function styleText(string $text): string <ide> */ <ide> protected function _replaceTags(array $matches): string <ide> { <del> /** @var array $style */ <del> $style = $this->styles($matches['tag']); <add> $style = $this->getStyle($matches['tag']); <ide> if (empty($style)) { <ide> return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>'; <ide> } <ide> protected function _write(string $message): int <ide> } <ide> <ide> /** <del> * Get the current styles offered, or append new ones in. <add> * Gets the current styles offered <ide> * <del> * ### Get a style definition <del> * <del> * ``` <del> * $output->styles('error'); <del> * ``` <del> * <del> * ### Get all the style definitions <del> * <del> * ``` <del> * $output->styles(); <del> * ``` <add> * @param string $style The style to get. <add> * @return array The style or empty array. <add> */ <add> public function getStyle(string $style): array <add> { <add> return static::$_styles[$style] ?? []; <add> } <add> <add> /** <add> * Sets style. <ide> * <del> * ### Create or modify an existing style <add> * ### Creates or modifies an existing style. <ide> * <ide> * ``` <del> * $output->styles('annoy', ['text' => 'purple', 'background' => 'yellow', 'blink' => true]); <add> * $output->setStyle('annoy', ['text' => 'purple', 'background' => 'yellow', 'blink' => true]); <ide> * ``` <ide> * <ide> * ### Remove a style <ide> * <ide> * ``` <del> * $this->output->styles('annoy', false); <add> * $this->output->setStyle('annoy', []); <ide> * ``` <ide> * <del> * @param string|null $style The style to get or create. <del> * @param array|false|null $definition The array definition of the style to change or create a style <del> * or false to remove a style. <del> * @return array|true|null If you are getting styles, the style or null will be returned. If you are creating/modifying <del> * styles true will be returned. <add> * @param string $style The style to get or create. <add> * @param array $definition The array definition of the style to change or create.. <add> * @return void <ide> */ <del> public function styles(?string $style = null, $definition = null) <add> public function setStyle(string $style, array $definition): void <ide> { <del> if ($style === null && $definition === null) { <del> return static::$_styles; <del> } <del> if ($definition === null) { <del> return static::$_styles[$style] ?? null; <del> } <del> if ($definition === false) { <add> if (!$definition) { <ide> /** @psalm-suppress PossiblyNullArrayOffset */ <ide> unset(static::$_styles[$style]); <ide> <del> return true; <add> return; <ide> } <add> <ide> /** @psalm-suppress PossiblyNullArrayOffset */ <ide> static::$_styles[$style] = $definition; <add> } <ide> <del> return true; <add> /** <add> * Gets all the style definitions. <add> * <add> * @return array <add> */ <add> public function styles(): array <add> { <add> return static::$_styles; <ide> } <ide> <ide> /** <ide><path>src/Shell/Helper/TableHelper.php <ide> protected function _cellWidth(?string $text): int <ide> return mb_strwidth($text); <ide> } <ide> <del> /** @var array $styles */ <ide> $styles = $this->_io->styles(); <ide> $tags = implode('|', array_keys($styles)); <ide> $text = preg_replace('#</?(?:' . $tags . ')>#', '', $text); <ide><path>tests/TestCase/Console/ConsoleIoTest.php <ide> public function testSetLoggersVerbose() <ide> $this->assertEquals(['notice', 'info', 'debug'], $engine->getConfig('levels')); <ide> } <ide> <add> /** <add> * Ensure that setStyle() just proxies to stdout. <add> * <add> * @return void <add> */ <add> public function testSetStyle() <add> { <add> $this->out->expects($this->once()) <add> ->method('setStyle') <add> ->with('name', ['props']); <add> $this->io->setStyle('name', ['props']); <add> } <add> <add> /** <add> * Ensure that getStyle() just proxies to stdout. <add> * <add> * @return void <add> */ <add> public function testGetStyle() <add> { <add> $this->out->expects($this->once()) <add> ->method('getStyle') <add> ->with('name'); <add> $this->io->getStyle('name'); <add> } <add> <ide> /** <ide> * Ensure that styles() just proxies to stdout. <ide> * <ide> public function testSetLoggersVerbose() <ide> public function testStyles() <ide> { <ide> $this->out->expects($this->once()) <del> ->method('styles') <del> ->with('name', 'props'); <del> $this->io->styles('name', 'props'); <add> ->method('styles'); <add> $this->io->styles(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Console/ConsoleOutputTest.php <ide> */ <ide> class ConsoleOutputTest extends TestCase <ide> { <add> /** <add> * @var \Cake\Console\ConsoleOutput|\PHPUnit\Framework\MockObject\MockObject <add> */ <add> protected $output; <add> <ide> /** <ide> * setup <ide> * <ide> class ConsoleOutputTest extends TestCase <ide> public function setUp(): void <ide> { <ide> parent::setUp(); <del> $this->output = $this->getMockBuilder('Cake\Console\ConsoleOutput') <add> $this->output = $this->getMockBuilder(ConsoleOutput::class) <ide> ->setMethods(['_write']) <ide> ->getMock(); <ide> $this->output->setOutputAs(ConsoleOutput::COLOR); <ide> public function testWriteArray() <ide> */ <ide> public function testStylesGet() <ide> { <del> $result = $this->output->styles('error'); <add> $result = $this->output->getStyle('error'); <ide> $expected = ['text' => 'red']; <ide> $this->assertEquals($expected, $result); <ide> <del> $this->assertNull($this->output->styles('made_up_goop')); <add> $this->assertSame([], $this->output->getStyle('made_up_goop')); <ide> <ide> $result = $this->output->styles(); <ide> $this->assertNotEmpty($result, 'Error is missing'); <ide> public function testStylesGet() <ide> */ <ide> public function testStylesAdding() <ide> { <del> $this->output->styles('test', ['text' => 'red', 'background' => 'black']); <del> $result = $this->output->styles('test'); <add> $this->output->setStyle('test', ['text' => 'red', 'background' => 'black']); <add> $result = $this->output->getStyle('test'); <ide> $expected = ['text' => 'red', 'background' => 'black']; <ide> $this->assertEquals($expected, $result); <ide> <del> $this->assertTrue($this->output->styles('test', false), 'Removing a style should return true.'); <del> $this->assertNull($this->output->styles('test'), 'Removed styles should be null.'); <add> $this->output->setStyle('test', []); <add> $this->assertSame([], $this->output->getStyle('test'), 'Removed styles should be empty.'); <ide> } <ide> <ide> /** <ide> public function testFormattingNotEatingTags() <ide> */ <ide> public function testFormattingCustom() <ide> { <del> $this->output->styles('annoying', [ <add> $this->output->setStyle('annoying', [ <ide> 'text' => 'magenta', <ide> 'background' => 'cyan', <ide> 'blink' => true,
5
Ruby
Ruby
pass the mode through the optlink method
4ea3997d9c29d37befb415a5e9b3e3f88b184fff
<ide><path>Library/Homebrew/keg.rb <ide> def link mode=OpenStruct.new <ide> <ide> unless mode.dry_run <ide> make_relative_symlink(linked_keg_record, path, mode) <del> optlink <add> optlink(mode) <ide> end <ide> rescue LinkError <ide> unlink <ide> def link mode=OpenStruct.new <ide> ObserverPathnameExtension.total <ide> end <ide> <del> def optlink <add> def optlink(mode=OpenStruct.new) <ide> opt_record.delete if opt_record.symlink? || opt_record.exist? <del> make_relative_symlink(opt_record, path) <add> make_relative_symlink(opt_record, path, mode) <ide> end <ide> <ide> def delete_pyc_files!
1
Python
Python
fix flakey test
70a43858e16184c2bc408b404a3b11dcad4f9526
<ide><path>spacy/tests/regression/test_issue999.py <ide> def test_issue999(train_data): <ide> doc = nlp2(raw_text) <ide> ents = {(ent.start_char, ent.end_char): ent.label_ for ent in doc.ents} <ide> for start, end, label in entity_offsets: <del> if (start, end) not in ents: <del> print(ents) <del> assert ents[(start, end)] == label <add> if (start, end) in ents: <add> assert ents[(start, end)] == label <add> break <add> else: <add> raise Exception(ents)
1
Python
Python
add flax dummy objects
6d4f8bd02a163ac711bdbec22045f8591ad8aa22
<ide><path>src/transformers/__init__.py <ide> if is_flax_available(): <ide> from .modeling_flax_bert import FlaxBertModel <ide> from .modeling_flax_roberta import FlaxRobertaModel <add>else: <add> # Import the same objects as dummies to get them in the namespace. <add> # They will raise an import error if the user tries to instantiate / use them. <add> from .utils.dummy_flax_objects import * <add> <ide> <ide> if not is_tf_available() and not is_torch_available(): <ide> logger.warning( <ide><path>src/transformers/file_utils.py <ide> def wrapper(*args, **kwargs): <ide> """ <ide> <ide> <add>FLAX_IMPORT_ERROR = """ <add>{0} requires the FLAX library but it was not found in your enviromnent. Checkout the instructions on the <add>installation page: https://github.com/google/flax and follow the ones that match your enviromnent. <add>""" <add> <add> <ide> def requires_datasets(obj): <ide> name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__ <ide> if not is_datasets_available(): <ide> def requires_tf(obj): <ide> raise ImportError(TENSORFLOW_IMPORT_ERROR.format(name)) <ide> <ide> <add>def requires_flax(obj): <add> name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__ <add> if not is_flax_available(): <add> raise ImportError(FLAX_IMPORT_ERROR.format(name)) <add> <add> <ide> def requires_tokenizers(obj): <ide> name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__ <ide> if not is_tokenizers_available(): <ide><path>src/transformers/utils/dummy_flax_objects.py <add># This file is autogenerated by the command `make fix-copies`, do not edit. <add>from ..file_utils import requires_flax <add> <add> <add>class FlaxBertModel: <add> def __init__(self, *args, **kwargs): <add> requires_flax(self) <add> <add> @classmethod <add> def from_pretrained(self, *args, **kwargs): <add> requires_flax(self) <add> <add> <add>class FlaxRobertaModel: <add> def __init__(self, *args, **kwargs): <add> requires_flax(self) <add> <add> @classmethod <add> def from_pretrained(self, *args, **kwargs): <add> requires_flax(self) <ide><path>utils/check_dummies.py <ide> def {0}(*args, **kwargs): <ide> """ <ide> <ide> <add>DUMMY_FLAX_PRETRAINED_CLASS = """ <add>class {0}: <add> def __init__(self, *args, **kwargs): <add> requires_flax(self) <add> <add> @classmethod <add> def from_pretrained(self, *args, **kwargs): <add> requires_flax(self) <add>""" <add> <add>DUMMY_FLAX_CLASS = """ <add>class {0}: <add> def __init__(self, *args, **kwargs): <add> requires_flax(self) <add>""" <add> <add>DUMMY_FLAX_FUNCTION = """ <add>def {0}(*args, **kwargs): <add> requires_flax({0}) <add>""" <add> <add> <ide> DUMMY_SENTENCEPIECE_PRETRAINED_CLASS = """ <ide> class {0}: <ide> def __init__(self, *args, **kwargs): <ide> def {0}(*args, **kwargs): <ide> DUMMY_PRETRAINED_CLASS = { <ide> "pt": DUMMY_PT_PRETRAINED_CLASS, <ide> "tf": DUMMY_TF_PRETRAINED_CLASS, <add> "flax": DUMMY_FLAX_PRETRAINED_CLASS, <ide> "sentencepiece": DUMMY_SENTENCEPIECE_PRETRAINED_CLASS, <ide> "tokenizers": DUMMY_TOKENIZERS_PRETRAINED_CLASS, <ide> } <ide> <ide> DUMMY_CLASS = { <ide> "pt": DUMMY_PT_CLASS, <ide> "tf": DUMMY_TF_CLASS, <add> "flax": DUMMY_FLAX_CLASS, <ide> "sentencepiece": DUMMY_SENTENCEPIECE_CLASS, <ide> "tokenizers": DUMMY_TOKENIZERS_CLASS, <ide> } <ide> <ide> DUMMY_FUNCTION = { <ide> "pt": DUMMY_PT_FUNCTION, <ide> "tf": DUMMY_TF_FUNCTION, <add> "flax": DUMMY_FLAX_FUNCTION, <ide> "sentencepiece": DUMMY_SENTENCEPIECE_FUNCTION, <ide> "tokenizers": DUMMY_TOKENIZERS_FUNCTION, <ide> } <ide> def read_init(): <ide> elif line.startswith(" "): <ide> tf_objects.append(line[8:-2]) <ide> line_index += 1 <del> return sentencepiece_objects, tokenizers_objects, pt_objects, tf_objects <add> <add> # Find where the FLAX imports begin <add> flax_objects = [] <add> while not lines[line_index].startswith("if is_flax_available():"): <add> line_index += 1 <add> line_index += 1 <add> <add> # Until we unindent, add PyTorch objects to the list <add> while len(lines[line_index]) <= 1 or lines[line_index].startswith(" "): <add> line = lines[line_index] <add> search = _re_single_line_import.search(line) <add> if search is not None: <add> flax_objects += search.groups()[0].split(", ") <add> elif line.startswith(" "): <add> flax_objects.append(line[8:-2]) <add> line_index += 1 <add> <add> return sentencepiece_objects, tokenizers_objects, pt_objects, tf_objects, flax_objects <ide> <ide> <ide> def create_dummy_object(name, type="pt"): <ide> def create_dummy_object(name, type="pt"): <ide> "Model", <ide> "Tokenizer", <ide> ] <del> assert type in ["pt", "tf", "sentencepiece", "tokenizers"] <add> assert type in ["pt", "tf", "sentencepiece", "tokenizers", "flax"] <ide> if name.isupper(): <ide> return DUMMY_CONSTANT.format(name) <ide> elif name.islower(): <ide> def create_dummy_object(name, type="pt"): <ide> <ide> def create_dummy_files(): <ide> """ Create the content of the dummy files. """ <del> sentencepiece_objects, tokenizers_objects, pt_objects, tf_objects = read_init() <add> sentencepiece_objects, tokenizers_objects, pt_objects, tf_objects, flax_objects = read_init() <ide> <ide> sentencepiece_dummies = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n" <ide> sentencepiece_dummies += "from ..file_utils import requires_sentencepiece\n\n" <ide> def create_dummy_files(): <ide> tf_dummies += "from ..file_utils import requires_tf\n\n" <ide> tf_dummies += "\n".join([create_dummy_object(o, type="tf") for o in tf_objects]) <ide> <del> return sentencepiece_dummies, tokenizers_dummies, pt_dummies, tf_dummies <add> flax_dummies = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n" <add> flax_dummies += "from ..file_utils import requires_flax\n\n" <add> flax_dummies += "\n".join([create_dummy_object(o, type="flax") for o in flax_objects]) <add> <add> return sentencepiece_dummies, tokenizers_dummies, pt_dummies, tf_dummies, flax_dummies <ide> <ide> <ide> def check_dummies(overwrite=False): <ide> """ Check if the dummy files are up to date and maybe `overwrite` with the right content. """ <del> sentencepiece_dummies, tokenizers_dummies, pt_dummies, tf_dummies = create_dummy_files() <add> sentencepiece_dummies, tokenizers_dummies, pt_dummies, tf_dummies, flax_dummies = create_dummy_files() <ide> path = os.path.join(PATH_TO_TRANSFORMERS, "utils") <ide> sentencepiece_file = os.path.join(path, "dummy_sentencepiece_objects.py") <ide> tokenizers_file = os.path.join(path, "dummy_tokenizers_objects.py") <ide> pt_file = os.path.join(path, "dummy_pt_objects.py") <ide> tf_file = os.path.join(path, "dummy_tf_objects.py") <add> flax_file = os.path.join(path, "dummy_flax_objects.py") <ide> <ide> with open(sentencepiece_file, "r", encoding="utf-8") as f: <ide> actual_sentencepiece_dummies = f.read() <ide> def check_dummies(overwrite=False): <ide> actual_pt_dummies = f.read() <ide> with open(tf_file, "r", encoding="utf-8") as f: <ide> actual_tf_dummies = f.read() <add> with open(flax_file, "r", encoding="utf-8") as f: <add> actual_flax_dummies = f.read() <ide> <ide> if sentencepiece_dummies != actual_sentencepiece_dummies: <ide> if overwrite: <ide> def check_dummies(overwrite=False): <ide> "Run `make fix-copies` to fix this.", <ide> ) <ide> <add> if flax_dummies != actual_flax_dummies: <add> if overwrite: <add> print("Updating transformers.utils.dummy_flax_objects.py as the main __init__ has new objects.") <add> with open(flax_file, "w", encoding="utf-8") as f: <add> f.write(flax_dummies) <add> else: <add> raise ValueError( <add> "The main __init__ has objects that are not present in transformers.utils.dummy_flax_objects.py.", <add> "Run `make fix-copies` to fix this.", <add> ) <add> <ide> <ide> if __name__ == "__main__": <ide> parser = argparse.ArgumentParser()
4
Javascript
Javascript
add default padding to iframe iphone view
d5231fc43fb614cecb0f6023d608e51b19d217ce
<ide><path>public/js/lib/coursewares/coursewaresFramework.js <ide> var libraryIncludes = "<script src='//ajax.googleapis.com/ajax/libs/jquery/2.1.3 <ide> "<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js'></script>" + <ide> "<script src='//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.min.js'></script>" + <ide> "<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css'/>" + <del>"<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css'/>" <add>"<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css'/>" + <add>"<style>body { padding: 0px 3px 0px 3px; }</style>" <ide> <ide> var delay; <ide> // Initialize CodeMirror editor with a nice html5 canvas demo.
1
Javascript
Javascript
remove the define.amd.jquery check, ref gh-1150
34c4e122a333bbfc80bd4f6e79db20f3a73ae5b3
<ide><path>src/exports.js <ide> if ( typeof module === "object" && typeof module.exports === "object" ) { <ide> // Otherwise expose jQuery to the global object as usual <ide> window.jQuery = window.$ = jQuery; <ide> <del> // Expose jQuery as an AMD module, but only for AMD loaders that <del> // understand the issues with loading multiple versions of jQuery <del> // in a page that all might call define(). The loader will indicate <del> // they have special allowances for multiple jQuery versions by <del> // specifying define.amd.jQuery = true. Register as a named module, <del> // since jQuery can be concatenated with other files that may use define, <del> // but not use a proper concatenation script that understands anonymous <del> // AMD modules. A named AMD is safest and most robust way to register. <del> // Lowercase jquery is used because AMD module names are derived from <del> // file names, and jQuery is normally delivered in a lowercase file name. <del> // Do this after creating the global so that if an AMD module wants to call <del> // noConflict to hide this version of jQuery, it will work. <del> if ( typeof define === "function" && define.amd && define.amd.jQuery ) { <add> // Register as a named AMD module, since jQuery can be concatenated with other <add> // files that may use define, but not via a proper concatenation script that <add> // understands anonymous AMD modules. A named AMD is safest and most robust <add> // way to register. Lowercase jquery is used because AMD module names are <add> // derived from file names, and jQuery is normally delivered in a lowercase <add> // file name. Do this after creating the global so that if an AMD module wants <add> // to call noConflict to hide this version of jQuery, it will work. <add> if ( typeof define === "function" && define.amd ) { <ide> define( "jquery", [], function () { return jQuery; } ); <ide> } <ide> } <ide><path>test/data/testinit.js <ide> function define( name, dependencies, callback ) { <ide> amdDefined = callback(); <ide> } <ide> <del>define.amd = { <del> jQuery: true <del>}; <add>define.amd = {}; <ide> <ide> /** <ide> * Returns an array of elements with the given IDs
2
PHP
PHP
use hasassociation() instead of getassociation()
29719a6eb1cefd9192432cd0df727f6c5edbffd6
<ide><path>src/ORM/Association/BelongsToMany.php <ide> protected function _generateTargetAssociations($junction, $source, $target) <ide> $junctionAlias = $junction->getAlias(); <ide> $sAlias = $source->getAlias(); <ide> <del> if (!$target->getAssociation($junctionAlias)) { <add> if (!$target->hasAssociation($junctionAlias)) { <ide> $target->hasMany($junctionAlias, [ <ide> 'targetTable' => $junction, <ide> 'foreignKey' => $this->getTargetForeignKey(), <ide> 'strategy' => $this->_strategy, <ide> ]); <ide> } <del> if (!$target->getAssociation($sAlias)) { <add> if (!$target->hasAssociation($sAlias)) { <ide> $target->belongsToMany($sAlias, [ <ide> 'sourceTable' => $target, <ide> 'targetTable' => $source, <ide> protected function _generateTargetAssociations($junction, $source, $target) <ide> protected function _generateSourceAssociations($junction, $source) <ide> { <ide> $junctionAlias = $junction->getAlias(); <del> if (!$source->getAssociation($junctionAlias)) { <add> if (!$source->hasAssociation($junctionAlias)) { <ide> $source->hasMany($junctionAlias, [ <ide> 'targetTable' => $junction, <ide> 'foreignKey' => $this->getForeignKey(), <ide> protected function _generateJunctionAssociations($junction, $source, $target) <ide> $tAlias = $target->getAlias(); <ide> $sAlias = $source->getAlias(); <ide> <del> if (!$junction->getAssociation($tAlias)) { <add> if (!$junction->hasAssociation($tAlias)) { <ide> $junction->belongsTo($tAlias, [ <ide> 'foreignKey' => $this->getTargetForeignKey(), <ide> 'targetTable' => $target <ide> ]); <ide> } <del> if (!$junction->getAssociation($sAlias)) { <add> if (!$junction->hasAssociation($sAlias)) { <ide> $junction->belongsTo($sAlias, [ <ide> 'foreignKey' => $this->getForeignKey(), <ide> 'targetTable' => $source <ide><path>src/ORM/Marshaller.php <ide> protected function _buildPropertyMap($data, $options) <ide> $key = $nested; <ide> $nested = []; <ide> } <del> $assoc = $this->_table->getAssociation($key); <ide> // If the key is not a special field like _ids or _joinData <ide> // it is a missing association that we should error on. <del> if (!$assoc) { <add> if (!$this->_table->hasAssociation($key)) { <ide> if (substr($key, 0, 1) !== '_') { <ide> throw new \InvalidArgumentException(sprintf( <ide> 'Cannot marshal data for "%s" association. It is not associated with "%s".', <ide> protected function _buildPropertyMap($data, $options) <ide> } <ide> continue; <ide> } <add> $assoc = $this->_table->getAssociation($key); <add> <ide> if (isset($options['forceNew'])) { <ide> $nested['forceNew'] = $options['forceNew']; <ide> } <ide><path>src/ORM/Query.php <ide> public function clearContain() <ide> protected function _addAssociationsToTypeMap($table, $typeMap, $associations) <ide> { <ide> foreach ($associations as $name => $nested) { <del> $association = $table->getAssociation($name); <del> if (!$association) { <add> if (!$table->hasAssociation($name)) { <ide> continue; <ide> } <add> $association = $table->getAssociation($name); <ide> $target = $association->getTarget(); <ide> $primary = (array)$target->getPrimaryKey(); <ide> if (empty($primary) || $typeMap->type($target->aliasField($primary[0])) === null) {
3
Ruby
Ruby
deprecate custom patterns for pathresolver
573e361a3ccb2cc716ed028d66da8af144bc0db2
<ide><path>actionview/lib/action_view/template/resolver.rb <ide> class PathResolver < Resolver #:nodoc: <ide> DEFAULT_PATTERN = ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}" <ide> <ide> def initialize(pattern = nil) <del> @pattern = pattern || DEFAULT_PATTERN <add> if pattern <add> ActiveSupport::Deprecation.warn "Specifying a custom path for #{self.class} is deprecated. Implement a custom Resolver subclass instead." <add> @pattern = pattern <add> else <add> @pattern = DEFAULT_PATTERN <add> end <ide> super() <ide> end <ide> <ide> def extract_handler_and_format_and_variant(path) <ide> end <ide> end <ide> <del> # A resolver that loads files from the filesystem. It allows setting your own <del> # resolving pattern. Such pattern can be a glob string supported by some variables. <del> # <del> # ==== Examples <del> # <del> # Default pattern, loads views the same way as previous versions of rails, eg. when you're <del> # looking for <tt>users/new</tt> it will produce query glob: <tt>users/new{.{en},}{.{html,js},}{.{erb,haml},}</tt> <del> # <del> # FileSystemResolver.new("/path/to/views", ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}") <del> # <del> # This one allows you to keep files with different formats in separate subdirectories, <del> # eg. <tt>users/new.html</tt> will be loaded from <tt>users/html/new.erb</tt> or <tt>users/new.html.erb</tt>, <del> # <tt>users/new.js</tt> from <tt>users/js/new.erb</tt> or <tt>users/new.js.erb</tt>, etc. <del> # <del> # FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}") <del> # <del> # If you don't specify a pattern then the default will be used. <del> # <del> # In order to use any of the customized resolvers above in a Rails application, you just need <del> # to configure ActionController::Base.view_paths in an initializer, for example: <del> # <del> # ActionController::Base.view_paths = FileSystemResolver.new( <del> # Rails.root.join("app/views"), <del> # ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", <del> # ) <del> # <del> # ==== Pattern format and variables <del> # <del> # Pattern has to be a valid glob string, and it allows you to use the <del> # following variables: <del> # <del> # * <tt>:prefix</tt> - usually the controller path <del> # * <tt>:action</tt> - name of the action <del> # * <tt>:locale</tt> - possible locale versions <del> # * <tt>:formats</tt> - possible request formats (for example html, json, xml...) <del> # * <tt>:variants</tt> - possible request variants (for example phone, tablet...) <del> # * <tt>:handlers</tt> - possible handlers (for example erb, haml, builder...) <del> # <add> # A resolver that loads files from the filesystem. <ide> class FileSystemResolver < PathResolver <ide> def initialize(path, pattern = nil) <ide> raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver) <ide> def eql?(resolver) <ide> <ide> # An Optimized resolver for Rails' most common case. <ide> class OptimizedFileSystemResolver < FileSystemResolver #:nodoc: <add> def initialize(path) <add> super(path) <add> end <add> <ide> private <ide> <ide> def find_template_paths_from_details(path, details) <ide><path>actionview/test/template/resolver_patterns_test.rb <ide> class ResolverPatternsTest < ActiveSupport::TestCase <ide> def setup <ide> path = File.expand_path("../fixtures", __dir__) <ide> pattern = ":prefix/{:formats/,}:action{.:formats,}{+:variants,}{.:handlers,}" <del> @resolver = ActionView::FileSystemResolver.new(path, pattern) <add> <add> assert_deprecated do <add> @resolver = ActionView::FileSystemResolver.new(path, pattern) <add> end <ide> end <ide> <ide> def test_should_return_empty_list_for_unknown_path
2
Javascript
Javascript
use same string representation as $interpolate
fa80a61a05a3b49a2c770d5544cb8480907a18d3
<ide><path>src/ng/directive/ngBind.js <ide> var ngBindDirective = ['$compile', function($compile) { <ide> $compile.$$addBindingInfo(element, attr.ngBind); <ide> element = element[0]; <ide> scope.$watch(attr.ngBind, function ngBindWatchAction(value) { <del> element.textContent = isUndefined(value) ? '' : value; <add> element.textContent = stringify(value); <ide> }); <ide> }; <ide> } <ide><path>test/ng/directive/ngBindSpec.js <ide> describe('ngBind*', function() { <ide> expect(element.text()).toEqual('-0false'); <ide> })); <ide> <add> they('should jsonify $prop', [[{a: 1}, '{"a":1}'], [true, 'true'], [false, 'false']], function(prop) { <add> inject(function($rootScope, $compile) { <add> $rootScope.value = prop[0]; <add> element = $compile('<div ng-bind="value"></div>')($rootScope); <add> $rootScope.$digest(); <add> expect(element.text()).toEqual(prop[1]); <add> }); <add> }); <add> <add> it('should use custom toString when present', inject(function($rootScope, $compile) { <add> $rootScope.value = { <add> toString: function() { <add> return 'foo'; <add> } <add> }; <add> element = $compile('<div ng-bind="value"></div>')($rootScope); <add> $rootScope.$digest(); <add> expect(element.text()).toEqual('foo'); <add> })); <add> <add> it('should NOT use toString on array objects', inject(function($rootScope, $compile) { <add> $rootScope.value = []; <add> element = $compile('<div ng-bind="value"></div>')($rootScope); <add> $rootScope.$digest(); <add> expect(element.text()).toEqual('[]'); <add> })); <add> <add> <add> it('should NOT use toString on Date objects', inject(function($rootScope, $compile) { <add> $rootScope.value = new Date(2014, 10, 10, 0, 0, 0); <add> element = $compile('<div ng-bind="value"></div>')($rootScope); <add> $rootScope.$digest(); <add> expect(element.text()).toBe(JSON.stringify($rootScope.value)); <add> expect(element.text()).not.toEqual($rootScope.value.toString()); <add> })); <add> <add> <ide> it('should one-time bind if the expression starts with two colons', inject(function($rootScope, $compile) { <ide> element = $compile('<div ng-bind="::a"></div>')($rootScope); <ide> $rootScope.a = 'lucas';
2
Text
Text
add credential helper documentation
68211f4cb45baca957fef625ba3bb0c422dd20ec
<ide><path>docs/reference/commandline/cli.md <ide> property is not set, the client falls back to the default table <ide> format. For a list of supported formatting directives, see <ide> [**Formatting** section in the `docker stats` documentation](stats.md) <ide> <add>The property `credsStore` specifies an external binary to serve as the default <add>credential store. When this property is set, `docker login` will attempt to <add>store credentials in the binary specified by `docker-credential-<value>` which <add>is visible on `$PATH`. If this property is not set, credentials will be stored <add>in the `auths` property of the config. For more information, see the <add>[**Credentials store** section in the `docker login` documentation](login.md#credentials-store) <add> <add>The property `credHelpers` specifies a set of credential helpers to use <add>preferentially over `credsStore` or `auths` when storing and retrieving <add>credentials for specific registries. If this property is set, the binary <add>`docker-credential-<value>` will be used when storing or retrieving credentials <add>for a specific registry. For more information, see the <add>[**Credential helpers** section in the `docker login` documentation](login.md#credential-helpers) <add> <ide> Once attached to a container, users detach from it and leave it running using <ide> the using `CTRL-p CTRL-q` key sequence. This detach key sequence is customizable <ide> using the `detachKeys` property. Specify a `<sequence>` value for the <ide> Following is a sample `config.json` file: <ide> "imagesFormat": "table {{.ID}}\\t{{.Repository}}\\t{{.Tag}}\\t{{.CreatedAt}}", <ide> "statsFormat": "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}", <ide> "serviceInspectFormat": "pretty", <del> "detachKeys": "ctrl-e,e" <add> "detachKeys": "ctrl-e,e", <add> "credsStore": "secretservice", <add> "credHelpers": { <add> "awesomereg.example.org": "hip-star", <add> "unicorn.example.com": "vcbait" <add> } <ide> } <ide> {% endraw %} <ide> <ide><path>docs/reference/commandline/login.md <ide> you can download them from: <ide> ### Usage <ide> <ide> You need to specify the credentials store in `$HOME/.docker/config.json` <del>to tell the docker engine to use it: <add>to tell the docker engine to use it. The value of the config property should be <add>the suffix of the program to use (i.e. everything after `docker-credential-`). <add>For example, to use `docker-credential-osxkeychain`: <ide> <ide> ```json <ide> { <ide> an example of that payload: `https://index.docker.io/v1`. <ide> <ide> The `erase` command can write error messages to `STDOUT` that the docker engine <ide> will show if there was an issue. <add> <add>## Credential helpers <add> <add>Credential helpers are similar to the credential store above, but act as the <add>designated programs to handle credentials for *specific registries*. The default <add>credential store (`credsStore` or the config file itself) will not be used for <add>operations concerning credentials of the specified registries. <add> <add>### Usage <add> <add>If you are currently logged in, run `docker logout` to remove <add>the credentials from the default store. <add> <add>Credential helpers are specified in a similar way to `credsStore`, but <add>allow for multiple helpers to be configured at a time. Keys specify the <add>registry domain, and values specify the suffix of the program to use <add>(i.e. everything after `docker-credential-`). <add>For example: <add> <add>```json <add>{ <add> "credHelpers": { <add> "registry.example.com": "registryhelper", <add> "awesomereg.example.org": "hip-star", <add> "unicorn.example.io": "vcbait" <add> } <add>} <add>```
2
Python
Python
expand linspace docstring
18d3af5ea658b0f1846e5307fe60263312d52bdd
<ide><path>numpy/lib/function_base.py <ide> def linspace(start, stop, num=50, endpoint=True, retstep=False): <ide> <ide> Return num evenly spaced samples from start to stop. If <ide> endpoint is True, the last sample is stop. If retstep is <del> True then return the step value used. <add> True then return (seq, step_value), where step_value used. <add> <add> :Parameters: <add> start : {float} <add> The value the sequence starts at. <add> stop : {float} <add> The value the sequence stops at. If ``endpoint`` is false, then <add> this is not included in the sequence. Otherwise it is <add> guaranteed to be the last value. <add> num : {integer} <add> Number of samples to generate. Default is 50. <add> endpoint : {boolean} <add> If true, ``stop`` is the last sample. Otherwise, it is not <add> included. Default is true. <add> retstep : {boolean} <add> If true, return ``(samples, step)``, where ``step`` is the <add> spacing used in generating the samples. <add> <add> :Returns: <add> samples : {array} <add> ``num`` equally spaced samples from the range [start, stop] <add> or [start, stop). <add> step : {float} (Only if ``retstep`` is true) <add> Size of spacing between samples. <add> <add> :See Also: <add> `arange` : Similiar to linspace, however, when used with <add> a float endpoint, that endpoint may or may not be included. <add> `logspace` <ide> """ <ide> num = int(num) <ide> if num <= 0:
1
Text
Text
add table explaining training metrics [closes ]
1b6238101ae5c2623ae1411ffbd2d0cdcdad7a49
<ide><path>website/docs/usage/training.md <ide> mkdir models <ide> python -m spacy train es models ancora-json/es_ancora-ud-train.json ancora-json/es_ancora-ud-dev.json <ide> ``` <ide> <add>#### Understanding the training output <add> <add>When you train a model using the [`spacy train`](/api/cli#train) command, you'll <add>see a table showing metrics after each pass over the data. Here's what those <add>metrics means: <add> <add>> #### Tokenization metrics <add>> <add>> Note that if the development data has raw text, some of the gold-standard <add>> entities might not align to the predicted tokenization. These tokenization <add>> errors are **excluded from the NER evaluation**. If your tokenization makes it <add>> impossible for the model to predict 50% of your entities, your NER F-score <add>> might still look good. <add> <add>| Name | Description | <add>| ---------- | ------------------------------------------------------------------------------------------------- | <add>| `Dep Loss` | Training loss for dependency parser. Should decrease, but usually not to 0. | <add>| `NER Loss` | Training loss for named entity recognizer. Should decrease, but usually not to 0. | <add>| `UAS` | Unlabeled attachment score for parser. The percentage of unlabeled correct arcs. Should increase. | <add>| `NER P.` | NER precision on development data. Should increase. | <add>| `NER R.` | NER recall on development data. Should increase. | <add>| `NER F.` | NER F-score on development data. Should increase. | <add>| `Tag %` | Fine-grained part-of-speech tag accuracy on development data. Should increase. | <add>| `Token %` | Tokenization accuracy on development data. | <add>| `CPU WPS` | Prediction speed on CPU in words per second, if available. Should stay stable. | <add>| `GPU WPS` | Prediction speed on GPU in words per second, if available. Should stay stable. | <add> <ide> ### Improving accuracy with transfer learning {#transfer-learning new="2.1"} <ide> <ide> In most projects, you'll usually have a small amount of labelled data, and
1
Text
Text
add v4.8.0-beta.1 to changelog
f48affedde8e19f617c973b4c01df33dfc475fee
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.8.0-beta.1 (September 6, 2022) <add> <add>- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Upgrade router_js to fix Linked list of RouteInfos contains undefined object <add> <ide> ### v4.7.0 (September 6, 2022) <ide> <ide> - [#20126](https://github.com/emberjs/ember.js/pull/20126) [BUGFIX] Replace Firefox detection that used a deprecated browser API
1
Text
Text
clarify element in role-playing-game
ef1c90ecd7ed923b9ec82ac52730951cdd7147c3
<ide><path>curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a7bfabe119461eb13ccbd6.md <ide> dashedName: step-45 <ide> <ide> # --description-- <ide> <del>Now you need to modify your display text. Change the `innerText` of the `text` to be `You enter the store.`. <add>Now you need to modify your display text. Change the `innerText` property of the `text` to be `You enter the store.`. <ide> <ide> # --hints-- <ide>
1
Ruby
Ruby
reduce array allocations while finding templates
07c50800fb08ca486c9592549a24fb18fc5e4309
<ide><path>actionview/lib/action_view/template/resolver.rb <ide> def build_regex(path, details) <ide> if ext == :variants && details[ext] == :any <ide> ".*?" <ide> else <del> details[ext].compact.uniq.map { |e| Regexp.escape(e) }.join("|") <add> arr = details[ext].compact <add> arr.uniq! <add> arr.map! { |e| Regexp.escape(e) } <add> arr.join("|") <ide> end <ide> prefix = Regexp.escape(prefix) <ide> "(#{prefix}(?<#{ext}>#{match}))?"
1
Python
Python
add clearer error message for diff(0-d)
d7de4ad70d6794b36e4789e4f6146a884113bd66
<ide><path>numpy/lib/function_base.py <ide> def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): <ide> <ide> a = asanyarray(a) <ide> nd = a.ndim <add> if nd == 0: <add> raise ValueError("diff requires input that is at least one dimensional") <ide> axis = normalize_axis_index(axis, nd) <ide> <ide> combined = [] <ide><path>numpy/lib/tests/test_function_base.py <ide> def test_axis(self): <ide> assert_raises(np.AxisError, diff, x, axis=3) <ide> assert_raises(np.AxisError, diff, x, axis=-4) <ide> <add> x = np.array(1.11111111111, np.float64) <add> assert_raises(ValueError, diff, x) <add> <ide> def test_nd(self): <ide> x = 20 * rand(10, 20, 30) <ide> out1 = x[:, :, 1:] - x[:, :, :-1]
2
PHP
PHP
fix showing/clearing of custom validity message
b89cbc2aaaac70ee26e58fc8548d2a287a18d839
<ide><path>src/View/Helper/FormHelper.php <ide> protected function _magicOptions($fieldName, $options, $allowOverride) <ide> $options['templateVars']['customValidityMessage'] = $message; <ide> <ide> if ($this->getConfig('autoSetCustomValidity')) { <del> $options['oninvalid'] = "this.setCustomValidity('$message')"; <del> $options['onvalid'] = "this.setCustomValidity('')"; <add> $options['oninvalid'] = "this.setCustomValidity(''); if (!this.validity.valid) this.setCustomValidity('$message')"; <add> $options['oninput'] = "this.setCustomValidity('')"; <ide> } <ide> } <ide> } <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testHtml5ErrorMessage() <ide> 'type' => 'password', <ide> 'value' => '', <ide> 'required' => 'required', <del> 'onvalid' => 'this.setCustomValidity(&#039;&#039;)', <del> 'oninvalid' => 'this.setCustomValidity(&#039;This field is required&#039;)', <add> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.validity.valid) this.setCustomValidity(&#039;This field is required&#039;)', <ide> ] <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> public function testHtml5ErrorMessage() <ide> 'value' => '', <ide> 'maxlength' => 255, <ide> 'required' => 'required', <del> 'onvalid' => 'this.setCustomValidity(&#039;&#039;)', <del> 'oninvalid' => 'this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.validity.valid) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <ide> ] <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> public function testHtml5ErrorMessage() <ide> 'value' => '', <ide> 'maxlength' => 255, <ide> 'required' => 'required', <del> 'onvalid' => 'this.setCustomValidity(&#039;&#039;)', <del> 'oninvalid' => 'this.setCustomValidity(&#039;Custom error message&#039;)', <add> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.validity.valid) this.setCustomValidity(&#039;Custom error message&#039;)', <ide> ] <ide> ]; <ide> $this->assertHtml($expected, $result);
2
Javascript
Javascript
remove conditions that are always true
a67575ea404363af75728f963f7fe2d658c1aec0
<ide><path>examples/js/loaders/XLoader.js <ide> <ide> var model = _model; <ide> var animation = _animation; <del> var bindFlag = _isBind ? _isBind : true; <ide> if ( ! model ) { <ide> <ide> model = this.Meshes[ 0 ]; <ide> model.geometry.animations = []; <ide> <ide> } <del> if ( bindFlag ) { <ide> <del> model.geometry.animations.push( THREE.AnimationClip.parseAnimation( put, model.skeleton.bones ) ); <del> if ( ! model.animationMixer ) { <add> model.geometry.animations.push( THREE.AnimationClip.parseAnimation( put, model.skeleton.bones ) ); <add> if ( ! model.animationMixer ) { <ide> <del> model.animationMixer = new THREE.AnimationMixer( model ); <del> <del> } <add> model.animationMixer = new THREE.AnimationMixer( model ); <ide> <ide> } <add> <ide> return put; <ide> <ide> }
1
PHP
PHP
add deprecation warnings to error package
c5570704bea3968089465238898285aa9167de87
<ide><path>src/Error/Debugger.php <ide> public static function setOutputFormat($format) <ide> */ <ide> public static function outputAs($format = null) <ide> { <add> deprecationWarning( <add> 'Debugger::outputAs() is deprecated. Use Debugger::getOutputFormat()/setOutputFormat() instead.' <add> ); <ide> $self = Debugger::getInstance(); <ide> if ($format === null) { <ide> return $self->_outputFormat; <ide><path>tests/TestCase/Error/DebuggerTest.php <ide> public function testExcerpt() <ide> /** <ide> * Test that outputAs works. <ide> * <add> * @group deprecated <ide> * @return void <ide> */ <ide> public function testOutputAs() <ide> { <del> Debugger::outputAs('html'); <del> $this->assertEquals('html', Debugger::outputAs()); <add> $this->deprecated(function() { <add> Debugger::outputAs('html'); <add> $this->assertEquals('html', Debugger::outputAs()); <add> }); <add> } <add> <add> /** <add> * Test that setOutputFormat works. <add> * <add> * @group deprecated <add> * @return void <add> */ <add> public function testSetOutputFormat() <add> { <add> Debugger::setOutputFormat('html'); <add> $this->assertEquals('html', Debugger::getOutputFormat()); <ide> } <ide> <ide> /** <ide> * Test that choosing a non-existent format causes an exception <ide> * <add> * @group deprecated <ide> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testOutputAsException() <ide> { <del> Debugger::outputAs('Invalid junk'); <add> $this->deprecated(function() { <add> Debugger::outputAs('Invalid junk'); <add> }); <ide> } <ide> <ide> /** <ide> public function testSetOutputAsException() <ide> */ <ide> public function testOutputErrorDescriptionEncoding() <ide> { <del> Debugger::outputAs('html'); <add> Debugger::setOutputFormat('html'); <ide> <ide> ob_start(); <ide> $debugger = Debugger::getInstance(); <ide> public function testOutputErrorDescriptionEncoding() <ide> */ <ide> public function testOutputErrorLineHighlight() <ide> { <del> Debugger::outputAs('js'); <add> Debugger::setOutputFormat('js'); <ide> <ide> ob_start(); <ide> $debugger = Debugger::getInstance(); <ide> public function testAddFormat() <ide> 'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' . <ide> '&line={:line}">{:path}</a>, line {:line}' <ide> ]); <del> Debugger::outputAs('js'); <add> Debugger::setOutputFormat('js'); <ide> <ide> $result = Debugger::trace(); <ide> $this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result); <ide> public function testAddFormat() <ide> 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' . <ide> '{:description}</error>', <ide> ]); <del> Debugger::outputAs('xml'); <add> Debugger::setOutputFormat('xml'); <ide> <ide> ob_start(); <ide> $debugger = Debugger::getInstance(); <ide> public function testAddFormat() <ide> public function testAddFormatCallback() <ide> { <ide> Debugger::addFormat('callback', ['callback' => [$this, 'customFormat']]); <del> Debugger::outputAs('callback'); <add> Debugger::setOutputFormat('callback'); <ide> <ide> ob_start(); <ide> $debugger = Debugger::getInstance();
2
Javascript
Javascript
fix some indents
8bf4f29237cec182f03ddc4f5b9ece5aa864d4e0
<ide><path>examples/js/shaders/BrightnessContrastShader.js <ide> THREE.BrightnessContrastShader = { <ide> <ide> "void main() {", <ide> <del> "vUv = uv;", <add> " vUv = uv;", <ide> <del> "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <add> " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <ide> <ide> "}" <ide> <ide> THREE.BrightnessContrastShader = { <ide> <ide> "void main() {", <ide> <del> "gl_FragColor = texture2D( tDiffuse, vUv );", <add> " gl_FragColor = texture2D( tDiffuse, vUv );", <ide> <del> "gl_FragColor.rgb += brightness;", <add> " gl_FragColor.rgb += brightness;", <ide> <del> "if (contrast > 0.0) {", <del> "gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - contrast) + 0.5;", <del> "} else {", <del> "gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + contrast) + 0.5;", <del> "}", <add> " if (contrast > 0.0) {", <add> " gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - contrast) + 0.5;", <add> " } else {", <add> " gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + contrast) + 0.5;", <add> " }", <ide> <ide> "}" <ide> <ide><path>examples/js/shaders/ColorCorrectionShader.js <ide> THREE.ColorCorrectionShader = { <ide> <ide> "void main() {", <ide> <del> "vUv = uv;", <add> " vUv = uv;", <ide> <del> "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <add> " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <ide> <ide> "}" <ide> <ide> THREE.ColorCorrectionShader = { <ide> <ide> "void main() {", <ide> <del> "gl_FragColor = texture2D( tDiffuse, vUv );", <del> "gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB );", <add> " gl_FragColor = texture2D( tDiffuse, vUv );", <add> " gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB );", <ide> <ide> "}" <ide> <ide><path>examples/js/shaders/ColorifyShader.js <ide> THREE.ColorifyShader = { <ide> <ide> "void main() {", <ide> <del> "vUv = uv;", <del> "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <add> " vUv = uv;", <add> " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <ide> <ide> "}" <ide> <ide> THREE.ColorifyShader = { <ide> <ide> "void main() {", <ide> <del> "vec4 texel = texture2D( tDiffuse, vUv );", <add> " vec4 texel = texture2D( tDiffuse, vUv );", <ide> <del> "vec3 luma = vec3( 0.299, 0.587, 0.114 );", <del> "float v = dot( texel.xyz, luma );", <add> " vec3 luma = vec3( 0.299, 0.587, 0.114 );", <add> " float v = dot( texel.xyz, luma );", <ide> <del> "gl_FragColor = vec4( v * color, texel.w );", <add> " gl_FragColor = vec4( v * color, texel.w );", <ide> <ide> "}" <ide> <ide><path>examples/js/shaders/ConvolutionShader.js <ide> THREE.ConvolutionShader = { <ide> <ide> "void main() {", <ide> <del> "vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;", <del> "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <add> " vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;", <add> " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <ide> <ide> "}" <ide> <ide> THREE.ConvolutionShader = { <ide> <ide> "void main() {", <ide> <del> "vec2 imageCoord = vUv;", <del> "vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );", <add> " vec2 imageCoord = vUv;", <add> " vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );", <ide> <del> "for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {", <add> " for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {", <ide> <del> "sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];", <del> "imageCoord += uImageIncrement;", <add> " sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];", <add> " imageCoord += uImageIncrement;", <ide> <del> "}", <add> " }", <ide> <del> "gl_FragColor = sum;", <add> " gl_FragColor = sum;", <ide> <ide> "}" <ide> <ide><path>examples/js/shaders/CopyShader.js <ide> THREE.CopyShader = { <ide> <ide> "void main() {", <ide> <del> "vUv = uv;", <del> "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <add> " vUv = uv;", <add> " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <ide> <ide> "}" <ide> <ide> THREE.CopyShader = { <ide> <ide> "void main() {", <ide> <del> "vec4 texel = texture2D( tDiffuse, vUv );", <del> "gl_FragColor = opacity * texel;", <add> " vec4 texel = texture2D( tDiffuse, vUv );", <add> " gl_FragColor = opacity * texel;", <ide> <ide> "}" <ide> <ide><path>examples/js/shaders/DigitalGlitch.js <ide> THREE.DigitalGlitch = { <ide> <ide> "varying vec2 vUv;", <ide> "void main() {", <del> "vUv = uv;", <del> "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <add> " vUv = uv;", <add> " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", <ide> "}" <ide> ].join( "\n" ), <ide> <ide> THREE.DigitalGlitch = { <ide> <ide> <ide> "float rand(vec2 co){", <del> "return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);", <add> " return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);", <ide> "}", <ide> <ide> "void main() {", <del> "if(byp<1) {", <del> "vec2 p = vUv;", <del> "float xs = floor(gl_FragCoord.x / 0.5);", <del> "float ys = floor(gl_FragCoord.y / 0.5);", <del> //based on staffantans glitch shader for unity https://github.com/staffantan/unityglitch <del> "vec4 normal = texture2D (tDisp, p*seed*seed);", <del> "if(p.y<distortion_x+col_s && p.y>distortion_x-col_s*seed) {", <del> "if(seed_x>0.){", <del> "p.y = 1. - (p.y + distortion_y);", <del> "}", <del> "else {", <del> "p.y = distortion_y;", <del> "}", <del> "}", <del> "if(p.x<distortion_y+col_s && p.x>distortion_y-col_s*seed) {", <del> "if(seed_y>0.){", <del> "p.x=distortion_x;", <del> "}", <del> "else {", <del> "p.x = 1. - (p.x + distortion_x);", <del> "}", <del> "}", <del> "p.x+=normal.x*seed_x*(seed/5.);", <del> "p.y+=normal.y*seed_y*(seed/5.);", <del> //base from RGB shift shader <del> "vec2 offset = amount * vec2( cos(angle), sin(angle));", <del> "vec4 cr = texture2D(tDiffuse, p + offset);", <del> "vec4 cga = texture2D(tDiffuse, p);", <del> "vec4 cb = texture2D(tDiffuse, p - offset);", <del> "gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a);", <del> //add noise <del> "vec4 snow = 200.*amount*vec4(rand(vec2(xs * seed,ys * seed*50.))*0.2);", <del> "gl_FragColor = gl_FragColor+ snow;", <del> "}", <del> "else {", <del> "gl_FragColor=texture2D (tDiffuse, vUv);", <del> "}", <add> " if(byp<1) {", <add> " vec2 p = vUv;", <add> " float xs = floor(gl_FragCoord.x / 0.5);", <add> " float ys = floor(gl_FragCoord.y / 0.5);", <add> //based on staffantans glitch shader for unity https://github.com/staffantan/unityglitch <add> " vec4 normal = texture2D (tDisp, p*seed*seed);", <add> " if(p.y<distortion_x+col_s && p.y>distortion_x-col_s*seed) {", <add> " if(seed_x>0.){", <add> " p.y = 1. - (p.y + distortion_y);", <add> " }", <add> " else {", <add> " p.y = distortion_y;", <add> " }", <add> " }", <add> " if(p.x<distortion_y+col_s && p.x>distortion_y-col_s*seed) {", <add> " if(seed_y>0.){", <add> " p.x=distortion_x;", <add> " }", <add> " else {", <add> " p.x = 1. - (p.x + distortion_x);", <add> " }", <add> " }", <add> " p.x+=normal.x*seed_x*(seed/5.);", <add> " p.y+=normal.y*seed_y*(seed/5.);", <add> //base from RGB shift shader <add> " vec2 offset = amount * vec2( cos(angle), sin(angle));", <add> " vec4 cr = texture2D(tDiffuse, p + offset);", <add> " vec4 cga = texture2D(tDiffuse, p);", <add> " vec4 cb = texture2D(tDiffuse, p - offset);", <add> " gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a);", <add> //add noise <add> " vec4 snow = 200.*amount*vec4(rand(vec2(xs * seed,ys * seed*50.))*0.2);", <add> " gl_FragColor = gl_FragColor+ snow;", <add> " }", <add> " else {", <add> " gl_FragColor=texture2D (tDiffuse, vUv);", <add> " }", <ide> "}" <ide> <ide> ].join( "\n" )
6
Javascript
Javascript
delay session.receive() by a tick
564fcb8f7844660bb732d1bf96f352f7cd40411c
<ide><path>lib/internal/http2/core.js <ide> function connect(authority, options, listener) { <ide> if (typeof listener === 'function') <ide> session.once('connect', listener); <ide> <del> debug('Http2Session connect', options.createConnection); <del> // Socket already has some buffered data - emulate receiving it <del> // https://github.com/nodejs/node/issues/35475 <del> if (socket && socket.readableLength) { <del> let buf; <del> while ((buf = socket.read()) !== null) { <del> debug(`Http2Session connect: injecting ${buf.length} already in buffer`); <del> session[kHandle].receive(buf); <add> // Process data on the next tick - a remoteSettings handler may be attached. <add> // https://github.com/nodejs/node/issues/35981 <add> process.nextTick(() => { <add> debug('Http2Session connect', options.createConnection); <add> // Socket already has some buffered data - emulate receiving it <add> // https://github.com/nodejs/node/issues/35475 <add> if (socket && socket.readableLength) { <add> let buf; <add> while ((buf = socket.read()) !== null) { <add> debug(`Http2Session connect: ${buf.length} bytes already in buffer`); <add> session[kHandle].receive(buf); <add> } <ide> } <del> } <add> }); <add> <ide> return session; <ide> } <ide> <ide><path>test/parallel/test-http2-connect-tls-with-delay.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <del>if (!common.hasMultiLocalhost()) <del> common.skip('platform-specific test.'); <del> <ide> const http2 = require('http2'); <del>const assert = require('assert'); <ide> const tls = require('tls'); <ide> const fixtures = require('../common/fixtures'); <ide> <ide> const serverOptions = { <ide> key: fixtures.readKey('agent1-key.pem'), <ide> cert: fixtures.readKey('agent1-cert.pem') <ide> }; <del>const server = http2.createSecureServer(serverOptions, (req, res) => { <del> console.log(`Connect from: ${req.connection.remoteAddress}`); <del> assert.strictEqual(req.connection.remoteAddress, '127.0.0.2'); <ide> <del> req.on('end', common.mustCall(() => { <del> res.writeHead(200, { 'Content-Type': 'text/plain' }); <del> res.end(`You are from: ${req.connection.remoteAddress}`); <del> })); <del> req.resume(); <add>const server = http2.createSecureServer(serverOptions, (req, res) => { <add> res.end(); <ide> }); <ide> <ide> server.listen(0, '127.0.0.1', common.mustCall(() => { <ide> const options = { <ide> ALPNProtocols: ['h2'], <ide> host: '127.0.0.1', <ide> servername: 'localhost', <del> localAddress: '127.0.0.2', <ide> port: server.address().port, <ide> rejectUnauthorized: false <ide> }; <ide> <del> console.log('Server ready', server.address().port); <del> <ide> const socket = tls.connect(options, async () => { <del> <del> console.log('TLS Connected!'); <del> <del> setTimeout(() => { <del> <add> socket.once('readable', () => { <ide> const client = http2.connect( <ide> 'https://localhost:' + server.address().port, <ide> { ...options, createConnection: () => socket } <ide> ); <del> const req = client.request({ <del> ':path': '/' <del> }); <del> req.on('data', () => req.resume()); <del> req.on('end', common.mustCall(function() { <del> client.close(); <del> req.close(); <del> server.close(); <add> <add> client.once('remoteSettings', common.mustCall(() => { <add> const req = client.request({ <add> ':path': '/' <add> }); <add> req.on('data', () => req.resume()); <add> req.on('end', common.mustCall(() => { <add> client.close(); <add> req.close(); <add> server.close(); <add> })); <add> req.end(); <ide> })); <del> req.end(); <del> }, 1000); <add> }); <ide> }); <ide> }));
2
Ruby
Ruby
fix misleading advice to add 'memcache' to gemfile
f659a1576fc4a447bbfbd866c7244d8d790a3d9c
<ide><path>activesupport/lib/active_support/cache/mem_cache_store.rb <ide> begin <ide> require 'memcache' <ide> rescue LoadError => e <del> $stderr.puts "You don't have memcache installed in your application. Please add it to your Gemfile and run bundle install" <add> $stderr.puts "You don't have memcache-client installed in your application. Please add it to your Gemfile and run bundle install" <ide> raise e <ide> end <ide> require 'digest/md5'
1