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
use the full path to the workflow being edited
3e917f1c02c4654a135c9a740ee264b766bbc58a
<ide><path>scripts/ci/runners/sync_authors.py <ide> # <ide> # This script should replace the contents of the array with a new list of <ide> # identically formatted names, such that changes to the source of truth: <del> <ide> AUTHORS = 'https://raw.githubusercontent.com/apache/airflow-ci-infra/main/authors.toml' <ide> <del># end up being reflected in the ci.yml. <add># ...end up being reflected in the ci.yml: <add>WORKFLOW = '.github/workflows/ci.yml' <ide> <ide> <ide> req = requests.get(AUTHORS) <ide> <ide> authors = authors[:-2] <ide> <del>with open('ci.yml') as handle: <del> <add>with open(WORKFLOW) as handle: <ide> new_ci = re.sub( <ide> r''' <ide> ^ <ide> flags=re.DOTALL | re.VERBOSE, <ide> ) <ide> <del>with open('ci.yml', 'w') as handle: <add>with open(WORKFLOW, 'w') as handle: <ide> handle.write(new_ci)
1
Javascript
Javascript
use const instead of var
98dfcf57ec0e44390f250829fe2a4ca24fedf405
<ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> }; <ide> } <ide> <del> var LINE_CAP_STYLES = [ "butt", "round", "square" ]; <del> var LINE_JOIN_STYLES = [ "miter", "round", "bevel" ]; <del> var NORMAL_CLIP = {}; <del> var EO_CLIP = {}; <add> const LINE_CAP_STYLES = [ "butt", "round", "square" ]; <add> const LINE_JOIN_STYLES = [ "miter", "round", "bevel" ]; <add> const NORMAL_CLIP = {}; <add> const EO_CLIP = {}; <ide> <ide> constructor.prototype = { <ide> beginDrawing: function(mediaBox) {
1
Python
Python
fix conn issues
8b19d31ab53595014c0791b85663478767ad0f82
<ide><path>libcloud/compute/drivers/openstack.py <ide> def ex_create_subnet(self, name, network, cidr, ip_version=4): <ide> """ <ide> data = {'subnet': {'cidr': cidr, 'network_id': network.id, <ide> 'ip_version': ip_version, 'name': name}} <del> response = self.connection.request(self._subnets_url_prefix, <del> method='POST', data=data).object <add> response = self.network_connection.request( <add> self._subnets_url_prefix, method='POST', data=data).object <ide> return self._to_subnet(response['subnet']) <ide> <ide> def ex_delete_subnet(self, subnet): <ide> def ex_delete_subnet(self, subnet): <ide> <ide> :rtype: ``bool`` <ide> """ <del> resp = self.connection.request('%s/%s' % (self._subnets_url_prefix, <del> subnet.id), <del> method='DELETE') <add> resp = self.network_connection.request('%s/%s' % ( <add> self._subnets_url_prefix, subnet.id), method='DELETE') <ide> return resp.status in (httplib.NO_CONTENT, httplib.ACCEPTED) <ide> <ide> def ex_list_ports(self):
1
Python
Python
add accuracy tests for fp16 umath functions
df168ac05b0bd925f858dec101ddfa1ed29ec973
<ide><path>numpy/core/tests/test_umath_accuracy.py <ide> from numpy.testing._private.utils import _glibc_older_than <ide> from numpy.core._multiarray_umath import __cpu_features__ <ide> <add>UNARY_UFUNCS = [obj for obj in np.core.umath.__dict__.values() if <add> isinstance(obj, np.ufunc)] <add>UNARY_OBJECT_UFUNCS = [uf for uf in UNARY_UFUNCS if "O->O" in uf.types] <add>UNARY_OBJECT_UFUNCS.remove(getattr(np, 'invert')) <add> <ide> IS_AVX = __cpu_features__.get('AVX512F', False) or \ <ide> (__cpu_features__.get('FMA3', False) and __cpu_features__.get('AVX2', False)) <ide> # only run on linux with AVX, also avoid old glibc (numpy/numpy#20448). <ide> def test_validate_transcendentals(self): <ide> outval = outval[perm] <ide> maxulperr = data_subset['ulperr'].max() <ide> assert_array_max_ulp(npfunc(inval), outval, maxulperr) <add> <add> @pytest.mark.parametrize("ufunc", UNARY_OBJECT_UFUNCS) <add> def test_validate_fp16_transcendentals(self, ufunc): <add> with np.errstate(all='ignore'): <add> arr = np.arange(65536, dtype=np.int16) <add> datafp16 = np.frombuffer(arr.tobytes(), dtype=np.float16) <add> datafp32 = datafp16.astype(np.float32) <add> assert_array_max_ulp(ufunc(datafp16), ufunc(datafp32), <add> maxulp=1, dtype=np.float16)
1
Javascript
Javascript
use host header as effective servername
b0c0111b04201bf99fde0fe0616b9fdf1f33655d
<ide><path>lib/http.js <ide> Agent.prototype.addRequest = function(req, host, port, localAddress) { <ide> } <ide> if (this.sockets[name].length < this.maxSockets) { <ide> // If we are under maxSockets create a new one. <del> req.onSocket(this.createSocket(name, host, port, localAddress)); <add> req.onSocket(this.createSocket(name, host, port, localAddress, req)); <ide> } else { <ide> // We are over limit so we'll add it to the queue. <ide> if (!this.requests[name]) { <ide> Agent.prototype.addRequest = function(req, host, port, localAddress) { <ide> this.requests[name].push(req); <ide> } <ide> }; <del>Agent.prototype.createSocket = function(name, host, port, localAddress) { <add>Agent.prototype.createSocket = function(name, host, port, localAddress, req) { <ide> var self = this; <ide> var options = util._extend({}, self.options); <ide> options.port = port; <ide> options.host = host; <ide> options.localAddress = localAddress; <add> <add> options.servername = host; <add> if (req) { <add> var hostHeader = req.getHeader('host'); <add> if (hostHeader) { <add> options.servername = hostHeader.replace(/:.*$/, ''); <add> } <add> } <add> <ide> var s = self.createConnection(options); <ide> if (!self.sockets[name]) { <ide> self.sockets[name] = []; <ide> Agent.prototype.removeSocket = function(s, name, host, port, localAddress) { <ide> } <ide> } <ide> if (this.requests[name] && this.requests[name].length) { <add> var req = this.requests[name][0]; <ide> // If we have pending requests and a socket gets closed a new one <del> this.createSocket(name, host, port, localAddress).emit('free'); <add> this.createSocket(name, host, port, localAddress, req).emit('free'); <ide> } <ide> }; <ide> <ide><path>test/simple/test-https-strict.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>if (!process.versions.openssl) { <add> console.error('Skipping because node compiled without OpenSSL.'); <add> process.exit(0); <add>} <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>var fs = require('fs'); <add>var path = require('path'); <add>var https = require('https'); <add> <add>function file(fname) { <add> return path.resolve(common.fixturesDir, 'keys', fname); <add>} <add> <add>function read(fname) { <add> return fs.readFileSync(file(fname)); <add>} <add> <add>// key1 is signed by ca1. <add>var key1 = read('agent1-key.pem'); <add>var cert1 = read('agent1-cert.pem'); <add> <add>// key2 has a self signed cert <add>var key2 = read('agent2-key.pem'); <add>var cert2 = read('agent2-cert.pem'); <add> <add>// key3 is signed by ca2. <add>var key3 = read('agent3-key.pem'); <add>var cert3 = read('agent3-cert.pem'); <add> <add>var ca1 = read('ca1-cert.pem'); <add>var ca2 = read('ca2-cert.pem'); <add> <add>// different agents to use different CA lists. <add>// this api is beyond bad. <add>var agent0 = new https.Agent(); <add>var agent1 = new https.Agent({ ca: [ca1] }); <add>var agent2 = new https.Agent({ ca: [ca2] }); <add>var agent3 = new https.Agent({ ca: [ca1, ca2] }); <add> <add>var options1 = { <add> key: key1, <add> cert: cert1 <add>}; <add> <add>var options2 = { <add> key: key2, <add> cert: cert2 <add>}; <add> <add>var options3 = { <add> key: key3, <add> cert: cert3 <add>}; <add> <add>var server1 = server(options1); <add>var server2 = server(options2); <add>var server3 = server(options3); <add> <add>var listenWait = 0; <add> <add>var port = common.PORT; <add>var port1 = port++; <add>var port2 = port++; <add>var port3 = port++; <add>server1.listen(port1, listening()); <add>server2.listen(port2, listening()); <add>server3.listen(port3, listening()); <add> <add>var responseErrors = {}; <add>var expectResponseCount = 0; <add>var responseCount = 0; <add>var pending = 0; <add> <add> <add> <add>function server(options, port) { <add> var s = https.createServer(options, handler); <add> s.requests = []; <add> s.expectCount = 0; <add> return s; <add>} <add> <add>function handler(req, res) { <add> this.requests.push(req.url); <add> res.statusCode = 200; <add> res.setHeader('foo', 'bar'); <add> res.end('hello, world\n'); <add>} <add> <add>function listening() { <add> listenWait++; <add> return function() { <add> listenWait--; <add> if (listenWait === 0) { <add> allListening(); <add> } <add> } <add>} <add> <add>function makeReq(path, port, error, host, ca) { <add> pending++; <add> var options = { <add> port: port, <add> path: path, <add> ca: ca <add> }; <add> var whichCa = 0; <add> if (!ca) { <add> options.agent = agent0; <add> } else { <add> if (!Array.isArray(ca)) ca = [ca]; <add> if (-1 !== ca.indexOf(ca1) && -1 !== ca.indexOf(ca2)) { <add> options.agent = agent3; <add> } else if (-1 !== ca.indexOf(ca1)) { <add> options.agent = agent1; <add> } else if (-1 !== ca.indexOf(ca2)) { <add> options.agent = agent2; <add> } else { <add> options.agent = agent0; <add> } <add> } <add> <add> if (host) { <add> options.headers = { host: host } <add> } <add> var req = https.get(options); <add> expectResponseCount++; <add> var server = port === port1 ? server1 <add> : port === port2 ? server2 <add> : port === port3 ? server3 <add> : null; <add> <add> if (!server) throw new Error('invalid port: '+port); <add> server.expectCount++; <add> <add> req.on('response', function(res) { <add> responseCount++; <add> assert.equal(res.connection.authorizationError, error); <add> responseErrors[path] = res.connection.authorizationError; <add> pending--; <add> if (pending === 0) { <add> server1.close(); <add> server2.close(); <add> server3.close(); <add> } <add> }) <add>} <add> <add>function allListening() { <add> // ok, ready to start the tests! <add> <add> // server1: host 'agent1', signed by ca1 <add> makeReq('/inv1', port1, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); <add> makeReq('/inv1-ca1', port1, <add> 'Hostname/IP doesn\'t match certificate\'s altnames', <add> null, ca1); <add> makeReq('/inv1-ca1ca2', port1, <add> 'Hostname/IP doesn\'t match certificate\'s altnames', <add> null, [ca1, ca2]); <add> makeReq('/val1-ca1', port1, null, 'agent1', ca1); <add> makeReq('/val1-ca1ca2', port1, null, 'agent1', [ca1, ca2]); <add> makeReq('/inv1-ca2', port1, <add> 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca2); <add> <add> // server2: self-signed, host = 'agent2' <add> // doesn't matter that thename matches, all of these will error. <add> makeReq('/inv2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT'); <add> makeReq('/inv2-ca1', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', <add> 'agent2', ca1); <add> makeReq('/inv2-ca1ca2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', <add> 'agent2', [ca1, ca2]); <add> <add> // server3: host 'agent3', signed by ca2 <add> makeReq('/inv3', port3, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); <add> makeReq('/inv3-ca2', port3, <add> 'Hostname/IP doesn\'t match certificate\'s altnames', <add> null, ca2); <add> makeReq('/inv3-ca1ca2', port3, <add> 'Hostname/IP doesn\'t match certificate\'s altnames', <add> null, [ca1, ca2]); <add> makeReq('/val3-ca2', port3, null, 'agent3', ca2); <add> makeReq('/val3-ca1ca2', port3, null, 'agent3', [ca1, ca2]); <add> makeReq('/inv3-ca1', port3, <add> 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca1); <add> <add>} <add> <add>process.on('exit', function() { <add> console.error(responseErrors); <add> assert.equal(server1.requests.length, server1.expectCount); <add> assert.equal(server2.requests.length, server2.expectCount); <add> assert.equal(server3.requests.length, server3.expectCount); <add> assert.equal(responseCount, expectResponseCount); <add>});
2
PHP
PHP
remove variable
e8dc4057c48bb2b2b7607cb4cf2b84a5e2c64db5
<ide><path>src/Illuminate/Support/Collection.php <ide> public function median($key = null) <ide> */ <ide> public function mode($key = null) <ide> { <del> $count = $this->count(); <del> <del> if ($count == 0) { <add> if ($this->count() == 0) { <ide> return; <ide> } <ide>
1
Text
Text
fix maintainer link
9f58edbdd5b104cff885ce4724f984c534a63c36
<ide><path>README.md <ide> This is our PGP key which is valid until May 24, 2017. <ide> ## Who Are You? <ide> Homebrew's lead maintainer is [Mike McQuaid](https://github.com/mikemcquaid). <ide> <del>Homebrew's current maintainers are [Misty De Meo](https://github.com/mistydemeo), [Andrew Janke](https://github.com/apjanke), [Xu Cheng](https://github.com/xu-cheng), [Tomasz Pajor](https://github.com/nijikon), [Baptiste Fontaine](https://github.com/bfontaine), [Zhiming Wang](https://github.com/zmwangx), [Brett Koonce](https://github.com/asparagui), [ilovezfs](https://github.com/ilovezfs), [Martin Afanasjew](https://github.com/UniqMartin), [Uladzislau Shablinski](https://github.com/orgs/Homebrew/people/vladshablinsky), [Dominyk Tiller](https://github.com/DomT4), [Tim Smith](https://github.com/tdsmith) and [Alex Dunn](https://github.com/dunn). <add>Homebrew's current maintainers are [Misty De Meo](https://github.com/mistydemeo), [Andrew Janke](https://github.com/apjanke), [Xu Cheng](https://github.com/xu-cheng), [Tomasz Pajor](https://github.com/nijikon), [Baptiste Fontaine](https://github.com/bfontaine), [Zhiming Wang](https://github.com/zmwangx), [Brett Koonce](https://github.com/asparagui), [ilovezfs](https://github.com/ilovezfs), [Martin Afanasjew](https://github.com/UniqMartin), [Uladzislau Shablinski](https://github.com/vladshablinsky), [Dominyk Tiller](https://github.com/DomT4), [Tim Smith](https://github.com/tdsmith) and [Alex Dunn](https://github.com/dunn). <ide> <ide> Former maintainers with significant contributions include [Jack Nagel](https://github.com/jacknagel), [Adam Vandenberg](https://github.com/adamv) and Homebrew's creator: [Max Howell](https://github.com/mxcl). <ide>
1
Text
Text
remove to_s example
30769669e388104626bfc9bd8e9680c4fcee25cc
<ide><path>guides/source/engines.md <ide> above the "Title" output inside `app/views/blorgh/articles/show.html.erb`: <ide> ```html+erb <ide> <p> <ide> <b>Author:</b> <del> <%= @article.author %> <add> <%= @article.author.name %> <ide> </p> <ide> ``` <ide> <del>By outputting `@article.author` using the `<%=` tag, the `to_s` method will be <del>called on the object. By default, this will look quite ugly: <del> <del>``` <del>#<User:0x00000100ccb3b0> <del>``` <del> <del>This is undesirable. It would be much better to have the user's name there. To <del>do this, add a `to_s` method to the `User` class within the application: <del> <del>```ruby <del>def to_s <del> name <del>end <del>``` <del> <del>Now instead of the ugly Ruby object output, the author's name will be displayed. <del> <ide> #### Using a Controller Provided by the Application <ide> <ide> Because Rails controllers generally share code for things like authentication
1
Text
Text
translate tip-15 to korean
23a5a8907726e9d0718ebde5db3ca82a645888ad
<ide><path>docs/tips/15-expose-component-functions.ko-KR.md <add>--- <add>id: expose-component-functions-ko-KR <add>title: ์ปดํฌ๋„ŒํŠธ ํ•จ์ˆ˜ ๋“œ๋Ÿฌ๋‚ด๊ธฐ <add>layout: tips <add>permalink: expose-component-functions-ko-KR.html <add>prev: communicate-between-components-ko-KR.html <add>next: references-to-components-ko-KR.html <add>--- <add> <add>[์ปดํฌ๋„ŒํŠธ๊ฐ„์˜ ํ†ต์‹ ](/react/tips/communicate-between-components-ko-KR.html)์„ ์œ„ํ•œ (์ผ๋ฐ˜์ ์ด์ง€ ์•Š์€) ๋˜๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์ด ์žˆ์Šต๋‹ˆ๋‹ค: ๋‹จ์ˆœํžˆ ๋ถ€๋ชจ์˜ ํ˜ธ์ถœ์„ ์œ„ํ•ด ์ž์‹ ์ปดํฌ๋„ŒํŠธ์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ๋…ธ์ถœํ•˜๋Š” ๊ฒ๋‹ˆ๋‹ค. <add> <add>ํ• ์ผ ๋ชฉ๋ก์„ ์ƒ๊ฐํ•ด๋ณด์ฃ . ์•„์ดํ…œ์„ ํด๋ฆญํ•˜๋ฉด ์ œ๊ฑฐ๋˜๊ณ , ํ•˜๋‚˜๊ฐ€ ๋‚จ์œผ๋ฉด ์• ๋‹ˆ๋ฉ”์ด์…˜ ํšจ๊ณผ๋ฅผ ์ค๋‹ˆ๋‹ค: <add> <add>```js <add>var Todo = React.createClass({ <add> render: function() { <add> return <div onClick={this.props.onClick}>{this.props.title}</div>; <add> }, <add> <add> //์ด ์ปดํฌ๋„ŒํŠธ๋Š” `ref` ์–ดํŠธ๋ฆฌ๋ทฐํŠธ๋ฅผ ํ†ตํ•ด ๋ถ€๋ชจ์—๊ฒŒ ๋‹ค๋ค„์งˆ ๊ฒƒ์ž…๋‹ˆ๋‹ค <add> animate: function() { <add> console.log('%s์ด ์• ๋‹ˆ๋ฉ”์ดํŒ…ํ•˜๋Š”๊ฒƒ์ฒ˜๋Ÿผ ์†์ž…๋‹ˆ๋‹ค', this.props.title); <add> } <add>}); <add> <add>var Todos = React.createClass({ <add> getInitialState: function() { <add> return {items: ['์‚ฌ๊ณผ', '๋ฐ”๋‚˜๋‚˜', 'ํฌ๋žœ๋ฒ ๋ฆฌ']}; <add> }, <add> <add> handleClick: function(index) { <add> var items = this.state.items.filter(function(item, i) { <add> return index !== i; <add> }); <add> this.setState({items: items}, function() { <add> if (items.length === 1) { <add> this.refs.item0.animate(); <add> } <add> }.bind(this)); <add> }, <add> <add> render: function() { <add> return ( <add> <div> <add> {this.state.items.map(function(item, i) { <add> var boundClick = this.handleClick.bind(this, i); <add> return ( <add> <Todo onClick={boundClick} key={i} title={item} ref={'item' + i} /> <add> ); <add> }, this)} <add> </div> <add> ); <add> } <add>}); <add> <add>React.render(<Todos />, mountNode); <add>``` <add> <add>๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์œผ๋กœ๋Š”, `isLastUnfinishedItem` prop์„ `todo`์— ๋„˜๊ธฐ๋Š” ๋ฐฉ์‹์œผ๋กœ ์›ํ•˜๋Š” ๋ฐ”๋ฅผ ์ด๋ฃฐ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. `componentDidUpdate`์—์„œ prop์„ ํ™•์ธํ•˜๊ณ  ์Šค์Šค๋กœ ์• ๋‹ˆ๋ฉ”์ด์…˜ ํšจ๊ณผ๋ฅผ ์ฃผ๋Š”๊ฒ๋‹ˆ๋‹ค; ํ•˜์ง€๋งŒ ์• ๋‹ˆ๋ฉ”์ด์…˜ ์ œ์–ด๋ฅผ ์œ„ํ•ด ๋‹ค๋ฅธ prop๋“ค์„ ๋„˜๊ธฐ๊ฒŒ ๋˜๋ฉด ์ด๋Š” ๊ธˆ์ƒˆ ๋‚œ์žกํ•ด์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
1
PHP
PHP
remove comment bloat
d197a97aac3637d90c5afaefc0f8b44553272faa
<ide><path>system/arr.php <ide> class Arr { <ide> * also be accessed using JavaScript "dot" style notation. Retrieving items nested <ide> * in multiple arrays is also supported. <ide> * <del> * <code> <del> * // Returns "taylor" <del> * $item = Arr::get(array('name' => 'taylor'), 'name', $default); <del> * <del> * // Returns "taylor" <del> * $item = Arr::get(array('name' => array('is' => 'taylor')), 'name.is'); <del> * </code> <del> * <ide> * @param array $array <ide> * @param string $key <ide> * @param mixed $default <ide><path>system/asset.php <ide> class Asset { <ide> * Containers provide a convenient method of grouping assets while maintaining <ide> * expressive code and a clean API. <ide> * <del> * <code> <del> * // Get the default asset container <del> * $container = Asset::container(); <del> * <del> * // Get the "footer" asset contanier <del> * $container = Asset::container('footer'); <del> * <del> * // Add an asset to the "footer" container <del> * Asset::container('footer')->add('jquery', 'js/jquery.js'); <del> * </code> <del> * <ide> * @param string $container <ide> * @return Asset_Container <ide> */ <ide> public static function container($container = 'default') <ide> <ide> /** <ide> * Magic Method for calling methods on the default Asset container. <del> * <del> * <code> <del> * // Add jQuery to the default container <del> * Asset::script('jquery', 'js/jquery.js'); <del> * <del> * // Equivalent call using the container method <del> * Asset::container()->script('jquery', 'js/jquery.js'); <del> * </code> <ide> */ <ide> public static function __callStatic($method, $parameters) <ide> { <ide> public function __construct($name) <ide> * asset being registered (CSS or JavaScript). If you are using a non-standard <ide> * extension, you may use the style or script methods to register assets. <ide> * <del> * <code> <del> * // Register a jQuery asset <del> * Asset::add('jquery', 'js/jquery.js'); <del> * </code> <del> * <ide> * You may also specify asset dependencies. This will instruct the class to <ide> * only link to the registered asset after its dependencies have been linked. <ide> * For example, you may wish to make jQuery UI dependent on jQuery. <ide> * <del> * <code> <del> * // Register jQuery UI as dependent on jQuery <del> * Asset::add('jquery-ui', 'js/jquery-ui.js', 'jquery'); <del> * <del> * // Register jQuery UI with multiple dependencies <del> * Asset::add('jquery-ui', 'js/jquery-ui.js', array('jquery', 'fader')); <del> * </code> <del> * <ide> * @param string $name <ide> * @param string $source <ide> * @param array $dependencies <ide> private function get_group($group) <ide> /** <ide> * Get the link to a single registered CSS asset. <ide> * <del> * <code> <del> * echo $container->get_style('common'); <del> * </code> <del> * <ide> * @param string $name <ide> * @return string <ide> */ <ide> public function get_style($name) <ide> /** <ide> * Get the link to a single registered JavaScript asset. <ide> * <del> * <code> <del> * echo $container->get_script('jquery'); <del> * </code> <del> * <ide> * @param string $name <ide> * @return string <ide> */ <ide><path>system/auth.php <ide> class Auth { <ide> /** <ide> * Determine if the current user of the application is authenticated. <ide> * <del> * <code> <del> * if (Auth::check()) <del> * { <del> * // The user is logged in... <del> * } <del> * </code> <del> * <ide> * @return bool <ide> * @see login <ide> */ <ide> public static function check() <ide> * the "by_id" closure in the authentication configuration file. The result <ide> * of the closure will be cached and returned. <ide> * <del> * <code> <del> * $email = Auth::user()->email; <del> * </code> <del> * <ide> * @return object <ide> * @see $user <ide> */ <ide> public static function user() <ide> * The password passed to the method should be plain text, as it will be hashed <ide> * by the Hash class when authenticating. <ide> * <del> * <code> <del> * if (Auth::login('test@gmail.com', 'secret')) <del> * { <del> * // The credentials are valid... <del> * } <del> * </code> <del> * <ide> * @param string $username <ide> * @param string $password <ide> * @return bool <ide><path>system/cache.php <ide> public static function driver($driver = null) <ide> /** <ide> * Get an item from the cache. <ide> * <del> * If the cached item doesn't exist, the specified default value will be returned. <del> * <del> * <code> <del> * // Get the "name" item from the cache <del> * $name = Cache::get('name'); <del> * <del> * // Get the "name" item, but return "Fred" if it doesn't exist <del> * $name = Cache::get('name', 'Fred'); <del> * </code> <del> * <del> * The driver may also be specified: <del> * <del> * <code> <del> * $name = Cache::get('name', null, 'memcached'); <del> * </code> <del> * <ide> * @param string $key <ide> * @param mixed $default <ide> * @param string $driver <ide> public static function get($key, $default = null, $driver = null) <ide> * Get an item from the cache. If the item doesn't exist in the cache, store <ide> * the default value in the cache and return it. <ide> * <del> * <code> <del> * // Get the name item. If it doesn't exist, store "Fred" for 30 minutes <del> * $name = Cache::remember('name', 'Fred', 30); <del> * <del> * // Closures may also be used as default values <del> * $name = Cache::remember('votes', function() {return Vote::count();}, 30); <del> * </code> <del> * <ide> * @param string $key <ide> * @param mixed $default <ide> * @param int $minutes <ide><path>system/config.php <ide> public static function has($key) <ide> * If the name of a configuration file is passed without specifying an item, the <ide> * entire configuration array will be returned. <ide> * <del> * <code> <del> * // Get the application timezone <del> * $timezone = Config::get('application.timezone'); <del> * <del> * // Get the application configuration array <del> * $application = Config::get('application'); <del> * </code> <del> * <ide> * @param string $key <ide> * @param string $default <ide> * @return array <ide> public static function get($key, $default = null) <ide> * <ide> * If a configuration item is not specified, the entire configuration array will be set. <ide> * <del> * <code> <del> * // Set the application timezone <del> * Config::set('application.timezone', 'America/Chicago'); <del> * <del> * // Set the application configuration array <del> * Config::set('application', array()); <del> * </code> <del> * <ide> * @param string $key <ide> * @param mixed $value <ide> * @return void
5
Python
Python
add dns module to setup.py
6d724b3cf283289d4c188778051399863529fe88
<ide><path>setup.py <ide> def run(self): <ide> 'libcloud.drivers', <ide> 'libcloud.loadbalancer', <ide> 'libcloud.loadbalancer.drivers', <add> 'libcloud.dns', <add> 'libcloud.dns.drivers' <ide> ], <ide> package_dir={ <ide> 'libcloud': 'libcloud',
1
Text
Text
describe labelling process for backports
b440e8e4e480e71d43eee3f1fadcf4e07886296b
<ide><path>doc/onboarding-extras.md <ide> Please use these when possible / appropriate <ide> git checkout $(git show -s --pretty='%T' $(git show-ref -d $(git describe --abbrev=0) | tail -n1 | awk '{print $1}')) -- test; make -j4 test <ide> ``` <ide> <add>### LTS/Version labels <add> <add>We use labels to keep track of which branches a commit should land on: <add> <add>* `dont-land-on-v?.x` <add> * For changes that do not apply to a certain release line <add> * Also used when the work of backporting a change outweighs the benefits <add>* `land-on-v?.x` <add> * Used by releasers to mark a PR as scheduled for inclusion in an LTS release <add> * Applied to the original PR for clean cherry-picks, to the backport PR otherwise <add>* `backport-requested-v?.x` <add> * Used to indicate that a PR needs a manual backport to a branch in order to land the changes on that branch <add> * Typically applied by a releaser when the PR does not apply cleanly or it breaks the tests after applying <add> * Will be replaced by either `dont-land-on-v?.x` or `backported-to-v?.x` <add>* `backported-to-v?.x` <add> * Applied to PRs for which a backport PR has been merged <add>* `lts-watch-v?.x` <add> * Applied to PRs which the LTS working group should consider including in a LTS release <add> * Does not indicate that any specific action will be taken, but can be effective as messaging to non-collaborators <add>* `lts-agenda` <add> * For things that need discussion by the LTS working group <add> * (for example semver-minor changes that need or should go into an LTS release) <add>* `v?.x` <add> * Automatically applied to changes that do not target `master` but rather the `v?.x-staging` branch <add> <add>Once a release line enters maintenance mode, the corresponding labels do not <add>need to be attached anymore, as only important bugfixes will be included. <ide> <ide> ### Other Labels <ide> <ide> Please use these when possible / appropriate <ide> * Architecture labels <ide> * `arm`, `mips`, `s390`, `ppc` <ide> * No x86{_64}, since that is the implied default <del>* `lts-agenda`, `lts-watch-v*` <del> * tag things that should be discussed to go into LTS or should go into a specific LTS branch <del> * (usually only semver-patch things) <del> * will come more naturally over time <ide> <ide> <ide> ## Updating Node.js from Upstream
1
Python
Python
add minmaxnorm constraint
99ee2fb09ab33f72dca627dc586ac3884ded337a
<ide><path>keras/constraints.py <ide> def get_config(self): <ide> 'axis': self.axis} <ide> <ide> <add>class MinMaxNorm(Constraint): <add> """MinMaxNorm weight constraint. <add> <add> Constrains the weights incident to each hidden unit <add> to have the norm between a lower bound and an upper bound. <add> <add> # Arguments <add> low: the minimum norm for the incoming weights. <add> high: the maximum norm for the incoming weights. <add> rate: rate for enforcing the constraint: weights will be <add> rescaled to yield (1 - rate) * norm + rate * norm.clip(low, high). <add> Effectively, this means that rate=1.0 stands for strict <add> enforcement of the constraint, while rate<1.0 means that <add> weights will be rescaled at each step to slowly move <add> towards a value inside the desired interval. <add> axis: integer, axis along which to calculate weight norms. <add> For instance, in a `Dense` layer the weight matrix <add> has shape `(input_dim, output_dim)`, <add> set `axis` to `0` to constrain each weight vector <add> of length `(input_dim,)`. <add> In a `Convolution2D` layer with `dim_ordering="tf"`, <add> the weight tensor has shape <add> `(rows, cols, input_depth, output_depth)`, <add> set `axis` to `[0, 1, 2]` <add> to constrain the weights of each filter tensor of size <add> `(rows, cols, input_depth)`. <add> """ <add> def __init__(self, low=0.0, high=1.0, rate=1.0, axis=0): <add> self.low = low <add> self.high = high <add> self.rate = rate <add> self.axis = axis <add> <add> def __call__(self, p): <add> norms = K.sqrt(K.sum(K.square(p), axis=self.axis, keepdims=True)) <add> desired = self.rate * K.clip(norms, self.low, self.high) + (1 - self.rate) * norms <add> p *= (desired / (K.epsilon() + norms)) <add> return p <add> <add> def get_config(self): <add> return {'name': self.__class__.__name__, <add> 'low': self.low, <add> 'high': self.high, <add> 'rate': self.rate, <add> 'axis': self.axis} <add> <add> <ide> # Aliases. <ide> <ide> maxnorm = MaxNorm
1
Python
Python
add example for custom intent parser
9dfca0f2f8fb53314dfe874fd327b07239669438
<ide><path>examples/training/train_intent_parser.py <add>#!/usr/bin/env python <add># coding: utf-8 <add>"""Using the parser to recognise your own semantics spaCy's parser component <add>can be used to trained to predict any type of tree structure over your input <add>text. You can also predict trees over whole documents or chat logs, with <add>connections between the sentence-roots used to annotate discourse structure. <add> <add>In this example, we'll build a message parser for a common "chat intent": <add>finding local businesses. Our message semantics will have the following types <add>of relations: INTENT, PLACE, QUALITY, ATTRIBUTE, TIME, LOCATION. For example: <add> <add>"show me the best hotel in berlin" <add>('show', 'ROOT', 'show') <add>('best', 'QUALITY', 'hotel') --> hotel with QUALITY best <add>('hotel', 'PLACE', 'show') --> show PLACE hotel <add>('berlin', 'LOCATION', 'hotel') --> hotel with LOCATION berlin <add>""" <add>from __future__ import unicode_literals, print_function <add> <add>import plac <add>import random <add>import spacy <add>from spacy.gold import GoldParse <add>from spacy.tokens import Doc <add>from pathlib import Path <add> <add> <add># training data: words, head and dependency labels <add># for no relation, we simply chose an arbitrary dependency label, e.g. '-' <add>TRAIN_DATA = [ <add> ( <add> ['find', 'a', 'cafe', 'with', 'great', 'wifi'], <add> [0, 2, 0, 5, 5, 2], # index of token head <add> ['ROOT', '-', 'PLACE', '-', 'QUALITY', 'ATTRIBUTE'] <add> ), <add> ( <add> ['find', 'a', 'hotel', 'near', 'the', 'beach'], <add> [0, 2, 0, 5, 5, 2], <add> ['ROOT', '-', 'PLACE', 'QUALITY', '-', 'ATTRIBUTE'] <add> ), <add> ( <add> ['find', 'me', 'the', 'closest', 'gym', 'that', "'s", 'open', 'late'], <add> [0, 0, 4, 4, 0, 6, 4, 6, 6], <add> ['ROOT', '-', '-', 'QUALITY', 'PLACE', '-', '-', 'ATTRIBUTE', 'TIME'] <add> ), <add> ( <add> ['show', 'me', 'the', 'cheapest', 'store', 'that', 'sells', 'flowers'], <add> [0, 0, 4, 4, 0, 4, 4, 4], # attach "flowers" to store! <add> ['ROOT', '-', '-', 'QUALITY', 'PLACE', '-', '-', 'PRODUCT'] <add> ), <add> ( <add> ['find', 'a', 'nice', 'restaurant', 'in', 'london'], <add> [0, 3, 3, 0, 3, 3], <add> ['ROOT', '-', 'QUALITY', 'PLACE', '-', 'LOCATION'] <add> ), <add> ( <add> ['show', 'me', 'the', 'coolest', 'hostel', 'in', 'berlin'], <add> [0, 0, 4, 4, 0, 4, 4], <add> ['ROOT', '-', '-', 'QUALITY', 'PLACE', '-', 'LOCATION'] <add> ), <add> ( <add> ['find', 'a', 'good', 'italian', 'restaurant', 'near', 'work'], <add> [0, 4, 4, 4, 0, 4, 5], <add> ['ROOT', '-', 'QUALITY', 'ATTRIBUTE', 'PLACE', 'ATTRIBUTE', 'LOCATION'] <add> ) <add>] <add> <add> <add>@plac.annotations( <add> model=("Model name. Defaults to blank 'en' model.", "option", "m", str), <add> output_dir=("Optional output directory", "option", "o", Path), <add> n_iter=("Number of training iterations", "option", "n", int)) <add>def main(model=None, output_dir=None, n_iter=100): <add> """Load the model, set up the pipeline and train the parser.""" <add> if model is not None: <add> nlp = spacy.load(model) # load existing spaCy model <add> print("Loaded model '%s'" % model) <add> else: <add> nlp = spacy.blank('en') # create blank Language class <add> print("Created blank 'en' model") <add> <add> # add the parser to the pipeline if it doesn't exist <add> # nlp.create_pipe works for built-ins that are registered with spaCy <add> if 'parser' not in nlp.pipe_names: <add> parser = nlp.create_pipe('parser') <add> nlp.add_pipe(parser, first=True) <add> # otherwise, get it, so we can add labels to it <add> else: <add> parser = nlp.get_pipe('parser') <add> <add> for _, _, deps in TRAIN_DATA: <add> for dep in deps: <add> parser.add_label(dep) <add> <add> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'parser'] <add> with nlp.disable_pipes(*other_pipes): # only train parser <add> optimizer = nlp.begin_training(lambda: []) <add> for itn in range(n_iter): <add> random.shuffle(TRAIN_DATA) <add> losses = {} <add> for words, heads, deps in TRAIN_DATA: <add> doc = Doc(nlp.vocab, words=words) <add> gold = GoldParse(doc, heads=heads, deps=deps) <add> nlp.update([doc], [gold], sgd=optimizer, losses=losses) <add> print(losses) <add> <add> # test the trained model <add> test_model(nlp) <add> <add> # save model to output directory <add> if output_dir is not None: <add> output_dir = Path(output_dir) <add> if not output_dir.exists(): <add> output_dir.mkdir() <add> nlp.to_disk(output_dir) <add> print("Saved model to", output_dir) <add> <add> # test the saved model <add> print("Loading from", output_dir) <add> nlp2 = spacy.load(output_dir) <add> test_model(nlp2) <add> <add> <add>def test_model(nlp): <add> texts = ["find a hotel with good wifi", <add> "find me the cheapest gym near work", <add> "show me the best hotel in berlin"] <add> docs = nlp.pipe(texts) <add> for doc in docs: <add> print(doc.text) <add> print([(t.text, t.dep_, t.head.text) for t in doc if t.dep_ != '-']) <add> <add> <add>if __name__ == '__main__': <add> plac.call(main) <add> <add> # Expected output: <add> # find a hotel with good wifi <add> # [ <add> # ('find', 'ROOT', 'find'), <add> # ('hotel', 'PLACE', 'find'), <add> # ('good', 'QUALITY', 'wifi'), <add> # ('wifi', 'ATTRIBUTE', 'hotel') <add> # ] <add> # find me the cheapest gym near work <add> # [ <add> # ('find', 'ROOT', 'find'), <add> # ('cheapest', 'QUALITY', 'gym'), <add> # ('gym', 'PLACE', 'find') <add> # ] <add> # show me the best hotel in berlin <add> # [ <add> # ('show', 'ROOT', 'show'), <add> # ('best', 'QUALITY', 'hotel'), <add> # ('hotel', 'PLACE', 'show'), <add> # ('berlin', 'LOCATION', 'hotel') <add> # ]
1
Javascript
Javascript
add deprecation warning to listview
e90f5fa2630f8a89e15fa57c70ada83e75a20642
<ide><path>Libraries/react-native/react-native-implementation.js <ide> <ide> const invariant = require('fbjs/lib/invariant'); <ide> <add>let showedListViewDeprecation = false; <add> <ide> // Export React, plus some native additions. <ide> const ReactNative = { <ide> // Components <ide> const ReactNative = { <ide> return require('KeyboardAvoidingView'); <ide> }, <ide> get ListView() { <add> if (!showedListViewDeprecation) { <add> console.warn( <add> 'ListView is deprecated and will be removed in a future release. ' + <add> 'See https://fb.me/nolistview for more information', <add> ); <add> <add> showedListViewDeprecation = true; <add> } <ide> return require('ListView'); <ide> }, <ide> get MaskedViewIOS() {
1
PHP
PHP
add scope to email logging
f1b815a9bbc9d58e09da9bab4f2110c643baa814
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> public function send($content = null) { <ide> $contents = $this->transportClass()->send($this); <ide> if (!empty($this->_config['log'])) { <ide> $level = LOG_DEBUG; <add> $scope = 'email'; <ide> if ($this->_config['log'] !== true) { <del> $level = $this->_config['log']; <add> if (!is_array($this->_config['log'])) { <add> $this->_config['log'] = array('level' => $this->_config['log']); <add> } <add> $this->_config['log'] = array_merge(compact('level', 'scope'), $this->_config['log']); <add> extract($this->_config['log']); <ide> } <del> CakeLog::write($level, PHP_EOL . $contents['headers'] . PHP_EOL . $contents['message']); <add> CakeLog::write($level, PHP_EOL . $contents['headers'] . PHP_EOL . $contents['message'], $scope); <ide> } <ide> return $contents; <ide> } <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testSendWithLog() { <ide> CakeLog::drop('email'); <ide> } <ide> <add>/** <add> * testSendWithLogAndScope method <add> * <add> * @return void <add> */ <add> public function testSendWithLogAndScope() { <add> CakeLog::config('email', array( <add> 'engine' => 'FileLog', <add> 'path' => TMP, <add> 'types' => array('cake_test_emails'), <add> 'scopes' => array('email') <add> )); <add> CakeLog::drop('default'); <add> $this->CakeEmail->transport('Debug'); <add> $this->CakeEmail->to('me@cakephp.org'); <add> $this->CakeEmail->from('cake@cakephp.org'); <add> $this->CakeEmail->subject('My title'); <add> $this->CakeEmail->config(array('log' => array('level' => 'cake_test_emails', 'scope' => 'email'))); <add> $result = $this->CakeEmail->send("Logging This"); <add> <add> App::uses('File', 'Utility'); <add> $File = new File(TMP . 'cake_test_emails.log'); <add> $log = $File->read(); <add> $this->assertTrue(strpos($log, $result['headers']) !== false); <add> $this->assertTrue(strpos($log, $result['message']) !== false); <add> $File->delete(); <add> CakeLog::drop('email'); <add> } <add> <ide> /** <ide> * testSendRender method <ide> *
2
Python
Python
fix compatibility with tf 0.11
914d976801c5d2323cdc87b902a5342637e86dc7
<ide><path>keras/backend/tensorflow_backend.py <ide> def normalize_batch_in_training(x, gamma, beta, <ide> target_shape.append(1) <ide> else: <ide> target_shape.append(tf.shape(x)[axis]) <del> target_shape = tf.stack(target_shape) <add> target_shape = stack(target_shape) <ide> <ide> broadcast_mean = tf.reshape(mean, target_shape) <ide> broadcast_var = tf.reshape(var, target_shape) <ide> def repeat(x, n): <ide> ''' <ide> assert ndim(x) == 2 <ide> x = tf.expand_dims(x, 1) <del> pattern = tf.stack([1, n, 1]) <add> pattern = stack([1, n, 1]) <ide> return tf.tile(x, pattern) <ide> <ide> <ide> def batch_flatten(x): <ide> '''Turn a n-D tensor into a 2D tensor where <ide> the first dimension is conserved. <ide> ''' <del> x = tf.reshape(x, tf.stack([-1, prod(shape(x)[1:])])) <add> x = tf.reshape(x, stack([-1, prod(shape(x)[1:])])) <ide> return x <ide> <ide> <ide> def spatial_3d_padding(x, padding=(1, 1, 1), dim_ordering='default'): <ide> <ide> <ide> def stack(x): <del> return tf.stack(x) <add> try: <add> return tf.stack(x) <add> except AttributeError: <add> return tf.pack(x) <ide> <ide> <ide> def one_hot(indices, nb_classes): <ide> def rnn(step_function, inputs, initial_states, <ide> successive_states = [] <ide> successive_outputs = [] <ide> <del> input_list = tf.unstack(inputs) <add> input_list = tf.unpack(inputs) <ide> if go_backwards: <ide> input_list.reverse() <ide> <ide> if mask is not None: <del> mask_list = tf.unstack(mask) <add> mask_list = tf.unpack(mask) <ide> if go_backwards: <ide> mask_list.reverse() <ide> <ide> def rnn(step_function, inputs, initial_states, <ide> # it just repeats the mask along its second dimension <ide> # n times. <ide> tiled_mask_t = tf.tile(mask_t, <del> tf.stack([1, tf.shape(output)[1]])) <add> stack([1, tf.shape(output)[1]])) <ide> <ide> if len(successive_outputs) == 0: <ide> prev_output = zeros_like(output) <ide> def rnn(step_function, inputs, initial_states, <ide> for state, new_state in zip(states, new_states): <ide> # (see earlier comment for tile explanation) <ide> tiled_mask_t = tf.tile(mask_t, <del> tf.stack([1, tf.shape(new_state)[1]])) <add> stack([1, tf.shape(new_state)[1]])) <ide> return_states.append(tf.where(tiled_mask_t, <ide> new_state, <ide> state)) <ide> def rnn(step_function, inputs, initial_states, <ide> successive_states.append(states) <ide> last_output = successive_outputs[-1] <ide> new_states = successive_states[-1] <del> outputs = tf.stack(successive_outputs) <add> outputs = stack(successive_outputs) <ide> else: <ide> for input in input_list: <ide> output, states = step_function(input, states + constants) <ide> successive_outputs.append(output) <ide> successive_states.append(states) <ide> last_output = successive_outputs[-1] <ide> new_states = successive_states[-1] <del> outputs = tf.stack(successive_outputs) <add> outputs = stack(successive_outputs) <ide> <ide> else: <ide> if go_backwards: <ide> def _step(time, output_ta_t, *states): <ide> for state, new_state in zip(states, new_states): <ide> new_state.set_shape(state.get_shape()) <ide> tiled_mask_t = tf.tile(mask_t, <del> tf.stack([1, tf.shape(output)[1]])) <add> stack([1, tf.shape(output)[1]])) <ide> output = tf.where(tiled_mask_t, output, states[0]) <ide> new_states = [tf.where(tiled_mask_t, new_states[i], states[i]) for i in range(len(states))] <ide> output_ta_t = output_ta_t.write(time, output) <ide> def random_binomial(shape, p=0.0, dtype=_FLOATX, seed=None): <ide> if seed is None: <ide> seed = np.random.randint(10e6) <ide> return tf.where(tf.random_uniform(shape, dtype=dtype, seed=seed) <= p, <del> tf.ones(shape, dtype=dtype), <del> tf.zeros(shape, dtype=dtype)) <add> tf.ones(shape, dtype=dtype), <add> tf.zeros(shape, dtype=dtype)) <ide> <ide> <ide> # CTC <ide> def ctc_label_dense_to_sparse(labels, label_lengths): <ide> # undocumented feature soon to be made public <ide> from tensorflow.python.ops import functional_ops <ide> label_shape = tf.shape(labels) <del> num_batches_tns = tf.stack([label_shape[0]]) <del> max_num_labels_tns = tf.stack([label_shape[1]]) <add> num_batches_tns = stack([label_shape[0]]) <add> max_num_labels_tns = stack([label_shape[1]]) <ide> <ide> def range_less_than(previous_state, current_input): <ide> return tf.expand_dims(tf.range(label_shape[1]), 0) < tf.fill(max_num_labels_tns, current_input)
1
Go
Go
add check about filter name for containers
8a90e8a19b8108ecdff325fc19dbdf945aa15fad
<ide><path>daemon/list.go <ide> var acceptedVolumeFilterTags = map[string]bool{ <ide> "dangling": true, <ide> } <ide> <add>var acceptedPsFilterTags = map[string]bool{ <add> "ancestor": true, <add> "before": true, <add> "exited": true, <add> "id": true, <add> "isolation": true, <add> "label": true, <add> "name": true, <add> "status": true, <add> "since": true, <add> "volume": true, <add>} <add> <ide> // iterationAction represents possible outcomes happening during the container iteration. <ide> type iterationAction int <ide> <ide> func (daemon *Daemon) reducePsContainer(container *container.Container, ctx *lis <ide> func (daemon *Daemon) foldFilter(config *types.ContainerListOptions) (*listContext, error) { <ide> psFilters := config.Filter <ide> <add> if err := psFilters.Validate(acceptedPsFilterTags); err != nil { <add> return nil, err <add> } <add> <ide> var filtExited []int <add> <ide> err := psFilters.WalkValues("exited", func(value string) error { <ide> code, err := strconv.Atoi(value) <ide> if err != nil { <ide><path>integration-cli/docker_cli_ps_test.go <ide> func assertContainerList(out string, expected []string) bool { <ide> return true <ide> } <ide> <add>func (s *DockerSuite) TestPsListContainersInvalidFilterName(c *check.C) { <add> out, _, err := dockerCmdWithError("ps", "-f", "invalidFilter=test") <add> c.Assert(err, checker.NotNil) <add> c.Assert(out, checker.Contains, "Invalid filter") <add>} <add> <ide> func (s *DockerSuite) TestPsListContainersSize(c *check.C) { <ide> // Problematic on Windows as it doesn't report the size correctly @swernli <ide> testRequires(c, DaemonIsLinux)
2
Python
Python
update modelserializer mappings
313b3d7c3b8dfdb159e3570c3baade827bd6d687
<ide><path>rest_framework/serializers.py <ide> class ModelSerializer(Serializer): <ide> models.SmallIntegerField: IntegerField, <ide> models.TextField: CharField, <ide> models.TimeField: TimeField, <del> models.URLField: URLField <add> models.URLField: URLField, <add> models.GenericIPAddressField: IPAddressField, <ide> # Note: Some version-specific mappings also defined below. <ide> }) <ide> _related_class = PrimaryKeyRelatedField <ide> class Meta: <ide> if hasattr(models, 'UUIDField'): <ide> ModelSerializer._field_mapping[models.UUIDField] = UUIDField <ide> <add># IPAddressField is deprecated in Django <add>if hasattr(models, 'IPAddressField'): <add> ModelSerializer._field_mapping[models.IPAddressField] = IPAddressField <add> <ide> if postgres_fields: <ide> class CharMappingField(DictField): <ide> child = CharField()
1
Text
Text
add readme in chinese
f40ed302df99f73a1059929041325e1d9d5e7f2f
<ide><path>README-zh-CN.md <add><img width="112" alt="screen shot 2016-10-25 at 2 37 27 pm" src="https://cloud.githubusercontent.com/assets/13041/19686250/971bf7f8-9ac0-11e6-975c-188defd82df1.png"> <add> <add>[![NPM version](https://img.shields.io/npm/v/next.svg)](https://www.npmjs.com/package/next) <add>[![Build Status](https://travis-ci.org/zeit/next.js.svg?branch=master)](https://travis-ci.org/zeit/next.js) <add>[![Build status](https://ci.appveyor.com/api/projects/status/gqp5hs71l3ebtx1r/branch/master?svg=true)](https://ci.appveyor.com/project/arunoda/next-js/branch/master) <add>[![Coverage Status](https://coveralls.io/repos/zeit/next.js/badge.svg?branch=master)](https://coveralls.io/r/zeit/next.js?branch=master) <add>[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/next-js) <add> <add>Next.js ๆ˜ฏไธ€ไธช่ฝป้‡็บง็š„ React ๆœๅŠก็ซฏๆธฒๆŸ“ๅบ”็”จๆก†ๆžถใ€‚ <add> <add>**ๅฏ่ฎฟ้—ฎ [nextjs.org/learn](https://nextjs.org/learn) ๅผ€ๅง‹ๅญฆไน  Next.js.** <add> <add>[README in English](README.md) <add> <add>--- <add> <add><!-- START doctoc generated TOC please keep comment here to allow auto update --> <add><!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <add><!-- https://github.com/thlorenz/doctoc --> <add> <add>- [ๆ€Žไนˆไฝฟ็”จ](#how-to-use) <add> - [ๅฎ‰่ฃ…](#setup) <add> - [ไปฃ็ ่‡ชๅŠจๅˆ†ๅ‰ฒ](#automatic-code-splitting) <add> - [CSS](#css) <add> - [ๆ”ฏๆŒๅตŒๅ…ฅๆ ทๅผ](#built-in-css-support) <add> - [ๅ†…ๅตŒๆ ทๅผ](#css-in-js) <add> - [ไฝฟ็”จ CSS / Sass / Less / Stylus files](#importing-css--sass--less--stylus-files) <add> - [้™ๆ€ๆ–‡ไปถๆœๅŠก๏ผˆๅฆ‚ๅ›พๅƒ)](#static-file-serving-eg-images) <add> - [`<head>`](#populating-head) <add> - [่Žทๅ–ๆ•ฐๆฎไปฅๅŠ็ป„ไปถ็”Ÿๅ‘ฝๅ‘จๆœŸ](#fetching-data-and-component-lifecycle) <add> - [่ทฏ็”ฑ](#routing) <add> - [`<Link>` ็”จๆณ•](#with-link) <add> - [URL ๅฏน่ฑก](#with-url-object) <add> - [ๆ›ฟๆข่ทฏ็”ฑ](#replace-instead-of-push-url) <add> - [็ป„ไปถๆ”ฏๆŒ็‚นๅ‡ปไบ‹ไปถ`onClick`](#using-a-component-that-supports-onclick) <add> - [ๆšด้œฒ`href`็ป™ๅญๅ…ƒ็ด ](#forcing-the-link-to-expose-href-to-its-child) <add> - [็ฆๆญขๆปšๅŠจๅˆฐ้กต้ข้กถ้ƒจ](#disabling-the-scroll-changes-to-top-on-page) <add> - [ๅ‘ฝไปคๅผ](#imperatively) <add> - [ๆ‹ฆๆˆชๅ™จ `popstate`](#intercepting-popstate) <add> - [URL ๅฏน่ฑก็”จๆณ•](#with-url-object-1) <add> - [่ทฏ็”ฑไบ‹ไปถ](#router-events) <add> - [ๆต…ๅฑ‚่ทฏ็”ฑ](#shallow-routing) <add> - [้ซ˜้˜ถ็ป„ไปถ](#using-a-higher-order-component) <add> - [้ข„ๅŠ ่ฝฝ้กต้ข](#prefetching-pages) <add> - [`<Link>`็”จๆณ•](#with-link-1) <add> - [ๅ‘ฝไปคๅผ prefetch ๅ†™ๆณ•](#imperatively-1) <add> - [่‡ชๅฎšไน‰ๆœๅŠก็ซฏ่ทฏ็”ฑ](#custom-server-and-routing) <add> - [็ฆๆญขๆ–‡ไปถ่ทฏ็”ฑ](#disabling-file-system-routing) <add> - [ๅŠจๆ€ๅ‰็ผ€](#dynamic-assetprefix) <add> - [ๅŠจๆ€ๅฏผๅ…ฅ](#dynamic-import) <add> - [1. ๅŸบ็ก€ๆ”ฏๆŒ (ๅŒๆ ทๆ”ฏๆŒ SSR)](#1-basic-usage-also-does-ssr) <add> - [2. ่‡ชๅฎšไน‰ๅŠ ่ฝฝ็ป„ไปถ](#2-with-custom-loading-component) <add> - [3. ็ฆๆญขไฝฟ็”จ SSR](#3-with-no-ssr) <add> - [4. ๅŒๆ—ถๅŠ ่ฝฝๅคšไธชๆจกๅ—](#4-with-multiple-modules-at-once) <add> - [่‡ชๅฎšไน‰ `<App>`](#custom-app) <add> - [่‡ชๅฎšไน‰ `<Document>`](#custom-document) <add> - [่‡ชๅฎšไน‰้”™่ฏฏๅค„็†](#custom-error-handling) <add> - [ๆธฒๆŸ“ๅ†…็ฝฎ้”™่ฏฏ้กต้ข](#reusing-the-built-in-error-page) <add> - [่‡ชๅฎšไน‰้…็ฝฎ](#custom-configuration) <add> - [่ฎพ็ฝฎ่‡ชๅฎšไน‰ๆž„ๅปบ็›ฎๅฝ•](#setting-a-custom-build-directory) <add> - [็ฆๆญข etag ็”Ÿๆˆ](#disabling-etag-generation) <add> - [้…็ฝฎ onDemandEntries](#configuring-the-ondemandentries) <add> - [้…็ฝฎ้กต้ขๅŽ็ผ€ๅ่งฃๆžๆ‰ฉๅฑ•](#configuring-extensions-looked-for-when-resolving-pages-in-pages) <add> - [้…็ฝฎๆž„ๅปบ ID](#configuring-the-build-id) <add> - [่‡ชๅฎšไน‰ webpack ้…็ฝฎ](#customizing-webpack-config) <add> - [่‡ชๅฎšไน‰ babel ้…็ฝฎ](#customizing-babel-config) <add> - [ๆšด้œฒ้…็ฝฎๅˆฐๆœๅŠก็ซฏๅ’Œๅฎขๆˆท็ซฏ](#exposing-configuration-to-the-server--client-side) <add> - [ๅฏๅŠจๆœๅŠก้€‰ๆ‹ฉ hostname](#starting-the-server-on-alternative-hostname) <add> - [CDN ๆ”ฏๆŒๅ‰็ผ€](#cdn-support-with-asset-prefix) <add>- [้กน็›ฎ้ƒจ็ฝฒ](#production-deployment) <add>- [ๆต่งˆๅ™จๆ”ฏๆŒ](#browser-support) <add>- [ๅฏผๅ‡บ้™ๆ€้กต้ข](#static-html-export) <add> - [ไฝฟ็”จ](#usage) <add> - [้™ๅˆถ](#limitation) <add>- [ๅคš zone](#multi-zones) <add> - [ๆ€Žไนˆๅฎšไน‰ไธ€ไธช zone](#how-to-define-a-zone) <add> - [ๆ€Žไนˆๅˆๅนถไป–ไปฌ](#how-to-merge-them) <add>- [ๆŠ€ๅทง](#recipes) <add>- [FAQ](#faq) <add>- [่ดก็Œฎ](#contributing) <add>- [ไฝœ่€…](#authors) <add> <add><!-- END doctoc generated TOC please keep comment here to allow auto update --> <add> <add><a id="how-to-use" style="display: none"></a> <add>## ๆ€Žไนˆไฝฟ็”จ <add> <add><a id="setup" style="display: none"></a> <add>### ๅฎ‰่ฃ… <add> <add>ๅฎ‰่ฃ…ๅฎƒ: <add> <add>```bash <add>npm install --save next react react-dom <add>``` <add> <add>ๅฐ†ไธ‹้ข่„šๆœฌๆทปๅŠ ๅˆฐ package.json ไธญ: <add> <add>```json <add>{ <add> "scripts": { <add> "dev": "next", <add> "build": "next build", <add> "start": "next start" <add> } <add>} <add>``` <add> <add>ไธ‹้ข, ๆ–‡ไปถ็ณป็ปŸๆ˜ฏไธป่ฆ็š„ API. ๆฏไธช`.js` ๆ–‡ไปถๅฐ†ๅ˜ๆˆไธ€ไธช่ทฏ็”ฑ๏ผŒ่‡ชๅŠจๅค„็†ๅ’ŒๆธฒๆŸ“ใ€‚ <add> <add>ๆ–ฐๅปบ `./pages/index.js` ๅˆฐไฝ ็š„้กน็›ฎไธญ: <add> <add>```jsx <add>export default () => <div>Welcome to next.js!</div> <add>``` <add> <add>่ฟ่กŒ `npm run dev` ๅ‘ฝไปคๅนถๆ‰“ๅผ€ `http://localhost:3000`ใ€‚ ๅฆ‚ๆžœไฝ ๆƒณไฝฟ็”จๅ…ถไป–็ซฏๅฃ๏ผŒๅฏ่ฟ่กŒ `npm run dev -- -p <่ฎพ็ฝฎ็ซฏๅฃๅท>`. <add> <add> <add>็›ฎๅ‰ไธบๆญขๆˆ‘ไปฌๅฏไปฅไบ†่งฃๅˆฐ: <add> <add>- ่‡ชๅŠจๆ‰“ๅŒ…็ผ–่ฏ‘ (ไฝฟ็”จ webpack ๅ’Œ babel) <add>- ็ƒญๅŠ ่ฝฝ <add>- ไปฅ `./pages`ไฝœไธบๆœๅŠก็ซฏ็š„ๆธฒๆŸ“ๅ’Œ็ดขๅผ• <add>- Static file serving. `./static/` is mapped to `/static/` (given you [create a `./static/` directory](#static-file-serving-eg-images) inside your project) <add>- ้™ๆ€ๆ–‡ไปถๆœๅŠก. `./static/` ๆ˜ ๅฐ„ๅˆฐ `/static/` (ๅฏไปฅ [ๅˆ›ๅปบไธ€ไธช้™ๆ€็›ฎๅฝ•](#static-file-serving-eg-images) ๅœจไฝ ็š„้กน็›ฎไธญ) <add> <add>่ฟ™้‡Œๆœ‰ไธช็ฎ€ๅ•็š„ๆกˆไพ‹๏ผŒๅฏไปฅไธ‹่ฝฝ็œ‹็œ‹ [sample app - nextgram](https://github.com/zeit/nextgram) <add> <add><a id="automatic-code-splitting" style="display: none"></a> <add>### ไปฃ็ ่‡ชๅŠจๅˆ†ๅ‰ฒ <add> <add>ๆฏไธช้กต้ขๅชไผšๅฏผๅ…ฅ`import`ไธญ็ป‘ๅฎšไปฅๅŠ่ขซ็”จๅˆฐ็š„ไปฃ็ . ไนŸๅฐฑๆ˜ฏ่ฏดๅนถไธไผšๅŠ ่ฝฝไธ้œ€่ฆ็š„ไปฃ็ ! <add> <add>```jsx <add>import cowsay from 'cowsay-browser' <add> <add>export default () => <add> <pre> <add> {cowsay.say({ text: 'hi there!' })} <add> </pre> <add>``` <add> <add><a id="css" style="display: none"></a> <add>### CSS <add> <add><a id="built-in-css-support" style="display: none"></a> <add>#### ๆ”ฏๆŒๅตŒๅ…ฅๆ ทๅผ <add> <add><p><details> <add> <summary><b>ๆกˆไพ‹</b></summary> <add> <ul><li><a href="https://github.com/zeit/next.js/tree/canary/examples/basic-css">Basic css</a></li></ul> <add></details></p> <add> <add>ๆˆ‘ไปฌ็ป‘ๅฎš [styled-jsx](https://github.com/zeit/styled-jsx) ๆฅ็”Ÿๆˆ็‹ฌ็ซ‹ไฝœ็”จๅŸŸ็š„ CSS. ็›ฎๆ ‡ๆ˜ฏๆ”ฏๆŒ "shadow CSS",ไฝ†ๆ˜ฏ [ไธๆ”ฏๆŒ็‹ฌ็ซ‹ๆจกๅ—ไฝœ็”จๅŸŸ็š„ JS](https://github.com/w3c/webcomponents/issues/71). <add> <add>```jsx <add>export default () => <add> <div> <add> Hello world <add> <p>scoped!</p> <add> <style jsx>{` <add> p { <add> color: blue; <add> } <add> div { <add> background: red; <add> } <add> @media (max-width: 600px) { <add> div { <add> background: blue; <add> } <add> } <add> `}</style> <add> <style global jsx>{` <add> body { <add> background: black; <add> } <add> `}</style> <add> </div> <add>``` <add> <add>ๆƒณๆŸฅ็œ‹ๆ›ดๅคšๆกˆไพ‹ๅฏไปฅ็‚นๅ‡ป [styled-jsx documentation](https://www.npmjs.com/package/styled-jsx)ๆŸฅ็œ‹. <add> <add><a id="css-in-js" style="display: none"></a> <add>#### ๅ†…ๅตŒๆ ทๅผ <add> <add><p><details> <add> <summary> <add> <b>Examples</b> <add> </summary> <add> <ul><li><a href="./examples/with-styled-components">Styled components</a></li><li><a href="./examples/with-styletron">Styletron</a></li><li><a href="./examples/with-glamor">Glamor</a></li><li><a href="./examples/with-glamorous">Glamorous</a></li><li><a href="./examples/with-cxs">Cxs</a></li><li><a href="./examples/with-aphrodite">Aphrodite</a></li><li><a href="./examples/with-fela">Fela</a></li></ul> <add></details></p> <add> <add>ๆœ‰ไบ›ๆƒ…ๅ†ตๅฏไปฅไฝฟ็”จ CSS ๅ†…ๅตŒ JS ๅ†™ๆณ•ใ€‚ๅฆ‚ไธ‹ๆ‰€็คบ๏ผš <add> <add>```jsx <add>export default () => <p style={{ color: 'red' }}>hi there</p> <add>``` <add> <add>ๆ›ดๅคๆ‚็š„ๅ†…ๅตŒๆ ทๅผ่งฃๅ†ณๆ–นๆกˆ๏ผŒ็‰นๅˆซๆ˜ฏๆœๅŠก็ซฏๆธฒๆŸ“็š„ๆ—ถๆ ทๅผๆ›ดๆ”นใ€‚ๆˆ‘ไปฌๅฏไปฅ้€š่ฟ‡ๅŒ…่ฃน่‡ชๅฎšไน‰ Document๏ผŒๆฅๆทปๅŠ ๆ ทๅผ๏ผŒๆกˆไพ‹ๅฆ‚ไธ‹๏ผš[custom `<Document>`](#user-content-custom-document) <add> <add><a id="importing-css--sass--less--stylus-files" style="display: none"></a> <add>#### ไฝฟ็”จ CSS / Sass / Less / Stylus files <add> <add>ๆ”ฏๆŒ็”จ`.css`, `.scss`, `.less` or `.styl`๏ผŒ้œ€่ฆ้…็ฝฎ้ป˜่ฎคๆ–‡ไปถ next.config.js๏ผŒๅ…ทไฝ“ๅฏๆŸฅ็œ‹ไธ‹้ข้“พๆŽฅ <add> <add>- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css) <add>- [@zeit/next-sass](https://github.com/zeit/next-plugins/tree/master/packages/next-sass) <add>- [@zeit/next-less](https://github.com/zeit/next-plugins/tree/master/packages/next-less) <add>- [@zeit/next-stylus](https://github.com/zeit/next-plugins/tree/master/packages/next-stylus) <add> <add><a id="static-file-serving-eg-images" style="display: none"></a> <add>### ้™ๆ€ๆ–‡ไปถๆœๅŠก๏ผˆๅฆ‚ๅ›พๅƒ๏ผ‰ <add> <add>ๅœจๆ น็›ฎๅฝ•ไธ‹ๆ–ฐๅปบๆ–‡ไปถๅคนๅซ`static`ใ€‚ไปฃ็ ๅฏไปฅ้€š่ฟ‡`/static/`ๆฅๅผ•ๅ…ฅ็›ธๅ…ณ็š„้™ๆ€่ต„ๆบใ€‚ <add> <add>```jsx <add>export default () => <img src="/static/my-image.png" alt="my image" /> <add>``` <add> <add>_ๆณจๆ„๏ผšไธ่ฆ่‡ชๅฎšไน‰้™ๆ€ๆ–‡ไปถๅคน็š„ๅๅญ—๏ผŒๅช่ƒฝๅซ`static` ๏ผŒๅ› ไธบๅชๆœ‰่ฟ™ไธชๅๅญ— Next.js ๆ‰ไผšๆŠŠๅฎƒๅฝ“ไฝœ้™ๆ€่ต„ๆบใ€‚ <add> <add> <add><a id="populating-head" style="display: none"></a> <add>### ็”Ÿๆˆ`<head>` <add> <add>`<head>` <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul> <add> <li><a href="./examples/head-elements">Head elements</a></li> <add> <li><a href="./examples/layout-component">Layout component</a></li> <add> </ul> <add></details></p> <add> <add>ๆˆ‘ไปฌ่ฎพ็ฝฎไธ€ไธชๅ†…็ฝฎ็ป„ไปถๆฅ่ฃ…่ฝฝ`<head>`ๅˆฐ้กต้ขไธญใ€‚ <add> <add>```jsx <add>import Head from 'next/head' <add> <add>export default () => <add> <div> <add> <Head> <add> <title>My page title</title> <add> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <add> </Head> <add> <p>Hello world!</p> <add> </div> <add>``` <add> <add>ๆˆ‘ไปฌๅฎšไน‰`key`ๅฑžๆ€งๆฅ้ฟๅ…้‡ๅค็š„`<head>`ๆ ‡็ญพ๏ผŒไฟ่ฏ`<head>`ๅชๆธฒๆŸ“ไธ€ๆฌก๏ผŒๅฆ‚ไธ‹ๆ‰€็คบ๏ผš <add> <add>```jsx <add>import Head from 'next/head' <add>export default () => ( <add> <div> <add> <Head> <add> <title>My page title</title> <add> <meta name="viewport" content="initial-scale=1.0, width=device-width" key="viewport" /> <add> </Head> <add> <Head> <add> <meta name="viewport" content="initial-scale=1.2, width=device-width" key="viewport" /> <add> </Head> <add> <p>Hello world!</p> <add> </div> <add>) <add>``` <add> <add>ๅชๆœ‰็ฌฌไบŒไธช`<meta name="viewport" />`ๆ‰่ขซๆธฒๆŸ“ใ€‚ <add> <add>ๆณจๆ„๏ผšๅœจๅธ่ฝฝ็ป„ไปถๆ—ถ๏ผŒ`<head>`็š„ๅ†…ๅฎนๅฐ†่ขซๆธ…้™คใ€‚่ฏท็กฎไฟๆฏไธช้กต้ข้ƒฝๅœจๅ…ถ`<head>`ๅฎšไน‰ไบ†ๆ‰€้œ€่ฆ็š„ๅ†…ๅฎน๏ผŒ่€Œไธๆ˜ฏๅ‡่ฎพๅ…ถไป–้กต้ขๅทฒ็ปๅŠ ่ฟ‡ไบ† <add> <add><a id="fetching-data-and-component-lifecycle" style="display: none"></a> <add>### ่Žทๅ–ๆ•ฐๆฎไปฅๅŠ็ป„ไปถ็”Ÿๅ‘ฝๅ‘จๆœŸ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul><li><a href="./examples/data-fetch">Data fetch</a></li></ul> <add></details></p> <add> <add>ๅฆ‚ๆžœไฝ ้œ€่ฆไธ€ไธชๆœ‰็Šถๆ€ใ€็”Ÿๅ‘ฝๅ‘จๆœŸๆˆ–ๆœ‰ๅˆๅง‹ๆ•ฐๆฎ็š„ React ็ป„ไปถ๏ผˆ่€Œไธๆ˜ฏไธŠ้ข็š„ๆ— ็Šถๆ€ๅ‡ฝๆ•ฐ๏ผ‰๏ผŒๅฆ‚ไธ‹ๆ‰€็คบ๏ผš <add> <add>```jsx <add>import React from 'react' <add> <add>export default class extends React.Component { <add> static async getInitialProps({ req }) { <add> const userAgent = req ? req.headers['user-agent'] : navigator.userAgent <add> return { userAgent } <add> } <add> <add> render() { <add> return ( <add> <div> <add> Hello World {this.props.userAgent} <add> </div> <add> ) <add> } <add>} <add>``` <add> <add>็›ธไฟกไฝ ๆณจๆ„ๅˆฐ๏ผŒๅฝ“้กต้ขๆธฒๆŸ“ๆ—ถๅŠ ่ฝฝๆ•ฐๆฎ๏ผŒๆˆ‘ไปฌไฝฟ็”จไบ†ไธ€ไธชๅผ‚ๆญฅๆ–นๆณ•`getInitialProps`ใ€‚ๅฎƒ่ƒฝๅผ‚ๆญฅ่Žทๅ– JS ๆ™ฎ้€šๅฏน่ฑก๏ผŒๅนถ็ป‘ๅฎšๅœจ`props`ไธŠ <add> <add>ๅฝ“ๆœๅŠกๆธฒๆŸ“ๆ—ถ๏ผŒ`getInitialProps`ๅฐ†ไผšๆŠŠๆ•ฐๆฎๅบๅˆ—ๅŒ–๏ผŒๅฐฑๅƒ`JSON.stringify`ใ€‚ๆ‰€ไปฅ็กฎไฟ`getInitialProps`่ฟ”ๅ›ž็š„ๆ˜ฏไธ€ไธชๆ™ฎ้€š JS ๅฏน่ฑก๏ผŒ่€Œไธๆ˜ฏ`Date`, `Map` ๆˆ– `Set`็ฑปๅž‹ใ€‚ <add> <add>ๅฝ“้กต้ขๅˆๆฌกๅŠ ่ฝฝๆ—ถ๏ผŒ`getInitialProps`ๅชไผšๅœจๆœๅŠก็ซฏๆ‰ง่กŒไธ€ๆฌกใ€‚`getInitialProps`ๅชๆœ‰ๅœจ่ทฏ็”ฑๅˆ‡ๆข็š„ๆ—ถๅ€™๏ผˆๅฆ‚`Link`็ป„ไปถ่ทณ่ฝฌๆˆ–่ทฏ็”ฑ่‡ชๅฎšไน‰่ทณ่ฝฌ๏ผ‰ๆ—ถ๏ผŒๅฎขๆˆท็ซฏ็š„ๆ‰ไผš่ขซๆ‰ง่กŒใ€‚ <add> <add>ๅฝ“้กต้ขๅˆๅง‹ๅŒ–ๅŠ ่ฝฝๆ—ถ๏ผŒ`getInitialProps`ๅชไผšๅŠ ่ฝฝๅœจๆœๅŠก็ซฏใ€‚ๅชๆœ‰ๅฝ“่ทฏ็”ฑ่ทณ่ฝฌ๏ผˆ`Link`็ป„ไปถ่ทณ่ฝฌๆˆ– API ๆ–นๆณ•่ทณ่ฝฌ๏ผ‰ๆ—ถ๏ผŒๅฎขๆˆท็ซฏๆ‰ไผšๆ‰ง่กŒ`getInitialProps`ใ€‚ <add> <add>ๆณจๆ„๏ผš`getInitialProps`ๅฐ†ไธ่ƒฝไฝฟ็”จๅœจๅญ็ป„ไปถไธญใ€‚ๅช่ƒฝไฝฟ็”จๅœจ`pages`้กต้ขไธญใ€‚ <add> <add><br/> <add> <add>> ๅชๆœ‰ๆœๅŠก็ซฏ็”จๅˆฐ็š„ๆจกๅ—ๆ”พๅœจ`getInitialProps`้‡Œ๏ผŒ่ฏท็กฎไฟๆญฃ็กฎ็š„ๅฏผๅ…ฅไบ†ๅฎƒไปฌ๏ผŒๅฏๅ‚่€ƒ[import them properly](https://arunoda.me/blog/ssr-and-server-only-modules)ใ€‚ <add>> ๅฆๅˆ™ไผšๆ‹–ๆ…ขไฝ ็š„ๅบ”็”จ้€Ÿๅบฆใ€‚ <add> <add><br/> <add> <add>ไฝ ไนŸๅฏไปฅ็ป™ๆ— ็Šถๆ€็ป„ไปถๅฎšไน‰`getInitialProps`๏ผš <add> <add>```jsx <add>const Page = ({ stars }) => <add> <div> <add> Next stars: {stars} <add> </div> <add> <add>Page.getInitialProps = async ({ req }) => { <add> const res = await fetch('https://api.github.com/repos/zeit/next.js') <add> const json = await res.json() <add> return { stars: json.stargazers_count } <add>} <add> <add>export default Page <add>``` <add> <add>`getInitialProps`ๅ…ฅๅ‚ๅฏน่ฑก็š„ๅฑžๆ€งๅฆ‚ไธ‹๏ผš <add> <add>- `pathname` - URL ็š„ path ้ƒจๅˆ† <add>- `query` - URL ็š„ query ้ƒจๅˆ†๏ผŒๅนถ่ขซ่งฃๆžๆˆๅฏน่ฑก <add>- `asPath` - ๆ˜พ็คบๅœจๆต่งˆๅ™จไธญ็š„ๅฎž้™…่ทฏๅพ„๏ผˆๅŒ…ๅซๆŸฅ่ฏข้ƒจๅˆ†๏ผ‰๏ผŒไธบ`String`็ฑปๅž‹ <add>- `req` - HTTP ่ฏทๆฑ‚ๅฏน่ฑก (ๅชๆœ‰ๆœๅŠกๅ™จ็ซฏๆœ‰) <add>- `res` - HTTP ่ฟ”ๅ›žๅฏน่ฑก (ๅชๆœ‰ๆœๅŠกๅ™จ็ซฏๆœ‰) <add>- `jsonPageRes` - [่Žทๅ–ๆ•ฐๆฎๅ“ๅบ”ๅฏน่ฑก](https://developer.mozilla.org/en-US/docs/Web/API/Response) (ๅชๆœ‰ๅฎขๆˆท็ซฏๆœ‰) <add>- `err` - ๆธฒๆŸ“่ฟ‡็จ‹ไธญ็š„ไปปไฝ•้”™่ฏฏ <add> <add><a id="routing" style="display: none"></a> <add>### ่ทฏ็”ฑ <add> <add><a id="with-link" style="display: none"></a> <add>#### `<Link>`็”จๆณ• <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul> <add> <li><a href="./examples/hello-world">Hello World</a></li> <add> </ul> <add></details></p> <add> <add>ๅฏไปฅ็”จ `<Link>` ็ป„ไปถๅฎž็Žฐๅฎขๆˆท็ซฏ็š„่ทฏ็”ฑๅˆ‡ๆขใ€‚ <add> <add>```jsx <add>// pages/index.js <add>import Link from 'next/link' <add> <add>export default () => <add> <div> <add> Click{' '} <add> <Link href="/about"> <add> <a>here</a> <add> </Link>{' '} <add> to read more <add> </div> <add>``` <add> <add>```jsx <add>// pages/about.js <add>export default () => <p>Welcome to About!</p> <add>``` <add> <add>ๆณจๆ„๏ผšๅฏไปฅไฝฟ็”จ[`<Link prefetch>`](#prefetching-pages)ไฝฟ้“พๆŽฅๅ’Œ้ข„ๅŠ ่ฝฝๅœจๅŽๅฐๅŒๆ—ถ่ฟ›่กŒ๏ผŒๆฅ่พพๅˆฐ้กต้ข็š„ๆœ€ไฝณๆ€ง่ƒฝใ€‚ <add> <add>ๅฎขๆˆท็ซฏ่ทฏ็”ฑ่กŒไธบไธŽๆต่งˆๅ™จๅพˆ็›ธไผผ๏ผš <add> <add>1. ็ป„ไปถ่Žทๅ– <add>2. ๅฆ‚ๆžœ็ป„ไปถๅฎšไน‰ไบ†`getInitialProps`๏ผŒๆ•ฐๆฎ่Žทๅ–ไบ†ใ€‚ๅฆ‚ๆžœๆœ‰้”™่ฏฏๆƒ…ๅ†ตๅฐ†ไผšๆธฒๆŸ“ `_error.js`ใ€‚ <add>3. 1ๅ’Œ2้ƒฝๅฎŒๆˆไบ†๏ผŒ`pushState`ๆ‰ง่กŒ๏ผŒๆ–ฐ็ป„ไปถ่ขซๆธฒๆŸ“ใ€‚ <add> <add>ๅฆ‚ๆžœ้œ€่ฆๆณจๅ…ฅ`pathname`, `query` ๆˆ– `asPath`ๅˆฐไฝ ็ป„ไปถไธญ๏ผŒไฝ ๅฏไปฅไฝฟ็”จ[withRouter](#using-a-higher-order-component)ใ€‚ <add> <add><a id="with-url-object" style="display: none"></a> <add>##### URL ๅฏน่ฑก <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul> <add> <li><a href="./examples/with-url-object-routing">With URL Object Routing</a></li> <add> </ul> <add></details></p> <add> <add>็ป„ไปถ`<Link>`ๆŽฅๆ”ถ URL ๅฏน่ฑก๏ผŒ่€Œไธ”ๅฎƒไผš่‡ชๅŠจๆ ผๅผๅŒ–็”Ÿๆˆ URL ๅญ—็ฌฆไธฒ <add> <add>```jsx <add>// pages/index.js <add>import Link from 'next/link' <add> <add>export default () => <add> <div> <add> Click{' '} <add> <Link href={{ pathname: '/about', query: { name: 'Zeit' }}}> <add> <a>here</a> <add> </Link>{' '} <add> to read more <add> </div> <add>``` <add> <add>ๅฐ†็”Ÿๆˆ URL ๅญ—็ฌฆไธฒ`/about?name=Zeit`๏ผŒไฝ ๅฏไปฅไฝฟ็”จไปปไฝ•ๅœจ[Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects)ๅฎšไน‰่ฟ‡็š„ๅฑžๆ€งใ€‚ <add> <add> <add><a id="replace-instead-of-push-url" style="display: none"></a> <add>##### ๆ›ฟๆข่ทฏ็”ฑ <add> <add>`<Link>`็ป„ไปถ้ป˜่ฎคๅฐ†ๆ–ฐ url ๆŽจๅ…ฅ่ทฏ็”ฑๆ ˆไธญใ€‚ไฝ ๅฏไปฅไฝฟ็”จ`replace`ๅฑžๆ€งๆฅ้˜ฒๆญขๆทปๅŠ ๆ–ฐ่พ“ๅ…ฅใ€‚ <add> <add>```jsx <add>// pages/index.js <add>import Link from 'next/link' <add> <add>export default () => <add> <div> <add> Click{' '} <add> <Link href="/about" replace> <add> <a>here</a> <add> </Link>{' '} <add> to read more <add> </div> <add>``` <add> <add><a id="using-a-component-that-supports-onclick" style="display: none"></a> <add>##### ็ป„ไปถๆ”ฏๆŒ็‚นๅ‡ปไบ‹ไปถ `onClick` <add> <add>`<Link>`ๆ”ฏๆŒๆฏไธช็ป„ไปถๆ‰€ๆ”ฏๆŒ็š„`onClick`ไบ‹ไปถใ€‚ๅฆ‚ๆžœไฝ ไธๆไพ›`<a>`ๆ ‡็ญพ๏ผŒๅชไผšๅค„็†`onClick`ไบ‹ไปถ่€Œ`href`ๅฐ†ไธ่ตทไฝœ็”จใ€‚ <add> <add>```jsx <add>// pages/index.js <add>import Link from 'next/link' <add> <add>export default () => <add> <div> <add> Click{' '} <add> <Link href="/about"> <add> <img src="/static/image.png" alt="image" /> <add> </Link> <add> </div> <add>``` <add> <add><a id="forcing-the-link-to-expose-href-to-its-child" style="display: none"></a> <add>##### ๆšด้œฒ `href` ็ป™ๅญๅ…ƒ็ด  <add> <add>ๅฆ‚ๅญๅ…ƒ็ด ๆ˜ฏไธ€ไธชๆฒกๆœ‰ href ๅฑžๆ€ง็š„`<a>`ๆ ‡็ญพ๏ผŒๆˆ‘ไปฌๅฐ†ไผšๆŒ‡ๅฎšๅฎƒไปฅๅ…็”จๆˆท้‡ๅคๆ“ไฝœใ€‚็„ถ่€Œๆœ‰ไบ›ๆ—ถๅ€™๏ผŒๆˆ‘ไปฌ้œ€่ฆ้‡Œ้ขๆœ‰`<a>`ๆ ‡็ญพ๏ผŒไฝ†ๆ˜ฏ`Link`็ป„ไปถไธไผš่ขซ่ฏ†ๅˆซๆˆ*่ถ…้“พๆŽฅ*๏ผŒ็ป“ๆžœไธ่ƒฝๅฐ†`href`ไผ ้€’็ป™ๅญๅ…ƒ็ด ใ€‚ๅœจ่ฟ™็งๅœบๆ™ฏไธ‹๏ผŒไฝ ๅฏไปฅๅฎšไน‰ไธ€ไธช`Link`็ป„ไปถไธญ็š„ๅธƒๅฐ”ๅฑžๆ€ง`passHref`๏ผŒๅผบๅˆถๅฐ†`href`ไผ ้€’็ป™ๅญๅ…ƒ็ด ใ€‚ <add> <add>**ๆณจๆ„**: ไฝฟ็”จ`a`ไน‹ๅค–็š„ๆ ‡็ญพ่€Œไธ”ๆฒกๆœ‰้€š่ฟ‡`passHref`็š„้“พๆŽฅๅฏ่ƒฝไผšไฝฟๅฏผ่ˆช็œ‹ไธŠๅŽปๆญฃ็กฎ๏ผŒไฝ†ๆ˜ฏๅฝ“ๆœ็ดขๅผ•ๆ“Ž็ˆฌ่กŒๆฃ€ๆต‹ๆ—ถ๏ผŒๅฐ†ไธไผš่ฏ†ๅˆซๆˆ้“พๆŽฅ๏ผˆ็”ฑไบŽ็ผบไน href ๅฑžๆ€ง๏ผ‰๏ผŒ่ฟ™ไผšๅฏนไฝ ็ฝ‘็ซ™็š„ SEO ไบง็”Ÿ่ดŸ้ขๅฝฑๅ“ใ€‚ <add> <add>```jsx <add>import Link from 'next/link' <add>import Unexpected_A from 'third-library' <add> <add>export default ({ href, name }) => <add> <Link href={href} passHref> <add> <Unexpected_A> <add> {name} <add> </Unexpected_A> <add> </Link> <add>``` <add> <add><a id="disabling-the-scroll-changes-to-top-on-page" style="display: none"></a> <add>##### ็ฆๆญขๆปšๅŠจๅˆฐ้กต้ข้กถ้ƒจ <add> <add>`<Link>`็š„้ป˜่ฎค่กŒไธบๅฐฑๆ˜ฏๆปšๅˆฐ้กต้ข้กถ้ƒจใ€‚ๅฝ“ๆœ‰ hash ๅฎšไน‰ๆ—ถ๏ผˆ๏ผƒ๏ผ‰๏ผŒ้กต้ขๅฐ†ไผšๆปšๅŠจๅˆฐๅฏนๅบ”็š„ id ไธŠ๏ผŒๅฐฑๅƒ`<a>`ๆ ‡็ญพไธ€ๆ ทใ€‚ไธบไบ†้ข„้˜ฒๆปšๅŠจๅˆฐ้กถ้ƒจ๏ผŒๅฏไปฅ็ป™`<Link>`ๅŠ  <add>`scroll={false}`ๅฑžๆ€ง๏ผš <add> <add>```jsx <add><Link scroll={false} href="/?counter=10"><a>Disables scrolling</a></Link> <add><Link href="/?counter=10"><a>Changes with scrolling to top</a></Link> <add>``` <add> <add><a id="imperatively" style="display: none"></a> <add>#### ๅ‘ฝไปคๅผ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul> <add> <li><a href="./examples/using-router">Basic routing</a></li> <add> <li><a href="./examples/with-loading">With a page loading indicator</a></li> <add> </ul> <add></details></p> <add> <add>ไฝ ไนŸๅฏไปฅ็”จ`next/router`ๅฎž็Žฐๅฎขๆˆท็ซฏ่ทฏ็”ฑๅˆ‡ๆข <add> <add> <add>```jsx <add>import Router from 'next/router' <add> <add>export default () => <add> <div> <add> Click <span onClick={() => Router.push('/about')}>here</span> to read more <add> </div> <add>``` <add> <add><a id="intercepting-popstate" style="display: none"></a> <add>#### ๆ‹ฆๆˆชๅ™จ `popstate` <add> <add>ๆœ‰ไบ›ๆƒ…ๅ†ต๏ผˆๆฏ”ๅฆ‚ไฝฟ็”จ[custom router](#custom-server-and-routing)๏ผ‰๏ผŒไฝ ๅฏ่ƒฝๆƒณ็›‘ๅฌ[`popstate`](https://developer.mozilla.org/en-US/docs/Web/Events/popstate)๏ผŒๅœจ่ทฏ็”ฑ่ทณ่ฝฌๅ‰ๅšไธ€ไบ›ๅŠจไฝœใ€‚ <add>ๆฏ”ๅฆ‚๏ผŒไฝ ๅฏไปฅๆ“ไฝœ request ๆˆ–ๅผบๅˆถ SSR ๅˆทๆ–ฐ <add> <add>```jsx <add>import Router from 'next/router' <add> <add>Router.beforePopState(({ url, as, options }) => { <add> // I only want to allow these two routes! <add> if (as !== "/" || as !== "/other") { <add> // Have SSR render bad routes as a 404. <add> window.location.href = as <add> return false <add> } <add> <add> return true <add>}); <add>``` <add> <add>ๅฆ‚ๆžœไฝ ๅœจ`beforePopState`ไธญ่ฟ”ๅ›ž false๏ผŒ`Router`ๅฐ†ไธไผšๆ‰ง่กŒ`popstate`ไบ‹ไปถใ€‚ <add>ไพ‹ๅฆ‚[Disabling File-System Routing](#disabling-file-system-routing)ใ€‚ <add> <add>ไปฅไธŠ`Router`ๅฏน่ฑก็š„ API ๅฆ‚ไธ‹๏ผš <add> <add>- `route` - ๅฝ“ๅ‰่ทฏ็”ฑ็š„`String`็ฑปๅž‹ <add>- `pathname` - ไธๅŒ…ๅซๆŸฅ่ฏขๅ†…ๅฎน็š„ๅฝ“ๅ‰่ทฏๅพ„๏ผŒไธบ`String`็ฑปๅž‹ <add>- `query` - ๆŸฅ่ฏขๅ†…ๅฎน๏ผŒ่ขซ่งฃๆžๆˆ`Object`็ฑปๅž‹. ้ป˜่ฎคไธบ`{}` <add>- `asPath` - ๅฑ•็Žฐๅœจๆต่งˆๅ™จไธŠ็š„ๅฎž้™…่ทฏๅพ„๏ผŒๅŒ…ๅซๆŸฅ่ฏขๅ†…ๅฎน๏ผŒไธบ`String`็ฑปๅž‹ <add>- `push(url, as=url)` - ้กต้ขๆธฒๆŸ“็ฌฌไธ€ไธชๅ‚ๆ•ฐ url ็š„้กต้ข๏ผŒๆต่งˆๅ™จๆ ๆ˜พ็คบ็š„ๆ˜ฏ็ฌฌไบŒไธชๅ‚ๆ•ฐ url <add>- `replace(url, as=url)` - performs a `replaceState` call with the given url <add>- `beforePopState(cb=function)` - ๅœจ่ทฏ็”ฑๅ™จๅค„็†ไบ‹ไปถไน‹ๅ‰ๆ‹ฆๆˆช. <add> <add>`push` ๅ’Œ `replace` ๅ‡ฝๆ•ฐ็š„็ฌฌไบŒไธชๅ‚ๆ•ฐ`as`๏ผŒๆ˜ฏไธบไบ†่ฃ…้ฅฐ URL ไฝœ็”จใ€‚ๅฆ‚ๆžœไฝ ๅœจๆœๅŠกๅ™จ็ซฏ่ฎพ็ฝฎไบ†่‡ชๅฎšไน‰่ทฏ็”ฑๅฐ†ไผš่ตทไฝœ็”จใ€‚ <add> <add><a id="with-url-object-1" style="display: none"></a> <add>##### URL ๅฏน่ฑก็”จๆณ• <add> <add>`push` ๆˆ– `replace`ๅฏๆŽฅๆ”ถ็š„ URL ๅฏน่ฑก๏ผˆ`<Link>`็ป„ไปถ็š„ URL ๅฏน่ฑกไธ€ๆ ท๏ผ‰ๆฅ็”Ÿๆˆ URLใ€‚ <add> <add>```jsx <add>import Router from 'next/router' <add> <add>const handler = () => <add> Router.push({ <add> pathname: '/about', <add> query: { name: 'Zeit' } <add> }) <add> <add>export default () => <add> <div> <add> Click <span onClick={handler}>here</span> to read more <add> </div> <add>``` <add> <add>ไนŸๅฏไปฅๅƒ`<Link>`็ป„ไปถไธ€ๆ ทๆทปๅŠ ้ขๅค–็š„ๅ‚ๆ•ฐใ€‚ <add> <add><a id="router-events" style="display: none"></a> <add>##### ่ทฏ็”ฑไบ‹ไปถ <add> <add>ไฝ ๅฏไปฅ็›‘ๅฌ่ทฏ็”ฑ็›ธๅ…ณไบ‹ไปถใ€‚ <add>ไธ‹้ขๆ˜ฏไบ‹ไปถๆ”ฏๆŒๅˆ—่กจ๏ผš <add> <add>- `routeChangeStart(url)` - ่ทฏ็”ฑๅผ€ๅง‹ๅˆ‡ๆขๆ—ถ่งฆๅ‘ <add>- `routeChangeComplete(url)` - ๅฎŒๆˆ่ทฏ็”ฑๅˆ‡ๆขๆ—ถ่งฆๅ‘ <add>- `routeChangeError(err, url)` - ่ทฏ็”ฑๅˆ‡ๆขๆŠฅ้”™ๆ—ถ่งฆๅ‘ <add>- `beforeHistoryChange(url)` - ๆต่งˆๅ™จ history ๆจกๅผๅผ€ๅง‹ๅˆ‡ๆขๆ—ถ่งฆๅ‘ <add>- `hashChangeStart(url)` - ๅผ€ๅง‹ๅˆ‡ๆข hash ๅ€ผไฝ†ๆ˜ฏๆฒกๆœ‰ๅˆ‡ๆข้กต้ข่ทฏ็”ฑๆ—ถ่งฆๅ‘ <add>- `hashChangeComplete(url)` - ๅฎŒๆˆๅˆ‡ๆข hash ๅ€ผไฝ†ๆ˜ฏๆฒกๆœ‰ๅˆ‡ๆข้กต้ข่ทฏ็”ฑๆ—ถ่งฆๅ‘ <add> <add>> ่ฟ™้‡Œ็š„`url`ๆ˜ฏๆŒ‡ๆ˜พ็คบๅœจๆต่งˆๅ™จไธญ็š„ urlใ€‚ๅฆ‚ๆžœไฝ ็”จไบ†`Router.push(url, as)`๏ผˆๆˆ–็ฑปไผผ็š„ๆ–นๆณ•๏ผ‰๏ผŒ้‚ฃๆต่งˆๅ™จไธญ็š„ url ๅฐ†ไผšๆ˜พ็คบ as ็š„ๅ€ผใ€‚ <add> <add>ไธ‹้ขๆ˜ฏๅฆ‚ไฝ•ๆญฃ็กฎไฝฟ็”จ่ทฏ็”ฑไบ‹ไปถ`routeChangeStart`็š„ไพ‹ๅญ๏ผš <add> <add>```js <add>const handleRouteChange = url => { <add> console.log('App is changing to: ', url) <add>} <add> <add>Router.events.on('routeChangeStart', handleRouteChange) <add>``` <add> <add>ๅฆ‚ๆžœไฝ ไธๆƒณ้•ฟๆœŸ็›‘ๅฌ่ฏฅไบ‹ไปถ๏ผŒไฝ ๅฏไปฅ็”จ`off`ไบ‹ไปถๅŽปๅ–ๆถˆ็›‘ๅฌ๏ผš <add> <add>```js <add>Router.events.off('routeChangeStart', handleRouteChange) <add>``` <add> <add>ๅฆ‚ๆžœ่ทฏ็”ฑๅŠ ่ฝฝ่ขซๅ–ๆถˆ๏ผˆๆฏ”ๅฆ‚ๅฟซ้€Ÿ่ฟž็ปญๅŒๅ‡ป้“พๆŽฅ๏ผ‰ <add> <add>```js <add>Router.events.on('routeChangeError', (err, url) => { <add> if (err.cancelled) { <add> console.log(`Route to ${url} was cancelled!`) <add> } <add>}) <add>``` <add> <add><a id="shallow-routing" style="display: none"></a> <add>##### ๆต…ๅฑ‚่ทฏ็”ฑ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul> <add> <li><a href="./examples/with-shallow-routing">Shallow Routing</a></li> <add> </ul> <add></details></p> <add> <add>ๆต…ๅฑ‚่ทฏ็”ฑๅ…่ฎธไฝ ๆ”นๅ˜ URL ไฝ†ๆ˜ฏไธๆ‰ง่กŒ`getInitialProps`็”Ÿๅ‘ฝๅ‘จๆœŸใ€‚ไฝ ๅฏไปฅๅŠ ่ฝฝ็›ธๅŒ้กต้ข็š„ URL๏ผŒๅพ—ๅˆฐๆ›ดๆ–ฐๅŽ็š„่ทฏ็”ฑๅฑžๆ€ง`pathname`ๅ’Œ`query`๏ผŒๅนถไธๅคฑๅŽป state ็Šถๆ€ใ€‚ <add> <add>ไฝ ๅฏไปฅ็ป™`Router.push` ๆˆ– `Router.replace`ๆ–นๆณ•ๅŠ `shallow: true`ๅ‚ๆ•ฐใ€‚ๅฆ‚ไธ‹้ข็š„ไพ‹ๅญๆ‰€็คบ๏ผš <add> <add>```js <add>// Current URL is "/" <add>const href = '/?counter=10' <add>const as = href <add>Router.push(href, as, { shallow: true }) <add>``` <add> <add>็Žฐๅœจ URL ๆ›ดๆ–ฐไธบ`/?counter=10`ใ€‚ๅœจ็ป„ไปถ้‡ŒๆŸฅ็œ‹`this.props.router.query`ไฝ ๅฐ†ไผš็œ‹ๅˆฐๆ›ดๆ–ฐ็š„ URLใ€‚ <add> <add>ไฝ ๅฏไปฅๅœจ[`componentdidupdate`](https://facebook.github.io/react/docs/react-component.html#componentdidupdate)้’ฉๅญๅ‡ฝๆ•ฐไธญ็›‘ๅฌ URL ็š„ๅ˜ๅŒ–ใ€‚ <add> <add>```js <add>componentDidUpdate(prevProps) { <add> const { pathname, query } = this.props.router <add> // verify props have changed to avoid an infinite loop <add> if (query.id !== prevProps.router.query.id) { <add> // fetch data based on the new query <add> } <add>} <add>``` <add> <add>> ๆณจๆ„: <add>> <add>> ๆต…ๅฑ‚่ทฏ็”ฑๅชไฝœ็”จไบŽ็›ธๅŒ URL ็š„ๅ‚ๆ•ฐๆ”นๅ˜๏ผŒๆฏ”ๅฆ‚ๆˆ‘ไปฌๅ‡ๅฎšๆœ‰ไธชๅ…ถไป–่ทฏ็”ฑ`about`๏ผŒ่€Œไฝ ๅ‘ไธ‹้ขไปฃ็ ๆ ท่ฟ่กŒ: <add>> ```js <add>> Router.push('/?counter=10', '/about?counter=10', { shallow: true }) <add>> ``` <add>> ้‚ฃไนˆ่ฟ™ๅฐ†ไผšๅ‡บ็Žฐๆ–ฐ้กต้ข๏ผŒๅณไฝฟๆˆ‘ไปฌๅŠ ไบ†ๆต…ๅฑ‚่ทฏ็”ฑ๏ผŒไฝ†ๆ˜ฏๅฎƒ่ฟ˜ๆ˜ฏไผšๅธ่ฝฝๅฝ“ๅ‰้กต๏ผŒไผšๅŠ ่ฝฝๆ–ฐ็š„้กต้ขๅนถ่งฆๅ‘ๆ–ฐ้กต้ข็š„`getInitialProps`ใ€‚ <add> <add><a id="using-a-higher-order-component" style="display: none"></a> <add>#### ้ซ˜้˜ถ็ป„ไปถ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul> <add> <li><a href="./examples/using-with-router">Using the `withRouter` utility</a></li> <add> </ul> <add></details></p> <add> <add>ๅฆ‚ๆžœไฝ ๆƒณๅบ”็”จ้‡Œๆฏไธช็ป„ไปถ้ƒฝๅค„็†่ทฏ็”ฑๅฏน่ฑก๏ผŒไฝ ๅฏไปฅไฝฟ็”จ`withRouter`้ซ˜้˜ถ็ป„ไปถใ€‚ไธ‹้ขๆ˜ฏๅฆ‚ไฝ•ไฝฟ็”จๅฎƒ๏ผš <add> <add>```jsx <add>import { withRouter } from 'next/router' <add> <add>const ActiveLink = ({ children, router, href }) => { <add> const style = { <add> marginRight: 10, <add> color: router.pathname === href? 'red' : 'black' <add> } <add> <add> const handleClick = (e) => { <add> e.preventDefault() <add> router.push(href) <add> } <add> <add> return ( <add> <a href={href} onClick={handleClick} style={style}> <add> {children} <add> </a> <add> ) <add>} <add> <add>export default withRouter(ActiveLink) <add>``` <add> <add>ไธŠ้ข่ทฏ็”ฑๅฏน่ฑก็š„ API ๅฏไปฅๅ‚่€ƒ[`next/router`](#imperatively). <add> <add><a id="prefetching-pages" style="display: none"></a> <add>### ้ข„ๅŠ ่ฝฝ้กต้ข <add> <add>โš ๏ธ ๅชๆœ‰็”Ÿไบง็Žฏๅขƒๆ‰ๆœ‰ๆญคๅŠŸ่ƒฝ โš ๏ธ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul><li><a href="./examples/with-prefetching">Prefetching</a></li></ul> <add></details></p> <add> <add>Next.js ๆœ‰ๅ…่ฎธไฝ ้ข„ๅŠ ่ฝฝ้กต้ข็š„ APIใ€‚ <add> <add>็”จ Next.js ๆœๅŠก็ซฏๆธฒๆŸ“ไฝ ็š„้กต้ข๏ผŒๅฏไปฅ่พพๅˆฐๆ‰€ๆœ‰ไฝ ๅบ”็”จ้‡Œๆ‰€ๆœ‰ๆœชๆฅไผš่ทณ่ฝฌ็š„่ทฏๅพ„ๅณๆ—ถๅ“ๅบ”๏ผŒๆœ‰ๆ•ˆ็š„ๅบ”็”จ Next.js๏ผŒๅฏไปฅ้€š่ฟ‡้ข„ๅŠ ่ฝฝๅบ”็”จ็จ‹ๅบ็š„ๅŠŸ่ƒฝ๏ผŒๆœ€ๅคง็จ‹ๅบฆ็š„ๅˆๅง‹ๅŒ–็ฝ‘็ซ™ๆ€ง่ƒฝใ€‚[ๆŸฅ็œ‹ๆ›ดๅคš](https://zeit.co/blog/next#anticipation-is-the-key-to-performance). <add> <add>> Next.js ็š„้ข„ๅŠ ่ฝฝๅŠŸ่ƒฝๅช้ข„ๅŠ ่ฝฝ JS ไปฃ็ ใ€‚ๅฝ“้กต้ขๆธฒๆŸ“ๆ—ถ๏ผŒไฝ ๅฏ่ƒฝ้œ€่ฆ็ญ‰ๅพ…ๆ•ฐๆฎ่ฏทๆฑ‚ใ€‚ <add> <add><a id="with-link-1" style="display: none"></a> <add>#### `<Link>`็”จๆณ• <add> <add>ไฝ ๅฏไปฅ็ป™<Link>ๆทปๅŠ  `prefetch` ๅฑžๆ€ง๏ผŒNext.js ๅฐ†ไผšๅœจๅŽๅฐ้ข„ๅŠ ่ฝฝ่ฟ™ไบ›้กต้ขใ€‚ <add> <add>```jsx <add>import Link from 'next/link' <add> <add>// example header component <add>export default () => <add> <nav> <add> <ul> <add> <li> <add> <Link prefetch href="/"> <add> <a>Home</a> <add> </Link> <add> </li> <add> <li> <add> <Link prefetch href="/about"> <add> <a>About</a> <add> </Link> <add> </li> <add> <li> <add> <Link prefetch href="/contact"> <add> <a>Contact</a> <add> </Link> <add> </li> <add> </ul> <add> </nav> <add>``` <add> <add><a id="imperatively-1" style="display: none"></a> <add>#### ๅ‘ฝไปคๅผ prefetch ๅ†™ๆณ• <add> <add>ๅคงๅคšๆ•ฐ้ข„ๅŠ ่ฝฝๆ˜ฏ้€š่ฟ‡<Link />ๅค„็†็š„๏ผŒไฝ†ๆ˜ฏๆˆ‘ไปฌ่ฟ˜ๆไพ›ไบ†ๅ‘ฝไปคๅผ API ็”จไบŽๆ›ดๅคๆ‚็š„ๅœบๆ™ฏใ€‚ <add> <add>```jsx <add>import { withRouter } from 'next/router' <add> <add>export default withRouter(({ router }) => <add> <div> <add> <a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}> <add> A route transition will happen after 100ms <add> </a> <add> {// but we can prefetch it! <add> router.prefetch('/dynamic')} <add> </div> <add>) <add>``` <add> <add>่ทฏ็”ฑๅฎžไพ‹ๅชๅ…่ฎธๅœจๅบ”็”จ็จ‹ๅบ็š„ๅฎขๆˆท็ซฏใ€‚ไปฅ้˜ฒๆœๅŠก็ซฏๆธฒๆŸ“ๅ‘็”Ÿ้”™่ฏฏ๏ผŒๅปบ่ฎฎ prefetch ไบ‹ไปถๅ†™ๅœจ`componentDidMount()`็”Ÿๅ‘ฝๅ‘จๆœŸ้‡Œใ€‚ <add> <add>```jsx <add>import React from 'react' <add>import { withRouter } from 'next/router' <add> <add>class MyLink extends React.Component { <add> componentDidMount() { <add> const { router } = this.props <add> router.prefetch('/dynamic') <add> } <add> <add> render() { <add> const { router } = this.props <add> return ( <add> <div> <add> <a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}> <add> A route transition will happen after 100ms <add> </a> <add> </div> <add> ) <add> } <add>} <add> <add>export default withRouter(MyLink) <add>``` <add> <add><a id="custom-server-and-routing" style="display: none"></a> <add>### ่‡ชๅฎšไน‰ๆœๅŠก็ซฏ่ทฏ็”ฑ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul> <add> <li><a href="./examples/custom-server">Basic custom server</a></li> <add> <li><a href="./examples/custom-server-express">Express integration</a></li> <add> <li><a href="./examples/custom-server-hapi">Hapi integration</a></li> <add> <li><a href="./examples/custom-server-koa">Koa integration</a></li> <add> <li><a href="./examples/parameterized-routing">Parameterized routing</a></li> <add> <li><a href="./examples/ssr-caching">SSR caching</a></li> <add> </ul> <add></details></p> <add> <add> <add>ไธ€่ˆฌไฝ ไฝฟ็”จ`next start`ๅ‘ฝไปคๆฅๅฏๅŠจ next ๆœๅŠก๏ผŒไฝ ่ฟ˜ๅฏไปฅ็ผ–ๅ†™ไปฃ็ ๆฅ่‡ชๅฎšไน‰่ทฏ็”ฑ๏ผŒๅฆ‚ไฝฟ็”จ่ทฏ็”ฑๆญฃๅˆ™็ญ‰ใ€‚ <add> <add>ๅฝ“ไฝฟ็”จ่‡ชๅฎšไน‰ๆœๅŠกๆ–‡ไปถ๏ผŒๅฆ‚ไธ‹้ขไพ‹ๅญๆ‰€็คบๅซ server.js ๆ—ถ๏ผŒ็กฎไฟไฝ ๆ›ดๆ–ฐไบ† package.json ไธญ็š„่„šๆœฌใ€‚ <add> <add>```json <add>{ <add> "scripts": { <add> "dev": "node server.js", <add> "build": "next build", <add> "start": "NODE_ENV=production node server.js" <add> } <add>} <add>``` <add> <add>ไธ‹้ข่ฟ™ไธชไพ‹ๅญไฝฟ `/a` ่ทฏ็”ฑ่งฃๆžไธบ`./pages/b`๏ผŒไปฅๅŠ`/b` ่ทฏ็”ฑ่งฃๆžไธบ`./pages/a`; <add> <add>```js <add>// This file doesn't go through babel or webpack transformation. <add>// Make sure the syntax and sources this file requires are compatible with the current node version you are running <add>// See https://github.com/zeit/next.js/issues/1245 for discussions on Universal Webpack or universal Babel <add>const { createServer } = require('http') <add>const { parse } = require('url') <add>const next = require('next') <add> <add>const dev = process.env.NODE_ENV !== 'production' <add>const app = next({ dev }) <add>const handle = app.getRequestHandler() <add> <add>app.prepare().then(() => { <add> createServer((req, res) => { <add> // Be sure to pass `true` as the second argument to `url.parse`. <add> // This tells it to parse the query portion of the URL. <add> const parsedUrl = parse(req.url, true) <add> const { pathname, query } = parsedUrl <add> <add> if (pathname === '/a') { <add> app.render(req, res, '/b', query) <add> } else if (pathname === '/b') { <add> app.render(req, res, '/a', query) <add> } else { <add> handle(req, res, parsedUrl) <add> } <add> }).listen(3000, err => { <add> if (err) throw err <add> console.log('> Ready on http://localhost:3000') <add> }) <add>}) <add>``` <add> <add>`next`็š„ API ๅฆ‚ไธ‹ๆ‰€็คบ <add>- `next(opts: object)` <add> <add>opts ็š„ๅฑžๆ€งๅฆ‚ไธ‹: <add>- `dev` (`boolean`) ๅˆคๆ–ญ Next.js ๅบ”็”จๆ˜ฏๅฆๅœจๅผ€ๅ‘็Žฏๅขƒ - ้ป˜่ฎค`false` <add>- `dir` (`string`) Next ้กน็›ฎ่ทฏๅพ„ - ้ป˜่ฎค`'.'` <add>- `quiet` (`boolean`) ๆ˜ฏๅฆ้š่—ๅŒ…ๅซๆœๅŠก็ซฏๆถˆๆฏๅœจๅ†…็š„้”™่ฏฏไฟกๆฏ - ้ป˜่ฎค`false` <add>- `conf` (`object`) ไธŽ`next.config.js`็š„ๅฏน่ฑก็›ธๅŒ - ้ป˜่ฎค`{}` <add> <add>็”Ÿไบง็Žฏๅขƒ็š„่ฏ๏ผŒๅฏไปฅๆ›ดๆ”น package.json ้‡Œ็š„`start`่„šๆœฌไธบ`NODE_ENV=production node server.js`ใ€‚ <add> <add><a id="disabling-file-system-routing" style="display: none"></a> <add>#### ็ฆๆญขๆ–‡ไปถ่ทฏ็”ฑ <add>้ป˜่ฎคๆƒ…ๅ†ต๏ผŒ`Next`ๅฐ†ไผšๆŠŠ`/pages`ไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถๅŒน้…่ทฏ็”ฑ๏ผˆๅฆ‚`/pages/some-file.js` ๆธฒๆŸ“ไธบ `site.com/some-file`๏ผ‰ <add> <add>ๅฆ‚ๆžœไฝ ็š„้กน็›ฎไฝฟ็”จ่‡ชๅฎšไน‰่ทฏ็”ฑ๏ผŒ้‚ฃไนˆๆœ‰ๅฏ่ƒฝไธๅŒ็š„่ทฏ็”ฑไผšๅพ—ๅˆฐ็›ธๅŒ็š„ๅ†…ๅฎน๏ผŒๅฏไปฅไผ˜ๅŒ– SEO ๅ’Œ็”จๆˆทไฝ“้ชŒใ€‚ <add> <add>็ฆๆญข่ทฏ็”ฑ้“พๆŽฅๅˆฐ`/pages`ไธ‹็š„ๆ–‡ไปถ๏ผŒๅช้œ€่ฎพ็ฝฎ`next.config.js`ๆ–‡ไปถๅฆ‚ไธ‹ๆ‰€็คบ๏ผš <add> <add>```js <add>// next.config.js <add>module.exports = { <add> useFileSystemPublicRoutes: false <add>} <add>``` <add> <add>ๆณจๆ„`useFileSystemPublicRoutes`ๅช็ฆๆญขๆœๅŠก็ซฏ็š„ๆ–‡ไปถ่ทฏ็”ฑ๏ผ›ไฝ†ๆ˜ฏๅฎขๆˆท็ซฏ็š„่ฟ˜ๆ˜ฏ็ฆๆญขไธไบ†ใ€‚ <add> <add>ไฝ ๅฆ‚ๆžœๆƒณ้…็ฝฎๅฎขๆˆท็ซฏ่ทฏ็”ฑไธ่ƒฝ่ทณ่ฝฌๆ–‡ไปถ่ทฏ็”ฑ๏ผŒๅฏไปฅๅ‚่€ƒ[Intercepting `popstate`](#intercepting-popstate)ใ€‚ <add> <add><a id="dynamic-assetprefix" style="display: none"></a> <add>#### ๅŠจๆ€ๅ‰็ผ€ <add> <add>ๆœ‰ๆ—ถไฝ ้œ€่ฆ่ฎพ็ฝฎๅŠจๆ€ๅ‰็ผ€๏ผŒๅฏไปฅๅœจ่ฏทๆฑ‚ๆ—ถ่ฎพ็ฝฎ`assetPrefix`ๆ”นๅ˜ๅ‰็ผ€ใ€‚ <add> <add>ไฝฟ็”จๆ–นๆณ•ๅฆ‚ไธ‹๏ผš <add> <add>```js <add>const next = require('next') <add>const micro = require('micro') <add> <add>const dev = process.env.NODE_ENV !== 'production' <add>const app = next({ dev }) <add>const handleNextRequests = app.getRequestHandler() <add> <add>app.prepare().then(() => { <add> const server = micro((req, res) => { <add> // Add assetPrefix support based on the hostname <add> if (req.headers.host === 'my-app.com') { <add> app.setAssetPrefix('http://cdn.com/myapp') <add> } else { <add> app.setAssetPrefix('') <add> } <add> <add> handleNextRequests(req, res) <add> }) <add> <add> server.listen(port, (err) => { <add> if (err) { <add> throw err <add> } <add> <add> console.log(`> Ready on http://localhost:${port}`) <add> }) <add>}) <add> <add>``` <add> <add><a id="dynamic-import" style="display: none"></a> <add>### ๅŠจๆ€ๅฏผๅ…ฅ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul> <add> <li><a href="./examples/with-dynamic-import">With Dynamic Import</a></li> <add> </ul> <add></details></p> <add> <add>ext.js ๆ”ฏๆŒ JavaScript ็š„ TC39 ๆ่ฎฎ[dynamic import proposal](https://github.com/tc39/proposal-dynamic-import)ใ€‚ไฝ ๅฏไปฅๅŠจๆ€ๅฏผๅ…ฅ JavaScript ๆจกๅ—๏ผˆๅฆ‚ React ็ป„ไปถ๏ผ‰ใ€‚ <add> <add>ๅŠจๆ€ๅฏผๅ…ฅ็›ธๅฝ“ไบŽๆŠŠไปฃ็ ๅˆ†ๆˆๅ„ไธชๅ—็ฎก็†ใ€‚Next.js ๆœๅŠก็ซฏๅŠจๆ€ๅฏผๅ…ฅๅŠŸ่ƒฝ๏ผŒไฝ ๅฏไปฅๅšๅพˆๅคš็‚ซ้…ทไบ‹ๆƒ…ใ€‚ <add> <add>ไธ‹้ขไป‹็ปไธ€ไบ›ๅŠจๆ€ๅฏผๅ…ฅๆ–นๅผ๏ผš <add> <add><a id="1-basic-usage-also-does-ssr" style="display: none"></a> <add>#### 1. ๅŸบ็ก€ๆ”ฏๆŒ (ๅŒๆ ทๆ”ฏๆŒ SSR) <add> <add>```jsx <add>import dynamic from 'next/dynamic' <add> <add>const DynamicComponent = dynamic(import('../components/hello')) <add> <add>export default () => <add> <div> <add> <Header /> <add> <DynamicComponent /> <add> <p>HOME PAGE is here!</p> <add> </div> <add>``` <add> <add><a id="2-with-custom-loading-componen" style="display: none"></a> <add>#### 2. ่‡ชๅฎšไน‰ๅŠ ่ฝฝ็ป„ไปถ <add> <add>```jsx <add>import dynamic from 'next/dynamic' <add> <add>const DynamicComponentWithCustomLoading = dynamic( <add> import('../components/hello2'), <add> { <add> loading: () => <p>...</p> <add> } <add>) <add> <add>export default () => <add> <div> <add> <Header /> <add> <DynamicComponentWithCustomLoading /> <add> <p>HOME PAGE is here!</p> <add> </div> <add>``` <add> <add><a id="3-with-no-ssr" style="display: none"></a> <add>#### 3. ็ฆๆญขไฝฟ็”จ SSR <add> <add>```jsx <add>import dynamic from 'next/dynamic' <add> <add>const DynamicComponentWithNoSSR = dynamic(import('../components/hello3'), { <add> ssr: false <add>}) <add> <add>export default () => <add> <div> <add> <Header /> <add> <DynamicComponentWithNoSSR /> <add> <p>HOME PAGE is here!</p> <add> </div> <add>``` <add> <add><a id="4-with-multiple-modules-at-once" style="display: none"></a> <add>#### 4. ๅŒๆ—ถๅŠ ่ฝฝๅคšไธชๆจกๅ— <add> <add>```jsx <add>import dynamic from 'next/dynamic' <add> <add>const HelloBundle = dynamic({ <add> modules: () => { <add> const components = { <add> Hello1: import('../components/hello1'), <add> Hello2: import('../components/hello2') <add> } <add> <add> return components <add> }, <add> render: (props, { Hello1, Hello2 }) => <add> <div> <add> <h1> <add> {props.title} <add> </h1> <add> <Hello1 /> <add> <Hello2 /> <add> </div> <add>}) <add> <add>export default () => <HelloBundle title="Dynamic Bundle" /> <add>``` <add> <add><a id="custom-app" style="display: none"></a> <add>### ่‡ชๅฎšไน‰ `<App>` <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul><li><a href="./examples/with-app-layout">Using `_app.js` for layout</a></li></ul> <add> <ul><li><a href="./examples/with-componentdidcatch">Using `_app.js` to override `componentDidCatch`</a></li></ul> <add></details></p> <add> <add>็ป„ไปถๆฅๅˆๅง‹ๅŒ–้กต้ขใ€‚ไฝ ๅฏไปฅ้‡ๅ†™ๅฎƒๆฅๆŽงๅˆถ้กต้ขๅˆๅง‹ๅŒ–๏ผŒๅฆ‚ไธ‹้ข็š„ไบ‹๏ผš <add> <add>- ๅฝ“้กต้ขๅ˜ๅŒ–ๆ—ถไฟๆŒ้กต้ขๅธƒๅฑ€ <add>- ๅฝ“่ทฏ็”ฑๅ˜ๅŒ–ๆ—ถไฟๆŒ้กต้ข็Šถๆ€ <add>- ไฝฟ็”จ`componentDidCatch`่‡ชๅฎšไน‰ๅค„็†้”™่ฏฏ <add>- ๆณจๅ…ฅ้ขๅค–ๆ•ฐๆฎๅˆฐ้กต้ข้‡Œ (ๅฆ‚ GraphQL ๆŸฅ่ฏข) <add> <add>้‡ๅ†™็š„่ฏ๏ผŒๆ–ฐๅปบ`./pages/_app.js`ๆ–‡ไปถ๏ผŒ้‡ๅ†™ App ๆจกๅ—ๅฆ‚ไธ‹ๆ‰€็คบ๏ผš <add> <add>```js <add>import App, {Container} from 'next/app' <add>import React from 'react' <add> <add>export default class MyApp extends App { <add> static async getInitialProps ({ Component, router, ctx }) { <add> let pageProps = {} <add> <add> if (Component.getInitialProps) { <add> pageProps = await Component.getInitialProps(ctx) <add> } <add> <add> return {pageProps} <add> } <add> <add> render () { <add> const {Component, pageProps} = this.props <add> return <Container> <add> <Component {...pageProps} /> <add> </Container> <add> } <add>} <add>``` <add> <add><a id="custom-document" style="display: none"></a> <add>### ่‡ชๅฎšไน‰ `<Document>` <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul><li><a href="./examples/with-styled-components">Styled components custom document</a></li></ul> <add> <ul><li><a href="./examples/with-amp">Google AMP</a></li></ul> <add></details></p> <add> <add>- ๅœจๆœๅŠก็ซฏๅ‘ˆ็Žฐ <add>- ๅˆๅง‹ๅŒ–ๆœๅŠก็ซฏๆ—ถๆทปๅŠ ๆ–‡ๆกฃๆ ‡่ฎฐๅ…ƒ็ด  <add>- ้€šๅธธๅฎž็ŽฐๆœๅŠก็ซฏๆธฒๆŸ“ไผšไฝฟ็”จไธ€ไบ› css-in-js ๅบ“๏ผŒๅฆ‚[styled-components](./examples/with-styled-components), [glamorous](./examples/with-glamorous) ๆˆ– [emotion](with-emotion)ใ€‚[styled-jsx](https://github.com/zeit/styled-jsx)ๆ˜ฏ Next.js ่‡ชๅธฆ้ป˜่ฎคไฝฟ็”จ็š„ css-in-js ๅบ“ <add> <add>`Next.js`ไผš่‡ชๅŠจๅฎšไน‰ๆ–‡ๆกฃๆ ‡่ฎฐ๏ผŒๆฏ”ๅฆ‚๏ผŒไฝ ไปŽๆฅไธ้œ€่ฆๆทปๅŠ `<html>`, `<body>`็ญ‰ใ€‚ๅฆ‚ๆžœๆƒณ่‡ชๅฎšไน‰ๆ–‡ๆกฃๆ ‡่ฎฐ๏ผŒไฝ ๅฏไปฅๆ–ฐๅปบ`./pages/_document.js`๏ผŒ็„ถๅŽๆ‰ฉๅฑ•`Document`็ฑป๏ผš <add> <add>```jsx <add>// _document is only rendered on the server side and not on the client side <add>// Event handlers like onClick can't be added to this file <add> <add>// ./pages/_document.js <add>import Document, { Head, Main, NextScript } from 'next/document' <add> <add>export default class MyDocument extends Document { <add> static async getInitialProps(ctx) { <add> const initialProps = await Document.getInitialProps(ctx) <add> return { ...initialProps } <add> } <add> <add> render() { <add> return ( <add> <html> <add> <Head> <add> <style>{`body { margin: 0 } /* custom! */`}</style> <add> </Head> <add> <body className="custom_class"> <add> <Main /> <add> <NextScript /> <add> </body> <add> </html> <add> ) <add> } <add>} <add>``` <add> <add>้’ฉๅญ[`getInitialProps`](#fetching-data-and-component-lifecycle)ๆŽฅๆ”ถๅˆฐ็š„ๅ‚ๆ•ฐ`ctx`ๅฏน่ฑก้ƒฝๆ˜ฏไธ€ๆ ท็š„ <add> <add>- ๅ›ž่ฐƒๅ‡ฝๆ•ฐ`renderPage`ๆ˜ฏไผšๆ‰ง่กŒ React ๆธฒๆŸ“้€ป่พ‘็š„ๅ‡ฝๆ•ฐ(ๅŒๆญฅ)๏ผŒ่ฟ™็งๅšๆณ•ๆœ‰ๅŠฉไบŽๆญคๅ‡ฝๆ•ฐๆ”ฏๆŒไธ€ไบ›็ฑปไผผไบŽ Aphrodite ็š„ renderStatic ็ญ‰ไธ€ไบ›ๆœๅŠกๅ™จ็ซฏๆธฒๆŸ“ๅฎนๅ™จใ€‚ <add> <add>__ๆณจๆ„๏ผš`<Main />`ๅค–็š„ React ็ป„ไปถๅฐ†ไธไผšๆธฒๆŸ“ๅˆฐๆต่งˆๅ™จไธญ๏ผŒๆ‰€ไปฅ้‚ฃๆทปๅŠ ๅบ”็”จ้€ป่พ‘ไปฃ็ ใ€‚ๅฆ‚ๆžœไฝ ้กต้ข้œ€่ฆๅ…ฌๅ…ฑ็ป„ไปถ๏ผˆ่œๅ•ๆˆ–ๅทฅๅ…ทๆ ๏ผ‰๏ผŒๅฏไปฅๅ‚็…งไธŠ้ข่ฏด็š„`App`็ป„ไปถไปฃๆ›ฟใ€‚__ <add> <add><a id="custom-error-handling" style="display: none"></a> <add>### ่‡ชๅฎšไน‰้”™่ฏฏๅค„็† <add> <add>404ๅ’Œ500้”™่ฏฏๅฎขๆˆท็ซฏๅ’ŒๆœๅŠก็ซฏ้ƒฝไผš้€š่ฟ‡`error.js`็ป„ไปถๅค„็†ใ€‚ๅฆ‚ๆžœไฝ ๆƒณๆ”นๅ†™ๅฎƒ๏ผŒๅˆ™ๆ–ฐๅปบ`_error.js`ๅœจๆ–‡ไปถๅคนไธญ๏ผš <add> <add>```jsx <add>import React from 'react' <add> <add>export default class Error extends React.Component { <add> static getInitialProps({ res, err }) { <add> const statusCode = res ? res.statusCode : err ? err.statusCode : null; <add> return { statusCode } <add> } <add> <add> render() { <add> return ( <add> <p> <add> {this.props.statusCode <add> ? `An error ${this.props.statusCode} occurred on server` <add> : 'An error occurred on client'} <add> </p> <add> ) <add> } <add>} <add>``` <add> <add><a id="reusing-the-built-in-error-page" style="display: none"></a> <add>### ๆธฒๆŸ“ๅ†…็ฝฎ้”™่ฏฏ้กต้ข <add> <add>ๅฆ‚ๆžœไฝ ๆƒณๆธฒๆŸ“ๅ†…็ฝฎ้”™่ฏฏ้กต้ข๏ผŒไฝ ๅฏไปฅไฝฟ็”จ`next/error`๏ผš <add> <add>```jsx <add>import React from 'react' <add>import Error from 'next/error' <add>import fetch from 'isomorphic-unfetch' <add> <add>export default class Page extends React.Component { <add> static async getInitialProps() { <add> const res = await fetch('https://api.github.com/repos/zeit/next.js') <add> const statusCode = res.statusCode > 200 ? res.statusCode : false <add> const json = await res.json() <add> <add> return { statusCode, stars: json.stargazers_count } <add> } <add> <add> render() { <add> if (this.props.statusCode) { <add> return <Error statusCode={this.props.statusCode} /> <add> } <add> <add> return ( <add> <div> <add> Next stars: {this.props.stars} <add> </div> <add> ) <add> } <add>} <add>``` <add> <add>> ๅฆ‚ๆžœไฝ ่‡ชๅฎšไน‰ไบ†ไธช้”™่ฏฏ้กต้ข๏ผŒไฝ ๅฏไปฅๅผ•ๅ…ฅ่‡ชๅทฑ็š„้”™่ฏฏ้กต้ขๆฅไปฃๆ›ฟ`next/error` <add> <add><a id="custom-configuration" style="display: none"></a> <add>### ่‡ชๅฎšไน‰้…็ฝฎ <add> <add>ๅฆ‚ๆžœไฝ ๆƒณ่‡ชๅฎšไน‰ Next.js ็š„้ซ˜็บง้…็ฝฎ๏ผŒๅฏไปฅๅœจๆ น็›ฎๅฝ•ไธ‹ๆ–ฐๅปบ`next.config.js`ๆ–‡ไปถ๏ผˆไธŽ`pages/` ๅ’Œ `package.json`ไธ€่ตท๏ผ‰ <add> <add>ๆณจๆ„๏ผš`next.config.js`ๆ˜ฏไธ€ไธช Node.js ๆจกๅ—๏ผŒไธๆ˜ฏไธ€ไธช JSON ๆ–‡ไปถ๏ผŒๅฏไปฅ็”จไบŽ Next ๅฏๅŠจๆœๅŠกๅทฒ็ปๆž„ๅปบ้˜ถๆฎต๏ผŒไฝ†ๆ˜ฏไธไฝœ็”จไบŽๆต่งˆๅ™จ็ซฏใ€‚ <add> <add>```js <add>// next.config.js <add>module.exports = { <add> /* config options here */ <add>} <add>``` <add> <add>ๆˆ–ไฝฟ็”จไธ€ไธชๅ‡ฝๆ•ฐ๏ผš <add> <add>```js <add>module.exports = (phase, {defaultConfig}) => { <add> // <add> // https://github.com/zeit/ <add> return { <add> /* config options here */ <add> } <add>} <add>``` <add> <add>`phase`ๆ˜ฏ้…็ฝฎๆ–‡ไปถ่ขซๅŠ ่ฝฝๆ—ถ็š„ๅฝ“ๅ‰ๅ†…ๅฎนใ€‚ไฝ ๅฏ็œ‹ๅˆฐๆ‰€ๆœ‰็š„ phases ๅธธ้‡๏ผš[constants](./lib/constants.js) <add>่ฟ™ไบ›ๅธธ้‡ๅฏไปฅ้€š่ฟ‡`next/constants`ๅผ•ๅ…ฅ๏ผš <add> <add>```js <add>const {PHASE_DEVELOPMENT_SERVER} = require('next/constants') <add>module.exports = (phase, {defaultConfig}) => { <add> if(phase === PHASE_DEVELOPMENT_SERVER) { <add> return { <add> /* development only config options here */ <add> } <add> } <add> <add> return { <add> /* config options for all phases except development here */ <add> } <add>} <add>``` <add> <add><a id="setting-a-custom-build-directory" style="display: none"></a> <add>#### ่ฎพ็ฝฎ่‡ชๅฎšไน‰ๆž„ๅปบ็›ฎๅฝ• <add> <add>ไฝ ๅฏไปฅ่‡ชๅฎšไน‰ไธ€ไธชๆž„ๅปบ็›ฎๅฝ•๏ผŒๅฆ‚ๆ–ฐๅปบ`build`ๆ–‡ไปถๅคนๆฅไปฃๆ›ฟ`.next` ๆ–‡ไปถๅคนๆˆไธบๆž„ๅปบ็›ฎๅฝ•ใ€‚ๅฆ‚ๆžœๆฒกๆœ‰้…็ฝฎๆž„ๅปบ็›ฎๅฝ•๏ผŒๆž„ๅปบๆ—ถๅฐ†ไผš่‡ชๅŠจๆ–ฐๅปบ`.next`ๆ–‡ไปถๅคน <add> <add>```js <add>// next.config.js <add>module.exports = { <add> distDir: 'build' <add>} <add>``` <add> <add><a id="disabling-etag-generation" style="display: none"></a> <add>#### ็ฆๆญข etag ็”Ÿๆˆ <add> <add>ไฝ ๅฏไปฅ็ฆๆญข etag ็”Ÿๆˆๆ นๆฎไฝ ็š„็ผ“ๅญ˜็ญ–็•ฅใ€‚ๅฆ‚ๆžœๆฒกๆœ‰้…็ฝฎ๏ผŒNext ๅฐ†ไผš็”Ÿๆˆ etags ๅˆฐๆฏไธช้กต้ขไธญใ€‚ <add> <add>```js <add>// next.config.js <add>module.exports = { <add> generateEtags: false <add>} <add>``` <add> <add><a id="configuring-the-ondemandentries" style="display: none"></a> <add>#### ้…็ฝฎ onDemandEntries <add> <add>Next ๆšด้œฒไธ€ไบ›้€‰้กนๆฅ็ป™ไฝ ๆŽงๅˆถๆœๅŠกๅ™จ้ƒจ็ฝฒไปฅๅŠ็ผ“ๅญ˜้กต้ข๏ผš <add> <add>```js <add>module.exports = { <add> onDemandEntries: { <add> // period (in ms) where the server will keep pages in the buffer <add> maxInactiveAge: 25 * 1000, <add> // number of pages that should be kept simultaneously without being disposed <add> pagesBufferLength: 2, <add> } <add>} <add>``` <add> <add>่ฟ™ไธชๅชๆ˜ฏๅœจๅผ€ๅ‘็Žฏๅขƒๆ‰ๆœ‰็š„ๅŠŸ่ƒฝใ€‚ๅฆ‚ๆžœไฝ ๅœจ็”Ÿๆˆ็Žฏๅขƒไธญๆƒณ็ผ“ๅญ˜ SSR ้กต้ข๏ผŒ่ฏทๆŸฅ็œ‹[SSR-caching](https://github.com/zeit/next.js/tree/canary/examples/ssr-caching) <add> <add><a id="configuring-extensions-looked-for-when-resolving-pages-in-pages" style="display: none"></a> <add>#### ้…็ฝฎ้กต้ขๅŽ็ผ€ๅ่งฃๆžๆ‰ฉๅฑ• <add> <add>ๅฆ‚ typescript ๆจกๅ—[`@zeit/next-typescript`](https://github.com/zeit/next-plugins/tree/master/packages/next-typescript)๏ผŒ้œ€่ฆๆ”ฏๆŒ่งฃๆžๅŽ็ผ€ๅไธบ`.ts`็š„ๆ–‡ไปถใ€‚`pageExtensions` ๅ…่ฎธไฝ ๆ‰ฉๅฑ•ๅŽ็ผ€ๅๆฅ่งฃๆžๅ„็ง pages ไธ‹็š„ๆ–‡ไปถใ€‚ <add> <add>```js <add>// next.config.js <add>module.exports = { <add> pageExtensions: ['jsx', 'js'] <add>} <add>``` <add> <add><a id="configuring-the-build-id" style="display: none"></a> <add>#### ้…็ฝฎๆž„ๅปบ ID <add> <add>Next.js ไฝฟ็”จๆž„ๅปบๆ—ถ็”Ÿๆˆ็š„ๅธธ้‡ๆฅๆ ‡่ฏ†ไฝ ็š„ๅบ”็”จๆœๅŠกๆ˜ฏๅ“ชไธช็‰ˆๆœฌใ€‚ๅœจๆฏๅฐๆœๅŠกๅ™จไธŠ่ฟ่กŒๆž„ๅปบๅ‘ฝไปคๆ—ถ๏ผŒๅฏ่ƒฝไผšๅฏผ่‡ดๅคšๆœๅŠกๅ™จ้ƒจ็ฝฒๅ‡บ็Žฐ้—ฎ้ข˜ใ€‚ไธบไบ†ไฟๆŒๅŒไธ€ไธชๆž„ๅปบ ID๏ผŒๅฏไปฅ้…็ฝฎ`generateBuildId`ๅ‡ฝๆ•ฐ๏ผš <add> <add>```js <add>// next.config.js <add>module.exports = { <add> generateBuildId: async () => { <add> // For example get the latest git commit hash here <add> return 'my-build-id' <add> } <add>} <add>``` <add> <add><a id="customizing-webpack-config" style="display: none"></a> <add>### ่‡ชๅฎšไน‰ webpack ้…็ฝฎ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul><li><a href="./examples/with-webpack-bundle-analyzer">Custom webpack bundle analyzer</a></li></ul> <add></details></p> <add> <add>ๅฏไปฅไฝฟ็”จไบ›ไธ€ไบ›ๅธธ่ง็š„ๆจกๅ— <add> <add>- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css) <add>- [@zeit/next-sass](https://github.com/zeit/next-plugins/tree/master/packages/next-sass) <add>- [@zeit/next-less](https://github.com/zeit/next-plugins/tree/master/packages/next-less) <add>- [@zeit/next-preact](https://github.com/zeit/next-plugins/tree/master/packages/next-preact) <add>- [@zeit/next-typescript](https://github.com/zeit/next-plugins/tree/master/packages/next-typescript) <add> <add>*ๆณจๆ„๏ผš `webpack`ๆ–นๆณ•ๅฐ†่ขซๆ‰ง่กŒไธคๆฌก๏ผŒไธ€ๆฌกๅœจๆœๅŠก็ซฏไธ€ๆฌกๅœจๅฎขๆˆท็ซฏใ€‚ไฝ ๅฏไปฅ็”จ`isServer`ๅฑžๆ€งๅŒบๅˆ†ๅฎขๆˆท็ซฏๅ’ŒๆœๅŠก็ซฏๆฅ้…็ฝฎ* <add> <add>ๅคš้…็ฝฎๅฏไปฅ็ป„ๅˆๅœจไธ€่ตท๏ผŒๅฆ‚๏ผš <add> <add>```js <add>const withTypescript = require('@zeit/next-typescript') <add>const withSass = require('@zeit/next-sass') <add> <add>module.exports = withTypescript(withSass({ <add> webpack(config, options) { <add> // Further custom configuration here <add> return config <add> } <add>})) <add>``` <add> <add>ไธบไบ†ๆ‰ฉๅฑ•`webpack`ไฝฟ็”จ๏ผŒๅฏไปฅๅœจ`next.config.js`ๅฎšไน‰ๅ‡ฝๆ•ฐใ€‚ <add> <add>```js <add>// next.config.js is not transformed by Babel. So you can only use javascript features supported by your version of Node.js. <add> <add>module.exports = { <add> webpack: (config, { buildId, dev, isServer, defaultLoaders }) => { <add> // Perform customizations to webpack config <add> // Important: return the modified config <add> return config <add> }, <add> webpackDevMiddleware: config => { <add> // Perform customizations to webpack dev middleware config <add> // Important: return the modified config <add> return config <add> } <add>} <add>``` <add> <add>`webpack`็š„็ฌฌไบŒไธชๅ‚ๆ•ฐๆ˜ฏไธชๅฏน่ฑก๏ผŒไฝ ๅฏไปฅ่‡ชๅฎšไน‰้…็ฝฎๅฎƒ๏ผŒๅฏน่ฑกๅฑžๆ€งๅฆ‚ไธ‹ๆ‰€็คบ๏ผš <add> <add>- `buildId` - ๅญ—็ฌฆไธฒ็ฑปๅž‹๏ผŒๆž„ๅปบ็š„ๅ”ฏไธ€ๆ ‡็คบ <add>- `dev` - `Boolean`ๅž‹๏ผŒๅˆคๆ–ญไฝ ๆ˜ฏๅฆๅœจๅผ€ๅ‘็Žฏๅขƒไธ‹ <add>- `isServer` - `Boolean` ๅž‹๏ผŒไธบ`true`ไฝฟ็”จๅœจๆœๅŠก็ซฏ, ไธบ`false`ไฝฟ็”จๅœจๅฎขๆˆท็ซฏ. <add>- `defaultLoaders` - ๅฏน่ฑกๅž‹ ๏ผŒๅ†…้ƒจๅŠ ่ฝฝๅ™จ, ไฝ ๅฏไปฅๅฆ‚ไธ‹้…็ฝฎ <add> - `babel` - ๅฏน่ฑกๅž‹๏ผŒ้…็ฝฎ`babel-loader`. <add> - `hotSelfAccept` - ๅฏน่ฑกๅž‹๏ผŒ `hot-self-accept-loader`้…็ฝฎ้€‰้กน.่ฟ™ไธชๅŠ ่ฝฝๅ™จๅช่ƒฝ็”จไบŽ้ซ˜้˜ถๆกˆไพ‹ใ€‚ๅฆ‚ [`@zeit/next-typescript`](https://github.com/zeit/next-plugins/tree/master/packages/next-typescript)ๆทปๅŠ ้กถๅฑ‚ typescript ้กต้ขใ€‚ <add> <add>`defaultLoaders.babel`ไฝฟ็”จๆกˆไพ‹ๅฆ‚ไธ‹๏ผš <add> <add>```js <add>// Example next.config.js for adding a loader that depends on babel-loader <add>// This source was taken from the @zeit/next-mdx plugin source: <add>// https://github.com/zeit/next-plugins/blob/master/packages/next-mdx <add>module.exports = { <add> webpack: (config, {}) => { <add> config.module.rules.push({ <add> test: /\.mdx/, <add> use: [ <add> options.defaultLoaders.babel, <add> { <add> loader: '@mdx-js/loader', <add> options: pluginOptions.options <add> } <add> ] <add> }) <add> <add> return config <add> } <add>} <add>``` <add> <add><a id="customizing-babel-config" style="display: none"></a> <add>### ่‡ชๅฎšไน‰ babel ้…็ฝฎ <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul><li><a href="./examples/with-custom-babel-config">Custom babel configuration</a></li></ul> <add></details></p> <add> <add>ไธบไบ†ๆ‰ฉๅฑ•ๆ–นไพฟๆˆ‘ไปฌไฝฟ็”จ`babel`๏ผŒๅฏไปฅๅœจๅบ”็”จๆ น็›ฎๅฝ•ๆ–ฐๅปบ`.babelrc`ๆ–‡ไปถ๏ผŒ่ฏฅๆ–‡ไปถๅฏ้…็ฝฎใ€‚ <add> <add>ๅฆ‚ๆžœๆœ‰่ฏฅๆ–‡ไปถ๏ผŒๆˆ‘ไปฌๅฐ†ไผš่€ƒ่™‘ๆ•ฐๆฎๆบ๏ผŒๅ› ๆญคไนŸ้œ€่ฆๅฎšไน‰ next ้กน็›ฎ้œ€่ฆ็š„ไธœ่ฅฟ๏ผŒไนŸๅฐฑๆ˜ฏ `next/babel`้ข„่ฎพใ€‚ <add> <add>่ฟ™็ง่ฎพ่ฎกๆ–นๆกˆๅฐ†ไผšไฝฟไฝ ไธ่ฏงๅผ‚ไบŽๆˆ‘ไปฌๅฏไปฅๅฎšๅˆถ babel ้…็ฝฎใ€‚ <add> <add>ไธ‹้ขๆ˜ฏ`.babelrc`ๆ–‡ไปถๆกˆไพ‹๏ผš <add> <add>```json <add>{ <add> "presets": ["next/babel"], <add> "plugins": [] <add>} <add>``` <add> <add>`next/babel`้ข„่ฎพๅฏๅค„็†ๅ„็ง React ๅบ”็”จๆ‰€้œ€่ฆ็š„ๆƒ…ๅ†ตใ€‚ๅŒ…ๆ‹ฌ๏ผš <add> <add>- preset-env <add>- preset-react <add>- plugin-proposal-class-properties <add>- plugin-proposal-object-rest-spread <add>- plugin-transform-runtime <add>- styled-jsx <add> <add>presets / plugins ไธๅ…่ฎธๆทปๅŠ ๅˆฐ`.babelrc`ไธญ๏ผŒ็„ถ่€Œไฝ ๅฏไปฅ้…็ฝฎ`next/babel`้ข„่ฎพ๏ผš <add> <add>```json <add>{ <add> "presets": [ <add> ["next/babel", { <add> "preset-env": {}, <add> "transform-runtime": {}, <add> "styled-jsx": {}, <add> "class-properties": {} <add> }] <add> ], <add> "plugins": [] <add>} <add>``` <add> <add>`"preset-env"`ๆจกๅ—้€‰้กนๅบ”่ฏฅไฟๆŒไธบ false๏ผŒๅฆๅˆ™ webpack ไปฃ็ ๅˆ†ๅ‰ฒๅฐ†่ขซ็ฆ็”จใ€‚ <add> <add> <add><a id="exposing-configuration-to-the-server--client-side" style="display: none"></a> <add>### ๆšด้œฒ้…็ฝฎๅˆฐๆœๅŠก็ซฏๅ’Œๅฎขๆˆท็ซฏ <add> <add>`next/config`ๆจกๅ—ไฝฟไฝ ๅบ”็”จ่ฟ่กŒๆ—ถๅฏไปฅ่ฏปๅ–ไบ›ๅญ˜ๅ‚จๅœจ`next.config.js`็š„้…็ฝฎ้กนใ€‚`serverRuntimeConfig`ๅฑžๆ€งๅชๅœจๆœๅŠกๅ™จ็ซฏๅฏ็”จ๏ผŒ`publicRuntimeConfig`ๅฑžๆ€งๅœจๆœๅŠก็ซฏๅ’Œๅฎขๆˆท็ซฏๅฏ็”จใ€‚ <add> <add>```js <add>// next.config.js <add>module.exports = { <add> serverRuntimeConfig: { // Will only be available on the server side <add> mySecret: 'secret' <add> }, <add> publicRuntimeConfig: { // Will be available on both server and client <add> staticFolder: '/static', <add> mySecret: process.env.MY_SECRET // Pass through env variables <add> } <add>} <add>``` <add> <add>```js <add>// pages/index.js <add>import getConfig from 'next/config' <add>// Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else. <add>const {serverRuntimeConfig, publicRuntimeConfig} = getConfig() <add> <add>console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side <add>console.log(publicRuntimeConfig.staticFolder) // Will be available on both server and client <add> <add>export default () => <div> <add> <img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" /> <add></div> <add>``` <add> <add><a id="starting-the-server-on-alternative-hostname" style="display: none"></a> <add>### ๅฏๅŠจๆœๅŠก้€‰ๆ‹ฉ hostname <add> <add>ๅฏๅŠจๅผ€ๅ‘็ŽฏๅขƒๆœๅŠกๅฏไปฅ่ฎพ็ฝฎไธๅŒ็š„ hostname๏ผŒไฝ ๅฏไปฅๅœจๅฏๅŠจๅ‘ฝไปคๅŽ้ขๅŠ ไธŠ`--hostname ไธปๆœบๅ` ๆˆ– `-H ไธปๆœบๅ`ใ€‚ๅฎƒๅฐ†ไผšๅฏๅŠจไธ€ไธช TCP ๆœๅŠกๅ™จๆฅ็›‘ๅฌ่ฟžๆŽฅๆ‰€ๆไพ›็š„ไธปๆœบใ€‚ <add> <add><a id="cdn-support-with-asset-prefix" style="display: none"></a> <add>### CDN ๆ”ฏๆŒๅ‰็ผ€ <add> <add>ๅปบ็ซ‹ไธ€ไธช CDN๏ผŒไฝ ่ƒฝ้…็ฝฎ`assetPrefix`้€‰้กน๏ผŒๅŽป้…็ฝฎไฝ ็š„ CDN ๆบใ€‚ <add> <add>```js <add>const isProd = process.env.NODE_ENV === 'production' <add>module.exports = { <add> // You may only need to add assetPrefix in the production. <add> assetPrefix: isProd ? 'https://cdn.mydomain.com' : '' <add>} <add>``` <add> <add>ๆณจๆ„๏ผšNext.js ่ฟ่กŒๆ—ถๅฐ†ไผš่‡ชๅŠจๆทปๅŠ ๅ‰็ผ€๏ผŒไฝ†ๆ˜ฏๅฏนไบŽ`/static`ๆ˜ฏๆฒกๆœ‰ๆ•ˆๆžœ็š„๏ผŒๅฆ‚ๆžœไฝ ๆƒณ่ฟ™ไบ›้™ๆ€่ต„ๆบไนŸ่ƒฝไฝฟ็”จ CDN๏ผŒไฝ ้œ€่ฆ่‡ชๅทฑๆทปๅŠ ๅ‰็ผ€ใ€‚ๆœ‰ไธ€ไธชๆ–นๆณ•ๅฏไปฅๅˆคๆ–ญไฝ ็š„็ŽฏๅขƒๆฅๅŠ ๅ‰็ผ€๏ผŒๅฆ‚ [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration)ใ€‚ <add> <add><a id="production-deployment" style="display: none"></a> <add>## ้กน็›ฎ้ƒจ็ฝฒ <add> <add>้ƒจ็ฝฒไธญ๏ผŒไฝ ๅฏไปฅๅ…ˆๆž„ๅปบๆ‰“ๅŒ…็”Ÿๆˆ็Žฏๅขƒไปฃ็ ๏ผŒๅ†ๅฏๅŠจๆœๅŠกใ€‚ๅ› ๆญค๏ผŒๆž„ๅปบๅ’ŒๅฏๅŠจๅˆ†ไธบไธ‹้ขไธคๆกๅ‘ฝไปค๏ผš <add> <add>```bash <add>next build <add>next start <add>``` <add> <add>ไพ‹ๅฆ‚๏ผŒไฝฟ็”จ[`now`](https://zeit.co/now)ๅŽป้ƒจ็ฝฒ`package.json`้…็ฝฎๆ–‡ไปถๅฆ‚ไธ‹๏ผš <add> <add>```json <add>{ <add> "name": "my-app", <add> "dependencies": { <add> "next": "latest" <add> }, <add> "scripts": { <add> "dev": "next", <add> "build": "next build", <add> "start": "next start" <add> } <add>} <add>``` <add> <add>็„ถๅŽๅฐฑๅฏไปฅ็›ดๆŽฅ่ฟ่กŒ`now`ไบ†ใ€‚ <add> <add>Next.js ไนŸๆœ‰ๅ…ถไป–ๆ‰˜็ฎก่งฃๅ†ณๆ–นๆกˆใ€‚่ฏทๆŸฅ่€ƒ wiki ็ซ ่Š‚['Deployment'](https://github.com/zeit/next.js/wiki/Deployment) ใ€‚ <add> <add>ๆณจๆ„๏ผš`NODE_ENV`ๅฏไปฅ้€š่ฟ‡`next`ๅ‘ฝไปค้…็ฝฎ๏ผŒๅฆ‚ๆžœๆฒกๆœ‰้…็ฝฎ๏ผŒไผšๆœ€ๅคงๆธฒๆŸ“๏ผŒๅฆ‚ๆžœไฝ ไฝฟ็”จ็ผ–็จ‹ๅผๅ†™ๆณ•็š„่ฏ[programmatically](#custom-server-and-routing)๏ผŒไฝ ้œ€่ฆๆ‰‹ๅŠจ่ฎพ็ฝฎ`NODE_ENV=production`ใ€‚ <add> <add>ๆณจๆ„๏ผšๆŽจ่ๅฐ†`.next`ๆˆ–่‡ชๅฎšไน‰ๆ‰“ๅŒ…ๆ–‡ไปถๅคน[custom dist folder](https://github.com/zeit/next.js#custom-configuration)ๆ”พๅ…ฅ`.gitignore` ๆˆ– `.npmignore`ไธญใ€‚ๅฆๅˆ™๏ผŒไฝฟ็”จ`files` ๆˆ– `now.files` <add>ๆทปๅŠ ้ƒจ็ฝฒ็™ฝๅๅ•๏ผŒๅนถๆŽ’้™ค`.next`ๆˆ–่‡ชๅฎšไน‰ๆ‰“ๅŒ…ๆ–‡ไปถๅคนใ€‚ <add> <add><a id="browser-support" style="display: none"></a> <add>## ๆต่งˆๅ™จๆ”ฏๆŒ <add> <add>Next.js ๆ”ฏๆŒ IE11 ๅ’Œๆ‰€ๆœ‰็š„็Žฐไปฃๆต่งˆๅ™จไฝฟ็”จไบ†[`@babel/preset-env`](https://new.babeljs.io/docs/en/next/babel-preset-env.html)ใ€‚ไธบไบ†ๆ”ฏๆŒ IE11๏ผŒNext.js ้œ€่ฆๅ…จๅฑ€ๆทปๅŠ `Promise`็š„ polyfillใ€‚ๆœ‰ๆ—ถไฝ ็š„ไปฃ็ ๆˆ–ๅผ•ๅ…ฅ็š„ๅ…ถไป– NPM ๅŒ…็š„้ƒจๅˆ†ๅŠŸ่ƒฝ็Žฐไปฃๆต่งˆๅ™จไธๆ”ฏๆŒ๏ผŒๅˆ™้œ€่ฆ็”จ polyfills ๅŽปๅฎž็Žฐใ€‚ <add> <add>ployflls ๅฎž็Žฐๆกˆไพ‹ไธบ[polyfills](https://github.com/zeit/next.js/tree/canary/examples/with-polyfills)ใ€‚ <add> <add><a id="static-html-export" style="display: none"></a> <add>## ๅฏผๅ‡บ้™ๆ€้กต้ข <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul><li><a href="./examples/with-static-export">Static export</a></li></ul> <add></details></p> <add> <add>`next export`ๅฏไปฅ่พ“ๅ‡บไธ€ไธช Next.js ๅบ”็”จไฝœไธบ้™ๆ€่ต„ๆบๅบ”็”จ่€Œไธไพ้  Node.js ๆœๅŠกใ€‚ <add>่ฟ™ไธช่พ“ๅ‡บ็š„ๅบ”็”จๅ‡ ไนŽๆ”ฏๆŒ Next.js ็š„ๆ‰€ๆœ‰ๅŠŸ่ƒฝ๏ผŒๅŒ…ๆ‹ฌๅŠจๆ€่ทฏ็”ฑ๏ผŒ้ข„่Žทๅ–๏ผŒ้ข„ๅŠ ่ฝฝไปฅๅŠๅŠจๆ€ๅฏผๅ…ฅใ€‚ <add> <add>`next export`ๅฐ†ๆŠŠๆ‰€ๆœ‰ๆœ‰ๅฏ่ƒฝๆธฒๆŸ“ๅ‡บ็š„ HTML ้ƒฝ็”Ÿๆˆใ€‚่ฟ™ๆ˜ฏๅŸบไบŽๆ˜ ๅฐ„ๅฏน่ฑก็š„`pathname`ๅ…ณ้”ฎๅญ—ๅ…ณ่”ๅˆฐ้กต้ขๅฏน่ฑกใ€‚่ฟ™ไธชๆ˜ ๅฐ„ๅซๅš`exportPathMap`ใ€‚ <add> <add>้กต้ขๅฏน่ฑกๆœ‰2ไธชๅฑžๆ€ง: <add> <add>- `page` - ๅญ—็ฌฆไธฒ็ฑปๅž‹๏ผŒ้กต้ข็”Ÿๆˆ็›ฎๅฝ• <add>- `query` - ๅฏน่ฑก็ฑปๅž‹๏ผŒๅฝ“้ข„ๆธฒๆŸ“ๆ—ถ๏ผŒ`query`ๅฏน่ฑกๅฐ†ไผšไผ ๅ…ฅ้กต้ข็š„็”Ÿๅ‘ฝๅ‘จๆœŸ`getInitialProps`ไธญใ€‚้ป˜่ฎคไธบ`{}`ใ€‚ <add> <add> <add><a id="usage" style="display: none"></a> <add>### ไฝฟ็”จ <add> <add>้€šๅธธๅผ€ๅ‘ Next.js ๅบ”็”จไฝ ๅฐ†ไผš่ฟ่กŒ๏ผš <add> <add>``` <add>next build <add>next export <add>``` <add> <add>`next export`ๅ‘ฝไปค้ป˜่ฎคไธ้œ€่ฆไปปไฝ•้…็ฝฎ๏ผŒๅฐ†ไผš่‡ชๅŠจ็”Ÿๆˆ้ป˜่ฎค`exportPathMap`็”Ÿๆˆ`pages`็›ฎๅฝ•ไธ‹็š„่ทฏ็”ฑไฝ ้กต้ขใ€‚ <add> <add>ๅฆ‚ๆžœไฝ ๆƒณๅŠจๆ€้…็ฝฎ่ทฏ็”ฑ๏ผŒๅฏไปฅๅœจ`next.config.js`ไธญๆทปๅŠ ๅผ‚ๆญฅๅ‡ฝๆ•ฐ`exportPathMap`ใ€‚ <add> <add>```js <add>// next.config.js <add>module.exports = { <add> exportPathMap: async function (defaultPathMap) { <add> return { <add> '/': { page: '/' }, <add> '/about': { page: '/about' }, <add> '/readme.md': { page: '/readme' }, <add> '/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } }, <add> '/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } }, <add> '/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } } <add> } <add> } <add>} <add>``` <add> <add>> ๆณจๆ„๏ผšๅฆ‚ๆžœ path ็š„็ป“ๅฐพๆ˜ฏ็›ฎๅฝ•ๅ๏ผŒๅˆ™ๅฐ†ๅฏผๅ‡บ`/dir-name/index.html`๏ผŒไฝ†ๆ˜ฏๅฆ‚ๆžœ็ป“ๅฐพๆœ‰ๆ‰ฉๅฑ•ๅ๏ผŒๅฐ†ไผšๅฏผๅ‡บๅฏนๅบ”็š„ๆ–‡ไปถ๏ผŒๅฆ‚ไธŠ`/readme.md`ใ€‚ๅฆ‚ๆžœไฝ ไฝฟ็”จ`.html`ไปฅๅค–็š„ๆ‰ฉๅฑ•ๅ่งฃๆžๆ–‡ไปถๆ—ถ๏ผŒไฝ ้œ€่ฆ่ฎพ็ฝฎ header ็š„`Content-Type`ๅคดไธบ"text/html". <add> <add>่พ“ๅ…ฅไธ‹้ขๅ‘ฝไปค๏ผš <add> <add>```sh <add>next build <add>next export <add>``` <add> <add>ไฝ ๅฏไปฅๅœจ`package.json`ๆทปๅŠ ไธ€ไธช NPM ่„šๆœฌ๏ผŒๅฆ‚ไธ‹ๆ‰€็คบ๏ผš <add> <add>```json <add>{ <add> "scripts": { <add> "build": "next build", <add> "export": "npm run build && next export" <add> } <add>} <add>``` <add> <add>ๆŽฅ็€ๅช็”จๆ‰ง่กŒไธ€ๆฌกไธ‹้ขๅ‘ฝไปค๏ผš <add> <add>```sh <add>npm run export <add>``` <add> <add>็„ถๅŽไฝ ๅฐ†ไผšๆœ‰ไธ€ไธช้™ๆ€้กต้ขๅบ”็”จๅœจ`out` ็›ฎๅฝ•ไธ‹ใ€‚ <add> <add>> ไฝ ไนŸๅฏไปฅ่‡ชๅฎšไน‰่พ“ๅ‡บ็›ฎๅฝ•ใ€‚ๅฏไปฅ่ฟ่กŒ`next export -h`ๅ‘ฝไปคๆŸฅ็œ‹ๅธฎๅŠฉใ€‚ <add> <add>็Žฐๅœจไฝ ๅฏไปฅ้ƒจ็ฝฒ`out`็›ฎๅฝ•ๅˆฐไปปๆ„้™ๆ€่ต„ๆบๆœๅŠกๅ™จไธŠใ€‚ๆณจๆ„ๅฆ‚ๆžœ้ƒจ็ฝฒ GitHub Pages ้œ€่ฆๅŠ ไธช้ขๅค–็š„ๆญฅ้ชค๏ผŒ[ๆ–‡ๆกฃๅฆ‚ไธ‹](https://github.com/zeit/next.js/wiki/Deploying-a-Next.js-app-into-GitHub-Pages) <add> <add>ไพ‹ๅฆ‚๏ผŒ่ฎฟ้—ฎ`out`็›ฎๅฝ•ๅนถ็”จไธ‹้ขๅ‘ฝไปค้ƒจ็ฝฒๅบ”็”จ[ZEIT Now](https://zeit.co/now). <add> <add>```sh <add>now <add>``` <add> <add><a id="limitation" style="display: none"></a> <add>### ้™ๅˆถ <add> <add>ไฝฟ็”จ`next export`๏ผŒๆˆ‘ไปฌๅˆ›ๅปบไบ†ไธช้™ๆ€ HTML ๅบ”็”จใ€‚ๆž„ๅปบๆ—ถๅฐ†ไผš่ฟ่กŒ้กต้ข้‡Œ็”Ÿๅ‘ฝๅ‘จๆœŸ`getInitialProps` ๅ‡ฝๆ•ฐใ€‚ <add> <add>`req`ๅ’Œ`res`ๅชๅœจๆœๅŠก็ซฏๅฏ็”จ๏ผŒไธ่ƒฝ้€š่ฟ‡`getInitialProps`ใ€‚ <add> <add>> ๆ‰€ไปฅไฝ ไธ่ƒฝ้ข„ๆž„ๅปบ HTML ๆ–‡ไปถๆ—ถๅŠจๆ€ๆธฒๆŸ“ HTML ้กต้ขใ€‚ๅฆ‚ๆžœไฝ ๆƒณๅŠจๆ€ๆธฒๆŸ“ๅฏไปฅ่ฟ่กŒ`next start`ๆˆ–ๅ…ถไป–่‡ชๅฎšไน‰ๆœๅŠก็ซฏ APIใ€‚ <add> <add><a id="multi-zones" style="display: none"></a> <add>## ๅคš zone <add> <add><p><details> <add> <summary><b>Examples</b></summary> <add> <ul><li><a href="./examples/with-zones">With Zones</a></li></ul> <add></details></p> <add> <add>ไธ€ไธช zone ๆ—ถไธ€ไธชๅ•็‹ฌ็š„ Next.js ๅบ”็”จใ€‚ๅฆ‚ๆžœไฝ ๆœ‰ๅพˆๅคš zone๏ผŒไฝ ๅฏไปฅๅˆๅนถๆˆไธ€ไธชๅบ”็”จใ€‚ <add> <add>ไพ‹ๅฆ‚๏ผŒไฝ ๅฆ‚ไธ‹ๆœ‰ไธคไธช zone๏ผš <add> <add>* https://docs.my-app.com ๆœๅŠกไบŽ่ทฏ็”ฑ `/docs/**` <add>* https://ui.my-app.com ๆœๅŠกไบŽๆ‰€ๆœ‰้กต้ข <add> <add>ๆœ‰ๅคš zone ๅบ”็”จๆŠ€ๆœฏๆ”ฏๆŒ๏ผŒไฝ ๅฏไปฅๅฐ†ๅ‡ ไธชๅบ”็”จๅˆๅนถๅˆฐไธ€ไธช๏ผŒ่€Œไธ”ๅฏไปฅ่‡ชๅฎšไน‰ URL ่ทฏๅพ„๏ผŒไฝฟไฝ ่ƒฝๅŒๆ—ถๅ•็‹ฌๅผ€ๅ‘ๅ„ไธชๅบ”็”จใ€‚ <add> <add>> ไธŽ microservices ่ง‚ๅฟต็ฑปไผผ, ๅชๆ˜ฏๅบ”็”จไบŽๅ‰็ซฏๅบ”็”จ. <add> <add><a id="how-to-define-a-zone" style="display: none"></a> <add>### ๆ€Žไนˆๅฎšไน‰ไธ€ไธช zone <add> <add>zone ๆฒกๆœ‰ๅ•็‹ฌ็š„ API ๆ–‡ๆกฃใ€‚ไฝ ้œ€่ฆๅšไธ‹้ขไบ‹ๅณๅฏ๏ผš <add> <add>* ็กฎไฟไฝ ็š„ๅบ”็”จ้‡Œๅชๆœ‰้œ€่ฆ็š„้กต้ข (ไพ‹ๅฆ‚, https://ui.my-app.com ไธๅŒ…ๅซ `/docs/**`) <add>* ็กฎไฟไฝ ็š„ๅบ”็”จๆœ‰ไธชๅ‰็ผ€[assetPrefix](https://github.com/zeit/next.js#cdn-support-with-asset-prefix)ใ€‚๏ผˆไฝ ไนŸๅฏไปฅๅฎšไน‰ๅŠจๆ€ๅ‰็ผ€[dynamically](https://github.com/zeit/next.js#dynamic-assetprefix)๏ผ‰ <add> <add><a id="how-to-merge-them" style="display: none"></a> <add>### ๆ€Žไนˆๅˆๅนถไป–ไปฌ <add> <add>ไฝ ่ƒฝไฝฟ็”จ HTTP ไปฃ็†ๅˆๅนถ zone <add> <add>ไฝ ่ƒฝไฝฟ็”จไปฃ็†[micro proxy](https://github.com/zeit/micro-proxy)ๆฅไฝœไธบไฝ ็š„ๆœฌๅœฐไปฃ็†ๆœๅŠกใ€‚ๅฎƒๅ…่ฎธไฝ ๅฎšไน‰่ทฏ็”ฑ่ง„ๅˆ™ๅฆ‚ไธ‹๏ผš <add> <add>```json <add>{ <add> "rules": [ <add> {"pathname": "/docs**", "method":["GET", "POST", "OPTIONS"], "dest": "https://docs.my-app.com"}, <add> {"pathname": "/**", "dest": "https://ui.my-app.com"} <add> ] <add>} <add>``` <add> <add>็”Ÿไบง็Žฏๅขƒ้ƒจ็ฝฒ๏ผŒๅฆ‚ๆžœไฝ ไฝฟ็”จไบ†[ZEIT now](https://zeit.co/now)๏ผŒๅฏไปฅๅฎƒ็š„ไฝฟ็”จ[path alias](https://zeit.co/docs/features/path-aliases) ๅŠŸ่ƒฝใ€‚ๅฆๅˆ™๏ผŒไฝ ๅฏไปฅ่ฎพ็ฝฎไฝ ๅทฒไฝฟ็”จ็š„ไปฃ็†ๆœๅŠก็ผ–ๅ†™ไธŠ้ข่ง„ๅˆ™ๆฅ่ทฏ็”ฑ HTML ้กต้ข <add> <add><a id="recipes" style="display: none"></a> <add>## ๆŠ€ๅทง <add> <add>- [่ฎพ็ฝฎ301้‡ๅฎšๅ‘](https://www.raygesualdo.com/posts/301-redirects-with-nextjs/) <add>- [ๅชๅค„็†ๆœๅŠกๅ™จ็ซฏๆจกๅ—](https://arunoda.me/blog/ssr-and-server-only-modules) <add>- [ๆž„ๅปบ้กน็›ฎ React-Material-UI-Next-Express-Mongoose-Mongodb](https://github.com/builderbook/builderbook) <add>- [ๆž„ๅปบไธ€ไธช SaaS ไบงๅ“ React-Material-UI-Next-MobX-Express-Mongoose-MongoDB-TypeScript](https://github.com/async-labs/saas) <add> <add><a id="faq" style="display: none"></a> <add>## ้—ฎ็ญ” <add> <add><details> <add> <summary>่ฟ™ไธชไบงๅ“ๅฏไปฅ็”จไบŽ็”Ÿไบง็Žฏๅขƒๅ—๏ผŸ</summary> <add> https://zeit.co ้ƒฝๆ˜ฏไธ€็›ด็”จ Next.js ๅ†™็š„ใ€‚ <add> <add> ๅฎƒ็š„ๅผ€ๅ‘ไฝ“้ชŒๅ’Œ็ปˆ็ซฏ็”จๆˆทไฝ“้ชŒ้ƒฝๅพˆๅฅฝ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅ†ณๅฎšๅผ€ๆบๅ‡บๆฅ็ป™ๅคงๅฎถๅ…ฑไบซใ€‚ <add></details> <add> <add><details> <add> <summary>ไฝ“็งฏๅคšๅคง๏ผŸ</summary> <add> <add>ๅฎขๆˆท็ซฏๅคงๅฐๆ นๆฎๅบ”็”จ้œ€ๆฑ‚ไธไธ€ๆ ทๅคงๅฐไนŸไธไธ€ๆ ทใ€‚ <add> <add>ไธ€ไธชๆœ€็ฎ€ๅ• Next ๅบ”่ฏฅ็”จ gzip ๅŽ‹็ผฉๅŽๅคง็บฆ65kb <add> <add></details> <add> <add><details> <add> <summary>่ฟ™ไธชๅƒ `create-react-app`?</summary> <add> <add>ๆ˜ฏๆˆ–ไธๆ˜ฏ. <add> <add>ๆ˜ฏ๏ผŒๅ› ไธบๅฎƒ่ฎฉไฝ ็š„ SSR ๅผ€ๅ‘ๆ›ด็ฎ€ๅ•ใ€‚ <add> <add>ไธๆ˜ฏ๏ผŒๅ› ไธบๅฎƒ่ง„ๅฎšไบ†ไธ€ๅฎš็š„็›ฎๅฝ•็ป“ๆž„๏ผŒไฝฟๆˆ‘ไปฌ่ƒฝๅšไปฅไธ‹ๆ›ด้ซ˜็บง็š„ไบ‹๏ผš <add>- ๆœๅŠก็ซฏๆธฒๆŸ“ <add>- ่‡ชๅŠจไปฃ็ ๅˆ†ๅ‰ฒ <add> <add>ๆญคๅค–๏ผŒNext.js ่ฟ˜ๆไพ›ไธคไธชๅ†…็ฝฎ็‰นๆ€ง๏ผš <add>- ่ทฏ็”ฑไธŽๆ‡’ๅŠ ่ฝฝ็ป„ไปถ: `<Link>` (้€š่ฟ‡ๅผ•ๅ…ฅ `next/link`) <add>- ไฟฎๆ”น`<head>`็š„็ป„ไปถ: `<Head>` (้€š่ฟ‡ๅผ•ๅ…ฅ `next/head`) <add> <add>ๅฆ‚ๆžœไฝ ๆƒณๅ†™ๅ…ฑ็”จ็ป„ไปถ๏ผŒๅฏไปฅๅตŒๅ…ฅ Next.js ๅบ”็”จๅ’Œ React ๅบ”็”จไธญ๏ผŒๆŽจ่ไฝฟ็”จ`create-react-app`ใ€‚ไฝ ๅฏไปฅๆ›ดๆ”น`import`ไฟๆŒไปฃ็ ๆธ…ๆ™ฐใ€‚ <add> <add> <add></details> <add> <add><details> <add> <summary>ๆ€Žไนˆ่งฃๅ†ณ CSS ๅตŒๅ…ฅ JS ้—ฎ้ข˜?</summary> <add> <add>Next.js ่‡ชๅธฆ[styled-jsx](https://github.com/zeit/styled-jsx)ๅบ“ๆ”ฏๆŒ CSS ๅตŒๅ…ฅ JSใ€‚่€Œไธ”ไฝ ๅฏไปฅ้€‰ๆ‹ฉๅ…ถไป–ๅตŒๅ…ฅๆ–นๆณ•ๅˆฐไฝ ็š„้กน็›ฎไธญ๏ผŒๅฏๅ‚่€ƒๆ–‡ๆกฃ[as mentioned before](#css-in-js)ใ€‚ <add> <add></details> <add> <add><details> <add> <summary>ๅ“ชไบ›่ฏญๆณ•ไผš่ขซ่ฝฌๆข๏ผŸๆ€Žไนˆ่ฝฌๆขๅฎƒไปฌ๏ผŸ</summary> <add> <add>ๆˆ‘ไปฌ้ตๅพช V8 ๅผ•ๆ“Ž็š„๏ผŒๅฆ‚ไปŠ V8 ๅผ•ๆ“Žๅนฟๆณ›ๆ”ฏๆŒ ES6 ่ฏญๆณ•ไปฅๅŠ`async`ๅ’Œ`await`่ฏญๆณ•๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๆ”ฏๆŒ่ฝฌๆขๅฎƒไปฌใ€‚ไฝ†ๆ˜ฏ V8 ๅผ•ๆ“Žไธๆ”ฏๆŒไฟฎ้ฅฐๅ™จ่ฏญๆณ•๏ผŒๆ‰€ไปฅๆˆ‘ไปฌไนŸไธๆ”ฏๆŒ่ฝฌๆข่ฟ™่ฏญๆณ•ใ€‚ <add> <add>ๅฏไปฅๅ‚็…ง[่ฟ™ไบ›](https://github.com/zeit/next.js/blob/master/server/build/webpack.js#L79) ไปฅๅŠ [่ฟ™ไบ›](https://github.com/zeit/next.js/issues/26) <add> <add></details> <add> <add><details> <add> <summary>ไธบไป€ไนˆไฝฟ็”จๆ–ฐ่ทฏ็”ฑ?</summary> <add> <add>Next.js ็š„็‰นๅˆซไน‹ๅค„ๅฆ‚ไธ‹ๆ‰€็คบ: <add> <add>- ่ทฏ็”ฑไธ้œ€่ฆ่ขซๆๅ‰็Ÿฅ้“ <add>- ่ทฏ็”ฑๆ€ปๆ˜ฏ่ขซๆ‡’ๅŠ ่ฝฝ <add>- ้กถๅฑ‚็ป„ไปถๅฏไปฅๅฎšไน‰็”Ÿๅ‘ฝๅ‘จๆœŸ`getInitialProps`ๆฅ้˜ปๆญข่ทฏ็”ฑๅŠ ่ฝฝ๏ผˆๅฝ“ๆœๅŠก็ซฏๆธฒๆŸ“ๆˆ–่ทฏ็”ฑๆ‡’ๅŠ ่ฝฝๆ—ถ๏ผ‰ <add> <add>ๅ› ๆญค,ๆˆ‘ไปฌๅฏไปฅไป‹็ปไธ€ไธช้žๅธธ็ฎ€ๅ•็š„่ทฏ็”ฑๆ–นๆณ•,ๅฎƒ็”ฑไธ‹้ขไธค้ƒจๅˆ†็ป„ๆˆ: <add> <add>- ๆฏไธช้กถๅฑ‚็ป„ไปถ้ƒฝๅฐ†ไผšๆ”ถๅˆฐไธ€ไธช`url`ๅฏน่ฑก๏ผŒๆฅๆฃ€ๆŸฅ url ๆˆ–ไฟฎๆ”นๅŽ†ๅฒ่ฎฐๅฝ• <add>- `<Link />`็ป„ไปถ็”จไบŽๅŒ…่ฃ…ๅฆ‚(`<a/>`)ๆ ‡็ญพ็š„ๅ…ƒ็ด ๅฎนๅ™จ๏ผŒๆฅๆ‰ง่กŒๅฎขๆˆท็ซฏ่ฝฌๆขใ€‚ <add> <add>ๆˆ‘ไปฌไฝฟ็”จไบ†ไบ›ๆœ‰่ถฃ็š„ๅœบๆ™ฏๆฅๆต‹่ฏ•่ทฏ็”ฑ็š„็ตๆดปๆ€ง๏ผŒไพ‹ๅฆ‚๏ผŒๅฏๆŸฅ็œ‹[nextgram](https://github.com/zeit/nextgram)ใ€‚ <add> <add></details> <add> <add><details> <add><summary>ๆˆ‘ๆ€Žไนˆๅฎšไน‰่‡ชๅฎšไน‰่ทฏ็”ฑ?</summary> <add> <add>ๆˆ‘ไปฌ้€š่ฟ‡่ฏทๆฑ‚ๅค„็†ๆฅ[ๆทปๅŠ ](#custom-server-and-routing)ไปปๆ„ URL ไธŽไปปๆ„็ป„ไปถไน‹ๅ‰็š„ๆ˜ ๅฐ„ๅ…ณ็ณปใ€‚ <add> <add>ๅœจๅฎขๆˆท็ซฏ๏ผŒๆˆ‘ไปฌ`<Link>`็ป„ไปถๆœ‰ไธชๅฑžๆ€ง`as`๏ผŒๅฏไปฅ่ฃ…้ฅฐๆ”นๅ˜่Žทๅ–ๅˆฐ็š„ URLใ€‚ <add></details> <add> <add><details> <add><summary>ๆ€Žไนˆ่Žทๅ–ๆ•ฐๆฎ?</summary> <add> <add>่ฟ™็”ฑไฝ ๅ†ณๅฎšใ€‚`getInitialProps`ๆ˜ฏไธ€ไธชๅผ‚ๆญฅๅ‡ฝๆ•ฐ`async`๏ผˆไนŸๅฐฑๆ˜ฏๅ‡ฝๆ•ฐๅฐ†ไผš่ฟ”ๅ›žไธช`Promise`๏ผ‰ใ€‚ไฝ ๅฏไปฅๅœจไปปๆ„ไฝ็ฝฎ่Žทๅ–ๆ•ฐๆฎใ€‚ <add></details> <add> <add><details> <add> <summary>ๆˆ‘ๅฏไปฅไฝฟ็”จ GraphQL ๅ—?</summary> <add> <add>ๆ˜ฏ็š„! ่ฟ™้‡Œๆœ‰ไธชไพ‹ๅญ[Apollo](./examples/with-apollo). <add> <add></details> <add> <add><details> <add><summary>ๆˆ‘ๅฏไปฅไฝฟ็”จ Redux ๅ—?</summary> <add> <add>ๆ˜ฏ็š„! ่ฟ™้‡Œๆœ‰ไธช[ไพ‹ๅญ](./examples/with-redux) <add></details> <add> <add><details> <add><summary>ๆˆ‘ๅฏไปฅๅœจ Next ๅบ”็”จไธญไฝฟ็”จๆˆ‘ๅ–œๆฌข็š„ Javascript ๅบ“ๆˆ–ๅทฅๅ…ทๅŒ…ๅ—?</summary> <add> <add>ไปŽๆˆ‘ไปฌ็ฌฌไธ€ๆฌกๅ‘็‰ˆๅฐฑๅทฒ็ปๆไพ›**ๅพˆๅคš**ไพ‹ๅญ๏ผŒไฝ ๅฏไปฅๆŸฅ็œ‹่ฟ™ไบ›[ไพ‹ๅญ](./examples)ใ€‚ <add></details> <add> <add><details> <add><summary>ไป€ไนˆๅฏๅ‘ๆˆ‘ไปฌๅš่ฟ™ไธช?</summary> <add> <add>ๆˆ‘ไปฌๅฎž็Žฐ็š„ๅคง้ƒจๅˆ†็›ฎๆ ‡้ƒฝๆ˜ฏ้€š่ฟ‡ Guillermo Rauch ็š„[Web ๅบ”็”จ็š„7ๅŽŸๅˆ™](http://rauchg.com/2014/7-principles-of-rich-web-applications/)ๆฅๅฏๅ‘ๅ‡บ็š„ใ€‚ <add> <add>PHP ็š„ๆ˜“็”จๆ€งไนŸๆ˜ฏไธชๅพˆๅฅฝ็š„็ตๆ„Ÿๆฅๆบ๏ผŒๆˆ‘ไปฌ่ง‰ๅพ— Next.js ๅฏไปฅๆ›ฟไปฃๅพˆๅคš้œ€่ฆ็”จ PHP ่พ“ๅ‡บ HTML ็š„ๅœบๆ™ฏใ€‚ <add> <add>ไธŽ PHP ไธๅŒ็š„ๆ˜ฏ๏ผŒๆˆ‘ไปฌๅพ—ๅˆฉไบŽ ES6 ๆจกๅ—็ณป็ปŸ๏ผŒๆฏไธชๆ–‡ไปถไผš่พ“ๅ‡บไธ€ไธช**็ป„ไปถๆˆ–ๆ–นๆณ•**๏ผŒไปฅไพฟๅฏไปฅ่ฝปๆพ็š„ๅฏผๅ…ฅ็”จไบŽๆ‡’ๅŠ ่ฝฝๅ’Œๆต‹่ฏ• <add> <add>ๆˆ‘ไปฌ็ ”็ฉถ React ็š„ๆœๅŠกๅ™จๆธฒๆŸ“ๆ—ถๅนถๆฒกๆœ‰่Šฑ่ดนๅพˆๅคง็š„ๆญฅ้ชค๏ผŒๅ› ไธบๆˆ‘ไปฌๅ‘็Žฐไธ€ไธช็ฑปไผผไบŽ Next.js ็š„ไบงๅ“๏ผŒReact ไฝœ่€… Jordan Walke ๅ†™็š„[react-page](https://github.com/facebookarchive/react-page) (็Žฐๅœจๅทฒ็ปๅบŸๅผƒ) <add> <add></details> <add> <add><a id="contributing" style="display: none"></a> <add>## ่ดก็Œฎ <add> <add>ๅฏๆŸฅ็œ‹ [contributing.md](./contributing.md) <add> <add><a id="authors" style="display: none"></a> <add>## ไฝœ่€… <add> <add>- Arunoda Susiripala ([@arunoda](https://twitter.com/arunoda)) โ€“ [ZEIT](https://zeit.co) <add>- Tim Neutkens ([@timneutkens](https://twitter.com/timneutkens)) โ€“ [ZEIT](https://zeit.co) <add>- Naoyuki Kanezawa ([@nkzawa](https://twitter.com/nkzawa)) โ€“ [ZEIT](https://zeit.co) <add>- Tony Kovanen ([@tonykovanen](https://twitter.com/tonykovanen)) โ€“ [ZEIT](https://zeit.co) <add>- Guillermo Rauch ([@rauchg](https://twitter.com/rauchg)) โ€“ [ZEIT](https://zeit.co) <add>- Dan Zajdband ([@impronunciable](https://twitter.com/impronunciable)) โ€“ Knight-Mozilla / Coral Project
1
Java
Java
fix measurement of virtual nodes
008ad0200fd55b8351c108ecfbdd1890a7ae8ab9
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java <ide> private void measureHelper(int reactTag, boolean relativeToWindow, Callback call <ide> return; <ide> } <ide> <add> // virtual nodes do not have values for width and height, so get these values <add> // from the first non-virtual parent node <add> while (node != null && node.isVirtual()) { <add> node = (FlatShadowNode) node.getParent(); <add> } <add> <add> if (node == null) { <add> // everything is virtual, this shouldn't happen so just silently return <add> return; <add> } <add> <ide> float width = node.getLayoutWidth(); <ide> float height = node.getLayoutHeight(); <ide> <del> float xInParent = node.getLayoutX(); <del> float yInParent = node.getLayoutY(); <add> boolean nodeMountsToView = node.mountsToView(); <add> // this is to avoid double-counting xInParent and yInParent when we visit <add> // the while loop, below. <add> float xInParent = nodeMountsToView ? node.getLayoutX() : 0; <add> float yInParent = nodeMountsToView ? node.getLayoutY() : 0; <ide> <del> while (true) { <del> node = Assertions.assumeNotNull((FlatShadowNode) node.getParent()); <del> if (node.mountsToView()) { <del> mStateBuilder.ensureBackingViewIsCreated(node); <del> break; <add> while (!node.mountsToView()) { <add> if (!node.isVirtual()) { <add> xInParent += node.getLayoutX(); <add> yInParent += node.getLayoutY(); <ide> } <ide> <del> xInParent += node.getLayoutX(); <del> yInParent += node.getLayoutY(); <add> node = Assertions.assumeNotNull((FlatShadowNode) node.getParent()); <ide> } <ide> <ide> float parentWidth = node.getLayoutWidth();
1
Mixed
Javascript
add domain postmortem
4a74fc9776d825115849997f4adacb46f4303494
<ide><path>doc/topics/domain-postmortem.md <add># Domain Module Postmortem <add> <add>## Usability Issues <add> <add>### Implicit Behavior <add> <add>It's possible for a developer to create a new domain and then simply run <add>`domain.enter()`. Which then acts as a catch-all for any exception in the <add>future that couldn't be observed by the thrower. Allowing a module author to <add>intercept the exceptions of unrelated code in a different module. Preventing <add>the originator of the code from knowing about its own exceptions. <add> <add>Here's an example of how one indirectly linked modules can affect another: <add> <add>```js <add>// module a.js <add>const b = require('./b'); <add>const c = require('./c'); <add> <add> <add>// module b.js <add>const d = require('domain').create(); <add>d.on('error', () => { /* silence everything */ }); <add>d.enter(); <add> <add> <add>// module c.js <add>const dep = require('some-dep'); <add>dep.method(); // Uh-oh! This method doesn't actually exist. <add>``` <add> <add>Since module `b` enters the domain but never exits any uncaught exception will <add>be swallowed. Leaving module `c` in the dark as to why it didn't run the entire <add>script. Leaving a potentially partially populated `module.exports`. Doing this <add>is not the same as listening for `'uncaughtException'`. As the latter is <add>explicitly meant to globally catch errors. The other issue is that domains are <add>processed prior to any `'uncaughtException'` handlers, and prevent them from <add>running. <add> <add>Another issue is that domains route errors automatically if no `'error'` <add>handler was set on the event emitter. There is no opt-in mechanism for this, <add>and automatically propagates across the entire asynchronous chain. This may <add>seem useful at first, but once asynchronous calls are two or more modules deep <add>and one of them doesn't include an error handler the creator of the domain will <add>suddenly be catching unexpected exceptions, and the thrower's exception will go <add>unnoticed by the author. <add> <add>The following is a simple example of how a missing `'error'` handler allows <add>the active domain to hijack the error: <add> <add>```js <add>const domain = require('domain'); <add>const net = require('net'); <add>const d = domain.create(); <add>d.on('error', (err) => console.error(err.message)); <add> <add>d.run(() => net.createServer((c) => { <add> c.end(); <add> c.write('bye'); <add>}).listen(8000)); <add>``` <add> <add>Even manually removing the connection via `d.remove(c)` does not prevent the <add>connection's error from being automatically intercepted. <add> <add>Failures that plagues both error routing and exception handling are the <add>inconsistencies in how errors are bubbled. The following is an example of how <add>nested domains will and won't bubble the exception based on when they happen: <add> <add>```js <add>const domain = require('domain'); <add>const net = require('net'); <add>const d = domain.create(); <add>d.on('error', () => console.error('d intercepted an error')); <add> <add>d.run(() => { <add> const server = net.createServer((c) => { <add> const e = domain.create(); // No 'error' handler being set. <add> e.run(() => { <add> // This will not be caught by d's error handler. <add> setImmediate(() => { <add> throw new Error('thrown from setImmediate'); <add> }); <add> // Though this one will bubble to d's error handler. <add> throw new Error('immediately thrown'); <add> }); <add> }).listen(8080); <add>}); <add>``` <add> <add>It may be expected that nested domains always remain nested, and will always <add>propagate the exception up the domain stack. Or that exceptions will never <add>automatically bubble. Unfortunately both these situations occur, leading to <add>potentially confusing behavior that may even be prone to difficult to debug <add>timing conflicts. <add> <add> <add>### API Gaps <add> <add>While APIs based on using `EventEmitter` can use `bind()` and errback style <add>callbacks can use `intercept()`, alternative APIs that implicitly bind to the <add>active domain must be executed inside of `run()`. Meaning if module authors <add>wanted to support domains using a mechanism alternative to those mentioned they <add>must manually implement domain support themselves. Instead of being able to <add>leverage the implicit mechanisms already in place. <add> <add> <add>### Error Propagation <add> <add>Propagating errors across nested domains is not straight forward, if even <add>possible. Existing documentation shows a simple example of how to `close()` an <add>`http` server if there is an error in the request handler. What it does not <add>explain is how to close the server if the request handler creates another <add>domain instance for another async request. Using the following as a simple <add>example of the failing of error propagation: <add> <add>```js <add>const d1 = domain.create(); <add>d1.foo = true; // custom member to make more visible in console <add>d1.on('error', (er) => { /* handle error */ }); <add> <add>d1.run(() => setTimeout(() => { <add> const d2 = domain.create(); <add> d2.bar = 43; <add> d2.on('error', (er) => console.error(er.message, domain._stack)); <add> d2.run(() => { <add> setTimeout(() => { <add> setTimeout(() => { <add> throw new Error('outer'); <add> }); <add> throw new Error('inner') <add> }); <add> }); <add>})); <add>``` <add> <add>Even in the case that the domain instances are being used for local storage so <add>access to resources are made available there is still no way to allow the error <add>to continue propagating from `d2` back to `d1`. Quick inspection may tell us <add>that simply throwing from `d2`'s domain `'error'` handler would allow `d1` to <add>then catch the exception and execute its own error handler. Though that is not <add>the case. Upon inspection of `domain._stack` you'll see that the stack only <add>contains `d2`. <add> <add>This may be considered a failing of the API, but even if it did operate in this <add>way there is still the issue of transmitting the fact that a branch in the <add>asynchronous execution has failed, and that all further operations in that <add>branch must cease. In the example of the http request handler, if we fire off <add>several asynchronous requests and each one then `write()`'s data back to the <add>client many more errors will arise from attempting to `write()` to a closed <add>handle. More on this in _Resource Cleanup on Exception_. <add> <add> <add>### Resource Cleanup on Exception <add> <add>The script [`domain-resource-cleanup.js`](domain-resource-cleanup.js) <add>contains a more complex example of properly cleaning up in a small resource <add>dependency tree in the case that an exception occurs in a given connection or <add>any of its dependencies. Breaking down the script into its basic operations: <add> <add>- When a new connection happens, concurrently: <add> - Open a file on the file system <add> - Open Pipe to unique socket <add>- Read a chunk of the file asynchronously <add>- Write chunk to both the TCP connection and any listening sockets <add>- If any of these resources error, notify all other attached resources that <add> they need to clean up and shutdown <add> <add>As we can see from this example a lot more must be done to properly clean up <add>resources when something fails than what can be done strictly through the <add>domain API. All that domains offer is an exception aggregation mechanism. Even <add>the potentially useful ability to propagate data with the domain is easily <add>countered, in this example, by passing the needed resources as a function <add>argument. <add> <add>One problem domains perpetuated was the supposed simplicity of being able to <add>continue execution, contrary to what the documentation stated, of the <add>application despite an unexpected exception. This example demonstrates the <add>fallacy behind that idea. <add> <add>Attempting proper resource cleanup on unexpected exception becomes more complex <add>as the application itself grows in complexity. This example only has 3 basic <add>resources in play, and all of them with a clear dependency path. If an <add>application uses something like shared resources or resource reuse the ability <add>to cleanup, and properly test that cleanup has been done, grows greatly. <add> <add>In the end, in terms of handling errors, domains aren't much more than a <add>glorified `'uncaughtException'` handler. Except with more implicit and <add>unobservable behavior by third-parties. <add> <add> <add>### Resource Propagation <add> <add>Another use case for domains was to use it to propagate data along asynchronous <add>data paths. One problematic point is the ambiguity of when to expect the <add>correct domain when there are multiple in the stack (which must be assumed if <add>the async stack works with other modules). Also the conflict between being <add>able to depend on a domain for error handling while also having it available to <add>retrieve the necessary data. <add> <add>The following is a involved example demonstrating the failing using domains to <add>propagate data along asynchronous stacks: <add> <add>```js <add>const domain = require('domain'); <add>const net = require('net'); <add> <add>const server = net.createServer((c) => { <add> // Use a domain to propagate data across events within the <add> // connection so that we don't have to pass arguments <add> // everywhere. <add> const d = domain.create(); <add> d.data = { connection: c }; <add> d.add(c); <add> // Mock class that does some useless async data transformation <add> // for demonstration purposes. <add> const ds = new DataStream(dataTransformed); <add> c.on('data', (chunk) => ds.data(chunk)); <add>}).listen(8080, () => console.log(`listening on 8080`)); <add> <add>function dataTransformed(chunk) { <add> // FAIL! Because the DataStream instance also created a <add> // domain we have now lost the active domain we had <add> // hoped to use. <add> domain.active.data.connection.write(chunk); <add>} <add> <add>function DataStream(cb) { <add> this.cb = cb; <add> // DataStream wants to use domains for data propagation too! <add> // Unfortunately this will conflict with any domain that <add> // already exists. <add> this.domain = domain.create(); <add> this.domain.data = { inst: this }; <add>} <add> <add>DataStream.prototype.data = function data(chunk) { <add> // This code is self contained, but pretend it's a complex <add> // operation that crosses at least one other module. So <add> // passing along "this", etc., is not easy. <add> this.domain.run(function() { <add> // Simulate an async operation that does the data transform. <add> setImmediate(() => { <add> for (var i = 0; i < chunk.length; i++) <add> chunk[i] = ((chunk[i] + Math.random() * 100) % 96) + 33; <add> // Grab the instance from the active domain and use that <add> // to call the user's callback. <add> const self = domain.active.data.inst; <add> self.cb.call(self, chunk); <add> }); <add> }); <add>}; <add>``` <add> <add>The above shows that it is difficult to have more than one asynchronous API <add>attempt to use domains to propagate data. This example could possibly be fixed <add>by assigning `parent: domain.active` in the `DataStream` constructor. Then <add>restoring it via `domain.active = domain.active.data.parent` just before the <add>user's callback is called. Also the instantiation of `DataStream` in the <add>`'connection'` callback must be run inside `d.run()`, instead of simply using <add>`d.add(c)`, otherwise there will be no active domain. <add> <add>In short, for this to have a prayer of a chance usage would need to strictly <add>adhere to a set of guidelines that would be difficult to enforce or test. <add> <add> <add>## Performance Issues <add> <add>A significant deterrent from using domains is the overhead. Using node's <add>built-in http benchmark, `http_simple.js`, without domains it can handle over <add>22,000 requests/second. Whereas if it's run with `NODE_USE_DOMAINS=1` that <add>number drops down to under 17,000 requests/second. In this case there is only <add>a single global domain. If we edit the benchmark so the http request callback <add>creates a new domain instance performance drops further to 15,000 <add>requests/second. <add> <add>While this probably wouldn't affect a server only serving a few hundred or even <add>a thousand requests per second, the amount of overhead is directly proportional <add>to the number of asynchronous requests made. So if a single connection needs to <add>connect to several other services all of those will contribute to the overall <add>latency of delivering the final product to the client. <add> <add>Using `AsyncWrap` and tracking the number of times <add>`init`/`pre`/`post`/`destroy` are called in the mentioned benchmark we find <add>that the sum of all events called is over 170,000 times per second. This means <add>even adding 1 microsecond overhead per call for any type of setup or tear down <add>will result in a 17% performance loss. Granted, this is for the optimized <add>scenario of the benchmark, but I believe this demonstrates the necessity for a <add>mechanism such as domain to be as cheap to run as possible. <add> <add> <add>## Looking Ahead <add> <add>The domain module has been soft deprecated since Dec 2014, but has not yet been <add>removed because node offers no alternative functionality at the moment. As of <add>this writing there is ongoing work building out the `AsyncWrap` API and a <add>proposal for Zones being prepared for the TC39. At such time there is suitable <add>functionality to replace domains it will undergo the full deprecation cycle and <add>eventually be removed from core. <ide><path>doc/topics/domain-resource-cleanup-example.js <add>'use strict'; <add> <add>const domain = require('domain'); <add>const EE = require('events'); <add>const fs = require('fs'); <add>const net = require('net'); <add>const util = require('util'); <add>const print = process._rawDebug; <add> <add>const pipeList = []; <add>const FILENAME = '/tmp/tmp.tmp'; <add>const PIPENAME = '/tmp/node-domain-example-'; <add>const FILESIZE = 1024; <add>var uid = 0; <add> <add>// Setting up temporary resources <add>const buf = Buffer(FILESIZE); <add>for (var i = 0; i < buf.length; i++) <add> buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII <add>fs.writeFileSync(FILENAME, buf); <add> <add>function ConnectionResource(c) { <add> EE.call(this); <add> this._connection = c; <add> this._alive = true; <add> this._domain = domain.create(); <add> this._id = Math.random().toString(32).substr(2).substr(0, 8) + (++uid); <add> <add> this._domain.add(c); <add> this._domain.on('error', () => { <add> this._alive = false; <add> }); <add>} <add>util.inherits(ConnectionResource, EE); <add> <add>ConnectionResource.prototype.end = function end(chunk) { <add> this._alive = false; <add> this._connection.end(chunk); <add> this.emit('end'); <add>}; <add> <add>ConnectionResource.prototype.isAlive = function isAlive() { <add> return this._alive; <add>}; <add> <add>ConnectionResource.prototype.id = function id() { <add> return this._id; <add>}; <add> <add>ConnectionResource.prototype.write = function write(chunk) { <add> this.emit('data', chunk); <add> return this._connection.write(chunk); <add>}; <add> <add>// Example begin <add>net.createServer((c) => { <add> const cr = new ConnectionResource(c); <add> <add> const d1 = domain.create(); <add> fs.open(FILENAME, 'r', d1.intercept((fd) => { <add> streamInParts(fd, cr, 0); <add> })); <add> <add> pipeData(cr); <add> <add> c.on('close', () => cr.end()); <add>}).listen(8080); <add> <add>function streamInParts(fd, cr, pos) { <add> const d2 = domain.create(); <add> var alive = true; <add> d2.on('error', (er) => { <add> print('d2 error:', er.message) <add> cr.end(); <add> }); <add> fs.read(fd, new Buffer(10), 0, 10, pos, d2.intercept((bRead, buf) => { <add> if (!cr.isAlive()) { <add> return fs.close(fd); <add> } <add> if (cr._connection.bytesWritten < FILESIZE) { <add> // Documentation says callback is optional, but doesn't mention that if <add> // the write fails an exception will be thrown. <add> const goodtogo = cr.write(buf); <add> if (goodtogo) { <add> setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); <add> } else { <add> cr._connection.once('drain', () => streamInParts(fd, cr, pos + bRead)); <add> } <add> return; <add> } <add> cr.end(buf); <add> fs.close(fd); <add> })); <add>} <add> <add>function pipeData(cr) { <add> const pname = PIPENAME + cr.id(); <add> const ps = net.createServer(); <add> const d3 = domain.create(); <add> const connectionList = []; <add> d3.on('error', (er) => { <add> print('d3 error:', er.message); <add> cr.end(); <add> }); <add> d3.add(ps); <add> ps.on('connection', (conn) => { <add> connectionList.push(conn); <add> conn.on('data', () => {}); // don't care about incoming data. <add> conn.on('close', () => { <add> connectionList.splice(connectionList.indexOf(conn), 1); <add> }); <add> }); <add> cr.on('data', (chunk) => { <add> for (var i = 0; i < connectionList.length; i++) { <add> connectionList[i].write(chunk); <add> } <add> }); <add> cr.on('end', () => { <add> for (var i = 0; i < connectionList.length; i++) { <add> connectionList[i].end(); <add> } <add> ps.close(); <add> }); <add> pipeList.push(pname); <add> ps.listen(pname); <add>} <add> <add>process.on('SIGINT', () => process.exit()); <add>process.on('exit', () => { <add> try { <add> for (var i = 0; i < pipeList.length; i++) { <add> fs.unlinkSync(pipeList[i]); <add> } <add> fs.unlinkSync(FILENAME); <add> } catch (e) { } <add>});
2
Python
Python
fix linode tests
06a9439aeffb819c883e866950d8d4db5c238a5b
<ide><path>test/dns/test_linode.py <ide> def test_get_record_zone_does_not_exist(self): <ide> try: <ide> record = self.driver.get_record(zone_id='444', record_id='28536') <ide> except ZoneDoesNotExistError: <del> self.assertEqual(e.zone_id, '4444') <add> pass <ide> else: <ide> self.fail('Exception was not thrown') <ide> <ide> def test_get_record_record_does_not_exist(self): <ide> try: <ide> record = self.driver.get_record(zone_id='444', record_id='28536') <ide> except ZoneDoesNotExistError: <del> self.assertEqual(e.zone_id, '4444') <add> pass <ide> else: <ide> self.fail('Exception was not thrown') <ide>
1
Javascript
Javascript
update stream2 transform for corrected behavior
c2f62d496a08e9d44bea4a459c2eab7457d724ee
<ide><path>test/simple/test-stream2-transform.js <ide> test('assymetric transform (expand)', function(t) { <ide> t.equal(pt.read(5).toString(), 'uelku'); <ide> t.equal(pt.read(5).toString(), 'el'); <ide> t.end(); <del> }, 100); <add> }, 200); <ide> }); <ide> <ide> test('assymetric transform (compress)', function(t) { <ide> test('passthrough event emission', function(t) { <ide> console.error('need emit 0'); <ide> <ide> pt.write(new Buffer('bazy')); <add> console.error('should have emitted, but not again'); <ide> pt.write(new Buffer('kuel')); <ide> <del> console.error('should have emitted readable now'); <add> console.error('should have emitted readable now 1 === %d', emits); <ide> t.equal(emits, 1); <ide> <ide> t.equal(pt.read(5).toString(), 'arkba'); <ide> test('passthrough event emission reordered', function(t) { <ide> console.error('need emit 0'); <ide> pt.once('readable', function() { <ide> t.equal(pt.read(5).toString(), 'arkba'); <del> t.equal(pt.read(5).toString(), 'zykue'); <add> <ide> t.equal(pt.read(5), null); <ide> <ide> console.error('need emit 1'); <ide> pt.once('readable', function() { <del> t.equal(pt.read(5).toString(), 'l'); <add> t.equal(pt.read(5).toString(), 'zykue'); <ide> t.equal(pt.read(5), null); <del> <del> t.equal(emits, 2); <del> t.end(); <add> pt.once('readable', function() { <add> t.equal(pt.read(5).toString(), 'l'); <add> t.equal(pt.read(5), null); <add> t.equal(emits, 3); <add> t.end(); <add> }); <add> pt.end(); <ide> }); <del> pt.end(); <add> pt.write(new Buffer('kuel')); <ide> }); <add> <ide> pt.write(new Buffer('bazy')); <del> pt.write(new Buffer('kuel')); <ide> }); <ide> <ide> test('passthrough facaded', function(t) {
1
Python
Python
remove config side effects from tests
caa60b1141ac02cdde1c33464be9adca114c2ed5
<ide><path>airflow/models/xcom.py <ide> def serialize_value(value: Any): <ide> # "pickling" will be removed in Airflow 2.0. <ide> if conf.getboolean('core', 'enable_xcom_pickling'): <ide> return pickle.dumps(value) <del> <ide> try: <ide> return json.dumps(value).encode('UTF-8') <del> except ValueError: <add> except (ValueError, TypeError): <ide> log.error("Could not serialize the XCOM value into JSON. " <ide> "If you are using pickles instead of JSON " <ide> "for XCOM, then you need to enable pickle " <ide><path>airflow/operators/latest_only_operator.py <ide> def choose_branch(self, context: Dict) -> Union[str, Iterable[str]]: <ide> if context['dag_run'] and context['dag_run'].external_trigger: <ide> self.log.info( <ide> "Externally triggered DAG_Run: allowing execution to proceed.") <del> return context['task'].get_direct_relative_ids(upstream=False) <add> return list(context['task'].get_direct_relative_ids(upstream=False)) <ide> <ide> now = pendulum.utcnow() <ide> left_window = context['dag'].following_schedule( <ide> def choose_branch(self, context: Dict) -> Union[str, Iterable[str]]: <ide> return [] <ide> else: <ide> self.log.info('Latest, allowing execution to proceed.') <del> return context['task'].get_direct_relative_ids(upstream=False) <add> return list(context['task'].get_direct_relative_ids(upstream=False)) <ide><path>tests/executors/test_dask_executor.py <ide> <ide> import pytest <ide> <del>from airflow.configuration import conf <ide> from airflow.jobs.backfill_job import BackfillJob <ide> from airflow.models import DagBag <ide> from airflow.utils import timezone <add>from tests.test_utils.config import conf_vars <ide> <ide> try: <ide> from airflow.executors.dask_executor import DaskExecutor <ide> class TestDaskExecutorTLS(TestBaseDask): <ide> def setUp(self): <ide> self.dagbag = DagBag(include_examples=True) <ide> <add> @conf_vars({ <add> ('dask', 'tls_ca'): get_cert('tls-ca-cert.pem'), <add> ('dask', 'tls_cert'): get_cert('tls-key-cert.pem'), <add> ('dask', 'tls_key'): get_cert('tls-key.pem'), <add> }) <ide> def test_tls(self): <add> # These use test certs that ship with dask/distributed and should not be <add> # used in production <ide> with dask_testing_cluster( <del> worker_kwargs={'security': tls_security(), "protocol": "tls"}, <del> scheduler_kwargs={'security': tls_security(), "protocol": "tls"}) as (cluster, _): <del> <del> # These use test certs that ship with dask/distributed and should not be <del> # used in production <del> conf.set('dask', 'tls_ca', get_cert('tls-ca-cert.pem')) <del> conf.set('dask', 'tls_cert', get_cert('tls-key-cert.pem')) <del> conf.set('dask', 'tls_key', get_cert('tls-key.pem')) <del> try: <del> executor = DaskExecutor(cluster_address=cluster['address']) <del> <del> self.assert_tasks_on_executor(executor) <del> <del> executor.end() <del> # close the executor, the cluster context manager expects all listeners <del> # and tasks to have completed. <del> executor.client.close() <del> finally: <del> conf.set('dask', 'tls_ca', '') <del> conf.set('dask', 'tls_key', '') <del> conf.set('dask', 'tls_cert', '') <add> worker_kwargs={'security': tls_security(), "protocol": "tls"}, <add> scheduler_kwargs={'security': tls_security(), "protocol": "tls"} <add> ) as (cluster, _): <add> <add> executor = DaskExecutor(cluster_address=cluster['address']) <add> <add> self.assert_tasks_on_executor(executor) <add> <add> executor.end() <add> # close the executor, the cluster context manager expects all listeners <add> # and tasks to have completed. <add> executor.client.close() <ide> <ide> @mock.patch('airflow.executors.dask_executor.DaskExecutor.sync') <ide> @mock.patch('airflow.executors.base_executor.BaseExecutor.trigger_tasks') <ide><path>tests/jobs/test_scheduler_job.py <ide> TEMP_DAG_FILENAME = "temp_dag.py" <ide> <ide> <add>@pytest.fixture(scope="class") <add>def disable_load_example(): <add> with conf_vars({('core', 'load_examples'): 'false'}): <add> yield <add> <add> <add>@pytest.mark.usefixtures("disable_load_example") <ide> class TestDagFileProcessor(unittest.TestCase): <ide> def setUp(self): <ide> clear_db_runs() <ide> def create_test_dag(self, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + timed <ide> @classmethod <ide> def setUpClass(cls): <ide> cls.dagbag = DagBag() <del> cls.old_val = None <del> if conf.has_option('core', 'load_examples'): <del> cls.old_val = conf.get('core', 'load_examples') <del> conf.set('core', 'load_examples', 'false') <del> <del> @classmethod <del> def tearDownClass(cls): <del> if cls.old_val is not None: <del> conf.set('core', 'load_examples', cls.old_val) <del> else: <del> conf.remove_option('core', 'load_examples') <ide> <ide> def test_dag_file_processor_sla_miss_callback(self): <ide> """ <ide> def test_process_file_queries_count( <ide> processor.process_file(ELASTIC_DAG_FILE, []) <ide> <ide> <add>@pytest.mark.usefixtures("disable_load_example") <ide> class TestSchedulerJob(unittest.TestCase): <ide> <ide> def setUp(self): <ide> def setUp(self): <ide> @classmethod <ide> def setUpClass(cls): <ide> cls.dagbag = DagBag() <del> cls.old_val = None <del> if conf.has_option('core', 'load_examples'): <del> cls.old_val = conf.get('core', 'load_examples') <del> conf.set('core', 'load_examples', 'false') <del> <del> @classmethod <del> def tearDownClass(cls): <del> if cls.old_val is not None: <del> conf.set('core', 'load_examples', cls.old_val) <del> else: <del> conf.remove_option('core', 'load_examples') <ide> <ide> def test_is_alive(self): <ide> job = SchedulerJob(None, heartrate=10, state=State.RUNNING) <ide><path>tests/models/test_cleartasks.py <ide> import unittest <ide> <ide> from airflow import settings <del>from airflow.configuration import conf <ide> from airflow.models import DAG, TaskInstance as TI, XCom, clear_task_instances <ide> from airflow.operators.dummy_operator import DummyOperator <ide> from airflow.utils import timezone <ide> from airflow.utils.session import create_session <ide> from airflow.utils.state import State <ide> from tests.models import DEFAULT_DATE <add>from tests.test_utils.config import conf_vars <ide> <ide> <ide> class TestClearTasks(unittest.TestCase): <ide> def test_operator_clear(self): <ide> # try_number (0) + retries(1) <ide> self.assertEqual(ti2.max_tries, 1) <ide> <add> @conf_vars({("core", "enable_xcom_pickling"): "False"}) <ide> def test_xcom_disable_pickle_type(self): <ide> json_obj = {"key": "value"} <ide> execution_date = timezone.utcnow() <ide> key = "xcom_test1" <ide> dag_id = "test_dag1" <ide> task_id = "test_task1" <del> <del> conf.set("core", "enable_xcom_pickling", "False") <del> <ide> XCom.set(key=key, <ide> value=json_obj, <ide> dag_id=dag_id, <ide> def test_xcom_disable_pickle_type(self): <ide> <ide> self.assertEqual(ret_value, json_obj) <ide> <add> @conf_vars({("core", "enable_xcom_pickling"): "True"}) <ide> def test_xcom_enable_pickle_type(self): <ide> json_obj = {"key": "value"} <ide> execution_date = timezone.utcnow() <ide> key = "xcom_test2" <ide> dag_id = "test_dag2" <ide> task_id = "test_task2" <del> <del> conf.set("core", "enable_xcom_pickling", "True") <del> <ide> XCom.set(key=key, <ide> value=json_obj, <ide> dag_id=dag_id, <ide> def test_xcom_enable_pickle_type(self): <ide> <ide> self.assertEqual(ret_value, json_obj) <ide> <add> @conf_vars({("core", "xcom_enable_pickling"): "False"}) <ide> def test_xcom_disable_pickle_type_fail_on_non_json(self): <ide> class PickleRce: <ide> def __reduce__(self): <ide> return os.system, ("ls -alt",) <ide> <del> conf.set("core", "xcom_enable_pickling", "False") <del> <ide> self.assertRaises(TypeError, XCom.set, <ide> key="xcom_test3", <ide> value=PickleRce(), <ide> dag_id="test_dag3", <ide> task_id="test_task3", <ide> execution_date=timezone.utcnow()) <ide> <add> @conf_vars({("core", "xcom_enable_pickling"): "True"}) <ide> def test_xcom_get_many(self): <ide> json_obj = {"key": "value"} <ide> execution_date = timezone.utcnow() <ide> def test_xcom_get_many(self): <ide> dag_id2 = "test_dag5" <ide> task_id2 = "test_task5" <ide> <del> conf.set("core", "xcom_enable_pickling", "True") <del> <ide> XCom.set(key=key, <ide> value=json_obj, <ide> dag_id=dag_id1, <ide><path>tests/models/test_taskinstance.py <ide> from sqlalchemy.orm.session import Session <ide> <ide> from airflow import models, settings <del>from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException, AirflowSkipException <ide> from airflow.models import ( <ide> DAG, DagRun, Pool, RenderedTaskInstanceFields, TaskFail, TaskInstance as TI, TaskReschedule, Variable, <ide> from airflow.utils.state import State <ide> from tests.models import DEFAULT_DATE <ide> from tests.test_utils import db <add>from tests.test_utils.config import conf_vars <ide> <ide> <ide> class CallbackWrapper: <ide> def test_email_alert(self, mock_send_email): <ide> self.assertIn('test_email_alert', body) <ide> self.assertIn('Try 1', body) <ide> <add> @conf_vars({ <add> ('email', 'subject_template'): '/subject/path', <add> ('email', 'html_content_template'): '/html_content/path', <add> }) <ide> @patch('airflow.models.taskinstance.send_email') <ide> def test_email_alert_with_config(self, mock_send_email): <ide> dag = models.DAG(dag_id='test_failure_email') <ide> def test_email_alert_with_config(self, mock_send_email): <ide> ti = TI( <ide> task=task, execution_date=datetime.datetime.now()) <ide> <del> conf.set('email', 'subject_template', '/subject/path') <del> conf.set('email', 'html_content_template', '/html_content/path') <del> <ide> opener = mock_open(read_data='template: {{ti.task_id}}') <ide> with patch('airflow.models.taskinstance.open', opener, create=True): <ide> try: <ide><path>tests/models/test_xcom.py <ide> def test_resolve_xcom_class_fallback_to_basexcom(self): <ide> assert cls().serialize_value([1]) == b"[1]" <ide> <ide> @conf_vars({("core", "enable_xcom_pickling"): "False"}) <add> @conf_vars({("core", "xcom_backend"): "to be removed"}) <ide> def test_resolve_xcom_class_fallback_to_basexcom_no_config(self): <del> init = conf.get("core", "xcom_backend") <ide> conf.remove_option("core", "xcom_backend") <ide> cls = resolve_xcom_backend() <ide> assert issubclass(cls, BaseXCom) <ide> assert cls().serialize_value([1]) == b"[1]" <del> conf.set("core", "xcom_backend", init) <ide><path>tests/providers/amazon/aws/operators/test_s3_to_sftp.py <ide> import boto3 <ide> from moto import mock_s3 <ide> <del>from airflow.configuration import conf <ide> from airflow.models import DAG, TaskInstance <ide> from airflow.providers.amazon.aws.operators.s3_to_sftp import S3ToSFTPOperator <ide> from airflow.providers.ssh.operators.ssh import SSHOperator <ide> from airflow.utils import timezone <ide> from airflow.utils.timezone import datetime <add>from tests.test_utils.config import conf_vars <ide> <ide> TASK_ID = 'test_s3_to_sftp' <ide> BUCKET = 'test-s3-bucket' <ide> def setUp(self): <ide> self.s3_key = S3_KEY <ide> <ide> @mock_s3 <add> @conf_vars({("core", "enable_xcom_pickling"): "True"}) <ide> def test_s3_to_sftp_operation(self): <ide> # Setting <del> conf.set("core", "enable_xcom_pickling", "True") <ide> test_remote_file_content = \ <ide> "This is remote file content \n which is also multiline " \ <ide> "another line here \n this is last line. EOF" <ide><path>tests/security/test_kerberos.py <ide> import unittest <ide> from argparse import Namespace <ide> <del>from airflow.configuration import conf <ide> from airflow.security import kerberos <ide> from airflow.security.kerberos import renew_from_kt <ide> from tests.test_utils.config import conf_vars <ide> <add>KRB5_KTNAME = os.environ.get('KRB5_KTNAME') <ide> <del>@unittest.skipIf('KRB5_KTNAME' not in os.environ, <del> 'Skipping Kerberos API tests due to missing KRB5_KTNAME') <add> <add>@unittest.skipIf(KRB5_KTNAME is None, 'Skipping Kerberos API tests due to missing KRB5_KTNAME') <ide> class TestKerberos(unittest.TestCase): <ide> def setUp(self): <del> <del> if not conf.has_section("kerberos"): <del> conf.add_section("kerberos") <del> conf.set("kerberos", "keytab", <del> os.environ['KRB5_KTNAME']) <del> keytab_from_cfg = conf.get("kerberos", "keytab") <del> self.args = Namespace(keytab=keytab_from_cfg, principal=None, pid=None, <add> self.args = Namespace(keytab=KRB5_KTNAME, principal=None, pid=None, <ide> daemon=None, stdout=None, stderr=None, log_file=None) <ide> <add> @conf_vars({('kerberos', 'keytab'): KRB5_KTNAME}) <ide> def test_renew_from_kt(self): <ide> """ <ide> We expect no result, but a successful run. No more TypeError <ide> """ <ide> self.assertIsNone(renew_from_kt(principal=self.args.principal, # pylint: disable=no-member <ide> keytab=self.args.keytab)) <ide> <add> @conf_vars({('kerberos', 'keytab'): ''}) <ide> def test_args_from_cli(self): <ide> """ <ide> We expect no result, but a run with sys.exit(1) because keytab not exist. <ide> """ <ide> self.args.keytab = "test_keytab" <ide> <del> with conf_vars({('kerberos', 'keytab'): ''}): <del> with self.assertRaises(SystemExit) as err: <del> renew_from_kt(principal=self.args.principal, # pylint: disable=no-member <del> keytab=self.args.keytab) <add> with self.assertRaises(SystemExit) as err: <add> renew_from_kt(principal=self.args.principal, # pylint: disable=no-member <add> keytab=self.args.keytab) <ide> <del> with self.assertLogs(kerberos.log) as log: <del> self.assertIn( <del> 'kinit: krb5_init_creds_set_keytab: Failed to find ' <del> 'airflow@LUPUS.GRIDDYNAMICS.NET in keytab FILE:{} ' <del> '(unknown enctype)'.format(self.args.keytab), log.output) <add> with self.assertLogs(kerberos.log) as log: <add> self.assertIn( <add> 'kinit: krb5_init_creds_set_keytab: Failed to find ' <add> 'airflow@LUPUS.GRIDDYNAMICS.NET in keytab FILE:{} ' <add> '(unknown enctype)'.format(self.args.keytab), log.output) <ide> <del> self.assertEqual(err.exception.code, 1) <add> self.assertEqual(err.exception.code, 1) <ide><path>tests/test_configuration.py <ide> }) <ide> class TestConf(unittest.TestCase): <ide> <del> @classmethod <del> def setUpClass(cls): <del> conf.set('core', 'percent', 'with%%inside') <del> <ide> def test_airflow_home_default(self): <ide> with unittest.mock.patch.dict('os.environ'): <ide> if 'AIRFLOW_HOME' in os.environ: <ide> def test_airflow_config_override(self): <ide> get_airflow_config('/home//airflow'), <ide> '/path/to/airflow/airflow.cfg') <ide> <add> @conf_vars({("core", "percent"): "with%%inside"}) <ide> def test_case_sensitivity(self): <ide> # section and key are case insensitive for get method <ide> # note: this is not the case for as_dict method <ide> def test_env_var_config(self): <ide> 'os.environ', <ide> AIRFLOW__KUBERNETES_ENVIRONMENT_VARIABLES__AIRFLOW__TESTSECTION__TESTKEY='nested' <ide> ) <add> @conf_vars({("core", "percent"): "with%%inside"}) <ide> def test_conf_as_dict(self): <ide> cfg_dict = conf.as_dict() <ide> <ide> def test_conf_as_dict_sensitive(self): <ide> self.assertEqual( <ide> cfg_dict['testsection']['testkey'], ('testvalue', 'env var')) <ide> <add> @conf_vars({("core", "percent"): "with%%inside"}) <ide> def test_conf_as_dict_raw(self): <ide> # test display_sensitive <ide> cfg_dict = conf.as_dict(raw=True, display_sensitive=True) <ide> def test_deprecated_options(self): <ide> with mock.patch.dict('os.environ', AIRFLOW__CELERY__CELERYD_CONCURRENCY="99"): <ide> self.assertEqual(conf.getint('celery', 'worker_concurrency'), 99) <ide> <del> with self.assertWarns(DeprecationWarning): <del> conf.set('celery', 'celeryd_concurrency', '99') <add> with self.assertWarns(DeprecationWarning), conf_vars({('celery', 'celeryd_concurrency'): '99'}): <ide> self.assertEqual(conf.getint('celery', 'worker_concurrency'), 99) <del> conf.remove_option('celery', 'celeryd_concurrency') <ide> <ide> @conf_vars({ <ide> ('logging', 'logging_level'): None, <ide> def test_deprecated_options_with_new_section(self): <ide> with mock.patch.dict('os.environ', AIRFLOW__CORE__LOGGING_LEVEL="VALUE"): <ide> self.assertEqual(conf.get('logging', 'logging_level'), "VALUE") <ide> <del> with self.assertWarns(DeprecationWarning): <del> conf.set('core', 'logging_level', 'VALUE') <add> with self.assertWarns(DeprecationWarning), conf_vars({('core', 'logging_level'): 'VALUE'}): <ide> self.assertEqual(conf.get('logging', 'logging_level'), "VALUE") <del> conf.remove_option('core', 'logging_level') <ide> <ide> @conf_vars({ <ide> ("celery", "result_backend"): None, <ide> def test_deprecated_options_cmd(self): <ide> conf.as_command_stdout.add(('celery', 'celery_result_backend')) <ide> <ide> conf.remove_option('celery', 'result_backend') <del> conf.set('celery', 'celery_result_backend_cmd', '/bin/echo 99') <del> <del> with self.assertWarns(DeprecationWarning): <del> tmp = None <del> if 'AIRFLOW__CELERY__RESULT_BACKEND' in os.environ: <del> tmp = os.environ.pop('AIRFLOW__CELERY__RESULT_BACKEND') <del> self.assertEqual(conf.getint('celery', 'result_backend'), 99) <del> if tmp: <del> os.environ['AIRFLOW__CELERY__RESULT_BACKEND'] = tmp <add> with conf_vars({('celery', 'celery_result_backend_cmd'): '/bin/echo 99'}): <add> with self.assertWarns(DeprecationWarning): <add> tmp = None <add> if 'AIRFLOW__CELERY__RESULT_BACKEND' in os.environ: <add> tmp = os.environ.pop('AIRFLOW__CELERY__RESULT_BACKEND') <add> self.assertEqual(conf.getint('celery', 'result_backend'), 99) <add> if tmp: <add> os.environ['AIRFLOW__CELERY__RESULT_BACKEND'] = tmp <ide> <ide> def test_deprecated_values(self): <ide> def make_config(): <ide><path>tests/test_logging_config.py <ide> # KIND, either express or implied. See the License for the <ide> # specific language governing permissions and limitations <ide> # under the License. <del> <add>import contextlib <ide> import importlib <ide> import os <ide> import pathlib <ide> SETTINGS_DEFAULT_NAME = 'custom_airflow_local_settings' <ide> <ide> <del>class settings_context: # pylint: disable=invalid-name <add>@contextlib.contextmanager <add>def settings_context(content, directory=None, name='LOGGING_CONFIG'): <ide> """ <ide> Sets a settings file and puts it in the Python classpath <ide> <ide> :param content: <ide> The content of the settings file <ide> """ <add> settings_root = tempfile.mkdtemp() <add> filename = f"{SETTINGS_DEFAULT_NAME}.py" <add> <add> if directory: <add> # Replace slashes by dots <add> module = directory.replace('/', '.') + '.' + SETTINGS_DEFAULT_NAME + '.' + name <add> <add> # Create the directory structure <add> dir_path = os.path.join(settings_root, directory) <add> pathlib.Path(dir_path).mkdir(parents=True, exist_ok=True) <ide> <del> def __init__(self, content, directory=None, name='LOGGING_CONFIG'): <del> self.content = content <del> self.settings_root = tempfile.mkdtemp() <del> filename = "{}.py".format(SETTINGS_DEFAULT_NAME) <del> <del> if directory: <del> # Replace slashes by dots <del> self.module = directory.replace('/', '.') + '.' + SETTINGS_DEFAULT_NAME + '.' + name <del> <del> # Create the directory structure <del> dir_path = os.path.join(self.settings_root, directory) <del> pathlib.Path(dir_path).mkdir(parents=True, exist_ok=True) <del> <del> # Add the __init__ for the directories <del> # This is required for Python 2.7 <del> basedir = self.settings_root <del> for part in directory.split('/'): <del> open(os.path.join(basedir, '__init__.py'), 'w').close() <del> basedir = os.path.join(basedir, part) <add> # Add the __init__ for the directories <add> # This is required for Python 2.7 <add> basedir = settings_root <add> for part in directory.split('/'): <ide> open(os.path.join(basedir, '__init__.py'), 'w').close() <add> basedir = os.path.join(basedir, part) <add> open(os.path.join(basedir, '__init__.py'), 'w').close() <add> <add> settings_file = os.path.join(dir_path, filename) <add> else: <add> module = SETTINGS_DEFAULT_NAME + '.' + name <add> settings_file = os.path.join(settings_root, filename) <add> <add> with open(settings_file, 'w') as handle: <add> handle.writelines(content) <add> sys.path.append(settings_root) <add> <add> with conf_vars({('logging', 'logging_config_class'): module}): <add> yield settings_file <ide> <del> self.settings_file = os.path.join(dir_path, filename) <del> else: <del> self.module = SETTINGS_DEFAULT_NAME + '.' + name <del> self.settings_file = os.path.join(self.settings_root, filename) <del> <del> def __enter__(self): <del> with open(self.settings_file, 'w') as handle: <del> handle.writelines(self.content) <del> sys.path.append(self.settings_root) <del> conf.set( <del> 'logging', <del> 'logging_config_class', <del> self.module <del> ) <del> return self.settings_file <del> <del> def __exit__(self, *exc_info): <del> # shutil.rmtree(self.settings_root) <del> # Reset config <del> conf.set('logging', 'logging_config_class', '') <del> sys.path.remove(self.settings_root) <add> sys.path.remove(settings_root) <ide> <ide> <ide> class TestLoggingSettings(unittest.TestCase): <ide><path>tests/utils/test_dag_processing.py <ide> # under the License. <ide> <ide> import os <del>import pathlib <ide> import sys <del>import tempfile <ide> import unittest <ide> from datetime import datetime, timedelta <ide> from unittest import mock <ide> from airflow.utils.file import correct_maybe_zipped, open_maybe_zipped <ide> from airflow.utils.session import create_session <ide> from airflow.utils.state import State <add>from tests.test_logging_config import SETTINGS_FILE_VALID, settings_context <ide> from tests.test_utils.config import conf_vars <ide> from tests.test_utils.db import clear_db_runs <ide> <ide> <ide> DEFAULT_DATE = timezone.datetime(2016, 1, 1) <ide> <del>SETTINGS_FILE_VALID = """ <del>LOGGING_CONFIG = { <del> 'version': 1, <del> 'disable_existing_loggers': False, <del> 'formatters': { <del> 'airflow.task': { <del> 'format': '[%(asctime)s] {%(process)d %(filename)s:%(lineno)d} %(levelname)s - %(message)s' <del> }, <del> }, <del> 'handlers': { <del> 'console': { <del> 'class': 'logging.StreamHandler', <del> 'formatter': 'airflow.task', <del> 'stream': 'ext://sys.stdout' <del> }, <del> 'task': { <del> 'class': 'logging.StreamHandler', <del> 'formatter': 'airflow.task', <del> 'stream': 'ext://sys.stdout' <del> }, <del> }, <del> 'loggers': { <del> 'airflow': { <del> 'handlers': ['console'], <del> 'level': 'INFO', <del> 'propagate': False <del> }, <del> 'airflow.task': { <del> 'handlers': ['task'], <del> 'level': 'INFO', <del> 'propagate': False, <del> }, <del> } <del>} <del>""" <del> <del>SETTINGS_DEFAULT_NAME = 'custom_airflow_local_settings' <del> <del> <del>class settings_context: # pylint: disable=invalid-name <del> """ <del> Sets a settings file and puts it in the Python classpath <del> <del> :param content: <del> The content of the settings file <del> """ <del> <del> def __init__(self, content, directory=None, name='LOGGING_CONFIG'): <del> self.content = content <del> self.settings_root = tempfile.mkdtemp() <del> filename = "{}.py".format(SETTINGS_DEFAULT_NAME) <del> <del> if directory: <del> # Replace slashes by dots <del> self.module = directory.replace('/', '.') + '.' + SETTINGS_DEFAULT_NAME + '.' + name <del> <del> # Create the directory structure <del> dir_path = os.path.join(self.settings_root, directory) <del> pathlib.Path(dir_path).mkdir(parents=True, exist_ok=True) <del> <del> # Add the __init__ for the directories <del> # This is required for Python 2.7 <del> basedir = self.settings_root <del> for part in directory.split('/'): <del> open(os.path.join(basedir, '__init__.py'), 'w').close() <del> basedir = os.path.join(basedir, part) <del> open(os.path.join(basedir, '__init__.py'), 'w').close() <del> <del> self.settings_file = os.path.join(dir_path, filename) <del> else: <del> self.module = SETTINGS_DEFAULT_NAME + '.' + name <del> self.settings_file = os.path.join(self.settings_root, filename) <del> <del> def __enter__(self): <del> with open(self.settings_file, 'w') as handle: <del> handle.writelines(self.content) <del> sys.path.append(self.settings_root) <del> conf.set( <del> 'logging', <del> 'logging_config_class', <del> self.module <del> ) <del> return self.settings_file <del> <del> def __exit__(self, *exc_info): <del> # shutil.rmtree(self.settings_root) <del> # Reset config <del> conf.set('logging', 'logging_config_class', '') <del> sys.path.remove(self.settings_root) <del> <ide> <ide> class TestDagFileProcessorManager(unittest.TestCase): <ide> def setUp(self): <ide><path>tests/utils/test_email.py <ide> def test_custom_backend(self, mock_send_email): <ide> self.assertFalse(mock_send_email.called) <ide> <ide> <add>@conf_vars({('smtp', 'SMTP_SSL'): 'False'}) <ide> class TestEmailSmtp(unittest.TestCase): <del> def setUp(self): <del> conf.set('smtp', 'SMTP_SSL', 'False') <del> <ide> @mock.patch('airflow.utils.email.send_mime_email') <ide> def test_send_smtp(self, mock_send_mime): <ide> attachment = tempfile.NamedTemporaryFile() <ide><path>tests/utils/test_task_handler_with_custom_formatter.py <ide> import unittest <ide> <ide> from airflow.config_templates.airflow_local_settings import DEFAULT_LOGGING_CONFIG <del>from airflow.configuration import conf <ide> from airflow.models import DAG, TaskInstance <ide> from airflow.operators.dummy_operator import DummyOperator <ide> from airflow.utils.log.logging_mixin import set_context <ide> from airflow.utils.timezone import datetime <add>from tests.test_utils.config import conf_vars <ide> <ide> DEFAULT_DATE = datetime(2019, 1, 1) <ide> TASK_LOGGER = 'airflow.task' <ide> def setUp(self): <ide> 'formatter': 'airflow', <ide> 'stream': 'sys.stdout' <ide> } <del> conf.set('logging', 'task_log_prefix_template', "{{ti.dag_id}}-{{ti.task_id}}") <ide> <ide> logging.config.dictConfig(DEFAULT_LOGGING_CONFIG) <ide> logging.root.disabled = False <ide> def tearDown(self): <ide> super().tearDown() <ide> DEFAULT_LOGGING_CONFIG['handlers']['task'] = PREV_TASK_HANDLER <ide> <add> @conf_vars({('logging', 'task_log_prefix_template'): "{{ti.dag_id}}-{{ti.task_id}}"}) <ide> def test_formatter(self): <ide> dag = DAG('test_dag', start_date=DEFAULT_DATE) <ide> task = DummyOperator(task_id='test_task', dag=dag) <ide><path>tests/www/api/experimental/test_kerberos_endpoints.py <ide> import pytest <ide> <ide> from airflow.api.auth.backend.kerberos_auth import CLIENT_AUTH <del>from airflow.configuration import conf <ide> from airflow.www import app as application <add>from tests.test_utils.config import conf_vars <add> <add>KRB5_KTNAME = os.environ.get("KRB5_KTNAME") <ide> <ide> <ide> @pytest.mark.integration("kerberos") <ide> class TestApiKerberos(unittest.TestCase): <add> @conf_vars({ <add> ("api", "auth_backend"): "airflow.api.auth.backend.kerberos_auth", <add> ("kerberos", "keytab"): KRB5_KTNAME, <add> }) <ide> def setUp(self): <del> try: <del> conf.add_section("api") <del> except Exception: # pylint: disable=broad-except <del> pass <del> conf.set("api", <del> "auth_backend", <del> "airflow.api.auth.backend.kerberos_auth") <del> try: <del> conf.add_section("kerberos") <del> except Exception: # pylint: disable=broad-except <del> pass <del> conf.set("kerberos", <del> "keytab", <del> os.environ['KRB5_KTNAME']) <del> <ide> self.app, _ = application.create_app(testing=True) <ide> <ide> def test_trigger_dag(self): <ide><path>tests/www/test_views.py <ide> def test_list(self): <ide> <ide> class TestMountPoint(unittest.TestCase): <ide> @classmethod <add> @conf_vars({("webserver", "base_url"): "http://localhost/test"}) <ide> def setUpClass(cls): <ide> application.app = None <ide> application.appbuilder = None <del> conf.set("webserver", "base_url", "http://localhost/test") <ide> app = application.cached_app(config={'WTF_CSRF_ENABLED': False}, session=Session, testing=True) <ide> cls.client = Client(app, BaseResponse) <ide> <ide> def test_task_stats(self): <ide> self.assertEqual(set(list(resp.json.items())[0][1][0].keys()), <ide> {'state', 'count', 'color'}) <ide> <add> @conf_vars({("webserver", "show_recent_stats_for_completed_runs"): "False"}) <ide> def test_task_stats_only_noncompleted(self): <del> conf.set("webserver", "show_recent_stats_for_completed_runs", "False") <ide> resp = self.client.post('task_stats', follow_redirects=True) <ide> self.assertEqual(resp.status_code, 200) <ide> <ide> def test_code_no_file(self): <ide> self.check_content_in_response('Failed to load file', resp) <ide> self.check_content_in_response('example_bash_operator', resp) <ide> <add> @conf_vars({("core", "store_dag_code"): "True"}) <ide> def test_code_from_db(self): <del> with conf_vars( <del> { <del> ("core", "store_dag_code"): "True" <del> } <del> ): <del> from airflow.models.dagcode import DagCode <del> dag = models.DagBag(include_examples=True).get_dag("example_bash_operator") <del> DagCode(dag.fileloc, DagCode._get_code_from_file(dag.fileloc)).sync_to_db() <del> url = 'code?dag_id=example_bash_operator' <del> resp = self.client.get(url) <del> self.check_content_not_in_response('Failed to load file', resp) <del> self.check_content_in_response('example_bash_operator', resp) <add> from airflow.models.dagcode import DagCode <add> dag = models.DagBag(include_examples=True).get_dag("example_bash_operator") <add> DagCode(dag.fileloc, DagCode._get_code_from_file(dag.fileloc)).sync_to_db() <add> url = 'code?dag_id=example_bash_operator' <add> resp = self.client.get(url) <add> self.check_content_not_in_response('Failed to load file', resp) <add> self.check_content_in_response('example_bash_operator', resp) <ide> <add> @conf_vars({("core", "store_dag_code"): "True"}) <ide> def test_code_from_db_all_example_dags(self): <del> with conf_vars( <del> { <del> ("core", "store_dag_code"): "True" <del> } <del> ): <del> from airflow.models.dagcode import DagCode <del> dagbag = models.DagBag(include_examples=True) <del> for dag in dagbag.dags.values(): <del> DagCode(dag.fileloc, DagCode._get_code_from_file(dag.fileloc)).sync_to_db() <del> url = 'code?dag_id=example_bash_operator' <del> resp = self.client.get(url) <del> self.check_content_not_in_response('Failed to load file', resp) <del> self.check_content_in_response('example_bash_operator', resp) <add> from airflow.models.dagcode import DagCode <add> dagbag = models.DagBag(include_examples=True) <add> for dag in dagbag.dags.values(): <add> DagCode(dag.fileloc, DagCode._get_code_from_file(dag.fileloc)).sync_to_db() <add> url = 'code?dag_id=example_bash_operator' <add> resp = self.client.get(url) <add> self.check_content_not_in_response('Failed to load file', resp) <add> self.check_content_in_response('example_bash_operator', resp) <ide> <ide> def test_paused(self): <ide> url = 'paused?dag_id=example_bash_operator&is_paused=false' <ide> def setUp(self): <ide> with open(settings_file, 'w') as handle: <ide> handle.writelines(new_logging_file) <ide> sys.path.append(self.settings_folder) <del> conf.set('logging', 'logging_config_class', 'airflow_local_settings.LOGGING_CONFIG') <del> <del> self.app, self.appbuilder = application.create_app(session=Session, testing=True) <del> self.app.config['WTF_CSRF_ENABLED'] = False <del> self.client = self.app.test_client() <del> settings.configure_orm() <del> self.login() <del> <del> from airflow.www.views import dagbag <del> dag = DAG(self.DAG_ID, start_date=self.DEFAULT_DATE) <del> dag.sync_to_db() <del> dag_removed = DAG(self.DAG_ID_REMOVED, start_date=self.DEFAULT_DATE) <del> dag_removed.sync_to_db() <del> dagbag.bag_dag(dag, parent_dag=dag, root_dag=dag) <del> with create_session() as session: <del> self.ti = TaskInstance( <del> task=DummyOperator(task_id=self.TASK_ID, dag=dag), <del> execution_date=self.DEFAULT_DATE <del> ) <del> self.ti.try_number = 1 <del> self.ti_removed_dag = TaskInstance( <del> task=DummyOperator(task_id=self.TASK_ID, dag=dag_removed), <del> execution_date=self.DEFAULT_DATE <del> ) <del> self.ti_removed_dag.try_number = 1 <ide> <del> session.merge(self.ti) <del> session.merge(self.ti_removed_dag) <add> with conf_vars({('logging', 'logging_config_class'): 'airflow_local_settings.LOGGING_CONFIG'}): <add> self.app, self.appbuilder = application.create_app(session=Session, testing=True) <add> self.app.config['WTF_CSRF_ENABLED'] = False <add> self.client = self.app.test_client() <add> settings.configure_orm() <add> self.login() <add> <add> from airflow.www.views import dagbag <add> dag = DAG(self.DAG_ID, start_date=self.DEFAULT_DATE) <add> dag.sync_to_db() <add> dag_removed = DAG(self.DAG_ID_REMOVED, start_date=self.DEFAULT_DATE) <add> dag_removed.sync_to_db() <add> dagbag.bag_dag(dag, parent_dag=dag, root_dag=dag) <add> with create_session() as session: <add> self.ti = TaskInstance( <add> task=DummyOperator(task_id=self.TASK_ID, dag=dag), <add> execution_date=self.DEFAULT_DATE <add> ) <add> self.ti.try_number = 1 <add> self.ti_removed_dag = TaskInstance( <add> task=DummyOperator(task_id=self.TASK_ID, dag=dag_removed), <add> execution_date=self.DEFAULT_DATE <add> ) <add> self.ti_removed_dag.try_number = 1 <add> <add> session.merge(self.ti) <add> session.merge(self.ti_removed_dag) <ide> <ide> def tearDown(self): <ide> logging.config.dictConfig(DEFAULT_LOGGING_CONFIG) <ide> def tearDown(self): <ide> <ide> sys.path.remove(self.settings_folder) <ide> shutil.rmtree(self.settings_folder) <del> conf.set('logging', 'logging_config_class', '') <del> <ide> self.logout() <ide> super().tearDown() <ide>
16
Ruby
Ruby
use opt_prefix for service helpers
869b0ea519ce1d18303d62c75a136a09a30361a8
<ide><path>Library/Homebrew/formula.rb <ide> def service_name <ide> # The generated launchd {.plist} file path. <ide> sig { returns(Pathname) } <ide> def plist_path <del> prefix/"#{plist_name}.plist" <add> opt_prefix/"#{plist_name}.plist" <ide> end <ide> <ide> # The generated systemd {.service} file path. <ide> sig { returns(Pathname) } <ide> def systemd_service_path <del> prefix/"#{service_name}.service" <add> opt_prefix/"#{service_name}.service" <ide> end <ide> <ide> # The service specification of the software. <ide><path>Library/Homebrew/test/formula_installer_spec.rb <ide> class #{Formulary.class_s(dep_name)} < Formula <ide> it "works if plist is set" do <ide> formula = Testball.new <ide> path = formula.plist_path <del> formula.prefix.mkpath <add> formula.opt_prefix.mkpath <ide> <ide> expect(formula).to receive(:plist).twice.and_return("PLIST") <ide> expect(formula).to receive(:plist_path).and_call_original <ide> class #{Formulary.class_s(dep_name)} < Formula <ide> plist_path = formula.plist_path <ide> service_path = formula.systemd_service_path <ide> service = Homebrew::Service.new(formula) <del> formula.prefix.mkpath <add> formula.opt_prefix.mkpath <ide> <ide> expect(formula).to receive(:plist).and_return(nil) <ide> expect(formula).to receive(:service?).exactly(3).and_return(true) <ide> class #{Formulary.class_s(dep_name)} < Formula <ide> it "returns without definition" do <ide> formula = Testball.new <ide> path = formula.plist_path <del> formula.prefix.mkpath <add> formula.opt_prefix.mkpath <ide> <ide> expect(formula).to receive(:plist).and_return(nil) <ide> expect(formula).to receive(:service?).exactly(3).and_return(nil) <ide> class #{Formulary.class_s(dep_name)} < Formula <ide> it "errors with duplicate definition" do <ide> formula = Testball.new <ide> path = formula.plist_path <del> formula.prefix.mkpath <add> formula.opt_prefix.mkpath <ide> <ide> expect(formula).to receive(:plist).and_return("plist") <ide> expect(formula).to receive(:service?).and_return(true) <ide><path>Library/Homebrew/test/formula_spec.rb <ide> end <ide> end <ide> <del> specify "#service" do <del> f = formula do <del> url "https://brew.sh/test-1.0.tbz" <add> describe "#service" do <add> specify "no service defined" do <add> f = formula do <add> url "https://brew.sh/test-1.0.tbz" <add> end <add> <add> expect(f.service).to eq(nil) <ide> end <ide> <del> f.class.service do <del> run [opt_bin/"beanstalkd"] <del> run_type :immediate <del> error_log_path var/"log/beanstalkd.error.log" <del> log_path var/"log/beanstalkd.log" <del> working_dir var <del> keep_alive true <add> specify "service complicated" do <add> f = formula do <add> url "https://brew.sh/test-1.0.tbz" <add> end <add> <add> f.class.service do <add> run [opt_bin/"beanstalkd"] <add> run_type :immediate <add> error_log_path var/"log/beanstalkd.error.log" <add> log_path var/"log/beanstalkd.log" <add> working_dir var <add> keep_alive true <add> end <add> expect(f.service).not_to eq(nil) <ide> end <del> expect(f.service).not_to eq(nil) <del> end <ide> <del> specify "service uses simple run" do <del> f = formula do <del> url "https://brew.sh/test-1.0.tbz" <del> service do <del> run opt_bin/"beanstalkd" <add> specify "service uses simple run" do <add> f = formula do <add> url "https://brew.sh/test-1.0.tbz" <add> service do <add> run opt_bin/"beanstalkd" <add> end <ide> end <add> <add> expect(f.service).not_to eq(nil) <ide> end <ide> <del> expect(f.service).not_to eq(nil) <add> specify "service helpers return data" do <add> f = formula do <add> url "https://brew.sh/test-1.0.tbz" <add> end <add> <add> expect(f.plist_name).to eq("homebrew.mxcl.formula_name") <add> expect(f.service_name).to eq("homebrew.formula_name") <add> expect(f.plist_path).to eq(HOMEBREW_PREFIX/"opt/formula_name/homebrew.mxcl.formula_name.plist") <add> expect(f.systemd_service_path).to eq(HOMEBREW_PREFIX/"opt/formula_name/homebrew.formula_name.service") <add> end <ide> end <ide> <ide> specify "dependencies" do
3
Javascript
Javascript
add html5 elements to the whitelist
fabc9f77a3fae10c2b8d9a9ad1541e827cc0390d
<ide><path>src/sanitizer.js <ide> var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?: <ide> URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/, <ide> NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) <ide> <del>// Empty Elements - HTML 4.01 <del>var emptyElements = makeMap("area,br,col,hr,img"); <del> <del>// Block Elements - HTML 4.01 <del>var blockElements = makeMap("address,blockquote,center,dd,del,dir,div,dl,dt,"+ <del> "hr,ins,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul"); <del> <del>// Inline Elements - HTML 4.01 <del>var inlineElements = makeMap("a,abbr,acronym,b,bdo,big,br,cite,code,del,dfn,em,font,i,img,"+ <del> "ins,kbd,label,map,q,s,samp,small,span,strike,strong,sub,sup,tt,u,var"); <del>// Elements that you can, intentionally, leave open <del>// (and which close themselves) <del>var closeSelfElements = makeMap("colgroup,dd,dt,li,p,td,tfoot,th,thead,tr"); <add> <add>// Good source of info about elements and attributes <add>// http://dev.w3.org/html5/spec/Overview.html#semantics <add>// http://simon.html5.org/html-elements <add> <add>// Safe Void Elements - HTML5 <add>// http://dev.w3.org/html5/spec/Overview.html#void-elements <add>var voidElements = makeMap("area,br,col,hr,img,wbr"); <add> <add>// Elements that you can, intentionally, leave open (and which close themselves) <add>// http://dev.w3.org/html5/spec/Overview.html#optional-tags <add>var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), <add> optionalEndTagInlineElements = makeMap("rp,rt"), <add> optionalEndTagElements = extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); <add> <add>// Safe Block Elements - HTML5 <add>var blockElements = extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," + <add> "blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," + <add> "header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); <add> <add>// Inline Elements - HTML5 <add>var inlineElements = extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," + <add> "big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," + <add> "span,strike,strong,sub,sup,time,tt,u,var")); <add> <add> <ide> // Special Elements (can contain anything) <ide> var specialElements = makeMap("script,style"); <del>var validElements = extend({}, emptyElements, blockElements, inlineElements, closeSelfElements); <add> <add>var validElements = extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); <ide> <ide> //Attributes that have href and hence need to be sanitized <del>var uriAttrs = makeMap("background,href,longdesc,src,usemap"); <add>var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); <ide> var validAttrs = extend({}, uriAttrs, makeMap( <ide> 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ <ide> 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ <ide> function htmlParser( html, handler ) { <ide> } <ide> } <ide> <del> if ( closeSelfElements[ tagName ] && stack.last() == tagName ) { <add> if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { <ide> parseEndTag( "", tagName ); <ide> } <ide> <del> unary = emptyElements[ tagName ] || !!unary; <add> unary = voidElements[ tagName ] || !!unary; <ide> <ide> if ( !unary ) <ide> stack.push( tagName );
1
Text
Text
use code markup/markdown in headers
5847a4d8ce8d1731125c9f9b426d093916f6676b
<ide><path>doc/api/buffer.md <ide> for (const b of buf) { <ide> Additionally, the [`buf.values()`][], [`buf.keys()`][], and <ide> [`buf.entries()`][] methods can be used to create iterators. <ide> <del>## Class: Buffer <add>## Class: `Buffer` <ide> <ide> The `Buffer` class is a global type for dealing with binary data directly. <ide> It can be constructed in a variety of ways. <ide> <del>### new Buffer(array) <add>### `new Buffer(array)` <ide> <!-- YAML <ide> deprecated: v6.0.0 <ide> changes: <ide> Allocates a new `Buffer` using an `array` of octets. <ide> const buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); <ide> ``` <ide> <del>### new Buffer(arrayBuffer\[, byteOffset\[, length\]\]) <add>### `new Buffer(arrayBuffer[, byteOffset[, length]])` <ide> <!-- YAML <ide> added: v3.0.0 <ide> deprecated: v6.0.0 <ide> console.log(buf); <ide> // Prints: <Buffer 88 13 70 17> <ide> ``` <ide> <del>### new Buffer(buffer) <add>### `new Buffer(buffer)` <ide> <!-- YAML <ide> deprecated: v6.0.0 <ide> changes: <ide> console.log(buf2.toString()); <ide> // Prints: buffer <ide> ``` <ide> <del>### new Buffer(size) <add>### `new Buffer(size)` <ide> <!-- YAML <ide> deprecated: v6.0.0 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00> <ide> ``` <ide> <del>### new Buffer(string\[, encoding\]) <add>### `new Buffer(string[, encoding])` <ide> <!-- YAML <ide> deprecated: v6.0.0 <ide> changes: <ide> console.log(buf1.toString('ascii')); <ide> // Prints: this is a tC)st <ide> ``` <ide> <del>### Class Method: Buffer.alloc(size\[, fill\[, encoding\]\]) <add>### Class Method: `Buffer.alloc(size[, fill[, encoding]])` <ide> <!-- YAML <ide> added: v5.10.0 <ide> changes: <ide> contents will *never contain sensitive data*. <ide> <ide> A `TypeError` will be thrown if `size` is not a number. <ide> <del>### Class Method: Buffer.allocUnsafe(size) <add>### Class Method: `Buffer.allocUnsafe(size)` <ide> <!-- YAML <ide> added: v5.10.0 <ide> changes: <ide> pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal <ide> difference is subtle but can be important when an application requires the <ide> additional performance that [`Buffer.allocUnsafe()`][] provides. <ide> <del>### Class Method: Buffer.allocUnsafeSlow(size) <add>### Class Method: `Buffer.allocUnsafeSlow(size)` <ide> <!-- YAML <ide> added: v5.12.0 <ide> --> <ide> developer has observed undue memory retention in their applications. <ide> <ide> A `TypeError` will be thrown if `size` is not a number. <ide> <del>### Class Method: Buffer.byteLength(string\[, encoding\]) <add>### Class Method: `Buffer.byteLength(string[, encoding])` <ide> <!-- YAML <ide> added: v0.1.90 <ide> changes: <ide> console.log(`${str}: ${str.length} characters, ` + <ide> When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/ <ide> [`SharedArrayBuffer`][], the actual byte length is returned. <ide> <del>### Class Method: Buffer.compare(buf1, buf2) <add>### Class Method: `Buffer.compare(buf1, buf2)` <ide> <!-- YAML <ide> added: v0.11.13 <ide> changes: <ide> console.log(arr.sort(Buffer.compare)); <ide> // (This result is equal to: [buf2, buf1].) <ide> ``` <ide> <del>### Class Method: Buffer.concat(list\[, totalLength\]) <add>### Class Method: `Buffer.concat(list[, totalLength])` <ide> <!-- YAML <ide> added: v0.7.11 <ide> changes: <ide> console.log(bufA.length); <ide> // Prints: 42 <ide> ``` <ide> <del>### Class Method: Buffer.from(array) <add>### Class Method: `Buffer.from(array)` <ide> <!-- YAML <ide> added: v5.10.0 <ide> --> <ide> const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); <ide> A `TypeError` will be thrown if `array` is not an `Array` or other type <ide> appropriate for `Buffer.from()` variants. <ide> <del>### Class Method: Buffer.from(arrayBuffer\[, byteOffset\[, length\]\]) <add>### Class Method: `Buffer.from(arrayBuffer[, byteOffset[, length]])` <ide> <!-- YAML <ide> added: v5.10.0 <ide> --> <ide> console.log(buf.length); <ide> A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`][] or a <ide> [`SharedArrayBuffer`][] or other type appropriate for `Buffer.from()` variants. <ide> <del>### Class Method: Buffer.from(buffer) <add>### Class Method: `Buffer.from(buffer)` <ide> <!-- YAML <ide> added: v5.10.0 <ide> --> <ide> console.log(buf2.toString()); <ide> A `TypeError` will be thrown if `buffer` is not a `Buffer` or other type <ide> appropriate for `Buffer.from()` variants. <ide> <del>### Class Method: Buffer.from(object\[, offsetOrEncoding\[, length\]\]) <add>### Class Method: `Buffer.from(object[, offsetOrEncoding[, length]])` <ide> <!-- YAML <ide> added: v8.2.0 <ide> --> <ide> const buf = Buffer.from(new Foo(), 'utf8'); <ide> A `TypeError` will be thrown if `object` has not mentioned methods or is not of <ide> other type appropriate for `Buffer.from()` variants. <ide> <del>### Class Method: Buffer.from(string\[, encoding\]) <add>### Class Method: `Buffer.from(string[, encoding])` <ide> <!-- YAML <ide> added: v5.10.0 <ide> --> <ide> console.log(buf1.toString('ascii')); <ide> A `TypeError` will be thrown if `string` is not a string or other type <ide> appropriate for `Buffer.from()` variants. <ide> <del>### Class Method: Buffer.isBuffer(obj) <add>### Class Method: `Buffer.isBuffer(obj)` <ide> <!-- YAML <ide> added: v0.1.101 <ide> --> <ide> added: v0.1.101 <ide> <ide> Returns `true` if `obj` is a `Buffer`, `false` otherwise. <ide> <del>### Class Method: Buffer.isEncoding(encoding) <add>### Class Method: `Buffer.isEncoding(encoding)` <ide> <!-- YAML <ide> added: v0.9.1 <ide> --> <ide> console.log(Buffer.isEncoding('')); <ide> // Prints: false <ide> ``` <ide> <del>### Class Property: Buffer.poolSize <add>### Class Property: `Buffer.poolSize` <ide> <!-- YAML <ide> added: v0.11.3 <ide> --> <ide> added: v0.11.3 <ide> This is the size (in bytes) of pre-allocated internal `Buffer` instances used <ide> for pooling. This value may be modified. <ide> <del>### buf\[index\] <add>### `buf[index]` <ide> <!-- YAML <ide> type: property <ide> name: [index] <ide> console.log(buf.toString('ascii')); <ide> // Prints: Node.js <ide> ``` <ide> <del>### buf.buffer <add>### `buf.buffer` <ide> <ide> * {ArrayBuffer} The underlying `ArrayBuffer` object based on <ide> which this `Buffer` object is created. <ide> console.log(buffer.buffer === arrayBuffer); <ide> // Prints: true <ide> ``` <ide> <del>### buf.byteOffset <add>### `buf.byteOffset` <ide> <ide> * {integer} The `byteOffset` on the underlying `ArrayBuffer` object based on <ide> which this `Buffer` object is created. <ide> const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); <ide> new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length); <ide> ``` <ide> <del>### buf.compare(target\[, targetStart\[, targetEnd\[, sourceStart\[, sourceEnd\]\]\]\]) <add>### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])` <ide> <!-- YAML <ide> added: v0.11.13 <ide> changes: <ide> console.log(buf1.compare(buf2, 5, 6, 5)); <ide> [`ERR_OUT_OF_RANGE`][] is thrown if `targetStart < 0`, `sourceStart < 0`, <ide> `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. <ide> <del>### buf.copy(target\[, targetStart\[, sourceStart\[, sourceEnd\]\]\]) <add>### `buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])` <ide> <!-- YAML <ide> added: v0.1.90 <ide> --> <ide> console.log(buf.toString()); <ide> // Prints: efghijghijklmnopqrstuvwxyz <ide> ``` <ide> <del>### buf.entries() <add>### `buf.entries()` <ide> <!-- YAML <ide> added: v1.1.0 <ide> --> <ide> for (const pair of buf.entries()) { <ide> // [5, 114] <ide> ``` <ide> <del>### buf.equals(otherBuffer) <add>### `buf.equals(otherBuffer)` <ide> <!-- YAML <ide> added: v0.11.13 <ide> changes: <ide> console.log(buf1.equals(buf3)); <ide> // Prints: false <ide> ``` <ide> <del>### buf.fill(value\[, offset\[, end\]\]\[, encoding\]) <add>### `buf.fill(value[, offset[, end]][, encoding])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> changes: <ide> console.log(buf.fill('zz', 'hex')); <ide> // Throws an exception. <ide> ``` <ide> <del>### buf.includes(value\[, byteOffset\]\[, encoding\]) <add>### `buf.includes(value[, byteOffset][, encoding])` <ide> <!-- YAML <ide> added: v5.3.0 <ide> --> <ide> console.log(buf.includes('this', 4)); <ide> // Prints: false <ide> ``` <ide> <del>### buf.indexOf(value\[, byteOffset\]\[, encoding\]) <add>### `buf.indexOf(value[, byteOffset][, encoding])` <ide> <!-- YAML <ide> added: v1.5.0 <ide> changes: <ide> If `value` is an empty string or empty `Buffer` and `byteOffset` is less <ide> than `buf.length`, `byteOffset` will be returned. If `value` is empty and <ide> `byteOffset` is at least `buf.length`, `buf.length` will be returned. <ide> <del>### buf.keys() <add>### `buf.keys()` <ide> <!-- YAML <ide> added: v1.1.0 <ide> --> <ide> for (const key of buf.keys()) { <ide> // 5 <ide> ``` <ide> <del>### buf.lastIndexOf(value\[, byteOffset\]\[, encoding\]) <add>### `buf.lastIndexOf(value[, byteOffset][, encoding])` <ide> <!-- YAML <ide> added: v6.0.0 <ide> changes: <ide> console.log(b.lastIndexOf('b', [])); <ide> <ide> If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. <ide> <del>### buf.length <add>### `buf.length` <ide> <!-- YAML <ide> added: v0.1.90 <ide> --> <ide> console.log(buf.length); <ide> // Prints: 5 <ide> ``` <ide> <del>### buf.parent <add>### `buf.parent` <ide> <!-- YAML <ide> deprecated: v8.0.0 <ide> --> <ide> deprecated: v8.0.0 <ide> <ide> The `buf.parent` property is a deprecated alias for `buf.buffer`. <ide> <del>### buf.readBigInt64BE(\[offset\]) <del>### buf.readBigInt64LE(\[offset\]) <add>### `buf.readBigInt64BE([offset])` <add>### `buf.readBigInt64LE([offset])` <ide> <!-- YAML <ide> added: v12.0.0 <ide> --> <ide> the specified endian format (`readBigInt64BE()` returns big endian, <ide> <ide> Integers read from a `Buffer` are interpreted as two's complement signed values. <ide> <del>### buf.readBigUInt64BE(\[offset\]) <del>### buf.readBigUInt64LE(\[offset\]) <add>### `buf.readBigUInt64BE([offset])` <add>### `buf.readBigUInt64LE([offset])` <ide> <!-- YAML <ide> added: v12.0.0 <ide> --> <ide> console.log(buf.readBigUInt64LE(0)); <ide> // Prints: 18446744069414584320n <ide> ``` <ide> <del>### buf.readDoubleBE(\[offset\]) <del>### buf.readDoubleLE(\[offset\]) <add>### `buf.readDoubleBE([offset])` <add>### `buf.readDoubleLE([offset])` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> console.log(buf.readDoubleLE(1)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readFloatBE(\[offset\]) <del>### buf.readFloatLE(\[offset\]) <add>### `buf.readFloatBE([offset])` <add>### `buf.readFloatLE([offset])` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> console.log(buf.readFloatLE(1)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readInt8(\[offset\]) <add>### `buf.readInt8([offset])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> changes: <ide> console.log(buf.readInt8(2)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readInt16BE(\[offset\]) <del>### buf.readInt16LE(\[offset\]) <add>### `buf.readInt16BE([offset])` <add>### `buf.readInt16LE([offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf.readInt16LE(1)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readInt32BE(\[offset\]) <del>### buf.readInt32LE(\[offset\]) <add>### `buf.readInt32BE([offset])` <add>### `buf.readInt32LE([offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf.readInt32LE(1)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readIntBE(offset, byteLength) <del>### buf.readIntLE(offset, byteLength) <add>### `buf.readIntBE(offset, byteLength)` <add>### `buf.readIntLE(offset, byteLength)` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> console.log(buf.readIntBE(1, 0).toString(16)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readUInt8(\[offset\]) <add>### `buf.readUInt8([offset])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> changes: <ide> console.log(buf.readUInt8(2)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readUInt16BE(\[offset\]) <del>### buf.readUInt16LE(\[offset\]) <add>### `buf.readUInt16BE([offset])` <add>### `buf.readUInt16LE([offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf.readUInt16LE(2).toString(16)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readUInt32BE(\[offset\]) <del>### buf.readUInt32LE(\[offset\]) <add>### `buf.readUInt32BE([offset])` <add>### `buf.readUInt32LE([offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf.readUInt32LE(1).toString(16)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.readUIntBE(offset, byteLength) <del>### buf.readUIntLE(offset, byteLength) <add>### `buf.readUIntBE(offset, byteLength)` <add>### `buf.readUIntLE(offset, byteLength)` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> console.log(buf.readUIntBE(1, 6).toString(16)); <ide> // Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <del>### buf.subarray(\[start\[, end\]\]) <add>### `buf.subarray([start[, end]])` <ide> <!-- YAML <ide> added: v3.0.0 <ide> --> <ide> console.log(buf.subarray(-5, -2).toString()); <ide> // (Equivalent to buf.subarray(1, 4).) <ide> ``` <ide> <del>### buf.slice(\[start\[, end\]\]) <add>### `buf.slice([start[, end]])` <ide> <!-- YAML <ide> added: v0.3.0 <ide> changes: <ide> console.log(buf.toString()); <ide> // Prints: buffer <ide> ``` <ide> <del>### buf.swap16() <add>### `buf.swap16()` <ide> <!-- YAML <ide> added: v5.10.0 <ide> --> <ide> const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); <ide> buf.swap16(); // Convert to big-endian UTF-16 text. <ide> ``` <ide> <del>### buf.swap32() <add>### `buf.swap32()` <ide> <!-- YAML <ide> added: v5.10.0 <ide> --> <ide> buf2.swap32(); <ide> // Throws ERR_INVALID_BUFFER_SIZE. <ide> ``` <ide> <del>### buf.swap64() <add>### `buf.swap64()` <ide> <!-- YAML <ide> added: v6.3.0 <ide> --> <ide> buf2.swap64(); <ide> JavaScript cannot encode 64-bit integers. This method is intended <ide> for working with 64-bit floats. <ide> <del>### buf.toJSON() <add>### `buf.toJSON()` <ide> <!-- YAML <ide> added: v0.9.2 <ide> --> <ide> console.log(copy); <ide> // Prints: <Buffer 01 02 03 04 05> <ide> ``` <ide> <del>### buf.toString(\[encoding\[, start\[, end\]\]\]) <add>### `buf.toString([encoding[, start[, end]]])` <ide> <!-- YAML <ide> added: v0.1.90 <ide> --> <ide> console.log(buf2.toString(undefined, 0, 3)); <ide> // Prints: tรฉ <ide> ``` <ide> <del>### buf.values() <add>### `buf.values()` <ide> <!-- YAML <ide> added: v1.1.0 <ide> --> <ide> for (const value of buf) { <ide> // 114 <ide> ``` <ide> <del>### buf.write(string\[, offset\[, length\]\]\[, encoding\]) <add>### `buf.write(string[, offset[, length]][, encoding])` <ide> <!-- YAML <ide> added: v0.1.90 <ide> --> <ide> console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); <ide> // Prints: 12 bytes: ยฝ + ยผ = ยพ <ide> ``` <ide> <del>### buf.writeBigInt64BE(value\[, offset\]) <del>### buf.writeBigInt64LE(value\[, offset\]) <add>### `buf.writeBigInt64BE(value[, offset])` <add>### `buf.writeBigInt64LE(value[, offset])` <ide> <!-- YAML <ide> added: v12.0.0 <ide> --> <ide> console.log(buf); <ide> // Prints: <Buffer 01 02 03 04 05 06 07 08> <ide> ``` <ide> <del>### buf.writeBigUInt64BE(value\[, offset\]) <del>### buf.writeBigUInt64LE(value\[, offset\]) <add>### `buf.writeBigUInt64BE(value[, offset])` <add>### `buf.writeBigUInt64LE(value[, offset])` <ide> <!-- YAML <ide> added: v12.0.0 <ide> --> <ide> console.log(buf); <ide> // Prints: <Buffer de fa ce ca fe fa ca de> <ide> ``` <ide> <del>### buf.writeDoubleBE(value\[, offset\]) <del>### buf.writeDoubleLE(value\[, offset\]) <add>### `buf.writeDoubleBE(value[, offset])` <add>### `buf.writeDoubleLE(value[, offset])` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer 77 be 9f 1a 2f dd 5e 40> <ide> ``` <ide> <del>### buf.writeFloatBE(value\[, offset\]) <del>### buf.writeFloatLE(value\[, offset\]) <add>### `buf.writeFloatBE(value[, offset])` <add>### `buf.writeFloatLE(value[, offset])` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer bb fe 4a 4f> <ide> ``` <ide> <del>### buf.writeInt8(value\[, offset\]) <add>### `buf.writeInt8(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer 02 fe> <ide> ``` <ide> <del>### buf.writeInt16BE(value\[, offset\]) <del>### buf.writeInt16LE(value\[, offset\]) <add>### `buf.writeInt16BE(value[, offset])` <add>### `buf.writeInt16LE(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer 01 02 04 03> <ide> ``` <ide> <del>### buf.writeInt32BE(value\[, offset\]) <del>### buf.writeInt32LE(value\[, offset\]) <add>### `buf.writeInt32BE(value[, offset])` <add>### `buf.writeInt32LE(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer 01 02 03 04 08 07 06 05> <ide> ``` <ide> <del>### buf.writeIntBE(value, offset, byteLength) <del>### buf.writeIntLE(value, offset, byteLength) <add>### `buf.writeIntBE(value, offset, byteLength)` <add>### `buf.writeIntLE(value, offset, byteLength)` <ide> <!-- YAML <ide> added: v0.11.15 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer ab 90 78 56 34 12> <ide> ``` <ide> <del>### buf.writeUInt8(value\[, offset\]) <add>### `buf.writeUInt8(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.0 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer 03 04 23 42> <ide> ``` <ide> <del>### buf.writeUInt16BE(value\[, offset\]) <del>### buf.writeUInt16LE(value\[, offset\]) <add>### `buf.writeUInt16BE(value[, offset])` <add>### `buf.writeUInt16LE(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer ad de ef be> <ide> ``` <ide> <del>### buf.writeUInt32BE(value\[, offset\]) <del>### buf.writeUInt32LE(value\[, offset\]) <add>### `buf.writeUInt32BE(value[, offset])` <add>### `buf.writeUInt32LE(value[, offset])` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer ce fa ed fe> <ide> ``` <ide> <del>### buf.writeUIntBE(value, offset, byteLength) <del>### buf.writeUIntLE(value, offset, byteLength) <add>### `buf.writeUIntBE(value, offset, byteLength)` <add>### `buf.writeUIntLE(value, offset, byteLength)` <ide> <!-- YAML <ide> added: v0.5.5 <ide> changes: <ide> console.log(buf); <ide> // Prints: <Buffer ab 90 78 56 34 12> <ide> ``` <ide> <del>## buffer.INSPECT_MAX_BYTES <add>## `buffer.INSPECT_MAX_BYTES` <ide> <!-- YAML <ide> added: v0.5.4 <ide> --> <ide> Returns the maximum number of bytes that will be returned when <ide> This is a property on the `buffer` module returned by <ide> `require('buffer')`, not on the `Buffer` global or a `Buffer` instance. <ide> <del>## buffer.kMaxLength <add>## `buffer.kMaxLength` <ide> <!-- YAML <ide> added: v3.0.0 <ide> --> <ide> An alias for [`buffer.constants.MAX_LENGTH`][]. <ide> This is a property on the `buffer` module returned by <ide> `require('buffer')`, not on the `Buffer` global or a `Buffer` instance. <ide> <del>## buffer.transcode(source, fromEnc, toEnc) <add>## `buffer.transcode(source, fromEnc, toEnc)` <ide> <!-- YAML <ide> added: v7.1.0 <ide> changes: <ide> with `?` in the transcoded `Buffer`. <ide> This is a property on the `buffer` module returned by <ide> `require('buffer')`, not on the `Buffer` global or a `Buffer` instance. <ide> <del>## Class: SlowBuffer <add>## Class: `SlowBuffer` <ide> <!-- YAML <ide> deprecated: v6.0.0 <ide> --> <ide> socket.on('readable', () => { <ide> Use of `SlowBuffer` should be used only as a last resort *after* a developer <ide> has observed undue memory retention in their applications. <ide> <del>### new SlowBuffer(size) <add>### `new SlowBuffer(size)` <ide> <!-- YAML <ide> deprecated: v6.0.0 <ide> --> <ide> added: v8.2.0 <ide> `buffer.constants` is a property on the `buffer` module returned by <ide> `require('buffer')`, not on the `Buffer` global or a `Buffer` instance. <ide> <del>### buffer.constants.MAX_LENGTH <add>### `buffer.constants.MAX_LENGTH` <ide> <!-- YAML <ide> added: v8.2.0 <ide> --> <ide> On 64-bit architectures, this value is `(2^31)-1` (~2GB). <ide> <ide> This value is also available as [`buffer.kMaxLength`][]. <ide> <del>### buffer.constants.MAX_STRING_LENGTH <add>### `buffer.constants.MAX_STRING_LENGTH` <ide> <!-- YAML <ide> added: v8.2.0 <ide> -->
1
Javascript
Javascript
add isobject3d unittest
a221c4a17770c4b79ba9b4055acb3e0ba4fd4f55
<ide><path>test/unit/src/core/Object3D.tests.js <ide> export default QUnit.module( 'Core', () => { <ide> } ); <ide> <ide> // PUBLIC STUFF <del> QUnit.todo( 'isObject3D', ( assert ) => { <add> QUnit.test( 'isObject3D', ( assert ) => { <ide> <del> assert.ok( false, 'everything\'s gonna be alright' ); <add> const object = new Object3D(); <add> assert.ok( object.isObject3D, 'Object3D.isObject3D should be true' ); <add> <add> const object2 = {}; <add> assert.ok( object2.isObject3D === undefined, 'other object isObject3D should be undefined' ); <ide> <ide> } ); <ide>
1
Python
Python
fix dagrun.conf when using trigger_dag api
31cab8ffbba7fa70a524e5809361f1e1f4306e99
<ide><path>airflow/models/dagrun.py <ide> def __init__( <ide> self.execution_date = execution_date <ide> self.start_date = start_date <ide> self.external_trigger = external_trigger <del> self.conf = conf <add> self.conf = conf or {} <ide> self.state = state <ide> self.run_type = run_type <ide> super().__init__() <ide><path>tests/api/common/experimental/test_trigger_dag.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> <del>import json <ide> import unittest <ide> from unittest import mock <ide> <add>from parameterized import parameterized <add> <ide> from airflow.api.common.experimental.trigger_dag import _trigger_dag <ide> from airflow.exceptions import AirflowException <ide> from airflow.models import DAG, DagRun <ide> from airflow.utils import timezone <add>from tests.test_utils import db <ide> <ide> <ide> class TestTriggerDag(unittest.TestCase): <ide> <add> def setUp(self) -> None: <add> db.clear_db_runs() <add> <add> def tearDown(self) -> None: <add> db.clear_db_runs() <add> <ide> @mock.patch('airflow.models.DagRun') <ide> @mock.patch('airflow.models.DagBag') <ide> def test_trigger_dag_dag_not_found(self, dag_bag_mock, dag_run_mock): <ide> def test_trigger_dag_include_nested_subdags(self, dag_bag_mock, dag_run_mock, da <ide> <ide> self.assertEqual(3, len(triggers)) <ide> <del> @mock.patch('airflow.models.DagBag') <del> def test_trigger_dag_with_str_conf(self, dag_bag_mock): <del> dag_id = "trigger_dag_with_str_conf" <del> dag = DAG(dag_id) <del> dag_bag_mock.dags = [dag_id] <del> dag_bag_mock.get_dag.return_value = dag <del> conf = "{\"foo\": \"bar\"}" <del> dag_run = DagRun() <del> triggers = _trigger_dag( <del> dag_id, <del> dag_bag_mock, <del> dag_run, <del> run_id=None, <del> conf=conf, <del> execution_date=None, <del> replace_microseconds=True) <del> <del> self.assertEqual(triggers[0].conf, json.loads(conf)) <del> <ide> @mock.patch('airflow.models.DagBag') <ide> def test_trigger_dag_with_too_early_start_date(self, dag_bag_mock): <ide> dag_id = "trigger_dag_with_too_early_start_date" <ide> def test_trigger_dag_with_valid_start_date(self, dag_bag_mock): <ide> <ide> assert len(triggers) == 1 <ide> <add> @parameterized.expand([ <add> (None, {}), <add> ({"foo": "bar"}, {"foo": "bar"}), <add> ('{"foo": "bar"}', {"foo": "bar"}), <add> ]) <ide> @mock.patch('airflow.models.DagBag') <del> def test_trigger_dag_with_dict_conf(self, dag_bag_mock): <del> dag_id = "trigger_dag_with_dict_conf" <add> def test_trigger_dag_with_conf(self, conf, expected_conf, dag_bag_mock): <add> dag_id = "trigger_dag_with_conf" <ide> dag = DAG(dag_id) <ide> dag_bag_mock.dags = [dag_id] <ide> dag_bag_mock.get_dag.return_value = dag <del> conf = dict(foo="bar") <ide> dag_run = DagRun() <ide> triggers = _trigger_dag( <ide> dag_id, <ide> def test_trigger_dag_with_dict_conf(self, dag_bag_mock): <ide> execution_date=None, <ide> replace_microseconds=True) <ide> <del> self.assertEqual(triggers[0].conf, conf) <add> self.assertEqual(triggers[0].conf, expected_conf)
2
PHP
PHP
revert the throw thing
88430a39968a33dbed94b87ee4fb8ae1c6879b48
<ide><path>src/Model/Behavior/TreeBehavior.php <ide> public function findChildren($query, $options) { <ide> * <ide> * @param integer|string $id The ID of the record to move <ide> * @param integer|boolean $number How many places to move the node, or true to move to first position <add> * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found <ide> * @return boolean true on success, false on failure <ide> */ <ide> public function moveUp($id, $number = 1) { <ide> public function moveUp($id, $number = 1) { <ide> ->first(); <ide> <ide> if (!$node) { <del> return false; <add> throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$id}\" was not found in the tree."); <ide> } <ide> <ide> if ($node->{$parent}) { <ide> public function moveUp($id, $number = 1) { <ide> * <ide> * @param integer|string $id The ID of the record to move <ide> * @param integer|boolean $number How many places to move the node or true to move to last position <add> * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found <ide> * @return boolean true on success, false on failure <ide> */ <ide> public function moveDown($id, $number = 1) { <ide> public function moveDown($id, $number = 1) { <ide> ->first(); <ide> <ide> if (!$node) { <del> return false; <add> throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$id}\" was not found in the tree."); <ide> } <ide> <ide> if ($node->{$parent}) { <ide><path>tests/TestCase/Model/Behavior/TreeBehaviorTest.php <ide> public function testMoveUp() { <ide> $this->assertFalse($this->table->moveUp(1, 0)); <ide> $this->assertFalse($this->table->moveUp(1, -10)); <ide> <del> // move unexisting node <del> $this->assertFalse($table->moveUp(500, 1)); <del> <ide> // move inner node <ide> $result = $table->moveUp(3, 1); <ide> $nodes = $table->find('children', ['for' => 1])->all(); <ide> public function testMoveUp() { <ide> $this->assertEquals([8, 1, 6], $nodes->extract('id')->toArray()); <ide> } <ide> <add>/** <add> * Tests that moveUp() will throw an exception if the node was not found <add> * <add> * @expectedException \Cake\ORM\Error\RecordNotFoundException <add> * @return void <add> */ <add> public function testMoveUpException() { <add> $table = TableRegistry::get('MenuLinkTrees'); <add> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]); <add> $table->moveUp(500, 1); <add> } <add> <ide> /** <ide> * Tests the moveDown() method <ide> * <ide> public function testMoveDown() { <ide> $this->assertFalse($this->table->moveUp(8, -10)); <ide> <ide> // move inner node <del> $nodeIds = []; <ide> $result = $table->moveDown(2, 1); <ide> $nodes = $table->find('children', ['for' => 1])->all(); <ide> $this->assertEquals([3, 4, 5, 2], $nodes->extract('id')->toArray()); <ide> $this->assertTrue($result); <ide> <del> // move unexisting node <del> $this->assertFalse($table->moveDown(500, 1)); <del> <ide> // move leaf <ide> $this->assertFalse( $table->moveDown(5, 1)); <ide> <ide> public function testMoveDown() { <ide> $this->assertEquals([6, 8, 1], $nodes->extract('id')->toArray()); <ide> } <ide> <add>/** <add> * Tests that moveDown() will throw an exception if the node was not found <add> * <add> * @expectedException \Cake\ORM\Error\RecordNotFoundException <add> * @return void <add> */ <add> public function testMoveDownException() { <add> $table = TableRegistry::get('MenuLinkTrees'); <add> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]); <add> $table->moveDown(500, 1); <add> } <add> <ide> /** <ide> * Tests the recover function <ide> *
2
Mixed
Javascript
add build option for setting the amd name
7e8a91c205723f11cd00c8834f348a649ab15926
<ide><path>README.md <ide> Some example modules that can be excluded are: <ide> - **event/alias**: All event attaching/triggering shorthands like `.click()` or `.mouseover()`. <ide> - **offset**: The `.offset()`, `.position()`, `.offsetParent()`, `.scrollLeft()`, and `.scrollTop()` methods. <ide> - **wrap**: The `.wrap()`, `.wrapAll()`, `.wrapInner()`, and `.unwrap()` methods. <del>- **exports/amd**: Exclude the AMD definition. <del>- **exports/global**: Exclude the attachment of global jQuery variables ($ and jQuery) to the window. <ide> - **core/ready**: Exclude the ready module if you place your scripts at the end of the body. Any ready callbacks bound with `jQuery()` will simply be called immediately. However, `jQuery(document).ready()` will not be a function and `.on("ready", ...)` or similar will not be triggered. <ide> - **deferred**: Exclude jQuery.Deferred. This also removes jQuery.Callbacks. *Note* that modules that depend on jQuery.Deferred(AJAX, effects, core/ready) will not be removed and will still expect jQuery.Deferred to be there. Include your own jQuery.Deferred implementation or exclude those modules as well (`grunt custom:-deferred,-ajax,-effects,-core/ready`). <add>- **exports/global**: Exclude the attachment of global jQuery variables ($ and jQuery) to the window. <add>- **exports/amd**: Exclude the AMD definition. <ide> <ide> As a special case, you may also replace Sizzle by using a special flag `grunt custom:-sizzle`. <ide> <ide> As a special case, you may also replace Sizzle by using a special flag `grunt cu <ide> <ide> The build process shows a message for each dependent module it excludes or includes. <ide> <add>##### AMD name <add> <add>As an option, you can set the module name for jQuery's AMD definition. By default, it is set to "jquery", which plays nicely with plugins and third-party libraries, but there may be cases where you'd like to change this. Simply set the `"amd"` option: <add> <add>```bash <add>grunt custom --amd="custom-name" <add>``` <add> <add>Or, to define anonymously, set the name to an empty string. <add> <add>```bash <add>grunt custom --amd="" <add>``` <add> <add>#### Custom Build Examples <add> <ide> To create a custom build of the latest stable version, first check out the version: <ide> <ide> ```bash <ide> Then, make sure all Node dependencies are installed: <ide> npm install <ide> ``` <ide> <del>Create the custom build, use the `grunt custom` option, listing the modules to be excluded. Examples: <add>Create the custom build using the `grunt custom` option, listing the modules to be excluded. <ide> <ide> Exclude all **ajax** functionality: <ide> <ide><path>build/tasks/build.js <ide> module.exports = function( grunt ) { <ide> * @param {String} contents The contents to be written (including their AMD wrappers) <ide> */ <ide> function convert( name, path, contents ) { <add> var amdName; <ide> // Convert var modules <ide> if ( /.\/var\//.test( path ) ) { <ide> contents = contents <ide> module.exports = function( grunt ) { <ide> // Remove EXPOSE lines from Sizzle <ide> .replace( /\/\/\s*EXPOSE[\w\W]*\/\/\s*EXPOSE/, "return Sizzle;" ); <ide> <add> // AMD Name <add> } else if ( (amdName = grunt.option( "amd" )) != null && /^exports\/amd$/.test( name ) ) { <add> // Remove the comma for anonymous defines <add> contents = contents <add> .replace( /(\s*)"jquery"(\,\s*)/, amdName ? "$1\"" + amdName + "\"$2" : "" ); <add> <ide> } else { <ide> <ide> // Ignore jQuery's exports (the only necessary one) <ide> module.exports = function( grunt ) { <ide> // <ide> // grunt build:*:*:+ajax:-dimensions:-effects:-offset <ide> grunt.registerTask( "custom", function() { <del> var args = [].slice.call( arguments ), <add> var args = this.args, <ide> modules = args.length ? args[ 0 ].replace( /,/g, ":" ) : ""; <ide> <ide> grunt.log.writeln( "Creating custom build...\n" ); <ide> <del> grunt.task.run([ "build:*:*:" + modules, "uglify", "dist" ]); <add> grunt.task.run([ "build:*:*" + (modules ? ":" + modules : ""), "uglify", "dist" ]); <ide> }); <ide> };
2
Ruby
Ruby
move `assert_raise` into behavior classes
aabc27fe15de6df988c8fb9caa658e85ff65a068
<ide><path>activesupport/test/cache/behaviors/failure_raising_behavior.rb <ide> module FailureRaisingBehavior <ide> def test_fetch_read_failure_raises <ide> @cache.write("foo", "bar") <ide> <del> emulating_unavailability do |cache| <del> cache.fetch("foo") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.fetch("foo") <add> end <ide> end <ide> end <ide> <ide> def test_fetch_with_block_read_failure_raises <ide> @cache.write("foo", "bar") <ide> <del> emulating_unavailability do |cache| <del> cache.fetch("foo") { '1' } <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.fetch("foo") { "1" } <add> end <ide> end <add> <add> assert_equal "bar", @cache.read("foo") <ide> end <ide> <ide> def test_read_failure_raises <ide> @cache.write("foo", "bar") <ide> <del> emulating_unavailability do |cache| <del> cache.read("foo") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.read("foo") <add> end <ide> end <ide> end <ide> <ide> def test_read_multi_failure_raises <ide> @cache.write_multi("foo" => "bar", "baz" => "quux") <ide> <del> emulating_unavailability do |cache| <del> cache.read_multi("foo", "baz") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.read_multi("foo", "baz") <add> end <ide> end <ide> end <ide> <ide> def test_write_failure_raises <del> emulating_unavailability do |cache| <del> cache.write("foo", "bar") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.write("foo", "bar") <add> end <ide> end <ide> end <ide> <ide> def test_write_multi_failure_raises <del> emulating_unavailability do |cache| <del> cache.write_multi("foo" => "bar", "baz" => "quux") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.write_multi("foo" => "bar", "baz" => "quux") <add> end <ide> end <ide> end <ide> <ide> def test_fetch_multi_failure_raises <ide> @cache.write_multi("foo" => "bar", "baz" => "quux") <ide> <del> emulating_unavailability do |cache| <del> cache.fetch_multi("foo", "baz") { |k| "unavailable" } <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.fetch_multi("foo", "baz") { |k| "unavailable" } <add> end <ide> end <ide> end <ide> <ide> def test_delete_failure_raises <ide> @cache.write("foo", "bar") <ide> <del> emulating_unavailability do |cache| <del> cache.delete("foo") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.delete("foo") <add> end <ide> end <ide> end <ide> <ide> def test_exist_failure_raises <ide> @cache.write("foo", "bar") <ide> <del> emulating_unavailability do |cache| <del> cache.exist?("foo") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.exist?("foo") <add> end <ide> end <ide> end <ide> <ide> def test_increment_failure_raises <ide> @cache.write("foo", 1, raw: true) <ide> <del> emulating_unavailability do |cache| <del> cache.increment("foo") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.increment("foo") <add> end <ide> end <ide> end <ide> <ide> def test_decrement_failure_raises <ide> @cache.write("foo", 1, raw: true) <ide> <del> emulating_unavailability do |cache| <del> cache.decrement("foo") <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.decrement("foo") <add> end <ide> end <ide> end <ide> <ide> def test_clear_failure_returns_nil <del> emulating_unavailability do |cache| <del> assert_nil cache.clear <add> assert_raise Redis::BaseError do <add> emulating_unavailability do |cache| <add> cache.clear <add> end <ide> end <ide> end <ide> end <ide><path>activesupport/test/cache/stores/redis_cache_store_test.rb <ide> def emulating_unavailability <ide> old_client = Redis.send(:remove_const, :Client) <ide> Redis.const_set(:Client, UnavailableRedisClient) <ide> <del> assert_raise Redis::BaseConnectionError do <del> yield ActiveSupport::Cache::RedisCacheStore.new(namespace: @namespace, error_handler: -> (method:, returning:, exception:) { raise exception }) <del> end <add> yield ActiveSupport::Cache::RedisCacheStore.new(namespace: @namespace, <add> error_handler: -> (method:, returning:, exception:) { raise exception }) <ide> ensure <ide> Redis.send(:remove_const, :Client) <ide> Redis.const_set(:Client, old_client) <ide> def emulating_unavailability <ide> old_client = Redis.send(:remove_const, :Client) <ide> Redis.const_set(:Client, MaxClientsReachedRedisClient) <ide> <del> assert_raise Redis::CommandError do <del> yield ActiveSupport::Cache::RedisCacheStore.new(namespace: @namespace, error_handler: -> (method:, returning:, exception:) { raise exception }) <del> end <add> yield ActiveSupport::Cache::RedisCacheStore.new(namespace: @namespace, <add> error_handler: -> (method:, returning:, exception:) { raise exception }) <ide> ensure <ide> Redis.send(:remove_const, :Client) <ide> Redis.const_set(:Client, old_client)
2
Ruby
Ruby
allow "press enter" to be a \r
dfa75f9230f75060a693add842fcdc5648398c69
<ide><path>install_homebrew.rb <ide> def macos_version <ide> if STDIN.tty? <ide> puts <ide> puts "Press enter to continue" <del> abort unless getc == 13 <add> c = getc <add> # we test for \r and \n because some stuff does \r instead <add> abort unless c == 13 or c == 10 <ide> end <ide> <ide> if File.directory? "/usr/local"
1
Javascript
Javascript
increase coverage of process.emitwarning
9e698bd6db036e7eaf8f9aa47c9b90cd721818f5
<ide><path>test/parallel/test-process-emitwarning.js <ide> process.on('warning', common.mustCall((warning) => { <ide> assert(warning); <ide> assert(/^(Warning|CustomWarning)/.test(warning.name)); <ide> assert(warning.message, 'A Warning'); <del>}, 3)); <add>}, 7)); <ide> <ide> process.emitWarning('A Warning'); <ide> process.emitWarning('A Warning', 'CustomWarning'); <add>process.emitWarning('A Warning', CustomWarning); <add>process.emitWarning('A Warning', 'CustomWarning', CustomWarning); <ide> <ide> function CustomWarning() { <ide> Error.call(this); <ide> function CustomWarning() { <ide> util.inherits(CustomWarning, Error); <ide> process.emitWarning(new CustomWarning()); <ide> <add>const warningNoToString = new CustomWarning(); <add>warningNoToString.toString = null; <add>process.emitWarning(warningNoToString); <add> <add>const warningThrowToString = new CustomWarning(); <add>warningThrowToString.toString = function() { <add> throw new Error('invalid toString'); <add>}; <add>process.emitWarning(warningThrowToString); <add> <ide> // TypeError is thrown on invalid output <ide> assert.throws(() => process.emitWarning(1), TypeError); <ide> assert.throws(() => process.emitWarning({}), TypeError);
1
Ruby
Ruby
remove the global router
226dfc2681c98deaf14e4ae82e973d1d5caedd68
<ide><path>actionpack/lib/action_controller.rb <ide> module ActionController <ide> autoload :SessionManagement <ide> autoload :Streaming <ide> autoload :Testing <del> autoload :UrlFor <add> # ROUTES TODO: Proxy UrlFor to Rails.application.routes.url_helpers <ide> autoload :Verification <ide> end <ide> <ide><path>actionpack/lib/action_controller/base.rb <ide> class Base < Metal <ide> include ActionController::Helpers <ide> <ide> include ActionController::HideActions <del> include ActionController::UrlFor <add> # include ActionController::UrlFor <ide> include ActionController::Redirecting <ide> include ActionController::Rendering <ide> include ActionController::Renderers::All <ide><path>actionpack/lib/action_controller/deprecated.rb <ide> ActionController::AbstractRequest = ActionController::Request = ActionDispatch::Request <ide> ActionController::AbstractResponse = ActionController::Response = ActionDispatch::Response <ide> ActionController::Routing = ActionDispatch::Routing <del>ActionController::UrlWriter = ActionController::UrlFor <add># ROUTES TODO: Figure out how to deprecate this. <add># ActionController::UrlWriter = ActionController::UrlFor <ide><path>actionpack/lib/action_controller/metal/head.rb <ide> module ActionController <ide> module Head <ide> extend ActiveSupport::Concern <del> include ActionController::UrlFor <ide> <ide> # Return a response that has no content (merely headers). The options <ide> # argument is interpreted to be a hash of header names and values. <ide> def head(status, options = {}) <ide> end <ide> <ide> self.status = status <add> # ROUTES TODO: Figure out how to rescue from a no method error <add> # This is needed only if you wire up a controller yourself, and <add> # this not working would be baffling without a better error <ide> self.location = url_for(location) if location <ide> self.content_type = Mime[formats.first] <ide> self.response_body = " " <ide><path>actionpack/lib/action_controller/metal/redirecting.rb <ide> module Redirecting <ide> <ide> include AbstractController::Logger <ide> include ActionController::RackDelegation <del> include ActionController::UrlFor <ide> <ide> # Redirects the browser to the target specified in +options+. This parameter can take one of three forms: <ide> # <ide> def _compute_redirect_to_location(options) <ide> raise RedirectBackError unless refer = request.headers["Referer"] <ide> refer <ide> else <add> # ROUTES TODO: Figure out how to rescue from a no method error <add> # This is needed only if you wire up a controller yourself, and <add> # this not working would be baffling without a better error <ide> url_for(options) <ide> end.gsub(/[\r\n]/, '') <ide> end <ide><path>actionpack/lib/action_controller/metal/url_for.rb <del>require 'active_support/core_ext/class/attribute' <del>require 'active_support/core_ext/module/attribute_accessors' <del> <del>module ActionController <del> # In <b>routes.rb</b> one defines URL-to-controller mappings, but the reverse <del> # is also possible: an URL can be generated from one of your routing definitions. <del> # URL generation functionality is centralized in this module. <del> # <del> # See ActionDispatch::Routing and ActionController::Resources for general <del> # information about routing and routes.rb. <del> # <del> # <b>Tip:</b> If you need to generate URLs from your models or some other place, <del> # then ActionController::UrlFor is what you're looking for. Read on for <del> # an introduction. <del> # <del> # == URL generation from parameters <del> # <del> # As you may know, some functions - such as ActionController::Base#url_for <del> # and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set <del> # of parameters. For example, you've probably had the chance to write code <del> # like this in one of your views: <del> # <del> # <%= link_to('Click here', :controller => 'users', <del> # :action => 'new', :message => 'Welcome!') %> <del> # <del> # #=> Generates a link to: /users/new?message=Welcome%21 <del> # <del> # link_to, and all other functions that require URL generation functionality, <del> # actually use ActionController::UrlFor under the hood. And in particular, <del> # they use the ActionController::UrlFor#url_for method. One can generate <del> # the same path as the above example by using the following code: <del> # <del> # include UrlFor <del> # url_for(:controller => 'users', <del> # :action => 'new', <del> # :message => 'Welcome!', <del> # :only_path => true) <del> # # => "/users/new?message=Welcome%21" <del> # <del> # Notice the <tt>:only_path => true</tt> part. This is because UrlFor has no <del> # information about the website hostname that your Rails app is serving. So if you <del> # want to include the hostname as well, then you must also pass the <tt>:host</tt> <del> # argument: <del> # <del> # include UrlFor <del> # url_for(:controller => 'users', <del> # :action => 'new', <del> # :message => 'Welcome!', <del> # :host => 'www.example.com') # Changed this. <del> # # => "http://www.example.com/users/new?message=Welcome%21" <del> # <del> # By default, all controllers and views have access to a special version of url_for, <del> # that already knows what the current hostname is. So if you use url_for in your <del> # controllers or your views, then you don't need to explicitly pass the <tt>:host</tt> <del> # argument. <del> # <del> # For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for. <del> # So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for' <del> # in full. However, mailers don't have hostname information, and what's why you'll still <del> # have to specify the <tt>:host</tt> argument when generating URLs in mailers. <del> # <del> # <del> # == URL generation for named routes <del> # <del> # UrlFor also allows one to access methods that have been auto-generated from <del> # named routes. For example, suppose that you have a 'users' resource in your <del> # <b>routes.rb</b>: <del> # <del> # map.resources :users <del> # <del> # This generates, among other things, the method <tt>users_path</tt>. By default, <del> # this method is accessible from your controllers, views and mailers. If you need <del> # to access this auto-generated method from other places (such as a model), then <del> # you can do that by including ActionController::UrlFor in your class: <del> # <del> # class User < ActiveRecord::Base <del> # include ActionController::UrlFor <del> # <del> # def base_uri <del> # user_path(self) <del> # end <del> # end <del> # <del> # User.find(1).base_uri # => "/users/1" <del> # <del> module UrlFor <del> extend ActiveSupport::Concern <del> <del> included do <del> ActionDispatch::Routing::Routes.install_helpers(self) <del> <del> # Including in a class uses an inheritable hash. Modules get a plain hash. <del> if respond_to?(:class_attribute) <del> class_attribute :default_url_options <del> else <del> mattr_accessor :default_url_options <del> end <del> <del> self.default_url_options = {} <del> end <del> <del> # Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in <del> # the form of a hash, just like the one you would use for url_for directly. Example: <del> # <del> # def default_url_options(options) <del> # { :project => @project.active? ? @project.url_name : "unknown" } <del> # end <del> # <del> # As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the <del> # urls as they stem from the business domain. Please note that any individual url_for call can always override the defaults set <del> # by this method. <del> def default_url_options(options = nil) <del> self.class.default_url_options <del> end <del> <del> def rewrite_options(options) #:nodoc: <del> if options.delete(:use_defaults) != false && (defaults = default_url_options(options)) <del> defaults.merge(options) <del> else <del> options <del> end <del> end <del> <del> # Generate a url based on the options provided, default_url_options and the <del> # routes defined in routes.rb. The following options are supported: <del> # <del> # * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+. <del> # * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'. <del> # * <tt>:host</tt> - Specifies the host the link should be targeted at. <del> # If <tt>:only_path</tt> is false, this option must be <del> # provided either explicitly, or via +default_url_options+. <del> # * <tt>:port</tt> - Optionally specify the port to connect to. <del> # * <tt>:anchor</tt> - An anchor name to be appended to the path. <del> # * <tt>:skip_relative_url_root</tt> - If true, the url is not constructed using the <del> # +relative_url_root+ set in ActionController::Base.relative_url_root. <del> # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/" <del> # <del> # Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to <del> # +url_for+ is forwarded to the Routes module. <del> # <del> # Examples: <del> # <del> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :port=>'8080' # => 'http://somehost.org:8080/tasks/testing' <del> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' <del> # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' <del> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' <del> def url_for(options = {}) <del> options ||= {} <del> case options <del> when String <del> options <del> when Hash <del> _url_rewriter.rewrite(rewrite_options(options)) <del> else <del> polymorphic_url(options) <del> end <del> end <del> <del> protected <del> <del> def _url_rewriter <del> ActionController::UrlRewriter <del> end <del> end <del>end <ide><path>actionpack/lib/action_controller/test_case.rb <ide> def self.new_escaped(strings) <ide> end <ide> end <ide> <del> def assign_parameters(controller_path, action, parameters = {}) <add> def assign_parameters(router, controller_path, action, parameters = {}) <ide> parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action) <del> extra_keys = ActionDispatch::Routing::Routes.extra_keys(parameters) <add> extra_keys = router.extra_keys(parameters) <ide> non_path_parameters = get? ? query_parameters : request_parameters <ide> parameters.each do |key, value| <ide> if value.is_a? Fixnum <ide> def xml_http_request(request_method, action, parameters = nil, session = nil, fl <ide> def process(action, parameters = nil, session = nil, flash = nil, http_method = 'GET') <ide> # Sanity check for required instance variables so we can give an <ide> # understandable error message. <del> %w(@controller @request @response).each do |iv_name| <add> %w(@router @controller @request @response).each do |iv_name| <ide> if !(instance_variable_names.include?(iv_name) || instance_variable_names.include?(iv_name.to_sym)) || instance_variable_get(iv_name).nil? <ide> raise "#{iv_name} is nil: make sure you set it in your test's setup method." <ide> end <ide> def process(action, parameters = nil, session = nil, flash = nil, http_method = <ide> @request.env['REQUEST_METHOD'] = http_method <ide> <ide> parameters ||= {} <del> @request.assign_parameters(@controller.class.name.underscore.sub(/_controller$/, ''), action.to_s, parameters) <add> @request.assign_parameters(@router, @controller.class.name.underscore.sub(/_controller$/, ''), action.to_s, parameters) <ide> <ide> @request.session = ActionController::TestSession.new(session) unless session.nil? <ide> @request.session["flash"] = @request.flash.update(flash || {}) <ide> def build_request_uri(action, parameters) <ide> options.update(:only_path => true, :action => action) <ide> <ide> url = ActionController::UrlRewriter.new(@request, parameters) <del> @request.request_uri = url.rewrite(options) <add> @request.request_uri = url.rewrite(@router, options) <ide> end <ide> end <ide> end <ide><path>actionpack/lib/action_controller/url_rewriter.rb <ide> def initialize(request, parameters) <ide> @request, @parameters = request, parameters <ide> end <ide> <del> def rewrite(options = {}) <add> def rewrite(router, options = {}) <ide> options[:host] ||= @request.host_with_port <ide> options[:protocol] ||= @request.protocol <ide> <del> self.class.rewrite(options, @request.symbolized_path_parameters) do |options| <add> self.class.rewrite(router, options, @request.symbolized_path_parameters) do |options| <ide> process_path_options(options) <ide> end <ide> end <ide> def to_str <ide> <ide> alias_method :to_s, :to_str <ide> <del> def self.rewrite(options, path_segments=nil) <add> # ROUTES TODO: Class method code smell <add> def self.rewrite(router, options, path_segments=nil) <ide> rewritten_url = "" <ide> <ide> unless options[:only_path] <ide> def self.rewrite(options, path_segments=nil) <ide> <ide> path_options = options.except(*RESERVED_OPTIONS) <ide> path_options = yield(path_options) if block_given? <del> path = Routing::Routes.generate(path_options, path_segments || {}) <add> path = router.generate(path_options, path_segments || {}) <ide> <ide> rewritten_url << ActionController::Base.relative_url_root.to_s unless options[:skip_relative_url_root] <ide> rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) <ide><path>actionpack/lib/action_dispatch/routing.rb <ide> module Routing <ide> autoload :Route, 'action_dispatch/routing/route' <ide> autoload :Routes, 'action_dispatch/routing/routes' <ide> autoload :RouteSet, 'action_dispatch/routing/route_set' <add> autoload :UrlFor, 'action_dispatch/routing/url_for' <ide> <ide> SEPARATORS = %w( / . ? ) <ide> HTTP_METHODS = [:get, :head, :post, :put, :delete, :options] <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def install_helpers(destinations = [ActionController::Base, ActionView::Base], r <ide> named_routes.install(destinations, regenerate_code) <ide> end <ide> <add> # ROUTES TODO: Revisit the name of these methods <add> def url_helpers <add> @url_helpers ||= begin <add> router = self <add> Module.new do <add> extend ActiveSupport::Concern <add> include UrlFor <add> <add> define_method(:_router) { router } <add> end <add> end <add> end <add> <add> def named_url_helpers <add> @named_url_helpers ||= begin <add> router = self <add> <add> Module.new do <add> extend ActiveSupport::Concern <add> include router.url_helpers <add> <add> # ROUTES TODO: install_helpers isn't great... can we make a module with the stuff that <add> # we can include? <add> included do <add> router.install_helpers(self) <add> end <add> end <add> end <add> end <add> <ide> def empty? <ide> routes.empty? <ide> end <ide><path>actionpack/lib/action_dispatch/routing/routes.rb <ide> # A singleton that stores the current route set <del>ActionDispatch::Routing::Routes = ActionDispatch::Routing::RouteSet.new <add># ActionDispatch::Routing::Routes = ActionDispatch::Routing::RouteSet.new <ide> <ide> # To preserve compatibility with pre-3.0 Rails action_controller/deprecated.rb <ide> # defines ActionDispatch::Routing::Routes as an alias <ide><path>actionpack/lib/action_dispatch/routing/url_for.rb <add>module ActionDispatch <add> module Routing <add> # In <b>routes.rb</b> one defines URL-to-controller mappings, but the reverse <add> # is also possible: an URL can be generated from one of your routing definitions. <add> # URL generation functionality is centralized in this module. <add> # <add> # See ActionDispatch::Routing and ActionController::Resources for general <add> # information about routing and routes.rb. <add> # <add> # <b>Tip:</b> If you need to generate URLs from your models or some other place, <add> # then ActionController::UrlFor is what you're looking for. Read on for <add> # an introduction. <add> # <add> # == URL generation from parameters <add> # <add> # As you may know, some functions - such as ActionController::Base#url_for <add> # and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set <add> # of parameters. For example, you've probably had the chance to write code <add> # like this in one of your views: <add> # <add> # <%= link_to('Click here', :controller => 'users', <add> # :action => 'new', :message => 'Welcome!') %> <add> # <add> # #=> Generates a link to: /users/new?message=Welcome%21 <add> # <add> # link_to, and all other functions that require URL generation functionality, <add> # actually use ActionController::UrlFor under the hood. And in particular, <add> # they use the ActionController::UrlFor#url_for method. One can generate <add> # the same path as the above example by using the following code: <add> # <add> # include UrlFor <add> # url_for(:controller => 'users', <add> # :action => 'new', <add> # :message => 'Welcome!', <add> # :only_path => true) <add> # # => "/users/new?message=Welcome%21" <add> # <add> # Notice the <tt>:only_path => true</tt> part. This is because UrlFor has no <add> # information about the website hostname that your Rails app is serving. So if you <add> # want to include the hostname as well, then you must also pass the <tt>:host</tt> <add> # argument: <add> # <add> # include UrlFor <add> # url_for(:controller => 'users', <add> # :action => 'new', <add> # :message => 'Welcome!', <add> # :host => 'www.example.com') # Changed this. <add> # # => "http://www.example.com/users/new?message=Welcome%21" <add> # <add> # By default, all controllers and views have access to a special version of url_for, <add> # that already knows what the current hostname is. So if you use url_for in your <add> # controllers or your views, then you don't need to explicitly pass the <tt>:host</tt> <add> # argument. <add> # <add> # For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for. <add> # So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for' <add> # in full. However, mailers don't have hostname information, and what's why you'll still <add> # have to specify the <tt>:host</tt> argument when generating URLs in mailers. <add> # <add> # <add> # == URL generation for named routes <add> # <add> # UrlFor also allows one to access methods that have been auto-generated from <add> # named routes. For example, suppose that you have a 'users' resource in your <add> # <b>routes.rb</b>: <add> # <add> # map.resources :users <add> # <add> # This generates, among other things, the method <tt>users_path</tt>. By default, <add> # this method is accessible from your controllers, views and mailers. If you need <add> # to access this auto-generated method from other places (such as a model), then <add> # you can do that by including ActionController::UrlFor in your class: <add> # <add> # class User < ActiveRecord::Base <add> # include ActionController::UrlFor <add> # <add> # def base_uri <add> # user_path(self) <add> # end <add> # end <add> # <add> # User.find(1).base_uri # => "/users/1" <add> # <add> module UrlFor <add> extend ActiveSupport::Concern <add> <add> included do <add> # ActionDispatch::Routing::Routes.install_helpers(self) <add> <add> # Including in a class uses an inheritable hash. Modules get a plain hash. <add> if respond_to?(:class_attribute) <add> class_attribute :default_url_options <add> else <add> mattr_accessor :default_url_options <add> end <add> <add> self.default_url_options = {} <add> end <add> <add> # Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in <add> # the form of a hash, just like the one you would use for url_for directly. Example: <add> # <add> # def default_url_options(options) <add> # { :project => @project.active? ? @project.url_name : "unknown" } <add> # end <add> # <add> # As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the <add> # urls as they stem from the business domain. Please note that any individual url_for call can always override the defaults set <add> # by this method. <add> def default_url_options(options = nil) <add> # ROUTES TODO: This should probably be an instance method <add> self.class.default_url_options <add> end <add> <add> def rewrite_options(options) #:nodoc: <add> if options.delete(:use_defaults) != false && (defaults = default_url_options(options)) <add> defaults.merge(options) <add> else <add> options <add> end <add> end <add> <add> # Generate a url based on the options provided, default_url_options and the <add> # routes defined in routes.rb. The following options are supported: <add> # <add> # * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+. <add> # * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'. <add> # * <tt>:host</tt> - Specifies the host the link should be targeted at. <add> # If <tt>:only_path</tt> is false, this option must be <add> # provided either explicitly, or via +default_url_options+. <add> # * <tt>:port</tt> - Optionally specify the port to connect to. <add> # * <tt>:anchor</tt> - An anchor name to be appended to the path. <add> # * <tt>:skip_relative_url_root</tt> - If true, the url is not constructed using the <add> # +relative_url_root+ set in ActionController::Base.relative_url_root. <add> # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/" <add> # <add> # Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to <add> # +url_for+ is forwarded to the Routes module. <add> # <add> # Examples: <add> # <add> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :port=>'8080' # => 'http://somehost.org:8080/tasks/testing' <add> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' <add> # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' <add> # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' <add> def url_for(options = {}) <add> options ||= {} <add> case options <add> when String <add> options <add> when Hash <add> _url_rewriter.rewrite(_router, rewrite_options(options)) <add> else <add> polymorphic_url(options) <add> end <add> end <add> <add> protected <add> <add> # ROUTES TODO: Figure out why _url_rewriter is sometimes the class and <add> # sometimes an instance. <add> def _url_rewriter <add> ActionController::UrlRewriter <add> end <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>actionpack/lib/action_dispatch/testing/assertions/routing.rb <ide> def assert_generates(expected_path, options, defaults={}, extras = {}, message=n <ide> expected_path = "/#{expected_path}" unless expected_path[0] == ?/ <ide> # Load routes.rb if it hasn't been loaded. <ide> <del> generated_path, extra_keys = ActionDispatch::Routing::Routes.generate_extras(options, defaults) <add> generated_path, extra_keys = @router.generate_extras(options, defaults) <ide> found_extras = options.reject {|k, v| ! extra_keys.include? k} <ide> <ide> msg = build_message(message, "found extras <?>, not <?>", found_extras, extras) <ide> def assert_routing(path, options, defaults={}, extras={}, message=nil) <ide> # end <ide> # <ide> def with_routing <del> real_routes = ActionDispatch::Routing::Routes <del> ActionDispatch::Routing.module_eval { remove_const :Routes } <del> <del> temporary_routes = ActionDispatch::Routing::RouteSet.new <del> ActionDispatch::Routing.module_eval { const_set :Routes, temporary_routes } <del> <del> yield temporary_routes <add> old_routes, @router = @router, ActionDispatch::Routing::RouteSet.new <add> old_controller, @controller = @controller, @controller.clone if @controller <add> # ROUTES TODO: Figure out this insanity <add> silence_warnings { ::ActionController.const_set(:UrlFor, @router.named_url_helpers) } <add> _router = @router <add> @controller.metaclass.send(:send, :include, @router.named_url_helpers) if @controller <add> yield @router <ide> ensure <del> if ActionDispatch::Routing.const_defined? :Routes <del> ActionDispatch::Routing.module_eval { remove_const :Routes } <del> end <del> ActionDispatch::Routing.const_set(:Routes, real_routes) if real_routes <add> @router = old_routes <add> @controller = old_controller if @controller <add> silence_warnings { ::ActionController.const_set(:UrlFor, @router.named_url_helpers) } if @router <ide> end <ide> <ide> def method_missing(selector, *args, &block) <del> if @controller && ActionDispatch::Routing::Routes.named_routes.helpers.include?(selector) <add> if @controller && @router.named_routes.helpers.include?(selector) <ide> @controller.send(selector, *args, &block) <ide> else <ide> super <ide> def recognized_request_for(path, request_method = nil) <ide> request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method <ide> request.path = path <ide> <del> params = ActionDispatch::Routing::Routes.recognize_path(path, { :method => request.method }) <add> params = @router.recognize_path(path, { :method => request.method }) <ide> request.path_parameters = params.with_indifferent_access <ide> <ide> request <ide><path>actionpack/lib/action_dispatch/testing/integration.rb <ide> def reset! <ide> unless defined? @named_routes_configured <ide> # install the named routes in this session instance. <ide> klass = singleton_class <del> ActionDispatch::Routing::Routes.install_helpers(klass) <add> # ActionDispatch::Routing::Routes.install_helpers(klass) <ide> <ide> # the helpers are made protected by default--we make them public for <ide> # easier access during testing and troubleshooting. <del> klass.module_eval { public *ActionDispatch::Routing::Routes.named_routes.helpers } <add> # klass.module_eval { public *ActionDispatch::Routing::Routes.named_routes.helpers } <ide> @named_routes_configured = true <ide> end <ide> end <ide> def host!(name) <ide> # Returns the URL for the given options, according to the rules specified <ide> # in the application's routes. <ide> def url_for(options) <add> # ROUTES TODO: @app.router is not guaranteed to exist, so a generic Rack <add> # application will not work here. This means that a generic Rack application <add> # integration test cannot call url_for, since the application will not have <add> # #router on it. <ide> controller ? <ide> controller.url_for(options) : <del> generic_url_rewriter.rewrite(options) <add> generic_url_rewriter.rewrite(SharedTestRoutes, options) <ide> end <ide> <ide> private <ide><path>actionpack/lib/action_view/test_case.rb <ide> def initialize <ide> setup :setup_with_controller <ide> def setup_with_controller <ide> @controller = TestController.new <add> @router = SharedTestRoutes <ide> @output_buffer = ActiveSupport::SafeBuffer.new <ide> @rendered = '' <ide> <ide> def _assigns <ide> end <ide> <ide> def method_missing(selector, *args) <del> if ActionDispatch::Routing::Routes.named_routes.helpers.include?(selector) <add> if @router.named_routes.helpers.include?(selector) <ide> @controller.__send__(selector, *args) <ide> else <ide> super <ide><path>actionpack/test/abstract_unit.rb <ide> def run_setup_once <ide> end <ide> end <ide> <del>class ActiveSupport::TestCase <del> include SetupOnce <del> <del> # Hold off drawing routes until all the possible controller classes <del> # have been loaded. <del> setup_once do <del> ActionDispatch::Routing::Routes.draw do |map| <del> match ':controller(/:action(/:id))' <add>SharedTestRoutes = ActionDispatch::Routing::RouteSet.new <add> <add>module ActiveSupport <add> class TestCase <add> include SetupOnce <add> # Hold off drawing routes until all the possible controller classes <add> # have been loaded. <add> setup_once do <add> SharedTestRoutes.draw do |map| <add> match ':controller(/:action(/:id))' <add> end <add> <add> # ROUTES TODO: Don't do this here <add> # brodel :'( <add> ActionController::IntegrationTest.app.router.draw do <add> match ':controller(/:action(/:id))' <add> end <ide> end <ide> end <ide> end <ide> <add>class RoutedRackApp <add> attr_reader :router <add> <add> def initialize(router, &blk) <add> @router = router <add> @stack = ActionDispatch::MiddlewareStack.new(&blk).build(@router) <add> end <add> <add> def call(env) <add> @stack.call(env) <add> end <add>end <add> <ide> class ActionController::IntegrationTest < ActiveSupport::TestCase <ide> def self.build_app(routes = nil) <del> ActionDispatch::Flash <del> ActionDispatch::MiddlewareStack.new { |middleware| <add> RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware| <ide> middleware.use "ActionDispatch::ShowExceptions" <ide> middleware.use "ActionDispatch::Callbacks" <ide> middleware.use "ActionDispatch::ParamsParser" <ide> middleware.use "ActionDispatch::Cookies" <ide> middleware.use "ActionDispatch::Flash" <ide> middleware.use "ActionDispatch::Head" <del> }.build(routes || ActionDispatch::Routing::Routes) <add> end <ide> end <ide> <ide> self.app = build_app <ide> def self.stub_controllers <ide> end <ide> <ide> def with_routing(&block) <del> real_routes = ActionDispatch::Routing::Routes <del> ActionDispatch::Routing.module_eval { remove_const :Routes } <del> <ide> temporary_routes = ActionDispatch::Routing::RouteSet.new <del> self.class.app = self.class.build_app(temporary_routes) <del> ActionDispatch::Routing.module_eval { const_set :Routes, temporary_routes } <add> old_app, self.class.app = self.class.app, self.class.build_app(temporary_routes) <add> old_routes = SharedTestRoutes <add> silence_warnings { Object.const_set(:SharedTestRoutes, temporary_routes) } <ide> <ide> yield temporary_routes <ide> ensure <del> if ActionDispatch::Routing.const_defined? :Routes <del> ActionDispatch::Routing.module_eval { remove_const :Routes } <del> end <del> ActionDispatch::Routing.const_set(:Routes, real_routes) if real_routes <del> self.class.app = self.class.build_app <add> self.class.app = old_app <add> silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) } <ide> end <ide> end <ide> <ide> class Base <ide> class TestCase <ide> include ActionDispatch::TestProcess <ide> <add> setup do <add> # ROUTES TODO: The router object should come from somewhere sane <add> @router = SharedTestRoutes <add> end <add> <ide> def assert_template(options = {}, message = nil) <ide> validate_request! <ide> <ide> def assert_template(options = {}, message = nil) <ide> end <ide> end <ide> end <add> <add># ROUTES TODO: Cleaner way to do this? <add>module ActionController <add> UrlFor = SharedTestRoutes.named_url_helpers <add> class Base <add> include UrlFor <add> end <add>end <ide>\ No newline at end of file <ide><path>actionpack/test/controller/action_pack_assertions_test.rb <ide> def test_assert_redirect_to_named_route_failure <ide> end <ide> <ide> def test_assert_redirect_to_nested_named_route <add> @controller = Admin::InnerModuleController.new <add> <ide> with_routing do |set| <ide> set.draw do |map| <ide> match 'admin/inner_module', :to => 'admin/inner_module#index', :as => :admin_inner_module <ide> match ':controller/:action' <ide> end <del> @controller = Admin::InnerModuleController.new <ide> process :redirect_to_index <ide> # redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}> <ide> assert_redirected_to admin_inner_module_path <ide> end <ide> end <ide> <ide> def test_assert_redirected_to_top_level_named_route_from_nested_controller <add> @controller = Admin::InnerModuleController.new <add> <ide> with_routing do |set| <ide> set.draw do |map| <ide> match '/action_pack_assertions/:id', :to => 'action_pack_assertions#index', :as => :top_level <ide> match ':controller/:action' <ide> end <del> @controller = Admin::InnerModuleController.new <ide> process :redirect_to_top_level_named_route <ide> # assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return <ide> assert_redirected_to "/action_pack_assertions/foo" <ide> end <ide> end <ide> <ide> def test_assert_redirected_to_top_level_named_route_with_same_controller_name_in_both_namespaces <add> @controller = Admin::InnerModuleController.new <add> <ide> with_routing do |set| <ide> set.draw do |map| <ide> # this controller exists in the admin namespace as well which is the only difference from previous test <ide> match '/user/:id', :to => 'user#index', :as => :top_level <ide> match ':controller/:action' <ide> end <del> @controller = Admin::InnerModuleController.new <ide> process :redirect_to_top_level_named_route <ide> # assert_redirected_to top_level_url('foo') would pass because of exact match early return <ide> assert_redirected_to top_level_path('foo') <ide><path>actionpack/test/controller/base_test.rb <ide> def test_ensure_url_for_works_as_expected_when_called_with_no_options_if_default <ide> end <ide> <ide> def test_named_routes_with_path_without_doing_a_request_first <add> @controller = EmptyController.new <add> <ide> with_routing do |set| <ide> set.draw do |map| <ide> resources :things <ide> end <ide> <del> assert_equal '/things', EmptyController.new.send(:things_path) <add> assert_equal '/things', @controller.send(:things_path) <ide> end <ide> end <ide> end <ide><path>actionpack/test/controller/integration_test.rb <ide> def test_url_for_with_controller <ide> def test_url_for_without_controller <ide> options = {:action => 'show'} <ide> mock_rewriter = mock() <del> mock_rewriter.expects(:rewrite).with(options).returns('/show') <add> mock_rewriter.expects(:rewrite).with(SharedTestRoutes, options).returns('/show') <ide> @session.stubs(:generic_url_rewriter).returns(mock_rewriter) <ide> @session.stubs(:controller).returns(nil) <ide> assert_equal '/show', @session.url_for(options) <ide> def test_generate_url_with_controller <ide> private <ide> def with_test_route_set <ide> with_routing do |set| <add> controller = ::IntegrationProcessTest::IntegrationController.clone <add> controller.class_eval do <add> include set.named_url_helpers <add> end <add> <ide> set.draw do |map| <del> match ':action', :to => ::IntegrationProcessTest::IntegrationController <del> get 'get/:action', :to => ::IntegrationProcessTest::IntegrationController <add> match ':action', :to => controller <add> get 'get/:action', :to => controller <ide> end <ide> yield <ide> end <ide><path>actionpack/test/controller/rescue_test.rb <ide> def show_errors(exception) <ide> end <ide> <ide> test 'rescue routing exceptions' do <del> @app = ActionDispatch::Rescue.new(ActionDispatch::Routing::Routes) do <add> @app = ActionDispatch::Rescue.new(SharedTestRoutes) do <ide> rescue_from ActionController::RoutingError, lambda { |env| [200, {"Content-Type" => "text/html"}, ["Gotcha!"]] } <ide> end <ide> <ide> def show_errors(exception) <ide> end <ide> <ide> test 'unrescued exception' do <del> @app = ActionDispatch::Rescue.new(ActionDispatch::Routing::Routes) <add> @app = ActionDispatch::Rescue.new(SharedTestRoutes) <ide> assert_raise(ActionController::RoutingError) { get '/b00m' } <ide> end <ide> <ide><path>actionpack/test/controller/resources_test.rb <ide> def test_multiple_default_restful_routes <ide> <ide> def test_with_custom_conditions <ide> with_restful_routing :messages, :conditions => { :subdomain => 'app' } do <del> assert ActionDispatch::Routing::Routes.recognize_path("/messages", :method => :get, :subdomain => 'app') <add> assert @router.recognize_path("/messages", :method => :get, :subdomain => 'app') <ide> end <ide> end <ide> <ide> def test_override_new_method <ide> assert_restful_routes_for :messages do |options| <ide> assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get) <ide> assert_raise(ActionController::RoutingError) do <del> ActionDispatch::Routing::Routes.recognize_path("/messages/new", :method => :post) <add> @router.recognize_path("/messages/new", :method => :post) <ide> end <ide> end <ide> end <ide> def test_shallow_nested_restful_routes_with_namespaces <ide> <ide> def test_restful_routes_dont_generate_duplicates <ide> with_restful_routing :messages do <del> routes = ActionDispatch::Routing::Routes.routes <add> routes = @router.routes <ide> routes.each do |route| <ide> routes.each do |r| <ide> next if route === r # skip the comparison instance <ide> def assert_restful_routes_for(controller_name, options = {}) <ide> options[:shallow_options] = options[:options] <ide> end <ide> <del> new_action = ActionDispatch::Routing::Routes.resources_path_names[:new] || "new" <del> edit_action = ActionDispatch::Routing::Routes.resources_path_names[:edit] || "edit" <add> new_action = @router.resources_path_names[:new] || "new" <add> edit_action = @router.resources_path_names[:edit] || "edit" <ide> <ide> if options[:path_names] <ide> new_action = options[:path_names][:new] if options[:path_names][:new] <ide> def assert_restful_named_routes_for(controller_name, singular_name = nil, option <ide> end <ide> <ide> @controller = "#{options[:options][:controller].camelize}Controller".constantize.new <add> # ROUTES TODO: Figure out a way to not extend the routing helpers here <add> @controller.metaclass.send(:include, @router.named_url_helpers) <ide> @request = ActionController::TestRequest.new <ide> @response = ActionController::TestResponse.new <ide> get :index, options[:options] <ide> def assert_singleton_routes_for(singleton_name, options = {}) <ide> def assert_singleton_named_routes_for(singleton_name, options = {}) <ide> (options[:options] ||= {})[:controller] ||= singleton_name.to_s.pluralize <ide> @controller = "#{options[:options][:controller].camelize}Controller".constantize.new <add> @controller.metaclass.send(:include, @router.named_url_helpers) <ide> @request = ActionController::TestRequest.new <ide> @response = ActionController::TestResponse.new <ide> get :show, options[:options] <ide><path>actionpack/test/controller/test_test.rb <ide> def test_assert_realistic_path_parameters <ide> end <ide> <ide> def test_with_routing_places_routes_back <del> assert ActionDispatch::Routing::Routes <del> routes_id = ActionDispatch::Routing::Routes.object_id <add> assert @router <add> routes_id = @router.object_id <ide> <ide> begin <ide> with_routing { raise 'fail' } <ide> fail 'Should not be here.' <ide> rescue RuntimeError <ide> end <ide> <del> assert ActionDispatch::Routing::Routes <del> assert_equal routes_id, ActionDispatch::Routing::Routes.object_id <add> assert @router <add> assert_equal routes_id, @router.object_id <ide> end <ide> <ide> def test_remote_addr <ide><path>actionpack/test/controller/url_for_test.rb <ide> module Testing <ide> <ide> class UrlForTests < ActionController::TestCase <ide> class W <del> include ActionController::UrlFor <add> include SharedTestRoutes.url_helpers <ide> end <ide> <ide> def teardown <ide><path>actionpack/test/controller/url_rewriter_test.rb <ide> def setup <ide> <ide> def test_port <ide> assert_equal('http://test.host:1271/c/a/i', <del> @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :port => 1271) <add> @rewriter.rewrite(@router, :controller => 'c', :action => 'a', :id => 'i', :port => 1271) <ide> ) <ide> end <ide> <ide> def test_protocol_with_and_without_separator <ide> assert_equal('https://test.host/c/a/i', <del> @rewriter.rewrite(:protocol => 'https', :controller => 'c', :action => 'a', :id => 'i') <add> @rewriter.rewrite(@router, :protocol => 'https', :controller => 'c', :action => 'a', :id => 'i') <ide> ) <ide> <ide> assert_equal('https://test.host/c/a/i', <del> @rewriter.rewrite(:protocol => 'https://', :controller => 'c', :action => 'a', :id => 'i') <add> @rewriter.rewrite(@router, :protocol => 'https://', :controller => 'c', :action => 'a', :id => 'i') <ide> ) <ide> end <ide> <ide> def test_user_name_and_password <ide> assert_equal( <ide> 'http://david:secret@test.host/c/a/i', <del> @rewriter.rewrite(:user => "david", :password => "secret", :controller => 'c', :action => 'a', :id => 'i') <add> @rewriter.rewrite(@router, :user => "david", :password => "secret", :controller => 'c', :action => 'a', :id => 'i') <ide> ) <ide> end <ide> <ide> def test_user_name_and_password_with_escape_codes <ide> assert_equal( <ide> 'http://openid.aol.com%2Fnextangler:one+two%3F@test.host/c/a/i', <del> @rewriter.rewrite(:user => "openid.aol.com/nextangler", :password => "one two?", :controller => 'c', :action => 'a', :id => 'i') <add> @rewriter.rewrite(@router, :user => "openid.aol.com/nextangler", :password => "one two?", :controller => 'c', :action => 'a', :id => 'i') <ide> ) <ide> end <ide> <ide> def test_anchor <ide> assert_equal( <ide> 'http://test.host/c/a/i#anchor', <del> @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => 'anchor') <add> @rewriter.rewrite(@router, :controller => 'c', :action => 'a', :id => 'i', :anchor => 'anchor') <ide> ) <ide> end <ide> <ide> def test_anchor_should_call_to_param <ide> assert_equal( <ide> 'http://test.host/c/a/i#anchor', <del> @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anchor')) <add> @rewriter.rewrite(@router, :controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anchor')) <ide> ) <ide> end <ide> <ide> def test_anchor_should_be_cgi_escaped <ide> assert_equal( <ide> 'http://test.host/c/a/i#anc%2Fhor', <del> @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor')) <add> @rewriter.rewrite(@router, :controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor')) <ide> ) <ide> end <ide> <ide> def test_overwrite_params <ide> @params[:action] = 'bye' <ide> @params[:id] = '2' <ide> <del> assert_equal '/hi/hi/2', @rewriter.rewrite(:only_path => true, :overwrite_params => {:action => 'hi'}) <del> u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:action => 'hi'}) <add> assert_equal '/hi/hi/2', @rewriter.rewrite(@router, :only_path => true, :overwrite_params => {:action => 'hi'}) <add> u = @rewriter.rewrite(@router, :only_path => false, :overwrite_params => {:action => 'hi'}) <ide> assert_match %r(/hi/hi/2$), u <ide> end <ide> <ide> def test_overwrite_removes_original <ide> @params[:action] = 'list' <ide> @params[:list_page] = 1 <ide> <del> assert_equal '/search/list?list_page=2', @rewriter.rewrite(:only_path => true, :overwrite_params => {"list_page" => 2}) <del> u = @rewriter.rewrite(:only_path => false, :overwrite_params => {:list_page => 2}) <add> assert_equal '/search/list?list_page=2', @rewriter.rewrite(@router, :only_path => true, :overwrite_params => {"list_page" => 2}) <add> u = @rewriter.rewrite(@router, :only_path => false, :overwrite_params => {:list_page => 2}) <ide> assert_equal 'http://test.host/search/list?list_page=2', u <ide> end <ide> <ide> def test_to_str <ide> <ide> def test_trailing_slash <ide> options = {:controller => 'foo', :action => 'bar', :id => '3', :only_path => true} <del> assert_equal '/foo/bar/3', @rewriter.rewrite(options) <del> assert_equal '/foo/bar/3?query=string', @rewriter.rewrite(options.merge({:query => 'string'})) <add> assert_equal '/foo/bar/3', @rewriter.rewrite(@router, options) <add> assert_equal '/foo/bar/3?query=string', @rewriter.rewrite(@router, options.merge({:query => 'string'})) <ide> options.update({:trailing_slash => true}) <del> assert_equal '/foo/bar/3/', @rewriter.rewrite(options) <add> assert_equal '/foo/bar/3/', @rewriter.rewrite(@router, options) <ide> options.update({:query => 'string'}) <del> assert_equal '/foo/bar/3/?query=string', @rewriter.rewrite(options) <add> assert_equal '/foo/bar/3/?query=string', @rewriter.rewrite(@router, options) <ide> end <ide> end <ide> <ide><path>actionpack/test/dispatch/routing_test.rb <ide> def app <ide> Routes <ide> end <ide> <add> include Routes.named_url_helpers <add> <ide> def test_logout <ide> with_test_routes do <ide> delete '/logout' <ide> def test_nested_optional_scoped_path <ide> <ide> private <ide> def with_test_routes <del> real_routes, temp_routes = ActionDispatch::Routing::Routes, Routes <del> <del> ActionDispatch::Routing.module_eval { remove_const :Routes } <del> ActionDispatch::Routing.module_eval { const_set :Routes, temp_routes } <del> <ide> yield <del> ensure <del> ActionDispatch::Routing.module_eval { remove_const :Routes } <del> ActionDispatch::Routing.const_set(:Routes, real_routes) <ide> end <ide> end <ide><path>actionpack/test/template/test_case_test.rb <ide> def render_from_helper <ide> end <ide> <ide> test "is able to use routes" do <del> controller.request.assign_parameters('foo', 'index') <add> controller.request.assign_parameters(@router, 'foo', 'index') <ide> assert_equal '/foo', url_for <ide> assert_equal '/bar', url_for(:controller => 'bar') <ide> end
26
Text
Text
add faq entry on pre-trained models
52ea31b65c09ec3370522956419f42e7507495c2
<ide><path>docs/templates/getting-started/faq.md <ide> - [How can I "freeze" layers?](#how-can-i-freeze-keras-layers) <ide> - [How can I use stateful RNNs?](#how-can-i-use-stateful-rnns) <ide> - [How can I remove a layer from a Sequential model?](#how-can-i-remove-a-layer-from-a-sequential-model) <add>- [How can I use pre-trained models in Keras?](#how-can-i-use-pre-trained-models-in-keras) <ide> <ide> --- <ide> <ide> print(len(model.layers)) # "2" <ide> model.pop() <ide> print(len(model.layers)) # "1" <ide> ``` <add> <add> <add>### How can I use pre-trained models in Keras? <add> <add>Code and pre-trained weights are available for the following image classification models: <add> <add>[VGG-16](https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3) <add>[VGG-19](https://gist.github.com/baraldilorenzo/8d096f48a1be4a2d660d) <add>[AlexNet](https://github.com/heuritech/convnets-keras) <add> <add>For an example of how to use such a pre-trained model for feature extraction or for fine-tuning, see [this blog post](http://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html). <add> <add>The VGG-16 model is also the basis for several Keras example scripts: <add> <add>- [style transfer](https://github.com/fchollet/keras/blob/master/examples/neural_style_transfer.py) <add>- [feature visualization](https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py) <add>- [deep dream](https://github.com/fchollet/keras/blob/master/examples/deep_dream.py)
1
Python
Python
add a note, remove bad comment line
9734f6935aec8766b05155bd02c41239f5dee72a
<ide><path>libcloud/__init__.py <ide> :var __version__: Current version of libcloud <ide> """ <ide> <del>import logging <ide> import os <ide> import codecs <ide> import atexit <ide> from libcloud.base import get_driver # NOQA <ide> <ide> try: <add> # TODO: This import is slow and adds overhead in situations when no <add> # requests are made but it's necessary for detecting bad version of <add> # requests <ide> import requests # NOQA <ide> have_requests = True <ide> except ImportError: <ide> def _init_once(): <ide> have_paramiko = False <ide> <ide> if have_paramiko and hasattr(paramiko.util, 'log_to_file'): <add> import logging <ide> paramiko.util.log_to_file(filename=path, level=logging.DEBUG) <ide> <ide> # check for broken `yum install python-requests` <ide><path>libcloud/compute/drivers/ec2.py <ide> def ex_import_snapshot(self, client_data=None, <ide> :type client_data: ``dict`` <ide> <ide> :param client_token: The token to enable idempotency for VM <del> import requests.(optional) <add> (optional) <ide> :type client_token: ``str`` <ide> <ide> :param description: The description string for the
2
Javascript
Javascript
extract common code to function
d9ca2459172a3ad62f0a19b8b1306d739c4b75b7
<ide><path>src/auto/injector.js <ide> var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; <ide> var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; <ide> var $injectorMinErr = minErr('$injector'); <ide> <add>function extractArgs(fn) { <add> var fnText = fn.toString().replace(STRIP_COMMENTS, ''), <add> args = fnText.match(FN_ARGS); <add> return args; <add>} <add> <ide> function anonFn(fn) { <ide> // For anonymous functions, showing at the very least the function signature can help in <ide> // debugging. <del> var fnText = fn.toString().replace(STRIP_COMMENTS, ''), <del> args = fnText.match(FN_ARGS); <add> var args = extractArgs(fn); <ide> if (args) { <ide> return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; <ide> } <ide> function anonFn(fn) { <ide> <ide> function annotate(fn, strictDi, name) { <ide> var $inject, <del> fnText, <ide> argDecl, <ide> last; <ide> <ide> function annotate(fn, strictDi, name) { <ide> throw $injectorMinErr('strictdi', <ide> '{0} is not using explicit annotation and cannot be invoked in strict mode', name); <ide> } <del> fnText = fn.toString().replace(STRIP_COMMENTS, ''); <del> argDecl = fnText.match(FN_ARGS); <add> argDecl = extractArgs(fn); <ide> forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { <ide> arg.replace(FN_ARG, function(all, underscore, name) { <ide> $inject.push(name);
1
Ruby
Ruby
fix minor typo in rails/engine docs [ci skip]
af8751fcf80cdce31744a05a2bbd148e3194346f
<ide><path>railties/lib/rails/engine.rb <ide> module Rails <ide> # resources :articles <ide> # end <ide> # <del> # If +MyEngine+ is isolated, The routes above will point to <add> # If +MyEngine+ is isolated, the routes above will point to <ide> # <tt>MyEngine::ArticlesController</tt>. You also don't need to use longer <ide> # URL helpers like +my_engine_articles_path+. Instead, you should simply use <ide> # +articles_path+, like you would do with your main application.
1
Text
Text
fix syntax error in docs
974ff00464d7743182f842a2c7786c334b9ca82c
<ide><path>docs/00-Getting-Started.md <ide> var img = new Image(); <ide> img.src = 'https://example.com/my_image.png'; <ide> img.onload = function() { <ide> var ctx = document.getElementById('canvas').getContext('2d'); <del> var fillPattern = ctx.CreatePattern(img, 'repeat'); <add> var fillPattern = ctx.createPattern(img, 'repeat'); <ide> <ide> var chart = new Chart(ctx, { <ide> data: {
1
Python
Python
optimize error messages on docker driver init
ff0d2e550fff45abbd30e5913cdaab79450097d3
<ide><path>libcloud/container/drivers/docker.py <ide> def __init__(self, key='', secret='', secure=False, host='localhost', <ide> else: <ide> self.key_file = key_file <ide> self.cert_file = cert_file <del> super(DockerContainerDriver, self).__init__(key=key, <del> secret=secret, <del> secure=secure, host=host, <del> port=port, <del> key_file=key_file, <del> cert_file=cert_file) <del> # set API version <del> self.version = self._get_api_version() <add> <ide> if host.startswith('https://'): <ide> secure = True <ide> <ide> def __init__(self, key='', secret='', secure=False, host='localhost', <ide> if host.startswith(prefix): <ide> host = host.strip(prefix) <ide> <add> super(DockerContainerDriver, self).__init__(key=key, <add> secret=secret, <add> secure=secure, host=host, <add> port=port, <add> key_file=key_file, <add> cert_file=cert_file) <add> # set API version <add> self.version = self._get_api_version() <add> <ide> if key_file or cert_file: <ide> # docker tls authentication- <ide> # https://docs.docker.com/articles/https/ <ide> def deploy_container(self, name, image, parameters=None, start=True, <ide> <ide> data = json.dumps(payload) <ide> if start: <del> if float(self._get_api_version()) > 1.22: <add> if float(self.version) > 1.22: <ide> result = self.connection.request( <ide> '/v%s/containers/%s/start' % <ide> (self.version, id_), <ide> def start_container(self, container): <ide> # starting container with non-empty request body <ide> # was deprecated since v1.10 and removed in v1.12 <ide> <del> if float(self._get_api_version()) > 1.22: <add> if float(self.version) > 1.22: <ide> result = self.connection.request( <ide> '/v%s/containers/%s/start' % <ide> (self.version, container.id), <ide> def ex_get_logs(self, container, stream=False): <ide> payload = {} <ide> data = json.dumps(payload) <ide> <del> if float(self._get_api_version()) > 1.10: <add> if float(self.version) > 1.10: <ide> result = self.connection.request( <ide> "/v%s/containers/%s/logs?follow=%s&stdout=1&stderr=1" % <ide> (self.version, container.id, str(stream))).object
1
Javascript
Javascript
freeze reactelement.props in dev mode
95373ce769188aacd25c6485bc2c628ff02a856f
<ide><path>src/isomorphic/classic/element/ReactElement.js <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> <ide> var assign = require('Object.assign'); <del>var warning = require('warning'); <ide> <ide> var RESERVED_PROPS = { <ide> key: true, <ide> ref: true, <ide> }; <ide> <del>/** <del> * Warn for mutations. <del> * <del> * @internal <del> * @param {object} object <del> * @param {string} key <del> */ <del>function defineWarningProperty(object, key) { <del> Object.defineProperty(object, key, { <del> <del> configurable: false, <del> enumerable: true, <del> <del> get: function() { <del> if (!this._store) { <del> return null; <del> } <del> return this._store[key]; <del> }, <del> <del> set: function(value) { <del> warning( <del> false, <del> 'Don\'t set the %s property of the React element. Instead, ' + <del> 'specify the correct value when initially creating the element.', <del> key <del> ); <del> this._store[key] = value; <del> }, <del> <del> }); <del>} <del> <del>/** <del> * This is updated to true if the membrane is successfully created. <del> */ <del>var useMutationMembrane = false; <del> <del>/** <del> * Warn for mutations. <del> * <del> * @internal <del> * @param {object} prototype <del> */ <del>function defineMutationMembrane(prototype) { <del> try { <del> var pseudoFrozenProperties = { <del> props: true, <del> }; <del> for (var key in pseudoFrozenProperties) { <del> defineWarningProperty(prototype, key); <del> } <del> useMutationMembrane = true; <del> } catch (x) { <del> // IE will fail on defineProperty <del> } <del>} <del> <ide> /** <ide> * Base constructor for all React elements. This is only used to make this <ide> * work with a dynamic instanceof check. Nothing should live on this prototype. <ide> var ReactElement = function(type, key, ref, owner, props) { <ide> this._owner = owner; <ide> <ide> if (__DEV__) { <del> // The validation flag and props are currently mutative. We put them on <add> // The validation flag is currently mutative. We put it on <ide> // an external backing store so that we can freeze the whole object. <ide> // This can be replaced with a WeakMap once they are implemented in <ide> // commonly used development environments. <del> this._store = {props: props, originalProps: assign({}, props)}; <add> this._store = {}; <ide> <ide> // To make comparing ReactElements easier for testing purposes, we make <ide> // the validation flag non-enumerable (where possible, which should <ide> var ReactElement = function(type, key, ref, owner, props) { <ide> configurable: false, <ide> enumerable: false, <ide> writable: true, <add> value: false, <ide> }); <ide> } catch (x) { <add> this._store.validated = false; <ide> } <del> this._store.validated = false; <del> <del> // We're not allowed to set props directly on the object so we early <del> // return and rely on the prototype membrane to forward to the backing <del> // store. <del> if (useMutationMembrane) { <del> Object.freeze(this); <del> return; <del> } <add> this.props = props; <add> Object.freeze(this.props); <add> Object.freeze(this); <ide> } <del> <del> this.props = props; <ide> }; <ide> <ide> // We intentionally don't expose the function on the constructor property. <ide> ReactElement.prototype = { <ide> _isReactElement: true, <ide> }; <ide> <del>if (__DEV__) { <del> defineMutationMembrane(ReactElement.prototype); <del>} <del> <ide> ReactElement.createElement = function(type, config, children) { <ide> var propName; <ide> <ide> ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { <ide> // If the key on the original is valid, then the clone is valid <ide> newElement._store.validated = oldElement._store.validated; <ide> } <add> <ide> return newElement; <ide> }; <ide> <ide><path>src/isomorphic/classic/element/ReactElementValidator.js <ide> function checkPropTypes(componentName, propTypes, props, location) { <ide> } <ide> } <ide> <del>var warnedPropsMutations = {}; <del> <del>/** <del> * Warn about mutating props when setting `propName` on `element`. <del> * <del> * @param {string} propName The string key within props that was set <del> * @param {ReactElement} element <del> */ <del>function warnForPropsMutation(propName, element) { <del> var type = element.type; <del> var elementName = typeof type === 'string' ? type : type.displayName; <del> var ownerName = element._owner ? <del> element._owner.getPublicInstance().constructor.displayName : null; <del> <del> var warningKey = propName + '|' + elementName + '|' + ownerName; <del> if (warnedPropsMutations.hasOwnProperty(warningKey)) { <del> return; <del> } <del> warnedPropsMutations[warningKey] = true; <del> <del> var elementInfo = ''; <del> if (elementName) { <del> elementInfo = ' <' + elementName + ' />'; <del> } <del> var ownerInfo = ''; <del> if (ownerName) { <del> ownerInfo = ' The element was created by ' + ownerName + '.'; <del> } <del> <del> warning( <del> false, <del> 'Don\'t set .props.%s of the React component%s. Instead, specify the ' + <del> 'correct value when initially creating the element or use ' + <del> 'React.cloneElement to make a new element with updated props.%s', <del> propName, <del> elementInfo, <del> ownerInfo <del> ); <del>} <del> <del>// Inline Object.is polyfill <del>function is(a, b) { <del> if (a !== a) { <del> // NaN <del> return b !== b; <del> } <del> if (a === 0 && b === 0) { <del> // +-0 <del> return 1 / a === 1 / b; <del> } <del> return a === b; <del>} <del> <del>/** <del> * Given an element, check if its props have been mutated since element <del> * creation (or the last call to this function). In particular, check if any <del> * new props have been added, which we can't directly catch by defining warning <del> * properties on the props object. <del> * <del> * @param {ReactElement} element <del> */ <del>function checkAndWarnForMutatedProps(element) { <del> if (!element._store) { <del> // Element was created using `new ReactElement` directly or with <del> // `ReactElement.createElement`; skip mutation checking <del> return; <del> } <del> <del> var originalProps = element._store.originalProps; <del> var props = element.props; <del> <del> for (var propName in props) { <del> if (props.hasOwnProperty(propName)) { <del> if (!originalProps.hasOwnProperty(propName) || <del> !is(originalProps[propName], props[propName])) { <del> warnForPropsMutation(propName, element); <del> <del> // Copy over the new value so that the two props objects match again <del> originalProps[propName] = props[propName]; <del> } <del> } <del> } <del>} <del> <ide> /** <ide> * Given an element, validate that its props follow the propTypes definition, <ide> * provided by the type. <ide> function validatePropTypes(element) { <ide> <ide> var ReactElementValidator = { <ide> <del> checkAndWarnForMutatedProps: checkAndWarnForMutatedProps, <del> <ide> createElement: function(type, props, children) { <ide> // We warn in this case but don't throw. We expect the element creation to <ide> // succeed and there will likely be errors in render. <ide><path>src/isomorphic/classic/element/__tests__/ReactElement-test.js <ide> describe('ReactElement', function() { <ide> expect(element.type).toBe(ComponentClass); <ide> expect(element.key).toBe(null); <ide> expect(element.ref).toBe(null); <del> expect(element.props).toEqual({}); <add> var expectation = {}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('allows a string to be passed as the type', function() { <ide> var element = React.createFactory('div')(); <ide> expect(element.type).toBe('div'); <ide> expect(element.key).toBe(null); <ide> expect(element.ref).toBe(null); <del> expect(element.props).toEqual({}); <add> var expectation = {}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('returns an immutable element', function() { <ide> describe('ReactElement', function() { <ide> expect(element.type).toBe(ComponentClass); <ide> expect(element.key).toBe('12'); <ide> expect(element.ref).toBe('34'); <del> expect(element.props).toEqual({foo:'56'}); <add> var expectation = {foo:'56'}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('coerces the key to a string', function() { <ide> describe('ReactElement', function() { <ide> expect(element.type).toBe(ComponentClass); <ide> expect(element.key).toBe('12'); <ide> expect(element.ref).toBe(null); <del> expect(element.props).toEqual({foo:'56'}); <add> var expectation = {foo:'56'}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('preserves the owner on the element', function() { <ide> describe('ReactElement', function() { <ide> expect(inst2.props.prop).toBe(null); <ide> }); <ide> <del> it('warns when changing a prop after element creation', function() { <del> spyOn(console, 'error'); <add> it('throws when changing a prop (in dev) after element creation', function() { <ide> var Outer = React.createClass({ <ide> render: function() { <ide> var el = <div className="moo" />; <ide> <del> // This assignment warns but should still work for now. <del> el.props.className = 'quack'; <del> expect(el.props.className).toBe('quack'); <add> expect(function() { <add> el.props.className = 'quack'; <add> }).toThrow(); <add> expect(el.props.className).toBe('moo'); <ide> <ide> return el; <ide> }, <ide> }); <ide> var outer = ReactTestUtils.renderIntoDocument(<Outer color="orange" />); <del> expect(React.findDOMNode(outer).className).toBe('quack'); <del> <del> expect(console.error.argsForCall.length).toBe(1); <del> expect(console.error.argsForCall[0][0]).toContain( <del> 'Don\'t set .props.className of the React component <div />.' <del> ); <del> expect(console.error.argsForCall[0][0]).toContain( <del> 'The element was created by Outer.' <del> ); <del> <del> console.error.reset(); <del> <del> // This also warns (just once per key/type pair) <del> outer.props.color = 'green'; <del> outer.forceUpdate(); <del> outer.props.color = 'purple'; <del> outer.forceUpdate(); <del> <del> expect(console.error.argsForCall.length).toBe(1); <del> expect(console.error.argsForCall[0][0]).toContain( <del> 'Don\'t set .props.color of the React component <Outer />.' <del> ); <add> expect(React.findDOMNode(outer).className).toBe('moo'); <ide> }); <ide> <del> it('warns when adding a prop after element creation', function() { <del> spyOn(console, 'error'); <add> it('throws when adding a prop (in dev) after element creation', function() { <ide> var container = document.createElement('div'); <ide> var Outer = React.createClass({ <ide> getDefaultProps: () => ({sound: 'meow'}), <ide> render: function() { <ide> var el = <div>{this.props.sound}</div>; <ide> <del> // This assignment doesn't warn immediately (because we can't) but it <del> // warns upon mount. <del> el.props.className = 'quack'; <del> expect(el.props.className).toBe('quack'); <add> expect(function() { <add> el.props.className = 'quack'; <add> }).toThrow(); <add> <add> expect(el.props.className).toBe(undefined); <ide> <ide> return el; <ide> }, <ide> }); <ide> var outer = React.render(<Outer />, container); <ide> expect(React.findDOMNode(outer).textContent).toBe('meow'); <del> expect(React.findDOMNode(outer).className).toBe('quack'); <del> <del> expect(console.error.argsForCall.length).toBe(1); <del> expect(console.error.argsForCall[0][0]).toContain( <del> 'Don\'t set .props.className of the React component <div />.' <del> ); <del> expect(console.error.argsForCall[0][0]).toContain( <del> 'The element was created by Outer.' <del> ); <del> <del> console.error.reset(); <del> <del> var newOuterEl = <Outer />; <del> newOuterEl.props.sound = 'oink'; <del> outer = React.render(newOuterEl, container); <del> expect(React.findDOMNode(outer).textContent).toBe('oink'); <del> expect(React.findDOMNode(outer).className).toBe('quack'); <del> <del> expect(console.error.argsForCall.length).toBe(1); <del> expect(console.error.argsForCall[0][0]).toContain( <del> 'Don\'t set .props.sound of the React component <Outer />.' <del> ); <add> expect(React.findDOMNode(outer).className).toBe(''); <ide> }); <ide> <ide> it('does not warn for NaN props', function() { <ide><path>src/isomorphic/modern/class/__tests__/ReactES6Class-test.js <ide> var React; <ide> describe('ReactES6Class', function() { <ide> <ide> var container; <add> var freeze = function(expectation) { <add> Object.freeze(expectation); <add> return expectation; <add> }; <ide> var Inner; <ide> var attachedListener = null; <ide> var renderedName = null; <ide> describe('ReactES6Class', function() { <ide> lifeCycles = []; // reset <ide> test(<Foo value="bar" />, 'SPAN', 'bar'); <ide> expect(lifeCycles).toEqual([ <del> 'receive-props', {value: 'bar'}, <del> 'should-update', {value: 'bar'}, {}, <del> 'will-update', {value: 'bar'}, {}, <del> 'did-update', {value: 'foo'}, {}, <add> 'receive-props', freeze({value: 'bar'}), <add> 'should-update', freeze({value: 'bar'}), {}, <add> 'will-update', freeze({value: 'bar'}), {}, <add> 'did-update', freeze({value: 'foo'}), {}, <ide> ]); <ide> lifeCycles = []; // reset <ide> React.unmountComponentAtNode(container); <ide><path>src/isomorphic/modern/element/__tests__/ReactJSXElement-test.js <ide> describe('ReactJSXElement', function() { <ide> expect(element.type).toBe(Component); <ide> expect(element.key).toBe(null); <ide> expect(element.ref).toBe(null); <del> expect(element.props).toEqual({}); <add> var expectation = {}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('allows a lower-case to be passed as the string type', function() { <ide> var element = <div />; <ide> expect(element.type).toBe('div'); <ide> expect(element.key).toBe(null); <ide> expect(element.ref).toBe(null); <del> expect(element.props).toEqual({}); <add> var expectation = {}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('allows a string to be passed as the type', function() { <ide> describe('ReactJSXElement', function() { <ide> expect(element.type).toBe('div'); <ide> expect(element.key).toBe(null); <ide> expect(element.ref).toBe(null); <del> expect(element.props).toEqual({}); <add> var expectation = {}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('returns an immutable element', function() { <ide> describe('ReactJSXElement', function() { <ide> expect(element.type).toBe(Component); <ide> expect(element.key).toBe('12'); <ide> expect(element.ref).toBe('34'); <del> expect(element.props).toEqual({foo:'56'}); <add> var expectation = {foo:'56'}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('coerces the key to a string', function() { <ide> var element = <Component key={12} foo="56" />; <ide> expect(element.type).toBe(Component); <ide> expect(element.key).toBe('12'); <ide> expect(element.ref).toBe(null); <del> expect(element.props).toEqual({foo:'56'}); <add> var expectation = {foo:'56'}; <add> Object.freeze(expectation); <add> expect(element.props).toEqual(expectation); <ide> }); <ide> <ide> it('merges JSX children onto the children prop', function() { <ide><path>src/renderers/dom/client/ReactMount.js <ide> var DOMProperty = require('DOMProperty'); <ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var ReactElement = require('ReactElement'); <del>var ReactElementValidator = require('ReactElementValidator'); <ide> var ReactEmptyComponent = require('ReactEmptyComponent'); <ide> var ReactInstanceHandles = require('ReactInstanceHandles'); <ide> var ReactInstanceMap = require('ReactInstanceMap'); <ide> var ReactMount = { <ide> nextElement, <ide> container, <ide> callback) { <del> if (__DEV__) { <del> ReactElementValidator.checkAndWarnForMutatedProps(nextElement); <del> } <del> <ide> ReactMount.scrollMonitor(container, function() { <ide> ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); <ide> if (callback) { <ide><path>src/renderers/shared/reconciler/ReactCompositeComponent.js <ide> var ReactComponentEnvironment = require('ReactComponentEnvironment'); <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var ReactElement = require('ReactElement'); <del>var ReactElementValidator = require('ReactElementValidator'); <ide> var ReactInstanceMap = require('ReactInstanceMap'); <ide> var ReactLifeCycle = require('ReactLifeCycle'); <ide> var ReactNativeComponent = require('ReactNativeComponent'); <ide> var ReactCompositeComponentMixin = { <ide> } <ide> <ide> if (this._pendingStateQueue !== null || this._pendingForceUpdate) { <del> if (__DEV__) { <del> ReactElementValidator.checkAndWarnForMutatedProps( <del> this._currentElement <del> ); <del> } <del> <ide> this.updateComponent( <ide> transaction, <ide> this._currentElement, <ide><path>src/renderers/shared/reconciler/ReactReconciler.js <ide> 'use strict'; <ide> <ide> var ReactRef = require('ReactRef'); <del>var ReactElementValidator = require('ReactElementValidator'); <ide> <ide> /** <ide> * Helper to call ReactRef.attachRefs with this composite component, split out <ide> var ReactReconciler = { <ide> */ <ide> mountComponent: function(internalInstance, rootID, transaction, context) { <ide> var markup = internalInstance.mountComponent(rootID, transaction, context); <del> if (__DEV__) { <del> ReactElementValidator.checkAndWarnForMutatedProps( <del> internalInstance._currentElement <del> ); <del> } <ide> if (internalInstance._currentElement.ref != null) { <ide> transaction.getReactMountReady().enqueue(attachRefs, internalInstance); <ide> } <ide> var ReactReconciler = { <ide> return; <ide> } <ide> <del> if (__DEV__) { <del> ReactElementValidator.checkAndWarnForMutatedProps(nextElement); <del> } <del> <ide> var refsChanged = ReactRef.shouldUpdateRefs( <ide> prevElement, <ide> nextElement
8
Ruby
Ruby
use tt in doc for actionpack [ci skip]
8c5ab21b25faa991de40fd7937387e20f0770d4b
<ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb <ide> class InvalidCrossOriginRequest < ActionControllerError #:nodoc: <ide> # Since HTML and JavaScript requests are typically made from the browser, we <ide> # need to ensure to verify request authenticity for the web browser. We can <ide> # use session-oriented authentication for these types of requests, by using <del> # the `protect_from_forgery` method in our controllers. <add> # the <tt>protect_from_forgery</tt> method in our controllers. <ide> # <ide> # GET requests are not protected since they don't have side effects like writing <ide> # to the database and don't leak sensitive information. JavaScript requests are <ide><path>actionpack/lib/action_controller/metal/rescue.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionController #:nodoc: <del> # This module is responsible for providing `rescue_from` helpers <add> # This module is responsible for providing +rescue_from+ helpers <ide> # to controllers and configuring when detailed exceptions must be <ide> # shown. <ide> module Rescue <ide> module Rescue <ide> <ide> # Override this method if you want to customize when detailed <ide> # exceptions must be shown. This method is only called when <del> # consider_all_requests_local is false. By default, it returns <del> # false, but someone may set it to `request.local?` so local <add> # +consider_all_requests_local+ is +false+. By default, it returns <add> # +false+, but someone may set it to <tt>request.local?</tt> so local <ide> # requests in production still show the detailed exception pages. <ide> def show_detailed_exceptions? <ide> false <ide><path>actionpack/lib/action_dispatch/http/cache.rb <ide> def date=(utc_time) <ide> # support strong ETags and will ignore weak ETags entirely. <ide> # <ide> # Weak ETags are what we almost always need, so they're the default. <del> # Check out `#strong_etag=` to provide a strong ETag validator. <add> # Check out #strong_etag= to provide a strong ETag validator. <ide> def etag=(weak_validators) <ide> self.weak_etag = weak_validators <ide> end <ide><path>actionpack/lib/action_dispatch/middleware/public_exceptions.rb <ide> <ide> module ActionDispatch <ide> # When called, this middleware renders an error page. By default if an HTML <del> # response is expected it will render static error pages from the `/public` <add> # response is expected it will render static error pages from the <tt>/public</tt> <ide> # directory. For example when this middleware receives a 500 response it will <del> # render the template found in `/public/500.html`. <add> # render the template found in <tt>/public/500.html</tt>. <ide> # If an internationalized locale is set, this middleware will attempt to render <del> # the template in `/public/500.<locale>.html`. If an internationalized template <del> # is not found it will fall back on `/public/500.html`. <add> # the template in <tt>/public/500.<locale>.html</tt>. If an internationalized template <add> # is not found it will fall back on <tt>/public/500.html</tt>. <ide> # <ide> # When a request with a content type other than HTML is made, this middleware <ide> # will attempt to convert error information into the appropriate response type. <ide><path>actionpack/lib/action_dispatch/middleware/session/cookie_store.rb <ide> module Session <ide> # be encrypted, and signed cookies generated by Rails 3 will be <ide> # transparently read and encrypted to provide a smooth upgrade path. <ide> # <del> # Configure your session store in config/initializers/session_store.rb: <add> # Configure your session store in <tt>config/initializers/session_store.rb</tt>: <ide> # <ide> # Rails.application.config.session_store :cookie_store, key: '_your_app_session' <ide> # <del> # Configure your secret key in config/secrets.yml: <add> # Configure your secret key in <tt>config/secrets.yml</tt>: <ide> # <ide> # development: <ide> # secret_key_base: 'secret key' <ide> # <del> # To generate a secret key for an existing application, run `rails secret`. <add> # To generate a secret key for an existing application, run <tt>rails secret</tt>. <ide> # <ide> # If you are upgrading an existing Rails 3 app, you should leave your <ide> # existing secret_token in place and simply add the new secret_key_base. <ide><path>actionpack/lib/action_dispatch/routing/redirection.rb <ide> module Redirection <ide> # get "/stories" => redirect("/posts") <ide> # <ide> # This will redirect the user, while ignoring certain parts of the request, including query string, etc. <del> # `/stories`, `/stories?foo=bar`, etc all redirect to `/posts`. <add> # <tt>/stories</tt>, <tt>/stories?foo=bar</tt>, etc all redirect to <tt>/posts</tt>. <ide> # <ide> # You can also use interpolation in the supplied redirect argument: <ide> # <ide> module Redirection <ide> # get '/stories', to: redirect(path: '/posts') <ide> # <ide> # This will redirect the user, while changing only the specified parts of the request, <del> # for example the `path` option in the last example. <del> # `/stories`, `/stories?foo=bar`, redirect to `/posts` and `/posts?foo=bar` respectively. <add> # for example the +path+ option in the last example. <add> # <tt>/stories</tt>, <tt>/stories?foo=bar</tt>, redirect to <tt>/posts</tt> and <tt>/posts?foo=bar</tt> respectively. <ide> # <ide> # Finally, an object which responds to call can be supplied to redirect, allowing you to reuse <ide> # common redirect routes. The call method must accept two arguments, params and request, and return <ide><path>actionpack/lib/action_dispatch/routing/url_for.rb <ide> def initialize(*) <ide> end <ide> <ide> # Hook overridden in controller to add request information <del> # with `default_url_options`. Application logic should not <add> # with +default_url_options+. Application logic should not <ide> # go into url_options. <ide> def url_options <ide> default_url_options <ide><path>actionpack/lib/action_dispatch/testing/test_request.rb <ide> class TestRequest < Request <ide> "HTTP_USER_AGENT" => "Rails Testing", <ide> ) <ide> <del> # Create a new test request with default `env` values. <add> # Create a new test request with default +env+ values. <ide> def self.create(env = {}) <ide> env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application <ide> env["rack.request.cookie_hash"] ||= {}.with_indifferent_access
8
Javascript
Javascript
replace loaders with rules in test
25fe5209693f98c7c2b720a94e4dea0550974145
<ide><path>test/TestCases.test.js <ide> describe("TestCases", () => { <ide> extensions: [".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"] <ide> }, <ide> module: { <del> loaders: [{ <add> rules: [{ <ide> test: /\.coffee$/, <ide> loader: "coffee-loader" <ide> }, {
1
Text
Text
remove outdated rule on single quotes in docs
42474f38690030f9c853f5ac1aa4959349d7ff15
<ide><path>CONTRIBUTING.md <ide> npm run test:watch <ide> <ide> ### Docs <ide> <del>Improvements to the documentation are always welcome. In the docs we abide by typographic rules, so instead of ' you should use '. Same goes for โ€œ โ€ and dashes (โ€”) where appropriate. These rules only apply to the text, not to code blocks. <del> <del>The docs are published automatically when the `master` branch is updated. <add>Improvements to the documentation are always welcome. You can find them in the [`docs`](/docs) path. We use [Docusaurus](https://docusaurus.io/) to build our documentation website. The website is published automatically whenever the `master` branch is updated. <ide> <ide> ### Examples <ide>
1
Javascript
Javascript
fix touchhistorymath import
554243eb567cc587ce50a3f2224bbf42b931c9b4
<ide><path>Libraries/Interaction/PanResponder.js <ide> 'use strict'; <ide> <ide> const InteractionManager = require('./InteractionManager'); <del>const TouchHistoryMath = require('TouchHistoryMath'); <add>const TouchHistoryMath = require('./TouchHistoryMath'); <ide> <ide> const currentCentroidXOfTouchesChangedAfter = TouchHistoryMath.currentCentroidXOfTouchesChangedAfter; <ide> const currentCentroidYOfTouchesChangedAfter = TouchHistoryMath.currentCentroidYOfTouchesChangedAfter;
1
Ruby
Ruby
fix rubocop warnings
501774e3bc73d5dd367054b954893d9561bf00d2
<ide><path>Library/Homebrew/test/test_os_mac_language.rb <ide> <ide> class OSMacLanguageTests < Homebrew::TestCase <ide> def test_language_format <del> assert_match %r{\A[a-z]{2}(-[A-Z]{2})?\Z}, OS::Mac.language <add> assert_match(/\A[a-z]{2}(-[A-Z]{2})?\Z/, OS::Mac.language) <ide> end <ide> end
1
Javascript
Javascript
allow optionalmemberexpression in deps
7992ca10df497002e0e91bb5bfbc9661c9c85b88
<ide><path>packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js <ide> const tests = { <ide> }, <ide> ], <ide> }, <add> { <add> code: normalizeIndent` <add> function MyComponent({ history }) { <add> useEffect(() => { <add> return [ <add> history?.foo <add> ]; <add> }, []); <add> } <add> `, <add> errors: [ <add> { <add> message: <add> "React Hook useEffect has a missing dependency: 'history?.foo'. " + <add> 'Either include it or remove the dependency array.', <add> suggestions: [ <add> { <add> desc: 'Update the dependencies array to be: [history?.foo]', <add> output: normalizeIndent` <add> function MyComponent({ history }) { <add> useEffect(() => { <add> return [ <add> history?.foo <add> ]; <add> }, [history?.foo]); <add> } <add> `, <add> }, <add> ], <add> }, <add> ], <add> }, <ide> { <ide> code: normalizeIndent` <ide> function MyComponent() { <ide><path>packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js <ide> function scanForDeclaredBareFunctions({ <ide> */ <ide> function getDependency(node) { <ide> if ( <del> node.parent.type === 'MemberExpression' && <add> (node.parent.type === 'MemberExpression' || <add> node.parent.type === 'OptionalMemberExpression') && <ide> node.parent.object === node && <ide> node.parent.property.name !== 'current' && <ide> !node.parent.computed && <ide> function getDependency(node) { <ide> * (foo) -> 'foo' <ide> * foo.(bar) -> 'foo.bar' <ide> * foo.bar.(baz) -> 'foo.bar.baz' <add> * foo?.(bar) -> 'foo?.bar' <ide> * Otherwise throw. <ide> */ <ide> function toPropertyAccessString(node) { <ide> function toPropertyAccessString(node) { <ide> const object = toPropertyAccessString(node.object); <ide> const property = toPropertyAccessString(node.property); <ide> return `${object}.${property}`; <add> } else if (node.type === 'OptionalMemberExpression' && !node.computed) { <add> const object = toPropertyAccessString(node.object); <add> const property = toPropertyAccessString(node.property); <add> return `${object}?.${property}`; <ide> } else { <ide> throw new Error(`Unsupported node type: ${node.type}`); <ide> }
2
PHP
PHP
fix return type of model update()
4495d0cfb8632e3c59d0a80a8da03595b4dfb3ab
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> protected function incrementOrDecrementAttributeValue($column, $amount, $method) <ide> * <ide> * @param array $attributes <ide> * @param array $options <del> * @return bool|int <add> * @return bool <ide> */ <ide> public function update(array $attributes = [], array $options = []) <ide> {
1
Python
Python
update caesar_cipher.py (#702)
ad68eed73e2cf39ee347e36a4e0fdf54310bd79a
<ide><path>ciphers/caesar_cipher.py <ide> def main(): <ide> print("4.Quit") <ide> choice = input("What would you like to do?: ") <ide> if choice not in ['1', '2', '3', '4']: <del> print ("Invalid choice") <add> print ("Invalid choice, please enter a valid choice") <ide> elif choice == '1': <del> strng = input("Please enter the string to be ecrypted: ") <add> strng = input("Please enter the string to be encrypted: ") <ide> key = int(input("Please enter off-set between 1-94: ")) <ide> if key in range(1, 95): <ide> print (encrypt(strng.lower(), key)) <ide> elif choice == '2': <ide> strng = input("Please enter the string to be decrypted: ") <ide> key = int(input("Please enter off-set between 1-94: ")) <del> if key > 0 and key <= 94: <add> if key in range(1,95): <ide> print(decrypt(strng, key)) <ide> elif choice == '3': <ide> strng = input("Please enter the string to be decrypted: ")
1
Javascript
Javascript
add a test for this.render('template')
6e6668a7acd93ccea5ccc7d87fe22414effa42c0
<ide><path>packages/ember/tests/routing/basic_test.js <ide> test("The Homepage with explicit template name in renderTemplate", function() { <ide> equal(Ember.$('h3:contains(Megatroll)', '#qunit-fixture').length, 1, "The homepage template was rendered"); <ide> }); <ide> <add>test("An alternate template will pull in an alternate controller", function() { <add> Router.map(function() { <add> this.route("home", { path: "/" }); <add> }); <add> <add> App.HomeRoute = Ember.Route.extend({ <add> renderTemplate: function() { <add> this.render('homepage'); <add> } <add> }); <add> <add> App.HomepageController = Ember.Controller.extend({ <add> home: "Comes from homepage" <add> }); <add> <add> bootApplication(); <add> <add> Ember.run(function() { <add> router.handleURL("/"); <add> }); <add> <add> equal(Ember.$('h3:contains(Megatroll) + p:contains(Comes from homepage)', '#qunit-fixture').length, 1, "The homepage template was rendered"); <add>}); <add> <ide> test("The Homepage with explicit template name in renderTemplate and controller", function() { <ide> Router.map(function() { <ide> this.route("home", { path: "/" });
1
Text
Text
add changelog entry for yaml parsing removal
ec53106068ad7950dc005739b2132f2392c3517b
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Remove support for parsing YAML parameters from request. <add> <add> *Aaron Patterson* <add> <ide> * Support for PostgreSQL's `ltree` data type. <ide> <ide> *Rob Worley* <ide> <del>* Fix undefined method `to_i` when calling `new` on a scope that uses an <add>* Fix undefined method `to_i` when calling `new` on a scope that uses an <ide> Array; Fix FloatDomainError when setting integer column to NaN. <ide> Fixes #8718, #8734, #8757. <ide>
1
Python
Python
fix ineffective no_decay bug
6c4789e4e86012a5678335e5eae47ac0687e6b2f
<ide><path>examples/run_classifier.py <ide> def main(): <ide> param_optimizer = list(model.named_parameters()) <ide> no_decay = ['bias', 'gamma', 'beta'] <ide> optimizer_grouped_parameters = [ <del> {'params': [p for n, p in param_optimizer if n not in no_decay], 'weight_decay_rate': 0.01}, <del> {'params': [p for n, p in param_optimizer if n in no_decay], 'weight_decay_rate': 0.0} <add> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.01}, <add> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.0} <ide> ] <ide> optimizer = BertAdam(optimizer_grouped_parameters, <ide> lr=args.learning_rate,
1
Text
Text
fix stability text for n-api
3706c65500008a8f762317ceb956477c0c2e39e2
<ide><path>doc/api/addons.md <ide> illustration of how it can be used. <ide> <ide> ## N-API <ide> <del>> Stability: 1 - Experimental <add>> Stability: 2 - Stable <ide> <ide> N-API is an API for building native Addons. It is independent from <ide> the underlying JavaScript runtime (e.g. V8) and is maintained as part of
1
Text
Text
add v4.9.0-beta.4 to changelog
792ca6cc82e28214228a27419d1f9caf370e352b
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.9.0-beta.4 (November 15, 2022) <add> <add>- [#20256](https://github.com/emberjs/ember.js/pull/20256) [BUGFIX] Correct types for Ember Arrays <add>- [#20257](https://github.com/emberjs/ember.js/pull/20257) [BUGFIX] Fix types for `getOwner` and GlimmerComponent <add> <ide> ### v4.8.2 (November 3, 2022) <ide> <ide> - [#20244](https://github.com/emberjs/ember.js/pull/20244) Add missing type for `getComponentTemplate` to preview types
1
Text
Text
use kbd element in tty doc
8a3808dc378219d39b0bf9693f0e640d390e51fb
<ide><path>doc/api/tty.md <ide> Allows configuration of `tty.ReadStream` so that it operates as a raw device. <ide> When in raw mode, input is always available character-by-character, not <ide> including modifiers. Additionally, all special processing of characters by the <ide> terminal is disabled, including echoing input characters. <del>`CTRL`+`C` will no longer cause a `SIGINT` when in this mode. <add><kbd>Ctrl</kbd>+<kbd>C</kbd> will no longer cause a `SIGINT` when in this mode. <ide> <ide> ## Class: `tty.WriteStream` <ide> <!-- YAML
1
PHP
PHP
skip flaky test when no results come back
418cdc45c16944321306882a89999f9234962b7d
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testDeepBelongsToManySubqueryStrategy() <ide> ]); <ide> <ide> $result = $table->find()->contain(['Articles.Tags'])->toArray(); <add> $this->skipIf(count($result) == 0, 'No results, this test sometimes acts up on PHP 5.6'); <add> <ide> $this->assertEquals( <ide> ['tag1', 'tag3'], <ide> collection($result[2]->articles[0]->tags)->extract('name')->toArray()
1
Go
Go
fix some revision about log output
adfd1ddfc6e094295d07ff2b36fb6e91cf7878dd
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> } <ide> <ide> func (devices *DeviceSet) AddDevice(hash, baseHash string) error { <del> log.Debugf("[deviceset] AddDevice() hash=%s basehash=%s", hash, baseHash) <add> log.Debugf("[deviceset] AddDevice(hash=%s basehash=%s)", hash, baseHash) <ide> defer log.Debugf("[deviceset] AddDevice(hash=%s basehash=%s) END", hash, baseHash) <ide> <ide> baseInfo, err := devices.lookupDevice(baseHash) <ide> func (devices *DeviceSet) waitClose(info *DevInfo) error { <ide> } <ide> <ide> func (devices *DeviceSet) Shutdown() error { <del> log.Debugf("[deviceset %s] shutdown()", devices.devicePrefix) <add> log.Debugf("[deviceset %s] Shutdown()", devices.devicePrefix) <ide> log.Debugf("[devmapper] Shutting down DeviceSet: %s", devices.root) <del> defer log.Debugf("[deviceset %s] shutdown END", devices.devicePrefix) <add> defer log.Debugf("[deviceset %s] Shutdown() END", devices.devicePrefix) <ide> <ide> var devs []*DevInfo <ide> <ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error { <ide> <ide> if info.mountCount > 0 { <ide> if path != info.mountPath { <del> return fmt.Errorf("Trying to mount devmapper device in multple places (%s, %s)", info.mountPath, path) <add> return fmt.Errorf("Trying to mount devmapper device in multiple places (%s, %s)", info.mountPath, path) <ide> } <ide> <ide> info.mountCount++
1
Javascript
Javascript
fix comment typo
ee73183dc953fe736a59b981d66c2babc08f3d69
<ide><path>src/menu-sort-helpers.js <ide> function indexOfGroupContainingCommand (groups, command, ignoreGroup) { <ide> } <ide> <ide> // Sort nodes topologically using a depth-first approach. Encountered cycles <del>// and broken. <add>// are broken. <ide> function sortTopologically (originalOrder, edgesById) { <ide> const sorted = [] <ide> const marked = new Set()
1
Go
Go
add compress option for 'jsonfiles' log driver
f69f09f44ce9fedbc9d70f11980c1fc8d7f77cec
<ide><path>daemon/logger/jsonfilelog/jsonfilelog.go <ide> func New(info logger.Info) (logger.Logger, error) { <ide> if err != nil { <ide> return nil, err <ide> } <add> if capval <= 0 { <add> return nil, fmt.Errorf("max-size should be a positive numbler") <add> } <ide> } <ide> var maxFiles = 1 <ide> if maxFileString, ok := info.Config["max-file"]; ok { <ide> func New(info logger.Info) (logger.Logger, error) { <ide> } <ide> } <ide> <add> var compress bool <add> if compressString, ok := info.Config["compress"]; ok { <add> var err error <add> compress, err = strconv.ParseBool(compressString) <add> if err != nil { <add> return nil, err <add> } <add> if compress && (maxFiles == 1 || capval == -1) { <add> return nil, fmt.Errorf("compress cannot be true when max-file is less than 2 or max-size is not set") <add> } <add> } <add> <ide> attrs, err := info.ExtraAttributes(nil) <ide> if err != nil { <ide> return nil, err <ide> func New(info logger.Info) (logger.Logger, error) { <ide> return b, nil <ide> } <ide> <del> writer, err := loggerutils.NewLogFile(info.LogPath, capval, maxFiles, marshalFunc, decodeFunc, 0640) <add> writer, err := loggerutils.NewLogFile(info.LogPath, capval, maxFiles, compress, marshalFunc, decodeFunc, 0640) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func ValidateLogOpt(cfg map[string]string) error { <ide> switch key { <ide> case "max-file": <ide> case "max-size": <add> case "compress": <ide> case "labels": <ide> case "env": <ide> case "env-regex": <ide><path>daemon/logger/jsonfilelog/jsonfilelog_test.go <ide> package jsonfilelog // import "github.com/docker/docker/daemon/logger/jsonfilelo <ide> <ide> import ( <ide> "bytes" <add> "compress/gzip" <ide> "encoding/json" <ide> "io/ioutil" <ide> "os" <ide> func TestJSONFileLoggerWithOpts(t *testing.T) { <ide> } <ide> defer os.RemoveAll(tmp) <ide> filename := filepath.Join(tmp, "container.log") <del> config := map[string]string{"max-file": "2", "max-size": "1k"} <add> config := map[string]string{"max-file": "3", "max-size": "1k", "compress": "true"} <ide> l, err := New(logger.Info{ <ide> ContainerID: cid, <ide> LogPath: filename, <ide> func TestJSONFileLoggerWithOpts(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> defer l.Close() <del> for i := 0; i < 20; i++ { <add> for i := 0; i < 36; i++ { <ide> if err := l.Log(&logger.Message{Line: []byte("line" + strconv.Itoa(i)), Source: "src1"}); err != nil { <ide> t.Fatal(err) <ide> } <ide> } <add> <ide> res, err := ioutil.ReadFile(filename) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <add> <ide> penUlt, err := ioutil.ReadFile(filename + ".1") <add> if err != nil { <add> if !os.IsNotExist(err) { <add> t.Fatal(err) <add> } <add> <add> file, err := os.Open(filename + ".1.gz") <add> defer file.Close() <add> if err != nil { <add> t.Fatal(err) <add> } <add> zipReader, err := gzip.NewReader(file) <add> defer zipReader.Close() <add> if err != nil { <add> t.Fatal(err) <add> } <add> penUlt, err = ioutil.ReadAll(zipReader) <add> if err != nil { <add> t.Fatal(err) <add> } <add> } <add> <add> file, err := os.Open(filename + ".2.gz") <add> defer file.Close() <add> if err != nil { <add> t.Fatal(err) <add> } <add> zipReader, err := gzip.NewReader(file) <add> defer zipReader.Close() <add> if err != nil { <add> t.Fatal(err) <add> } <add> antepenult, err := ioutil.ReadAll(zipReader) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> expectedPenultimate := `{"log":"line0\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add> expectedAntepenultimate := `{"log":"line0\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> {"log":"line1\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> {"log":"line2\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> {"log":"line3\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> func TestJSONFileLoggerWithOpts(t *testing.T) { <ide> {"log":"line14\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> {"log":"line15\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> ` <del> expected := `{"log":"line16\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add> expectedPenultimate := `{"log":"line16\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> {"log":"line17\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> {"log":"line18\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> {"log":"line19\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line20\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line21\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line22\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line23\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line24\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line25\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line26\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line27\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line28\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line29\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line30\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line31\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>` <add> expected := `{"log":"line32\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line33\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line34\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <add>{"log":"line35\n","stream":"src1","time":"0001-01-01T00:00:00Z"} <ide> ` <ide> <ide> if string(res) != expected { <ide> func TestJSONFileLoggerWithOpts(t *testing.T) { <ide> if string(penUlt) != expectedPenultimate { <ide> t.Fatalf("Wrong log content: %q, expected %q", penUlt, expectedPenultimate) <ide> } <del> <add> if string(antepenult) != expectedAntepenultimate { <add> t.Fatalf("Wrong log content: %q, expected %q", antepenult, expectedAntepenultimate) <add> } <ide> } <ide> <ide> func TestJSONFileLoggerWithLabelsEnv(t *testing.T) { <ide><path>daemon/logger/loggerutils/logfile.go <ide> package loggerutils // import "github.com/docker/docker/daemon/logger/loggerutil <ide> <ide> import ( <ide> "bytes" <add> "compress/gzip" <ide> "context" <add> "encoding/json" <ide> "fmt" <ide> "io" <ide> "os" <ide> "strconv" <add> "strings" <ide> "sync" <ide> "time" <ide> <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/daemon/logger/loggerutils/multireader" <ide> "github.com/docker/docker/pkg/filenotify" <add> "github.com/docker/docker/pkg/pools" <ide> "github.com/docker/docker/pkg/pubsub" <ide> "github.com/docker/docker/pkg/tailfile" <ide> "github.com/fsnotify/fsnotify" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <add>const tmpLogfileSuffix = ".tmp" <add> <add>// rotateFileMetadata is a metadata of the gzip header of the compressed log file <add>type rotateFileMetadata struct { <add> LastTime time.Time `json:"lastTime,omitempty"` <add>} <add> <add>// refCounter is a counter of logfile being referenced <add>type refCounter struct { <add> mu sync.Mutex <add> counter map[string]int <add>} <add> <add>// Reference increase the reference counter for specified logfile <add>func (rc *refCounter) GetReference(fileName string, openRefFile func(fileName string, exists bool) (*os.File, error)) (*os.File, error) { <add> rc.mu.Lock() <add> defer rc.mu.Unlock() <add> <add> var ( <add> file *os.File <add> err error <add> ) <add> _, ok := rc.counter[fileName] <add> file, err = openRefFile(fileName, ok) <add> if err != nil { <add> return nil, err <add> } <add> <add> if ok { <add> rc.counter[fileName]++ <add> } else if file != nil { <add> rc.counter[file.Name()] = 1 <add> } <add> <add> return file, nil <add>} <add> <add>// Dereference reduce the reference counter for specified logfile <add>func (rc *refCounter) Dereference(fileName string) error { <add> rc.mu.Lock() <add> defer rc.mu.Unlock() <add> <add> rc.counter[fileName]-- <add> if rc.counter[fileName] <= 0 { <add> delete(rc.counter, fileName) <add> err := os.Remove(fileName) <add> if err != nil { <add> return err <add> } <add> } <add> return nil <add>} <add> <ide> // LogFile is Logger implementation for default Docker logging. <ide> type LogFile struct { <del> f *os.File // store for closing <del> closed bool <del> mu sync.RWMutex <del> capacity int64 //maximum size of each file <del> currentSize int64 // current size of the latest file <del> maxFiles int //maximum number of files <del> notifyRotate *pubsub.Publisher <del> marshal logger.MarshalFunc <del> createDecoder makeDecoderFunc <del> perms os.FileMode <add> mu sync.RWMutex // protects the logfile access <add> f *os.File // store for closing <add> closed bool <add> rotateMu sync.Mutex // blocks the next rotation until the current rotation is completed <add> capacity int64 // maximum size of each file <add> currentSize int64 // current size of the latest file <add> maxFiles int // maximum number of files <add> compress bool // whether old versions of log files are compressed <add> lastTimestamp time.Time // timestamp of the last log <add> filesRefCounter refCounter // keep reference-counted of decompressed files <add> notifyRotate *pubsub.Publisher <add> marshal logger.MarshalFunc <add> createDecoder makeDecoderFunc <add> perms os.FileMode <ide> } <ide> <ide> type makeDecoderFunc func(rdr io.Reader) func() (*logger.Message, error) <ide> <ide> //NewLogFile creates new LogFile <del>func NewLogFile(logPath string, capacity int64, maxFiles int, marshaller logger.MarshalFunc, decodeFunc makeDecoderFunc, perms os.FileMode) (*LogFile, error) { <add>func NewLogFile(logPath string, capacity int64, maxFiles int, compress bool, marshaller logger.MarshalFunc, decodeFunc makeDecoderFunc, perms os.FileMode) (*LogFile, error) { <ide> log, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, perms) <ide> if err != nil { <ide> return nil, err <ide> func NewLogFile(logPath string, capacity int64, maxFiles int, marshaller logger. <ide> } <ide> <ide> return &LogFile{ <del> f: log, <del> capacity: capacity, <del> currentSize: size, <del> maxFiles: maxFiles, <del> notifyRotate: pubsub.NewPublisher(0, 1), <del> marshal: marshaller, <del> createDecoder: decodeFunc, <del> perms: perms, <add> f: log, <add> capacity: capacity, <add> currentSize: size, <add> maxFiles: maxFiles, <add> compress: compress, <add> filesRefCounter: refCounter{counter: make(map[string]int)}, <add> notifyRotate: pubsub.NewPublisher(0, 1), <add> marshal: marshaller, <add> createDecoder: decodeFunc, <add> perms: perms, <ide> }, nil <ide> } <ide> <ide> func (w *LogFile) WriteLogEntry(msg *logger.Message) error { <ide> n, err := w.f.Write(b) <ide> if err == nil { <ide> w.currentSize += int64(n) <add> w.lastTimestamp = msg.Timestamp <ide> } <ide> w.mu.Unlock() <ide> return err <ide> func (w *LogFile) checkCapacityAndRotate() error { <ide> } <ide> <ide> if w.currentSize >= w.capacity { <del> name := w.f.Name() <add> w.rotateMu.Lock() <add> fname := w.f.Name() <ide> if err := w.f.Close(); err != nil { <add> w.rotateMu.Unlock() <ide> return errors.Wrap(err, "error closing file") <ide> } <del> if err := rotate(name, w.maxFiles); err != nil { <add> if err := rotate(fname, w.maxFiles, w.compress); err != nil { <add> w.rotateMu.Unlock() <ide> return err <ide> } <del> file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, w.perms) <add> file, err := os.OpenFile(fname, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, w.perms) <ide> if err != nil { <add> w.rotateMu.Unlock() <ide> return err <ide> } <ide> w.f = file <ide> w.currentSize = 0 <ide> w.notifyRotate.Publish(struct{}{}) <add> <add> if w.maxFiles <= 1 || !w.compress { <add> w.rotateMu.Unlock() <add> return nil <add> } <add> <add> go func() { <add> compressFile(fname+".1", w.lastTimestamp) <add> w.rotateMu.Unlock() <add> }() <ide> } <ide> <ide> return nil <ide> } <ide> <del>func rotate(name string, maxFiles int) error { <add>func rotate(name string, maxFiles int, compress bool) error { <ide> if maxFiles < 2 { <ide> return nil <ide> } <add> <add> var extension string <add> if compress { <add> extension = ".gz" <add> } <ide> for i := maxFiles - 1; i > 1; i-- { <del> toPath := name + "." + strconv.Itoa(i) <del> fromPath := name + "." + strconv.Itoa(i-1) <add> toPath := name + "." + strconv.Itoa(i) + extension <add> fromPath := name + "." + strconv.Itoa(i-1) + extension <ide> if err := os.Rename(fromPath, toPath); err != nil && !os.IsNotExist(err) { <del> return errors.Wrap(err, "error rotating old log entries") <add> return err <ide> } <ide> } <ide> <ide> if err := os.Rename(name, name+".1"); err != nil && !os.IsNotExist(err) { <del> return errors.Wrap(err, "error rotating current log") <add> return err <ide> } <add> <ide> return nil <ide> } <ide> <add>func compressFile(fileName string, lastTimestamp time.Time) { <add> file, err := os.Open(fileName) <add> if err != nil { <add> logrus.Errorf("Failed to open log file: %v", err) <add> return <add> } <add> defer func() { <add> file.Close() <add> err := os.Remove(fileName) <add> if err != nil { <add> logrus.Errorf("Failed to remove source log file: %v", err) <add> } <add> }() <add> <add> outFile, err := os.OpenFile(fileName+".gz", os.O_CREATE|os.O_RDWR, 0640) <add> if err != nil { <add> logrus.Errorf("Failed to open or create gzip log file: %v", err) <add> return <add> } <add> defer func() { <add> outFile.Close() <add> if err != nil { <add> os.Remove(fileName + ".gz") <add> } <add> }() <add> <add> compressWriter := gzip.NewWriter(outFile) <add> defer compressWriter.Close() <add> <add> // Add the last log entry timestramp to the gzip header <add> extra := rotateFileMetadata{} <add> extra.LastTime = lastTimestamp <add> compressWriter.Header.Extra, err = json.Marshal(&extra) <add> if err != nil { <add> // Here log the error only and don't return since this is just an optimization. <add> logrus.Warningf("Failed to marshal JSON: %v", err) <add> } <add> <add> _, err = pools.Copy(compressWriter, file) <add> if err != nil { <add> logrus.WithError(err).WithField("module", "container.logs").WithField("file", fileName).Error("Error compressing log file") <add> return <add> } <add>} <add> <ide> // MaxFiles return maximum number of files <ide> func (w *LogFile) MaxFiles() int { <ide> return w.maxFiles <ide> func (w *LogFile) Close() error { <ide> // ReadLogs decodes entries from log files and sends them the passed in watcher <ide> func (w *LogFile) ReadLogs(config logger.ReadConfig, watcher *logger.LogWatcher) { <ide> w.mu.RLock() <del> files, err := w.openRotatedFiles() <del> if err != nil { <del> w.mu.RUnlock() <del> watcher.Err <- err <del> return <del> } <del> defer func() { <del> for _, f := range files { <del> f.Close() <del> } <del> }() <del> <ide> currentFile, err := os.Open(w.f.Name()) <ide> if err != nil { <ide> w.mu.RUnlock() <ide> func (w *LogFile) ReadLogs(config logger.ReadConfig, watcher *logger.LogWatcher) <ide> defer currentFile.Close() <ide> <ide> currentChunk, err := newSectionReader(currentFile) <del> w.mu.RUnlock() <del> <ide> if err != nil { <add> w.mu.RUnlock() <ide> watcher.Err <- err <ide> return <ide> } <ide> <ide> if config.Tail != 0 { <add> files, err := w.openRotatedFiles(config) <add> if err != nil { <add> w.mu.RUnlock() <add> watcher.Err <- err <add> return <add> } <add> w.mu.RUnlock() <ide> seekers := make([]io.ReadSeeker, 0, len(files)+1) <ide> for _, f := range files { <ide> seekers = append(seekers, f) <ide> func (w *LogFile) ReadLogs(config logger.ReadConfig, watcher *logger.LogWatcher) <ide> if len(seekers) > 0 { <ide> tailFile(multireader.MultiReadSeeker(seekers...), watcher, w.createDecoder, config) <ide> } <add> for _, f := range files { <add> f.Close() <add> fileName := f.Name() <add> if strings.HasSuffix(fileName, tmpLogfileSuffix) { <add> err := w.filesRefCounter.Dereference(fileName) <add> if err != nil { <add> logrus.Errorf("Failed to dereference the log file %q: %v", fileName, err) <add> } <add> } <add> } <add> <add> w.mu.RLock() <ide> } <ide> <del> w.mu.RLock() <ide> if !config.Follow || w.closed { <ide> w.mu.RUnlock() <ide> return <ide> func (w *LogFile) ReadLogs(config logger.ReadConfig, watcher *logger.LogWatcher) <ide> followLogs(currentFile, watcher, notifyRotate, w.createDecoder, config.Since, config.Until) <ide> } <ide> <del>func (w *LogFile) openRotatedFiles() (files []*os.File, err error) { <add>func (w *LogFile) openRotatedFiles(config logger.ReadConfig) (files []*os.File, err error) { <add> w.rotateMu.Lock() <add> defer w.rotateMu.Unlock() <add> <ide> defer func() { <ide> if err == nil { <ide> return <ide> } <ide> for _, f := range files { <ide> f.Close() <add> if strings.HasSuffix(f.Name(), tmpLogfileSuffix) { <add> err := os.Remove(f.Name()) <add> if err != nil && !os.IsNotExist(err) { <add> logrus.Warningf("Failed to remove the logfile %q: %v", f.Name, err) <add> } <add> } <ide> } <ide> }() <ide> <ide> func (w *LogFile) openRotatedFiles() (files []*os.File, err error) { <ide> if !os.IsNotExist(err) { <ide> return nil, err <ide> } <add> <add> fileName := fmt.Sprintf("%s.%d.gz", w.f.Name(), i-1) <add> decompressedFileName := fileName + tmpLogfileSuffix <add> tmpFile, err := w.filesRefCounter.GetReference(decompressedFileName, func(refFileName string, exists bool) (*os.File, error) { <add> if exists { <add> return os.Open(refFileName) <add> } <add> return decompressfile(fileName, refFileName, config.Since) <add> }) <add> <add> if err != nil { <add> if !os.IsNotExist(err) { <add> return nil, err <add> } <add> continue <add> } <add> if tmpFile == nil { <add> // The log before `config.Since` does not need to read <add> break <add> } <add> <add> files = append(files, tmpFile) <ide> continue <ide> } <ide> files = append(files, f) <ide> func (w *LogFile) openRotatedFiles() (files []*os.File, err error) { <ide> return files, nil <ide> } <ide> <add>func decompressfile(fileName, destFileName string, since time.Time) (*os.File, error) { <add> cf, err := os.Open(fileName) <add> if err != nil { <add> return nil, err <add> } <add> defer cf.Close() <add> <add> rc, err := gzip.NewReader(cf) <add> if err != nil { <add> return nil, err <add> } <add> defer rc.Close() <add> <add> // Extract the last log entry timestramp from the gzip header <add> extra := &rotateFileMetadata{} <add> err = json.Unmarshal(rc.Header.Extra, extra) <add> if err == nil && extra.LastTime.Before(since) { <add> return nil, nil <add> } <add> <add> rs, err := os.OpenFile(destFileName, os.O_CREATE|os.O_RDWR, 0640) <add> if err != nil { <add> return nil, err <add> } <add> <add> _, err = pools.Copy(rs, rc) <add> if err != nil { <add> rs.Close() <add> rErr := os.Remove(rs.Name()) <add> if rErr != nil && os.IsNotExist(rErr) { <add> logrus.Errorf("Failed to remove the logfile %q: %v", rs.Name(), rErr) <add> } <add> return nil, err <add> } <add> <add> return rs, nil <add>} <add> <ide> func newSectionReader(f *os.File) (*io.SectionReader, error) { <ide> // seek to the end to get the size <ide> // we'll leave this at the end of the file since section reader does not advance the reader
3
PHP
PHP
update controller alias
73f37c6ce004a6da53711573365c3e8be555019e
<ide><path>app/config/app.php <ide> 'Cache' => 'Illuminate\Support\Facades\Cache', <ide> 'ClassLoader' => 'Illuminate\Support\ClassLoader', <ide> 'Config' => 'Illuminate\Support\Facades\Config', <del> 'Controller' => 'Illuminate\Routing\Controllers\Controller', <add> 'Controller' => 'Illuminate\Routing\Controller', <ide> 'Cookie' => 'Illuminate\Support\Facades\Cookie', <ide> 'Crypt' => 'Illuminate\Support\Facades\Crypt', <ide> 'DB' => 'Illuminate\Support\Facades\DB',
1
Text
Text
show images in readme.md by removing html tags
0d4c7748124a152aa92fc0f30d9707000291db95
<ide><path>resnet/README.md <ide> https://arxiv.org/pdf/1605.07146v1.pdf <ide> <ide> <b>Results:</b> <ide> <del><left> <del>![Precisions](g3doc/cifar_resnet.gif) <del></left> <del><left> <del>![Precisions Legends](g3doc/cifar_resnet_legends.gif) <del></left> <add> <add>![Precisions](g3doc/cifar_resnet.gif) ![Precisions Legends](g3doc/cifar_resnet_legends.gif) <ide> <ide> <ide> CIFAR-10 Model|Best Precision|Steps
1
Text
Text
add link to preview the new clas
683ceb8ff067ac53a7cb464ba1ec3f88e353e3f5
<ide><path>CONTRIBUTING.md <ide> Note: This is the code development repository for *jQuery Core* only. Before ope <ide> <ide> We're always looking for help [identifying bugs](#how-to-report-bugs), writing and reducing test cases, and improving documentation. And although new features are rare, anything passing our [guidelines](https://github.com/jquery/jquery/wiki/Adding-new-features) will be considered. <ide> <del>More information on how to contribute to this and other jQuery organization projects is at [contribute.jquery.org](https://contribute.jquery.org), including a short guide with tips, tricks, and ideas on [getting started with open source](https://contribute.jquery.org/open-source/). Please review our [commit & pull request guide](https://contribute.jquery.org/commits-and-pull-requests/) and [style guides](https://contribute.jquery.org/style-guide/) for instructions on how to maintain a fork and submit patches. Before we can merge any pull request, we'll also need you to sign our [contributor license agreement](https://contribute.jquery.org/cla/). <add>More information on how to contribute to this and other jQuery organization projects is at [contribute.jquery.org](https://contribute.jquery.org), including a short guide with tips, tricks, and ideas on [getting started with open source](https://contribute.jquery.org/open-source/). Please review our [commit & pull request guide](https://contribute.jquery.org/commits-and-pull-requests/) and [style guides](https://contribute.jquery.org/style-guide/) for instructions on how to maintain a fork and submit patches. <ide> <add>When opening a pull request, you'll be asked to sign our Contributor License Agreement. Both the Corporate and Individual agreements can be [previewed on GitHub](https://github.com/openjs-foundation/easycla). <ide> <ide> ## Questions and Discussion <ide>
1
Java
Java
move routerfunction webhandler to inner class
edd86e5dd556429f69f2098676867d77b7044116
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java <ide> public abstract class RouterFunctions { <ide> RouterFunctions.class.getName() + ".matchingPattern"; <ide> <ide> <del> private static final HandlerFunction<ServerResponse> NOT_FOUND_HANDLER = <del> request -> ServerResponse.notFound().build(); <ide> <ide> <ide> /** <ide> public static WebHandler toWebHandler(RouterFunction<?> routerFunction, HandlerS <ide> Assert.notNull(routerFunction, "RouterFunction must not be null"); <ide> Assert.notNull(strategies, "HandlerStrategies must not be null"); <ide> <del> return exchange -> { <del> ServerRequest request = new DefaultServerRequest(exchange, strategies.messageReaders()); <del> addAttributes(exchange, request); <del> return routerFunction.route(request) <del> .defaultIfEmpty(notFound()) <del> .flatMap(handlerFunction -> wrapException(() -> handlerFunction.handle(request))) <del> .flatMap(response -> wrapException(() -> response.writeTo(exchange, <del> new HandlerStrategiesResponseContext(strategies)))); <del> }; <add> return new RouterFunctionWebHandler(strategies, routerFunction); <ide> } <ide> <del> <del> private static <T> Mono<T> wrapException(Supplier<Mono<T>> supplier) { <del> try { <del> return supplier.get(); <del> } <del> catch (Throwable ex) { <del> return Mono.error(ex); <del> } <del> } <del> <del> private static void addAttributes(ServerWebExchange exchange, ServerRequest request) { <del> Map<String, Object> attributes = exchange.getAttributes(); <del> attributes.put(REQUEST_ATTRIBUTE, request); <del> } <del> <del> @SuppressWarnings("unchecked") <del> private static <T extends ServerResponse> HandlerFunction<T> notFound() { <del> return (HandlerFunction<T>) NOT_FOUND_HANDLER; <del> } <del> <del> @SuppressWarnings("unchecked") <del> static <T extends ServerResponse> HandlerFunction<T> cast(HandlerFunction<?> handlerFunction) { <del> return (HandlerFunction<T>) handlerFunction; <del> } <del> <del> <ide> /** <ide> * Represents a discoverable builder for router functions. <ide> * Obtained via {@link RouterFunctions#route()}. <ide> public DifferentComposedRouterFunction(RouterFunction<?> first, RouterFunction<? <ide> @Override <ide> public Mono<HandlerFunction<ServerResponse>> route(ServerRequest request) { <ide> return this.first.route(request) <del> .map(RouterFunctions::cast) <del> .switchIfEmpty(Mono.defer(() -> this.second.route(request).map(RouterFunctions::cast))); <add> .map(this::cast) <add> .switchIfEmpty(Mono.defer(() -> this.second.route(request).map(this::cast))); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private <T extends ServerResponse> HandlerFunction<T> cast(HandlerFunction<?> handlerFunction) { <add> return (HandlerFunction<T>) handlerFunction; <ide> } <ide> <ide> @Override <ide> public List<ViewResolver> viewResolvers() { <ide> } <ide> } <ide> <add> <add> private static class RouterFunctionWebHandler implements WebHandler { <add> <add> private static final HandlerFunction<ServerResponse> NOT_FOUND_HANDLER = <add> request -> ServerResponse.notFound().build(); <add> <add> private final HandlerStrategies strategies; <add> <add> private final RouterFunction<?> routerFunction; <add> <add> public RouterFunctionWebHandler(HandlerStrategies strategies, RouterFunction<?> routerFunction) { <add> this.strategies = strategies; <add> this.routerFunction = routerFunction; <add> } <add> <add> @Override <add> public Mono<Void> handle(ServerWebExchange exchange) { <add> return Mono.defer(() -> { <add> ServerRequest request = new DefaultServerRequest(exchange, this.strategies.messageReaders()); <add> addAttributes(exchange, request); <add> return this.routerFunction.route(request) <add> .defaultIfEmpty(notFound()) <add> .flatMap(handlerFunction -> wrapException(() -> handlerFunction.handle(request))) <add> .flatMap(response -> wrapException(() -> response.writeTo(exchange, <add> new HandlerStrategiesResponseContext(this.strategies)))); <add> }); <add> } <add> <add> private void addAttributes(ServerWebExchange exchange, ServerRequest request) { <add> Map<String, Object> attributes = exchange.getAttributes(); <add> attributes.put(REQUEST_ATTRIBUTE, request); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private static <T extends ServerResponse> HandlerFunction<T> notFound() { <add> return (HandlerFunction<T>) NOT_FOUND_HANDLER; <add> } <add> <add> private static <T> Mono<T> wrapException(Supplier<Mono<T>> supplier) { <add> try { <add> return supplier.get(); <add> } <add> catch (Throwable ex) { <add> return Mono.error(ex); <add> } <add> } <add> } <ide> }
1
Python
Python
return pidlockfile if the lock is stale
fa0fb625f233bbc475a72abb85670c817e8ad758
<ide><path>celery/bin/celeryd.py <ide> def acquire_pidlock(pidfile): <ide> if exc.errno == errno.ESRCH: <ide> sys.stderr.write("Stale pidfile exists. Removing it.\n") <ide> pidlock.release() <del> return <add> return PIDLockFile(pidfile) <ide> else: <ide> raise SystemExit( <ide> "ERROR: Pidfile (%s) already exists.\n"
1
Ruby
Ruby
add signature for bottle dsl
88a8def34cf617f20ef84c6191a9dbfc7b8790d6
<ide><path>Library/Homebrew/formula.rb <ide> def stage(interactive: false, debug_symbols: false) <ide> # The methods below define the formula DSL. <ide> class << self <ide> extend Predicable <add> extend T::Sig <ide> include BuildEnvironment::DSL <ide> include OnSystem::MacOSAndLinux <ide> <ide> def sha256(val) <ide> # <ide> # Formulae which should not be bottled should be tagged with: <ide> # <pre>bottle :disable, "reasons"</pre> <del> def bottle(*args, &block) <del> stable.bottle(*args, &block) <add> sig { params(block: T.proc.bind(BottleSpecification).void).void } <add> def bottle(&block) <add> stable.bottle(&block) <ide> end <ide> <ide> # @private
1
Go
Go
use sequential file access
c98e77c77c5b43bf50e8ae5296b02ce0b47ea188
<ide><path>cli/command/utils.go <ide> package command <ide> import ( <ide> "fmt" <ide> "io" <del> "io/ioutil" <ide> "os" <ide> "path/filepath" <ide> "runtime" <ide> "strings" <add> <add> "github.com/docker/docker/pkg/system" <ide> ) <ide> <ide> // CopyToFile writes the content of the reader to the specified file <ide> func CopyToFile(outfile string, r io.Reader) error { <del> tmpFile, err := ioutil.TempFile(filepath.Dir(outfile), ".docker_temp_") <add> // We use sequential file access here to avoid depleting the standby list <add> // on Windows. On Linux, this is a call directly to ioutil.TempFile <add> tmpFile, err := system.TempFileSequential(filepath.Dir(outfile), ".docker_temp_") <ide> if err != nil { <ide> return err <ide> } <ide><path>daemon/graphdriver/windows/windows.go <ide> func (fg *fileGetCloserWithBackupPrivileges) Get(filename string) (io.ReadCloser <ide> var f *os.File <ide> // Open the file while holding the Windows backup privilege. This ensures that the <ide> // file can be opened even if the caller does not actually have access to it according <del> // to the security descriptor. <add> // to the security descriptor. Also use sequential file access to avoid depleting the <add> // standby list - Microsoft VSO Bug Tracker #9900466 <ide> err := winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error { <ide> path := longpath.AddPrefix(filepath.Join(fg.path, filename)) <ide> p, err := syscall.UTF16FromString(path) <ide> if err != nil { <ide> return err <ide> } <del> h, err := syscall.CreateFile(&p[0], syscall.GENERIC_READ, syscall.FILE_SHARE_READ, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) <add> const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN <add> h, err := syscall.CreateFile(&p[0], syscall.GENERIC_READ, syscall.FILE_SHARE_READ, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS|fileFlagSequentialScan, 0) <ide> if err != nil { <ide> return &os.PathError{Op: "open", Path: path, Err: err} <ide> } <ide><path>pkg/system/filesys.go <ide> package system <ide> <ide> import ( <add> "io/ioutil" <ide> "os" <ide> "path/filepath" <ide> ) <ide> func IsAbs(path string) bool { <ide> return filepath.IsAbs(path) <ide> } <ide> <del>// The functions below here are wrappers for the equivalents in the os package. <add>// The functions below here are wrappers for the equivalents in the os and ioutils packages. <ide> // They are passthrough on Unix platforms, and only relevant on Windows. <ide> <ide> // CreateSequential creates the named file with mode 0666 (before umask), truncating <ide> func OpenSequential(name string) (*os.File, error) { <ide> func OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) { <ide> return os.OpenFile(name, flag, perm) <ide> } <add> <add>// TempFileSequential creates a new temporary file in the directory dir <add>// with a name beginning with prefix, opens the file for reading <add>// and writing, and returns the resulting *os.File. <add>// If dir is the empty string, TempFile uses the default directory <add>// for temporary files (see os.TempDir). <add>// Multiple programs calling TempFile simultaneously <add>// will not choose the same file. The caller can use f.Name() <add>// to find the pathname of the file. It is the caller's responsibility <add>// to remove the file when no longer needed. <add>func TempFileSequential(dir, prefix string) (f *os.File, err error) { <add> return ioutil.TempFile(dir, prefix) <add>} <ide><path>pkg/system/filesys_windows.go <ide> import ( <ide> "os" <ide> "path/filepath" <ide> "regexp" <add> "strconv" <ide> "strings" <add> "sync" <ide> "syscall" <add> "time" <ide> "unsafe" <ide> <ide> winio "github.com/Microsoft/go-winio" <ide> func syscallOpenSequential(path string, mode int, _ uint32) (fd syscall.Handle, <ide> h, e := syscall.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0) <ide> return h, e <ide> } <add> <add>// Helpers for TempFileSequential <add>var rand uint32 <add>var randmu sync.Mutex <add> <add>func reseed() uint32 { <add> return uint32(time.Now().UnixNano() + int64(os.Getpid())) <add>} <add>func nextSuffix() string { <add> randmu.Lock() <add> r := rand <add> if r == 0 { <add> r = reseed() <add> } <add> r = r*1664525 + 1013904223 // constants from Numerical Recipes <add> rand = r <add> randmu.Unlock() <add> return strconv.Itoa(int(1e9 + r%1e9))[1:] <add>} <add> <add>// TempFileSequential is a copy of ioutil.TempFile, modified to use sequential <add>// file access. Below is the original comment from golang: <add>// TempFile creates a new temporary file in the directory dir <add>// with a name beginning with prefix, opens the file for reading <add>// and writing, and returns the resulting *os.File. <add>// If dir is the empty string, TempFile uses the default directory <add>// for temporary files (see os.TempDir). <add>// Multiple programs calling TempFile simultaneously <add>// will not choose the same file. The caller can use f.Name() <add>// to find the pathname of the file. It is the caller's responsibility <add>// to remove the file when no longer needed. <add>func TempFileSequential(dir, prefix string) (f *os.File, err error) { <add> if dir == "" { <add> dir = os.TempDir() <add> } <add> <add> nconflict := 0 <add> for i := 0; i < 10000; i++ { <add> name := filepath.Join(dir, prefix+nextSuffix()) <add> f, err = OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) <add> if os.IsExist(err) { <add> if nconflict++; nconflict > 10 { <add> randmu.Lock() <add> rand = reseed() <add> randmu.Unlock() <add> } <add> continue <add> } <add> break <add> } <add> return <add>}
4
Javascript
Javascript
reuse program when not changed
a9e0b9de16960b04389bec9ee64c105d80d0e9c2
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> function initMaterial( material, lights, fog, object ) { <ide> <del> material.addEventListener( 'dispose', onMaterialDispose ); <del> <ide> var shaderID = shaderIDs[ material.type ]; <ide> <del> if ( shaderID ) { <del> <del> var shader = THREE.ShaderLib[ shaderID ]; <del> <del> material.__webglShader = { <del> uniforms: THREE.UniformsUtils.clone( shader.uniforms ), <del> vertexShader: shader.vertexShader, <del> fragmentShader: shader.fragmentShader <del> } <del> <del> } else { <del> <del> material.__webglShader = { <del> uniforms: material.uniforms, <del> vertexShader: material.vertexShader, <del> fragmentShader: material.fragmentShader <del> } <del> <del> } <del> <ide> // heuristics to create shader parameters according to lights in the scene <ide> // (not to blow over maxLights budget) <ide> <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> var code = chunks.join(); <ide> <add> if ( !material.program ) { <add> <add> // new material <add> material.addEventListener( 'dispose', onMaterialDispose ); <add> <add> } else if ( material.program.code !== code ) { <add> <add> // changed glsl or parameters <add> deallocateMaterial( material ); <add> <add> } else { <add> <add> // same glsl and parameters <add> return; <add> <add> } <add> <add> if ( shaderID ) { <add> <add> var shader = THREE.ShaderLib[ shaderID ]; <add> <add> material.__webglShader = { <add> uniforms: THREE.UniformsUtils.clone( shader.uniforms ), <add> vertexShader: shader.vertexShader, <add> fragmentShader: shader.fragmentShader <add> } <add> <add> } else { <add> <add> material.__webglShader = { <add> uniforms: material.uniforms, <add> vertexShader: material.vertexShader, <add> fragmentShader: material.fragmentShader <add> } <add> <add> } <add> <ide> var program; <ide> <ide> // Check if code has been already compiled <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> if ( material.needsUpdate ) { <ide> <del> if ( material.program ) deallocateMaterial( material ); <del> <ide> initMaterial( material, lights, fog, object ); <ide> material.needsUpdate = false; <ide>
1
PHP
PHP
fix extra parameters to action method
cc0bd4d8c8f86d4fb841d02d3a7a2106c4f037f9
<ide><path>src/Illuminate/Routing/UrlGenerator.php <ide> protected function toRoute($route, $parameters) <ide> <ide> $path = preg_replace_sub('/\{.*?\}/', $parameters, $route->uri()); <ide> <del> return $this->trimUrl($this->getRouteRoot($route, $domain), $path); <add> $query = count($parameters) > 0 ? '?'.http_build_query($parameters) : ''; <add> <add> return $this->trimUrl($this->getRouteRoot($route, $domain), $path.$query); <ide> } <ide> <ide> /** <ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> public function testBasicRouteGeneration() <ide> $routes->add($route); <ide> <ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->route('foo')); <del> $this->assertEquals('http://www.foo.com/foo/bar/taylor/breeze/otwell', $url->route('bar', array('taylor', 'otwell'))); <add> $this->assertEquals('http://www.foo.com/foo/bar/taylor/breeze/otwell?fly=wall', $url->route('bar', array('taylor', 'otwell', 'fly' => 'wall'))); <ide> $this->assertEquals('https://www.foo.com/foo/bar', $url->route('baz')); <ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->action('foo@bar')); <ide> }
2
Javascript
Javascript
run gc and dump stats if --expose-gc is set
4e84dfa6830336131a63993dcf2119b3edcb0f37
<ide><path>benchmark/http_simple_auto.js <ide> server.listen(port, function () { <ide> cp.stderr.pipe(process.stderr); <ide> cp.on('exit', function() { <ide> server.close(); <add> process.nextTick(dump_mm_stats); <ide> }); <ide> }); <add> <add>function dump_mm_stats() { <add> if (typeof gc != 'function') return; <add> <add> var before = process.memoryUsage(); <add> for (var i = 0; i < 10; ++i) gc(); <add> var after = process.memoryUsage(); <add> setTimeout(print_stats, 250); // give GC time to settle <add> <add> function print_stats() { <add> console.log('\nBEFORE / AFTER GC'); <add> ['rss', 'heapTotal', 'heapUsed'].forEach(function(key) { <add> var a = before[key] / (1024 * 1024); <add> var b = after[key] / (1024 * 1024); <add> console.log('%sM / %sM %s', a.toFixed(2), b.toFixed(2), key); <add> }); <add> } <add>}
1
Javascript
Javascript
add duration.add() and duration.subtract() methods
e9e6c4201768446406984613ca19d39c376007fc
<ide><path>moment.js <ide> return this.lang().postformat(output); <ide> }, <ide> <add> add : function (input, val) { <add> // supports only 2.0-style add(1, 's') or add(moment) <add> var dur = moment.duration(input, val); <add> <add> this._milliseconds += dur._milliseconds; <add> this._days += dur._days; <add> this._months += dur._months; <add> <add> return this; <add> }, <add> <add> subtract : function (input, val) { <add> var dur = moment.duration(input, val); <add> <add> this._milliseconds -= dur._milliseconds; <add> this._days -= dur._days; <add> this._months -= dur._months; <add> <add> return this; <add> }, <add> <ide> get : function (units) { <ide> units = normalizeUnits(units); <ide> return this[units.toLowerCase() + 's']();
1
Javascript
Javascript
correct @ngdoc annotations for methods of $q
9da8d63ef43d5b8e90a3b390c6449878fa2f92ea
<ide><path>src/ng/q.js <ide> function qFactory(nextTick, exceptionHandler) { <ide> } <ide> <ide> /** <del> * @ngdoc <add> * @ngdoc method <ide> * @name ng.$q#defer <del> * @methodOf ng.$q <add> * @kind function <add> * <ide> * @description <ide> * Creates a `Deferred` object which represents a task which will finish in the future. <ide> * <ide> function qFactory(nextTick, exceptionHandler) { <ide> }; <ide> <ide> /** <del> * @ngdoc <del> * @name ng.$q#reject <del> * @methodOf ng.$q <add> * @ngdoc method <add> * @name $q#reject <add> * @kind function <add> * <ide> * @description <ide> * Creates a promise that is resolved as rejected with the specified `reason`. This api should be <ide> * used to forward rejection in a chain of promises. If you are dealing with the last promise in <ide> function qFactory(nextTick, exceptionHandler) { <ide> }; <ide> <ide> /** <del> * @ngdoc <del> * @name ng.$q#when <del> * @methodOf ng.$q <add> * @ngdoc method <add> * @name $q#when <add> * @kind function <add> * <ide> * @description <ide> * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. <ide> * This is useful when you are dealing with an object that might or might not be a promise, or if <ide> function qFactory(nextTick, exceptionHandler) { <ide> }; <ide> <ide> /** <del> * @ngdoc <del> * @name ng.$q#all <del> * @methodOf ng.$q <add> * @ngdoc method <add> * @name $q#all <add> * @kind function <add> * <ide> * @description <ide> * Combines multiple promises into a single promise that is resolved when all of the input <ide> * promises are resolved.
1
Text
Text
fix incorrect markdown rendering
4a698c9c43804df1d6096e09ff682477efae3431
<ide><path>docs/extend/plugin_api.md <ide> Responds with a list of Docker subsystems which this plugin implements. <ide> After activation, the plugin will then be sent events from this subsystem. <ide> <ide> Possible values are: <del> - [`authz`](plugins_authorization.md) <del> - [`NetworkDriver`](plugins_network.md) <del> - [`VolumeDriver`](plugins_volume.md) <add> <add>* [`authz`](plugins_authorization.md) <add>* [`NetworkDriver`](plugins_network.md) <add>* [`VolumeDriver`](plugins_volume.md) <ide> <ide> <ide> ## Plugin retries
1
Text
Text
make less facebooky
ed98f2ca571fbf738d5ac9db2a3494a5b0d940b5
<ide><path>docs/docs/refactor/01-motivation.md <ide> React is all about building reusable components. In fact, with React the *only* <ide> <ide> ## Give it five minutes <ide> <del>React challenges a lot of conventional wisdom, and at first glance some of the ideas may seem crazy. We ask that you [give it five minutes](http://37signals.com/svn/posts/3124-give-it-five-minutes) while reading about React; we've built thousands of components with engineers and designers at Facebook and Instagram, and we hope you'll find it useful! <add>React challenges a lot of conventional wisdom, and at first glance some of the ideas may seem crazy. We ask that you [give it five minutes](http://37signals.com/svn/posts/3124-give-it-five-minutes) while reading about React; engineers and designers have built thousands of components both inside and outside of Facebook and Instagram, and we hope you'll find it useful!
1
Mixed
Javascript
add rectrounded point style
97f6c8f12d75981ace1df5662f544f0758653170
<ide><path>docs/03-Line-Chart.md <ide> pointHitRadius | `Number or Array<Number>` | The pixel size of the non-displayed <ide> pointHoverBackgroundColor | `Color or Array<Color>` | Point background color when hovered <ide> pointHoverBorderColor | `Color or Array<Color>` | Point border color when hovered <ide> pointHoverBorderWidth | `Number or Array<Number>` | Border width of point when hovered <del>pointStyle | `String, Array<String>, Image, Array<Image>` | The style of point. Options are 'circle', 'triangle', 'rect', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash'. If the option is an image, that image is drawn on the canvas using `drawImage`. <add>pointStyle | `String, Array<String>, Image, Array<Image>` | The style of point. Options are 'circle', 'triangle', 'rect', 'rectRounded', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash'. If the option is an image, that image is drawn on the canvas using `drawImage`. <ide> showLine | `Boolean` | If false, the line is not drawn for this dataset <ide> spanGaps | `Boolean` | If true, lines will be drawn between points with no or null data <ide> steppedLine | `Boolean` | If true, the line is shown as a stepped line and 'lineTension' will be ignored <ide><path>docs/05-Radar-Chart.md <ide> pointHitRadius | `Number or Array<Number>` | The pixel size of the non-displayed <ide> pointHoverBackgroundColor | `Color or Array<Color>` | Point background color when hovered <ide> pointHoverBorderColor | `Color or Array<Color>` | Point border color when hovered <ide> pointHoverBorderWidth | `Number or Array<Number>` | Border width of point when hovered <del>pointStyle | `String or Array<String>` | The style of point. Options include 'circle', 'triangle', 'rect', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash' <add>pointStyle | `String or Array<String>` | The style of point. Options include 'circle', 'triangle', 'rect', 'rectRounded', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash' <ide> <ide> An example data object using these attributes is shown below. <ide> <ide><path>src/core/core.canvasHelpers.js <ide> module.exports = function(Chart) { <ide> ctx.fillRect(x - size, y - size, 2 * size, 2 * size); <ide> ctx.strokeRect(x - size, y - size, 2 * size, 2 * size); <ide> break; <add> case 'rectRounded': <add> var offset = radius / Math.SQRT2; <add> var leftX = x - offset; <add> var topY = y - offset; <add> var sideSize = Math.SQRT2 * radius; <add> Chart.helpers.drawRoundedRectangle(ctx, leftX, topY, sideSize, sideSize, radius / 2); <add> ctx.fill(); <add> break; <ide> case 'rectRot': <ide> size = 1 / Math.SQRT2 * radius; <ide> ctx.beginPath(); <ide><path>test/element.point.tests.js <ide> describe('Point element tests', function() { <ide> args: [] <ide> }]); <ide> <add> var drawRoundedRectangleSpy = jasmine.createSpy('drawRoundedRectangle'); <add> var drawRoundedRectangle = Chart.helpers.drawRoundedRectangle; <add> var offset = point._view.radius / Math.SQRT2; <add> Chart.helpers.drawRoundedRectangle = drawRoundedRectangleSpy; <add> mockContext.resetCalls(); <add> point._view.pointStyle = 'rectRounded'; <add> point.draw(); <add> <add> expect(drawRoundedRectangleSpy).toHaveBeenCalledWith( <add> mockContext, <add> 10 - offset, <add> 15 - offset, <add> Math.SQRT2 * 2, <add> Math.SQRT2 * 2, <add> 2 / 2 <add> ); <add> expect(mockContext.getCalls()).toContain( <add> jasmine.objectContaining({ <add> name: 'fill', <add> args: [], <add> }) <add> ); <add> <add> Chart.helpers.drawRoundedRectangle = drawRoundedRectangle; <ide> mockContext.resetCalls(); <ide> point._view.pointStyle = 'rectRot'; <ide> point.draw();
4
Ruby
Ruby
remove bintray.version method
71c7781ecd673722b1fe8a9547cb57e9e6fb55a5
<ide><path>Library/Homebrew/bottles.rb <ide> def self.repository(tap=nil) <ide> return "bottles" if tap.to_s.empty? <ide> "bottles-#{tap.sub(/^homebrew\/(homebrew-)?/i, "")}" <ide> end <del> <del> def self.version(path) <del> BottleVersion.parse(path).to_s <del> end <ide> end <ide> <ide> class BottleCollector
1
Go
Go
fix the usage for `service rm` command
cf61cd3a920809f6a0be44a584f365544acaf1a9
<ide><path>api/client/service/remove.go <ide> import ( <ide> func newRemoveCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> <ide> cmd := &cobra.Command{ <del> Use: "rm [OPTIONS] SERVICE", <add> Use: "rm [OPTIONS] SERVICE [SERVICE...]", <ide> Aliases: []string{"remove"}, <ide> Short: "Remove a service", <ide> Args: cli.RequiresMinArgs(1),
1
Text
Text
update changelog for 2.11.2
75285e141cdf034bd270fc7973f6c93248531662
<ide><path>CHANGELOG.md <ide> Changelog <ide> ========= <ide> <add>### 2.11.2 (Fix ReDoS attack vector) <add> <add>* [#2939](https://github.com/moment/moment/pull/2939) use full-string match to speed up aspnet regex match <add> <ide> ### 2.11.1 [See full changelog](https://gist.github.com/ichernev/8ec3ee25b749b4cff3c2) <ide> <ide> ## Bugfixes:
1
Python
Python
maximize fmeasure as well when mode==auto
f6b804263a6e1d3ce6d2131cb9d758e1d7e57888
<ide><path>keras/callbacks.py <ide> def __init__(self, filepath, monitor='val_loss', verbose=0, <ide> self.monitor_op = np.greater <ide> self.best = -np.Inf <ide> else: <del> if 'acc' in self.monitor: <add> if self.monitor.startswith(('acc', 'fmeasure')): <ide> self.monitor_op = np.greater <ide> self.best = -np.Inf <ide> else: <ide> def __init__(self, monitor='val_loss', min_delta=0, patience=0, verbose=0, mode= <ide> elif mode == 'max': <ide> self.monitor_op = np.greater <ide> else: <del> if 'acc' in self.monitor: <add> if self.monitor.startswith(('acc', 'fmeasure')): <ide> self.monitor_op = np.greater <ide> else: <ide> self.monitor_op = np.less
1
Python
Python
improve output handling in evaluate
42eb381ec6107b68e7683d5d0244358b54a15aca
<ide><path>spacy/cli/evaluate.py <ide> from timeit import default_timer as timer <ide> from wasabi import Printer <ide> from pathlib import Path <add>import re <add>import srsly <ide> <ide> from ..gold import Corpus <ide> from ..tokens import Doc <ide> def evaluate_cli( <ide> # fmt: off <ide> model: str = Arg(..., help="Model name or path"), <ide> data_path: Path = Arg(..., help="Location of JSON-formatted evaluation data", exists=True), <add> output: Optional[Path] = Opt(None, "--output", "-o", help="Output JSON file for metrics", dir_okay=False), <ide> gpu_id: int = Opt(-1, "--gpu-id", "-g", help="Use GPU"), <ide> gold_preproc: bool = Opt(False, "--gold-preproc", "-G", help="Use gold preprocessing"), <ide> displacy_path: Optional[Path] = Opt(None, "--displacy-path", "-dp", help="Directory to output rendered parses as HTML", exists=True, file_okay=False), <ide> displacy_limit: int = Opt(25, "--displacy-limit", "-dl", help="Limit of parses to render as HTML"), <del> return_scores: bool = Opt(False, "--return-scores", "-R", help="Return dict containing model scores"), <del> <del> # fmt: on <add> # fmt: on <ide> ): <ide> """ <ide> Evaluate a model. To render a sample of parses in a HTML file, set an <ide> def evaluate_cli( <ide> evaluate( <ide> model, <ide> data_path, <add> output=output, <ide> gpu_id=gpu_id, <ide> gold_preproc=gold_preproc, <ide> displacy_path=displacy_path, <ide> displacy_limit=displacy_limit, <ide> silent=False, <del> return_scores=return_scores, <ide> ) <ide> <ide> <ide> def evaluate( <ide> model: str, <ide> data_path: Path, <add> output: Optional[Path], <ide> gpu_id: int = -1, <ide> gold_preproc: bool = False, <ide> displacy_path: Optional[Path] = None, <ide> displacy_limit: int = 25, <ide> silent: bool = True, <del> return_scores: bool = False, <ide> ) -> Scorer: <ide> msg = Printer(no_print=silent, pretty=not silent) <ide> util.fix_random_seed() <ide> if gpu_id >= 0: <ide> util.use_gpu(gpu_id) <ide> util.set_env_log(False) <ide> data_path = util.ensure_path(data_path) <add> output_path = util.ensure_path(output) <ide> displacy_path = util.ensure_path(displacy_path) <ide> if not data_path.exists(): <ide> msg.fail("Evaluation data not found", data_path, exits=1) <ide> def evaluate( <ide> ents=render_ents, <ide> ) <ide> msg.good(f"Generated {displacy_limit} parses as HTML", displacy_path) <del> if return_scores: <del> return scorer.scores <add> <add> data = {re.sub(r"[\s/]", "_", k.lower()): v for k, v in results.items()} <add> if output_path is not None: <add> srsly.write_json(output_path, data) <add> return data <ide> <ide> <ide> def render_parses(
1
Java
Java
remove timeout on tests
9b3a838c02b433ed8fbed014a5565fcb5b800891
<ide><path>rxjava-core/src/test/java/rx/schedulers/AbstractSchedulerConcurrencyTests.java <ide> public Subscription call(Scheduler innerScheduler, Long i) { <ide> assertEquals(10, counter.get()); <ide> } <ide> <del> @Test(timeout = 20000) <add> @Test <ide> public void recursionUsingFunc2() throws InterruptedException { <ide> final CountDownLatch latch = new CountDownLatch(1); <ide> getScheduler().schedule(1L, new Func2<Scheduler, Long, Subscription>() { <ide> public Subscription call(Scheduler innerScheduler, Long i) { <ide> latch.await(); <ide> } <ide> <del> @Test(timeout = 20000) <add> @Test <ide> public void recursionUsingAction0() throws InterruptedException { <ide> final CountDownLatch latch = new CountDownLatch(1); <ide> getScheduler().schedule(new Action1<Action0>() {
1
Python
Python
add ipv6 support
44b27d9787e123e124c0984602273bc6ab64b933
<ide><path>glances/glances.py <ide> def update(self, stats): <ide> self.__cvsfile_fd.flush() <ide> <ide> <del>class GlancesHandler(SimpleXMLRPCRequestHandler): <add>class GlancesXMLRPCHandler(SimpleXMLRPCRequestHandler): <ide> """ <ide> Main XMLRPC handler <ide> """ <ide> def log_message(self, format, *args): <ide> pass <ide> <ide> <add>class GlancesXMLRPCServer(SimpleXMLRPCServer): <add> """ <add> Init a SimpleXMLRPCServer instance (IPv6-ready) <add> """ <add> def __init__(self, bind_address, bind_port=61209, <add> requestHandler=GlancesXMLRPCHandler): <add> <add> try: <add> self.address_family = socket.getaddrinfo(bind_address, bind_port)[0][0] <add> except socket.error as e: <add> print(_("Couldn't open socket: %s") % e) <add> sys.exit(1) <add> <add> SimpleXMLRPCServer.__init__(self, (bind_address, bind_port), <add> requestHandler) <add> <add> <ide> class GlancesInstance(): <ide> """ <ide> All the methods of this class are published as XML RPC methods <ide> class GlancesServer(): <ide> """ <ide> This class creates and manages the TCP client <ide> """ <del> <ide> def __init__(self, bind_address, bind_port=61209, <del> RequestHandler=GlancesHandler, cached_time=1): <del> self.server = SimpleXMLRPCServer((bind_address, bind_port), <del> requestHandler=RequestHandler) <add> requestHandler=GlancesXMLRPCHandler, cached_time=1): <add> self.server = GlancesXMLRPCServer(bind_address, bind_port, <add> requestHandler) <add> <ide> # The users dict <ide> # username / MD5 password couple <ide> # By default, no auth is needed <ide> def main(): <ide> if server_tag: <ide> # Init the server <ide> print(_("Glances server is running on") + " %s:%s" % (bind_ip, server_port)) <del> server = GlancesServer(bind_ip, int(server_port), GlancesHandler, cached_time) <add> server = GlancesServer(bind_ip, int(server_port), GlancesXMLRPCHandler, cached_time) <ide> <ide> # Set the server login/password (if -P tag) <ide> if password != "":
1
Javascript
Javascript
remove redundant helper and guide code from header
67d49efd1ee825bb5afa090a52ee4ac69f5ff265
<ide><path>client/src/components/Header/index.js <ide> import { Link } from '../helpers'; <ide> import './header.css'; <ide> <ide> const propTypes = { <del> disableSettings: PropTypes.bool, <del> navigationMenu: PropTypes.element <add> disableSettings: PropTypes.bool <ide> }; <ide> <ide> function Header(props) { <del> const { disableSettings, navigationMenu } = props; <add> const { disableSettings } = props; <ide> return ( <ide> <header> <ide> <nav id='top-nav'> <ide> <Link className='home-link' to='/'> <ide> <NavLogo /> <ide> </Link> <ide> {disableSettings ? null : <SearchBar />} <del> {navigationMenu ? ( <del> navigationMenu <del> ) : ( <del> <NavigationMenu disableSettings={disableSettings} /> <del> )} <add> <NavigationMenu disableSettings={disableSettings} /> <ide> </nav> <ide> </header> <ide> ); <ide><path>client/src/components/layouts/Default.js <ide> const propTypes = { <ide> isOnline: PropTypes.bool.isRequired, <ide> isSignedIn: PropTypes.bool, <ide> landingPage: PropTypes.bool, <del> navigationMenu: PropTypes.element, <ide> onlineStatusChange: PropTypes.func.isRequired, <ide> pathname: PropTypes.string.isRequired, <ide> removeFlashMessage: PropTypes.func.isRequired, <ide> class DefaultLayout extends Component { <ide> isOnline, <ide> isSignedIn, <ide> landingPage, <del> navigationMenu, <ide> removeFlashMessage, <ide> showFooter = true <ide> } = this.props; <ide> class DefaultLayout extends Component { <ide> <style>{fontawesome.dom.css()}</style> <ide> </Helmet> <ide> <WithInstantSearch> <del> <Header <del> disableSettings={landingPage} <del> navigationMenu={navigationMenu} <del> /> <add> <Header disableSettings={landingPage} /> <ide> <div <ide> className={`default-layout ${landingPage ? 'landing-page' : ''}`} <ide> > <ide><path>client/utils/getGithubPath.js <del>exports.getGithubPath = function getGithubPath(fileAbsolutePath) { <del> const { NODE_ENV: env } = process.env; <del> const guideType = env === 'production' ? 'guide' : 'mock-guide'; <del> let githubFilePath = <del> 'https://github.com/freeCodeCamp/freeCodeCamp/blob/master/CONTRIBUTING.md#research-write-and-update-our-guide-articles'; <del> const pathIndex = fileAbsolutePath.indexOf(`/${guideType}`); <del> if (pathIndex > -1) { <del> const newPath = fileAbsolutePath.slice(pathIndex); <del> githubFilePath = `https://github.com/freeCodeCamp/freeCodeCamp/blob/master${newPath}`; <del> } <del> return githubFilePath; <del>};
3
Javascript
Javascript
add unstable args test
0f6afed29de363bfe755dd229e6ce43d7aed1051
<ide><path>packages/@ember/-internals/glimmer/tests/integration/components/tracked-test.js <del>import { EMBER_METAL_TRACKED_PROPERTIES } from '@ember/canary-features'; <ide> import { Object as EmberObject, A } from '@ember/-internals/runtime'; <add>import { <add> EMBER_CUSTOM_COMPONENT_ARG_PROXY, <add> EMBER_METAL_TRACKED_PROPERTIES, <add>} from '@ember/canary-features'; <add>import { Object as EmberObject } from '@ember/-internals/runtime'; <ide> import { tracked, nativeDescDecorator as descriptor } from '@ember/-internals/metal'; <ide> import { moduleFor, RenderingTestCase, strip, runTask } from 'internal-test-helpers'; <ide> import GlimmerishComponent from '../../utils/glimmerish-component'; <ide> if (EMBER_METAL_TRACKED_PROPERTIES) { <ide> } <ide> } <ide> ); <add> <add> if (EMBER_CUSTOM_COMPONENT_ARG_PROXY) { <add> moduleFor( <add> 'Component Tracked Properties w/ Args Proxy', <add> class extends RenderingTestCase { <add> '@test downstream property changes do not invalidate upstream component getters/arguments'( <add> assert <add> ) { <add> let outerRenderCount = 0; <add> let innerRenderCount = 0; <add> <add> class OuterComponent extends GlimmerishComponent { <add> get count() { <add> outerRenderCount++; <add> return this.args.count; <add> } <add> } <add> <add> class InnerComponent extends GlimmerishComponent { <add> @tracked count = 0; <add> <add> get combinedCounts() { <add> innerRenderCount++; <add> return this.args.count + this.count; <add> } <add> <add> updateInnerCount() { <add> this.count++; <add> } <add> } <add> <add> this.registerComponent('outer', { <add> ComponentClass: OuterComponent, <add> template: '<Inner @count={{this.count}}/>', <add> }); <add> <add> this.registerComponent('inner', { <add> ComponentClass: InnerComponent, <add> template: '<button {{action this.updateInnerCount}}>{{this.combinedCounts}}</button>', <add> }); <add> <add> this.render('<Outer @count={{this.count}}/>', { <add> count: 0, <add> }); <add> <add> this.assertText('0'); <add> <add> assert.equal(outerRenderCount, 1); <add> assert.equal(innerRenderCount, 1); <add> <add> runTask(() => this.$('button').click()); <add> <add> this.assertText('1'); <add> <add> assert.equal( <add> outerRenderCount, <add> 1, <add> 'updating inner component does not cause outer component to rerender' <add> ); <add> assert.equal( <add> innerRenderCount, <add> 2, <add> 'updating inner component causes inner component to rerender' <add> ); <add> <add> runTask(() => this.context.set('count', 1)); <add> <add> this.assertText('2'); <add> <add> assert.equal(outerRenderCount, 2, 'outer component updates based on context'); <add> assert.equal(innerRenderCount, 3, 'inner component updates based on outer component'); <add> } <add> } <add> ); <add> } <ide> }
1
Javascript
Javascript
add support for regex in yellowbox warnings
50fc666aad1e83d5728b09646c3a5fbbecaddfb9
<ide><path>Libraries/YellowBox/Data/YellowBoxRegistry.js <ide> export type Registry = Map<Category, $ReadOnlyArray<YellowBoxWarning>>; <ide> <ide> export type Observer = (registry: Registry) => void; <ide> <add>type IgnorePattern = string | RegExp; <add> <ide> export type Subscription = $ReadOnly<{| <ide> unsubscribe: () => void, <ide> |}>; <ide> <ide> const observers: Set<{observer: Observer}> = new Set(); <del>const ignorePatterns: Set<string> = new Set(); <add>const ignorePatterns: Set<IgnorePattern> = new Set(); <ide> const registry: Registry = new Map(); <ide> <ide> let disabled = false; <ide> let updateTimeout = null; <ide> <ide> function isWarningIgnored(warning: YellowBoxWarning): boolean { <ide> for (const pattern of ignorePatterns) { <del> if (warning.message.content.includes(pattern)) { <add> if (pattern instanceof RegExp && pattern.test(warning.message.content)) { <add> return true; <add> } else if ( <add> typeof pattern === 'string' && <add> warning.message.content.includes(pattern) <add> ) { <ide> return true; <ide> } <ide> } <ide> const YellowBoxRegistry = { <ide> } <ide> }, <ide> <del> addIgnorePatterns(patterns: $ReadOnlyArray<string>): void { <del> const newPatterns = patterns.filter( <del> pattern => !ignorePatterns.has(pattern), <del> ); <add> addIgnorePatterns(patterns: $ReadOnlyArray<IgnorePattern>): void { <add> const newPatterns = patterns.filter((pattern: IgnorePattern) => { <add> if (pattern instanceof RegExp) { <add> for (const existingPattern of ignorePatterns.entries()) { <add> if ( <add> existingPattern instanceof RegExp && <add> existingPattern.toString() === pattern.toString() <add> ) { <add> return false; <add> } <add> } <add> return true; <add> } <add> return !ignorePatterns.has(pattern); <add> }); <ide> if (newPatterns.length === 0) { <ide> return; <ide> } <ide><path>Libraries/YellowBox/Data/__tests__/YellowBoxRegistry-test.js <ide> describe('YellowBoxRegistry', () => { <ide> expect(registry().size).toBe(0); <ide> }); <ide> <add> it('ignores warnings matching regexs or pattern', () => { <add> YellowBoxRegistry.add({args: ['There are 4 dogs'], framesToPop: 0}); <add> YellowBoxRegistry.add({args: ['There are 3 cats'], framesToPop: 0}); <add> YellowBoxRegistry.add({args: ['There are H cats'], framesToPop: 0}); <add> expect(registry().size).toBe(3); <add> <add> YellowBoxRegistry.addIgnorePatterns(['dogs']); <add> expect(registry().size).toBe(2); <add> <add> YellowBoxRegistry.addIgnorePatterns([/There are \d+ cats/]); <add> expect(registry().size).toBe(1); <add> <add> YellowBoxRegistry.addIgnorePatterns(['cats']); <add> expect(registry().size).toBe(0); <add> }); <add> <ide> it('ignores all warnings when disabled', () => { <ide> YellowBoxRegistry.add({args: ['A!'], framesToPop: 0}); <ide> YellowBoxRegistry.add({args: ['B?'], framesToPop: 0});
2
PHP
PHP
write the compiled file to the storage directory
3812a6f80ef79bc87a5b42d5c0728333bb5085ba
<ide><path>src/Illuminate/Foundation/Console/ClearCompiledCommand.php <ide> class ClearCompiledCommand extends Command { <ide> */ <ide> public function fire() <ide> { <del> if (file_exists($path = $this->laravel['path.base'].'/bootstrap/compiled.php')) <add> if (file_exists($path = $this->laravel['path.storage'].'/meta/compiled.php')) <ide> { <ide> @unlink($path); <ide> } <ide><path>src/Illuminate/Foundation/Console/OptimizeCommand.php <ide> protected function compileClasses() <ide> { <ide> $this->registerClassPreloaderCommand(); <ide> <del> $outputPath = $this->laravel['path.base'].'/bootstrap/compiled.php'; <add> $outputPath = $this->laravel['path.storage'].'/meta/compiled.php'; <ide> <ide> $this->callSilent('compile', array( <ide> '--config' => implode(',', $this->getClassFiles()),
2
Javascript
Javascript
add version to glslang
ca306c07511a63a257d07f505e6a0a7ef4dbc5a6
<ide><path>examples/jsm/libs/glslang.js <del> <add>// 0.0.15 <ide> var Module = (function() { <ide> var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; <del> <add> <ide> return ( <ide> function(Module) { <ide> Module = Module || {};
1
Text
Text
fix navigation links in documentation
2f2c3ea2547c9a76a0452c1a75d7514032ff2dee
<ide><path>docs/ComponentsAndAPIs.md <ide> --- <del>id: components <add>id: components-and-apis <ide> title: Components and APIs <ide> layout: docs <ide> category: Guides <ide><path>docs/MoreResources.md <ide> title: More Resources <ide> layout: docs <ide> category: The Basics <ide> permalink: docs/more-resources.html <del>next: components <add>next: components-and-apis <ide> previous: network <ide> --- <ide> <ide><path>docs/PlatformSpecificInformation.md <ide> layout: docs <ide> category: Guides <ide> permalink: docs/platform-specific-code.html <ide> next: navigation <del>previous: components <add>previous: components-and-apis <ide> --- <ide> <ide> When building a cross-platform app, you'll want to re-use as much code as possible. Scenarios may arise where it makes sense for the code to be different, for example you may want to implement separate visual components for iOS and Android.
3
Javascript
Javascript
upgrade flow definition in rn + metro
f8b4850425f115c8a23dead7ec0716b61663aed6
<ide><path>flow/jest.js <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <ide> * <del> * Modified from https://raw.githubusercontent.com/flowtype/flow-typed/e3b0f3034929e0f0fb85c790450a201b380ac2fd/definitions/npm/jest_v17.x.x/flow_v0.33.x-/jest_v17.x.x.js <add> * Modified from https://raw.githubusercontent.com/flowtype/flow-typed/b43dff3e0ed5ccf7033839045f4819e8db40faa9/definitions/npm/jest_v20.x.x/flow_v0.22.x-/jest_v20.x.x.js <ide> * Duplicated from www/flow/shared/jest.js <add> * List of modifications: <add> * - added function fail <add> * - added jest.requireActual <add> * - added jest.requireMock <add> * - added JestMockFn.mockName <add> * - added JestMockFn.mockRejectedValue <add> * - added JestMockFn.mockRejectedValueOnce <add> * - added JestMockFn.mockResolvedValue <add> * - added JestMockFn.mockResolvedValueOnce <add> * - added JestMockFn.mock.thrownErrors <add> * - added JestMockFn.mock.returnValues <add> * - added jest.setTimeout <ide> * @flow <ide> * @format <ide> */ <ide> <del>'use strict'; <add>/* eslint-disable lint/no-unclear-flowtypes */ <ide> <del>type JestMockFn = { <del> (...args: Array<any>): any, <add>type JestMockFn<TArguments: $ReadOnlyArray<*>, TReturn> = { <add> (...args: TArguments): TReturn, <add> /** <add> * An object for introspecting mock calls <add> */ <ide> mock: { <del> calls: Array<Array<any>>, <del> instances: mixed, <add> /** <add> * An array that represents all calls that have been made into this mock <add> * function. Each call is represented by an array of arguments that were <add> * passed during the call. <add> */ <add> calls: Array<TArguments>, <add> /** <add> * An array that contains all the object instances that have been <add> * instantiated from this mock function. <add> */ <add> instances: Array<TReturn>, <add> /** <add> * An array containing the results of a method, and whether they were <add> * returned or thrown. <add> */ <add> results: Array<{isThrown: boolean}>, <ide> }, <del> mockClear(): Function, <del> mockReset(): Function, <del> mockImplementation(fn: Function): JestMockFn, <del> mockImplementationOnce(fn: Function): JestMockFn, <add> /** <add> * Resets all information stored in the mockFn.mock.calls and <add> * mockFn.mock.instances arrays. Often this is useful when you want to clean <add> * up a mock's usage data between two assertions. <add> */ <add> mockClear(): void, <add> /** <add> * Resets all information stored in the mock. This is useful when you want to <add> * completely restore a mock back to its initial state. <add> */ <add> mockReset(): void, <add> /** <add> * Removes the mock and restores the initial implementation. This is useful <add> * when you want to mock functions in certain test cases and restore the <add> * original implementation in others. Beware that mockFn.mockRestore only <add> * works when mock was created with jest.spyOn. Thus you have to take care of <add> * restoration yourself when manually assigning jest.fn(). <add> */ <add> mockRestore(): void, <add> /** <add> * Accepts a function that should be used as the implementation of the mock. <add> * The mock itself will still record all calls that go into and instances <add> * that come from itself -- the only difference is that the implementation <add> * will also be executed when the mock is called. <add> */ <add> mockImplementation( <add> fn: (...args: TArguments) => TReturn, <add> ): JestMockFn<TArguments, TReturn>, <add> /** <add> * Accepts a function that will be used as an implementation of the mock for <add> * one call to the mocked function. Can be chained so that multiple function <add> * calls produce different results. <add> */ <add> mockImplementationOnce( <add> fn: (...args: TArguments) => TReturn, <add> ): JestMockFn<TArguments, TReturn>, <add> /** <add> * Accepts a string to use in test result output in place of "jest.fn()" to <add> * indicate which mock function is being referenced. <add> */ <add> mockName(name: string): JestMockFn<TArguments, TReturn>, <add> /** <add> * Sugar for: jest.fn().mockReturnValue(Promise.reject(value)); <add> */ <add> mockRejectedValue(value: TReturn): JestMockFn<TArguments, TReturn>, <add> /** <add> * Sugar for: jest.fn().mockReturnValueOnce(Promise.reject(value)); <add> */ <add> mockRejectedValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>, <add> /** <add> * Sugar for: jest.fn().mockReturnValue(Promise.resolve(value)); <add> */ <add> mockResolvedValue(value: TReturn): JestMockFn<TArguments, TReturn>, <add> /** <add> * Sugar for: jest.fn().mockReturnValueOnce(Promise.resolve(value)); <add> */ <add> mockResolvedValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>, <add> /** <add> * Just a simple sugar function for returning `this` <add> */ <ide> mockReturnThis(): void, <del> mockReturnValue(value: any): JestMockFn, <del> mockReturnValueOnce(value: any): JestMockFn, <add> /** <add> * Deprecated: use jest.fn(() => value) instead <add> */ <add> mockReturnValue(value: TReturn): JestMockFn<TArguments, TReturn>, <add> /** <add> * Sugar for only returning a value once inside your mock <add> */ <add> mockReturnValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>, <ide> }; <ide> <ide> type JestAsymmetricEqualityType = { <add> /** <add> * A custom Jasmine equality tester <add> */ <ide> asymmetricMatch(value: mixed): boolean, <ide> }; <ide> <ide> type JestCallsType = { <ide> type JestClockType = { <ide> install(): void, <ide> mockDate(date: Date): void, <del> tick(): void, <add> tick(milliseconds?: number): void, <ide> uninstall(): void, <ide> }; <ide> <ide> type JestPromiseType = { <ide> resolves: JestExpectType, <ide> }; <ide> <add>/** <add> * Plugin: jest-enzyme <add> */ <add>type EnzymeMatchersType = { <add> toBeChecked(): void, <add> toBeDisabled(): void, <add> toBeEmpty(): void, <add> toBePresent(): void, <add> toContainReact(element: React$Element<any>): void, <add> toHaveClassName(className: string): void, <add> toHaveHTML(html: string): void, <add> toHaveProp(propKey: string, propValue?: any): void, <add> toHaveRef(refName: string): void, <add> toHaveState(stateKey: string, stateValue?: any): void, <add> toHaveStyle(styleKey: string, styleValue?: any): void, <add> toHaveTagName(tagName: string): void, <add> toHaveText(text: string): void, <add> toIncludeText(text: string): void, <add> toHaveValue(value: any): void, <add> toMatchElement(element: React$Element<any>): void, <add> toMatchSelector(selector: string): void, <add>}; <add> <ide> type JestExpectType = { <del> not: JestExpectType, <add> not: JestExpectType & EnzymeMatchersType, <add> /** <add> * If you have a mock function, you can use .lastCalledWith to test what <add> * arguments it was last called with. <add> */ <ide> lastCalledWith(...args: Array<any>): void, <add> /** <add> * toBe just checks that a value is what you expect. It uses === to check <add> * strict equality. <add> */ <ide> toBe(value: any): void, <add> /** <add> * Use .toHaveBeenCalled to ensure that a mock function got called. <add> */ <ide> toBeCalled(): void, <add> /** <add> * Use .toBeCalledWith to ensure that a mock function was called with <add> * specific arguments. <add> */ <ide> toBeCalledWith(...args: Array<any>): void, <add> /** <add> * Using exact equality with floating point numbers is a bad idea. Rounding <add> * means that intuitive things fail. <add> */ <ide> toBeCloseTo(num: number, delta: any): void, <add> /** <add> * Use .toBeDefined to check that a variable is not undefined. <add> */ <ide> toBeDefined(): void, <add> /** <add> * Use .toBeFalsy when you don't care what a value is, you just want to <add> * ensure a value is false in a boolean context. <add> */ <ide> toBeFalsy(): void, <add> /** <add> * To compare floating point numbers, you can use toBeGreaterThan. <add> */ <ide> toBeGreaterThan(number: number): void, <add> /** <add> * To compare floating point numbers, you can use toBeGreaterThanOrEqual. <add> */ <ide> toBeGreaterThanOrEqual(number: number): void, <add> /** <add> * To compare floating point numbers, you can use toBeLessThan. <add> */ <ide> toBeLessThan(number: number): void, <add> /** <add> * To compare floating point numbers, you can use toBeLessThanOrEqual. <add> */ <ide> toBeLessThanOrEqual(number: number): void, <add> /** <add> * Use .toBeInstanceOf(Class) to check that an object is an instance of a <add> * class. <add> */ <ide> toBeInstanceOf(cls: Class<*>): void, <add> /** <add> * .toBeNull() is the same as .toBe(null) but the error messages are a bit <add> * nicer. <add> */ <ide> toBeNull(): void, <add> /** <add> * Use .toBeTruthy when you don't care what a value is, you just want to <add> * ensure a value is true in a boolean context. <add> */ <ide> toBeTruthy(): void, <add> /** <add> * Use .toBeUndefined to check that a variable is undefined. <add> */ <ide> toBeUndefined(): void, <add> /** <add> * Use .toContain when you want to check that an item is in a list. For <add> * testing the items in the list, this uses ===, a strict equality check. <add> */ <ide> toContain(item: any): void, <add> /** <add> * Use .toContainEqual when you want to check that an item is in a list. For <add> * testing the items in the list, this matcher recursively checks the <add> * equality of all fields, rather than checking for object identity. <add> */ <ide> toContainEqual(item: any): void, <add> /** <add> * Use .toEqual when you want to check that two objects have the same value. <add> * This matcher recursively checks the equality of all fields, rather than <add> * checking for object identity. <add> */ <ide> toEqual(value: any): void, <add> /** <add> * Use .toHaveBeenCalled to ensure that a mock function got called. <add> */ <ide> toHaveBeenCalled(): void, <add> /** <add> * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact <add> * number of times. <add> */ <ide> toHaveBeenCalledTimes(number: number): void, <add> /** <add> * Use .toHaveBeenCalledWith to ensure that a mock function was called with <add> * specific arguments. <add> */ <ide> toHaveBeenCalledWith(...args: Array<any>): void, <del> toHaveProperty(path: string, value?: any): void, <del> toMatch(regexp: RegExp): void, <add> /** <add> * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called <add> * with specific arguments. <add> */ <add> toHaveBeenLastCalledWith(...args: Array<any>): void, <add> /** <add> * Check that an object has a .length property and it is set to a certain <add> * numeric value. <add> */ <add> toHaveLength(number: number): void, <add> /** <add> * <add> */ <add> toHaveProperty(propPath: string, value?: any): void, <add> /** <add> * Use .toMatch to check that a string matches a regular expression or string. <add> */ <add> toMatch(regexpOrString: RegExp | string): void, <add> /** <add> * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object. <add> */ <ide> toMatchObject(object: Object): void, <del> toMatchSnapshot(): void, <del> toThrow(message?: string | Error | Class<Error>): void, <del> toThrowError(message?: string | Error | Class<Error> | RegExp): void, <add> /** <add> * This ensures that a React component matches the most recent snapshot. <add> */ <add> toMatchSnapshot(name?: string): void, <add> /** <add> * Use .toThrow to test that a function throws when it is called. <add> * If you want to test that a specific error gets thrown, you can provide an <add> * argument to toThrow. The argument can be a string for the error message, <add> * a class for the error, or a regex that should match the error. <add> * <add> * Alias: .toThrowError <add> */ <add> toThrow(message?: string | Error | RegExp): void, <add> toThrowError(message?: string | Error | RegExp): void, <add> /** <add> * Use .toThrowErrorMatchingSnapshot to test that a function throws a error <add> * matching the most recent snapshot when it is called. <add> */ <ide> toThrowErrorMatchingSnapshot(): void, <ide> }; <ide> <add>type JestObjectType = { <add> /** <add> * Disables automatic mocking in the module loader. <add> * <add> * After this method is called, all `require()`s will return the real <add> * versions of each module (rather than a mocked version). <add> */ <add> disableAutomock(): JestObjectType, <add> /** <add> * An un-hoisted version of disableAutomock <add> */ <add> autoMockOff(): JestObjectType, <add> /** <add> * Enables automatic mocking in the module loader. <add> */ <add> enableAutomock(): JestObjectType, <add> /** <add> * An un-hoisted version of enableAutomock <add> */ <add> autoMockOn(): JestObjectType, <add> /** <add> * Clears the mock.calls and mock.instances properties of all mocks. <add> * Equivalent to calling .mockClear() on every mocked function. <add> */ <add> clearAllMocks(): JestObjectType, <add> /** <add> * Resets the state of all mocks. Equivalent to calling .mockReset() on every <add> * mocked function. <add> */ <add> resetAllMocks(): JestObjectType, <add> /** <add> * Restores all mocks back to their original value. <add> */ <add> restoreAllMocks(): JestObjectType, <add> /** <add> * Removes any pending timers from the timer system. <add> */ <add> clearAllTimers(): void, <add> /** <add> * The same as `mock` but not moved to the top of the expectation by <add> * babel-jest. <add> */ <add> doMock(moduleName: string, moduleFactory?: any): JestObjectType, <add> /** <add> * The same as `unmock` but not moved to the top of the expectation by <add> * babel-jest. <add> */ <add> dontMock(moduleName: string): JestObjectType, <add> /** <add> * Returns a new, unused mock function. Optionally takes a mock <add> * implementation. <add> */ <add> fn<TArguments: $ReadOnlyArray<*>, TReturn>( <add> implementation?: (...args: TArguments) => TReturn, <add> ): JestMockFn<TArguments, TReturn>, <add> /** <add> * Determines if the given function is a mocked function. <add> */ <add> isMockFunction(fn: Function): boolean, <add> /** <add> * Given the name of a module, use the automatic mocking system to generate a <add> * mocked version of the module for you. <add> */ <add> genMockFromModule(moduleName: string): any, <add> /** <add> * Mocks a module with an auto-mocked version when it is being required. <add> * <add> * The second argument can be used to specify an explicit module factory that <add> * is being run instead of using Jest's automocking feature. <add> * <add> * The third argument can be used to create virtual mocks -- mocks of modules <add> * that don't exist anywhere in the system. <add> */ <add> mock( <add> moduleName: string, <add> moduleFactory?: any, <add> options?: Object, <add> ): JestObjectType, <add> /** <add> * Resets the module registry - the cache of all required modules. This is <add> * useful to isolate modules where local state might conflict between tests. <add> */ <add> resetModules(): JestObjectType, <add> /** <add> * Exhausts the micro-task queue (usually interfaced in node via <add> * process.nextTick). <add> */ <add> runAllTicks(): void, <add> /** <add> * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(), <add> * setInterval(), and setImmediate()). <add> */ <add> runAllTimers(): void, <add> /** <add> * Exhausts all tasks queued by setImmediate(). <add> */ <add> runAllImmediates(): void, <add> /** <add> * Executes only the macro task queue (i.e. all tasks queued by setTimeout() <add> * or setInterval() and setImmediate()). <add> */ <add> advanceTimersByTime(msToRun: number): void, <add> /** <add> * Executes only the macro task queue (i.e. all tasks queued by setTimeout() <add> * or setInterval() and setImmediate()). <add> * <add> * Renamed to `advanceTimersByTime`. <add> */ <add> runTimersToTime(msToRun: number): void, <add> /** <add> * Executes only the macro-tasks that are currently pending (i.e., only the <add> * tasks that have been queued by setTimeout() or setInterval() up to this <add> * point) <add> */ <add> runOnlyPendingTimers(): void, <add> /** <add> * Explicitly supplies the mock object that the module system should return <add> * for the specified module. Note: It is recommended to use jest.mock() <add> * instead. <add> */ <add> setMock(moduleName: string, moduleExports: any): JestObjectType, <add> /** <add> * Indicates that the module system should never return a mocked version of <add> * the specified module from require() (e.g. that it should always return the <add> * real module). <add> */ <add> unmock(moduleName: string): JestObjectType, <add> /** <add> * Instructs Jest to use fake versions of the standard timer functions <add> * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, <add> * setImmediate and clearImmediate). <add> */ <add> useFakeTimers(): JestObjectType, <add> /** <add> * Instructs Jest to use the real versions of the standard timer functions. <add> */ <add> useRealTimers(): JestObjectType, <add> /** <add> * Creates a mock function similar to jest.fn but also tracks calls to <add> * object[methodName]. <add> */ <add> spyOn(object: Object, methodName: string): JestMockFn<any, any>, <add> /** <add> * Set the default timeout interval for tests and before/after hooks in milliseconds. <add> * Note: The default timeout interval is 5 seconds if this method is not called. <add> */ <add> setTimeout(timeout: number): JestObjectType, <add> <add> // These methods are added separately and not a part of flow-typed OSS <add> // version of this file. They were added in jest@21.0.0.alpha-2 which is not <add> // yet publicly released yet. <add> // TODO T21262347 Add them to OSS version of flow-typed <add> requireActual(module: string): any, <add> requireMock(module: string): any, <add>}; <add> <ide> type JestSpyType = { <ide> calls: JestCallsType, <ide> }; <ide> <del>declare function afterEach(fn: Function): void; <del>declare function beforeEach(fn: Function): void; <del>declare function afterAll(fn: Function): void; <del>declare function beforeAll(fn: Function): void; <del>declare function describe(name: string, fn: Function): void; <add>/** Runs this function after every test inside this context */ <add>declare function afterEach( <add> fn: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add>): void; <add>/** Runs this function before every test inside this context */ <add>declare function beforeEach( <add> fn: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add>): void; <add>/** Runs this function after all tests have finished inside this context */ <add>declare function afterAll( <add> fn: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add>): void; <add>/** Runs this function before any tests have started inside this context */ <add>declare function beforeAll( <add> fn: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add>): void; <add> <add>/** A context for grouping tests together */ <add>declare var describe: { <add> /** <add> * Creates a block that groups together several related tests in one "test suite" <add> */ <add> (name: string, fn: () => void): void, <add> <add> /** <add> * Only run this describe block <add> */ <add> only(name: string, fn: () => void): void, <add> <add> /** <add> * Skip running this describe block <add> */ <add> skip(name: string, fn: () => void): void, <add>}; <add> <add>/** An individual test unit */ <ide> declare var it: { <del> (name: string, fn: Function): ?Promise<void>, <del> only(name: string, fn: Function): ?Promise<void>, <del> skip(name: string, fn: Function): ?Promise<void>, <add> /** <add> * An individual test unit <add> * <add> * @param {string} Name of Test <add> * @param {Function} Test <add> * @param {number} Timeout for the test, in milliseconds. <add> */ <add> ( <add> name: string, <add> fn?: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add> ): void, <add> /** <add> * Only run this test <add> * <add> * @param {string} Name of Test <add> * @param {Function} Test <add> * @param {number} Timeout for the test, in milliseconds. <add> */ <add> only( <add> name: string, <add> fn?: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add> ): void, <add> /** <add> * Skip running this test <add> * <add> * @param {string} Name of Test <add> * @param {Function} Test <add> * @param {number} Timeout for the test, in milliseconds. <add> */ <add> skip( <add> name: string, <add> fn?: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add> ): void, <add> /** <add> * Run the test concurrently <add> * <add> * @param {string} Name of Test <add> * @param {Function} Test <add> * @param {number} Timeout for the test, in milliseconds. <add> */ <add> concurrent( <add> name: string, <add> fn?: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add> ): void, <ide> }; <del>declare function fit(name: string, fn: Function): ?Promise<void>; <del>declare function pit(name: string, fn: () => Promise<any>): Promise<void>; <add>declare function fit( <add> name: string, <add> fn: (done: () => void) => ?Promise<mixed>, <add> timeout?: number, <add>): void; <add>/** An individual test unit */ <ide> declare var test: typeof it; <add>/** A disabled group of tests */ <ide> declare var xdescribe: typeof describe; <add>/** A focused group of tests */ <ide> declare var fdescribe: typeof describe; <add>/** A disabled individual test */ <ide> declare var xit: typeof it; <add>/** A disabled individual test */ <ide> declare var xtest: typeof it; <ide> <add>/** The expect function is used every time you want to test a value */ <ide> declare var expect: { <del> (value: any): JestExpectType & JestPromiseType, <del> any: any, <add> /** The object that you want to make assertions against */ <add> (value: any): JestExpectType & JestPromiseType & EnzymeMatchersType, <add> /** Add additional Jasmine matchers to Jest's roster */ <ide> extend(matchers: {[name: string]: JestMatcher}): void, <del> objectContaining(any): void, <add> /** Add a module that formats application-specific data structures. */ <add> addSnapshotSerializer(serializer: (input: Object) => string): void, <add> assertions(expectedAssertions: number): void, <add> hasAssertions(): void, <add> any(value: mixed): JestAsymmetricEqualityType, <add> anything(): void, <add> arrayContaining(value: Array<mixed>): void, <add> objectContaining(value: Object): void, <add> /** Matches any received string that contains the exact expected string. */ <add> stringContaining(value: string): void, <add> stringMatching(value: string | RegExp): void, <ide> }; <add> <ide> declare function fail(message?: string): void; <ide> <ide> // TODO handle return type <ide> // http://jasmine.github.io/2.4/introduction.html#section-Spies <ide> declare function spyOn(value: mixed, method: string): Object; <ide> <del>type Jest = { <del> autoMockOff(): Jest, <del> autoMockOn(): Jest, <del> resetAllMocks(): Jest, <del> clearAllTimers(): void, <del> currentTestPath(): void, <del> disableAutomock(): Jest, <del> doMock(moduleName: string, moduleFactory?: any): void, <del> dontMock(moduleName: string): Jest, <del> enableAutomock(): Jest, <del> fn(implementation?: Function): JestMockFn, <del> genMockFromModule(moduleName: string): any, <del> isMockFunction(fn: Function): boolean, <del> mock( <del> moduleName: string, <del> moduleFactory?: any, <del> options?: {virtual?: boolean}, <del> ): Jest, <del> resetModuleRegistry(): Jest, // undocumented alias for resetModuleRegistry <del> resetModules(): Jest, <del> restoreAllMocks(): Jest, <del> runAllTicks(): Jest, <del> runAllTimers(): Jest, <del> runTimersToTime(msToRun: number): Jest, <del> runOnlyPendingTimers(): Jest, <del> setMock(moduleName: string, moduleExports: any): Jest, <del> unmock(moduleName: string): Jest, <del> useFakeTimers(): Jest, <del> useRealTimers(): Jest, <del>}; <del> <del>declare var jest: Jest; <add>/** Holds all functions related to manipulating test runner */ <add>declare var jest: JestObjectType; <ide> <add>/** <add> * The global Jamine object, this is generally not exposed as the public API, <add> * using features inside here could break in later versions of Jest. <add> */ <ide> declare var jasmine: { <ide> DEFAULT_TIMEOUT_INTERVAL: number, <ide> any(value: mixed): JestAsymmetricEqualityType, <ide> anything(): void, <ide> arrayContaining(value: Array<mixed>): void, <ide> clock(): JestClockType, <ide> createSpy(name: string): JestSpyType, <add> createSpyObj( <add> baseName: string, <add> methodNames: Array<string>, <add> ): {[methodName: string]: JestSpyType}, <ide> objectContaining(value: Object): void, <ide> stringMatching(value: string): void, <ide> };
1
Text
Text
add v3.3.0 to changelog
d08990a3045367d4be73729899c6c8016c92167b
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.3.0-beta.5 (July 2, 2018) <del>- [#16781](https://github.com/emberjs/ember.js/pull/16781) [BUGFIX] Ensure tests from @ember/* are excluded from debug/prod builds. <del> <del>### v3.3.0-beta.4 (June 25, 2018) <del>- [#16754](https://github.com/emberjs/ember.js/pull/16754) [BUGFIX] Fix container destroy timing <del>- [#16767](https://github.com/emberjs/ember.js/pull/16767) [BUGFIX] Ensure meta._parent is initialized <del> <del>### v3.3.0-beta.3 (June 18, 2018) <del>- [#16743](https://github.com/emberjs/ember.js/pull/16743) [BUGFIX] Update glimmer-vm to 0.35.4. <del>- [#16750](https://github.com/emberjs/ember.js/pull/16750) [BUGFIX] Bring back isObject guard for ember-utils/is_proxy <del> <del>### v3.3.0-beta.2 (June 11, 2018) <del>- [#16709](https://github.com/emberjs/ember.js/pull/16709) [BUGFIX] Avoid ordered set deprecation in @ember/ordered-set addon <del>- [#16715](https://github.com/emberjs/ember.js/pull/16715) [BUGFIX] Update glimmer-vm to 0.35.3 <del>- [#16729](https://github.com/emberjs/ember.js/pull/16729) [BUGFIX] Throw error if run.bind receives no method <del>- [#16731](https://github.com/emberjs/ember.js/pull/16731) [BUGFIX] Better error when a route name is not valid <del> <del>### v3.3.0-beta.1 (May 31, 2018) <add>### v3.3.0 (July 16, 2018) <ide> <ide> - [#16687](https://github.com/emberjs/ember.js/pull/16687) [FEATURE] Implement optional jQuery integration (see [emberjs/rfcs#294](https://github.com/emberjs/rfcs/blob/master/text/0294-optional-jquery.md) for more details). <ide> - [#16690](https://github.com/emberjs/ember.js/pull/16690) [DEPRECATION] [emberjs/rfcs#294](emberjs/rfcs#294) Deprecate accessing `jQuery.Event#originalEvent`. <ide> - [#16691](https://github.com/emberjs/ember.js/pull/16691) [DEPRECATION] [emberjs/rfcs#237](https://github.com/emberjs/rfcs/pull/237) Implement `Ember.Map`, `Ember.MapWithDefault`, and `Ember.OrderedSet` deprecation. <ide> - [#16692](https://github.com/emberjs/ember.js/pull/16692) [DEPRECATION] [emberjs/rfcs#322](https://github.com/emberjs/rfcs/pull/322) Implement `Ember.copy`/`Ember.Copyable` deprecation. <add>- [#16709](https://github.com/emberjs/ember.js/pull/16709) [BUGFIX] Avoid ordered set deprecation in @ember/ordered-set addon. <add>- [#16729](https://github.com/emberjs/ember.js/pull/16729) [BUGFIX] Throw error if run.bind receives no method. <add>- [#16731](https://github.com/emberjs/ember.js/pull/16731) [BUGFIX] Better error when a route name is not valid. <add>- [#16743](https://github.com/emberjs/ember.js/pull/16743) [BUGFIX] Update glimmer-vm to 0.35.4. <add>- [#16767](https://github.com/emberjs/ember.js/pull/16767) [BUGFIX] Ensure meta._parent is initialized. <add>- [#16781](https://github.com/emberjs/ember.js/pull/16781) [BUGFIX] Ensure tests from @ember/* are excluded from debug/prod builds. <add>- [#16619](https://github.com/emberjs/ember.js/pull/16619) [BUGFIX] Update router_js to ensure `(hash` works in query params. <add>- [#16632](https://github.com/emberjs/ember.js/pull/16632) [BUGFIX] computed.sort array should update if sort properties array is empty/ <ide> <ide> ### v3.2.2 (June 21, 2018) <ide>
1
Python
Python
fix timeout of test-heap-prof.js in riscv devices
186745bc0d32b81aca658503318b2b2d7a5cca45
<ide><path>tools/test.py <ide> def GetTestStatus(self, context, sections, defs): <ide> <ide> <ide> TIMEOUT_SCALEFACTOR = { <del> 'arm' : { 'debug' : 8, 'release' : 3 }, # The ARM buildbots are slow. <del> 'ia32' : { 'debug' : 4, 'release' : 1 }, <del> 'ppc' : { 'debug' : 4, 'release' : 1 }, <del> 's390' : { 'debug' : 4, 'release' : 1 } } <add> 'arm' : { 'debug' : 8, 'release' : 3 }, # The ARM buildbots are slow. <add> 'riscv64' : { 'debug' : 8, 'release' : 3 }, # The riscv devices are slow. <add> 'ia32' : { 'debug' : 4, 'release' : 1 }, <add> 'ppc' : { 'debug' : 4, 'release' : 1 }, <add> 's390' : { 'debug' : 4, 'release' : 1 } } <ide> <ide> <ide> class Context(object): <ide><path>tools/utils.py <ide> def GuessArchitecture(): <ide> return 'ppc' <ide> elif id == 's390x': <ide> return 's390' <add> elif id == 'riscv64': <add> return 'riscv64' <ide> else: <ide> id = platform.processor() <ide> if id == 'powerpc':
2
Ruby
Ruby
add missing require for cookies middleware
a50865c7dcc0827ea843d04a58e91acce9bf2c0e
<ide><path>actionpack/lib/action_dispatch/testing/test_process.rb <add>require 'action_dispatch/middleware/cookies' <ide> require 'action_dispatch/middleware/flash' <ide> require 'active_support/core_ext/hash/indifferent_access' <ide>
1
Text
Text
fix example of i18n setting in the guide [ci skip]
939b85af709d02da569be6a6009f732d5a9d3742
<ide><path>guides/source/i18n.md <ide> A trivial implementation of using an `Accept-Language` header would be: <ide> def switch_locale(&action) <ide> logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}" <ide> locale = extract_locale_from_accept_language_header <del> logger.debug "* Locale set to '#{I18n.locale}'" <add> logger.debug "* Locale set to '#{locale}'" <ide> I18n.with_locale(locale, &action) <ide> end <ide>
1
Ruby
Ruby
use v2 api
7962b15a982cef28cf2356fff1f534000fdb333a
<ide><path>Library/Homebrew/utils.rb <ide> def find_pull_requests rx <ide> require 'vendor/multi_json' <ide> <ide> pulls = [] <del> uri = URI.parse("https://api.github.com/repos/mxcl/homebrew/pulls") <del> uri.query = "per_page=100" <add> query = rx.source.delete '.*' <add> uri = URI.parse("http://github.com/api/v2/json/issues/search/mxcl/homebrew/open/#{query}") <ide> <ide> open uri do |f| <del> MultiJson.decode((f.read)).each do |pull| <del> pulls << pull['html_url'] if rx.match pull['title'] <add> MultiJson.decode(f.read)["issues"].each do |pull| <add> pulls << pull['pull_request_url'] if rx.match pull['title'] and pull["pull_request_url"] <ide> end <del> <del> uri = if f.meta['link'] =~ /rel="next"/ <del> f.meta['link'].slice(URI.regexp) <del> else <del> nil <del> end <del> end while uri <add> end <ide> pulls <ide> rescue <ide> []
1
Python
Python
improve docs of conv_filter_vis example
bb2b3ada3d502c740f2704e44362c9bc32be4353
<ide><path>examples/conv_filter_visualization.py <ide> This script can run on CPU in a few minutes (with the TensorFlow backend). <ide> <ide> Results example: http://i.imgur.com/4nj4KjN.jpg <add> <add>Before running this script, download the weights for the VGG16 model at: <add>https://drive.google.com/file/d/0Bz7KyqmuGsilT0J5dmRCM0ROVHc/view?usp=sharing <add>(source: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3) <add>and make sure the variable `weights_path` in this script matches the location of the file. <ide> ''' <ide> from __future__ import print_function <ide> from scipy.misc import imsave <ide> def normalize(x): <ide> # we start from a gray image with some random noise <ide> input_img_data = np.random.random((1, 3, img_width, img_height)) * 20 + 128. <ide> <del> # we run gradient ascent for 12 steps <del> for i in range(12): <add> # we run gradient ascent for 20 steps <add> for i in range(20): <ide> loss_value, grads_value = iterate([input_img_data]) <ide> input_img_data += grads_value * step <ide>
1
Text
Text
add my text about web components to the article
b7b1cdad60a639266e6b89f4e854e4a0218745ce
<ide><path>guide/english/web-components/how-do-i-use-web-components/index.md <ide> title: How do I use Web Components? <ide> --- <ide> #### How do I use Web Components? <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/web-components/how-do-I-use-web-components/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <ide> <del><ahref='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add><h1>Web Components</h1> <add> <add> <p>Web Components are <q>a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps</q>. You can learn more<a href="https://www.webcomponents.org/introduction" target="_blank"> here</a>.</p> <add> <add> <img src="https://cdn-images-1.medium.com/max/1600/0*_yWD1AV3xLlml1l5.png" alt="four web components" width="704" height="531" /> <add> <add> <p>You can also learn more about this <b>components</b> and how to use them on other <i>websites</i>, such as: <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <ide> <ide> #### More Information: <ide> <!-- Please add any articles you think might be helpful to read before writing the article --> <add>- <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">Mozilla</a> <add>- <a href="https://www.sitepen.com/blog/2018/07/06/web-components-in-2018/">Sitepen</a> <add>- <a href="https://codeburst.io/6-reasons-you-should-use-native-web-components-b45e18e069c2">Codeburst</a> <add>
1
Python
Python
fix template for new models in readme
aeeab1ffd06aaf9703494508752ab75448019c38
<ide><path>utils/check_copies.py <ide> def check_model_list_copy(overwrite=False, max_per_line=119): <ide> <ide> <ide> README_TEMPLATE = ( <del> "1. **[{model_name}](https://huggingface.co/docs/transformers/model_doc/{model_type})** (from <FILL INSTITUTION>) " <del> "released with the paper [<FILL PAPER TITLE>](<FILL ARKIV LINK>) by <FILL AUTHORS>." <add> "1. **[{model_name}](https://huggingface.co/docs/main/transformers/model_doc/{model_type})** (from " <add> "<FILL INSTITUTION>) released with the paper [<FILL PAPER TITLE>](<FILL ARKIV LINK>) by <FILL AUTHORS>." <ide> ) <ide> <ide>
1
Ruby
Ruby
improve test coverage
fe98d21289b7510182e338f352f5a416bd01f1ad
<ide><path>railties/lib/rails/commands/test.rb <ide> require "rails/test_unit/minitest_plugin" <ide> <ide> if defined?(ENGINE_ROOT) <del> $: << File.expand_path("test", ENGINE_ROOT) <add> $LOAD_PATH << File.expand_path("test", ENGINE_ROOT) <ide> else <del> $: << File.expand_path("../../test", APP_PATH) <add> $LOAD_PATH << File.expand_path("../../test", APP_PATH) <ide> end <ide> <ide> exit Minitest.run(ARGV) <ide><path>railties/test/application/test_test.rb <ide> def teardown <ide> teardown_app <ide> end <ide> <del> test "truth" do <add> test "simple successful test" do <ide> app_file "test/unit/foo_test.rb", <<-RUBY <ide> require 'test_helper' <ide> <ide> def test_truth <ide> assert_successful_test_run "unit/foo_test.rb" <ide> end <ide> <add> test "simple failed test" do <add> app_file "test/unit/foo_test.rb", <<-RUBY <add> require 'test_helper' <add> <add> class FooTest < ActiveSupport::TestCase <add> def test_truth <add> assert false <add> end <add> end <add> RUBY <add> <add> assert_unsuccessful_run "unit/foo_test.rb", "Failed assertion" <add> end <add> <ide> test "integration test" do <ide> controller "posts", <<-RUBY <ide> class PostsController < ActionController::Base <ide> class UserTest < ActiveSupport::TestCase <ide> def assert_unsuccessful_run(name, message) <ide> result = run_test_file(name) <ide> assert_not_equal 0, $?.to_i <del> assert result.include?(message) <add> assert_includes result, message <ide> result <ide> end <ide>
2
Text
Text
fix typo in hostnameversioning doc
0712094ea2e846d41ef3ce2a4d12b9159911abfe
<ide><path>docs/api-guide/versioning.md <ide> By default this implementation expects the hostname to match this simple regular <ide> <ide> Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname. <ide> <del>The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online services which you to [access localhost with a custom subdomain][lvh] which you may find helpful in this case. <add>The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online tutorials on how to [access localhost with a custom subdomain][lvh] which you may find helpful in this case. <ide> <ide> Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions. <ide>
1