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
|
---|---|---|---|---|---|
Text | Text | add grafgiti to examples | 9ecf8870c7cc123bd8cfb534ea9212ee4eae7e23 | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide>
<ide> * [Official Examples](Examples.md) — A few official examples covering different Redux techniques
<ide> * [SoundRedux](https://github.com/andrewngu/sound-redux) — A SoundCloud client built with Redux
<add>* [grafgiti](https://github.com/mohebifar/grafgiti) — Create graffity on your GitHub contributions wall
<ide>
<ide> ### Tutorials and Articles
<ide> | 1 |
PHP | PHP | remove empty files for test and plugin bakes | bf4c69a97a31ad081102f412abaf35c5b74fe412 | <ide><path>src/Shell/Task/PluginTask.php
<ide> public function bake($plugin) {
<ide> $out .= "class AppController extends BaseController {\n\n";
<ide> $out .= "}\n";
<ide> $this->createFile($this->path . $plugin . DS . $classBase . DS . 'Controller' . DS . $controllerFileName, $out);
<add> $emptyFile = $this->path . 'empty';
<add> $this->_deleteEmptyFile($emptyFile);
<ide>
<ide> $hasAutoloader = $this->_modifyAutoloader($plugin, $this->path);
<ide> $this->_generateRoutes($plugin, $this->path);
<ide><path>src/Shell/Task/TestTask.php
<ide> public function bake($type, $className) {
<ide> $out = $this->Template->generate('classes', 'test');
<ide>
<ide> $filename = $this->testCaseFileName($type, $fullClassName);
<add> $emptyFile = $this->getPath() . $this->getSubspacePath($type) . DS . 'empty';
<add> $this->_deleteEmptyFile($emptyFile);
<ide> if ($this->createFile($filename, $out)) {
<ide> return $out;
<ide> }
<ide> public function getRealClassName($type, $class) {
<ide> return $namespace . '\\' . $subSpace . '\\' . $class;
<ide> }
<ide>
<add>/**
<add> * Gets the subspace path for a test.
<add> *
<add> * @param string $type The Type of object you are generating tests for eg. controller.
<add> * @return string Path of the subspace.
<add> */
<add> public function getSubspacePath($type) {
<add> $namespace = Configure::read('App.namespace');
<add> if ($this->plugin) {
<add> $namespace = $this->plugin;
<add> }
<add> $suffix = $this->classSuffixes[strtolower($type)];
<add> $subspace = $this->mapType($type);
<add> return str_replace('\\', DS, $subspace);
<add> }
<add>
<ide> /**
<ide> * Map the types that TestTask uses to concrete types that App::className can use.
<ide> * | 2 |
Python | Python | add tests for it | 31b61eeda5373d53b8c3fb2dbbadb3a548861fe7 | <ide><path>libcloud/test/storage/test_cloudfiles.py
<ide> from libcloud.test import MockHttp # pylint: disable-msg=E0611
<ide> from libcloud.test import unittest, generate_random_data, make_response
<ide> from libcloud.test.file_fixtures import StorageFileFixtures # pylint: disable-msg=E0611
<add>from libcloud.test.storage.base import BaseRangeDownloadMockHttp
<ide>
<ide>
<ide> class CloudFilesTests(unittest.TestCase):
<ide> def test_download_object_success_not_found(self):
<ide> else:
<ide> self.fail('Object does not exist but an exception was not thrown')
<ide>
<add> def test_download_object_range_success(self):
<add> container = Container(name='foo_bar_container', extra={}, driver=self)
<add> obj = Object(name='foo_bar_object_range', size=10, hash=None, extra={},
<add> container=container, meta_data=None,
<add> driver=CloudFilesStorageDriver)
<add> destination_path = os.path.abspath(__file__) + '.temp'
<add> result = self.driver.download_object_range(obj=obj,
<add> destination_path=destination_path,
<add> start_bytes=5,
<add> end_bytes=7,
<add> overwrite_existing=False,
<add> delete_on_failure=True)
<add> self.assertTrue(result)
<add>
<add> with open(destination_path, 'r') as fp:
<add> content = fp.read()
<add>
<add> self.assertEqual(content, '56')
<add>
<ide> def test_download_object_as_stream(self):
<ide> container = Container(name='foo_bar_container', extra={}, driver=self)
<ide> obj = Object(name='foo_bar_object', size=1000, hash=None, extra={},
<ide> def test_download_object_as_stream_data_is_not_buffered_in_memory(self):
<ide>
<ide> self.assertEqual(result, 'a' * 1000)
<ide>
<add> def test_download_object_range_as_stream_success(self):
<add> container = Container(name='foo_bar_container', extra={}, driver=self)
<add> obj = Object(name='foo_bar_object_range', size=2, hash=None, extra={},
<add> container=container, meta_data=None,
<add> driver=CloudFilesStorageDriver)
<add>
<add> stream = self.driver.download_object_range_as_stream(
<add> start_bytes=5, end_bytes=7, obj=obj, chunk_size=None)
<add> self.assertTrue(hasattr(stream, '__iter__'))
<add> consumed_stream = ''.join(chunk.decode('utf-8') for chunk in stream)
<add> self.assertEqual(consumed_stream, '56')
<add> self.assertEqual(len(consumed_stream), obj.size)
<add>
<ide> def test_upload_object_success(self):
<ide> def upload_file(self, object_name=None, content_type=None,
<ide> request_path=None, request_method=None,
<ide> class CloudFilesDeprecatedUKTests(CloudFilesTests):
<ide> region = 'lon'
<ide>
<ide>
<del>class CloudFilesMockHttp(MockHttp, unittest.TestCase):
<add>class CloudFilesMockHttp(BaseRangeDownloadMockHttp, unittest.TestCase):
<ide>
<ide> fixtures = StorageFileFixtures('cloudfiles')
<ide> base_headers = {'content-type': 'application/json; charset=UTF-8'}
<ide> def _v1_MossoCloudFS_foo_bar_container_foo_bar_object(
<ide> self.base_headers,
<ide> httplib.responses[httplib.OK])
<ide>
<add> def _v1_MossoCloudFS_foo_bar_container_foo_bar_object_range(
<add> self, method, url, body, headers):
<add> if method == 'GET':
<add> # test_download_object_range_success
<add> body = '0123456789123456789'
<add>
<add> self.assertTrue('Range' in headers)
<add> self.assertEqual(headers['Range'], 'bytes=5-6')
<add>
<add> start_bytes, end_bytes = self._get_start_and_end_bytes_from_range_str(headers['Range'], body)
<add>
<add> return (httplib.PARTIAL_CONTENT,
<add> body[start_bytes:end_bytes + 1],
<add> self.base_headers,
<add> httplib.responses[httplib.PARTIAL_CONTENT])
<add>
<ide> def _v1_MossoCloudFS_py3_img_or_vid(self, method, url, body, headers):
<ide> headers = {'etag': 'e2378cace8712661ce7beec3d9362ef6'}
<ide> headers.update(self.base_headers) | 1 |
PHP | PHP | avoid call to method alias | be140fcc63fb2c7373e8c19269125b8f711a127b | <ide><path>src/Illuminate/Cache/Repository.php
<ide> public function put($key, $value, $ttl = null)
<ide> $seconds = $this->getSeconds($ttl);
<ide>
<ide> if ($seconds <= 0) {
<del> return $this->delete($key);
<add> return $this->forget($key);
<ide> }
<ide>
<ide> $result = $this->store->put($this->itemKey($key), $value, $seconds); | 1 |
Java | Java | use correct return type in javadoc documentation | 913e80046194b2f679e4213335c7a17cfa74c1e0 | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final Maybe<T> elementAt(long index) {
<ide> }
<ide>
<ide> /**
<del> * Returns a Flowable that emits the item found at a specified index in a sequence of emissions from
<add> * Returns a Single that emits the item found at a specified index in a sequence of emissions from
<ide> * this Flowable, or a default item if that index is out of range.
<ide> * <p>
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/elementAtOrDefault.png" alt="">
<ide> public final Maybe<T> elementAt(long index) {
<ide> * the zero-based index of the item to retrieve
<ide> * @param defaultItem
<ide> * the default item
<del> * @return a Flowable that emits the item at the specified position in the sequence emitted by the source
<add> * @return a Single that emits the item at the specified position in the sequence emitted by the source
<ide> * Publisher, or the default item if that index is outside the bounds of the source sequence
<ide> * @throws IndexOutOfBoundsException
<ide> * if {@code index} is less than 0
<ide> public final Single<T> elementAt(long index, T defaultItem) {
<ide> }
<ide>
<ide> /**
<del> * Returns a Flowable that emits the item found at a specified index in a sequence of emissions from
<add> * Returns a Single that emits the item found at a specified index in a sequence of emissions from
<ide> * this Flowable or signals a {@link NoSuchElementException} if this Flowable has fewer elements than index.
<ide> * <p>
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/elementAtOrDefault.png" alt="">
<ide> public final Single<T> elementAt(long index, T defaultItem) {
<ide> *
<ide> * @param index
<ide> * the zero-based index of the item to retrieve
<del> * @return a Flowable that emits the item at the specified position in the sequence emitted by the source
<add> * @return a Single that emits the item at the specified position in the sequence emitted by the source
<ide> * Publisher, or the default item if that index is outside the bounds of the source sequence
<ide> * @throws IndexOutOfBoundsException
<ide> * if {@code index} is less than 0
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final Maybe<T> lastElement() {
<ide> *
<ide> * @param defaultItem
<ide> * the default item to emit if the source ObservableSource is empty
<del> * @return an Observable that emits only the last item emitted by the source ObservableSource, or a default item
<add> * @return a Single that emits only the last item emitted by the source ObservableSource, or a default item
<ide> * if the source ObservableSource is empty
<ide> * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX operators documentation: Last</a>
<ide> */ | 2 |
Javascript | Javascript | fix a memory leak in reactcomponenttreedevtool | 3779a5d18c3e624bd12846592469e9c69a8c19c9 | <ide><path>src/isomorphic/ReactDebugTool.js
<ide> var currentTimerDebugID = null;
<ide> var currentTimerStartTime = null;
<ide> var currentTimerType = null;
<ide>
<add>function clearHistory() {
<add> ReactComponentTreeDevtool.purgeUnmountedComponents();
<add> ReactNativeOperationHistoryDevtool.clearHistory();
<add>}
<add>
<add>function getTreeSnapshot(registeredIDs) {
<add> return registeredIDs.reduce((tree, id) => {
<add> var ownerID = ReactComponentTreeDevtool.getOwnerID(id);
<add> var parentID = ReactComponentTreeDevtool.getParentID(id);
<add> tree[id] = {
<add> displayName: ReactComponentTreeDevtool.getDisplayName(id),
<add> text: ReactComponentTreeDevtool.getText(id),
<add> updateCount: ReactComponentTreeDevtool.getUpdateCount(id),
<add> childIDs: ReactComponentTreeDevtool.getChildIDs(id),
<add> // Text nodes don't have owners but this is close enough.
<add> ownerID: ownerID || ReactComponentTreeDevtool.getOwnerID(parentID),
<add> parentID,
<add> };
<add> return tree;
<add> }, {});
<add>}
<add>
<ide> function resetMeasurements() {
<ide> if (__DEV__) {
<add> var previousStartTime = currentFlushStartTime;
<add> var previousMeasurements = currentFlushMeasurements || [];
<add> var previousOperations = ReactNativeOperationHistoryDevtool.getHistory();
<add>
<ide> if (!isProfiling || currentFlushNesting === 0) {
<ide> currentFlushStartTime = null;
<ide> currentFlushMeasurements = null;
<add> clearHistory();
<ide> return;
<ide> }
<ide>
<del> var previousStartTime = currentFlushStartTime;
<del> var previousMeasurements = currentFlushMeasurements || [];
<del> var previousOperations = ReactNativeOperationHistoryDevtool.getHistory();
<del>
<ide> if (previousMeasurements.length || previousOperations.length) {
<ide> var registeredIDs = ReactComponentTreeDevtool.getRegisteredIDs();
<ide> flushHistory.push({
<ide> duration: performanceNow() - previousStartTime,
<ide> measurements: previousMeasurements || [],
<ide> operations: previousOperations || [],
<del> treeSnapshot: registeredIDs.reduce((tree, id) => {
<del> var ownerID = ReactComponentTreeDevtool.getOwnerID(id);
<del> var parentID = ReactComponentTreeDevtool.getParentID(id);
<del> tree[id] = {
<del> displayName: ReactComponentTreeDevtool.getDisplayName(id),
<del> text: ReactComponentTreeDevtool.getText(id),
<del> updateCount: ReactComponentTreeDevtool.getUpdateCount(id),
<del> childIDs: ReactComponentTreeDevtool.getChildIDs(id),
<del> // Text nodes don't have owners but this is close enough.
<del> ownerID: ownerID || ReactComponentTreeDevtool.getOwnerID(parentID),
<del> parentID,
<del> };
<del> return tree;
<del> }, {}),
<add> treeSnapshot: getTreeSnapshot(registeredIDs),
<ide> });
<ide> }
<ide>
<add> clearHistory();
<ide> currentFlushStartTime = performanceNow();
<ide> currentFlushMeasurements = [];
<del> ReactComponentTreeDevtool.purgeUnmountedComponents();
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<ide> }
<ide> }
<ide>
<ide><path>src/isomorphic/__tests__/ReactPerf-test.js
<ide> describe('ReactPerf', function() {
<ide> });
<ide> });
<ide>
<add> it('should include stats for components unmounted during measurement', function() {
<add> var container = document.createElement('div');
<add> var measurements = measure(() => {
<add> ReactDOM.render(<Div><Div key="a" /></Div>, container);
<add> ReactDOM.render(<Div><Div key="b" /></Div>, container);
<add> });
<add> expect(ReactPerf.getExclusive(measurements)).toEqual([{
<add> key: 'Div',
<add> instanceCount: 3,
<add> counts: { ctor: 3, render: 4 },
<add> durations: { ctor: 3, render: 4 },
<add> totalDuration: 7,
<add> }]);
<add> });
<add>
<ide> it('warns once when using getMeasurementsSummaryMap', function() {
<ide> var measurements = measure(() => {});
<ide> spyOn(console, 'error');
<ide><path>src/isomorphic/devtools/ReactComponentTreeDevtool.js
<ide> var ReactComponentTreeDevtool = {
<ide> },
<ide>
<ide> purgeUnmountedComponents() {
<add> if (ReactComponentTreeDevtool._preventPurging) {
<add> // Should only be used for testing.
<add> return;
<add> }
<add>
<ide> Object.keys(tree)
<ide> .filter(id => !tree[id].isMounted)
<ide> .forEach(purgeDeep);
<ide><path>src/isomorphic/devtools/ReactNativeOperationHistoryDevtool.js
<ide> var ReactNativeOperationHistoryDevtool = {
<ide> },
<ide>
<ide> clearHistory() {
<add> if (ReactNativeOperationHistoryDevtool._preventClearing) {
<add> // Should only be used for tests.
<add> return;
<add> }
<add>
<ide> history = [];
<ide> },
<ide>
<ide><path>src/isomorphic/devtools/__tests__/ReactComponentTreeDevtool-test.js
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> // Ensure the tree is correct on every step.
<ide> pairs.forEach(([element, expectedTree]) => {
<ide> currentElement = element;
<add>
<add> // Mount a new tree or update the existing tree.
<ide> ReactDOM.render(<Wrapper />, node);
<ide> expect(getActualTree()).toEqual(expectedTree);
<add>
<add> // Purging should have no effect
<add> // on the tree we expect to see.
<ide> ReactComponentTreeDevtool.purgeUnmountedComponents();
<ide> expect(getActualTree()).toEqual(expectedTree);
<ide> });
<add>
<add> // Unmounting the root node should purge
<add> // the whole subtree automatically.
<ide> ReactDOM.unmountComponentAtNode(node);
<del> ReactComponentTreeDevtool.purgeUnmountedComponents();
<ide> expect(getActualTree()).toBe(undefined);
<ide> expect(getRootDisplayNames()).toEqual([]);
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> // Ensure the tree is correct on every step.
<ide> pairs.forEach(([element, expectedTree]) => {
<ide> currentElement = element;
<add>
<add> // Rendering to string should not produce any entries
<add> // because ReactDebugTool purges it when the flush ends.
<add> ReactDOMServer.renderToString(<Wrapper />);
<add> expect(getActualTree()).toBe(undefined);
<add> expect(getRootDisplayNames()).toEqual([]);
<add> expect(getRegisteredDisplayNames()).toEqual([]);
<add>
<add> // To test it, we tell the devtool to ignore next purge
<add> // so the cleanup request by ReactDebugTool is ignored.
<add> // This lets us make assertions on the actual tree.
<add> ReactComponentTreeDevtool._preventPurging = true;
<ide> ReactDOMServer.renderToString(<Wrapper />);
<add> ReactComponentTreeDevtool._preventPurging = false;
<ide> expect(getActualTree()).toEqual(expectedTree);
<add>
<add> // Purge manually since we skipped the automatic purge.
<ide> ReactComponentTreeDevtool.purgeUnmountedComponents();
<ide> expect(getActualTree()).toBe(undefined);
<ide> expect(getRootDisplayNames()).toEqual([]);
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> assertTreeMatches([element, tree], {includeOwnerDisplayName: true});
<ide> });
<ide>
<del> it('preserves unmounted components until purge', () => {
<add> it('purges unmounted components automatically', () => {
<ide> var node = document.createElement('div');
<ide> var renderBar = true;
<ide> var fooInstance;
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> renderBar = false;
<ide> ReactDOM.render(<Foo />, node);
<ide> expect(
<del> getTree(barInstance._debugID, {
<del> includeParentDisplayName: true,
<del> expectedParentID: fooInstance._debugID,
<del> })
<add> getTree(barInstance._debugID, {expectedParentID: null})
<ide> ).toEqual({
<del> displayName: 'Bar',
<del> parentDisplayName: 'Foo',
<add> displayName: 'Unknown',
<ide> children: [],
<ide> });
<ide>
<ide> ReactDOM.unmountComponentAtNode(node);
<ide> expect(
<del> getTree(barInstance._debugID, {
<del> includeParentDisplayName: true,
<del> expectedParentID: fooInstance._debugID,
<del> })
<del> ).toEqual({
<del> displayName: 'Bar',
<del> parentDisplayName: 'Foo',
<del> children: [],
<del> });
<del>
<del> ReactComponentTreeDevtool.purgeUnmountedComponents();
<del> expect(
<del> getTree(barInstance._debugID, {includeParentDisplayName: true})
<add> getTree(barInstance._debugID, {expectedParentID: null})
<ide> ).toEqual({
<ide> displayName: 'Unknown',
<ide> children: [],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> ReactDOM.unmountComponentAtNode(node);
<ide> expect(ReactComponentTreeDevtool.getUpdateCount(divID)).toEqual(0);
<del> expect(ReactComponentTreeDevtool.getUpdateCount(spanID)).toEqual(2);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(spanID)).toEqual(0);
<ide> });
<ide>
<ide> it('does not report top-level wrapper as a root', () => {
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> ReactDOM.unmountComponentAtNode(node);
<ide> expect(getRootDisplayNames()).toEqual([]);
<del>
<del> ReactComponentTreeDevtool.purgeUnmountedComponents();
<del> expect(getRootDisplayNames()).toEqual([]);
<del>
<del> // This currently contains TopLevelWrapper until purge
<del> // so we only check it at the very end.
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide> });
<ide> });
<ide><path>src/isomorphic/devtools/__tests__/ReactComponentTreeDevtool-test.native.js
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> // Ensure the tree is correct on every step.
<ide> pairs.forEach(([element, expectedTree]) => {
<ide> currentElement = element;
<add>
<add> // Mount a new tree or update the existing tree.
<ide> ReactNative.render(<Wrapper />, 1);
<ide> expect(getActualTree()).toEqual(expectedTree);
<add>
<add> // Purging should have no effect
<add> // on the tree we expect to see.
<ide> ReactComponentTreeDevtool.purgeUnmountedComponents();
<ide> expect(getActualTree()).toEqual(expectedTree);
<ide> });
<add>
<add> // Unmounting the root node should purge
<add> // the whole subtree automatically.
<ide> ReactNative.unmountComponentAtNode(1);
<del> ReactComponentTreeDevtool.purgeUnmountedComponents();
<ide> expect(getActualTree()).toBe(undefined);
<ide> expect(getRootDisplayNames()).toEqual([]);
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> // Ensure the tree is correct on every step.
<ide> pairs.forEach(([element, expectedTree]) => {
<ide> currentElement = element;
<add>
<add> // Mount a new tree.
<ide> ReactNative.render(<Wrapper />, 1);
<del> ReactNative.unmountComponentAtNode(1);
<ide> expect(getActualTree()).toEqual(expectedTree);
<del> ReactComponentTreeDevtool.purgeUnmountedComponents();
<add>
<add> // Unmounting should clean it up.
<add> ReactNative.unmountComponentAtNode(1);
<ide> expect(getActualTree()).toBe(undefined);
<ide> expect(getRootDisplayNames()).toEqual([]);
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> assertTreeMatches([element, tree], {includeOwnerDisplayName: true});
<ide> });
<ide>
<del> it('preserves unmounted components until purge', () => {
<add> it('purges unmounted components automatically', () => {
<ide> var renderBar = true;
<ide> var fooInstance;
<ide> var barInstance;
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> renderBar = false;
<ide> ReactNative.render(<Foo />, 1);
<ide> expect(
<del> getTree(barInstance._debugID, {
<del> includeParentDisplayName: true,
<del> expectedParentID: fooInstance._debugID,
<del> })
<add> getTree(barInstance._debugID, {expectedParentID: null})
<ide> ).toEqual({
<del> displayName: 'Bar',
<del> parentDisplayName: 'Foo',
<add> displayName: 'Unknown',
<ide> children: [],
<ide> });
<ide>
<ide> ReactNative.unmountComponentAtNode(1);
<ide> expect(
<del> getTree(barInstance._debugID, {
<del> includeParentDisplayName: true,
<del> expectedParentID: fooInstance._debugID,
<del> })
<del> ).toEqual({
<del> displayName: 'Bar',
<del> parentDisplayName: 'Foo',
<del> children: [],
<del> });
<del>
<del> ReactComponentTreeDevtool.purgeUnmountedComponents();
<del> expect(
<del> getTree(barInstance._debugID, {includeParentDisplayName: true})
<add> getTree(barInstance._debugID, {expectedParentID: null})
<ide> ).toEqual({
<ide> displayName: 'Unknown',
<ide> children: [],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> ReactNative.unmountComponentAtNode(1);
<ide> expect(ReactComponentTreeDevtool.getUpdateCount(viewID)).toEqual(0);
<del> expect(ReactComponentTreeDevtool.getUpdateCount(imageID)).toEqual(2);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(imageID)).toEqual(0);
<ide> });
<ide>
<ide> it('does not report top-level wrapper as a root', () => {
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> ReactNative.unmountComponentAtNode(1);
<ide> expect(getRootDisplayNames()).toEqual([]);
<del>
<del> ReactComponentTreeDevtool.purgeUnmountedComponents();
<del> expect(getRootDisplayNames()).toEqual([]);
<del>
<del> // This currently contains TopLevelWrapper until purge
<del> // so we only check it at the very end.
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide> });
<ide> });
<ide><path>src/isomorphic/devtools/__tests__/ReactNativeOperationHistoryDevtool-test.js
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> describe('mount', () => {
<ide> it('gets recorded for native roots', () => {
<ide> var node = document.createElement('div');
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div><p>Hi.</p></div>, node);
<del> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<add> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'mount',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> return <div><p>Hi.</p></div>;
<ide> }
<ide> var node = document.createElement('div');
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<Foo />, node);
<add>
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> return null;
<ide> }
<ide> var node = document.createElement('div');
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<Foo />, node);
<ide>
<ide> // Empty DOM components should be invisible to devtools.
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> return element;
<ide> }
<ide>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<add>
<ide> var node = document.createElement('div');
<ide> element = null;
<ide> ReactDOM.render(<Foo />, node);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<ide> element = <span />;
<ide> ReactDOM.render(<Foo />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> describe('update styles', () => {
<ide> it('gets recorded during mount', () => {
<ide> var node = document.createElement('div');
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div style={{
<ide> color: 'red',
<ide> backgroundColor: 'yellow',
<ide> }} />, node);
<del> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<add> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide> if (ReactDOMFeatureFlags.useCreateElement) {
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div style={{ color: 'red' }} />, node);
<ide> ReactDOM.render(<div style={{
<ide> color: 'blue',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div style={{
<ide> color: 'red',
<ide> backgroundColor: 'yellow',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> describe('simple attribute', () => {
<ide> it('gets recorded during mount', () => {
<ide> var node = document.createElement('div');
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div className="rad" tabIndex={42} />, node);
<del> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<add> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide> if (ReactDOMFeatureFlags.useCreateElement) {
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div className="rad" />, node);
<ide> ReactDOM.render(<div className="mad" tabIndex={42} />, node);
<ide> ReactDOM.render(<div tabIndex={43} />, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'update attribute',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div disabled={true} />, node);
<ide> ReactDOM.render(<div disabled={false} />, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'update attribute',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> describe('custom attribute', () => {
<ide> it('gets recorded during mount', () => {
<ide> var node = document.createElement('div');
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div data-x="rad" data-y={42} />, node);
<del> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<add> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide> if (ReactDOMFeatureFlags.useCreateElement) {
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div data-x="rad" />, node);
<ide> ReactDOM.render(<div data-x="mad" data-y={42} />, node);
<ide> ReactDOM.render(<div data-y={43} />, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'update attribute',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> describe('attribute on a web component', () => {
<ide> it('gets recorded during mount', () => {
<ide> var node = document.createElement('div');
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<my-component className="rad" tabIndex={42} />, node);
<del> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<add> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide> if (ReactDOMFeatureFlags.useCreateElement) {
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<my-component />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<my-component className="rad" />, node);
<ide> ReactDOM.render(<my-component className="mad" tabIndex={42} />, node);
<ide> ReactDOM.render(<my-component tabIndex={43} />, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'update attribute',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div>Hi.</div>, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div>Bye.</div>, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'replace text',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 'Hi.'}} />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div>Bye.</div>, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'replace text',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div><span /><p /></div>, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div>Bye.</div>, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'remove child',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> var node = document.createElement('div');
<ide> ReactDOM.render(<div>Hi.</div>, node);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div>Hi.</div>, node);
<add>
<ide> assertHistoryMatches([]);
<ide> });
<ide> });
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> var inst1 = ReactDOMComponentTree.getInstanceFromNode(node.firstChild.childNodes[0]);
<ide> var inst2 = ReactDOMComponentTree.getInstanceFromNode(node.firstChild.childNodes[3]);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div>{'Bye.'}{43}</div>, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst1._debugID,
<ide> type: 'replace text',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> var node = document.createElement('div');
<ide> ReactDOM.render(<div>{'Hi.'}{42}</div>, node);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div>{'Hi.'}{42}</div>, node);
<add>
<ide> assertHistoryMatches([]);
<ide> });
<ide> });
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<Foo />, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<ide> element = <span />;
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<Foo />, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'replace with',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> var node = document.createElement('div');
<ide> element = <span />;
<ide> ReactDOM.render(<Foo />, node);
<del> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide> element = null;
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<Foo />, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'replace with',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> element = <div />;
<ide> ReactDOM.render(<Foo />, node);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<ide> element = <div />;
<add>
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<Foo />, node);
<add>
<ide> assertHistoryMatches([]);
<ide> });
<ide> });
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div>Hi.</div>, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(
<ide> <div dangerouslySetInnerHTML={{__html: 'Bye.'}} />,
<ide> node
<ide> );
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'replace children',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> );
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(
<ide> <div dangerouslySetInnerHTML={{__html: 'Bye.'}} />,
<ide> node
<ide> );
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'replace children',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div><span /><p /></div>, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(
<ide> <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />,
<ide> node
<ide> );
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'remove child',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> node
<ide> );
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(
<ide> <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />,
<ide> node
<ide> );
<add>
<ide> assertHistoryMatches([]);
<ide> });
<ide> });
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div><span /></div>, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div><span /><p /></div>, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'insert child',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div><span key="a" /><p key="b" /></div>, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div><p key="b" /><span key="a" /></div>, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'move child',
<ide> describe('ReactNativeOperationHistoryDevtool', () => {
<ide> ReactDOM.render(<div><span key="a" /><p key="b" /></div>, node);
<ide> var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
<ide>
<del> ReactNativeOperationHistoryDevtool.clearHistory();
<add> ReactNativeOperationHistoryDevtool._preventClearing = true;
<ide> ReactDOM.render(<div><span key="a" /></div>, node);
<add>
<ide> assertHistoryMatches([{
<ide> instanceID: inst._debugID,
<ide> type: 'remove child',
<ide><path>src/renderers/dom/server/ReactServerRendering.js
<ide> function renderToStringImpl(element, makeStaticMarkup) {
<ide> transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup);
<ide>
<ide> return transaction.perform(function() {
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onBeginFlush();
<add> }
<ide> var componentInstance = instantiateReactComponent(element);
<ide> var markup = ReactReconciler.mountComponent(
<ide> componentInstance,
<ide> function renderToStringImpl(element, makeStaticMarkup) {
<ide> ReactInstrumentation.debugTool.onUnmountComponent(
<ide> componentInstance._debugID
<ide> );
<add> ReactInstrumentation.debugTool.onEndFlush();
<ide> }
<ide> if (!makeStaticMarkup) {
<ide> markup = ReactMarkupChecksum.addChecksumToMarkup(markup);
<ide><path>src/renderers/native/ReactNativeMount.js
<ide> var ReactNativeMount = {
<ide> if (!instance) {
<ide> return false;
<ide> }
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onBeginFlush();
<add> }
<ide> ReactNativeMount.unmountComponentFromNode(instance, containerTag);
<ide> delete ReactNativeMount._instancesByContainerID[containerTag];
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onEndFlush();
<add> }
<ide> return true;
<ide> },
<ide> | 9 |
Python | Python | improve error messages in dense_attention.py | 0fadd903ecc41214a7fcdc92cd944351e8c2e07d | <ide><path>keras/layers/dense_attention.py
<ide> def _validate_call_args(self, inputs, mask):
<ide> class_name = self.__class__.__name__
<ide> if not isinstance(inputs, list):
<ide> raise ValueError(
<del> '{} layer must be called on a list of inputs, namely [query, value] '
<del> 'or [query, value, key].'.format(class_name))
<add> f'{class_name} layer must be called on a list of inputs, '
<add> 'namely [query, value] or [query, value, key]. '
<add> f'Received: {inputs}.')
<ide> if len(inputs) < 2 or len(inputs) > 3:
<ide> raise ValueError(
<del> '{} layer accepts inputs list of length 2 or 3, '
<add> f'{class_name} layer accepts inputs list of length 2 or 3, '
<ide> 'namely [query, value] or [query, value, key]. '
<del> 'Given length: {}'.format(class_name, len(inputs)))
<add> f'Received length: {len(inputs)}.')
<ide> if mask:
<ide> if not isinstance(mask, list):
<ide> raise ValueError(
<del> '{} layer mask must be a list, '
<del> 'namely [query_mask, value_mask].'.format(class_name))
<add> f'{class_name} layer mask must be a list, '
<add> f'namely [query_mask, value_mask]. Received: {mask}.')
<ide> if len(mask) < 2 or len(mask) > len(inputs):
<ide> raise ValueError(
<del> '{} layer mask must be a list of length 2, namely [query_mask, '
<del> 'value_mask]. Given length: {}'.format(class_name, len(mask)))
<add> f'{class_name} layer mask must be a list of length 2, '
<add> f'namely [query_mask, value_mask]. Received length: {len(mask)}.')
<ide>
<ide> def get_config(self):
<ide> config = { | 1 |
Ruby | Ruby | fix version update task to deal with .beta1.1 | 23c36725a0fa097cbfde0a3661fa21e9470d0a48 | <ide><path>tasks/release.rb
<ide> file = Dir[glob].first
<ide> ruby = File.read(file)
<ide>
<del> major, minor, tiny, pre = version.split('.')
<add> major, minor, tiny, pre = version.split('.', 4)
<ide> pre = pre ? pre.inspect : "nil"
<ide>
<ide> ruby.gsub!(/^(\s*)MAJOR(\s*)= .*?$/, "\\1MAJOR = #{major}") | 1 |
Ruby | Ruby | fix syntax of routing tests so they actually run | aa31a255c831808b42c28978a36ffa42ff03e68e | <ide><path>actionpack/test/dispatch/routing_test.rb
<ide> def test_constraints_are_merged_from_scope
<ide> assert_equal 'Not Found', @response.body
<ide> assert_raises(ActionController::RoutingError){ movie_trailer_path(:movie_id => '00001') }
<ide> end
<add> end
<ide>
<del> def test_only_option_should_be_overwritten
<add> def test_only_option_should_be_overwritten
<add> with_test_routes do
<ide> get '/clubs'
<ide> assert_equal 'clubs#index', @response.body
<ide> assert_equal '/clubs', clubs_path
<ide>
<ide> get '/clubs/1'
<ide> assert_equal 'Not Found', @response.body
<del> assert_raise(NameError) { club_path(:id => '1') }
<add> assert_raise(NoMethodError) { club_path(:id => '1') }
<ide>
<ide> get '/clubs/1/players'
<ide> assert_equal 'Not Found', @response.body
<del> assert_raise(NameError) { club_players_path(:club_id => '1') }
<add> assert_raise(NoMethodError) { club_players_path(:club_id => '1') }
<ide>
<ide> get '/clubs/1/players/2'
<ide> assert_equal 'players#show', @response.body
<ide> assert_equal '/clubs/1/players/2', club_player_path(:club_id => '1', :id => '2')
<ide>
<ide> get '/clubs/1/chairman/new'
<ide> assert_equal 'Not Found', @response.body
<del> assert_raise(NameError) { new_club_chairman_path(:club_id => '1') }
<add> assert_raise(NoMethodError) { new_club_chairman_path(:club_id => '1') }
<ide>
<ide> get '/clubs/1/chairman'
<ide> assert_equal 'chairmen#show', @response.body
<ide> assert_equal '/clubs/1/chairman', club_chairman_path(:club_id => '1')
<ide> end
<add> end
<ide>
<del> def test_except_option_should_be_overwritten
<add> def test_except_option_should_be_overwritten
<add> with_test_routes do
<ide> get '/sectors'
<ide> assert_equal 'sectors#index', @response.body
<ide> assert_equal '/sectors', sectors_path
<ide>
<del> get '/sectors/new'
<add> get '/sectors/1/edit'
<ide> assert_equal 'Not Found', @response.body
<del> assert_raise(NameError) { new_sector_path }
<add> assert_raise(NoMethodError) { edit_sector_path(:id => '1') }
<ide>
<ide> delete '/sectors/1'
<ide> assert_equal 'sectors#destroy', @response.body
<ide>
<ide> get '/sectors/1/companies/new'
<ide> assert_equal 'companies#new', @response.body
<del> assert_equal '/sectors/1/companies/new', new_sector_company_path
<add> assert_equal '/sectors/1/companies/new', new_sector_company_path(:sector_id => '1')
<ide>
<ide> delete '/sectors/1/companies/1'
<ide> assert_equal 'Not Found', @response.body
<ide>
<ide> get '/sectors/1/leader/new'
<ide> assert_equal 'leaders#new', @response.body
<del> assert_equal '/sectors/1/leader/new', new_sector_leader_path
<add> assert_equal '/sectors/1/leader/new', new_sector_leader_path(:sector_id => '1')
<ide>
<ide> delete '/sectors/1/leader'
<ide> assert_equal 'Not Found', @response.body
<ide> end
<add> end
<ide>
<del> def test_only_option_should_overwrite_except_option
<add> def test_only_option_should_overwrite_except_option
<add> with_test_routes do
<ide> get '/sectors/1/companies/2/divisions'
<ide> assert_equal 'divisions#index', @response.body
<del> assert_equal '/sectors/1/companies/2/divisions', sector_company_divisions_path
<add> assert_equal '/sectors/1/companies/2/divisions', sector_company_divisions_path(:sector_id => '1', :company_id => '2')
<ide>
<ide> get '/sectors/1/companies/2/divisions/3'
<ide> assert_equal 'Not Found', @response.body
<del> assert_raise(NameError) { sector_company_division_path(:sector_id => '1', :company_id => '2', :id => '3') }
<add> assert_raise(NoMethodError) { sector_company_division_path(:sector_id => '1', :company_id => '2', :id => '3') }
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | remove platform blacklists | 23d84c8df894bf7daba1ece53cc68cddb5f0c489 | <ide><path>local-cli/bundle/buildBundle.js
<ide> function buildBundle(args, config, output = outputBundle, packagerInstance) {
<ide> projectRoots: config.getProjectRoots(),
<ide> assetExts: defaultAssetExts.concat(assetExts),
<ide> assetRoots: config.getAssetRoots(),
<del> blacklistRE: config.getBlacklistRE(args.platform),
<add> blacklistRE: config.getBlacklistRE(),
<ide> getTransformOptionsModulePath: config.getTransformOptionsModulePath,
<ide> transformModulePath: transformModulePath,
<ide> extraNodeModules: config.extraNodeModules,
<ide><path>local-cli/default.config.js
<del>'use strict';
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add> 'use strict';
<ide>
<ide> var blacklist = require('../packager/blacklist');
<ide> var path = require('path');
<ide> var config = {
<ide> * Returns a regular expression for modules that should be ignored by the
<ide> * packager on a given platform.
<ide> */
<del> getBlacklistRE(platform) {
<del> return blacklist(platform);
<add> getBlacklistRE() {
<add> return blacklist();
<ide> },
<ide>
<ide> /**
<ide><path>local-cli/dependencies/dependencies.js
<ide> function dependencies(argv, config, args, packagerInstance) {
<ide> const packageOpts = {
<ide> projectRoots: config.getProjectRoots(),
<ide> assetRoots: config.getAssetRoots(),
<del> blacklistRE: config.getBlacklistRE(args.platform),
<add> blacklistRE: config.getBlacklistRE(),
<ide> getTransformOptionsModulePath: config.getTransformOptionsModulePath,
<ide> transformModulePath: transformModulePath,
<ide> extraNodeModules: config.extraNodeModules,
<ide><path>packager/blacklist.js
<ide> var sharedBlacklist = [
<ide> 'Libraries/Relay/relay/tools/relayUnstableBatchedUpdates.js',
<ide> ];
<ide>
<del>var platformBlacklists = {
<del> web: [
<del> '.ios.js',
<del> '.android.js',
<del> '.windows.js'
<del> ],
<del> ios: [
<del> '.web.js',
<del> '.android.js',
<del> '.windows.js',
<del> ],
<del> android: [
<del> '.web.js',
<del> '.ios.js',
<del> '.windows.js'
<del> ],
<del> windows: [
<del> '.web.js',
<del> '.ios.js',
<del> '.android.js'
<del> ],
<del>};
<del>
<ide> function escapeRegExp(pattern) {
<ide> if (Object.prototype.toString.call(pattern) === '[object RegExp]') {
<ide> return pattern.source.replace(/\//g, path.sep);
<ide> function escapeRegExp(pattern) {
<ide> }
<ide> }
<ide>
<del>function blacklist(platform, additionalBlacklist) {
<add>function blacklist(additionalBlacklist) {
<ide> return new RegExp('(' +
<ide> (additionalBlacklist || []).concat(sharedBlacklist)
<del> .concat(platformBlacklists[platform] || [])
<ide> .map(escapeRegExp)
<ide> .join('|') +
<ide> ')$'
<ide><path>packager/rn-cli.config.js
<del>// Copyright 2004-present Facebook. All Rights Reserved.
<del>
<ide> /**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<ide> * React Native CLI configuration file
<ide> */
<ide> 'use strict';
<ide> module.exports = {
<ide> return [];
<ide> },
<ide>
<del> getBlacklistRE(platform) {
<del> return blacklist(platform);
<add> getBlacklistRE() {
<add> return blacklist();
<ide> },
<ide>
<ide> _getRoots() { | 5 |
Ruby | Ruby | add more helper methods | 5d1f4dd531f9e88c762f2f65e73e67511798c62d | <ide><path>Library/Homebrew/migrator.rb
<ide> def initialize(formula, tap)
<ide> # path to newname keg that will be linked if old_linked_keg isn't nil
<ide> attr_reader :new_linked_keg_record
<ide>
<del> def initialize(formula)
<add> def self.needs_migration?(formula)
<add> oldname = formula.oldname
<add> return false unless oldname
<add> oldname_rack = HOMEBREW_CELLAR/oldname
<add> return false if oldname_rack.symlink?
<add> return false unless oldname_rack.directory?
<add> true
<add> end
<add>
<add> def self.migrate_if_needed(formula)
<add> return unless Migrator.needs_migration?(formula)
<add> begin
<add> migrator = Migrator.new(formula, force: true)
<add> migrator.migrate
<add> rescue Exception => e
<add> onoe e
<add> end
<add> end
<add>
<add> def initialize(formula, force: ARGV.force?)
<ide> @oldname = formula.oldname
<ide> @newname = formula.name
<ide> raise MigratorNoOldnameError, formula unless oldname
<ide> def initialize(formula)
<ide> @old_tabs = old_cellar.subdirs.map { |d| Tab.for_keg(Keg.new(d)) }
<ide> @old_tap = old_tabs.first.tap
<ide>
<del> if !ARGV.force? && !from_same_taps?
<add> if !force && !from_same_taps?
<ide> raise MigratorDifferentTapsError.new(formula, old_tap)
<ide> end
<ide> | 1 |
Ruby | Ruby | fix example in thread_mattr_accessor documentation | b1589f671224adbb30eb54799483218376752411 | <ide><path>activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
<ide> def #{sym}=(obj)
<ide> # Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
<ide> #
<ide> # class Current
<del> # mattr_accessor :user, instance_accessor: false
<add> # thread_mattr_accessor :user, instance_accessor: false
<ide> # end
<ide> #
<ide> # Current.new.user = "DHH" # => NoMethodError | 1 |
Mixed | Javascript | add missing deprecation code | a67b73b9aee64d74dba52029b57c7d2b97b9e149 | <ide><path>doc/api/deprecations.md
<ide> Type: Documentation-only
<ide> Prefer [`response.socket`][] over [`response.connection`] and
<ide> [`request.socket`][] over [`request.connection`].
<ide>
<del><a id="DEP0XXX"></a>
<del>### DEP0XXX: process._tickCallback
<add><a id="DEP0134"></a>
<add>### DEP0134: process._tickCallback
<ide> <!-- YAML
<ide> changes:
<ide> - version: REPLACEME
<ide><path>lib/internal/bootstrap/pre_execution.js
<ide> function initializeDeprecations() {
<ide>
<ide> process._tickCallback = deprecate(process._tickCallback,
<ide> 'process._tickCallback() is deprecated',
<del> 'DEP0XXX');
<add> 'DEP0134');
<ide> }
<ide>
<ide> // Create global.process and global.Buffer as getters so that we have a | 2 |
Text | Text | add initial contributing.md | ed824469c15301584f479c17471f121ec69b92e8 | <ide><path>CONTRIBUTING.md
<add># :rotating_light: Contributing to Atom :rotating_light:
<add>
<add>## Issues
<add> * Include screenshots and animated GIFs whenever possible, they are immensely
<add> helpful
<add> * Include the behavior you expected to happen and other places you've seen
<add> that behavior such as Emacs, vi, Xcode, etc.
<add> * Check the Console app for stack traces to include if reporting a crash
<add> * Check the Dev tools (`alt-cmd-i`) for errors and stack traces to include
<add>
<add>## Code
<add> * Follow the [JavaScript](https://github.com/styleguide/javascript),
<add> [CSS](https://github.com/styleguide/css),
<add> and [Objective-C](https://github.com/github/objective-c-conventions)
<add> styleguides
<add> * Include thoughtfully worded [Jasmine](http://pivotal.github.com/jasmine/)
<add> specs
<add> * New packages go in `src/packages/`
<add> * Add 3rd-party packages by submoduling in `vendor/packages/`
<add> * Commit messages are in the present tense | 1 |
Text | Text | simplify collaborator_guide.md instructions | a72bfb94ddb27b1c8cff229702f32df46233506c | <ide><path>COLLABORATOR_GUIDE.md
<ide> The TSC should serve as the final arbiter where required.
<ide> one](https://github.com/nodejs/node/commit/b636ba8186) if unsure exactly how
<ide> to format your commit messages.
<ide>
<del>Additionally:
<add>Check PRs from new contributors to make sure the person's name and email address
<add>are correct before merging.
<ide>
<del>* Double check PRs to make sure the person's _full name_ and email
<del> address are correct before merging.
<del>* All commits should be self-contained (meaning every commit should pass all
<del> tests). This makes it much easier when bisecting to find a breaking change.
<add>All commits should be self-contained, meaning every commit should pass all
<add>tests. This makes it much easier when bisecting to find a breaking change.
<ide>
<ide> ### Using `git-node`
<ide> | 1 |
Java | Java | add reset() to mockrestserviceserver | 4e8754ea87c1f52c589049eb123cc5e0e897639f | <ide><path>spring-test/src/main/java/org/springframework/test/web/client/AbstractRequestExpectationManager.java
<ide> protected AssertionError createUnexpectedRequestError(ClientHttpRequest request)
<ide> return new AssertionError(message + getRequestDetails());
<ide> }
<ide>
<add> @Override
<add> public void reset() {
<add> this.expectations.clear();
<add> this.requests.clear();
<add> }
<add>
<ide>
<ide> /**
<ide> * Helper class to manage a group of request expectations. It helps with
<ide> public RequestExpectation findExpectation(ClientHttpRequest request) throws IOEx
<ide> }
<ide> return null;
<ide> }
<add>
<add> public void reset() {
<add> this.expectations.clear();
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/MockRestServiceServer.java
<ide> public void verify() {
<ide> this.expectationManager.verify();
<ide> }
<ide>
<add> /**
<add> * Reset the internal state removing all expectations and recorded requests.
<add> */
<add> public void reset() {
<add> this.expectationManager.reset();
<add> }
<add>
<ide>
<ide> /**
<ide> * Return a builder for a {@code MockRestServiceServer} that should be used
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/RequestExpectationManager.java
<ide> public interface RequestExpectationManager {
<ide> */
<ide> void verify();
<ide>
<add> /**
<add> * Reset the internal state removing all expectations and recorded requests.
<add> */
<add> void reset();
<add>
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/SimpleRequestExpectationManager.java
<ide> private RequestExpectation next(ClientHttpRequest request) {
<ide> throw createUnexpectedRequestError(request);
<ide> }
<ide>
<add> @Override
<add> public void reset() {
<add> super.reset();
<add> this.expectationIterator = null;
<add> this.repeatExpectations.reset();
<add> }
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/UnorderedRequestExpectationManager.java
<ide> public ClientHttpResponse validateRequestInternal(ClientHttpRequest request) thr
<ide> throw createUnexpectedRequestError(request);
<ide> }
<ide>
<add> @Override
<add> public void reset() {
<add> super.reset();
<add> this.remainingExpectations.reset();
<add> }
<add>
<ide> }
<ide><path>spring-test/src/test/java/org/springframework/test/web/client/MockRestServiceServerTests.java
<ide> */
<ide> package org.springframework.test.web.client;
<ide>
<add>import org.hamcrest.Matchers;
<ide> import org.junit.Test;
<ide>
<ide> import org.springframework.test.web.client.MockRestServiceServer.MockRestServiceServerBuilder;
<ide> import org.springframework.web.client.RestTemplate;
<ide>
<add>import static org.junit.Assert.assertTrue;
<add>import static org.junit.Assert.fail;
<ide> import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
<ide> import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
<ide>
<ide> */
<ide> public class MockRestServiceServerTests {
<ide>
<add> private RestTemplate restTemplate = new RestTemplate();
<add>
<add>
<ide> @Test
<ide> public void buildMultipleTimes() throws Exception {
<del>
<del> RestTemplate restTemplate = new RestTemplate();
<del> MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(restTemplate);
<add> MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(this.restTemplate);
<ide>
<ide> MockRestServiceServer server = builder.build();
<ide> server.expect(requestTo("/foo")).andRespond(withSuccess());
<del> restTemplate.getForObject("/foo", Void.class);
<add> this.restTemplate.getForObject("/foo", Void.class);
<ide> server.verify();
<ide>
<ide> server = builder.ignoreExpectOrder(true).build();
<ide> server.expect(requestTo("/foo")).andRespond(withSuccess());
<ide> server.expect(requestTo("/bar")).andRespond(withSuccess());
<del> restTemplate.getForObject("/bar", Void.class);
<del> restTemplate.getForObject("/foo", Void.class);
<add> this.restTemplate.getForObject("/bar", Void.class);
<add> this.restTemplate.getForObject("/foo", Void.class);
<ide> server.verify();
<ide>
<ide> server = builder.build();
<ide> server.expect(requestTo("/bar")).andRespond(withSuccess());
<del> restTemplate.getForObject("/bar", Void.class);
<add> this.restTemplate.getForObject("/bar", Void.class);
<add> server.verify();
<add> }
<add>
<add> @Test
<add> public void resetAndReuseServer() throws Exception {
<add> MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build();
<add>
<add> server.expect(requestTo("/foo")).andRespond(withSuccess());
<add> this.restTemplate.getForObject("/foo", Void.class);
<add> server.verify();
<add> server.reset();
<add>
<add> server.expect(requestTo("/bar")).andRespond(withSuccess());
<add> this.restTemplate.getForObject("/bar", Void.class);
<add> server.verify();
<add> }
<add>
<add> @Test
<add> public void resetAndReuseServerWithUnorderedExpectationManager() throws Exception {
<add> MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate)
<add> .ignoreExpectOrder(true).build();
<add>
<add> server.expect(requestTo("/foo")).andRespond(withSuccess());
<add> this.restTemplate.getForObject("/foo", Void.class);
<add> server.verify();
<add> server.reset();
<add>
<add> server.expect(requestTo("/foo")).andRespond(withSuccess());
<add> server.expect(requestTo("/bar")).andRespond(withSuccess());
<add> this.restTemplate.getForObject("/bar", Void.class);
<add> this.restTemplate.getForObject("/foo", Void.class);
<ide> server.verify();
<ide> }
<ide> | 6 |
Java | Java | add tests for stringutils split() method | f1827cb1f94b365f31531002a6bf1aa43c51fe9e | <ide><path>spring-core/src/test/java/org/springframework/util/StringUtilsTests.java
<ide> void invalidLocaleWithLanguageTag() {
<ide> assertThat(StringUtils.parseLocale("")).isNull();
<ide> }
<ide>
<add> @Test
<add> void split() {
<add> assertThat(StringUtils.split("Hello, world", ",")).isEqualTo(new String[]{"Hello", " world"});
<add> assertThat(StringUtils.split(",Hello world", ",")).isEqualTo(new String[]{"", "Hello world"});
<add> assertThat(StringUtils.split("Hello world,", ",")).isEqualTo(new String[]{"Hello world", ""});
<add> assertThat(StringUtils.split("Hello, world,", ",")).isEqualTo(new String[]{"Hello", " world,"});
<add> }
<add>
<add> @Test
<add> void splitWithEmptyString() {
<add> assertThat(StringUtils.split("Hello, world", "")).isNull();
<add> assertThat(StringUtils.split("", ",")).isNull();
<add> assertThat(StringUtils.split(null, ",")).isNull();
<add> assertThat(StringUtils.split("Hello, world", null)).isNull();
<add> assertThat(StringUtils.split(null, null)).isNull();
<add> }
<ide> } | 1 |
Javascript | Javascript | fix ping callback | bb546ac001356da4dffd762c3f847660210f3064 | <ide><path>lib/internal/http2/core.js
<ide> const proxySocketHandler = {
<ide> // data received on the PING acknowlegement.
<ide> function pingCallback(cb) {
<ide> return function pingCallback(ack, duration, payload) {
<del> const err = ack ? null : new ERR_HTTP2_PING_CANCEL();
<del> cb(err, duration, payload);
<add> if (ack) {
<add> cb(null, duration, payload);
<add> } else {
<add> cb(new ERR_HTTP2_PING_CANCEL());
<add> }
<ide> };
<ide> }
<ide> | 1 |
Javascript | Javascript | allow zero when parsing http req/s | b888bfe81d39a0b528ca371c7fa1376111f9e667 | <ide><path>benchmark/_http-benchmarkers.js
<ide> WrkBenchmarker.prototype.create = function(options) {
<ide> WrkBenchmarker.prototype.processResults = function(output) {
<ide> const match = output.match(this.regexp);
<ide> const result = match && +match[1];
<del> if (!result) {
<add> if (!isFinite(result)) {
<ide> return undefined;
<ide> } else {
<ide> return result;
<ide> exports.run = function(options, callback) {
<ide> }
<ide>
<ide> const result = benchmarker.processResults(stdout);
<del> if (!result) {
<add> if (result === undefined) {
<ide> callback(new Error(`${options.benchmarker} produced strange output: ` +
<ide> stdout, code));
<ide> return; | 1 |
Javascript | Javascript | remove string argument to strictequal() | 5977f28ebf1855580a2eef46ec609acc6ef5ca07 | <ide><path>test/sequential/test-crypto-timing-safe-equal.js
<ide> if (!common.hasCrypto)
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<add>// 'should consider equal strings to be equal'
<ide> assert.strictEqual(
<ide> crypto.timingSafeEqual(Buffer.from('foo'), Buffer.from('foo')),
<del> true,
<del> 'should consider equal strings to be equal'
<add> true
<ide> );
<ide>
<add>// 'should consider unequal strings to be unequal'
<ide> assert.strictEqual(
<ide> crypto.timingSafeEqual(Buffer.from('foo'), Buffer.from('bar')),
<del> false,
<del> 'should consider unequal strings to be unequal'
<add> false
<ide> );
<ide>
<ide> common.expectsError( | 1 |
Javascript | Javascript | preserve process.env after test-init exec | 7592615aaa1eb7a18dca1b9ab70865bbfd99a80d | <ide><path>test/simple/test-init.js
<ide> // being in the test folder
<ide> process.chdir(__dirname);
<ide>
<del> child.exec(process.execPath + ' test-init', {env: {'TEST_INIT': 1}},
<add> // slow but simple
<add> var envCopy = JSON.parse(JSON.stringify(process.env));
<add> envCopy.TEST_INIT = 1;
<add>
<add> child.exec(process.execPath + ' test-init', {env: envCopy},
<ide> function(err, stdout, stderr) {
<ide> assert.equal(stdout, 'Loaded successfully!',
<ide> '`node test-init` failed!');
<ide> });
<del> child.exec(process.execPath + ' test-init.js', {env: {'TEST_INIT': 1}},
<add> child.exec(process.execPath + ' test-init.js', {env: envCopy},
<ide> function(err, stdout, stderr) {
<ide> assert.equal(stdout, 'Loaded successfully!',
<ide> '`node test-init.js` failed!');
<ide> // test-init-index is in fixtures dir as requested by ry, so go there
<ide> process.chdir(common.fixturesDir);
<ide>
<del> child.exec(process.execPath + ' test-init-index', {env: {'TEST_INIT': 1}},
<add> child.exec(process.execPath + ' test-init-index', {env: envCopy},
<ide> function(err, stdout, stderr) {
<ide> assert.equal(stdout, 'Loaded successfully!',
<ide> '`node test-init-index failed!');
<ide> // expected in node
<ide> process.chdir(common.fixturesDir + '/test-init-native/');
<ide>
<del> child.exec(process.execPath + ' fs', {env: {'TEST_INIT': 1}},
<add> child.exec(process.execPath + ' fs', {env: envCopy},
<ide> function(err, stdout, stderr) {
<ide> assert.equal(stdout, 'fs loaded successfully',
<ide> '`node fs` failed!'); | 1 |
Text | Text | fix broken link | 927a11976012975c8d1c7beb1fbd388cc684c280 | <ide><path>docs/faq/Reducers.md
<ide>
<ide> ## Table of Contents
<ide>
<del>- [How do I share state between two reducers? Do I have to use combineReducers?](#reducers-share-state)
<del>- [Do I have to use the switch statement to handle actions?](#reducers-use-switch)
<add>- [How do I share state between two reducers? Do I have to use combineReducers?](#reducers-share-state)
<add>- [Do I have to use the switch statement to handle actions?](#reducers-use-switch)
<ide>
<ide>
<ide>
<ide> Many users later want to try to share data between two reducers, but find that `
<ide>
<ide> * If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
<ide> * You may need to write some custom functions for handling some of these actions. This may require replacing `combineReducers` with your own top-level reducer function. You can also use a utility such as [reduce-reducers](https://github.com/acdlite/reduce-reducers) to run `combineReducers` to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.
<del>* [Async action creators](advanced/AsyncActions.md) such as [redux-thunk](https://github.com/gaearon/redux-thunk) have access to the entire state through `getState()`. An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.
<add>* [Async action creators](/docs/advanced/AsyncActions.md#async-action-creators) such as [redux-thunk](https://github.com/gaearon/redux-thunk) have access to the entire state through `getState()`. An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.
<ide>
<ide> In general, remember that reducers are just functions—you can organize them and subdivide them any way you want, and you are encouraged to break them down into smaller, reusable functions (“reducer composition”). While you do so, you may pass a custom third argument from a parent reducer if a child reducer needs additional data to calculate its next state. You just need to make sure that together they follow the basic rules of reducers: `(state, action) => newState`, and update state immutably rather than mutating it directly.
<ide> | 1 |
Ruby | Ruby | remove unnecessary rescue-all exception handling | 471502bc06e8dde06618b30885d21d10c53528e5 | <ide><path>Library/Contributions/cmd/brew-ls-taps.rb
<ide> require 'vendor/multi_json'
<ide>
<ide> GitHub.open "https://api.github.com/legacy/repos/search/homebrew" do |f|
<del> begin
<del> MultiJson.decode(f.read)["repositories"].each do |repo|
<del> if repo['name'] =~ /^homebrew-(\S+)$/
<del> puts tap = if repo['username'] == "Homebrew"
<del> "homebrew/#{$1}"
<del> else
<del> repo['username']+"/"+$1
<del> end
<add> MultiJson.decode(f.read)["repositories"].each do |repo|
<add> if repo['name'] =~ /^homebrew-(\S+)$/
<add> puts tap = if repo['username'] == "Homebrew"
<add> "homebrew/#{$1}"
<add> else
<add> repo['username']+"/"+$1
<ide> end
<ide> end
<del> rescue
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/search.rb
<ide> def search_tap user, repo, rx
<ide>
<ide> results = []
<ide> GitHub.open "https://api.github.com/repos/#{user}/homebrew-#{repo}/git/trees/HEAD?recursive=1" do |f|
<del> begin
<del> user.downcase! if user == "Homebrew" # special handling for the Homebrew organization
<del> MultiJson.decode(f.read)["tree"].map{ |hash| hash['path'] }.compact.each do |file|
<del> name = File.basename(file, '.rb')
<del> if file =~ /\.rb$/ and name =~ rx
<del> results << "#{user}/#{repo}/#{name}"
<del> $found += 1
<del> end
<add> user.downcase! if user == "Homebrew" # special handling for the Homebrew organization
<add> MultiJson.decode(f.read)["tree"].map{ |hash| hash['path'] }.compact.each do |file|
<add> name = File.basename(file, '.rb')
<add> if file =~ /\.rb$/ and name =~ rx
<add> results << "#{user}/#{repo}/#{name}"
<add> $found += 1
<ide> end
<del> rescue
<ide> end
<ide> end
<ide> results
<ide><path>Library/Homebrew/utils.rb
<ide> def issues_for_formula name
<ide>
<ide> uri = URI.parse("https://api.github.com/legacy/issues/search/mxcl/homebrew/open/#{name}")
<ide>
<del> open uri do |f|
<del> begin
<del> MultiJson.decode(f.read)['issues'].each do |issue|
<del> # don't include issues that just refer to the tool in their body
<del> issues << issue['html_url'] if issue['title'].include? name
<del> end
<del> rescue
<add> GitHub.open uri do |f|
<add> MultiJson.decode(f.read)['issues'].each do |issue|
<add> # don't include issues that just refer to the tool in their body
<add> issues << issue['html_url'] if issue['title'].include? name
<ide> end
<ide> end
<ide>
<ide> def find_pull_requests rx
<ide> uri = URI.parse("https://api.github.com/legacy/issues/search/mxcl/homebrew/open/#{query}")
<ide>
<ide> GitHub.open uri do |f|
<del> begin
<del> MultiJson.decode(f.read)['issues'].each do |pull|
<del> yield pull['pull_request_url'] if rx.match pull['title'] and pull['pull_request_url']
<del> end
<del> rescue
<add> MultiJson.decode(f.read)['issues'].each do |pull|
<add> yield pull['pull_request_url'] if rx.match pull['title'] and pull['pull_request_url']
<ide> end
<ide> end
<ide> end | 3 |
Ruby | Ruby | remove unused modules from strongparameters | 93e0f975e9dbf2bc766b5e58fcf792b577bacd1f | <ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb
<ide> require "active_support/core_ext/array/wrap"
<ide> require "active_support/core_ext/string/filters"
<ide> require "active_support/core_ext/object/to_query"
<del>require "active_support/rescuable"
<ide> require "action_dispatch/http/upload"
<ide> require "rack/test"
<ide> require "stringio"
<ide> def initialize_copy(source)
<ide> # See ActionController::Parameters.require and ActionController::Parameters.permit
<ide> # for more information.
<ide> module StrongParameters
<del> extend ActiveSupport::Concern
<del> include ActiveSupport::Rescuable
<del>
<ide> # Returns a new ActionController::Parameters object that
<ide> # has been instantiated with the <tt>request.parameters</tt>.
<ide> def params | 1 |
Go | Go | return proper error types on sandbox creation | 2e88dfa4062e777c9dec28cfbb8258250dbba3eb | <ide><path>libnetwork/controller.go
<ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (s
<ide> // If not a stub, then we already have a complete sandbox.
<ide> if !s.isStub {
<ide> c.Unlock()
<del> return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, s)
<add> return nil, types.ForbiddenErrorf("container %s is already present: %v", containerID, s)
<ide> }
<ide>
<ide> // We already have a stub sandbox from the
<ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (s
<ide> c.Lock()
<ide> if sb.ingress && c.ingressSandbox != nil {
<ide> c.Unlock()
<del> return nil, fmt.Errorf("ingress sandbox already present")
<add> return nil, types.ForbiddenErrorf("ingress sandbox already present")
<ide> }
<ide>
<ide> if sb.ingress { | 1 |
Javascript | Javascript | add spec for blobmodule | 342c81d75448e760ae32d62ebd9004bf6eeeff46 | <ide><path>Libraries/Blob/BlobManager.js
<ide>
<ide> const Blob = require('./Blob');
<ide> const BlobRegistry = require('./BlobRegistry');
<del>const {BlobModule} = require('../BatchedBridge/NativeModules');
<add>import NativeBlobModule from './NativeBlobModule';
<add>import invariant from 'invariant';
<ide>
<ide> import type {BlobData, BlobOptions, BlobCollector} from './BlobTypes';
<ide>
<ide> class BlobManager {
<ide> /**
<ide> * If the native blob module is available.
<ide> */
<del> static isAvailable = !!BlobModule;
<add> static isAvailable = !!NativeBlobModule;
<ide>
<ide> /**
<ide> * Create blob from existing array of blobs.
<ide> class BlobManager {
<ide> parts: Array<Blob | string>,
<ide> options?: BlobOptions,
<ide> ): Blob {
<add> invariant(NativeBlobModule, 'NativeBlobModule is available.');
<add>
<ide> const blobId = uuidv4();
<ide> const items = parts.map(part => {
<ide> if (
<ide> class BlobManager {
<ide> }
<ide> }, 0);
<ide>
<del> BlobModule.createFromParts(items, blobId);
<add> NativeBlobModule.createFromParts(items, blobId);
<ide>
<ide> return BlobManager.createFromOptions({
<ide> blobId,
<ide> class BlobManager {
<ide> * Deallocate resources for a blob.
<ide> */
<ide> static release(blobId: string): void {
<add> invariant(NativeBlobModule, 'NativeBlobModule is available.');
<add>
<ide> BlobRegistry.unregister(blobId);
<ide> if (BlobRegistry.has(blobId)) {
<ide> return;
<ide> }
<del> BlobModule.release(blobId);
<add> NativeBlobModule.release(blobId);
<ide> }
<ide>
<ide> /**
<ide> * Inject the blob content handler in the networking module to support blob
<ide> * requests and responses.
<ide> */
<ide> static addNetworkingHandler(): void {
<del> BlobModule.addNetworkingHandler();
<add> invariant(NativeBlobModule, 'NativeBlobModule is available.');
<add>
<add> NativeBlobModule.addNetworkingHandler();
<ide> }
<ide>
<ide> /**
<ide> * Indicate the websocket should return a blob for incoming binary
<ide> * messages.
<ide> */
<ide> static addWebSocketHandler(socketId: number): void {
<del> BlobModule.addWebSocketHandler(socketId);
<add> invariant(NativeBlobModule, 'NativeBlobModule is available.');
<add>
<add> NativeBlobModule.addWebSocketHandler(socketId);
<ide> }
<ide>
<ide> /**
<ide> * Indicate the websocket should no longer return a blob for incoming
<ide> * binary messages.
<ide> */
<ide> static removeWebSocketHandler(socketId: number): void {
<del> BlobModule.removeWebSocketHandler(socketId);
<add> invariant(NativeBlobModule, 'NativeBlobModule is available.');
<add>
<add> NativeBlobModule.removeWebSocketHandler(socketId);
<ide> }
<ide>
<ide> /**
<ide> * Send a blob message to a websocket.
<ide> */
<ide> static sendOverSocket(blob: Blob, socketId: number): void {
<del> BlobModule.sendOverSocket(blob.data, socketId);
<add> invariant(NativeBlobModule, 'NativeBlobModule is available.');
<add>
<add> NativeBlobModule.sendOverSocket(blob.data, socketId);
<ide> }
<ide> }
<ide>
<ide><path>Libraries/Blob/NativeBlobModule.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>export interface Spec extends TurboModule {
<add> +getConstants: () => {|BLOB_URI_SCHEME: string, BLOB_URI_HOST: ?string|};
<add> +addNetworkingHandler: () => void;
<add> +addWebSocketHandler: (id: number) => void;
<add> +removeWebSocketHandler: (id: number) => void;
<add> +sendOverSocket: (blob: Object, id: number) => void;
<add> +createFromParts: (parts: Array<Object>, blobId: string) => void;
<add> +release: (blobId: string) => void;
<add>}
<add>
<add>export default TurboModuleRegistry.get<Spec>('BlobModule');
<ide><path>Libraries/Blob/URL.js
<ide>
<ide> const Blob = require('./Blob');
<ide>
<del>const {BlobModule} = require('../BatchedBridge/NativeModules');
<add>import NativeBlobModule from './NativeBlobModule';
<ide>
<ide> let BLOB_URL_PREFIX = null;
<ide>
<del>if (BlobModule && typeof BlobModule.BLOB_URI_SCHEME === 'string') {
<del> BLOB_URL_PREFIX = BlobModule.BLOB_URI_SCHEME + ':';
<del> if (typeof BlobModule.BLOB_URI_HOST === 'string') {
<del> BLOB_URL_PREFIX += `//${BlobModule.BLOB_URI_HOST}/`;
<add>if (
<add> NativeBlobModule &&
<add> typeof NativeBlobModule.getConstants().BLOB_URI_SCHEME === 'string'
<add>) {
<add> const constants = NativeBlobModule.getConstants();
<add> BLOB_URL_PREFIX = constants.BLOB_URI_SCHEME + ':';
<add> if (typeof constants.BLOB_URI_HOST === 'string') {
<add> BLOB_URL_PREFIX += `//${constants.BLOB_URI_HOST}/`;
<ide> }
<ide> }
<ide>
<ide><path>jest/setup.js
<ide> const mockNativeModules = {
<ide> },
<ide> },
<ide> BlobModule: {
<del> BLOB_URI_SCHEME: 'content',
<del> BLOB_URI_HOST: null,
<add> getConstants: () => ({BLOB_URI_SCHEME: 'content', BLOB_URI_HOST: null}),
<ide> addNetworkingHandler: jest.fn(),
<ide> enableBlobSupport: jest.fn(),
<ide> disableBlobSupport: jest.fn(), | 4 |
Ruby | Ruby | create custom matchers for “valid symlink” | 6cd36428505b1b3548b1e15fe7e0a850b2e2aeaa | <ide><path>Library/Homebrew/cask/spec/cask/artifact/binary_spec.rb
<ide> shutup do
<ide> Hbc::Artifact::Binary.new(cask).install_phase
<ide> end
<del> expect(FileHelper.valid_alias?(expected_path)).to be true
<add> expect(expected_path).to be_a_valid_symlink
<ide> end
<ide>
<ide> it "avoids clobbering an existing binary by linking over it" do
<ide> Hbc::Artifact::Binary.new(cask).install_phase
<ide> end
<ide>
<del> expect(FileHelper.valid_alias?(expected_path)).to be true
<add> expect(expected_path).to be_a_valid_symlink
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/spec/spec_helper.rb
<ide> RSpec.configure do |config|
<ide> config.order = :random
<ide> config.include(Test::Helper::Shutup)
<add> config.include(FileMatchers)
<ide> end
<ide><path>Library/Homebrew/cask/spec/support/file_helper.rb
<del>module FileHelper
<del> module_function
<del>
<del> def valid_alias?(candidate)
<del> return false unless candidate.symlink?
<del> candidate.readlink.exist?
<del> end
<del>end
<ide><path>Library/Homebrew/cask/spec/support/file_matchers.rb
<add>module FileMatchers
<add> extend RSpec::Matchers::DSL
<add>
<add> matcher :be_a_valid_symlink do
<add> match do |path|
<add> path.symlink? && path.readlink.exist?
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/cask/test/cask/artifact/suite_test.rb
<ide> end
<ide>
<ide> target_path.must_be :directory?
<del> TestHelper.valid_alias?(target_path).must_equal false
<add> TestHelper.valid_symlink?(target_path).must_equal false
<ide> source_path.wont_be :exist?
<ide> end
<ide>
<ide><path>Library/Homebrew/cask/test/test_helper.rb
<ide> def self.local_binary_url(name)
<ide> "file://" + local_binary_path(name)
<ide> end
<ide>
<del> def self.valid_alias?(candidate)
<add> def self.valid_symlink?(candidate)
<ide> return false unless candidate.symlink?
<ide> candidate.readlink.exist?
<ide> end | 6 |
Javascript | Javascript | use fresh maps when not available | 5601c5618599d035340567a04221c0c4f47c7dce | <ide><path>lib/node/NodeWatchFileSystem.js
<ide> class NodeWatchFileSystem {
<ide> getFileTimeInfoEntries: () => {
<ide> if (fileMap) return fileMap;
<ide> if (this.watcher) {
<del> this.watcher.getTimeInfoEntries(fileMap, directoryMap);
<add> this.watcher.getTimeInfoEntries(
<add> (fileMap = new Map()),
<add> (directoryMap = new Map())
<add> );
<ide> return fileMap;
<ide> }
<ide> return new Map();
<ide> },
<ide> getContextTimeInfoEntries: () => {
<ide> if (directoryMap) return directoryMap;
<ide> if (this.watcher) {
<del> this.watcher.getTimeInfoEntries(fileMap, directoryMap);
<add> this.watcher.getTimeInfoEntries(
<add> (fileMap = new Map()),
<add> (directoryMap = new Map())
<add> );
<ide> return directoryMap;
<ide> }
<ide> return new Map(); | 1 |
Javascript | Javascript | fix regression on randomfillsync | 4cbcfaee9c11f242107f21b01c1a835f9c36ac86 | <ide><path>lib/internal/crypto/random.js
<ide> function randomFillSync(buf, offset = 0, size) {
<ide>
<ide> const job = new RandomBytesJob(
<ide> kCryptoJobSync,
<del> buf.buffer || buf,
<add> buf,
<ide> offset,
<ide> size);
<ide>
<ide><path>test/parallel/test-crypto-randomfillsync-regression.js
<add>'use strict';
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>const { randomFillSync } = require('crypto');
<add>const { notStrictEqual } = require('assert');
<add>
<add>const ab = new ArrayBuffer(20);
<add>const buf = Buffer.from(ab, 10);
<add>
<add>const before = buf.toString('hex');
<add>
<add>randomFillSync(buf);
<add>
<add>const after = buf.toString('hex');
<add>
<add>notStrictEqual(before, after); | 2 |
Python | Python | upgrade version number of trunk and add 'math' | 2aba0e2b842867f7d5c5bb48be1b15e709903828 | <ide><path>numpy/lib/__init__.py
<ide> from utils import *
<ide> from arraysetops import *
<ide>
<del>__all__ = []
<add>__all__ = ['math']
<ide> __all__ += type_check.__all__
<ide> __all__ += index_tricks.__all__
<ide> __all__ += function_base.__all__
<ide><path>numpy/version.py
<del>version='0.9.5'
<add>version='0.9.6'
<ide>
<ide> import os
<ide> svn_version_file = os.path.join(os.path.dirname(__file__), | 2 |
Ruby | Ruby | remove unused parser option required_for | 1d5c668110b81e417382ccb78dc09e19c2863cc5 | <ide><path>Library/Homebrew/cli/parser.rb
<ide> def initialize(&block)
<ide> generate_banner
<ide> end
<ide>
<del> def switch(*names, description: nil, replacement: nil, env: nil, required_for: nil, depends_on: nil,
<add> def switch(*names, description: nil, replacement: nil, env: nil, depends_on: nil,
<ide> method: :on, hidden: false)
<ide> global_switch = names.first.is_a?(Symbol)
<ide> return if global_switch
<ide> def switch(*names, description: nil, replacement: nil, env: nil, required_for: n
<ide> end
<ide>
<ide> names.each do |name|
<del> set_constraints(name, required_for: required_for, depends_on: depends_on)
<add> set_constraints(name, depends_on: depends_on)
<ide> end
<ide>
<ide> env_value = env?(env)
<ide> def comma_array(name, description: nil, hidden: false)
<ide> end
<ide> end
<ide>
<del> def flag(*names, description: nil, replacement: nil, required_for: nil,
<del> depends_on: nil, hidden: false)
<add> def flag(*names, description: nil, replacement: nil, depends_on: nil, hidden: false)
<ide> required, flag_type = if names.any? { |name| name.end_with? "=" }
<ide> [OptionParser::REQUIRED_ARGUMENT, :required_flag]
<ide> else
<ide> def flag(*names, description: nil, replacement: nil, required_for: nil,
<ide> end
<ide>
<ide> names.each do |name|
<del> set_constraints(name, required_for: required_for, depends_on: depends_on)
<add> set_constraints(name, depends_on: depends_on)
<ide> end
<ide> end
<ide>
<ide> def wrap_option_desc(desc)
<ide> Formatter.format_help_text(desc, width: OPTION_DESC_WIDTH).split("\n")
<ide> end
<ide>
<del> def set_constraints(name, depends_on:, required_for:)
<del> secondary = option_to_name(name)
<del> unless required_for.nil?
<del> primary = option_to_name(required_for)
<del> @constraints << [primary, secondary, :mandatory]
<del> end
<del>
<add> def set_constraints(name, depends_on:)
<ide> return if depends_on.nil?
<ide>
<ide> primary = option_to_name(depends_on)
<del> @constraints << [primary, secondary, :optional]
<add> secondary = option_to_name(name)
<add> @constraints << [primary, secondary]
<ide> end
<ide>
<ide> def check_constraints
<del> @constraints.each do |primary, secondary, constraint_type|
<add> @constraints.each do |primary, secondary|
<ide> primary_passed = option_passed?(primary)
<ide> secondary_passed = option_passed?(secondary)
<ide>
<add> next if !secondary_passed || (primary_passed && secondary_passed)
<add>
<ide> primary = name_to_option(primary)
<ide> secondary = name_to_option(secondary)
<ide>
<del> if :mandatory.equal?(constraint_type) && primary_passed && !secondary_passed
<del> raise OptionConstraintError.new(primary, secondary)
<del> end
<del> raise OptionConstraintError.new(primary, secondary, missing: true) if secondary_passed && !primary_passed
<add> raise OptionConstraintError.new(primary, secondary, missing: true)
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/test/cli/parser_spec.rb
<ide> subject(:parser) {
<ide> described_class.new do
<ide> flag "--flag1="
<add> flag "--flag2=", depends_on: "--flag1="
<ide> flag "--flag3="
<del> flag "--flag2=", required_for: "--flag1="
<del> flag "--flag4=", depends_on: "--flag3="
<ide>
<ide> conflicts "--flag1=", "--flag3="
<ide> end
<ide> }
<ide>
<del> it "raises exception on required_for constraint violation" do
<del> expect { parser.parse(["--flag1=flag1"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
<del> end
<del>
<ide> it "raises exception on depends_on constraint violation" do
<ide> expect { parser.parse(["--flag2=flag2"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
<del> expect { parser.parse(["--flag4=flag4"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
<ide> end
<ide>
<ide> it "raises exception for conflict violation" do
<ide> described_class.new do
<ide> switch "-a", "--switch-a", env: "switch_a"
<ide> switch "-b", "--switch-b", env: "switch_b"
<del> switch "--switch-c", required_for: "--switch-a"
<del> switch "--switch-d", depends_on: "--switch-b"
<add> switch "--switch-c", depends_on: "--switch-a"
<ide>
<ide> conflicts "--switch-a", "--switch-b"
<ide> end
<ide> }
<ide>
<del> it "raises exception on required_for constraint violation" do
<del> expect { parser.parse(["--switch-a"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
<del> end
<del>
<ide> it "raises exception on depends_on constraint violation" do
<ide> expect { parser.parse(["--switch-c"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
<del> expect { parser.parse(["--switch-d"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
<ide> end
<ide>
<ide> it "raises exception for conflict violation" do | 2 |
Go | Go | fix goroutine leak on logs -f with no output | 0c84604f5458bc38b793e5bcdf86624eef3e3184 | <ide><path>api/server/server.go
<ide> func (s *Server) getContainersLogs(version version.Version, w http.ResponseWrite
<ide> since = time.Unix(s, 0)
<ide> }
<ide>
<add> var closeNotifier <-chan bool
<add> if notifier, ok := w.(http.CloseNotifier); ok {
<add> closeNotifier = notifier.CloseNotify()
<add> }
<add>
<ide> logsConfig := &daemon.ContainerLogsConfig{
<ide> Follow: boolValue(r, "follow"),
<ide> Timestamps: boolValue(r, "timestamps"),
<ide> func (s *Server) getContainersLogs(version version.Version, w http.ResponseWrite
<ide> UseStdout: stdout,
<ide> UseStderr: stderr,
<ide> OutStream: ioutils.NewWriteFlusher(w),
<add> Stop: closeNotifier,
<ide> }
<ide>
<ide> if err := s.daemon.ContainerLogs(vars["name"], logsConfig); err != nil {
<ide><path>daemon/logs.go
<ide> type ContainerLogsConfig struct {
<ide> Since time.Time
<ide> UseStdout, UseStderr bool
<ide> OutStream io.Writer
<add> Stop <-chan bool
<ide> }
<ide>
<ide> func (daemon *Daemon) ContainerLogs(name string, config *ContainerLogsConfig) error {
<ide> func (daemon *Daemon) ContainerLogs(name string, config *ContainerLogsConfig) er
<ide> }
<ide>
<ide> if config.Follow && container.IsRunning() {
<del> chErr := make(chan error)
<add> chErrStderr := make(chan error)
<add> chErrStdout := make(chan error)
<ide> var stdoutPipe, stderrPipe io.ReadCloser
<ide>
<ide> // write an empty chunk of data (this is to ensure that the
<ide> func (daemon *Daemon) ContainerLogs(name string, config *ContainerLogsConfig) er
<ide> stdoutPipe = container.StdoutLogPipe()
<ide> go func() {
<ide> logrus.Debug("logs: stdout stream begin")
<del> chErr <- jsonlog.WriteLog(stdoutPipe, outStream, format, config.Since)
<add> chErrStdout <- jsonlog.WriteLog(stdoutPipe, outStream, format, config.Since)
<ide> logrus.Debug("logs: stdout stream end")
<ide> }()
<ide> }
<ide> if config.UseStderr {
<ide> stderrPipe = container.StderrLogPipe()
<ide> go func() {
<ide> logrus.Debug("logs: stderr stream begin")
<del> chErr <- jsonlog.WriteLog(stderrPipe, errStream, format, config.Since)
<add> chErrStderr <- jsonlog.WriteLog(stderrPipe, errStream, format, config.Since)
<ide> logrus.Debug("logs: stderr stream end")
<ide> }()
<ide> }
<ide>
<del> err = <-chErr
<del> if stdoutPipe != nil {
<del> stdoutPipe.Close()
<del> }
<del> if stderrPipe != nil {
<del> stderrPipe.Close()
<add> select {
<add> case err = <-chErrStderr:
<add> if stdoutPipe != nil {
<add> stdoutPipe.Close()
<add> <-chErrStdout
<add> }
<add> case err = <-chErrStdout:
<add> if stderrPipe != nil {
<add> stderrPipe.Close()
<add> <-chErrStderr
<add> }
<add> case <-config.Stop:
<add> if stdoutPipe != nil {
<add> stdoutPipe.Close()
<add> <-chErrStdout
<add> }
<add> if stderrPipe != nil {
<add> stderrPipe.Close()
<add> <-chErrStderr
<add> }
<add> return nil
<ide> }
<del> <-chErr // wait for 2nd goroutine to exit, otherwise bad things will happen
<ide>
<ide> if err != nil && err != io.EOF && err != io.ErrClosedPipe {
<ide> if e, ok := err.(*net.OpError); ok && e.Err != syscall.EPIPE {
<ide><path>integration-cli/docker_cli_logs_test.go
<ide> func (s *DockerSuite) TestLogsFollowGoroutinesWithStdout(c *check.C) {
<ide> }
<ide> }
<ide> }
<add>
<add>func (s *DockerSuite) TestLogsFollowGoroutinesNoOutput(c *check.C) {
<add> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true; do sleep 2; done")
<add> id := strings.TrimSpace(out)
<add> c.Assert(waitRun(id), check.IsNil)
<add>
<add> type info struct {
<add> NGoroutines int
<add> }
<add> getNGoroutines := func() int {
<add> var i info
<add> status, b, err := sockRequest("GET", "/info", nil)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(status, check.Equals, 200)
<add> c.Assert(json.Unmarshal(b, &i), check.IsNil)
<add> return i.NGoroutines
<add> }
<add>
<add> nroutines := getNGoroutines()
<add>
<add> cmd := exec.Command(dockerBinary, "logs", "-f", id)
<add> c.Assert(cmd.Start(), check.IsNil)
<add> time.Sleep(200 * time.Millisecond)
<add> c.Assert(cmd.Process.Kill(), check.IsNil)
<add>
<add> // NGoroutines is not updated right away, so we need to wait before failing
<add> t := time.After(30 * time.Second)
<add> for {
<add> select {
<add> case <-t:
<add> if n := getNGoroutines(); n > nroutines {
<add> c.Fatalf("leaked goroutines: expected less than or equal to %d, got: %d", nroutines, n)
<add> }
<add> default:
<add> if n := getNGoroutines(); n <= nroutines {
<add> return
<add> }
<add> time.Sleep(200 * time.Millisecond)
<add> }
<add> }
<add>} | 3 |
Text | Text | update main branch name in onboarding.md | 2af48c0ef84bb42bd62eadccf2b19c8b2588b9b5 | <ide><path>onboarding.md
<ide> onboarding session.
<ide> * Add the canonical nodejs repository as `upstream` remote:
<ide> * `git remote add upstream [email protected]:nodejs/node.git`
<ide> * To update from `upstream`:
<del> * `git checkout master`
<add> * `git checkout main`
<ide> * `git fetch upstream HEAD`
<ide> * `git reset --hard FETCH_HEAD`
<ide> * Make a new branch for each pull request you submit. | 1 |
PHP | PHP | unskip tests that now pass | c67eee98c8bf15f05eb19a368023ba24592e58bc | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testDateTimeRounding() {
<ide> * @return void
<ide> */
<ide> public function testDatetimeWithDefault() {
<del> $this->markTestIncomplete('Need to revisit soon.');
<ide> $result = $this->Form->dateTime('Contact.updated', array('value' => '2009-06-01 11:15:30'));
<ide> $this->assertRegExp('/<option[^<>]+value="2009"[^<>]+selected="selected"[^>]*>2009<\/option>/', $result);
<ide> $this->assertRegExp('/<option[^<>]+value="01"[^<>]+selected="selected"[^>]*>1<\/option>/', $result); | 1 |
Javascript | Javascript | fix version number processing | ed4cd6c3c6a30ddfead1cbcf48f2ac6adf60a802 | <ide><path>lib/grunt/utils.js
<ide> module.exports = {
<ide> .replace(/"NG_VERSION_FULL"/g, NG_VERSION.full)
<ide> .replace(/"NG_VERSION_MAJOR"/, NG_VERSION.major)
<ide> .replace(/"NG_VERSION_MINOR"/, NG_VERSION.minor)
<del> .replace(/"NG_VERSION_DOT"/, NG_VERSION.dot)
<add> .replace(/"NG_VERSION_DOT"/, NG_VERSION.patch)
<ide> .replace(/"NG_VERSION_CDN"/, NG_VERSION.cdn)
<del> .replace(/"NG_VERSION_CODENAME"/, NG_VERSION.codename);
<add> .replace(/"NG_VERSION_CODENAME"/, NG_VERSION.codeName);
<ide> if (strict !== false) processed = this.singleStrict(processed, '\n\n', true);
<ide> return processed;
<ide> }, | 1 |
Go | Go | reduce testruncommandwithtimeoutkilled flakiness | 797f630d2e3c9180848b1adb7fd6fa879f284165 | <ide><path>pkg/integration/cmd/command_test.go
<ide> func TestRunCommandWithTimeoutKilled(t *testing.T) {
<ide> t.Skip("Needs porting to Windows")
<ide> }
<ide>
<del> command := []string{"sh", "-c", "while true ; do echo 1 ; sleep .1 ; done"}
<del> result := RunCmd(Cmd{Command: command, Timeout: 500 * time.Millisecond})
<add> command := []string{"sh", "-c", "while true ; do echo 1 ; sleep .5 ; done"}
<add> result := RunCmd(Cmd{Command: command, Timeout: 1250 * time.Millisecond})
<ide> result.Assert(t, Expected{Timeout: true})
<ide>
<ide> ones := strings.Split(result.Stdout(), "\n")
<del> assert.Equal(t, len(ones), 6)
<add> assert.Equal(t, len(ones), 4)
<ide> }
<ide>
<ide> func TestRunCommandWithErrors(t *testing.T) { | 1 |
PHP | PHP | remove duplicate call to prepareresponse | bb83eeb94759803685813daf7436b3013f6b767d | <ide><path>src/Illuminate/Routing/Router.php
<ide> public function dispatch(Request $request)
<ide> {
<ide> $this->currentRequest = $request;
<ide>
<del> $response = $this->dispatchToRoute($request);
<del>
<del> return $this->prepareResponse($request, $response);
<add> return $this->dispatchToRoute($request);
<ide> }
<ide>
<ide> /** | 1 |
Go | Go | allow .dockerignore to ignore everything | 82ea6ed2bc33ac1ec2ad2bd8d4a098031dd77095 | <ide><path>api/client/build.go
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> }
<ide>
<ide> if err := utils.ValidateContextDirectory(root, excludes); err != nil {
<del> return fmt.Errorf("Error checking context is accessible: '%s'. Please check permissions and try again.", err)
<add> return fmt.Errorf("Error checking context: '%s'.", err)
<ide> }
<ide> options := &archive.TarOptions{
<ide> Compression: archive.Uncompressed,
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
<ide> c.Fatalf("output should've contained the string: no permission to read from but contained: %s", out)
<ide> }
<ide>
<del> if !strings.Contains(out, "Error checking context is accessible") {
<del> c.Fatalf("output should've contained the string: Error checking context is accessible")
<add> if !strings.Contains(out, "Error checking context") {
<add> c.Fatalf("output should've contained the string: Error checking context")
<ide> }
<ide> }
<ide> {
<ide> func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
<ide> c.Fatalf("output should've contained the string: can't access %s", out)
<ide> }
<ide>
<del> if !strings.Contains(out, "Error checking context is accessible") {
<del> c.Fatalf("output should've contained the string: Error checking context is accessible")
<add> if !strings.Contains(out, "Error checking context") {
<add> c.Fatalf("output should've contained the string: Error checking context\ngot:%s", out)
<ide> }
<ide>
<ide> }
<ide> func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
<ide> ".gitignore": "",
<ide> ".dockerignore": ".*\n",
<ide> })
<add> c.Assert(err, check.IsNil)
<ide> defer ctx.Close()
<del> if err != nil {
<add> if _, err = buildImageFromContext(name, ctx, true); err != nil {
<add> c.Fatal(err)
<add> }
<add>
<add> c.Assert(ctx.Add(".dockerfile", "*"), check.IsNil)
<add> if _, err = buildImageFromContext(name, ctx, true); err != nil {
<add> c.Fatal(err)
<add> }
<add>
<add> c.Assert(ctx.Add(".dockerfile", "."), check.IsNil)
<add> if _, err = buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatal(err)
<ide> }
<add>
<add> c.Assert(ctx.Add(".dockerfile", "?"), check.IsNil)
<ide> if _, err = buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> }
<ide>
<add>func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) {
<add> name := "testbuilddockerignorewholedir"
<add> dockerfile := `
<add> FROM busybox
<add> COPY . /
<add> RUN [[ ! -e /.gitignore ]]
<add> RUN [[ -f /Makefile ]]`
<add> ctx, err := fakeContext(dockerfile, map[string]string{
<add> "Dockerfile": "FROM scratch",
<add> "Makefile": "all:",
<add> ".gitignore": "",
<add> ".dockerignore": "!\n",
<add> })
<add> c.Assert(err, check.IsNil)
<add> defer ctx.Close()
<add> if _, err = buildImageFromContext(name, ctx, true); err == nil {
<add> c.Fatalf("Build was supposed to fail but didn't")
<add> }
<add>
<add> if err.Error() != "failed to build the image: Error checking context: 'Illegal exclusion pattern: !'.\n" {
<add> c.Fatalf("Incorrect output, got:%q", err.Error())
<add> }
<add>}
<add>
<ide> func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
<ide> name := "testbuildlinebreak"
<ide> _, err := buildImage(name,
<ide><path>pkg/fileutils/fileutils.go
<ide> func CleanPatterns(patterns []string) ([]string, [][]string, bool, error) {
<ide> }
<ide> if Exclusion(pattern) {
<ide> if len(pattern) == 1 {
<del> logrus.Errorf("Illegal exclusion pattern: %s", pattern)
<ide> return nil, nil, false, errors.New("Illegal exclusion pattern: !")
<ide> }
<ide> exceptions = true
<ide> func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool,
<ide>
<ide> match, err := filepath.Match(pattern, file)
<ide> if err != nil {
<del> logrus.Errorf("Error matching: %s (pattern: %s)", file, pattern)
<ide> return false, err
<ide> }
<ide>
<ide> func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool,
<ide> if matched {
<ide> logrus.Debugf("Skipping excluded path: %s", file)
<ide> }
<add>
<ide> return matched, nil
<ide> }
<ide> | 3 |
PHP | PHP | add blade cache command | 9fd1273ad79a46bb3aa006129109c6bc72766e4b | <ide><path>src/Illuminate/Foundation/Console/BladeCacheCommand.php
<add><?php
<add>
<add>namespace Illuminate\Foundation\Console;
<add>
<add>use Illuminate\Console\Command;
<add>use Illuminate\Support\Collection;
<add>use Illuminate\Support\Facades\View;
<add>use Symfony\Component\Finder\Finder;
<add>use Symfony\Component\Finder\SplFileInfo;
<add>
<add>class BladeCacheCommand extends Command
<add>{
<add> /**
<add> * The name and signature of the console command.
<add> *
<add> * @var string
<add> */
<add> protected $signature = 'blade:cache';
<add>
<add> /**
<add> * The console command description.
<add> *
<add> * @var string
<add> */
<add> protected $description = "Compile all of the application's Blade templates";
<add>
<add> /**
<add> * Execute the console command.
<add> *
<add> * @return mixed
<add> */
<add> public function handle()
<add> {
<add> $this->paths()->each(function ($path) {
<add> $this->compileViews($this->bladeFilesIn([$path]));
<add> });
<add>
<add> $this->info('Blade templates cached successfully!');
<add> }
<add>
<add> /**
<add> * Compile the given view files.
<add> *
<add> * @param \Illuminate\Support\Collection $views
<add> * @return void
<add> */
<add> protected function compileViews(Collection $views)
<add> {
<add> $compiler = $this->laravel['blade.compiler'];
<add>
<add> $views->map(function (SplFileInfo $file) use ($compiler) {
<add> $compiler->compile($file->getRealPath());
<add> });
<add> }
<add>
<add> /**
<add> * Get the Blade files in the given path.
<add> *
<add> * @param array $paths
<add> * @return \Illuminate\Support\Collection
<add> */
<add> protected function bladeFilesIn(array $paths)
<add> {
<add> return collect(Finder::create()->
<add> in($paths)
<add> ->exclude('vendor')
<add> ->name('*.blade.php')->files());
<add> }
<add>
<add> /**
<add> * Get all of the possible view paths.
<add> *
<add> * @return \Illuminate\Support\Collection
<add> */
<add> protected function paths()
<add> {
<add> $finder = $this->laravel['view']->getFinder();
<add>
<add> return collect($finder->getPaths())->merge(
<add> collect($finder->getHints())->flatten()
<add> );
<add> }
<add>}
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> use Illuminate\Session\Console\SessionTableCommand;
<ide> use Illuminate\Foundation\Console\PolicyMakeCommand;
<ide> use Illuminate\Foundation\Console\RouteCacheCommand;
<add>use Illuminate\Foundation\Console\BladeCacheCommand;
<ide> use Illuminate\Foundation\Console\RouteClearCommand;
<ide> use Illuminate\Console\Scheduling\ScheduleRunCommand;
<ide> use Illuminate\Foundation\Console\ChannelMakeCommand;
<ide> class ArtisanServiceProvider extends ServiceProvider
<ide> * @var array
<ide> */
<ide> protected $commands = [
<add> 'BladeCache' => 'command.blade.cache',
<ide> 'CacheClear' => 'command.cache.clear',
<ide> 'CacheForget' => 'command.cache.forget',
<ide> 'ClearCompiled' => 'command.clear-compiled',
<ide> protected function registerAuthMakeCommand()
<ide> });
<ide> }
<ide>
<add> /**
<add> * Register the command.
<add> *
<add> * @return void
<add> */
<add> protected function registerBladeCacheCommand()
<add> {
<add> $this->app->singleton('command.blade.cache', function ($app) {
<add> return new BladeCacheCommand;
<add> });
<add> }
<add>
<ide> /**
<ide> * Register the command.
<ide> * | 2 |
Python | Python | fix syntax error | 30e35d9666f03cbe27c80fc6adc3e1c571aa9105 | <ide><path>spacy/util.py
<ide> def get_model_meta(path):
<ide> meta = read_json(meta_path)
<ide> for setting in ['lang', 'name', 'version']:
<ide> if setting not in meta or not meta[setting]:
<del> raise ValueError('No valid '%s' setting found in model meta.json' % setting)
<add> raise ValueError("No valid '%s' setting found in model meta.json" % setting)
<ide> return meta
<ide>
<ide> | 1 |
PHP | PHP | catch throwable in timezone validation | c2e4b5c000961800650f8ef6b40160ff664261f5 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> use DateTime;
<ide> use Countable;
<ide> use Exception;
<add>use Throwable;
<ide> use DateTimeZone;
<ide> use RuntimeException;
<ide> use DateTimeInterface;
<ide> protected function validateTimezone($attribute, $value)
<ide> new DateTimeZone($value);
<ide> } catch (Exception $e) {
<ide> return false;
<add> } catch (Throwable $e) {
<add> return false;
<ide> }
<ide>
<ide> return true;
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateTimezone()
<ide>
<ide> $v = new Validator($trans, ['foo' => 'GMT'], ['foo' => 'Timezone']);
<ide> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, ['foo' => ['this_is_not_a_timezone']], ['foo' => 'Timezone']);
<add> $this->assertFalse($v->passes());
<ide> }
<ide>
<ide> public function testValidateRegex() | 2 |
Text | Text | add cli flag to docs for selinux support | 64d0f7e39b395a3fc52f441a53f188a19bd53cf3 | <ide><path>docs/sources/reference/commandline/cli.md
<ide> expect an integer, and they can only be specified once.
<ide> -d, --daemon=false: Enable daemon mode
<ide> --dns=[]: Force docker to use specific DNS servers
<ide> --dns-search=[]: Force Docker to use specific DNS search domains
<add> --enable-selinux=false: Enable selinux support for running containers
<ide> -g, --graph="/var/lib/docker": Path to use as the root of the docker runtime
<ide> --icc=true: Enable inter-container communication
<ide> --ip="0.0.0.0": Default IP address to use when binding container ports | 1 |
Python | Python | remove trailing whitespace from the lines | b20c2857c8e6eb855a64bcec923cb1b27c2c31a2 | <ide><path>contrib/generate_contributor_list.py
<ide> def compare(item1, item2):
<ide> else:
<ide> line = '* %(name)s' % {'name': name}
<ide>
<del> result.append(line)
<add> result.append(line.strip())
<ide>
<ide> result = '\n'.join(result)
<ide> return result | 1 |
PHP | PHP | add model.initialize event | c71f919819e69e19aaf2653910686baaf57c1371 | <ide><path>src/ORM/Table.php
<ide> public function __construct(array $config = []) {
<ide>
<ide> $this->initialize($config);
<ide> $this->_eventManager->attach($this);
<add> $this->dispatchEvent('Model.initialize');
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> use Cake\Database\Expression\QueryExpression;
<ide> use Cake\Database\TypeMap;
<ide> use Cake\Datasource\ConnectionManager;
<add>use Cake\Event\EventManager;
<ide> use Cake\I18n\Time;
<ide> use Cake\ORM\Table;
<ide> use Cake\ORM\TableRegistry;
<ide> public function setUp() {
<ide> ]);
<ide> }
<ide>
<add>/**
<add> * teardown method
<add> *
<add> * @return void
<add> */
<ide> public function tearDown() {
<ide> parent::tearDown();
<ide> TableRegistry::clear();
<ide> public function testDeleteCallbacks() {
<ide> ->method('attach');
<ide>
<ide> $mock->expects($this->at(1))
<add> ->method('dispatch');
<add>
<add> $mock->expects($this->at(2))
<ide> ->method('dispatch')
<ide> ->with($this->logicalAnd(
<ide> $this->attributeEqualTo('_name', 'Model.beforeDelete'),
<ide> public function testDeleteCallbacks() {
<ide> )
<ide> ));
<ide>
<del> $mock->expects($this->at(2))
<add> $mock->expects($this->at(3))
<ide> ->method('dispatch')
<ide> ->with($this->logicalAnd(
<ide> $this->attributeEqualTo('_name', 'Model.afterDelete'),
<ide> public function testDeleteBeforeDeleteAbort() {
<ide> $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
<ide>
<ide> $mock = $this->getMock('Cake\Event\EventManager');
<del> $mock->expects($this->once())
<add> $mock->expects($this->at(2))
<ide> ->method('dispatch')
<ide> ->will($this->returnCallback(function ($event) {
<ide> $event->stopPropagation();
<ide> public function testDeleteBeforeDeleteReturnResult() {
<ide> $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
<ide>
<ide> $mock = $this->getMock('Cake\Event\EventManager');
<del> $mock->expects($this->once())
<add> $mock->expects($this->at(2))
<ide> ->method('dispatch')
<ide> ->will($this->returnCallback(function ($event) {
<ide> $event->stopPropagation();
<ide> function ($article) {
<ide> $this->assertEquals(2, $article->author_id);
<ide> }
<ide>
<add>/**
<add> * Test that creating a table fires the initialize event.
<add> *
<add> * @return void
<add> */
<add> public function testInitializeEvent() {
<add> $count = 0;
<add> $cb = function ($event) use (&$count){
<add> $count++;
<add> };
<add> EventManager::instance()->attach($cb, 'Model.initialize');
<add> $articles = TableRegistry::get('Articles');
<add>
<add> $this->assertEquals(1, $count, 'Callback should be called');
<add> EventManager::instance()->detach($cb, 'Model.initialize');
<add> }
<add>
<ide> } | 2 |
Text | Text | fix example of crypto.generatekeysync | 8037d1749afe7736c4a1c691e8fb43f4791c8e7a | <ide><path>doc/api/crypto.md
<ide> const {
<ide> generateKeySync
<ide> } = await import('crypto');
<ide>
<del>const key = generateKeySync('hmac', 64);
<add>const key = generateKeySync('hmac', { length: 64 });
<ide> console.log(key.export().toString('hex')); // e89..........41e
<ide> ```
<ide>
<ide> const {
<ide> generateKeySync,
<ide> } = require('crypto');
<ide>
<del>const key = generateKeySync('hmac', 64);
<add>const key = generateKeySync('hmac', { length: 64 });
<ide> console.log(key.export().toString('hex')); // e89..........41e
<ide> ```
<ide> | 1 |
Python | Python | move abbreviations below other exceptions | a23504fe07c5d3d55b247e4aa0b185dd0a338ee7 | <ide><path>spacy/en/tokenizer_exceptions.py
<ide> }
<ide>
<ide>
<del># Other exceptions
<del>
<del>OTHER = {
<del> " ": [
<del> {ORTH: " ", TAG: "SP"}
<del> ],
<del>
<del> "\u00a0": [
<del> {ORTH: "\u00a0", TAG: "SP", LEMMA: " "}
<del> ],
<del>
<del> "and/or": [
<del> {ORTH: "and/or", LEMMA: "and/or", TAG: "CC"}
<del> ],
<del>
<del> "'cause": [
<del> {ORTH: "'cause", LEMMA: "because"}
<del> ],
<del>
<del> "y'all": [
<del> {ORTH: "y'", LEMMA: PRON_LEMMA, NORM: "you"},
<del> {ORTH: "all"}
<del> ],
<del>
<del> "yall": [
<del> {ORTH: "y", LEMMA: PRON_LEMMA, NORM: "you"},
<del> {ORTH: "all"}
<del> ],
<del>
<del> "'em": [
<del> {ORTH: "'em", LEMMA: PRON_LEMMA, NORM: "them"}
<del> ],
<del>
<del> "em": [
<del> {ORTH: "em", LEMMA: PRON_LEMMA, NORM: "them"}
<del> ],
<del>
<del> "nothin'": [
<del> {ORTH: "nothin'", LEMMA: "nothing"}
<del> ],
<del>
<del> "nuthin'": [
<del> {ORTH: "nuthin'", LEMMA: "nothing"}
<del> ],
<del>
<del> "'nuff": [
<del> {ORTH: "'nuff", LEMMA: "enough"}
<del> ],
<del>
<del> "ol'": [
<del> {ORTH: "ol'", LEMMA: "old"}
<del> ],
<del>
<del> "not've": [
<del> {ORTH: "not", LEMMA: "not", TAG: "RB"},
<del> {ORTH: "'ve", LEMMA: "have", TAG: "VB"}
<del> ],
<del>
<del> "notve": [
<del> {ORTH: "not", LEMMA: "not", TAG: "RB"},
<del> {ORTH: "ve", LEMMA: "have", TAG: "VB"}
<del> ],
<del>
<del> "Not've": [
<del> {ORTH: "Not", LEMMA: "not", TAG: "RB"},
<del> {ORTH: "'ve", LEMMA: "have", TAG: "VB"}
<del> ],
<del>
<del> "Notve": [
<del> {ORTH: "Not", LEMMA: "not", TAG: "RB"},
<del> {ORTH: "ve", LEMMA: "have", TAG: "VB"}
<del> ],
<del>
<del> "cannot": [
<del> {ORTH: "can", LEMMA: "can", TAG: "MD"},
<del> {ORTH: "not", LEMMA: "not", TAG: "RB"}
<del> ],
<del>
<del> "Cannot": [
<del> {ORTH: "Can", LEMMA: "can", TAG: "MD"},
<del> {ORTH: "not", LEMMA: "not", TAG: "RB"}
<del> ],
<del>
<del> "gonna": [
<del> {ORTH: "gon", LEMMA: "go", NORM: "going"},
<del> {ORTH: "na", LEMMA: "to"}
<del> ],
<del>
<del> "Gonna": [
<del> {ORTH: "Gon", LEMMA: "go", NORM: "going"},
<del> {ORTH: "na", LEMMA: "to"}
<del> ],
<del>
<del> "let's": [
<del> {ORTH: "let"},
<del> {ORTH: "'s", LEMMA: PRON_LEMMA, NORM: "us"}
<del> ],
<del>
<del> "Let's": [
<del> {ORTH: "Let"},
<del> {ORTH: "'s", LEMMA: PRON_LEMMA, NORM: "us"}
<del> ],
<del>
<del> "'S": [
<del> {ORTH: "'S", LEMMA: "'s"}
<del> ],
<del>
<del> "'s": [
<del> {ORTH: "'s", LEMMA: "'s"}
<del> ],
<del>
<del> "\u2018S": [
<del> {ORTH: "\u2018S", LEMMA: "'s"}
<del> ],
<del>
<del> "\u2018s": [
<del> {ORTH: "\u2018s", LEMMA: "'s"}
<del> ],
<del>
<del> "\u2014": [
<del> {ORTH: "\u2014", TAG: ":", LEMMA: "--"}
<del> ],
<del>
<del> "\n": [
<del> {ORTH: "\n", TAG: "SP"}
<del> ],
<del>
<del> "\t": [
<del> {ORTH: "\t", TAG: "SP"}
<del> ]
<del>}
<del>
<del>
<ide> TOKENIZER_EXCEPTIONS = dict(EXC)
<del>TOKENIZER_EXCEPTIONS.update(ABBREVIATIONS)
<ide> TOKENIZER_EXCEPTIONS.update(OTHER)
<add>TOKENIZER_EXCEPTIONS.update(ABBREVIATIONS)
<ide>
<ide>
<ide> # Remove EXCLUDE_EXC if in exceptions | 1 |
Python | Python | add note about compatibility | 085f2559f01b5b9a668fa624e5d8be19ca16aeaa | <ide><path>libcloud/compute/drivers/opennebula.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide> """
<del>OpenNebula driver
<add>OpenNebula driver. Compatible with OpenNebula 1.4
<ide> """
<ide>
<ide> from base64 import b64encode | 1 |
Python | Python | use a tuple when defining the ms_win64 macro | a7bf18812f143bc6926c1c21fcda25ef4ea1d26e | <ide><path>numpy/distutils/command/build_ext.py
<ide> def build_extension(self, ext):
<ide> # Py_ModuleInit4_64, etc... So we add it here
<ide> if self.compiler.compiler_type == 'mingw32' and \
<ide> get_build_architecture() == 'AMD64':
<del> macros.append('MS_WIN64')
<add> macros.append(('MS_WIN64',))
<ide>
<ide> # Set Fortran/C++ compilers for compilation and linking.
<ide> if ext.language=='f90': | 1 |
Text | Text | fix broken link in inception readme | 2f09f78b8db9e13942acec3d061ef9c80ad59627 | <ide><path>inception/README.md
<ide> your custom data set. Please see the associated options and assumptions behind
<ide> this script by reading the comments section of [`build_image_data.py`]
<ide> (inception/data/build_image_data.py). Also, if your custom data has a different
<ide> number of examples or classes, you need to change the appropriate values in
<del>[`imagenet_data.py`](imagenet_data.py).
<add>[`imagenet_data.py`](inception/imagenet_data.py).
<ide>
<ide> The second piece you will need is a trained Inception v3 image model. You have
<ide> the option of either training one yourself (See [How to Train from Scratch] | 1 |
Javascript | Javascript | add util inspect null getter test | 1dbf2765bc30745dd7e221e96e88f010526d13a4 | <ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(
<ide> const value = {};
<ide> value.a = value;
<ide> assert.strictEqual(util.inspect(value), '<ref *1> { a: [Circular *1] }');
<add> const getterFn = {
<add> get one() {
<add> return null;
<add> }
<add> };
<add> assert.strictEqual(
<add> util.inspect(getterFn, { getters: true }),
<add> '{ one: [Getter: null] }'
<add> );
<ide> }
<ide>
<ide> // Array with dynamic properties. | 1 |
Go | Go | fix loading of containerized plugins | d85b9f858050dbfb2dde3d68517952958b8e38ee | <ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Register(container *container.Container) error {
<ide> }
<ide> }
<ide>
<del> if err := daemon.prepareMountPoints(container); err != nil {
<del> return err
<del> }
<del>
<ide> return nil
<ide> }
<ide>
<ide> func (daemon *Daemon) restore() error {
<ide> }
<ide> group.Wait()
<ide>
<add> // any containers that were started above would already have had this done,
<add> // however we need to now prepare the mountpoints for the rest of the containers as well.
<add> // This shouldn't cause any issue running on the containers that already had this run.
<add> // This must be run after any containers with a restart policy so that containerized plugins
<add> // can have a chance to be running before we try to initialize them.
<add> for _, c := range containers {
<add> group.Add(1)
<add> go func(c *container.Container) {
<add> defer group.Done()
<add> if err := daemon.prepareMountPoints(c); err != nil {
<add> logrus.Error(err)
<add> }
<add> }(c)
<add> }
<add>
<add> group.Wait()
<add>
<ide> if !debug {
<ide> if logrus.GetLevel() == logrus.InfoLevel {
<ide> fmt.Println()
<ide><path>daemon/volumes.go
<ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo
<ide> func (daemon *Daemon) lazyInitializeVolume(containerID string, m *volume.MountPoint) error {
<ide> if len(m.Driver) > 0 && m.Volume == nil {
<ide> v, err := daemon.volumes.GetWithRef(m.Name, m.Driver, containerID)
<del>
<ide> if err != nil {
<ide> return err
<ide> } | 2 |
Python | Python | harmonize max and min docstrings with each other | f40e9d53548a5033d1fd2c68c8257dddea14e9f1 | <ide><path>numpy/core/code_generators/ufunc_docstrings.py
<ide> def add_newdoc(place, name, doc):
<ide> """
<ide> Element-wise maximum of array elements.
<ide>
<del> Compare two arrays and returns a new array containing
<del> the element-wise maxima. If one of the elements being
<del> compared is a nan, then that element is returned. If
<del> both elements are nans then the first is returned. The
<del> latter distinction is important for complex nans,
<del> which are defined as at least one of the real or
<del> imaginary parts being a nan. The net effect is that
<del> nans are propagated.
<add> Compare two arrays and returns a new array containing the element-wise
<add> maxima. If one of the elements being compared is a nan, then that element
<add> is returned. If both elements are nans then the first is returned. The
<add> latter distinction is important for complex nans, which are defined as at
<add> least one of the real or imaginary parts being a nan. The net effect is
<add> that nans are propagated.
<ide>
<ide> Parameters
<ide> ----------
<ide> def add_newdoc(place, name, doc):
<ide>
<ide> Notes
<ide> -----
<del> Equivalent to ``np.where(x1 > x2, x1, x2)`` but faster and does proper
<del> broadcasting.
<add> The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither
<add> x1 nor x2 are nans, but it is faster and does proper broadcasting.
<ide>
<ide> Examples
<ide> --------
<ide> >>> np.maximum([2, 3, 4], [1, 5, 2])
<ide> array([2, 5, 4])
<ide>
<del> >>> np.maximum(np.eye(2), [0.5, 2])
<add> >>> np.maximum(np.eye(2), [0.5, 2]) # broadcasting
<ide> array([[ 1. , 2. ],
<ide> [ 0.5, 2. ]])
<ide>
<ide> def add_newdoc(place, name, doc):
<ide>
<ide> >>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan])
<ide> array([ NaN, NaN, NaN])
<add> >>> np.minimum(-np.Inf, 1)
<add> -inf
<ide>
<ide> """)
<ide>
<ide> def add_newdoc(place, name, doc):
<ide>
<ide> add_newdoc('numpy.core.umath', 'fmin',
<ide> """
<del> fmin(x1, x2[, out])
<del>
<ide> Element-wise minimum of array elements.
<ide>
<ide> Compare two arrays and returns a new array containing the element-wise
<ide><path>numpy/core/fromnumeric.py
<ide> def amax(a, axis=None, out=None, keepdims=False):
<ide> a : array_like
<ide> Input data.
<ide> axis : int, optional
<del> Axis along which to operate. By default flattened input is used.
<add> Axis along which to operate. By default, flattened input is used.
<ide> out : ndarray, optional
<del> Alternate output array in which to place the result. Must be of
<del> the same shape and buffer length as the expected output. See
<del> `doc.ufuncs` (Section "Output arguments") for more details.
<add> Alternative output array in which to place the result. Must
<add> be of the same shape and buffer length as the expected output.
<add> See `doc.ufuncs` (Section "Output arguments") for more details.
<ide> keepdims : bool, optional
<ide> If this is set to True, the axes which are reduced are left
<ide> in the result as dimensions with size one. With this option,
<ide> def amax(a, axis=None, out=None, keepdims=False):
<ide> Notes
<ide> -----
<ide> NaN values are propagated, that is if at least one item is NaN, the
<del> corresponding max value will be NaN as well. To ignore NaN values
<add> corresponding max value will be NaN as well. To ignore NaN values
<ide> (MATLAB behavior), please use nanmax.
<ide>
<ide> Don't use `amax` for element-wise comparison of 2 arrays; when
<ide> def amax(a, axis=None, out=None, keepdims=False):
<ide> >>> a
<ide> array([[0, 1],
<ide> [2, 3]])
<del> >>> np.amax(a)
<add> >>> np.amax(a) # Maximum of the flattened array
<ide> 3
<del> >>> np.amax(a, axis=0)
<add> >>> np.amax(a, axis=0) # Maxima along the first axis
<ide> array([2, 3])
<del> >>> np.amax(a, axis=1)
<add> >>> np.amax(a, axis=1) # Maxima along the second axis
<ide> array([1, 3])
<ide>
<ide> >>> b = np.arange(5, dtype=np.float)
<ide> def amax(a, axis=None, out=None, keepdims=False):
<ide> except AttributeError:
<ide> return _methods._amax(a, axis=axis,
<ide> out=out, keepdims=keepdims)
<del> # NOTE: Dropping and keepdims parameter
<add> # NOTE: Dropping the keepdims parameter
<ide> return amax(axis=axis, out=out)
<ide> else:
<ide> return _methods._amax(a, axis=axis,
<ide> def amin(a, axis=None, out=None, keepdims=False):
<ide> a : array_like
<ide> Input data.
<ide> axis : int, optional
<del> Axis along which to operate. By default a flattened input is used.
<add> Axis along which to operate. By default, flattened input is used.
<ide> out : ndarray, optional
<ide> Alternative output array in which to place the result. Must
<ide> be of the same shape and buffer length as the expected output.
<ide> def amin(a, axis=None, out=None, keepdims=False):
<ide>
<ide> Returns
<ide> -------
<del> amin : ndarray
<del> A new array or a scalar array with the result.
<add> amin : ndarray or scalar
<add> Minimum of `a`. If `axis` is None, the result is a scalar value.
<add> If `axis` is given, the result is an array of dimension
<add> ``a.ndim - 1``.
<ide>
<ide> See Also
<ide> --------
<ide> def amin(a, axis=None, out=None, keepdims=False):
<ide>
<ide> Notes
<ide> -----
<del> NaN values are propagated, that is if at least one item is nan, the
<del> corresponding min value will be nan as well. To ignore NaN values (matlab
<del> behavior), please use nanmin.
<add> NaN values are propagated, that is if at least one item is NaN, the
<add> corresponding min value will be NaN as well. To ignore NaN values
<add> (MATLAB behavior), please use nanmin.
<ide>
<ide> Don't use `amin` for element-wise comparison of 2 arrays; when
<ide> ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
<ide> def amin(a, axis=None, out=None, keepdims=False):
<ide> [2, 3]])
<ide> >>> np.amin(a) # Minimum of the flattened array
<ide> 0
<del> >>> np.amin(a, axis=0) # Minima along the first axis
<add> >>> np.amin(a, axis=0) # Minima along the first axis
<ide> array([0, 1])
<del> >>> np.amin(a, axis=1) # Minima along the second axis
<add> >>> np.amin(a, axis=1) # Minima along the second axis
<ide> array([0, 2])
<ide>
<ide> >>> b = np.arange(5, dtype=np.float)
<ide><path>numpy/lib/function_base.py
<ide> def nansum(a, axis=None):
<ide>
<ide> def nanmin(a, axis=None):
<ide> """
<del> Return the minimum of an array or minimum along an axis ignoring any NaNs.
<add> Return the minimum of an array or minimum along an axis, ignoring any NaNs.
<ide>
<ide> Parameters
<ide> ----------
<ide> a : array_like
<del> Array containing numbers whose minimum is desired.
<add> Array containing numbers whose minimum is desired. If `a` is not
<add> an array, a conversion is attempted.
<ide> axis : int, optional
<del> Axis along which the minimum is computed.The default is to compute
<add> Axis along which the minimum is computed. The default is to compute
<ide> the minimum of the flattened array.
<ide>
<ide> Returns
<ide> -------
<ide> nanmin : ndarray
<del> A new array or a scalar array with the result.
<add> An array with the same shape as `a`, with the specified axis removed.
<add> If `a` is a 0-d array, or if axis is None, an ndarray scalar is
<add> returned. The same dtype as `a` is returned.
<ide>
<ide> See Also
<ide> --------
<ide> def nanmin(a, axis=None):
<ide>
<ide> If the input has a integer type the function is equivalent to np.min.
<ide>
<del>
<ide> Examples
<ide> --------
<ide> >>> a = np.array([[1, 2], [3, np.nan]])
<ide> def nanargmin(a, axis=None):
<ide>
<ide> def nanmax(a, axis=None):
<ide> """
<del> Return the maximum of an array or maximum along an axis ignoring any NaNs.
<add> Return the maximum of an array or maximum along an axis, ignoring any NaNs.
<ide>
<ide> Parameters
<ide> ----------
<ide> def nanmax(a, axis=None):
<ide> -------
<ide> nanmax : ndarray
<ide> An array with the same shape as `a`, with the specified axis removed.
<del> If `a` is a 0-d array, or if axis is None, a ndarray scalar is
<del> returned. The the same dtype as `a` is returned.
<add> If `a` is a 0-d array, or if axis is None, an ndarray scalar is
<add> returned. The same dtype as `a` is returned.
<ide>
<ide> See Also
<ide> -------- | 3 |
Ruby | Ruby | use tt in doc for activerecord [ci skip] | a2f2d2617b144b616700af4fe0f4c184d15cee66 | <ide><path>activemodel/lib/active_model/callbacks.rb
<ide> def self.extended(base) #:nodoc:
<ide> # end
<ide> # end
<ide> #
<del> # NOTE: +method_name+ passed to `define_model_callbacks` must not end with
<del> # `!`, `?` or `=`.
<add> # NOTE: +method_name+ passed to define_model_callbacks must not end with
<add> # <tt>!</tt>, <tt>?</tt> or <tt>=</tt>.
<ide> def define_model_callbacks(*callbacks)
<ide> options = callbacks.extract_options!
<ide> options = {
<ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb
<ide> def attribute_changed_in_place?(attr_name) # :nodoc:
<ide> end
<ide>
<ide> # Did this attribute change when we last saved? This method can be invoked
<del> # as `saved_change_to_name?` instead of `saved_change_to_attribute?("name")`.
<add> # as +saved_change_to_name?+ instead of <tt>saved_change_to_attribute?("name")</tt>.
<ide> # Behaves similarly to +attribute_changed?+. This method is useful in
<ide> # after callbacks to determine if the call to save changed a certain
<ide> # attribute.
<ide> def saved_change_to_attribute?(attr_name, **options)
<ide> # Behaves similarly to +attribute_change+. This method is useful in after
<ide> # callbacks, to see the change in an attribute that just occurred
<ide> #
<del> # This method can be invoked as `saved_change_to_name` in instead of
<del> # `saved_change_to_attribute("name")`
<add> # This method can be invoked as +saved_change_to_name+ in instead of
<add> # <tt>saved_change_to_attribute("name")</tt>
<ide> def saved_change_to_attribute(attr_name)
<ide> mutations_before_last_save.change_to_attribute(attr_name)
<ide> end
<ide> def attribute_before_last_save(attr_name)
<ide> mutations_before_last_save.original_value(attr_name)
<ide> end
<ide>
<del> # Did the last call to `save` have any changes to change?
<add> # Did the last call to +save+ have any changes to change?
<ide> def saved_changes?
<ide> mutations_before_last_save.any_changes?
<ide> end
<ide> def saved_changes
<ide> mutations_before_last_save.changes
<ide> end
<ide>
<del> # Alias for `attribute_changed?`
<add> # Alias for +attribute_changed?+
<ide> def will_save_change_to_attribute?(attr_name, **options)
<ide> mutations_from_database.changed?(attr_name, **options)
<ide> end
<ide>
<del> # Alias for `attribute_change`
<add> # Alias for +attribute_change+
<ide> def attribute_change_to_be_saved(attr_name)
<ide> mutations_from_database.change_to_attribute(attr_name)
<ide> end
<ide>
<del> # Alias for `attribute_was`
<add> # Alias for +attribute_was+
<ide> def attribute_in_database(attr_name)
<ide> mutations_from_database.original_value(attr_name)
<ide> end
<ide>
<del> # Alias for `changed?`
<add> # Alias for +changed?+
<ide> def has_changes_to_save?
<ide> mutations_from_database.any_changes?
<ide> end
<ide>
<del> # Alias for `changes`
<add> # Alias for +changes+
<ide> def changes_to_save
<ide> mutations_from_database.changes
<ide> end
<ide>
<del> # Alias for `changed`
<add> # Alias for +changed+
<ide> def changed_attribute_names_to_save
<ide> changes_to_save.keys
<ide> end
<ide>
<del> # Alias for `changed_attributes`
<add> # Alias for +changed_attributes+
<ide> def attributes_in_database
<ide> changes_to_save.transform_values(&:first)
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> class SQLite3Adapter < AbstractAdapter
<ide> ##
<ide> # :singleton-method:
<ide> # Indicates whether boolean values are stored in sqlite3 databases as 1
<del> # and 0 or 't' and 'f'. Leaving `ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer`
<add> # and 0 or 't' and 'f'. Leaving <tt>ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer</tt>
<ide> # set to false is deprecated. SQLite databases have used 't' and 'f' to
<ide> # serialize boolean values and must have old data converted to 1 and 0
<ide> # (its native boolean serialization) before setting this flag to true.
<ide> class SQLite3Adapter < AbstractAdapter
<ide> # ExampleModel.where("boolean_column = 't'").update_all(boolean_column: 1)
<ide> # ExampleModel.where("boolean_column = 'f'").update_all(boolean_column: 0)
<ide> # for all models and all boolean columns, after which the flag must be set
<del> # to true by adding the following to your application.rb file:
<add> # to true by adding the following to your <tt>application.rb</tt> file:
<ide> #
<ide> # Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true
<ide> class_attribute :represent_boolean_as_integer, default: false
<ide><path>activerecord/lib/active_record/define_callbacks.rb
<ide> # frozen_string_literal: true
<ide>
<ide> module ActiveRecord
<del> # This module exists because `ActiveRecord::AttributeMethods::Dirty` needs to
<del> # define callbacks, but continue to have its version of `save` be the super
<del> # method of `ActiveRecord::Callbacks`. This will be removed when the removal
<add> # This module exists because ActiveRecord::AttributeMethods::Dirty needs to
<add> # define callbacks, but continue to have its version of +save+ be the super
<add> # method of ActiveRecord::Callbacks. This will be removed when the removal
<ide> # of deprecated code removes this need.
<ide> module DefineCallbacks
<ide> extend ActiveSupport::Concern
<ide><path>activerecord/lib/active_record/fixtures.rb
<ide> class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
<ide> # unwanted inter-test dependencies. Methods used by multiple fixtures should be defined in a module
<ide> # that is included in ActiveRecord::FixtureSet.context_class.
<ide> #
<del> # - define a helper method in `test_helper.rb`
<add> # - define a helper method in <tt>test_helper.rb</tt>
<ide> # module FixtureFileHelpers
<ide> # def file_sha(path)
<ide> # Digest::SHA2.hexdigest(File.read(Rails.root.join('test/fixtures', path)))
<ide><path>activerecord/lib/active_record/no_touching.rb
<ide> module NoTouching
<ide> extend ActiveSupport::Concern
<ide>
<ide> module ClassMethods
<del> # Lets you selectively disable calls to `touch` for the
<add> # Lets you selectively disable calls to +touch+ for the
<ide> # duration of a block.
<ide> #
<ide> # ==== Examples
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def increment(attribute, by = 1)
<ide> # Wrapper around #increment that writes the update to the database.
<ide> # Only +attribute+ is updated; the record itself is not saved.
<ide> # This means that any other modified attributes will still be dirty.
<del> # Validations and callbacks are skipped. Supports the `touch` option from
<add> # Validations and callbacks are skipped. Supports the +touch+ option from
<ide> # +update_counters+, see that for more.
<ide> # Returns +self+.
<ide> def increment!(attribute, by = 1, touch: nil)
<ide> def decrement(attribute, by = 1)
<ide> # Wrapper around #decrement that writes the update to the database.
<ide> # Only +attribute+ is updated; the record itself is not saved.
<ide> # This means that any other modified attributes will still be dirty.
<del> # Validations and callbacks are skipped. Supports the `touch` option from
<add> # Validations and callbacks are skipped. Supports the +touch+ option from
<ide> # +update_counters+, see that for more.
<ide> # Returns +self+.
<ide> def decrement!(attribute, by = 1, touch: nil) | 7 |
Go | Go | fix golint errors in docker/api/client | 58065d0dd9adec4b2f397a453652cc8cc7237a17 | <ide><path>api/client/cli.go
<ide> func (cli *DockerCli) Cmd(args ...string) error {
<ide> return cli.CmdHelp()
<ide> }
<ide>
<add>// Subcmd is a subcommand of the main "docker" command.
<add>// A subcommand represents an action that can be performed
<add>// from the Docker command line client.
<add>//
<add>// To see all available subcommands, run "docker --help".
<ide> func (cli *DockerCli) Subcmd(name, signature, description string, exitOnError bool) *flag.FlagSet {
<ide> var errorHandling flag.ErrorHandling
<ide> if exitOnError {
<ide> func (cli *DockerCli) Subcmd(name, signature, description string, exitOnError bo
<ide> return flags
<ide> }
<ide>
<add>// CheckTtyInput checks if we are trying to attach to a container tty
<add>// from a non-tty client input stream, and if so, returns an error.
<ide> func (cli *DockerCli) CheckTtyInput(attachStdin, ttyMode bool) error {
<ide> // In order to attach to a container tty, input stream for the client must
<ide> // be a tty itself: redirecting or piping the client standard input is
<ide><path>api/client/images.go
<ide> import (
<ide> )
<ide>
<ide> // FIXME: --viz and --tree are deprecated. Remove them in a future version.
<del>func (cli *DockerCli) WalkTree(noTrunc bool, images []*types.Image, byParent map[string][]*types.Image, prefix string, printNode func(cli *DockerCli, noTrunc bool, image *types.Image, prefix string)) {
<add>func (cli *DockerCli) walkTree(noTrunc bool, images []*types.Image, byParent map[string][]*types.Image, prefix string, printNode func(cli *DockerCli, noTrunc bool, image *types.Image, prefix string)) {
<ide> length := len(images)
<ide> if length > 1 {
<ide> for index, image := range images {
<ide> if index+1 == length {
<ide> printNode(cli, noTrunc, image, prefix+"└─")
<ide> if subimages, exists := byParent[image.ID]; exists {
<del> cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
<add> cli.walkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
<ide> }
<ide> } else {
<ide> printNode(cli, noTrunc, image, prefix+"\u251C─")
<ide> if subimages, exists := byParent[image.ID]; exists {
<del> cli.WalkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode)
<add> cli.walkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode)
<ide> }
<ide> }
<ide> }
<ide> } else {
<ide> for _, image := range images {
<ide> printNode(cli, noTrunc, image, prefix+"└─")
<ide> if subimages, exists := byParent[image.ID]; exists {
<del> cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
<add> cli.walkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
<ide> }
<ide> }
<ide> }
<ide> func (cli *DockerCli) CmdImages(args ...string) error {
<ide>
<ide> if startImage != nil {
<ide> root := []*types.Image{startImage}
<del> cli.WalkTree(*noTrunc, root, byParent, "", printNode)
<add> cli.walkTree(*noTrunc, root, byParent, "", printNode)
<ide> } else if matchName == "" {
<del> cli.WalkTree(*noTrunc, roots, byParent, "", printNode)
<add> cli.walkTree(*noTrunc, roots, byParent, "", printNode)
<ide> }
<ide> if *flViz {
<ide> fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
<ide><path>api/client/rm.go
<ide> import (
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> )
<ide>
<add>// CmdRm removes one or more containers.
<add>//
<add>// Usage: docker rm [OPTIONS] CONTAINER [CONTAINER...]
<ide> func (cli *DockerCli) CmdRm(args ...string) error {
<ide> cmd := cli.Subcmd("rm", "CONTAINER [CONTAINER...]", "Remove one or more containers", true)
<ide> v := cmd.Bool([]string{"v", "-volumes"}, false, "Remove the volumes associated with the container")
<ide><path>api/client/search.go
<ide> import (
<ide> "github.com/docker/docker/registry"
<ide> )
<ide>
<add>// ByStars sorts search results in ascending order by number of stars.
<ide> type ByStars []registry.SearchResult
<ide>
<ide> func (r ByStars) Len() int { return len(r) }
<ide><path>api/client/utils.go
<ide> import (
<ide> )
<ide>
<ide> var (
<del> ErrConnectionRefused = errors.New("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
<add> errConnectionRefused = errors.New("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
<ide> )
<ide>
<add>// HTTPClient creates a new HTP client with the cli's client transport instance.
<ide> func (cli *DockerCli) HTTPClient() *http.Client {
<ide> return &http.Client{Transport: cli.transport}
<ide> }
<ide> func (cli *DockerCli) clientRequest(method, path string, in io.Reader, headers m
<ide> }
<ide> if err != nil {
<ide> if strings.Contains(err.Error(), "connection refused") {
<del> return nil, "", statusCode, ErrConnectionRefused
<add> return nil, "", statusCode, errConnectionRefused
<ide> }
<ide>
<ide> if cli.tlsConfig == nil {
<ide> func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
<ide> stream, _, err := cli.call("GET", "/containers/"+containerID+"/json", nil, nil)
<ide> if err != nil {
<ide> // If we can't connect, then the daemon probably died.
<del> if err != ErrConnectionRefused {
<add> if err != errConnectionRefused {
<ide> return false, -1, err
<ide> }
<ide> return false, -1, nil
<ide> func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
<ide> stream, _, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil)
<ide> if err != nil {
<ide> // If we can't connect, then the daemon probably died.
<del> if err != ErrConnectionRefused {
<add> if err != errConnectionRefused {
<ide> return false, -1, err
<ide> }
<ide> return false, -1, nil | 5 |
Java | Java | fix race condition for asynchronousfilechannel | d5da823482134cc447a7023ad223a661cc50e348 | <ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java
<ide> public void failed(Throwable exc, AsynchronousFileChannel channel) {
<ide>
<ide> private final AtomicBoolean completed = new AtomicBoolean();
<ide>
<del> private long position;
<add> private final AtomicLong position;
<ide>
<ide> @Nullable
<ide> private DataBuffer dataBuffer;
<ide> public AsynchronousFileChannelWriteCompletionHandler(
<ide> FluxSink<DataBuffer> sink, AsynchronousFileChannel channel, long position) {
<ide> this.sink = sink;
<ide> this.channel = channel;
<del> this.position = position;
<add> this.position = new AtomicLong(position);
<ide> }
<ide>
<ide> @Override
<ide> protected void hookOnNext(DataBuffer value) {
<ide> this.dataBuffer = value;
<ide> ByteBuffer byteBuffer = value.asByteBuffer();
<ide>
<del> this.channel.write(byteBuffer, this.position, byteBuffer, this);
<add> this.channel.write(byteBuffer, this.position.get(), byteBuffer, this);
<ide> }
<ide>
<ide> @Override
<ide> protected void hookOnError(Throwable throwable) {
<ide> @Override
<ide> protected void hookOnComplete() {
<ide> this.completed.set(true);
<add>
<add> if (this.dataBuffer == null) {
<add> this.sink.complete();
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void completed(Integer written, ByteBuffer byteBuffer) {
<del> this.position += written;
<add> this.position.addAndGet(written);
<ide> if (byteBuffer.hasRemaining()) {
<del> this.channel.write(byteBuffer, this.position, byteBuffer, this);
<add> this.channel.write(byteBuffer, this.position.get(), byteBuffer, this);
<ide> return;
<ide> }
<del> else if (this.dataBuffer != null) {
<add>
<add> if (this.dataBuffer != null) {
<ide> this.sink.next(this.dataBuffer);
<add> this.dataBuffer = null;
<ide> }
<ide> if (this.completed.get()) {
<ide> this.sink.complete();
<ide><path>spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java
<ide> public void writeWritableByteChannel() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> @Ignore // SPR-15798
<ide> public void writeAsynchronousFileChannel() throws Exception {
<ide> DataBuffer foo = stringBuffer("foo");
<ide> DataBuffer bar = stringBuffer("bar"); | 2 |
Javascript | Javascript | fix reference to wrong variable | 154a8cf32869cb9fabbb0ef2b68c77a5c17954e9 | <ide><path>scripts/rollup/build-all-release-channels.js
<ide> function updatePackageVersions(
<ide>
<ide> if (packageInfo.dependencies) {
<ide> for (const dep of Object.keys(packageInfo.dependencies)) {
<del> if (modulesDir.includes(dep)) {
<add> if (versionsMap.has(dep)) {
<ide> packageInfo.dependencies[dep] = version;
<ide> }
<ide> }
<ide> }
<ide> if (packageInfo.peerDependencies) {
<ide> for (const dep of Object.keys(packageInfo.peerDependencies)) {
<del> if (modulesDir.includes(dep)) {
<add> if (versionsMap.has(dep)) {
<ide> packageInfo.peerDependencies[dep] = version;
<ide> }
<ide> } | 1 |
Text | Text | add a badge with latest npm package published | b157088e717a2a47f691c1d6322b735bd8e81dd7 | <ide><path>README.md
<del># [React](https://facebook.github.io/react) [](https://travis-ci.org/facebook/react)
<add># [React](https://facebook.github.io/react) [](https://travis-ci.org/facebook/react) [](http://badge.fury.io/js/react)
<ide>
<ide> React is a JavaScript library for building user interfaces.
<ide> | 1 |
Go | Go | replace multiline with empty string not space | 1e723bc95a61fb6c46af82557c128d1e95a33a99 | <ide><path>buildfile.go
<ide> func (b *buildFile) Build(context io.Reader) (string, error) {
<ide> return "", err
<ide> }
<ide> dockerfile := string(fileBytes)
<del> dockerfile = lineContinuation.ReplaceAllString(dockerfile, " ")
<add> dockerfile = lineContinuation.ReplaceAllString(dockerfile, "")
<ide> stepN := 0
<ide> for _, line := range strings.Split(dockerfile, "\n") {
<ide> line = strings.Trim(strings.Replace(line, "\t", " ", -1), " \t\r\n") | 1 |
Javascript | Javascript | optimize outline rendering of mmd | 501f2da27291d3244e184bc837953c03e18bf111 | <ide><path>examples/js/loaders/MMDLoader.js
<ide> THREE.MMDHelper.prototype = {
<ide>
<ide> add: function ( mesh ) {
<ide>
<add> if ( ! ( mesh instanceof THREE.SkinnedMesh ) ) {
<add>
<add> throw new Error( 'THREE.MMDHelper.add() accepts only THREE.SkinnedMesh instance.' );
<add>
<add> }
<add>
<ide> mesh.mixer = null;
<ide> mesh.ikSolver = null;
<ide> mesh.grantSolver = null;
<ide> THREE.MMDHelper.prototype = {
<ide>
<ide> },
<ide>
<del> renderOutline: function ( scene, camera ) {
<add> renderOutline: function () {
<ide>
<del> var tmpEnabled = this.renderer.shadowMap.enabled;
<del> this.renderer.shadowMap.enabled = false;
<add> var invisibledObjects = [];
<add> var setInvisible;
<add> var restoreVisible;
<ide>
<del> this.setupOutlineRendering();
<del> this.callRender( scene, camera );
<add> return function renderOutline( scene, camera ) {
<ide>
<del> this.renderer.shadowMap.enabled = tmpEnabled;
<add> var self = this;
<ide>
<del> },
<add> if ( setInvisible === undefined ) {
<add>
<add> setInvisible = function ( object ) {
<add>
<add> if ( ! object.visible || ! object.layers.test( camera.layers ) ) return;
<add>
<add> // any types else to skip?
<add> if ( object instanceof THREE.Scene ||
<add> object instanceof THREE.Bone ||
<add> object instanceof THREE.Light ||
<add> object instanceof THREE.Camera ||
<add> object instanceof THREE.Audio ||
<add> object instanceof THREE.AudioListener ) return;
<add>
<add> if ( object instanceof THREE.SkinnedMesh ) {
<add>
<add> for ( var i = 0, il = self.meshes.length; i < il; i ++ ) {
<add>
<add> if ( self.meshes[ i ] === object ) return;
<add>
<add> }
<add>
<add> }
<add>
<add> object.layers.mask &= ~ camera.layers.mask;
<add> invisibledObjects.push( object );
<add>
<add> };
<add>
<add> }
<add>
<add> if ( restoreVisible === undefined ) {
<add>
<add> restoreVisible = function () {
<add>
<add> for ( var i = 0, il = invisibledObjects.length; i < il; i ++ ) {
<add>
<add> invisibledObjects[ i ].layers.mask |= camera.layers.mask;
<add>
<add> }
<add>
<add> invisibledObjects.length = 0;
<add>
<add> };
<add>
<add> }
<add>
<add> scene.traverse( setInvisible );
<add>
<add> var tmpEnabled = this.renderer.shadowMap.enabled;
<add> this.renderer.shadowMap.enabled = false;
<add>
<add> this.setupOutlineRendering();
<add> this.callRender( scene, camera );
<add>
<add> this.renderer.shadowMap.enabled = tmpEnabled;
<add>
<add> restoreVisible();
<add>
<add> };
<add>
<add> }(),
<ide>
<ide> callRender: function ( scene, camera ) {
<ide> | 1 |
Ruby | Ruby | fix typo in postgres requirement | 3bdce1a7fa12ec9e779edb429971249fefe9a501 | <ide><path>Library/Homebrew/requirements.rb
<ide> def message; <<-EOS.undent
<ide> end
<ide> end
<ide>
<del>class PostgresInstalled < Requirement
<add>class PostgresqlInstalled < Requirement
<ide> def fatal?; true; end
<ide>
<ide> def satisfied? | 1 |
PHP | PHP | fix path that doesn't exist | 855bb1b07e1d0cd8e88115849baf4c5c02136a95 | <ide><path>src/Illuminate/Foundation/Providers/PublisherServiceProvider.php
<ide> protected function registerViewPublisher()
<ide>
<ide> $this->app->bindShared('view.publisher', function($app)
<ide> {
<del> $viewPath = $app['path.views'];
<add> $viewPath = $app['path'].'/resources/views';;
<ide>
<ide> // Once we have created the view publisher, we will set the default packages
<ide> // path on this object so that it knows where to find all of the packages | 1 |
Go | Go | remove a test that was moved to docker/cli | 1a03bd396b21f0c291499e1c5bd185d23e20ffc1 | <ide><path>integration-cli/docker_cli_cp_from_container_test.go
<ide> func (s *DockerSuite) TestCpFromErrSrcNotDir(c *check.C) {
<ide> c.Assert(isCpNotDir(err), checker.True, check.Commentf("expected IsNotDir error, but got %T: %s", err, err))
<ide> }
<ide>
<del>// Test for error when SRC is a valid file or directory,
<del>// bu the DST parent directory does not exist.
<del>func (s *DockerSuite) TestCpFromErrDstParentNotExists(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<del> containerID := makeTestContainer(c, testContainerOptions{addContent: true})
<del>
<del> tmpDir := getTestDir(c, "test-cp-from-err-dst-parent-not-exists")
<del> defer os.RemoveAll(tmpDir)
<del>
<del> makeTestContentInDir(c, tmpDir)
<del>
<del> // Try with a file source.
<del> srcPath := containerCpPath(containerID, "/file1")
<del> dstPath := cpPath(tmpDir, "notExists", "file1")
<del> _, dstStatErr := os.Lstat(filepath.Dir(dstPath))
<del> c.Assert(os.IsNotExist(dstStatErr), checker.True)
<del>
<del> err := runDockerCp(c, srcPath, dstPath, nil)
<del> c.Assert(err.Error(), checker.Contains, dstStatErr.Error())
<del>
<del> // Try with a directory source.
<del> srcPath = containerCpPath(containerID, "/dir1")
<del>
<del> err = runDockerCp(c, srcPath, dstPath, nil)
<del> c.Assert(err.Error(), checker.Contains, dstStatErr.Error())
<del>}
<del>
<ide> // Test for error when DST ends in a trailing
<ide> // path separator but exists as a file.
<ide> func (s *DockerSuite) TestCpFromErrDstNotDir(c *check.C) { | 1 |
Mixed | Ruby | add prepend option to protect_from_forgery | 0074bbb07bb9c0a2e6a134a4230bf3afac8a71b1 | <ide><path>actionpack/CHANGELOG.md
<add>* Allow you to pass `prepend: false` to protect_from_forgery to have the
<add> verification callback appended instead of prepended to the chain.
<add> This allows you to let the verification step depend on prior callbacks.
<add> Example:
<add>
<add> class ApplicationController < ActionController::Base
<add> before_action :authenticate
<add> protect_from_forgery unless: -> { @authenticated_by.oauth? }
<add>
<add> private
<add> def authenticate
<add> if oauth_request?
<add> # authenticate with oauth
<add> @authenticated_by = 'oauth'.inquiry
<add> else
<add> # authenticate with cookies
<add> @authenticated_by = 'cookie'.inquiry
<add> end
<add> end
<add> end
<add>
<add> *Josef Šimánek*
<add>
<ide> * Remove `ActionController::HideActions`
<ide>
<ide> *Ravil Bayramgalin*
<ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> module ClassMethods
<ide> #
<ide> # * <tt>:only/:except</tt> - Only apply forgery protection to a subset of actions. Like <tt>only: [ :create, :create_all ]</tt>.
<ide> # * <tt>:if/:unless</tt> - Turn off the forgery protection entirely depending on the passed proc or method reference.
<add> # * <tt>:prepend</tt> - By default, the verification of the authentication token is added to the front of the
<add> # callback chain. If you need to make the verification depend on other callbacks, like authentication methods
<add> # (say cookies vs oauth), this might not work for you. Pass <tt>prepend: false</tt> to just add the
<add> # verification callback in the position of the protect_from_forgery call. This means any callbacks added
<add> # before are run first.
<ide> # * <tt>:with</tt> - Set the method to handle unverified request.
<ide> #
<ide> # Valid unverified request handling methods are:
<ide> # * <tt>:exception</tt> - Raises ActionController::InvalidAuthenticityToken exception.
<ide> # * <tt>:reset_session</tt> - Resets the session.
<ide> # * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
<ide> def protect_from_forgery(options = {})
<add> options = options.reverse_merge(prepend: true)
<add>
<ide> self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
<ide> self.request_forgery_protection_token ||= :authenticity_token
<del> prepend_before_action :verify_authenticity_token, options
<add> before_action :verify_authenticity_token, options
<ide> append_after_action :verify_same_origin_request
<ide> end
<ide>
<ide><path>actionpack/test/controller/request_forgery_protection_test.rb
<ide> def try_to_reset_session
<ide> end
<ide> end
<ide>
<add>class PrependProtectForgeryBaseController < ActionController::Base
<add> before_action :custom_action
<add> attr_accessor :called_callbacks
<add>
<add> def index
<add> render inline: 'OK'
<add> end
<add>
<add> protected
<add>
<add> def add_called_callback(name)
<add> @called_callbacks ||= []
<add> @called_callbacks << name
<add> end
<add>
<add>
<add> def custom_action
<add> add_called_callback("custom_action")
<add> end
<add>
<add> def verify_authenticity_token
<add> add_called_callback("verify_authenticity_token")
<add> end
<add>end
<add>
<ide> class FreeCookieController < RequestForgeryProtectionControllerUsingResetSession
<ide> self.allow_forgery_protection = false
<ide>
<ide> def assert_blocked
<ide> end
<ide> end
<ide>
<add>class PrependProtectForgeryBaseControllerTest < ActionController::TestCase
<add> PrependTrueController = Class.new(PrependProtectForgeryBaseController) do
<add> protect_from_forgery prepend: true
<add> end
<add>
<add> PrependFalseController = Class.new(PrependProtectForgeryBaseController) do
<add> protect_from_forgery prepend: false
<add> end
<add>
<add> PrependDefaultController = Class.new(PrependProtectForgeryBaseController) do
<add> protect_from_forgery
<add> end
<add>
<add> def test_verify_authenticity_token_is_prepended
<add> @controller = PrependTrueController.new
<add> get :index
<add> expected_callback_order = ["verify_authenticity_token", "custom_action"]
<add> assert_equal(expected_callback_order, @controller.called_callbacks)
<add> end
<add>
<add> def test_verify_authenticity_token_is_not_prepended
<add> @controller = PrependFalseController.new
<add> get :index
<add> expected_callback_order = ["custom_action", "verify_authenticity_token"]
<add> assert_equal(expected_callback_order, @controller.called_callbacks)
<add> end
<add>
<add> def test_verify_authenticity_token_is_prepended_by_default
<add> @controller = PrependDefaultController.new
<add> get :index
<add> expected_callback_order = ["verify_authenticity_token", "custom_action"]
<add> assert_equal(expected_callback_order, @controller.called_callbacks)
<add> end
<add>end
<add>
<ide> class FreeCookieControllerTest < ActionController::TestCase
<ide> def setup
<ide> @controller = FreeCookieController.new | 3 |
PHP | PHP | update reserved names in generatorcommand | 6a05d150eb828c852960517f9d15d99ea42f0f41 | <ide><path>src/Illuminate/Console/GeneratorCommand.php
<ide> abstract class GeneratorCommand extends Command
<ide> 'endif',
<ide> 'endswitch',
<ide> 'endwhile',
<add> 'enum',
<ide> 'eval',
<ide> 'exit',
<ide> 'extends',
<ide> abstract class GeneratorCommand extends Command
<ide> 'interface',
<ide> 'isset',
<ide> 'list',
<add> 'match',
<ide> 'namespace',
<ide> 'new',
<ide> 'or',
<ide> 'print',
<ide> 'private',
<ide> 'protected',
<ide> 'public',
<add> 'readonly',
<ide> 'require',
<ide> 'require_once',
<ide> 'return', | 1 |
Javascript | Javascript | improve test case | 70da0dd0432299c674e603fd1efd4d321ad1fa60 | <ide><path>test/configCases/trusted-types/devtool-eval/index.js
<del>it("should pass TrustedScript to eval", function() {
<del> class TrustedScript {
<del> constructor(script) {
<del> this._script = script;
<del> }
<del> };
<del>
<add>it("should pass TrustedScript to eval", function () {
<ide> var policy = __webpack_require__.tt();
<del> policy.createScript = jest.fn((script) => {
<add> policy.createScript = jest.fn(script => {
<ide> expect(typeof script).toEqual("string");
<ide> return new TrustedScript(script);
<ide> });
<ide>
<del> const globalEval = eval;
<del> window.module = {};
<del> window.eval = jest.fn((x) => {
<del> expect(x).toBeInstanceOf(TrustedScript);
<del> return globalEval(x._script);
<del> });
<del>
<ide> require("./test.js");
<ide> expect(window.module.exports).toBeInstanceOf(Object);
<del> expect(window.module.exports.foo).toEqual('bar');
<add> expect(window.module.exports.foo).toEqual("bar");
<ide>
<del> const testPattern = "var test = {\\s*foo: \'bar\'\\s*};\\s*module.exports = test;";
<add> const testPattern =
<add> "var test = {\\s*foo: 'bar'\\s*};\\s*module.exports = test;";
<ide> expect(policy.createScript).toBeCalledWith(
<ide> expect.stringMatching(testPattern)
<ide> );
<ide> it("should pass TrustedScript to eval", function() {
<ide> })
<ide> );
<ide> });
<add>
<add>class TrustedScript {
<add> constructor(script) {
<add> this._script = script;
<add> }
<add>}
<add>
<add>let globalEval;
<add>beforeEach(done => {
<add> globalEval = eval;
<add> window.module = {};
<add> window.eval = jest.fn(x => {
<add> expect(x).toBeInstanceOf(TrustedScript);
<add> return globalEval(x._script);
<add> });
<add> done();
<add>});
<add>
<add>afterEach(done => {
<add> delete window.module;
<add> window.eval = globalEval;
<add> done();
<add>}); | 1 |
Text | Text | add issue templates | 7c524d631e4c0fd0531d02d6a155fc95a3e90810 | <ide><path>.github/ISSUE_TEMPLATE/bug-report.md
<add>---
<add>name: "\U0001F41B Bug Report"
<add>about: Submit a bug report to help us improve PyTorch Transformers
<add>---
<add>
<add>## 🐛 Bug
<add>
<add><!-- A clear and concise description of what the bug is. -->
<add>
<add>## To Reproduce
<add>
<add>Steps to reproduce the behavior:
<add>
<add>1.
<add>2.
<add>3.
<add>
<add><!-- If you have a code sample, error messages, stack traces, please provide it here as well. -->
<add>
<add>## Expected behavior
<add>
<add><!-- A clear and concise description of what you expected to happen. -->
<add>
<add>## Environment
<add>
<add>* OS:
<add>* Python version:
<add>* PyTorch version:
<add>* PyTorch Transformers version (or branch):
<add>* Using GPU ?
<add>* Distributed of parallel setup ?
<add>* Any other relevant information:
<add>
<add>## Additional context
<add>
<add><!-- Add any other context about the problem here. -->
<ide>\ No newline at end of file
<ide><path>.github/ISSUE_TEMPLATE/feature-request.md
<add>---
<add>name: "\U0001F680 Feature Request"
<add>about: Submit a proposal/request for a new PyTorch Transformers feature
<add>---
<add>
<add>## 🚀 Feature
<add>
<add><!-- A clear and concise description of the feature proposal. Please provide a link to the paper and code in case they exist. -->
<add>
<add>## Motivation
<add>
<add><!-- Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too. -->
<add>
<add>## Additional context
<add>
<add><!-- Add any other context or screenshots about the feature request here. -->
<ide>\ No newline at end of file
<ide><path>.github/ISSUE_TEMPLATE/migration.md
<add>---
<add>name: "\U0001F4DA Migration from PyTorch-pretrained-Bert"
<add>about: Report a problem when migrating from PyTorch-pretrained-Bert to PyTorch-Transformers
<add>---
<add>
<add>## 📚 Migration
<add>
<add><!-- Give at least the following information -->
<add>
<add>Model I am using (Bert, XLNet....):
<add>
<add>The problem arise when using:
<add>* [ ] the official example scripts
<add>* [ ] my own modified scripts
<add>
<add>The tasks I am working on is:
<add>* [ ] an official GLUE/SQUaD task: (give the name)
<add>* [ ] my own task or dataset: (give details)
<add>
<add>Language I am using the model on (English, Chinese....):
<add>
<add>Details of the issue:
<add>
<add><!-- A clear and concise description of the migration issue. If you have code snippets, please provide it here as well. -->
<add>
<add>## Environment
<add>
<add>* OS:
<add>* Python version:
<add>* PyTorch version:
<add>* PyTorch Transformers version (or branch):
<add>* Using GPU ?
<add>* Distributed of parallel setup ?
<add>* Any other relevant information:
<add>
<add>## Checklist
<add>
<add>- [ ] I have read the migration guide in the readme.
<add>- [ ] I checked if a related official extension example runs on my machine.
<add>
<add>## Additional context
<add>
<add><!-- Add any other context about the problem here. -->
<ide>\ No newline at end of file
<ide><path>.github/ISSUE_TEMPLATE/question-help.md
<add>---
<add>name: "❓Questions & Help"
<add>about: Start a general discussion related to PyTorch Transformers
<add>---
<add>
<add>## ❓ Questions & Help
<add>
<add><!-- A clear and concise description of the question. -->
<ide>\ No newline at end of file | 4 |
Java | Java | assert context uniqueness against merged config | 7658d856cac027ae367f04833bee6c43c62b5534 | <ide><path>spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java
<ide> private static void convertContextConfigToConfigAttributesAndAddToList(ContextCo
<ide> * never {@code null}
<ide> * @throws IllegalArgumentException if the supplied class is {@code null}; if
<ide> * neither {@code @ContextConfiguration} nor {@code @ContextHierarchy} is
<del> * <em>present</em> on the supplied class; if a given class in the class hierarchy
<add> * <em>present</em> on the supplied class; or if a given class in the class hierarchy
<ide> * declares both {@code @ContextConfiguration} and {@code @ContextHierarchy} as
<del> * top-level annotations; or if individual {@code @ContextConfiguration}
<del> * elements within a {@code @ContextHierarchy} declaration on a given class
<del> * in the class hierarchy do not define unique context configuration.
<add> * top-level annotations.
<ide> *
<ide> * @since 3.2.2
<ide> * @see #buildContextHierarchyMap(Class)
<ide> else if (contextHierarchyDeclaredLocally) {
<ide> convertContextConfigToConfigAttributesAndAddToList(contextConfiguration, declaringClass,
<ide> configAttributesList);
<ide> }
<del>
<del> // Check for uniqueness
<del> Set<ContextConfigurationAttributes> configAttributesSet = new HashSet<ContextConfigurationAttributes>(
<del> configAttributesList);
<del> if (configAttributesSet.size() != configAttributesList.size()) {
<del> String msg = String.format("The @ContextConfiguration elements configured via "
<del> + "@ContextHierarchy in test class [%s] must define unique contexts to load.",
<del> declaringClass.getName());
<del> logger.error(msg);
<del> throw new IllegalStateException(msg);
<del> }
<ide> }
<ide> else {
<ide> // This should theoretically actually never happen...
<ide> else if (contextHierarchyDeclaredLocally) {
<ide> * (must not be {@code null})
<ide> * @return a map of context configuration attributes for the context hierarchy,
<ide> * keyed by context hierarchy level name; never {@code null}
<add> * @throws IllegalArgumentException if the lists of context configuration
<add> * attributes for each level in the {@code @ContextHierarchy} do not define
<add> * unique context configuration within the overall hierarchy.
<ide> *
<ide> * @since 3.2.2
<ide> * @see #resolveContextHierarchyAttributes(Class)
<ide> static Map<String, List<ContextConfigurationAttributes>> buildContextHierarchyMa
<ide> }
<ide> }
<ide>
<add> // Check for uniqueness
<add> Set<List<ContextConfigurationAttributes>> set = new HashSet<List<ContextConfigurationAttributes>>(map.values());
<add> if (set.size() != map.size()) {
<add> String msg = String.format("The @ContextConfiguration elements configured via "
<add> + "@ContextHierarchy in test class [%s] and its superclasses must "
<add> + "define unique contexts per hierarchy level.", testClass.getName());
<add> logger.error(msg);
<add> throw new IllegalStateException(msg);
<add> }
<add>
<ide> return map;
<ide> }
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/context/ContextLoaderUtilsContextHierarchyTests.java
<ide> import java.util.Map;
<ide>
<ide> import org.junit.Test;
<add>import org.springframework.context.ApplicationContextInitializer;
<add>import org.springframework.context.ConfigurableApplicationContext;
<ide> import org.springframework.test.context.support.AnnotationConfigContextLoader;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<ide> public void resolveContextHierarchyAttributesForTestClassHierarchyWithMultiLevel
<ide> assertThat(configAttributesListClassLevel3.get(2).getLocations()[0], equalTo("3-C.xml"));
<ide> }
<ide>
<del> private void assertContextConfigEntriesAreNotUnique(Class<?> testClass) {
<del> try {
<del> resolveContextHierarchyAttributes(testClass);
<del> fail("Should throw an IllegalStateException");
<del> }
<del> catch (IllegalStateException e) {
<del> String msg = String.format(
<del> "The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] must define unique contexts to load.",
<del> testClass.getName());
<del> assertEquals(msg, e.getMessage());
<del> }
<del> }
<del>
<del> @Test
<del> public void resolveContextHierarchyAttributesForSingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig() {
<del> assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig.class);
<del> }
<del>
<del> @Test
<del> public void resolveContextHierarchyAttributesForSingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig() {
<del> assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig.class);
<del> }
<del>
<ide> @Test
<ide> public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchies() {
<ide> Map<String, List<ContextConfigurationAttributes>> map = buildContextHierarchyMap(TestClass3WithMultiLevelContextHierarchy.class);
<ide> public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHi
<ide> assertThat(level3Config.get(0).getLocations()[0], is("2-C.xml"));
<ide> }
<ide>
<add> private void assertContextConfigEntriesAreNotUnique(Class<?> testClass) {
<add> try {
<add> buildContextHierarchyMap(testClass);
<add> fail("Should throw an IllegalStateException");
<add> }
<add> catch (IllegalStateException e) {
<add> String msg = String.format(
<add> "The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] and its superclasses must define unique contexts per hierarchy level.",
<add> testClass.getName());
<add> assertEquals(msg, e.getMessage());
<add> }
<add> }
<add>
<add> @Test
<add> public void buildContextHierarchyMapForSingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig() {
<add> assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig.class);
<add> }
<add>
<add> @Test
<add> public void buildContextHierarchyMapForSingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig() {
<add> assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig.class);
<add> }
<add>
<add> /**
<add> * Used to reproduce bug reported in https://jira.springsource.org/browse/SPR-10997
<add> */
<add> @Test
<add> public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchiesAndOverriddenInitializers() {
<add> Map<String, List<ContextConfigurationAttributes>> map = buildContextHierarchyMap(TestClass2WithMultiLevelContextHierarchyWithOverriddenInitializers.class);
<add>
<add> assertThat(map.size(), is(2));
<add> assertThat(map.keySet(), hasItems("alpha", "beta"));
<add>
<add> List<ContextConfigurationAttributes> alphaConfig = map.get("alpha");
<add> assertThat(alphaConfig.size(), is(2));
<add> assertThat(alphaConfig.get(0).getLocations().length, is(1));
<add> assertThat(alphaConfig.get(0).getLocations()[0], is("1-A.xml"));
<add> assertThat(alphaConfig.get(0).getInitializers().length, is(0));
<add> assertThat(alphaConfig.get(1).getLocations().length, is(0));
<add> assertThat(alphaConfig.get(1).getInitializers().length, is(1));
<add> assertEquals(DummyApplicationContextInitializer.class, alphaConfig.get(1).getInitializers()[0]);
<add>
<add> List<ContextConfigurationAttributes> betaConfig = map.get("beta");
<add> assertThat(betaConfig.size(), is(2));
<add> assertThat(betaConfig.get(0).getLocations().length, is(1));
<add> assertThat(betaConfig.get(0).getLocations()[0], is("1-B.xml"));
<add> assertThat(betaConfig.get(0).getInitializers().length, is(0));
<add> assertThat(betaConfig.get(1).getLocations().length, is(0));
<add> assertThat(betaConfig.get(1).getInitializers().length, is(1));
<add> assertEquals(DummyApplicationContextInitializer.class, betaConfig.get(1).getInitializers()[0]);
<add> }
<add>
<ide>
<ide> // -------------------------------------------------------------------------
<ide>
<ide> private static class SingleTestClassWithMultiLevelContextHierarchyWithEmptyConte
<ide> private static class SingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig {
<ide> }
<ide>
<add> /**
<add> * Used to reproduce bug reported in https://jira.springsource.org/browse/SPR-10997
<add> */
<add> @ContextHierarchy({//
<add> //
<add> @ContextConfiguration(name = "alpha", locations = "1-A.xml"),//
<add> @ContextConfiguration(name = "beta", locations = "1-B.xml") //
<add> })
<add> private static class TestClass1WithMultiLevelContextHierarchyWithUniqueContextConfig {
<add> }
<add>
<add> /**
<add> * Used to reproduce bug reported in https://jira.springsource.org/browse/SPR-10997
<add> */
<add> @ContextHierarchy({//
<add> //
<add> @ContextConfiguration(name = "alpha", initializers = DummyApplicationContextInitializer.class),//
<add> @ContextConfiguration(name = "beta", initializers = DummyApplicationContextInitializer.class) //
<add> })
<add> private static class TestClass2WithMultiLevelContextHierarchyWithOverriddenInitializers extends
<add> TestClass1WithMultiLevelContextHierarchyWithUniqueContextConfig {
<add> }
<add>
<add> /**
<add> * Used to reproduce bug reported in https://jira.springsource.org/browse/SPR-10997
<add> */
<add> private static class DummyApplicationContextInitializer implements
<add> ApplicationContextInitializer<ConfigurableApplicationContext> {
<add>
<add> @Override
<add> public void initialize(ConfigurableApplicationContext applicationContext) {
<add> /* no-op */
<add> }
<add>
<add> }
<add>
<ide> } | 2 |
PHP | PHP | use openssl constants rather than a bool | a05d02db9d1f7e02e12a10505dc331cdd5924aec | <ide><path>src/Utility/Crypto/OpenSsl.php
<ide> public static function encrypt($plain, $key, $hmacSalt = null)
<ide> $ivSize = openssl_cipher_iv_length($method);
<ide>
<ide> $iv = openssl_random_pseudo_bytes($ivSize);
<del> return $iv . openssl_encrypt($plain, $method, $key, true, $iv);
<add> return $iv . openssl_encrypt($plain, $method, $key, OPENSSL_RAW_DATA, $iv);
<ide> }
<ide>
<ide> /**
<ide> public static function decrypt($cipher, $key)
<ide> $iv = mb_substr($cipher, 0, $ivSize, '8bit');
<ide>
<ide> $cipher = mb_substr($cipher, $ivSize, null, '8bit');
<del> return openssl_decrypt($cipher, $method, $key, true, $iv);
<add> return openssl_decrypt($cipher, $method, $key, OPENSSL_RAW_DATA, $iv);
<ide> }
<ide> } | 1 |
Python | Python | add the dbapi_hook | f77205994b8cf3d9385b403ffc633304e2f539bd | <ide><path>airflow/hooks/dbapi_hook.py
<add>from datetime import datetime
<add>import numpy
<add>import logging
<add>
<add>from airflow.hooks.base_hook import BaseHook
<add>from airflow.utils import AirflowException
<add>
<add>
<add>class DbApiHook(BaseHook):
<add> """
<add> Abstract base class for sql hooks.
<add> """
<add>
<add> """
<add> Override to provide the connection name.
<add> """
<add> conn_name_attr = None
<add>
<add> """
<add> Override to have a default connection id for a particular dbHook
<add> """
<add> default_conn_name = 'default_conn_id'
<add>
<add> """
<add> Override if this db supports autocommit.
<add> """
<add> supports_autocommit = False
<add>
<add> def __init__(self, **kwargs):
<add> try:
<add> self.conn_id_name = kwargs[self.conn_name_attr]
<add> except NameError:
<add> raise AirflowException("conn_name_attr is not defined")
<add> except KeyError:
<add> raise AirflowException(
<add> self.conn_name_attr + " was not passed in the kwargs")
<add>
<add> def get_pandas_df(self, sql, parameters=None):
<add> '''
<add> Executes the sql and returns a pandas dataframe
<add> '''
<add> import pandas.io.sql as psql
<add> conn = self.get_conn()
<add> df = psql.read_sql(sql, con=conn)
<add> conn.close()
<add> return df
<add>
<add> def get_records(self, sql, parameters=None):
<add> '''
<add> Executes the sql and returns a set of records.
<add> '''
<add> conn = self.get_conn()
<add> cur = self.get_cursor()
<add> cur.execute(sql)
<add> rows = cur.fetchall()
<add> cur.close()
<add> conn.close()
<add> return rows
<add>
<add> def get_first(self, sql, parameters=None):
<add> '''
<add> Executes the sql and returns a set of records.
<add> '''
<add> conn = self.get_conn()
<add> cur = conn.cursor()
<add> cur.execute(sql)
<add> rows = cur.fetchone()
<add> cur.close()
<add> conn.close()
<add> return rows
<add>
<add> def run(self, sql, autocommit=False, parameters=None):
<add> """
<add> Runs a command
<add> """
<add> conn = self.get_conn()
<add> if self.supports_autocommit:
<add> conn.autocommit = autocommit
<add> cur = conn.cursor()
<add> cur.execute(sql)
<add> conn.commit()
<add> cur.close()
<add> conn.close()
<add>
<add> def get_cursor(self):
<add> """Returns a cursor"""
<add> return self.get_conn().cursor()
<add>
<add> def insert_rows(self, table, rows, target_fields=None, commit_every=1000):
<add> """
<add> A generic way to insert a set of tuples into a table,
<add> the whole set of inserts is treated as one transaction
<add> """
<add> if target_fields:
<add> target_fields = ", ".join(target_fields)
<add> target_fields = "({})".format(target_fields)
<add> else:
<add> target_fields = ''
<add> conn = self.get_conn()
<add> cur = conn.cursor()
<add> if self.supports_autocommit:
<add> cur.execute('SET autocommit = 0')
<add> conn.commit()
<add> i = 0
<add> for row in rows:
<add> i += 1
<add> l = []
<add> for cell in row:
<add> if isinstance(cell, basestring):
<add> l.append("'" + str(cell).replace("'", "''") + "'")
<add> elif cell is None:
<add> l.append('NULL')
<add> elif isinstance(cell, numpy.datetime64):
<add> l.append("'" + str(cell) + "'")
<add> elif isinstance(cell, datetime):
<add> l.append("'" + cell.isoformat() + "'")
<add> else:
<add> l.append(str(cell))
<add> values = tuple(l)
<add> sql = "INSERT INTO {0} {1} VALUES ({2});".format(
<add> table,
<add> target_fields,
<add> ",".join(values))
<add> cur.execute(sql)
<add> if i % commit_every == 0:
<add> conn.commit()
<add> logging.info(
<add> "Loaded {i} into {table} rows so far".format(**locals()))
<add> conn.commit()
<add> cur.close()
<add> conn.close()
<add> logging.info(
<add> "Done loading. Loaded a total of {i} rows".format(**locals()))
<add>
<add> def get_conn(self):
<add> """
<add> Retuns a sql connection that can be used to retrieve a cursor.
<add> """
<add> raise NotImplemented() | 1 |
Javascript | Javascript | remove domain enter and exit | 2c94424a0d9941f7e2290f86f3417b66905acdef | <ide><path>lib/timers.js
<ide> function listOnTimeout() {
<ide> continue;
<ide> }
<ide>
<del> var domain = timer.domain;
<del> if (domain) {
<del> domain.enter();
<del> }
<del>
<ide> tryOnTimeout(timer, list);
<del>
<del> if (domain)
<del> domain.exit();
<ide> }
<ide>
<ide> // If `L.peek(list)` returned nothing, the list was either empty or we have
<ide> var immediateQueue = new ImmediateList();
<ide> function processImmediate() {
<ide> var immediate = immediateQueue.head;
<ide> var tail = immediateQueue.tail;
<del> var domain;
<ide>
<ide> // Clear the linked list early in case new `setImmediate()` calls occur while
<ide> // immediate callbacks are executed
<ide> immediateQueue.head = immediateQueue.tail = null;
<ide>
<ide> while (immediate !== null) {
<del> domain = immediate.domain;
<del>
<ide> if (!immediate._onImmediate) {
<ide> immediate = immediate._idleNext;
<ide> continue;
<ide> }
<ide>
<del> if (domain)
<del> domain.enter();
<del>
<ide> // Save next in case `clearImmediate(immediate)` is called from callback
<ide> var next = immediate._idleNext;
<ide>
<ide> tryOnImmediate(immediate, tail);
<ide>
<del> if (domain)
<del> domain.exit();
<del>
<ide> // If `clearImmediate(immediate)` wasn't called from the callback, use the
<ide> // `immediate`'s next item
<ide> if (immediate._idleNext !== null) | 1 |
Javascript | Javascript | remove outdated comment | 1bee544a20633370d33a592d54ab44f2e6653e69 | <ide><path>lib/internal/util/inspect.js
<ide> function formatPromise(ctx, value, recurseTimes) {
<ide> if (state === kPending) {
<ide> output = [ctx.stylize('<pending>', 'special')];
<ide> } else {
<del> // Using `formatValue` is correct here without the need to fix the
<del> // indentation level.
<ide> ctx.indentationLvl += 2;
<ide> const str = formatValue(ctx, result, recurseTimes);
<ide> ctx.indentationLvl -= 2; | 1 |
Javascript | Javascript | remove obsolete todo comments | bdfeb798ad3b3a6eac5d0c24ec2136480907f783 | <ide><path>test/parallel/test-fs-read-stream-inherit.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide>
<del>// TODO Improved this test. test_ca.pem is too small. A proper test would
<del>// great a large utf8 (with multibyte chars) file and stream it in,
<del>// performing sanity checks throughout.
<del>
<ide> var path = require('path');
<ide> var fs = require('fs');
<ide> var fn = path.join(common.fixturesDir, 'elipses.txt');
<ide><path>test/parallel/test-fs-read-stream.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide>
<del>// TODO Improved this test. test_ca.pem is too small. A proper test would
<del>// great a large utf8 (with multibyte chars) file and stream it in,
<del>// performing sanity checks throughout.
<del>
<ide> var path = require('path');
<ide> var fs = require('fs');
<ide> var fn = path.join(common.fixturesDir, 'elipses.txt'); | 2 |
Javascript | Javascript | add tests for provider settings | 3cb5bad15db3b85490f29e24a4880c5dbcd60f43 | <ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide>
<ide> describe('configuration', function() {
<ide>
<add> it('should allow aHrefSanitizationWhitelist to be configured', function() {
<add> module(function($compileProvider) {
<add> expect($compileProvider.aHrefSanitizationWhitelist()).toEqual(/^\s*(https?|ftp|mailto|tel|file):/); // the default
<add> $compileProvider.aHrefSanitizationWhitelist(/other/);
<add> expect($compileProvider.aHrefSanitizationWhitelist()).toEqual(/other/);
<add> });
<add> inject();
<add> });
<add>
<add> it('should allow debugInfoEnabled to be configured', function() {
<add> module(function($compileProvider) {
<add> expect($compileProvider.debugInfoEnabled()).toBe(true); // the default
<add> $compileProvider.debugInfoEnabled(false);
<add> expect($compileProvider.debugInfoEnabled()).toBe(false);
<add> });
<add> inject();
<add> });
<add>
<add> it('should allow preAssignBindingsEnabled to be configured', function() {
<add> module(function($compileProvider) {
<add> expect($compileProvider.preAssignBindingsEnabled()).toBe(true); // the default
<add> $compileProvider.preAssignBindingsEnabled(false);
<add> expect($compileProvider.preAssignBindingsEnabled()).toBe(false);
<add> });
<add> inject();
<add> });
<add>
<add> it('should allow onChangesTtl to be configured', function() {
<add> module(function($compileProvider) {
<add> expect($compileProvider.onChangesTtl()).toBe(10); // the default
<add> $compileProvider.onChangesTtl(2);
<add> expect($compileProvider.onChangesTtl()).toBe(2);
<add> });
<add> inject();
<add> });
<add>
<add> it('should allow commentDirectivesEnabled to be configured', function() {
<add> module(function($compileProvider) {
<add> expect($compileProvider.commentDirectivesEnabled()).toBe(true); // the default
<add> $compileProvider.commentDirectivesEnabled(false);
<add> expect($compileProvider.commentDirectivesEnabled()).toBe(false);
<add> });
<add> inject();
<add> });
<add>
<add> it('should allow cssClassDirectivesEnabled to be configured', function() {
<add> module(function($compileProvider) {
<add> expect($compileProvider.cssClassDirectivesEnabled()).toBe(true); // the default
<add> $compileProvider.cssClassDirectivesEnabled(false);
<add> expect($compileProvider.cssClassDirectivesEnabled()).toBe(false);
<add> });
<add> inject();
<add> });
<add>
<ide> it('should register a directive', function() {
<ide> module(function() {
<ide> directive('div', function(log) { | 1 |
Go | Go | implement stringer interface | d9524d92a9ddf02fa8f209291032ce4e37cb2a3f | <ide><path>api/types/swarm/common.go
<ide> package swarm // import "github.com/docker/docker/api/types/swarm"
<ide>
<del>import "time"
<add>import (
<add> "strconv"
<add> "time"
<add>)
<ide>
<ide> // Version represents the internal object version.
<ide> type Version struct {
<ide> Index uint64 `json:",omitempty"`
<ide> }
<ide>
<add>// String implements fmt.Stringer interface.
<add>func (v Version) String() string {
<add> return strconv.FormatUint(v.Index, 10)
<add>}
<add>
<ide> // Meta is a base object inherited by most of the other once.
<ide> type Meta struct {
<ide> Version Version `json:",omitempty"`
<ide><path>client/config_update.go
<ide> package client // import "github.com/docker/docker/client"
<ide> import (
<ide> "context"
<ide> "net/url"
<del> "strconv"
<ide>
<ide> "github.com/docker/docker/api/types/swarm"
<ide> )
<ide> func (cli *Client) ConfigUpdate(ctx context.Context, id string, version swarm.Ve
<ide> return err
<ide> }
<ide> query := url.Values{}
<del> query.Set("version", strconv.FormatUint(version.Index, 10))
<add> query.Set("version", version.String())
<ide> resp, err := cli.post(ctx, "/configs/"+id+"/update", query, config, nil)
<ide> ensureReaderClosed(resp)
<ide> return err
<ide><path>client/node_update.go
<ide> package client // import "github.com/docker/docker/client"
<ide> import (
<ide> "context"
<ide> "net/url"
<del> "strconv"
<ide>
<ide> "github.com/docker/docker/api/types/swarm"
<ide> )
<ide>
<ide> // NodeUpdate updates a Node.
<ide> func (cli *Client) NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error {
<ide> query := url.Values{}
<del> query.Set("version", strconv.FormatUint(version.Index, 10))
<add> query.Set("version", version.String())
<ide> resp, err := cli.post(ctx, "/nodes/"+nodeID+"/update", query, node, nil)
<ide> ensureReaderClosed(resp)
<ide> return err
<ide><path>client/secret_update.go
<ide> package client // import "github.com/docker/docker/client"
<ide> import (
<ide> "context"
<ide> "net/url"
<del> "strconv"
<ide>
<ide> "github.com/docker/docker/api/types/swarm"
<ide> )
<ide> func (cli *Client) SecretUpdate(ctx context.Context, id string, version swarm.Ve
<ide> return err
<ide> }
<ide> query := url.Values{}
<del> query.Set("version", strconv.FormatUint(version.Index, 10))
<add> query.Set("version", version.String())
<ide> resp, err := cli.post(ctx, "/secrets/"+id+"/update", query, secret, nil)
<ide> ensureReaderClosed(resp)
<ide> return err
<ide><path>client/service_update.go
<ide> import (
<ide> "context"
<ide> "encoding/json"
<ide> "net/url"
<del> "strconv"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/swarm"
<ide> func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version
<ide> query.Set("rollback", options.Rollback)
<ide> }
<ide>
<del> query.Set("version", strconv.FormatUint(version.Index, 10))
<add> query.Set("version", version.String())
<ide>
<ide> if err := validateServiceSpec(service); err != nil {
<ide> return response, err
<ide><path>client/swarm_update.go
<ide> package client // import "github.com/docker/docker/client"
<ide>
<ide> import (
<ide> "context"
<del> "fmt"
<ide> "net/url"
<ide> "strconv"
<ide>
<ide> import (
<ide> // SwarmUpdate updates the swarm.
<ide> func (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error {
<ide> query := url.Values{}
<del> query.Set("version", strconv.FormatUint(version.Index, 10))
<del> query.Set("rotateWorkerToken", fmt.Sprintf("%v", flags.RotateWorkerToken))
<del> query.Set("rotateManagerToken", fmt.Sprintf("%v", flags.RotateManagerToken))
<del> query.Set("rotateManagerUnlockKey", fmt.Sprintf("%v", flags.RotateManagerUnlockKey))
<add> query.Set("version", version.String())
<add> query.Set("rotateWorkerToken", strconv.FormatBool(flags.RotateWorkerToken))
<add> query.Set("rotateManagerToken", strconv.FormatBool(flags.RotateManagerToken))
<add> query.Set("rotateManagerUnlockKey", strconv.FormatBool(flags.RotateManagerUnlockKey))
<ide> resp, err := cli.post(ctx, "/swarm/update", query, swarm, nil)
<ide> ensureReaderClosed(resp)
<ide> return err
<ide><path>client/volume_update.go
<ide> package client // import "github.com/docker/docker/client"
<ide> import (
<ide> "context"
<ide> "net/url"
<del> "strconv"
<ide>
<ide> "github.com/docker/docker/api/types/swarm"
<ide> "github.com/docker/docker/api/types/volume"
<ide> func (cli *Client) VolumeUpdate(ctx context.Context, volumeID string, version sw
<ide> }
<ide>
<ide> query := url.Values{}
<del> query.Set("version", strconv.FormatUint(version.Index, 10))
<add> query.Set("version", version.String())
<ide>
<ide> resp, err := cli.put(ctx, "/volumes/"+volumeID, query, options, nil)
<ide> ensureReaderClosed(resp) | 7 |
Javascript | Javascript | add `invalidheaders` test | 1e4187fcf4b8cc27df027fee2c4c266f17f14161 | <ide><path>lib/internal/http2/compat.js
<ide> let statusConnectionHeaderWarned = false;
<ide> // close as possible to the current require('http') API
<ide>
<ide> const assertValidHeader = hideStackFrames((name, value) => {
<del> if (name === '' || typeof name !== 'string') {
<add> if (name === '' || typeof name !== 'string' || name.indexOf(' ') >= 0) {
<ide> throw new ERR_INVALID_HTTP_TOKEN('Header name', name);
<ide> }
<ide> if (isPseudoHeader(name)) {
<ide><path>lib/internal/http2/util.js
<ide> const {
<ide> ERR_HTTP2_INVALID_CONNECTION_HEADERS,
<ide> ERR_HTTP2_INVALID_PSEUDOHEADER,
<ide> ERR_HTTP2_INVALID_SETTING_VALUE,
<del> ERR_INVALID_ARG_TYPE
<add> ERR_INVALID_ARG_TYPE,
<add> ERR_INVALID_HTTP_TOKEN
<ide> },
<ide> addCodeToName,
<ide> hideStackFrames
<ide> function mapToHeaders(map,
<ide> count++;
<ide> continue;
<ide> }
<add> if (key.indexOf(' ') >= 0) {
<add> throw new ERR_INVALID_HTTP_TOKEN('Header name', key);
<add> }
<ide> if (isIllegalConnectionSpecificHeader(key, value)) {
<ide> throw new ERR_HTTP2_INVALID_CONNECTION_HEADERS(key);
<ide> }
<ide><path>test/parallel/test-http2-invalidheaderfield.js
<add>'use strict';
<add>const common = require('../common');
<add>if (!common.hasCrypto) { common.skip('missing crypto'); }
<add>
<add>// Check for:
<add>// Spaced headers
<add>// Psuedo headers
<add>// Capitalized headers
<add>
<add>const http2 = require('http2');
<add>const { throws, strictEqual } = require('assert');
<add>
<add>const server = http2.createServer(common.mustCall((req, res) => {
<add> throws(() => {
<add> res.setHeader(':path', '/');
<add> }, {
<add> code: 'ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED'
<add> });
<add> throws(() => {
<add> res.setHeader('t est', 123);
<add> }, {
<add> code: 'ERR_INVALID_HTTP_TOKEN'
<add> });
<add> res.setHeader('TEST', 123);
<add> res.setHeader('test_', 123);
<add> res.setHeader(' test', 123);
<add> res.end();
<add>}));
<add>
<add>server.listen(0, common.mustCall(() => {
<add> const session1 = http2.connect(`http://localhost:${server.address().port}`);
<add> session1.request({ 'test_': 123, 'TEST': 123 })
<add> .on('end', common.mustCall(() => {
<add> session1.close();
<add> server.close();
<add> }));
<add>
<add> const session2 = http2.connect(`http://localhost:${server.address().port}`);
<add> session2.on('error', common.mustCall((e) => {
<add> strictEqual(e.code, 'ERR_INVALID_HTTP_TOKEN');
<add> }));
<add> throws(() => {
<add> session2.request({ 't est': 123 });
<add> }, {
<add> code: 'ERR_INVALID_HTTP_TOKEN'
<add> });
<add>
<add> const session3 = http2.connect(`http://localhost:${server.address().port}`);
<add> session3.on('error', common.mustCall((e) => {
<add> strictEqual(e.code, 'ERR_INVALID_HTTP_TOKEN');
<add> }));
<add> throws(() => {
<add> session3.request({ ' test': 123 });
<add> }, {
<add> code: 'ERR_INVALID_HTTP_TOKEN'
<add> });
<add>
<add> const session4 = http2.connect(`http://localhost:${server.address().port}`);
<add> throws(() => {
<add> session4.request({ ':test': 123 });
<add> }, {
<add> code: 'ERR_HTTP2_INVALID_PSEUDOHEADER'
<add> });
<add> session4.close();
<add>}));
<ide><path>test/parallel/test-http2-invalidheaderfields-client.js
<ide> const server1 = http2.createServer();
<ide> server1.listen(0, common.mustCall(() => {
<ide> const session = http2.connect(`http://localhost:${server1.address().port}`);
<ide> // Check for req headers
<del> session.request({ 'no underscore': 123 });
<add> assert.throws(() => {
<add> session.request({ 'no underscore': 123 });
<add> }, {
<add> code: 'ERR_INVALID_HTTP_TOKEN'
<add> });
<ide> session.on('error', common.mustCall((e) => {
<ide> assert.strictEqual(e.code, 'ERR_INVALID_HTTP_TOKEN');
<ide> server1.close();
<ide> server1.listen(0, common.mustCall(() => {
<ide>
<ide> const server2 = http2.createServer(common.mustCall((req, res) => {
<ide> // check for setHeader
<del> res.setHeader('x y z', 123);
<add> assert.throws(() => {
<add> res.setHeader('x y z', 123);
<add> }, {
<add> code: 'ERR_INVALID_HTTP_TOKEN'
<add> });
<ide> res.end();
<ide> }));
<ide>
<ide> server2.listen(0, common.mustCall(() => {
<ide> const session = http2.connect(`http://localhost:${server2.address().port}`);
<ide> const req = session.request();
<del> req.on('error', common.mustCall((e) => {
<del> assert.strictEqual(e.code, 'ERR_HTTP2_STREAM_ERROR');
<add> req.on('end', common.mustCall(() => {
<ide> session.close();
<ide> server2.close();
<ide> }));
<ide> const server3 = http2.createServer(common.mustCall((req, res) => {
<ide> 'an invalid header': 123
<ide> });
<ide> }), {
<del> code: 'ERR_HTTP2_INVALID_STREAM'
<add> code: 'ERR_INVALID_HTTP_TOKEN'
<ide> });
<ide> res.end();
<ide> }));
<ide>
<ide> server3.listen(0, common.mustCall(() => {
<ide> const session = http2.connect(`http://localhost:${server3.address().port}`);
<ide> const req = session.request();
<del> req.on('error', common.mustCall((e) => {
<del> assert.strictEqual(e.code, 'ERR_HTTP2_STREAM_ERROR');
<add> req.on('end', common.mustCall(() => {
<ide> server3.close();
<ide> session.close();
<ide> })); | 4 |
Javascript | Javascript | introduce synthetic scrolling | 5a47f179e3cad7d68c2bf323372d035cc985c6e6 | <ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> expect(element.querySelectorAll('.line-number').length).toBe(9)
<ide> expect(element.querySelectorAll('.line').length).toBe(9)
<ide>
<del> component.refs.scroller.scrollTop = 5 * component.measurements.lineHeight
<add> component.setScrollTop(5 * component.getLineHeight())
<ide> await component.getNextUpdatePromise()
<ide>
<ide> // After scrolling down beyond > 3 rows, the order of line numbers and lines
<ide> describe('TextEditorComponent', () => {
<ide> editor.lineTextForScreenRow(8)
<ide> ])
<ide>
<del> component.refs.scroller.scrollTop = 2.5 * component.measurements.lineHeight
<add> component.setScrollTop(2.5 * component.getLineHeight())
<ide> await component.getNextUpdatePromise()
<ide> expect(Array.from(element.querySelectorAll('.line-number')).map(element => element.textContent.trim())).toEqual([
<ide> '1', '2', '3', '4', '5', '6', '7', '8', '9'
<ide> describe('TextEditorComponent', () => {
<ide>
<ide> it('honors the scrollPastEnd option by adding empty space equivalent to the clientHeight to the end of the content area', async () => {
<ide> const {component, element, editor} = buildComponent({autoHeight: false, autoWidth: false})
<del> const {scroller} = component.refs
<add> const {scrollContainer} = component.refs
<ide>
<ide> await editor.update({scrollPastEnd: true})
<ide> await setEditorHeightInLines(component, 6)
<ide>
<ide> // scroll to end
<del> scroller.scrollTop = scroller.scrollHeight - scroller.clientHeight
<add> component.setScrollTop(scrollContainer.scrollHeight - scrollContainer.clientHeight)
<ide> await component.getNextUpdatePromise()
<ide> expect(component.getFirstVisibleRow()).toBe(editor.getScreenLineCount() - 3)
<ide>
<ide> editor.update({scrollPastEnd: false})
<ide> await component.getNextUpdatePromise() // wait for scrollable content resize
<del> await component.getNextUpdatePromise() // wait for async scroll event due to scrollbar shrinking
<ide> expect(component.getFirstVisibleRow()).toBe(editor.getScreenLineCount() - 6)
<ide>
<ide> // Always allows at least 3 lines worth of overscroll if the editor is short
<ide> await setEditorHeightInLines(component, 2)
<ide> await editor.update({scrollPastEnd: true})
<del> scroller.scrollTop = scroller.scrollHeight - scroller.clientHeight
<add> component.setScrollTop(scrollContainer.scrollHeight - scrollContainer.clientHeight)
<ide> await component.getNextUpdatePromise()
<ide> expect(component.getFirstVisibleRow()).toBe(editor.getScreenLineCount() + 1)
<ide> })
<ide> describe('TextEditorComponent', () => {
<ide> expect(gutterElement.firstChild.style.contain).toBe('strict')
<ide> })
<ide>
<del> it('translates the gutter so it is always visible when scrolling to the right', async () => {
<del> const {component, element, editor} = buildComponent({width: 100})
<del>
<del> expect(component.refs.gutterContainer.style.transform).toBe('translateX(0px)')
<del> component.refs.scroller.scrollLeft = 100
<del> await component.getNextUpdatePromise()
<del> expect(component.refs.gutterContainer.style.transform).toBe('translateX(100px)')
<del> })
<del>
<ide> it('renders cursors within the visible row range', async () => {
<ide> const {component, element, editor} = buildComponent({height: 40, rowsPerTile: 2})
<del> component.refs.scroller.scrollTop = 100
<add> component.setScrollTop(100)
<ide> await component.getNextUpdatePromise()
<ide>
<ide> expect(component.getRenderedStartRow()).toBe(4)
<ide> describe('TextEditorComponent', () => {
<ide> it('places the hidden input element at the location of the last cursor if it is visible', async () => {
<ide> const {component, element, editor} = buildComponent({height: 60, width: 120, rowsPerTile: 2})
<ide> const {hiddenInput} = component.refs
<del> component.refs.scroller.scrollTop = 100
<del> component.refs.scroller.scrollLeft = 40
<add> component.setScrollTop(100)
<add> component.setScrollLeft(40)
<ide> await component.getNextUpdatePromise()
<ide>
<ide> expect(component.getRenderedStartRow()).toBe(4)
<ide> describe('TextEditorComponent', () => {
<ide> jasmine.attachToDOM(element)
<ide>
<ide> expect(getBaseCharacterWidth(component)).toBe(55)
<add> console.log('running expectation');
<ide> expect(lineNodeForScreenRow(component, 3).textContent).toBe(
<ide> ' var pivot = items.shift(), current, left = [], '
<ide> )
<ide> describe('TextEditorComponent', () => {
<ide> ' = [], right = [];'
<ide> )
<ide>
<del> const {scroller} = component.refs
<del> expect(scroller.clientWidth).toBe(scroller.scrollWidth)
<add> const {scrollContainer} = component.refs
<add> expect(scrollContainer.clientWidth).toBe(scrollContainer.scrollWidth)
<ide> })
<ide>
<ide> it('decorates the line numbers of folded lines', async () => {
<ide> describe('TextEditorComponent', () => {
<ide> expect(lineNumberNodeForScreenRow(component, 1).classList.contains('folded')).toBe(true)
<ide> })
<ide>
<del> it('makes lines at least as wide as the scroller', async () => {
<add> it('makes lines at least as wide as the scrollContainer', async () => {
<ide> const {component, element, editor} = buildComponent()
<del> const {scroller, gutterContainer} = component.refs
<add> const {scrollContainer, gutterContainer} = component.refs
<ide> editor.setText('a')
<ide> await component.getNextUpdatePromise()
<ide>
<del> expect(element.querySelector('.line').offsetWidth).toBe(scroller.offsetWidth - gutterContainer.offsetWidth)
<add> expect(element.querySelector('.line').offsetWidth).toBe(scrollContainer.offsetWidth)
<ide> })
<ide>
<ide> it('resizes based on the content when the autoHeight and/or autoWidth options are true', async () => {
<ide> const {component, element, editor} = buildComponent({autoHeight: true, autoWidth: true})
<add> const {gutterContainer, scrollContainer} = component.refs
<ide> const initialWidth = element.offsetWidth
<ide> const initialHeight = element.offsetHeight
<del> expect(initialWidth).toBe(component.refs.scroller.scrollWidth)
<del> expect(initialHeight).toBe(component.refs.scroller.scrollHeight)
<add> expect(initialWidth).toBe(gutterContainer.offsetWidth + scrollContainer.scrollWidth)
<add> expect(initialHeight).toBe(scrollContainer.scrollHeight)
<ide> editor.setCursorScreenPosition([6, Infinity])
<ide> editor.insertText('x'.repeat(50))
<ide> await component.getNextUpdatePromise()
<del> expect(element.offsetWidth).toBe(component.refs.scroller.scrollWidth)
<add> expect(element.offsetWidth).toBe(gutterContainer.offsetWidth + scrollContainer.scrollWidth)
<ide> expect(element.offsetWidth).toBeGreaterThan(initialWidth)
<ide> editor.insertText('\n'.repeat(5))
<ide> await component.getNextUpdatePromise()
<del> expect(element.offsetHeight).toBe(component.refs.scroller.scrollHeight)
<add> expect(element.offsetHeight).toBe(scrollContainer.scrollHeight)
<ide> expect(element.offsetHeight).toBeGreaterThan(initialHeight)
<ide> })
<ide>
<ide> describe('TextEditorComponent', () => {
<ide>
<ide> describe('autoscroll on cursor movement', () => {
<ide> it('automatically scrolls vertically when the requested range is within the vertical scroll margin of the top or bottom', async () => {
<del> const {component, element, editor} = buildComponent({height: 120})
<del> const {scroller} = component.refs
<add> const {component, editor} = buildComponent({height: 120})
<ide> expect(component.getLastVisibleRow()).toBe(8)
<ide>
<ide> editor.scrollToScreenRange([[4, 0], [6, 0]])
<ide> await component.getNextUpdatePromise()
<del> let scrollBottom = scroller.scrollTop + scroller.clientHeight
<del> expect(scrollBottom).toBe((6 + 1 + editor.verticalScrollMargin) * component.measurements.lineHeight)
<add> expect(component.getScrollBottom()).toBe((6 + 1 + editor.verticalScrollMargin) * component.getLineHeight())
<ide>
<ide> editor.scrollToScreenPosition([8, 0])
<ide> await component.getNextUpdatePromise()
<del> scrollBottom = scroller.scrollTop + scroller.clientHeight
<del> expect(scrollBottom).toBe((8 + 1 + editor.verticalScrollMargin) * component.measurements.lineHeight)
<add> expect(component.getScrollBottom()).toBe((8 + 1 + editor.verticalScrollMargin) * component.measurements.lineHeight)
<ide>
<ide> editor.scrollToScreenPosition([3, 0])
<ide> await component.getNextUpdatePromise()
<del> expect(scroller.scrollTop).toBe((3 - editor.verticalScrollMargin) * component.measurements.lineHeight)
<add> expect(component.getScrollTop()).toBe((3 - editor.verticalScrollMargin) * component.measurements.lineHeight)
<ide>
<ide> editor.scrollToScreenPosition([2, 0])
<ide> await component.getNextUpdatePromise()
<del> expect(scroller.scrollTop).toBe(0)
<add> expect(component.getScrollTop()).toBe(0)
<ide> })
<ide>
<ide> it('does not vertically autoscroll by more than half of the visible lines if the editor is shorter than twice the scroll margin', async () => {
<ide> const {component, element, editor} = buildComponent({autoHeight: false})
<del> const {scroller} = component.refs
<add> const {scrollContainer} = component.refs
<ide> element.style.height = 5.5 * component.measurements.lineHeight + 'px'
<ide> await component.getNextUpdatePromise()
<ide> expect(component.getLastVisibleRow()).toBe(6)
<ide> const scrollMarginInLines = 2
<ide>
<ide> editor.scrollToScreenPosition([6, 0])
<ide> await component.getNextUpdatePromise()
<del> let scrollBottom = scroller.scrollTop + scroller.clientHeight
<del> expect(scrollBottom).toBe((6 + 1 + scrollMarginInLines) * component.measurements.lineHeight)
<add> expect(component.getScrollBottom()).toBe((6 + 1 + scrollMarginInLines) * component.measurements.lineHeight)
<ide>
<ide> editor.scrollToScreenPosition([6, 4])
<ide> await component.getNextUpdatePromise()
<del> scrollBottom = scroller.scrollTop + scroller.clientHeight
<del> expect(scrollBottom).toBe((6 + 1 + scrollMarginInLines) * component.measurements.lineHeight)
<add> expect(component.getScrollBottom()).toBe((6 + 1 + scrollMarginInLines) * component.measurements.lineHeight)
<ide>
<ide> editor.scrollToScreenRange([[4, 4], [6, 4]])
<ide> await component.getNextUpdatePromise()
<del> expect(scroller.scrollTop).toBe((4 - scrollMarginInLines) * component.measurements.lineHeight)
<add> expect(component.getScrollTop()).toBe((4 - scrollMarginInLines) * component.measurements.lineHeight)
<ide>
<ide> editor.scrollToScreenRange([[4, 4], [6, 4]], {reversed: false})
<ide> await component.getNextUpdatePromise()
<del> expect(scrollBottom).toBe((6 + 1 + scrollMarginInLines) * component.measurements.lineHeight)
<add> expect(component.getScrollBottom()).toBe((6 + 1 + scrollMarginInLines) * component.measurements.lineHeight)
<ide> })
<ide>
<del> it('automatically scrolls horizontally when the requested range is within the horizontal scroll margin of the right edge of the gutter or right edge of the screen', async () => {
<add> it('automatically scrolls horizontally when the requested range is within the horizontal scroll margin of the right edge of the gutter or right edge of the scroll container', async () => {
<ide> const {component, element, editor} = buildComponent()
<del> const {scroller} = component.refs
<add> const {scrollContainer} = component.refs
<ide> element.style.width =
<ide> component.getGutterContainerWidth() +
<ide> 3 * editor.horizontalScrollMargin * component.measurements.baseCharacterWidth + 'px'
<ide> await component.getNextUpdatePromise()
<ide>
<ide> editor.scrollToScreenRange([[1, 12], [2, 28]])
<ide> await component.getNextUpdatePromise()
<del> let expectedScrollLeft = Math.floor(
<add> let expectedScrollLeft = Math.round(
<ide> clientLeftForCharacter(component, 1, 12) -
<ide> lineNodeForScreenRow(component, 1).getBoundingClientRect().left -
<ide> (editor.horizontalScrollMargin * component.measurements.baseCharacterWidth)
<ide> )
<del> expect(scroller.scrollLeft).toBe(expectedScrollLeft)
<add> expect(component.getScrollLeft()).toBe(expectedScrollLeft)
<ide>
<ide> editor.scrollToScreenRange([[1, 12], [2, 28]], {reversed: false})
<ide> await component.getNextUpdatePromise()
<del> expectedScrollLeft = Math.floor(
<add> expectedScrollLeft = Math.round(
<ide> component.getGutterContainerWidth() +
<ide> clientLeftForCharacter(component, 2, 28) -
<ide> lineNodeForScreenRow(component, 2).getBoundingClientRect().left +
<ide> (editor.horizontalScrollMargin * component.measurements.baseCharacterWidth) -
<del> scroller.clientWidth
<add> scrollContainer.clientWidth
<ide> )
<del> expect(scroller.scrollLeft).toBe(expectedScrollLeft)
<add> expect(component.getScrollLeft()).toBe(expectedScrollLeft)
<ide> })
<ide>
<ide> it('does not horizontally autoscroll by more than half of the visible "base-width" characters if the editor is narrower than twice the scroll margin', async () => {
<del> const {component, element, editor} = buildComponent({autoHeight: false})
<del> const {scroller, gutterContainer} = component.refs
<add> const {component, editor} = buildComponent({autoHeight: false})
<ide> await setEditorWidthInCharacters(component, 1.5 * editor.horizontalScrollMargin)
<ide>
<del> const contentWidth = scroller.clientWidth - gutterContainer.offsetWidth
<del> const contentWidthInCharacters = Math.floor(contentWidth / component.measurements.baseCharacterWidth)
<add> const contentWidthInCharacters = Math.floor(component.getScrollContainerClientWidth() / component.getBaseCharacterWidth())
<ide> expect(contentWidthInCharacters).toBe(9)
<ide>
<ide> editor.scrollToScreenRange([[6, 10], [6, 15]])
<ide> await component.getNextUpdatePromise()
<ide> let expectedScrollLeft = Math.floor(
<ide> clientLeftForCharacter(component, 6, 10) -
<ide> lineNodeForScreenRow(component, 1).getBoundingClientRect().left -
<del> (4 * component.measurements.baseCharacterWidth)
<add> (4 * component.getBaseCharacterWidth())
<ide> )
<del> expect(scroller.scrollLeft).toBe(expectedScrollLeft)
<add> expect(component.getScrollLeft()).toBe(expectedScrollLeft)
<ide> })
<ide>
<ide> it('correctly autoscrolls after inserting a line that exceeds the current content width', async () => {
<ide> const {component, element, editor} = buildComponent()
<del> const {scroller} = component.refs
<del> element.style.width = component.getGutterContainerWidth() + component.measurements.longestLineWidth + 'px'
<add> element.style.width = component.getGutterContainerWidth() + component.getContentWidth() + 'px'
<ide> await component.getNextUpdatePromise()
<ide>
<ide> editor.setCursorScreenPosition([0, Infinity])
<ide> editor.insertText('x'.repeat(100))
<ide> await component.getNextUpdatePromise()
<ide>
<del> expect(scroller.scrollLeft).toBe(component.getScrollWidth() - scroller.clientWidth)
<add> expect(component.getScrollLeft()).toBe(component.getScrollWidth() - component.getScrollContainerClientWidth())
<ide> })
<ide>
<ide> it('accounts for the presence of horizontal scrollbars that appear during the same frame as the autoscroll', async () => {
<ide> const {component, element, editor} = buildComponent()
<del> const {scroller} = component.refs
<add> const {scrollContainer} = component.refs
<ide> element.style.height = component.getScrollHeight() + 'px'
<ide> element.style.width = component.getScrollWidth() + 'px'
<ide> await component.getNextUpdatePromise()
<ide> describe('TextEditorComponent', () => {
<ide> editor.insertText('\n\n' + 'x'.repeat(100))
<ide> await component.getNextUpdatePromise()
<ide>
<del> expect(scroller.scrollTop).toBe(component.getScrollHeight() - scroller.clientHeight)
<del> expect(scroller.scrollLeft).toBe(component.getScrollWidth() - scroller.clientWidth)
<add> expect(component.getScrollTop()).toBe(component.getScrollHeight() - component.getScrollContainerClientHeight())
<add> expect(component.getScrollLeft()).toBe(component.getScrollWidth() - component.getScrollContainerClientWidth())
<ide> })
<ide> })
<ide>
<ide> describe('TextEditorComponent', () => {
<ide> )
<ide>
<ide> // Don't flash on next update if another flash wasn't requested
<del> component.refs.scroller.scrollTop = 100
<add> component.setScrollTop(100)
<ide> await component.getNextUpdatePromise()
<ide> expect(highlights[0].classList.contains('b')).toBe(false)
<ide> expect(highlights[1].classList.contains('b')).toBe(false)
<ide> describe('TextEditorComponent', () => {
<ide> expect(editor.getCursorScreenPosition()).toEqual([0, 0])
<ide> })
<ide>
<del> it('autoscrolls the content when dragging near the edge of the screen', async () => {
<del> const {component, editor} = buildComponent({width: 200, height: 200})
<del> const {scroller} = component.refs
<add> it('autoscrolls the content when dragging near the edge of the scroll container', async () => {
<add> const {component, element, editor} = buildComponent({width: 200, height: 200})
<ide> spyOn(component, 'handleMouseDragUntilMouseUp')
<ide>
<ide> let previousScrollTop = 0
<ide> let previousScrollLeft = 0
<ide> function assertScrolledDownAndRight () {
<del> expect(scroller.scrollTop).toBeGreaterThan(previousScrollTop)
<del> previousScrollTop = scroller.scrollTop
<del> expect(scroller.scrollLeft).toBeGreaterThan(previousScrollLeft)
<del> previousScrollLeft = scroller.scrollLeft
<add> expect(component.getScrollTop()).toBeGreaterThan(previousScrollTop)
<add> previousScrollTop = component.getScrollTop()
<add> expect(component.getScrollLeft()).toBeGreaterThan(previousScrollLeft)
<add> previousScrollLeft = component.getScrollLeft()
<ide> }
<ide>
<ide> function assertScrolledUpAndLeft () {
<del> expect(scroller.scrollTop).toBeLessThan(previousScrollTop)
<del> previousScrollTop = scroller.scrollTop
<del> expect(scroller.scrollLeft).toBeLessThan(previousScrollLeft)
<del> previousScrollLeft = scroller.scrollLeft
<add> expect(component.getScrollTop()).toBeLessThan(previousScrollTop)
<add> previousScrollTop = component.getScrollTop()
<add> expect(component.getScrollLeft()).toBeLessThan(previousScrollLeft)
<add> previousScrollLeft = component.getScrollLeft()
<ide> }
<ide>
<ide> component.didMouseDownOnContent({detail: 1, button: 0, clientX: 100, clientY: 100})
<ide> const {didDrag, didStopDragging} = component.handleMouseDragUntilMouseUp.argsForCall[0][0]
<add>
<ide> didDrag({clientX: 199, clientY: 199})
<ide> assertScrolledDownAndRight()
<ide> didDrag({clientX: 199, clientY: 199})
<ide> describe('TextEditorComponent', () => {
<ide> didDrag({clientX: component.getGutterContainerWidth() + 1, clientY: 1})
<ide> assertScrolledUpAndLeft()
<ide>
<del> // Don't artificially update scroll measurements beyond the minimum or
<del> // maximum possible scroll positions
<del> expect(scroller.scrollTop).toBe(0)
<del> expect(scroller.scrollLeft).toBe(0)
<add> // Don't artificially update scroll position beyond possible values
<add> expect(component.getScrollTop()).toBe(0)
<add> expect(component.getScrollLeft()).toBe(0)
<ide> didDrag({clientX: component.getGutterContainerWidth() + 1, clientY: 1})
<del> expect(component.measurements.scrollTop).toBe(0)
<del> expect(scroller.scrollTop).toBe(0)
<del> expect(component.measurements.scrollLeft).toBe(0)
<del> expect(scroller.scrollLeft).toBe(0)
<del>
<del> const maxScrollTop = scroller.scrollHeight - scroller.clientHeight
<del> const maxScrollLeft = scroller.scrollWidth - scroller.clientWidth
<del> scroller.scrollTop = maxScrollTop
<del> scroller.scrollLeft = maxScrollLeft
<add> expect(component.getScrollTop()).toBe(0)
<add> expect(component.getScrollLeft()).toBe(0)
<add>
<add> const maxScrollTop = component.getMaxScrollTop()
<add> const maxScrollLeft = component.getMaxScrollLeft()
<add> component.setScrollTop(maxScrollTop)
<add> component.setScrollLeft(maxScrollLeft)
<ide> await component.getNextUpdatePromise()
<ide>
<ide> didDrag({clientX: 199, clientY: 199})
<ide> didDrag({clientX: 199, clientY: 199})
<ide> didDrag({clientX: 199, clientY: 199})
<del> expect(component.measurements.scrollTop).toBe(maxScrollTop)
<del> expect(component.measurements.scrollLeft).toBe(maxScrollLeft)
<add> expect(component.getScrollTop()).toBe(maxScrollTop)
<add> expect(component.getScrollLeft()).toBe(maxScrollLeft)
<ide> })
<ide> })
<ide>
<ide> describe('TextEditorComponent', () => {
<ide> expect(editor.isFoldedAtScreenRow(1)).toBe(false)
<ide> })
<ide>
<del> it('autoscrolls the content when dragging near the edge of the screen', async () => {
<add> it('autoscrolls when dragging near the top or bottom of the gutter', async () => {
<ide> const {component, editor} = buildComponent({width: 200, height: 200})
<del> const {scroller} = component.refs
<add> const {scrollContainer} = component.refs
<ide> spyOn(component, 'handleMouseDragUntilMouseUp')
<ide>
<ide> let previousScrollTop = 0
<ide> let previousScrollLeft = 0
<ide> function assertScrolledDown () {
<del> expect(scroller.scrollTop).toBeGreaterThan(previousScrollTop)
<del> previousScrollTop = scroller.scrollTop
<del> expect(scroller.scrollLeft).toBe(previousScrollLeft)
<del> previousScrollLeft = scroller.scrollLeft
<add> expect(component.getScrollTop()).toBeGreaterThan(previousScrollTop)
<add> previousScrollTop = component.getScrollTop()
<add> expect(component.getScrollLeft()).toBe(previousScrollLeft)
<add> previousScrollLeft = component.getScrollLeft()
<ide> }
<ide>
<ide> function assertScrolledUp () {
<del> expect(scroller.scrollTop).toBeLessThan(previousScrollTop)
<del> previousScrollTop = scroller.scrollTop
<del> expect(scroller.scrollLeft).toBe(previousScrollLeft)
<del> previousScrollLeft = scroller.scrollLeft
<add> expect(component.getScrollTop()).toBeLessThan(previousScrollTop)
<add> previousScrollTop = component.getScrollTop()
<add> expect(component.getScrollLeft()).toBe(previousScrollLeft)
<add> previousScrollLeft = component.getScrollLeft()
<ide> }
<ide>
<ide> component.didMouseDownOnLineNumberGutter({detail: 1, button: 0, clientX: 0, clientY: 100})
<ide> describe('TextEditorComponent', () => {
<ide>
<ide> // Don't artificially update scroll measurements beyond the minimum or
<ide> // maximum possible scroll positions
<del> expect(scroller.scrollTop).toBe(0)
<del> expect(scroller.scrollLeft).toBe(0)
<add> expect(component.getScrollTop()).toBe(0)
<add> expect(component.getScrollLeft()).toBe(0)
<ide> didDrag({clientX: component.getGutterContainerWidth() + 1, clientY: 1})
<del> expect(component.measurements.scrollTop).toBe(0)
<del> expect(scroller.scrollTop).toBe(0)
<del> expect(component.measurements.scrollLeft).toBe(0)
<del> expect(scroller.scrollLeft).toBe(0)
<del>
<del> const maxScrollTop = scroller.scrollHeight - scroller.clientHeight
<del> const maxScrollLeft = scroller.scrollWidth - scroller.clientWidth
<del> scroller.scrollTop = maxScrollTop
<del> scroller.scrollLeft = maxScrollLeft
<add> expect(component.getScrollTop()).toBe(0)
<add> expect(component.getScrollLeft()).toBe(0)
<add>
<add> const maxScrollTop = component.getMaxScrollTop()
<add> const maxScrollLeft = component.getMaxScrollLeft()
<add> component.setScrollTop(maxScrollTop)
<add> component.setScrollLeft(maxScrollLeft)
<ide> await component.getNextUpdatePromise()
<ide>
<ide> didDrag({clientX: 199, clientY: 199})
<ide> didDrag({clientX: 199, clientY: 199})
<ide> didDrag({clientX: 199, clientY: 199})
<del> expect(component.measurements.scrollTop).toBe(maxScrollTop)
<del> expect(component.measurements.scrollLeft).toBe(maxScrollLeft)
<add> expect(component.getScrollTop()).toBe(maxScrollTop)
<add> expect(component.getScrollLeft()).toBe(maxScrollLeft)
<ide> })
<ide> })
<ide> })
<ide> function buildComponent (params = {}) {
<ide> }
<ide>
<ide> function getBaseCharacterWidth (component) {
<del> return Math.round(
<del> (component.refs.scroller.clientWidth - component.getGutterContainerWidth()) /
<del> component.measurements.baseCharacterWidth
<del> )
<add> return Math.round(component.getScrollContainerWidth() / component.getBaseCharacterWidth())
<ide> }
<ide>
<ide> async function setEditorHeightInLines(component, heightInLines) {
<ide><path>src/text-editor-component.js
<ide> const KOREAN_CHARACTER = '세'
<ide> const NBSP_CHARACTER = '\u00a0'
<ide> const ZERO_WIDTH_NBSP_CHARACTER = '\ufeff'
<ide> const MOUSE_DRAG_AUTOSCROLL_MARGIN = 40
<add>const MOUSE_WHEEL_SCROLL_SENSITIVITY = 0.8
<ide>
<ide> function scaleMouseDragAutoscrollDelta (delta) {
<ide> return Math.pow(delta / 3, 3) / 280
<ide> class TextEditorComponent {
<ide> this.lineNodesByScreenLineId = new Map()
<ide> this.textNodesByScreenLineId = new Map()
<ide> this.pendingAutoscroll = null
<del> this.autoscrollTop = null
<add> this.scrollTop = 0
<add> this.scrollLeft = 0
<ide> this.previousScrollWidth = 0
<ide> this.previousScrollHeight = 0
<ide> this.lastKeydown = null
<ide> class TextEditorComponent {
<ide> }
<ide>
<ide> this.horizontalPositionsToMeasure.clear()
<del> if (this.pendingAutoscroll) this.initiateAutoscroll()
<add> if (this.pendingAutoscroll) this.autoscrollVertically()
<ide> this.populateVisibleRowRange()
<ide> const longestLineToMeasure = this.checkForNewLongestLine()
<ide> this.queryScreenLinesToRender()
<ide> class TextEditorComponent {
<ide>
<ide> etch.updateSync(this)
<ide>
<del> // If scrollHeight or scrollWidth changed, we may have shown or hidden
<del> // scrollbars, affecting the clientWidth or clientHeight
<del> if (this.checkIfScrollDimensionsChanged()) {
<del> this.measureClientDimensions()
<del> // If the clientHeight changed, our previous vertical autoscroll may have
<del> // been off by the height of the horizontal scrollbar. If we *still* need
<del> // to autoscroll, just re-render the frame.
<del> if (this.pendingAutoscroll && this.initiateAutoscroll()) {
<del> this.updateSync()
<del> return
<del> }
<add> if (this.pendingAutoscroll) {
<add> this.autoscrollHorizontally()
<add> this.pendingAutoscroll = null
<ide> }
<del> if (this.pendingAutoscroll) this.finalizeAutoscroll()
<ide> this.currentFrameLineNumberGutterProps = null
<ide> }
<ide>
<ide> class TextEditorComponent {
<ide> render () {
<ide> const {model} = this.props
<ide>
<del> const style = {
<del> overflow: 'hidden',
<del> }
<add> const style = {}
<ide> if (!model.getAutoHeight() && !model.getAutoWidth()) {
<ide> style.contain = 'strict'
<ide> }
<del>
<ide> if (this.measurements) {
<ide> if (model.getAutoHeight()) {
<del> style.height = this.getScrollHeight() + 'px'
<add> style.height = this.getContentHeight() + 'px'
<ide> }
<ide> if (model.getAutoWidth()) {
<del> style.width = this.getScrollWidth() + 'px'
<add> style.width = this.getGutterContainerWidth() + this.getContentWidth() + 'px'
<ide> }
<ide> }
<ide>
<ide> let attributes = null
<ide> let className = 'editor'
<del> if (this.focused) {
<del> className += ' is-focused'
<del> }
<add> if (this.focused) className += ' is-focused'
<ide> if (model.isMini()) {
<ide> attributes = {mini: ''}
<ide> className += ' mini'
<ide> }
<ide>
<del> const scrollerOverflowX = (model.isMini() || model.isSoftWrapped()) ? 'hidden' : 'auto'
<del> const scrollerOverflowY = model.isMini() ? 'hidden' : 'auto'
<del>
<ide> return $('atom-text-editor',
<ide> {
<ide> className,
<del> attributes,
<ide> style,
<add> attributes,
<ide> tabIndex: -1,
<ide> on: {
<ide> focus: this.didFocus,
<del> blur: this.didBlur
<add> blur: this.didBlur,
<add> mousewheel: this.didMouseWheel
<ide> }
<ide> },
<ide> $.div(
<ide> {
<add> ref: 'clientContainer',
<ide> style: {
<ide> position: 'relative',
<add> contain: 'strict',
<add> overflow: 'hidden',
<add> backgroundColor: 'inherit',
<ide> width: '100%',
<del> height: '100%',
<del> backgroundColor: 'inherit'
<add> height: '100%'
<ide> }
<ide> },
<del> $.div(
<del> {
<del> ref: 'scroller',
<del> className: 'scroll-view',
<del> on: {scroll: this.didScroll},
<del> style: {
<del> position: 'absolute',
<del> contain: 'strict',
<del> top: 0,
<del> right: 0,
<del> bottom: 0,
<del> left: 0,
<del> overflowX: scrollerOverflowX,
<del> overflowY: scrollerOverflowY,
<del> backgroundColor: 'inherit'
<del> }
<del> },
<del> $.div(
<del> {
<del> style: {
<del> isolate: 'content',
<del> width: 'max-content',
<del> height: 'max-content',
<del> backgroundColor: 'inherit'
<del> }
<del> },
<del> this.renderGutterContainer(),
<del> this.renderContent()
<del> )
<del> )
<add> this.renderGutterContainer(),
<add> this.renderScrollContainer()
<ide> )
<ide> )
<ide> }
<ide>
<ide> renderGutterContainer () {
<ide> if (this.props.model.isMini()) return null
<del> const props = {ref: 'gutterContainer', className: 'gutter-container'}
<ide>
<add> const innerStyle = {
<add> willChange: 'transform',
<add> backgroundColor: 'inherit'
<add> }
<ide> if (this.measurements) {
<del> props.style = {
<del> position: 'relative',
<del> willChange: 'transform',
<del> transform: `translateX(${this.measurements.scrollLeft}px)`,
<del> zIndex: 1
<del> }
<add> innerStyle.transform = `translateY(${-this.getScrollTop()}px)`
<ide> }
<ide>
<del> return $.div(props, this.renderLineNumberGutter())
<add> return $.div(
<add> {
<add> ref: 'gutterContainer',
<add> className: 'gutter-container',
<add> style: {
<add> position: 'relative',
<add> zIndex: 1,
<add> backgroundColor: 'inherit'
<add> }
<add> },
<add> $.div({style: innerStyle},
<add> this.renderLineNumberGutter()
<add> )
<add> )
<ide> }
<ide>
<ide> renderLineNumberGutter () {
<ide> class TextEditorComponent {
<ide> ref: 'lineNumberGutter',
<ide> parentComponent: this,
<ide> height: this.getScrollHeight(),
<del> width: this.measurements.lineNumberGutterWidth,
<del> lineHeight: this.measurements.lineHeight,
<add> width: this.getLineNumberGutterWidth(),
<add> lineHeight: this.getLineHeight(),
<ide> startRow, endRow, rowsPerTile, maxLineNumberDigits,
<ide> bufferRows, lineNumberDecorations, softWrappedFlags,
<ide> foldableFlags
<ide> class TextEditorComponent {
<ide> }
<ide> }
<ide>
<add> renderScrollContainer () {
<add> const style = {
<add> position: 'absolute',
<add> contain: 'strict',
<add> overflow: 'hidden',
<add> top: 0,
<add> bottom: 0,
<add> backgroundColor: 'inherit'
<add> }
<add>
<add> if (this.measurements) {
<add> style.left = this.getGutterContainerWidth() + 'px'
<add> style.width = this.getScrollContainerWidth() + 'px'
<add> }
<add>
<add> return $.div(
<add> {
<add> ref: 'scrollContainer',
<add> className: 'scroll-view',
<add> style
<add> },
<add> this.renderContent()
<add> )
<add> }
<add>
<ide> renderContent () {
<ide> let children
<ide> let style = {
<ide> class TextEditorComponent {
<ide> backgroundColor: 'inherit'
<ide> }
<ide> if (this.measurements) {
<del> const contentWidth = this.getContentWidth()
<del> const scrollHeight = this.getScrollHeight()
<del> const width = contentWidth + 'px'
<del> const height = scrollHeight + 'px'
<del> style.width = width
<del> style.height = height
<add> style.width = this.getScrollWidth() + 'px'
<add> style.height = this.getScrollHeight() + 'px'
<add> style.willChange = 'transform'
<add> style.transform = `translate(${-this.getScrollLeft()}px, ${-this.getScrollTop()}px)`
<ide> children = [
<del> this.renderCursorsAndInput(width, height),
<del> this.renderLineTiles(width, height),
<add> this.renderCursorsAndInput(),
<add> this.renderLineTiles(),
<ide> this.renderPlaceholderText()
<ide> ]
<ide> } else {
<ide> class TextEditorComponent {
<ide> )
<ide> }
<ide>
<del> renderLineTiles (width, height) {
<add> renderLineTiles () {
<ide> if (!this.measurements) return []
<ide>
<ide> const {lineNodesByScreenLineId, textNodesByScreenLineId} = this
<ide>
<ide> const startRow = this.getRenderedStartRow()
<ide> const endRow = this.getRenderedEndRow()
<ide> const rowsPerTile = this.getRowsPerTile()
<del> const tileHeight = this.measurements.lineHeight * rowsPerTile
<del> const tileWidth = this.getContentWidth()
<add> const tileHeight = this.getLineHeight() * rowsPerTile
<add> const tileWidth = this.getScrollWidth()
<ide>
<ide> const displayLayer = this.props.model.displayLayer
<ide> const tileNodes = new Array(this.getRenderedTileCount())
<ide> class TextEditorComponent {
<ide> height: tileHeight,
<ide> width: tileWidth,
<ide> top: this.topPixelPositionForRow(tileStartRow),
<del> lineHeight: this.measurements.lineHeight,
<add> lineHeight: this.getLineHeight(),
<ide> screenLines: this.renderedScreenLines.slice(tileStartRow - startRow, tileEndRow - startRow),
<ide> lineDecorations,
<ide> highlightDecorations,
<ide> class TextEditorComponent {
<ide> style: {
<ide> position: 'absolute',
<ide> contain: 'strict',
<del> width, height,
<add> overflow: 'hidden',
<add> width: this.getScrollWidth() + 'px',
<add> height: this.getScrollHeight() + 'px',
<ide> backgroundColor: 'inherit'
<ide> }
<ide> }, tileNodes)
<ide> }
<ide>
<del> renderCursorsAndInput (width, height) {
<del> const cursorHeight = this.measurements.lineHeight + 'px'
<add> renderCursorsAndInput () {
<add> const cursorHeight = this.getLineHeight() + 'px'
<ide>
<ide> const children = [this.renderHiddenInput()]
<ide>
<ide> class TextEditorComponent {
<ide> position: 'absolute',
<ide> contain: 'strict',
<ide> zIndex: 1,
<del> width, height
<add> width: this.getScrollWidth() + 'px',
<add> height: this.getScrollHeight() + 'px'
<ide> }
<ide> }, children)
<ide> }
<ide> class TextEditorComponent {
<ide> style: {
<ide> position: 'absolute',
<ide> width: '1px',
<del> height: this.measurements.lineHeight + 'px',
<add> height: this.getLineHeight() + 'px',
<ide> top: top + 'px',
<ide> left: left + 'px',
<ide> opacity: 0,
<ide> class TextEditorComponent {
<ide> updateCursorsToRender () {
<ide> this.decorationsToRender.cursors.length = 0
<ide>
<del> const height = this.measurements.lineHeight + 'px'
<add> const height = this.getLineHeight() + 'px'
<ide> for (let i = 0; i < this.decorationsToMeasure.cursors.length; i++) {
<ide> const cursor = this.decorationsToMeasure.cursors[i]
<ide> const {row, column} = cursor.screenPosition
<ide> class TextEditorComponent {
<ide> }
<ide> }
<ide>
<del> didScroll () {
<del> if (this.measureScrollPosition(true)) {
<del> this.updateSync()
<del> }
<add> didMouseWheel (eveWt) {
<add> let {deltaX, deltaY} = event
<add> deltaX = deltaX * MOUSE_WHEEL_SCROLL_SENSITIVITY
<add> deltaY = deltaY * MOUSE_WHEEL_SCROLL_SENSITIVITY
<add>
<add> const scrollPositionChanged =
<add> this.setScrollLeft(this.getScrollLeft() + deltaX) ||
<add> this.setScrollTop(this.getScrollTop() + deltaY)
<add>
<add> if (scrollPositionChanged) this.updateSync()
<ide> }
<ide>
<ide> didResize () {
<del> if (this.measureEditorDimensions()) {
<del> this.measureClientDimensions()
<add> if (this.measureClientContainerDimensions()) {
<ide> this.scheduleUpdate()
<ide> }
<ide> }
<ide> class TextEditorComponent {
<ide> }
<ide>
<ide> autoscrollOnMouseDrag ({clientX, clientY}, verticalOnly = false) {
<del> let {top, bottom, left, right} = this.refs.scroller.getBoundingClientRect()
<add> let {top, bottom, left, right} = this.refs.scrollContainer.getBoundingClientRect()
<ide> top += MOUSE_DRAG_AUTOSCROLL_MARGIN
<ide> bottom -= MOUSE_DRAG_AUTOSCROLL_MARGIN
<del> left += this.getGutterContainerWidth() + MOUSE_DRAG_AUTOSCROLL_MARGIN
<add> left += MOUSE_DRAG_AUTOSCROLL_MARGIN
<ide> right -= MOUSE_DRAG_AUTOSCROLL_MARGIN
<ide>
<ide> let yDelta, yDirection
<ide> class TextEditorComponent {
<ide> let scrolled = false
<ide> if (yDelta != null) {
<ide> const scaledDelta = scaleMouseDragAutoscrollDelta(yDelta) * yDirection
<del> const newScrollTop = this.constrainScrollTop(this.measurements.scrollTop + scaledDelta)
<del> if (newScrollTop !== this.measurements.scrollTop) {
<del> this.measurements.scrollTop = newScrollTop
<del> this.refs.scroller.scrollTop = newScrollTop
<del> scrolled = true
<del> }
<add> scrolled = this.setScrollTop(this.getScrollTop() + scaledDelta)
<ide> }
<ide>
<ide> if (!verticalOnly && xDelta != null) {
<ide> const scaledDelta = scaleMouseDragAutoscrollDelta(xDelta) * xDirection
<del> const newScrollLeft = this.constrainScrollLeft(this.measurements.scrollLeft + scaledDelta)
<del> if (newScrollLeft !== this.measurements.scrollLeft) {
<del> this.measurements.scrollLeft = newScrollLeft
<del> this.refs.scroller.scrollLeft = newScrollLeft
<del> scrolled = true
<del> }
<add> scrolled = this.setScrollLeft(this.getScrollLeft() + scaledDelta)
<ide> }
<ide>
<ide> if (scrolled) this.updateSync()
<ide> }
<ide>
<ide> screenPositionForMouseEvent ({clientX, clientY}) {
<del> const scrollerRect = this.refs.scroller.getBoundingClientRect()
<del> clientX = Math.min(scrollerRect.right, Math.max(scrollerRect.left, clientX))
<del> clientY = Math.min(scrollerRect.bottom, Math.max(scrollerRect.top, clientY))
<add> const scrollContainerRect = this.refs.scrollContainer.getBoundingClientRect()
<add> clientX = Math.min(scrollContainerRect.right, Math.max(scrollContainerRect.left, clientX))
<add> clientY = Math.min(scrollContainerRect.bottom, Math.max(scrollContainerRect.top, clientY))
<ide> const linesRect = this.refs.lineTiles.getBoundingClientRect()
<ide> return this.screenPositionForPixelPosition({
<ide> top: clientY - linesRect.top,
<ide> class TextEditorComponent {
<ide> this.scheduleUpdate()
<ide> }
<ide>
<del> initiateAutoscroll () {
<add> autoscrollVertically () {
<ide> const {screenRange, options} = this.pendingAutoscroll
<ide>
<ide> const screenRangeTop = this.pixelTopForRow(screenRange.start.row)
<del> const screenRangeBottom = this.pixelTopForRow(screenRange.end.row) + this.measurements.lineHeight
<del> const verticalScrollMargin = this.getVerticalScrollMargin()
<add> const screenRangeBottom = this.pixelTopForRow(screenRange.end.row) + this.getLineHeight()
<add> const verticalScrollMargin = this.getVerticalAutoscrollMargin()
<ide>
<ide> this.requestHorizontalMeasurement(screenRange.start.row, screenRange.start.column)
<ide> this.requestHorizontalMeasurement(screenRange.end.row, screenRange.end.column)
<ide> class TextEditorComponent {
<ide> desiredScrollBottom = screenRangeBottom + verticalScrollMargin
<ide> }
<ide>
<del> if (desiredScrollTop != null) {
<del> desiredScrollTop = this.constrainScrollTop(desiredScrollTop)
<del> }
<del>
<del> if (desiredScrollBottom != null) {
<del> desiredScrollBottom = this.constrainScrollTop(desiredScrollBottom - this.getClientHeight()) + this.getClientHeight()
<del> }
<del>
<ide> if (!options || options.reversed !== false) {
<ide> if (desiredScrollBottom > this.getScrollBottom()) {
<del> this.autoscrollTop = desiredScrollBottom - this.measurements.clientHeight
<del> this.measurements.scrollTop = this.autoscrollTop
<del> return true
<add> return this.setScrollBottom(desiredScrollBottom, true)
<ide> }
<ide> if (desiredScrollTop < this.getScrollTop()) {
<del> this.autoscrollTop = desiredScrollTop
<del> this.measurements.scrollTop = this.autoscrollTop
<del> return true
<add> return this.setScrollTop(desiredScrollTop, true)
<ide> }
<ide> } else {
<ide> if (desiredScrollTop < this.getScrollTop()) {
<del> this.autoscrollTop = desiredScrollTop
<del> this.measurements.scrollTop = this.autoscrollTop
<del> return true
<add> return this.setScrollTop(desiredScrollTop, true)
<ide> }
<ide> if (desiredScrollBottom > this.getScrollBottom()) {
<del> this.autoscrollTop = desiredScrollBottom - this.measurements.clientHeight
<del> this.measurements.scrollTop = this.autoscrollTop
<del> return true
<add> return this.setScrollBottom(desiredScrollBottom, true)
<ide> }
<ide> }
<ide>
<ide> return false
<ide> }
<ide>
<del> finalizeAutoscroll () {
<del> const horizontalScrollMargin = this.getHorizontalScrollMargin()
<add> autoscrollHorizontally () {
<add> const horizontalScrollMargin = this.getHorizontalAutoscrollMargin()
<ide>
<ide> const {screenRange, options} = this.pendingAutoscroll
<ide> const gutterContainerWidth = this.getGutterContainerWidth()
<ide> class TextEditorComponent {
<ide> const desiredScrollLeft = Math.max(0, left - horizontalScrollMargin - gutterContainerWidth)
<ide> const desiredScrollRight = Math.min(this.getScrollWidth(), right + horizontalScrollMargin)
<ide>
<del> let autoscrollLeft
<ide> if (!options || options.reversed !== false) {
<ide> if (desiredScrollRight > this.getScrollRight()) {
<del> autoscrollLeft = desiredScrollRight - this.getClientWidth()
<del> this.measurements.scrollLeft = autoscrollLeft
<add> this.setScrollRight(desiredScrollRight, true)
<ide> }
<ide> if (desiredScrollLeft < this.getScrollLeft()) {
<del> autoscrollLeft = desiredScrollLeft
<del> this.measurements.scrollLeft = autoscrollLeft
<add> this.setScrollLeft(desiredScrollLeft, true)
<ide> }
<ide> } else {
<ide> if (desiredScrollLeft < this.getScrollLeft()) {
<del> autoscrollLeft = desiredScrollLeft
<del> this.measurements.scrollLeft = autoscrollLeft
<add> this.setScrollLeft(desiredScrollLeft, true)
<ide> }
<ide> if (desiredScrollRight > this.getScrollRight()) {
<del> autoscrollLeft = desiredScrollRight - this.getClientWidth()
<del> this.measurements.scrollLeft = autoscrollLeft
<add> this.setScrollRight(desiredScrollRight, true)
<ide> }
<ide> }
<del>
<del> if (this.autoscrollTop != null) {
<del> this.refs.scroller.scrollTop = this.autoscrollTop
<del> this.autoscrollTop = null
<del> }
<del>
<del> if (autoscrollLeft != null) {
<del> this.refs.scroller.scrollLeft = autoscrollLeft
<del> }
<del>
<del> this.pendingAutoscroll = null
<ide> }
<ide>
<del> getVerticalScrollMargin () {
<del> const {clientHeight, lineHeight} = this.measurements
<add> getVerticalAutoscrollMargin () {
<add> const maxMarginInLines = Math.floor(
<add> (this.getScrollContainerClientHeight() / this.getLineHeight() - 1) / 2
<add> )
<ide> const marginInLines = Math.min(
<ide> this.props.model.verticalScrollMargin,
<del> Math.floor(((clientHeight / lineHeight) - 1) / 2)
<add> maxMarginInLines
<ide> )
<del> return marginInLines * lineHeight
<add> return marginInLines * this.getLineHeight()
<ide> }
<ide>
<del> getHorizontalScrollMargin () {
<del> const {clientWidth, baseCharacterWidth} = this.measurements
<del> const contentClientWidth = clientWidth - this.getGutterContainerWidth()
<add> getHorizontalAutoscrollMargin () {
<add> const maxMarginInBaseCharacters = Math.floor(
<add> (this.getScrollContainerClientWidth() / this.getBaseCharacterWidth() - 1) / 2
<add> )
<ide> const marginInBaseCharacters = Math.min(
<ide> this.props.model.horizontalScrollMargin,
<del> Math.floor(((contentClientWidth / baseCharacterWidth) - 1) / 2)
<del> )
<del> return marginInBaseCharacters * baseCharacterWidth
<del> }
<del>
<del> constrainScrollTop (desiredScrollTop) {
<del> return Math.max(
<del> 0, Math.min(desiredScrollTop, this.getScrollHeight() - this.getClientHeight())
<del> )
<del> }
<del>
<del> constrainScrollLeft (desiredScrollLeft) {
<del> return Math.max(
<del> 0, Math.min(desiredScrollLeft, this.getScrollWidth() - this.getClientWidth())
<add> maxMarginInBaseCharacters
<ide> )
<add> return marginInBaseCharacters * this.getBaseCharacterWidth()
<ide> }
<ide>
<ide> performInitialMeasurements () {
<ide> this.measurements = {}
<del> this.measureGutterDimensions()
<del> this.measureEditorDimensions()
<del> this.measureClientDimensions()
<del> this.measureScrollPosition()
<ide> this.measureCharacterDimensions()
<add> this.measureGutterDimensions()
<add> this.measureClientContainerDimensions()
<ide> }
<ide>
<del> measureEditorDimensions () {
<add> measureClientContainerDimensions () {
<ide> if (!this.measurements) return false
<ide>
<ide> let dimensionsChanged = false
<del> const scrollerHeight = this.refs.scroller.offsetHeight
<del> const scrollerWidth = this.refs.scroller.offsetWidth
<del> if (scrollerHeight !== this.measurements.scrollerHeight) {
<del> this.measurements.scrollerHeight = scrollerHeight
<add> const clientContainerHeight = this.refs.clientContainer.offsetHeight
<add> const clientContainerWidth = this.refs.clientContainer.offsetWidth
<add> if (clientContainerHeight !== this.measurements.clientContainerHeight) {
<add> this.measurements.clientContainerHeight = clientContainerHeight
<ide> dimensionsChanged = true
<ide> }
<del> if (scrollerWidth !== this.measurements.scrollerWidth) {
<del> this.measurements.scrollerWidth = scrollerWidth
<add> if (clientContainerWidth !== this.measurements.clientContainerWidth) {
<add> this.measurements.clientContainerWidth = clientContainerWidth
<add> this.props.model.setEditorWidthInChars(this.getScrollContainerWidth() / this.getBaseCharacterWidth())
<ide> dimensionsChanged = true
<ide> }
<ide> return dimensionsChanged
<ide> }
<ide>
<del> measureScrollPosition () {
<del> let scrollPositionChanged = false
<del> const {scrollTop, scrollLeft} = this.refs.scroller
<del> if (scrollTop !== this.measurements.scrollTop) {
<del> this.measurements.scrollTop = scrollTop
<del> scrollPositionChanged = true
<del> }
<del> if (scrollLeft !== this.measurements.scrollLeft) {
<del> this.measurements.scrollLeft = scrollLeft
<del> scrollPositionChanged = true
<del> }
<del> return scrollPositionChanged
<del> }
<del>
<del> measureClientDimensions () {
<del> const {clientHeight, clientWidth} = this.refs.scroller
<del> if (clientHeight !== this.measurements.clientHeight) {
<del> this.measurements.clientHeight = clientHeight
<del> }
<del> if (clientWidth !== this.measurements.clientWidth) {
<del> this.measurements.clientWidth = clientWidth
<del> this.props.model.setWidth(clientWidth - this.getGutterContainerWidth(), true)
<del> }
<del> }
<del>
<ide> measureCharacterDimensions () {
<ide> this.measurements.lineHeight = this.refs.characterMeasurementLine.getBoundingClientRect().height
<ide> this.measurements.baseCharacterWidth = this.refs.normalWidthCharacterSpan.getBoundingClientRect().width
<ide> class TextEditorComponent {
<ide> }
<ide>
<ide> pixelTopForRow (row) {
<del> return row * this.measurements.lineHeight
<add> return row * this.getLineHeight()
<ide> }
<ide>
<ide> pixelLeftForRowAndColumn (row, column) {
<ide> class TextEditorComponent {
<ide> return this.element.offsetWidth > 0 || this.element.offsetHeight > 0
<ide> }
<ide>
<add> getLineHeight () {
<add> return this.measurements.lineHeight
<add> }
<add>
<ide> getBaseCharacterWidth () {
<ide> return this.measurements ? this.measurements.baseCharacterWidth : null
<ide> }
<ide>
<del> getScrollTop () {
<del> if (this.measurements != null) {
<del> return this.measurements.scrollTop
<add> getLongestLineWidth () {
<add> return this.measurements.longestLineWidth
<add> }
<add>
<add> getClientContainerHeight () {
<add> return this.measurements.clientContainerHeight
<add> }
<add>
<add> getClientContainerWidth () {
<add> return this.measurements.clientContainerWidth
<add> }
<add>
<add> getScrollContainerWidth () {
<add> if (this.props.model.getAutoWidth()) {
<add> return this.getScrollWidth()
<add> } else {
<add> return this.getClientContainerWidth() - this.getGutterContainerWidth()
<ide> }
<ide> }
<ide>
<del> getScrollBottom () {
<del> return this.measurements
<del> ? this.measurements.scrollTop + this.measurements.clientHeight
<del> : null
<add> getScrollContainerHeight () {
<add> if (this.props.model.getAutoHeight()) {
<add> return this.getScrollHeight()
<add> } else {
<add> return this.getClientContainerHeight()
<add> }
<ide> }
<ide>
<del> getScrollLeft () {
<del> return this.measurements ? this.measurements.scrollLeft : null
<add> getScrollContainerHeightInLines () {
<add> return Math.ceil(this.getScrollContainerHeight() / this.getLineHeight())
<ide> }
<ide>
<del> getScrollRight () {
<del> return this.measurements
<del> ? this.measurements.scrollLeft + this.measurements.clientWidth
<del> : null
<add> getScrollContainerClientWidth () {
<add> return this.getScrollContainerWidth()
<add> }
<add>
<add> getScrollContainerClientHeight () {
<add> return this.getScrollContainerHeight()
<ide> }
<ide>
<ide> getScrollHeight () {
<del> const {model} = this.props
<del> const contentHeight = model.getApproximateScreenLineCount() * this.measurements.lineHeight
<del> if (model.getScrollPastEnd()) {
<del> const extraScrollHeight = Math.max(
<del> 3 * this.measurements.lineHeight,
<del> this.getClientHeight() - 3 * this.measurements.lineHeight
<add> if (this.props.model.getScrollPastEnd()) {
<add> return this.getContentHeight() + Math.max(
<add> 3 * this.getLineHeight(),
<add> this.getScrollContainerClientHeight() - (3 * this.getLineHeight())
<ide> )
<del> return contentHeight + extraScrollHeight
<ide> } else {
<del> return contentHeight
<add> return this.getContentHeight()
<ide> }
<ide> }
<ide>
<ide> getScrollWidth () {
<del> return this.getContentWidth() + this.getGutterContainerWidth()
<add> const {model} = this.props
<add>
<add> if (model.isSoftWrapped()) {
<add> return this.getScrollContainerClientWidth()
<add> } else if (model.getAutoWidth()) {
<add> return this.getContentWidth()
<add> } else {
<add> return Math.max(this.getContentWidth(), this.getScrollContainerClientWidth())
<add> }
<ide> }
<ide>
<del> getClientHeight () {
<del> return this.measurements.clientHeight
<add> getContentHeight () {
<add> return this.props.model.getApproximateScreenLineCount() * this.getLineHeight()
<ide> }
<ide>
<del> getClientWidth () {
<del> return this.measurements.clientWidth
<add> getContentWidth () {
<add> return Math.round(this.getLongestLineWidth() + this.getBaseCharacterWidth())
<ide> }
<ide>
<ide> getGutterContainerWidth () {
<del> return this.measurements.lineNumberGutterWidth
<add> return this.getLineNumberGutterWidth()
<ide> }
<ide>
<del> getContentWidth () {
<del> if (this.props.model.isSoftWrapped()) {
<del> return this.getClientWidth() - this.getGutterContainerWidth()
<del> } else if (this.props.model.getAutoWidth()) {
<del> return Math.round(this.measurements.longestLineWidth + this.measurements.baseCharacterWidth)
<del> } else {
<del> return Math.max(
<del> Math.round(this.measurements.longestLineWidth + this.measurements.baseCharacterWidth),
<del> this.measurements.scrollerWidth - this.getGutterContainerWidth()
<del> )
<del> }
<add> getLineNumberGutterWidth () {
<add> return this.measurements.lineNumberGutterWidth
<ide> }
<ide>
<ide> getRowsPerTile () {
<ide> class TextEditorComponent {
<ide> }
<ide>
<ide> getFirstVisibleRow () {
<del> const scrollTop = this.getScrollTop()
<del> const lineHeight = this.measurements.lineHeight
<del> return Math.floor(scrollTop / lineHeight)
<add> return Math.floor(this.getScrollTop() / this.getLineHeight())
<ide> }
<ide>
<ide> getLastVisibleRow () {
<del> const {scrollerHeight, lineHeight} = this.measurements
<ide> return Math.min(
<ide> this.props.model.getApproximateScreenLineCount() - 1,
<del> this.getFirstVisibleRow() + Math.ceil(scrollerHeight / lineHeight)
<add> this.getFirstVisibleRow() + this.getScrollContainerHeightInLines()
<ide> )
<ide> }
<ide>
<ide> getVisibleTileCount () {
<ide> return Math.floor((this.getLastVisibleRow() - this.getFirstVisibleRow()) / this.getRowsPerTile()) + 2
<ide> }
<ide>
<add>
<add> getScrollTop () {
<add> this.scrollTop = Math.min(this.getMaxScrollTop(), this.scrollTop)
<add> return this.scrollTop
<add> }
<add>
<add> setScrollTop (scrollTop, suppressUpdate = false) {
<add> scrollTop = Math.round(Math.max(0, Math.min(this.getMaxScrollTop(), scrollTop)))
<add> if (scrollTop !== this.scrollTop) {
<add> this.scrollTop = scrollTop
<add> if (!suppressUpdate) this.scheduleUpdate()
<add> return true
<add> } else {
<add> return false
<add> }
<add> }
<add>
<add> getMaxScrollTop () {
<add> return Math.max(0, this.getScrollHeight() - this.getScrollContainerClientHeight())
<add> }
<add>
<add> getScrollBottom () {
<add> return this.getScrollTop() + this.getScrollContainerClientHeight()
<add> }
<add>
<add> setScrollBottom (scrollBottom, suppressUpdate = false) {
<add> return this.setScrollTop(scrollBottom - this.getScrollContainerClientHeight(), suppressUpdate)
<add> }
<add>
<add> getScrollLeft () {
<add> // this.scrollLeft = Math.min(this.getMaxScrollLeft(), this.scrollLeft)
<add> return this.scrollLeft
<add> }
<add>
<add> setScrollLeft (scrollLeft, suppressUpdate = false) {
<add> scrollLeft = Math.round(Math.max(0, Math.min(this.getMaxScrollLeft(), scrollLeft)))
<add> if (scrollLeft !== this.scrollLeft) {
<add> this.scrollLeft = scrollLeft
<add> if (!suppressUpdate) this.scheduleUpdate()
<add> return true
<add> } else {
<add> return false
<add> }
<add> }
<add>
<add> getMaxScrollLeft () {
<add> return Math.max(0, this.getScrollWidth() - this.getScrollContainerClientWidth())
<add> }
<add>
<add> getScrollRight () {
<add> return this.getScrollLeft() + this.getScrollContainerClientWidth()
<add> }
<add>
<add> setScrollRight (scrollRight, suppressUpdate = false) {
<add> return this.setScrollLeft(scrollRight - this.getScrollContainerClientWidth(), suppressUpdate)
<add> }
<add>
<ide> // Ensure the spatial index is populated with rows that are currently
<ide> // visible so we *at least* get the longest row in the visible range.
<ide> populateVisibleRowRange () {
<ide> class TextEditorComponent {
<ide> }
<ide>
<ide> topPixelPositionForRow (row) {
<del> return row * this.measurements.lineHeight
<add> return row * this.getLineHeight()
<ide> }
<ide>
<ide> getNextUpdatePromise () {
<ide> class LinesTileComponent {
<ide> position: 'absolute',
<ide> contain: 'strict',
<ide> height: height + 'px',
<del> width: width + 'px',
<add> width: width + 'px'
<ide> }
<ide> }, children)
<ide> }
<ide><path>src/text-editor-element.js
<ide> class TextEditorElement extends HTMLElement {
<ide> }
<ide>
<ide> getModel () {
<del> return this.getComponent().getModel()
<add> return this.getComponent().props.model
<ide> }
<ide>
<ide> setModel (model) { | 3 |
Go | Go | remove double newline | fcf37be2b1efa11da1958658da0e04755a225c89 | <ide><path>api/server/server.go
<ide> func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, local
<ide> log.Debugf("Calling %s %s", localMethod, localRoute)
<ide>
<ide> if logging {
<del> log.Infof("%s %s\n", r.Method, r.RequestURI)
<add> log.Infof("%s %s", r.Method, r.RequestURI)
<ide> }
<ide>
<ide> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
<ide> func ServeApi(job *engine.Job) engine.Status {
<ide> return job.Errorf("usage: %s PROTO://ADDR [PROTO://ADDR ...]", job.Name)
<ide> }
<ide> go func() {
<del> log.Infof("Listening for HTTP on %s (%s)\n", protoAddrParts[0], protoAddrParts[1])
<add> log.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1])
<ide> chErrors <- ListenAndServe(protoAddrParts[0], protoAddrParts[1], job)
<ide> }()
<ide> }
<ide><path>daemon/container.go
<ide> func (container *Container) initializeNetworking() error {
<ide> // Make sure the config is compatible with the current kernel
<ide> func (container *Container) verifyDaemonSettings() {
<ide> if container.Config.Memory > 0 && !container.daemon.sysInfo.MemoryLimit {
<del> log.Infof("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
<add> log.Infof("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.")
<ide> container.Config.Memory = 0
<ide> }
<ide> if container.Config.Memory > 0 && !container.daemon.sysInfo.SwapLimit {
<del> log.Infof("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
<add> log.Infof("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.")
<ide> container.Config.MemorySwap = -1
<ide> }
<ide> if container.daemon.sysInfo.IPv4ForwardingDisabled {
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) restore() error {
<ide> }
<ide>
<ide> if !debug {
<del> log.Infof(": done.\n")
<add> log.Infof(": done.")
<ide> }
<ide>
<ide> return nil
<ide> func (daemon *Daemon) checkLocaldns() error {
<ide> return err
<ide> }
<ide> if len(daemon.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) {
<del> log.Infof("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v\n", DefaultDns)
<add> log.Infof("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v", DefaultDns)
<ide> daemon.config.Dns = DefaultDns
<ide> }
<ide> return nil
<ide> func checkKernelAndArch() error {
<ide> // the circumstances of pre-3.8 crashes are clearer.
<ide> // For details see http://github.com/docker/docker/issues/407
<ide> if k, err := kernel.GetKernelVersion(); err != nil {
<del> log.Infof("WARNING: %s\n", err)
<add> log.Infof("WARNING: %s", err)
<ide> } else {
<ide> if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
<ide> if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
<ide><path>daemon/delete.go
<ide> func (daemon *Daemon) ContainerDestroy(job *engine.Job) engine.Status {
<ide> for volumeId := range volumes {
<ide> // If the requested volu
<ide> if c, exists := usedVolumes[volumeId]; exists {
<del> log.Infof("The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.ID)
<add> log.Infof("The volume %s is used by the container %s. Impossible to remove it. Skipping.", volumeId, c.ID)
<ide> continue
<ide> }
<ide> if err := daemon.Volumes().Delete(volumeId); err != nil {
<ide><path>daemon/networkdriver/bridge/driver.go
<ide> func Release(job *engine.Job) engine.Status {
<ide> }
<ide>
<ide> if err := ipallocator.ReleaseIP(bridgeNetwork, &containerInterface.IP); err != nil {
<del> log.Infof("Unable to release ip %s\n", err)
<add> log.Infof("Unable to release ip %s", err)
<ide> }
<ide> return engine.StatusOK
<ide> } | 5 |
Ruby | Ruby | use arel to compile sql rather than build strings | 6ca921a98cefa2bce67486f1ba2a8f52f4170d78 | <ide><path>activerecord/lib/active_record/association_preload.rb
<ide> def preload_has_and_belongs_to_many_association(records, reflection, preload_opt
<ide> right[reflection.association_foreign_key])
<ide>
<ide> join = left.create_join(right, left.create_on(condition))
<add> select = [
<add> # FIXME: options[:select] is always nil in the tests. Do we really
<add> # need it?
<add> options[:select] || left[Arel.star],
<add> right[reflection.primary_key_name].as(
<add> Arel.sql('the_parent_record_id'))
<add> ]
<ide>
<ide> associated_records_proxy = reflection.klass.unscoped.
<ide> includes(options[:include]).
<ide> joins(join).
<del> select("#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as the_parent_record_id").
<add> select(select).
<ide> order(options[:order])
<ide>
<ide> all_associated_records = associated_records(ids) do |some_ids| | 1 |
Text | Text | use es6 module instead of commonjs | 3a4c2a661fd875c98d9589922545fb98457611cf | <ide><path>docs/docs/context.md
<ide> class MessageList extends React.Component {
<ide> In this example, we manually thread through a `color` prop in order to style the `Button` and `Message` components appropriately. Using context, we can pass this through the tree automatically:
<ide>
<ide> ```javascript{6,13-15,21,28-30,40-42}
<del>const PropTypes = require('prop-types');
<add>import PropTypes from 'prop-types';
<ide>
<ide> class Button extends React.Component {
<ide> render() {
<ide> If `contextTypes` is defined within a component, the following [lifecycle method
<ide> Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows a `Button` component written as a stateless functional component.
<ide>
<ide> ```javascript
<del>const PropTypes = require('prop-types');
<add>import PropTypes from 'prop-types';
<ide>
<ide> const Button = ({children}, context) =>
<ide> <button style={{'{{'}}background: context.color}}>
<ide> React has an API to update context, but it is fundamentally broken and you shoul
<ide> The `getChildContext` function will be called when the state or props changes. In order to update data in the context, trigger a local state update with `this.setState`. This will trigger a new context and changes will be received by the children.
<ide>
<ide> ```javascript
<del>const PropTypes = require('prop-types');
<add>import PropTypes from 'prop-types';
<ide>
<ide> class MediaQuery extends React.Component {
<ide> constructor(props) { | 1 |
Javascript | Javascript | add zhopout to showcase | c01435ced01d5bf1bea2f6f457c82b16708181ce | <ide><path>website/src/react-native/showcase.js
<ide> var featured = [
<ide> link: 'https://itunes.apple.com/us/app/wpv/id725222647?mt=8',
<ide> author: 'Yamill Vallecillo',
<ide> },
<add> {
<add> name: 'Zhopout',
<add> icon: 'http://zhopout.com/Content/Images/zhopout-logo-app-3.png',
<add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.zhopout',
<add> author: 'Jarvis Software Private Limited ',
<add> blogs: [
<add> "https://medium.com/@murugandurai/how-we-developed-our-mobile-app-in-30-days-using-react-native-45affa6449e8#.29nnretsi",
<add> ],
<add> },
<ide> ];
<ide>
<ide> var apps = [ | 1 |
Javascript | Javascript | remove react.autobind entirely | f0a4ca5f69a4c0bffe40aa26335a7171ab6e7883 | <ide><path>src/core/__tests__/ReactBind-test.js
<ide> describe('React.autoBind', function() {
<ide> },
<ide> onMouseEnter: ReactDoNotBindDeprecated.doNotBind(mouseDidEnter),
<ide> onMouseLeave: ReactDoNotBindDeprecated.doNotBind(mouseDidLeave),
<del> onClick: React.autoBind(mouseDidClick),
<add> onClick: mouseDidClick,
<ide>
<ide> // auto binding only occurs on top level functions in class defs.
<ide> badIdeas: {
<ide> describe('React.autoBind', function() {
<ide> var mouseDidClick = mocks.getMockFunction();
<ide>
<ide> var TestMixin = {
<del> onClick: React.autoBind(mouseDidClick)
<add> onClick: mouseDidClick
<ide> };
<ide>
<ide> var TestBindComponent = React.createClass({ | 1 |
Javascript | Javascript | use parser#hooks instead of tapable#plugin | 9669c9e013664a5e4d8ed1f3baeab283ebd92e16 | <ide><path>lib/APIPlugin.js
<ide> class APIPlugin {
<ide>
<ide> const handler = parser => {
<ide> Object.keys(REPLACEMENTS).forEach(key => {
<del> parser.plugin(`expression ${key}`, NO_WEBPACK_REQUIRE[key] ? ParserHelpers.toConstantDependency(parser, REPLACEMENTS[key]) : ParserHelpers.toConstantDependencyWithWebpackRequire(parser, REPLACEMENTS[key]));
<del> parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
<add> parser.hooks.expression.for(key).tap("APIPlugin", NO_WEBPACK_REQUIRE[key] ? ParserHelpers.toConstantDependency(parser, REPLACEMENTS[key]) : ParserHelpers.toConstantDependencyWithWebpackRequire(parser, REPLACEMENTS[key]));
<add> parser.hooks.evaluateTypeof.for(key).tap("APIPlugin", ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
<ide> });
<ide> };
<ide>
<ide><path>lib/CompatibilityPlugin.js
<ide> class CompatibilityPlugin {
<ide> if(typeof parserOptions.browserify !== "undefined" && !parserOptions.browserify)
<ide> return;
<ide>
<del> parser.plugin("call require", (expr) => {
<add> parser.hooks.call.for("require").tap("CompatibilityPlugin", (expr) => {
<ide> // support for browserify style require delegator: "require(o, !0)"
<ide> if(expr.arguments.length !== 2) return;
<ide> const second = parser.evaluateExpression(expr.arguments[1]);
<ide><path>lib/ConstPlugin.js
<ide> class ConstPlugin {
<ide> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
<ide>
<ide> const handler = parser => {
<del> parser.plugin("statement if", statement => {
<add> parser.hooks.statementIf.tap("ConstPlugin", statement => {
<ide> const param = parser.evaluateExpression(statement.test);
<ide> const bool = param.asBool();
<ide> if(typeof bool === "boolean") {
<ide> class ConstPlugin {
<ide> return bool;
<ide> }
<ide> });
<del> parser.plugin("expression ?:", expression => {
<add> parser.hooks.expressionConditionalOperator.tap("ConstPlugin", expression => {
<ide> const param = parser.evaluateExpression(expression.test);
<ide> const bool = param.asBool();
<ide> if(typeof bool === "boolean") {
<ide> class ConstPlugin {
<ide> return bool;
<ide> }
<ide> });
<del> parser.plugin("evaluate Identifier __resourceQuery", expr => {
<add> parser.hooks.evaluateIdentifier.for("__resourceQuery").tap("ConstPlugin", expr => {
<ide> if(!parser.state.module) return;
<ide> return ParserHelpers.evaluateToString(getQuery(parser.state.module.resource))(expr);
<ide> });
<del> parser.plugin("expression __resourceQuery", () => {
<add> parser.hooks.expression.for("__resourceQuery").tap("ConstPlugin", () => {
<ide> if(!parser.state.module) return;
<ide> parser.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(parser.state.module.resource)));
<ide> return true;
<ide><path>lib/DefinePlugin.js
<ide> class DefinePlugin {
<ide> const splittedKey = key.split(".");
<ide> splittedKey.slice(1).forEach((_, i) => {
<ide> const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
<del> parser.plugin("can-rename " + fullKey, ParserHelpers.approve);
<add> parser.hooks.canRename.for(fullKey).tap("DefinePlugin", ParserHelpers.approve);
<ide> });
<ide> };
<ide>
<ide> class DefinePlugin {
<ide> let recurseTypeof = false;
<ide> code = toCode(code);
<ide> if(!isTypeof) {
<del> parser.plugin("can-rename " + key, ParserHelpers.approve);
<del> parser.plugin("evaluate Identifier " + key, (expr) => {
<add> parser.hooks.canRename.for(key).tap("DefinePlugin", ParserHelpers.approve);
<add> parser.hooks.evaluateIdentifier.for(key).tap("DefinePlugin", (expr) => {
<ide> /**
<ide> * this is needed in case there is a recursion in the DefinePlugin
<ide> * to prevent an endless recursion
<ide> class DefinePlugin {
<ide> res.setRange(expr.range);
<ide> return res;
<ide> });
<del> parser.plugin("expression " + key, /__webpack_require__/.test(code) ? ParserHelpers.toConstantDependencyWithWebpackRequire(parser, code) : ParserHelpers.toConstantDependency(parser, code));
<add> parser.hooks.expression.for(key).tap("DefinePlugin", /__webpack_require__/.test(code) ? ParserHelpers.toConstantDependencyWithWebpackRequire(parser, code) : ParserHelpers.toConstantDependency(parser, code));
<ide> }
<ide> const typeofCode = isTypeof ? code : "typeof (" + code + ")";
<del> parser.plugin("evaluate typeof " + key, (expr) => {
<add> parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", (expr) => {
<ide> /**
<ide> * this is needed in case there is a recursion in the DefinePlugin
<ide> * to prevent an endless recursion
<ide> class DefinePlugin {
<ide> res.setRange(expr.range);
<ide> return res;
<ide> });
<del> parser.plugin("typeof " + key, (expr) => {
<add> parser.hooks.typeof.for(key).tap("DefinePlugin", (expr) => {
<ide> const res = parser.evaluate(typeofCode);
<ide> if(!res.isString()) return;
<ide> return ParserHelpers.toConstantDependency(parser, JSON.stringify(res.string)).bind(parser)(expr);
<ide> class DefinePlugin {
<ide>
<ide> const applyObjectDefine = (key, obj) => {
<ide> const code = stringifyObj(obj);
<del> parser.plugin("can-rename " + key, ParserHelpers.approve);
<del> parser.plugin("evaluate Identifier " + key, (expr) => new BasicEvaluatedExpression().setTruthy().setRange(expr.range));
<del> parser.plugin("evaluate typeof " + key, ParserHelpers.evaluateToString("object"));
<del> parser.plugin("expression " + key, /__webpack_require__/.test(code) ? ParserHelpers.toConstantDependencyWithWebpackRequire(parser, code) : ParserHelpers.toConstantDependency(parser, code));
<del> parser.plugin("typeof " + key, ParserHelpers.toConstantDependency(parser, JSON.stringify("object")));
<add> parser.hooks.canRename.for(key).tap("DefinePlugin", ParserHelpers.approve);
<add> parser.hooks.evaluateIdentifier.for(key).tap("DefinePlugin", (expr) => new BasicEvaluatedExpression().setTruthy().setRange(expr.range));
<add> parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", ParserHelpers.evaluateToString("object"));
<add> parser.hooks.expression.for(key).tap("DefinePlugin", /__webpack_require__/.test(code) ? ParserHelpers.toConstantDependencyWithWebpackRequire(parser, code) : ParserHelpers.toConstantDependency(parser, code));
<add> parser.hooks.typeof.for(key).tap("DefinePlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("object")));
<ide> };
<ide>
<ide> walkDefinitions(definitions, "");
<ide><path>lib/ExtendedAPIPlugin.js
<ide> class ExtendedAPIPlugin {
<ide>
<ide> const handler = (parser, parserOptions) => {
<ide> Object.keys(REPLACEMENTS).forEach(key => {
<del> parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependencyWithWebpackRequire(parser, REPLACEMENTS[key]));
<del> parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
<add> parser.hooks.expression.for(key).tap("ExtendedAPIPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, REPLACEMENTS[key]));
<add> parser.hooks.evaluateTypeof.for(key).tap("ExtendedAPIPlugin", ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
<ide> });
<ide> };
<ide>
<ide><path>lib/HotModuleReplacementPlugin.js
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> });
<ide>
<ide> const handler = (parser, parserOptions) => {
<del> parser.plugin("expression __webpack_hash__", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, "__webpack_require__.h()"));
<del> parser.plugin("evaluate typeof __webpack_hash__", ParserHelpers.evaluateToString("string"));
<del> parser.plugin("evaluate Identifier module.hot", expr => {
<add> parser.hooks.expression.for("__webpack_hash__").tap("HotModuleReplacementPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, "__webpack_require__.h()"));
<add> parser.hooks.evaluateTypeof.for("__webpack_hash__").tap("HotModuleReplacementPlugin", ParserHelpers.evaluateToString("string"));
<add> parser.hooks.evaluateIdentifier.for("module.hot").tap("HotModuleReplacementPlugin", expr => {
<ide> return ParserHelpers.evaluateToIdentifier("module.hot", !!parser.state.compilation.hotUpdateChunkTemplate)(expr);
<ide> });
<ide> // TODO webpack 5: refactor this, no custom hooks
<ide> if(!parser.hooks.hotAcceptCallback)
<ide> parser.hooks.hotAcceptCallback = new SyncBailHook(["expression", "requests"]);
<ide> if(!parser.hooks.hotAcceptWithoutCallback)
<ide> parser.hooks.hotAcceptWithoutCallback = new SyncBailHook(["expression", "requests"]);
<del> parser.plugin("call module.hot.accept", expr => {
<add> parser.hooks.call.for("module.hot.accept").tap("HotModuleReplacementPlugin", expr => {
<ide> if(!parser.state.compilation.hotUpdateChunkTemplate) return false;
<ide> if(expr.arguments.length >= 1) {
<ide> const arg = parser.evaluateExpression(expr.arguments[0]);
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> }
<ide> }
<ide> });
<del> parser.plugin("call module.hot.decline", expr => {
<add> parser.hooks.call.for("module.hot.decline").tap("HotModuleReplacementPlugin", expr => {
<ide> if(!parser.state.compilation.hotUpdateChunkTemplate) return false;
<ide> if(expr.arguments.length === 1) {
<ide> const arg = parser.evaluateExpression(expr.arguments[0]);
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> });
<ide> }
<ide> });
<del> parser.plugin("expression module.hot", ParserHelpers.skipTraversal);
<add> parser.hooks.expression.for("module.hot").tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal);
<ide> };
<ide>
<ide> // TODO add HMR support for javascript/esm
<ide><path>lib/NodeStuffPlugin.js
<ide> class NodeStuffPlugin {
<ide> localOptions = Object.assign({}, localOptions, parserOptions.node);
<ide>
<ide> const setConstant = (expressionName, value) => {
<del> parser.plugin(`expression ${expressionName}`, () => {
<add> parser.hooks.expression.for(expressionName).tap("NodeStuffPlugin", () => {
<ide> parser.state.current.addVariable(expressionName, JSON.stringify(value));
<ide> return true;
<ide> });
<ide> };
<ide>
<ide> const setModuleConstant = (expressionName, fn) => {
<del> parser.plugin(`expression ${expressionName}`, () => {
<add> parser.hooks.expression.for(expressionName).tap("NodeStuffPlugin", () => {
<ide> parser.state.current.addVariable(expressionName, JSON.stringify(fn(parser.state.module)));
<ide> return true;
<ide> });
<ide> class NodeStuffPlugin {
<ide> } else if(localOptions.__filename) {
<ide> setModuleConstant("__filename", module => path.relative(context, module.resource));
<ide> }
<del> parser.plugin("evaluate Identifier __filename", expr => {
<add> parser.hooks.evaluateIdentifier.for("__filename").tap("NodeStuffPlugin", expr => {
<ide> if(!parser.state.module) return;
<ide> const resource = parser.state.module.resource;
<ide> const i = resource.indexOf("?");
<ide> class NodeStuffPlugin {
<ide> } else if(localOptions.__dirname) {
<ide> setModuleConstant("__dirname", module => path.relative(context, module.context));
<ide> }
<del> parser.plugin("evaluate Identifier __dirname", expr => {
<add> parser.hooks.evaluateIdentifier.for("__dirname").tap("NodeStuffPlugin", expr => {
<ide> if(!parser.state.module) return;
<ide> return ParserHelpers.evaluateToString(parser.state.module.context)(expr);
<ide> });
<del> parser.plugin("expression require.main", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, "__webpack_require__.c[__webpack_require__.s]"));
<del> parser.plugin(
<del> "expression require.extensions",
<del> ParserHelpers.expressionIsUnsupported(parser, "require.extensions is not supported by webpack. Use a loader instead.")
<del> );
<del> parser.plugin("expression module.loaded", expr => {
<add> parser.hooks.expression.for("require.main").tap("NodeStuffPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, "__webpack_require__.c[__webpack_require__.s]"));
<add> parser.hooks.expression.for("require.extensions").tap("NodeStuffPlugin", ParserHelpers.expressionIsUnsupported(parser, "require.extensions is not supported by webpack. Use a loader instead."));
<add> parser.hooks.expression.for("module.loaded").tap("NodeStuffPlugin", expr => {
<ide> parser.state.module.buildMeta.moduleConcatenationBailout = "module.loaded";
<ide> return ParserHelpers.toConstantDependency(parser, "module.l")(expr);
<ide> });
<del> parser.plugin("expression module.id", expr => {
<add> parser.hooks.expression.for("module.id").tap("NodeStuffPlugin", expr => {
<ide> parser.state.module.buildMeta.moduleConcatenationBailout = "module.id";
<ide> return ParserHelpers.toConstantDependency(parser, "module.i")(expr);
<ide> });
<del> parser.plugin("expression module.exports", () => {
<add> parser.hooks.expression.for("module.exports").tap("NodeStuffPlugin", () => {
<ide> const module = parser.state.module;
<ide> const isHarmony = module.buildMeta && module.buildMeta.harmonyModule;
<ide> if(!isHarmony)
<ide> return true;
<ide> });
<del> parser.plugin("evaluate Identifier module.hot", ParserHelpers.evaluateToIdentifier("module.hot", false));
<del> parser.plugin("expression module", () => {
<add> parser.hooks.evaluateIdentifier.for("module.hot").tap("NodeStuffPlugin", ParserHelpers.evaluateToIdentifier("module.hot", false));
<add> parser.hooks.expression.for("module").tap("NodeStuffPlugin", () => {
<ide> const module = parser.state.module;
<ide> const isHarmony = module.buildMeta && module.buildMeta.harmonyModule;
<ide> let moduleJsPath = path.join(__dirname, "..", "buildin", isHarmony ? "harmony-module.js" : "module.js");
<ide><path>lib/Parser.js
<ide> class Parser extends Tapable {
<ide> assigned: new HookMap(() => new SyncBailHook(["expression"])),
<ide> assign: new HookMap(() => new SyncBailHook(["expression"])),
<ide> typeof: new HookMap(() => new SyncBailHook(["expression"])),
<del> expressionConditionalOperator: new SyncBailHook(["expression"]),
<ide> importCall: new SyncBailHook(["expression"]),
<ide> call: new HookMap(() => new SyncBailHook(["expression"])),
<ide> callAnyMember: new HookMap(() => new SyncBailHook(["expression"])),
<ide> new: new HookMap(() => new SyncBailHook(["expression"])),
<ide> expression: new HookMap(() => new SyncBailHook(["expression"])),
<ide> expressionAnyMember: new HookMap(() => new SyncBailHook(["expression"])),
<add> expressionConditionalOperator: new SyncBailHook(["expression"]),
<ide> program: new SyncBailHook(["ast", "comments"]),
<ide> };
<ide> const HOOK_MAP_COMPAT_CONFIG = {
<ide> class Parser extends Tapable {
<ide> typeof: /^typeof (.+)$/,
<ide> assigned: /^assigned (.+)$/,
<ide> assign: /^assign (.+)$/,
<del> expressionConditionalOperator: /^expression \?:$/,
<ide> callAnyMember: /^call (.+)\.\*$/,
<ide> call: /^call (.+)$/,
<ide> new: /^new (.+)$/,
<add> expressionConditionalOperator: /^expression \?:$/,
<ide> expressionAnyMember: /^expression (.+)\.\*$/,
<ide> expression: /^expression (.+)$/,
<ide> };
<ide> class Parser extends Tapable {
<ide> }
<ide>
<ide> initializeEvaluating() {
<del> this.plugin("evaluate Literal", expr => {
<add> this.hooks.evaluate.for("Literal").tap("Parser", expr => {
<ide> switch(typeof expr.value) {
<ide> case "number":
<ide> return new BasicEvaluatedExpression().setNumber(expr.value).setRange(expr.range);
<ide> class Parser extends Tapable {
<ide> if(expr.value instanceof RegExp)
<ide> return new BasicEvaluatedExpression().setRegExp(expr.value).setRange(expr.range);
<ide> });
<del> this.plugin("evaluate LogicalExpression", expr => {
<add> this.hooks.evaluate.for("LogicalExpression").tap("Parser", expr => {
<ide> let left;
<ide> let leftAsBool;
<ide> let right;
<ide> class Parser extends Tapable {
<ide> return right.setRange(expr.range);
<ide> }
<ide> });
<del> this.plugin("evaluate BinaryExpression", expr => {
<add> this.hooks.evaluate.for("BinaryExpression").tap("Parser", expr => {
<ide> let left;
<ide> let right;
<ide> let res;
<ide> class Parser extends Tapable {
<ide> return res;
<ide> }
<ide> });
<del> this.plugin("evaluate UnaryExpression", expr => {
<add> this.hooks.evaluate.for("UnaryExpression").tap("Parser", expr => {
<ide> if(expr.operator === "typeof") {
<ide> let res;
<ide> let name;
<ide> class Parser extends Tapable {
<ide> return res;
<ide> }
<ide> });
<del> this.plugin("evaluate typeof undefined", expr => {
<add> this.hooks.evaluateTypeof.for("undefined").tap("Parser", expr => {
<ide> return new BasicEvaluatedExpression().setString("undefined").setRange(expr.range);
<ide> });
<del> this.plugin("evaluate Identifier", expr => {
<add> this.hooks.evaluate.for("Identifier").tap("Parser", expr => {
<ide> const name = this.scope.renames.get(expr.name) || expr.name;
<ide> if(!this.scope.definitions.has(expr.name)) {
<ide> const hook = this.hooks.evaluateIdentifier.get(name);
<ide> class Parser extends Tapable {
<ide> }
<ide> }
<ide> });
<del> this.plugin("evaluate ThisExpression", expr => {
<add> this.hooks.evaluate.for("ThisExpression").tap("Parser", expr => {
<ide> const name = this.scope.renames.get("this");
<ide> if(name) {
<ide> const hook = this.hooks.evaluateIdentifier.get(name);
<ide> class Parser extends Tapable {
<ide> return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range);
<ide> }
<ide> });
<del> this.plugin("evaluate MemberExpression", expression => {
<add> this.hooks.evaluate.for("MemberExpression").tap("Parser", expression => {
<ide> let exprName = this.getNameForExpression(expression);
<ide> if(exprName) {
<ide> if(exprName.free) {
<ide> class Parser extends Tapable {
<ide> }
<ide> }
<ide> });
<del> this.plugin("evaluate CallExpression", expr => {
<add> this.hooks.evaluate.for("CallExpression").tap("Parser", expr => {
<ide> if(expr.callee.type !== "MemberExpression") return;
<ide> if(expr.callee.property.type !== (expr.callee.computed ? "Literal" : "Identifier")) return;
<ide> const param = this.evaluateExpression(expr.callee.object);
<ide> class Parser extends Tapable {
<ide> return hook.call(expr, param);
<ide> }
<ide> });
<del> this.plugin("evaluate CallExpression .replace", (expr, param) => {
<add> this.hooks.evaluateCallExpressionMember.for("replace").tap("Parser", (expr, param) => {
<ide> if(!param.isString()) return;
<ide> if(expr.arguments.length !== 2) return;
<ide> let arg1 = this.evaluateExpression(expr.arguments[0]);
<ide> class Parser extends Tapable {
<ide> return new BasicEvaluatedExpression().setString(param.string.replace(arg1, arg2)).setRange(expr.range);
<ide> });
<ide> ["substr", "substring"].forEach(fn => {
<del> this.plugin("evaluate CallExpression ." + fn, (expr, param) => {
<add> this.hooks.evaluateCallExpressionMember.for(fn).tap("Parser", (expr, param) => {
<ide> if(!param.isString()) return;
<ide> let arg1;
<ide> let result, str = param.string;
<ide> class Parser extends Tapable {
<ide> return parts;
<ide> };
<ide>
<del> this.plugin("evaluate TemplateLiteral", node => {
<add> this.hooks.evaluate.for("TemplateLiteral").tap("Parser", node => {
<ide> const parts = getSimplifiedTemplateResult.call(this, "cooked", node.quasis, node.expressions);
<ide> if(parts.length === 1) {
<ide> return parts[0].setRange(node.range);
<ide> }
<ide> return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);
<ide> });
<del> this.plugin("evaluate TaggedTemplateExpression", node => {
<add> this.hooks.evaluate.for("TaggedTemplateExpression").tap("Parser", node => {
<ide> if(this.evaluateExpression(node.tag).identifier !== "String.raw") return;
<ide> const parts = getSimplifiedTemplateResult.call(this, "raw", node.quasi.quasis, node.quasi.expressions);
<ide> return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);
<ide> });
<ide>
<del> this.plugin("evaluate CallExpression .concat", (expr, param) => {
<add> this.hooks.evaluateCallExpressionMember.for("concat").tap("Parser", (expr, param) => {
<ide> if(!param.isString() && !param.isWrapped()) return;
<ide>
<ide> let stringSuffix = null;
<ide> class Parser extends Tapable {
<ide> return new BasicEvaluatedExpression().setString(newString).setRange(expr.range);
<ide> }
<ide> });
<del> this.plugin("evaluate CallExpression .split", (expr, param) => {
<add> this.hooks.evaluateCallExpressionMember.for("split").tap("Parser", (expr, param) => {
<ide> if(!param.isString()) return;
<ide> if(expr.arguments.length !== 1) return;
<ide> let result;
<ide> class Parser extends Tapable {
<ide> } else return;
<ide> return new BasicEvaluatedExpression().setArray(result).setRange(expr.range);
<ide> });
<del> this.plugin("evaluate ConditionalExpression", expr => {
<add> this.hooks.evaluate.for("ConditionalExpression").tap("Parser", expr => {
<ide> const condition = this.evaluateExpression(expr.test);
<ide> const conditionValue = condition.asBool();
<ide> let res;
<ide> class Parser extends Tapable {
<ide> res.setRange(expr.range);
<ide> return res;
<ide> });
<del> this.plugin("evaluate ArrayExpression", expr => {
<add> this.hooks.evaluate.for("ArrayExpression").tap("Parser", expr => {
<ide> const items = expr.elements.map(element => {
<ide> return element !== null && this.evaluateExpression(element);
<ide> });
<ide><path>lib/RequireJsStuffPlugin.js
<ide> module.exports = class RequireJsStuffPlugin {
<ide> if(typeof parserOptions.requireJs !== "undefined" && !parserOptions.requireJs)
<ide> return;
<ide>
<del> parser.plugin("call require.config", ParserHelpers.toConstantDependency(parser, "undefined"));
<del> parser.plugin("call requirejs.config", ParserHelpers.toConstantDependency(parser, "undefined"));
<add> parser.hooks.call.for("require.config").tap("RequireJsStuffPlugin", ParserHelpers.toConstantDependency(parser, "undefined"));
<add> parser.hooks.call.for("requirejs.config").tap("RequireJsStuffPlugin", ParserHelpers.toConstantDependency(parser, "undefined"));
<ide>
<del> parser.plugin("expression require.version", ParserHelpers.toConstantDependency(parser, JSON.stringify("0.0.0")));
<del> parser.plugin("expression requirejs.onError", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, "__webpack_require__.oe"));
<add> parser.hooks.expression.for("require.version").tap("RequireJsStuffPlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("0.0.0")));
<add> parser.hooks.expression.for("requirejs.onError").tap("RequireJsStuffPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, "__webpack_require__.oe"));
<ide> };
<ide> normalModuleFactory.hooks.parser.for("javascript/auto").tap("RequireJsStuffPlugin", handler);
<ide> normalModuleFactory.hooks.parser.for("javascript/dynamic").tap("RequireJsStuffPlugin", handler);
<ide><path>lib/dependencies/AMDDefineDependencyParserPlugin.js
<ide> class AMDDefineDependencyParserPlugin {
<ide> return true;
<ide> };
<ide>
<del> parser.plugin("call define", (expr) => {
<add> parser.hooks.call.for("define").tap("AMDDefineDependencyParserPlugin", (expr) => {
<ide> let array, fn, obj, namedModule;
<ide> switch(expr.arguments.length) {
<ide> case 1:
<ide><path>lib/dependencies/AMDPlugin.js
<ide> class AMDPlugin {
<ide> return;
<ide>
<ide> const setExpressionToModule = (outerExpr, module) => {
<del> parser.plugin("expression " + outerExpr, (expr) => {
<add> parser.hooks.expression.for(outerExpr).tap("AMDPlugin", (expr) => {
<ide> const dep = new AMDRequireItemDependency(module, expr.range);
<ide> dep.userRequest = outerExpr;
<ide> dep.loc = expr.loc;
<ide> class AMDPlugin {
<ide> setExpressionToModule("define.amd", "!!webpack amd options");
<ide> setExpressionToModule("define", "!!webpack amd define");
<ide>
<del> parser.plugin("expression __webpack_amd_options__", () =>
<add> parser.hooks.expression.for("__webpack_amd_options__").tap("AMDPlugin", () =>
<ide> parser.state.current.addVariable("__webpack_amd_options__", JSON.stringify(amdOptions)));
<del> parser.plugin("evaluate typeof define.amd", ParserHelpers.evaluateToString(typeof amdOptions));
<del> parser.plugin("evaluate typeof require.amd", ParserHelpers.evaluateToString(typeof amdOptions));
<del> parser.plugin("evaluate Identifier define.amd", ParserHelpers.evaluateToIdentifier("define.amd", true));
<del> parser.plugin("evaluate Identifier require.amd", ParserHelpers.evaluateToIdentifier("require.amd", true));
<del> parser.plugin("typeof define", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<del> parser.plugin("evaluate typeof define", ParserHelpers.evaluateToString("function"));
<del> parser.plugin("can-rename define", ParserHelpers.approve);
<del> parser.plugin("rename define", (expr) => {
<add> parser.hooks.evaluateTypeof.for("define.amd").tap("AMDPlugin", ParserHelpers.evaluateToString(typeof amdOptions));
<add> parser.hooks.evaluateTypeof.for("require.amd").tap("AMDPlugin", ParserHelpers.evaluateToString(typeof amdOptions));
<add> parser.hooks.evaluateIdentifier.for("define.amd").tap("AMDPlugin", ParserHelpers.evaluateToIdentifier("define.amd", true));
<add> parser.hooks.evaluateIdentifier.for("require.amd").tap("AMDPlugin", ParserHelpers.evaluateToIdentifier("require.amd", true));
<add> parser.hooks.typeof.for("define").tap("AMDPlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<add> parser.hooks.evaluateTypeof.for("define").tap("AMDPlugin", ParserHelpers.evaluateToString("function"));
<add> parser.hooks.canRename.for("define").tap("AMDPlugin", ParserHelpers.approve);
<add> parser.hooks.rename.for("define").tap("AMDPlugin", (expr) => {
<ide> const dep = new AMDRequireItemDependency("!!webpack amd define", expr.range);
<ide> dep.userRequest = "define";
<ide> dep.loc = expr.loc;
<ide> parser.state.current.addDependency(dep);
<ide> return false;
<ide> });
<del> parser.plugin("typeof require", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<del> parser.plugin("evaluate typeof require", ParserHelpers.evaluateToString("function"));
<add> parser.hooks.typeof.for("require").tap("AMDPlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<add> parser.hooks.evaluateTypeof.for("require").tap("AMDPlugin", ParserHelpers.evaluateToString("function"));
<ide> };
<ide>
<ide> normalModuleFactory.hooks.parser.for("javascript/auto").tap("AMDPlugin", handler);
<ide><path>lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js
<ide> class AMDRequireDependenciesBlockParserPlugin {
<ide> return true;
<ide> };
<ide>
<del> parser.plugin("call require", (expr) => {
<add> parser.hooks.call.for("require").tap("AMDRequireDependenciesBlockParserPlugin", (expr) => {
<ide> let param;
<ide> let dep;
<ide> let result;
<ide><path>lib/dependencies/CommonJsPlugin.js
<ide> class CommonJsPlugin {
<ide>
<ide> const requireExpressions = ["require", "require.resolve", "require.resolveWeak"];
<ide> for(let expression of requireExpressions) {
<del> parser.plugin(`typeof ${expression}`, ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<del> parser.plugin(`evaluate typeof ${expression}`, ParserHelpers.evaluateToString("function"));
<del> parser.plugin(`evaluate Identifier ${expression}`, ParserHelpers.evaluateToIdentifier(expression, true));
<add> parser.hooks.typeof.for(expression).tap("CommonJsPlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<add> parser.hooks.evaluateTypeof.for(expression).tap("CommonJsPlugin", ParserHelpers.evaluateToString("function"));
<add> parser.hooks.evaluateIdentifier.for(expression).tap("CommonJsPlugin", ParserHelpers.evaluateToIdentifier(expression, true));
<ide> }
<ide>
<del> parser.plugin("evaluate typeof module", ParserHelpers.evaluateToString("object"));
<del> parser.plugin("assign require", (expr) => {
<add> parser.hooks.evaluateTypeof.for("module").tap("CommonJsPlugin", ParserHelpers.evaluateToString("object"));
<add> parser.hooks.assign.for("require").tap("CommonJsPlugin", (expr) => {
<ide> // to not leak to global "require", we need to define a local require here.
<ide> const dep = new ConstDependency("var require;", 0);
<ide> dep.loc = expr.loc;
<ide> parser.state.current.addDependency(dep);
<ide> parser.scope.definitions.add("require");
<ide> return true;
<ide> });
<del> parser.plugin("can-rename require", () => true);
<del> parser.plugin("rename require", (expr) => {
<add> parser.hooks.canRename.for("require").tap("CommonJsPlugin", () => true);
<add> parser.hooks.rename.for("require").tap("CommonJsPlugin", (expr) => {
<ide> // define the require variable. It's still undefined, but not "not defined".
<ide> const dep = new ConstDependency("var require;", 0);
<ide> dep.loc = expr.loc;
<ide> parser.state.current.addDependency(dep);
<ide> return false;
<ide> });
<del> parser.plugin("typeof module", () => true);
<del> parser.plugin("evaluate typeof exports", ParserHelpers.evaluateToString("object"));
<add> parser.hooks.typeof.for("module").tap("CommonJsPlugin", () => true);
<add> parser.hooks.evaluateTypeof.for("exports").tap("CommonJsPlugin", ParserHelpers.evaluateToString("object"));
<ide>
<ide> new CommonJsRequireDependencyParserPlugin(options).apply(parser);
<ide> new RequireResolveDependencyParserPlugin(options).apply(parser);
<ide><path>lib/dependencies/CommonJsRequireDependencyParserPlugin.js
<ide> class CommonJsRequireDependencyParserPlugin {
<ide> return true;
<ide> };
<ide>
<del> parser.plugin("expression require.cache", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, "__webpack_require__.c"));
<del> parser.plugin("expression require", (expr) => {
<add> parser.hooks.expression.for("require.cache").tap("CommonJsRequireDependencyParserPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire(parser, "__webpack_require__.c"));
<add> parser.hooks.expression.for("require").tap("CommonJsRequireDependencyParserPlugin", (expr) => {
<ide> const dep = new CommonJsRequireContextDependency({
<ide> request: options.unknownContextRequest,
<ide> recursive: options.unknownContextRecursive,
<ide> class CommonJsRequireDependencyParserPlugin {
<ide> parser.state.current.addDependency(dep);
<ide> return true;
<ide> });
<del> parser.plugin("call require", (expr) => {
<add> parser.hooks.call.for("require").tap("CommonJsRequireDependencyParserPlugin", (expr) => {
<ide> if(expr.arguments.length !== 1) return;
<ide> let localModule;
<ide> const param = parser.evaluateExpression(expr.arguments[0]);
<ide><path>lib/dependencies/HarmonyDetectionParserPlugin.js
<ide> const HarmonyInitDependency = require("./HarmonyInitDependency");
<ide>
<ide> module.exports = class HarmonyDetectionParserPlugin {
<ide> apply(parser) {
<del> parser.plugin("program", (ast) => {
<add> parser.hooks.program.tap("HarmonyDetectionParserPlugin", (ast) => {
<ide> const isStrictHarmony = parser.state.module.type === "javascript/esm";
<ide> const isHarmony = isStrictHarmony || ast.body.some(statement => {
<ide> return /^(Import|Export).*Declaration$/.test(statement.type);
<ide> module.exports = class HarmonyDetectionParserPlugin {
<ide>
<ide> const nonHarmonyIdentifiers = ["define", "exports"];
<ide> nonHarmonyIdentifiers.forEach(identifer => {
<del> parser.plugin(`evaluate typeof ${identifer}`, nullInHarmony);
<del> parser.plugin(`typeof ${identifer}`, skipInHarmony);
<del> parser.plugin(`evaluate ${identifer}`, nullInHarmony);
<del> parser.plugin(`expression ${identifer}`, skipInHarmony);
<del> parser.plugin(`call ${identifer}`, skipInHarmony);
<add> parser.hooks.evaluateTypeof.for(identifer).tap("HarmonyDetectionParserPlugin", nullInHarmony);
<add> parser.hooks.typeof.for(identifer).tap("HarmonyDetectionParserPlugin", skipInHarmony);
<add> parser.hooks.evaluate.for(identifer).tap("HarmonyDetectionParserPlugin", nullInHarmony);
<add> parser.hooks.expression.for(identifer).tap("HarmonyDetectionParserPlugin", skipInHarmony);
<add> parser.hooks.call.for(identifer).tap("HarmonyDetectionParserPlugin", skipInHarmony);
<ide> });
<ide> }
<ide> };
<ide><path>lib/dependencies/HarmonyExportDependencyParserPlugin.js
<ide> module.exports = class HarmonyExportDependencyParserPlugin {
<ide> }
<ide>
<ide> apply(parser) {
<del> parser.plugin("export", statement => {
<add> parser.hooks.export.tap("HarmonyExportDependencyParserPlugin", statement => {
<ide> const dep = new HarmonyExportHeaderDependency(statement.declaration && statement.declaration.range, statement.range);
<ide> dep.loc = Object.create(statement.loc);
<ide> dep.loc.index = -1;
<ide> parser.state.current.addDependency(dep);
<ide> return true;
<ide> });
<del> parser.plugin("export import", (statement, source) => {
<add> parser.hooks.exportImport.tap("HarmonyExportDependencyParserPlugin", (statement, source) => {
<ide> parser.state.lastHarmonyImportOrder = (parser.state.lastHarmonyImportOrder || 0) + 1;
<ide> const clearDep = new ConstDependency("", statement.range);
<ide> clearDep.loc = Object.create(statement.loc);
<ide> module.exports = class HarmonyExportDependencyParserPlugin {
<ide> parser.state.current.addDependency(sideEffectDep);
<ide> return true;
<ide> });
<del> parser.plugin("export expression", (statement, expr) => {
<add> parser.hooks.exportExpression.tap("HarmonyExportDependencyParserPlugin", (statement, expr) => {
<ide> const dep = new HarmonyExportExpressionDependency(parser.state.module, expr.range, statement.range);
<ide> dep.loc = Object.create(statement.loc);
<ide> dep.loc.index = -1;
<ide> parser.state.current.addDependency(dep);
<ide> return true;
<ide> });
<del> parser.plugin("export declaration", statement => {});
<del> parser.plugin("export specifier", (statement, id, name, idx) => {
<add> parser.hooks.exportDeclaration.tap("HarmonyExportDependencyParserPlugin", statement => {});
<add> parser.hooks.exportSpecifier.tap("HarmonyExportDependencyParserPlugin", (statement, id, name, idx) => {
<ide> const rename = parser.scope.renames.get(id);
<ide> let dep;
<ide> const harmonyNamedExports = parser.state.harmonyNamedExports = parser.state.harmonyNamedExports || new Set();
<ide> module.exports = class HarmonyExportDependencyParserPlugin {
<ide> parser.state.current.addDependency(dep);
<ide> return true;
<ide> });
<del> parser.plugin("export import specifier", (statement, source, id, name, idx) => {
<add> parser.hooks.exportImportSpecifier.tap("HarmonyExportDependencyParserPlugin", (statement, source, id, name, idx) => {
<ide> const harmonyNamedExports = parser.state.harmonyNamedExports = parser.state.harmonyNamedExports || new Set();
<ide> let harmonyStarExports = null;
<ide> if(name) {
<ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> }
<ide>
<ide> apply(parser) {
<del> parser.plugin("import", (statement, source) => {
<add> parser.hooks.import.tap("HarmonyImportDependencyParserPlugin", (statement, source) => {
<ide> parser.state.lastHarmonyImportOrder = (parser.state.lastHarmonyImportOrder || 0) + 1;
<ide> const clearDep = new ConstDependency("", statement.range);
<ide> clearDep.loc = statement.loc;
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> parser.state.module.addDependency(sideEffectDep);
<ide> return true;
<ide> });
<del> parser.plugin("import specifier", (statement, source, id, name) => {
<add> parser.hooks.importSpecifier.tap("HarmonyImportDependencyParserPlugin", (statement, source, id, name) => {
<ide> parser.scope.definitions.delete(name);
<ide> parser.scope.renames.set(name, "imported var");
<ide> if(!parser.state.harmonySpecifier) parser.state.harmonySpecifier = new Map();
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> });
<ide> return true;
<ide> });
<del> parser.plugin("expression imported var", (expr) => {
<add> parser.hooks.expression.for("imported var").tap("HarmonyImportDependencyParserPlugin", (expr) => {
<ide> const name = expr.name;
<ide> const settings = parser.state.harmonySpecifier.get(name);
<ide> const dep = new HarmonyImportSpecifierDependency(settings.source, parser.state.module, settings.sourceOrder, parser.state.harmonyParserScope, settings.id, name, expr.range, this.strictExportPresence);
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> parser.state.module.addDependency(dep);
<ide> return true;
<ide> });
<del> parser.plugin("expression imported var.*", (expr) => {
<add> parser.hooks.expressionAnyMember.for("imported var").tap("HarmonyImportDependencyParserPlugin", (expr) => {
<ide> const name = expr.object.name;
<ide> const settings = parser.state.harmonySpecifier.get(name);
<ide> if(settings.id !== null)
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> });
<ide> if(this.strictThisContextOnImports) {
<ide> // only in case when we strictly follow the spec we need a special case here
<del> parser.plugin("call imported var.*", (expr) => {
<add> parser.hooks.callAnyMember.for("imported var").tap("HarmonyImportDependencyParserPlugin", (expr) => {
<ide> if(expr.callee.type !== "MemberExpression") return;
<ide> if(expr.callee.object.type !== "Identifier") return;
<ide> const name = expr.callee.object.name;
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> return true;
<ide> });
<ide> }
<del> parser.plugin("call imported var", (expr) => {
<add> parser.hooks.call.for("imported var").tap("HarmonyImportDependencyParserPlugin", (expr) => {
<ide> const args = expr.arguments;
<ide> const fullExpr = expr;
<ide> expr = expr.callee;
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> parser.hooks.hotAcceptCallback = new SyncBailHook(["expression", "requests"]);
<ide> if(!parser.hooks.hotAcceptWithoutCallback)
<ide> parser.hooks.hotAcceptWithoutCallback = new SyncBailHook(["expression", "requests"]);
<del> parser.plugin("hot accept callback", (expr, requests) => {
<add> parser.hooks.hotAcceptCallback.tap("HarmonyImportDependencyParserPlugin", (expr, requests) => {
<ide> const dependencies = requests
<ide> .map(request => {
<ide> const dep = new HarmonyAcceptImportDependency(request, parser.state.module, parser.state.harmonyParserScope);
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> parser.state.module.addDependency(dep);
<ide> }
<ide> });
<del> parser.plugin("hot accept without callback", (expr, requests) => {
<add> parser.hooks.hotAcceptWithoutCallback.tap("HarmonyImportDependencyParserPlugin", (expr, requests) => {
<ide> const dependencies = requests
<ide> .map(request => {
<ide> const dep = new HarmonyAcceptImportDependency(request, parser.state.module, parser.state.harmonyParserScope);
<ide><path>lib/dependencies/ImportParserPlugin.js
<ide> class ImportParserPlugin {
<ide>
<ide> apply(parser) {
<ide> const options = this.options;
<del>
<del> parser.plugin(["call System.import", "import-call"], (expr) => {
<add> const handler = (expr) => {
<ide> if(expr.arguments.length !== 1)
<ide> throw new Error("Incorrect number of arguments provided to 'import(module: string) -> Promise'.");
<ide>
<ide> class ImportParserPlugin {
<ide> parser.state.current.addDependency(dep);
<ide> return true;
<ide> }
<del> });
<add> };
<add>
<add> parser.hooks.call.for("System.import").tap("ImportParserPlugin", handler);
<add> parser.hooks.importCall.tap("ImportParserPlugin", handler);
<ide> }
<ide> }
<ide> module.exports = ImportParserPlugin;
<ide><path>lib/dependencies/RequireContextDependencyParserPlugin.js
<ide> const RequireContextDependency = require("./RequireContextDependency");
<ide>
<ide> module.exports = class RequireContextDependencyParserPlugin {
<ide> apply(parser) {
<del> parser.plugin("call require.context", expr => {
<add> parser.hooks.call.for("require.context").tap("RequireContextDependencyParserPlugin", expr => {
<ide> let regExp = /^\.\/.*$/;
<ide> let recursive = true;
<ide> let mode = "sync";
<ide><path>lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js
<ide> const getFunctionExpression = require("./getFunctionExpression");
<ide>
<ide> module.exports = class RequireEnsureDependenciesBlockParserPlugin {
<ide> apply(parser) {
<del> parser.plugin("call require.ensure", expr => {
<add> parser.hooks.call.for("require.ensure").tap("RequireEnsureDependenciesBlockParserPlugin", expr => {
<ide> let chunkName = null;
<ide> let chunkNameRange = null;
<ide> let errorExpressionArg = null;
<ide><path>lib/dependencies/RequireEnsurePlugin.js
<ide> class RequireEnsurePlugin {
<ide> return;
<ide>
<ide> new RequireEnsureDependenciesBlockParserPlugin().apply(parser);
<del> parser.plugin("evaluate typeof require.ensure", ParserHelpers.evaluateToString("function"));
<del> parser.plugin("typeof require.ensure", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<add> parser.hooks.evaluateTypeof.for("require.ensure").tap("RequireEnsurePlugin", ParserHelpers.evaluateToString("function"));
<add> parser.hooks.typeof.for("require.ensure").tap("RequireEnsurePlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<ide> };
<ide>
<ide> normalModuleFactory.hooks.parser.for("javascript/auto").tap("RequireEnsurePlugin", handler);
<ide><path>lib/dependencies/RequireIncludeDependencyParserPlugin.js
<ide> const RequireIncludeDependency = require("./RequireIncludeDependency");
<ide>
<ide> module.exports = class RequireIncludeDependencyParserPlugin {
<ide> apply(parser) {
<del> parser.plugin("call require.include", expr => {
<add> parser.hooks.call.for("require.include").tap("RequireIncludeDependencyParserPlugin", expr => {
<ide> if(expr.arguments.length !== 1) return;
<ide> const param = parser.evaluateExpression(expr.arguments[0]);
<ide> if(!param.isString()) return;
<ide><path>lib/dependencies/RequireIncludePlugin.js
<ide> class RequireIncludePlugin {
<ide> return;
<ide>
<ide> new RequireIncludeDependencyParserPlugin().apply(parser);
<del> parser.plugin("evaluate typeof require.include", ParserHelpers.evaluateToString("function"));
<del> parser.plugin("typeof require.include", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<add> parser.hooks.evaluateTypeof.for("require.include").tap("RequireIncludePlugin", ParserHelpers.evaluateToString("function"));
<add> parser.hooks.typeof.for("require.include").tap("RequireIncludePlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<ide> };
<ide>
<ide> normalModuleFactory.hooks.parser.for("javascript/auto").tap("RequireIncludePlugin", handler);
<ide><path>lib/dependencies/RequireResolveDependencyParserPlugin.js
<ide> class RequireResolveDependencyParserPlugin {
<ide> return true;
<ide> };
<ide>
<del> parser.plugin("call require.resolve", (expr) => {
<add> parser.hooks.call.for("require.resolve").tap("RequireResolveDependencyParserPlugin", (expr) => {
<ide> return process(expr, false);
<ide> });
<del> parser.plugin("call require.resolveWeak", (expr) => {
<add> parser.hooks.call.for("require.resolveWeak").tap("RequireResolveDependencyParserPlugin", (expr) => {
<ide> return process(expr, true);
<ide> });
<ide> }
<ide><path>lib/dependencies/SystemPlugin.js
<ide> class SystemPlugin {
<ide> return;
<ide>
<ide> const setNotSupported = name => {
<del> parser.plugin("evaluate typeof " + name, ParserHelpers.evaluateToString("undefined"));
<del> parser.plugin("expression " + name,
<add> parser.hooks.evaluateTypeof.for(name).tap("SystemPlugin", ParserHelpers.evaluateToString("undefined"));
<add> parser.hooks.expression.for(name).tap("SystemPlugin",
<ide> ParserHelpers.expressionIsUnsupported(parser, name + " is not supported by webpack.")
<ide> );
<ide> };
<ide>
<del> parser.plugin("typeof System.import", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<del> parser.plugin("evaluate typeof System.import", ParserHelpers.evaluateToString("function"));
<del> parser.plugin("typeof System", ParserHelpers.toConstantDependency(parser, JSON.stringify("object")));
<del> parser.plugin("evaluate typeof System", ParserHelpers.evaluateToString("object"));
<add> parser.hooks.typeof.for("System.import").tap("SystemPlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("function")));
<add> parser.hooks.evaluateTypeof.for("System.import").tap("SystemPlugin", ParserHelpers.evaluateToString("function"));
<add> parser.hooks.typeof.for("System").tap("SystemPlugin", ParserHelpers.toConstantDependency(parser, JSON.stringify("object")));
<add> parser.hooks.evaluateTypeof.for("System").tap("SystemPlugin", ParserHelpers.evaluateToString("object"));
<ide>
<ide> setNotSupported("System.set");
<ide> setNotSupported("System.get");
<ide> setNotSupported("System.register");
<del> parser.plugin("expression System", () => {
<add>
<add> parser.hooks.expression.for("System").tap("SystemPlugin", () => {
<ide> const systemPolyfillRequire = ParserHelpers.requireFileAsExpression(
<ide> parser.state.module.context, require.resolve("../../buildin/system.js"));
<ide> return ParserHelpers.addParsedVariableToModule(parser, "System", systemPolyfillRequire);
<ide><path>lib/node/NodeSourcePlugin.js
<ide> module.exports = class NodeSourcePlugin {
<ide>
<ide> const addExpression = (parser, name, module, type, suffix) => {
<ide> suffix = suffix || "";
<del> parser.plugin(`expression ${name}`, () => {
<add> parser.hooks.expression.for(name).tap("NodeSourcePlugin", () => {
<ide> if(parser.state.module && parser.state.module.resource === getPathToModule(module, type)) return;
<ide> const mockModule = ParserHelpers.requireFileAsExpression(parser.state.module.context, getPathToModule(module, type));
<ide> return ParserHelpers.addParsedVariableToModule(parser, name, mockModule + suffix);
<ide> module.exports = class NodeSourcePlugin {
<ide> localOptions = Object.assign({}, localOptions, parserOptions.node);
<ide>
<ide> if(localOptions.global) {
<del> parser.plugin("expression global", () => {
<add> parser.hooks.expression.for("global").tap("NodeSourcePlugin", () => {
<ide> const retrieveGlobalModule = ParserHelpers.requireFileAsExpression(parser.state.module.context, require.resolve("../../buildin/global.js"));
<ide> return ParserHelpers.addParsedVariableToModule(parser, "global", retrieveGlobalModule);
<ide> });
<ide><path>lib/optimize/ModuleConcatenationPlugin.js
<ide> class ModuleConcatenationPlugin {
<ide> normalModuleFactory
<ide> }) => {
<ide> const handler = (parser, parserOptions) => {
<del> parser.plugin("call eval", () => {
<add> parser.hooks.call.for("eval").tap("ModuleConcatenationPlugin", () => {
<ide> // Because of variable renaming we can't use modules with eval.
<ide> parser.state.module.buildMeta.moduleConcatenationBailout = "eval()";
<ide> }); | 27 |
Ruby | Ruby | update documentation of length validation | 30edef785f61fa505426ff5307be7d0fe3255d6e | <ide><path>activemodel/lib/active_model/validations/validates.rb
<ide> module ClassMethods
<ide> # Example:
<ide> #
<ide> # validates :password, presence: true, confirmation: true, if: :password_required?
<del> # validates :token, length: 24, strict: TokenLengthException
<add> # validates :token, length: {is: 24}, strict: TokenLengthException
<ide> #
<ide> #
<ide> # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+, +:strict+ | 1 |
Ruby | Ruby | run relocation machinery on local bottles | 0daa33668b66a4c2a9dfee554845ce58f6a3475a | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def fix_install_names
<ide> keg = Keg.new(f.prefix)
<ide> keg.fix_install_names(:keg_only => f.keg_only?)
<ide>
<del> if @poured_bottle and f.bottle
<add> if @poured_bottle
<ide> keg.relocate_install_names Keg::PREFIX_PLACEHOLDER, HOMEBREW_PREFIX.to_s,
<ide> Keg::CELLAR_PLACEHOLDER, HOMEBREW_CELLAR.to_s, :keg_only => f.keg_only?
<ide> end | 1 |
PHP | PHP | fix invalid function calls | c1f48eca0947d81ae0a351c7680767a8a8bb5045 | <ide><path>src/Database/Schema/CachedCollection.php
<ide> public function __construct(CollectionInterface $collection, string $prefix, Cac
<ide> $this->cacher = $cacher;
<ide> }
<ide>
<del> /**
<del> * @inheritDoc
<del> */
<del> public function listTablesAndViews(): array
<del> {
<del> return $this->collection->listTablesAndViews();
<del> }
<del>
<ide> /**
<ide> * @inheritDoc
<ide> */
<ide> public function listTablesWithoutViews(): array
<ide> */
<ide> public function listTables(): array
<ide> {
<del> return $this->collection->listTablesAndViews();
<add> return $this->collection->listTables();
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | push trunk to 0.4.3-dev | 3865d8a168365847e28cb7a1cb5e0f2bfa6b3863 | <ide><path>libcloud/__init__.py
<ide>
<ide> __all__ = ["__version__", "enable_debug"]
<ide>
<del>__version__ = "0.4.2"
<add>__version__ = "0.4.3-dev"
<ide>
<ide>
<ide> def enable_debug(fo):
<ide><path>setup.py
<ide> def run(self):
<ide>
<ide> setup(
<ide> name='apache-libcloud',
<del> version='0.4.2',
<add> version='0.4.3',
<ide> description='A unified interface into many cloud server providers',
<ide> author='Apache Software Foundation',
<ide> author_email='[email protected]', | 2 |
Text | Text | add a chinese translation to pythonzen | e2fa3aeb6126b5427ac70d6117ac02c555c9089a | <ide><path>guide/chinese/python/index.md
<ide> $ python3.5
<ide> If the implementation is hard to explain, it's a bad idea.
<ide> If the implementation is easy to explain, it may be a good idea.
<ide> Namespaces are one honking great idea -- let's do more of those!
<add>
<add> 优美胜于丑陋,显明胜于隐含。
<add> 简单胜于复杂,复杂胜于繁复。
<add> 扁平胜于嵌套,稀疏胜于密集。
<add> 可读性会起作用。
<add> 即使要为了实用性而牺牲纯粹性,
<add> 特例也并不特殊到足以破坏常规。
<add> 除非你想明白无误地保持沉默,
<add> 否则就永远不要悄悄放过错误。
<add> 面对模棱两可,
<add> 拒绝猜的诱惑。
<add> 做任何事情总该有一个,
<add> 而且最好只有一个明显的方式,
<add> 尽管那种方式起初并不见得明显,
<add> 但是谁叫你不是荷兰人[1]。
<add> 虽然一直不做经常要好过匆忙去做,
<add> 但是现在就做还是要好过一直不做。
<add> 如果实现方法很难以解释,那一定是个坏主意;
<add> 如果实现方法很容易解释,那也许是个好注意。
<add> 名字空间就是一个呱呱叫的好主意。
<add> 现在就让我们多多动手体验这些吧。
<add>
<add> [1]python发明人Guido van Rossum是荷兰人。
<ide> ```
<ide>
<ide> ## Python的优点和缺点 | 1 |
Ruby | Ruby | move cdf to the boneyard | 649579072ca7a0f5fe2576f78499a7a35597161f | <ide><path>Library/Homebrew/tap_migrations.rb
<ide> "cantera" => "homebrew/science",
<ide> "cardpeek" => "homebrew/x11",
<ide> "catdoc" => "homebrew/boneyard",
<add> "cdf" => "homebrew/boneyard",
<ide> "clam" => "homebrew/boneyard",
<ide> "cloudfoundry-cli" => "pivotal/tap",
<ide> "clusterit" => "homebrew/x11", | 1 |
Python | Python | add general attention classes | 15a2fc88a68741163cc9b798921e6b33ef32528a | <ide><path>transformers/modeling_bert.py
<ide> def forward(self, input_ids, token_type_ids=None, position_ids=None):
<ide> return embeddings
<ide>
<ide>
<del>class BertSelfAttention(nn.Module):
<add>class BertGeneralAttention(nn.Module):
<ide> def __init__(self, config):
<del> super(BertSelfAttention, self).__init__()
<add> super(BertGeneralAttention, self).__init__()
<ide> if config.hidden_size % config.num_attention_heads != 0:
<ide> raise ValueError(
<ide> "The hidden size (%d) is not a multiple of the number of attention "
<ide> def forward(self, query, key, value, attention_mask=None, head_mask=None):
<ide> return outputs
<ide>
<ide>
<add>class BertSelfAttention(nn.Module):
<add> def __init__(self, config):
<add> super(BertSelfAttention, self).__init__()
<add> if config.hidden_size % config.num_attention_heads != 0:
<add> raise ValueError(
<add> "The hidden size (%d) is not a multiple of the number of attention "
<add> "heads (%d)" % (config.hidden_size, config.num_attention_heads))
<add> self.output_attentions = config.output_attentions
<add>
<add> self.num_attention_heads = config.num_attention_heads
<add> self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
<add> self.all_head_size = self.num_attention_heads * self.attention_head_size
<add>
<add> self.query = nn.Linear(config.hidden_size, self.all_head_size)
<add> self.key = nn.Linear(config.hidden_size, self.all_head_size)
<add> self.value = nn.Linear(config.hidden_size, self.all_head_size)
<add>
<add> self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
<add>
<add> def transpose_for_scores(self, x):
<add> new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
<add> x = x.view(*new_x_shape)
<add> return x.permute(0, 2, 1, 3)
<add>
<add> def forward(self, hidden_states, attention_mask=None, head_mask=None):
<add> mixed_query_layer = self.query(hidden_states)
<add> mixed_key_layer = self.key(hidden_states)
<add> mixed_value_layer = self.value(hidden_states)
<add>
<add> query_layer = self.transpose_for_scores(mixed_query_layer)
<add> key_layer = self.transpose_for_scores(mixed_key_layer)
<add> value_layer = self.transpose_for_scores(mixed_value_layer)
<add>
<add> # Take the dot product between "query" and "key" to get the raw attention scores.
<add> attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
<add> attention_scores = attention_scores / math.sqrt(self.attention_head_size)
<add> if attention_mask is not None:
<add> # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
<add> attention_scores = attention_scores + attention_mask
<add>
<add> # Normalize the attention scores to probabilities.
<add> attention_probs = nn.Softmax(dim=-1)(attention_scores)
<add>
<add> # This is actually dropping out entire tokens to attend to, which might
<add> # seem a bit unusual, but is taken from the original Transformer paper.
<add> attention_probs = self.dropout(attention_probs)
<add>
<add> # Mask heads if we want to
<add> if head_mask is not None:
<add> attention_probs = attention_probs * head_mask
<add>
<add> context_layer = torch.matmul(attention_probs, value_layer)
<add>
<add> context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
<add> new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
<add> context_layer = context_layer.view(*new_context_layer_shape)
<add>
<add> outputs = (context_layer, attention_probs) if self.output_attentions else (context_layer,)
<add> return outputs
<add>
<add>
<ide> class BertSelfOutput(nn.Module):
<ide> def __init__(self, config):
<ide> super(BertSelfOutput, self).__init__()
<ide> def prune_heads(self, heads):
<ide> self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
<ide> self.pruned_heads = self.pruned_heads.union(heads)
<ide>
<del> def forward(self, query_tensor, key_tensor, value_tensor, attention_mask=None, head_mask=None):
<del> self_outputs = self.self(query_tensor, key_tensor, value_tensor, attention_mask, head_mask)
<add> def forward(self, hidden_states, attention_mask=None, head_mask=None):
<add> self_outputs = self.self(hidden_states, attention_mask, head_mask)
<add> attention_output = self.output(self_outputs[0], hidden_states)
<add> outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
<add> return outputs
<add>
<add>
<add>class BertDecoderAttention(nn.Module):
<add> def __init__(self, config):
<add> super(BertAttention, self).__init__()
<add> self.self = BertGeneralAttention(config)
<add> self.output = BertSelfOutput(config)
<add> self.pruned_heads = set()
<add>
<add> def prune_heads(self, heads):
<add> if len(heads) == 0:
<add> return
<add> mask = torch.ones(self.self.num_attention_heads, self.self.attention_head_size)
<add> heads = set(heads) - self.pruned_heads # Convert to set and emove already pruned heads
<add> for head in heads:
<add> # Compute how many pruned heads are before the head and move the index accordingly
<add> head = head - sum(1 if h < head else 0 for h in self.pruned_heads)
<add> mask[head] = 0
<add> mask = mask.view(-1).contiguous().eq(1)
<add> index = torch.arange(len(mask))[mask].long()
<add>
<add> # Prune linear layers
<add> self.self.query = prune_linear_layer(self.self.query, index)
<add> self.self.key = prune_linear_layer(self.self.key, index)
<add> self.self.value = prune_linear_layer(self.self.value, index)
<add> self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
<add>
<add> # Update hyper params and store pruned heads
<add> self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
<add> self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
<add> self.pruned_heads = self.pruned_heads.union(heads)
<add>
<add> def forward(self, query, key, value, attention_mask=None, head_mask=None):
<add> self_outputs = self.self(query, key, value, attention_mask, head_mask)
<ide> # in encoder-decoder attention we use the output of the previous decoder stage as the query
<ide> # in the Multi-Head Attention. We thus pass query_tensor as the residual in BertOutput.
<ide> # This shows the limits of the current code architecture, which may benefit from some refactoring.
<del> attention_output = self.output(self_outputs[0], query_tensor)
<add> attention_output = self.output(self_outputs[0], query)
<ide> outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
<ide> return outputs
<ide>
<ide> def __init__(self, config):
<ide> self.output = BertOutput(config)
<ide>
<ide> def forward(self, hidden_states, attention_mask=None, head_mask=None):
<del> attention_outputs = self.attention(query_tensor=hidden_states,
<del> key_tensor=hidden_states,
<del> value_tensor=hidden_states,
<del> attention_mask=attention_mask,
<del> head_mask=head_mask)
<add> attention_outputs = self.attention(hidden_states, attention_mask, head_mask)
<ide> attention_output = attention_outputs[0]
<ide> intermediate_output = self.intermediate(attention_output)
<ide> layer_output = self.output(intermediate_output, attention_output)
<ide> class BertDecoderLayer(nn.Module):
<ide> def __init__(self, config):
<ide> super(BertDecoderLayer, self).__init__()
<ide> self.self_attention = BertAttention(config)
<del> self.attention = BertAttention(config)
<add> self.attention = BertDecoderAttention(config)
<ide> self.intermediate = BertIntermediate(config)
<ide> self.output = BertOutput(config)
<ide>
<ide> def forward(self, hidden_states, encoder_outputs, attention_mask=None, head_mask=None):
<del> self_attention_outputs = self.self_attention(query_tensor=hidden_states,
<del> key_tensor=hidden_states,
<del> value_tensor=hidden_states,
<del> attention_mask=attention_mask,
<del> head_mask=head_mask)
<add> self_attention_outputs = self.self_attention(hidden_states, attention_mask, head_mask)
<ide> self_attention_output = self_attention_outputs[0]
<del> attention_outputs = self.attention(query_tensor=self_attention_output,
<del> key_tensor=encoder_outputs,
<del> value_tensor=encoder_outputs,
<add> attention_outputs = self.attention(query=self_attention_output,
<add> key=encoder_outputs,
<add> value=encoder_outputs,
<ide> attention_mask=attention_mask,
<ide> head_mask=head_mask)
<ide> attention_output = attention_outputs[0]
<ide> def forward(self, hidden_states, attention_mask=None, head_mask=None):
<ide>
<ide> class BertDecoder(nn.Module):
<ide> def __init__(self, config):
<del> raise NotImplementedError
<add> super(BertDecoder, self).__init__()
<add> self.output_attentions = config.output_attentions
<add> self.output_hidden_states = config.output_hidden_states
<add> self.layers = nn.ModuleList([BertEncoderLayer(config) for _ in range(config.num_hidden_layers)])
<add>
<add> def forward(self, hidden_states, encoder_outputs, attention_mask=None, head_mask=None):
<add> all_hidden_states = ()
<add> all_attentions = ()
<add> for i, layer_module in enumerate(self.layer):
<add> if self.output_hidden_states:
<add> all_hidden_states = all_hidden_states + (hidden_states,)
<add>
<add> layer_outputs = layer_module(hidden_states, attention_mask, head_mask[i])
<add> if self.output_attentions:
<add> all_attentions = all_attentions + (layer_outputs[1],)
<add>
<add> hidden_states = layer_outputs[0]
<ide>
<del> def forward(self, encoder_output):
<del> raise NotImplementedError
<add> # Add last layer
<add> if self.output_hidden_states:
<add> all_hidden_states = all_hidden_states + (hidden_states,)
<add>
<add> outputs = (hidden_states,)
<add> if self.output_hidden_states:
<add> outputs = outputs + (all_hidden_states,)
<add> if self.output_attentions:
<add> outputs = outputs + (all_attentions,)
<add> return outputs # last-layer hidden state, (all hidden states), (all attentions)
<ide>
<ide>
<ide> class BertPooler(nn.Module): | 1 |
PHP | PHP | update helper usage to 2.x style in code examples | db8127626a912fd3a2167d766d6bd107c485af59 | <ide><path>lib/Cake/View/Helper/HtmlHelper.php
<ide> public function script($url, $options = array()) {
<ide> public function scriptBlock($script, $options = array()) {
<ide> $options += array('safe' => true, 'inline' => true);
<ide> if ($options['safe']) {
<del> $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
<add> $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
<ide> }
<ide> if (!$options['inline'] && empty($options['block'])) {
<ide> $options['block'] = 'script';
<ide> public function scriptEnd() {
<ide> * ### Usage:
<ide> *
<ide> * {{{
<del> * echo $html->style(array('margin' => '10px', 'padding' => '10px'), true);
<add> * echo $this->Html->style(array('margin' => '10px', 'padding' => '10px'), true);
<ide> *
<ide> * // creates
<ide> * 'margin:10px;padding:10px;'
<ide> protected function _prepareCrumbs($startText) {
<ide> *
<ide> * Create a regular image:
<ide> *
<del> * `echo $html->image('cake_icon.png', array('alt' => 'CakePHP'));`
<add> * `echo $this->Html->image('cake_icon.png', array('alt' => 'CakePHP'));`
<ide> *
<ide> * Create an image link:
<ide> *
<del> * `echo $html->image('cake_icon.png', array('alt' => 'CakePHP', 'url' => 'http://cakephp.org'));`
<add> * `echo $this->Html->image('cake_icon.png', array('alt' => 'CakePHP', 'url' => 'http://cakephp.org'));`
<ide> *
<ide> * ### Options:
<ide> * | 1 |
Python | Python | stop recursion after 5000 nodes | 16bcb47a6557baaae8106569712d6603941c6d03 | <ide><path>airflow/www/app.py
<ide> def tree(self):
<ide> for ti in dag.get_task_instances(session, from_date):
<ide> task_instances[(ti.task_id, ti.execution_date)] = ti
<ide>
<del> # if force_expand is passed True, then no timeout is applied
<del> # when computing all possible paths through the graph.
<del> # Otherwise the graph will revert to a quick calculation if it hasn't
<del> # completed after `timeout_seconds`
<del> timeout_seconds = None if request.args.get('force_expand') else 1
<del>
<del> def recurse_nodes(t):
<del> start_time = time.time()
<del> expanded = []
<del>
<del> def recurse_nodes_inner(task, visited, force_expand):
<del> elapsed = time.time() - start_time
<del> if timeout_seconds and elapsed > timeout_seconds:
<del> raise ValueError('Recursion timeout')
<del>
<del> if not force_expand:
<del> visited.add(task)
<del>
<del> children = [
<del> recurse_nodes_inner(t, visited, force_expand)
<del> for t in task.upstream_list if t not in visited]
<del>
<del> # D3 tree uses children vs _children to define what is
<del> # expanded or not. The following block makes it such that
<del> # repeated nodes are collapsed by default.
<del> children_key = 'children'
<del> if task.task_id not in expanded:
<del> expanded.append(task.task_id)
<del> elif children:
<del> children_key = "_children"
<del>
<del> return {
<del> 'name': task.task_id,
<del> 'instances': [
<del> utils.alchemy_to_dict(
<del> task_instances.get((task.task_id, d))) or {
<del> 'execution_date': d.isoformat(),
<del> 'task_id': task.task_id
<del> }
<del> for d in dates],
<del> children_key: children,
<del> 'num_dep': len(task.upstream_list),
<del> 'operator': task.task_type,
<del> 'retries': task.retries,
<del> 'owner': task.owner,
<del> 'start_date': task.start_date,
<del> 'end_date': task.end_date,
<del> 'depends_on_past': task.depends_on_past,
<del> 'ui_color': task.ui_color,
<del> }
<del>
<del> # try the expensive operation by recursing with force_expand=True
<del> # if timeout_seconds elapse, a ValueError is raised
<del> try:
<del> return recurse_nodes_inner(
<del> t, visited=set(), force_expand=True)
<del> except ValueError:
<del> # start over with a quick calculation
<del> logging.debug(
<del> 'Tree creation timed out; falling back on quick method.')
<del> expanded = []
<del> start_time = time.time()
<del> return recurse_nodes_inner(t, visited=set(), force_expand=False)
<add> expanded = []
<add>
<add> # The default recursion traces every path so that tree view has full
<add> # expand/collapse functionality. After 5,000 nodes we stop and fall
<add> # back on a quick DFS search for performance. See PR #320.
<add> node_count = [0]
<add> node_limit = 5000 / len(dag.roots)
<add>
<add> def recurse_nodes(task, visited):
<add> visited.add(task)
<add> node_count[0] += 1
<add>
<add> children = [
<add> recurse_nodes(t, visited) for t in task.upstream_list
<add> if node_count[0] < node_limit or t not in visited]
<add>
<add> # D3 tree uses children vs _children to define what is
<add> # expanded or not. The following block makes it such that
<add> # repeated nodes are collapsed by default.
<add> children_key = 'children'
<add> if task.task_id not in expanded:
<add> expanded.append(task.task_id)
<add> elif children:
<add> children_key = "_children"
<add>
<add> return {
<add> 'name': task.task_id,
<add> 'instances': [
<add> utils.alchemy_to_dict(
<add> task_instances.get((task.task_id, d))) or {
<add> 'execution_date': d.isoformat(),
<add> 'task_id': task.task_id
<add> }
<add> for d in dates],
<add> children_key: children,
<add> 'num_dep': len(task.upstream_list),
<add> 'operator': task.task_type,
<add> 'retries': task.retries,
<add> 'owner': task.owner,
<add> 'start_date': task.start_date,
<add> 'end_date': task.end_date,
<add> 'depends_on_past': task.depends_on_past,
<add> 'ui_color': task.ui_color,
<add> }
<ide>
<ide> if len(dag.roots) > 1:
<ide> # d3 likes a single root
<ide> data = {
<ide> 'name': 'root',
<ide> 'instances': [],
<del> 'children': [recurse_nodes(t) for t in dag.roots]
<add> 'children': [recurse_nodes(t, set()) for t in dag.roots]
<ide> }
<ide> elif len(dag.roots) == 1:
<del> data = recurse_nodes(dag.roots[0])
<add> data = recurse_nodes(dag.roots[0], set())
<ide> else:
<ide> flash("No tasks found.", "error")
<ide> data = [] | 1 |
Javascript | Javascript | fix bug, not calling animationaction.init | a1fb6c3134d6dd68035aecab72bfaf58ff3a3c20 | <ide><path>src/animation/AnimationMixer.js
<ide> THREE.AnimationMixer.prototype = {
<ide> // TODO: check for duplicate action names? Or provide each action with a UUID?
<ide>
<ide> this.actions.push( action );
<add> action.init( this.time );
<ide> action.mixer = this;
<ide>
<ide> var tracks = action.clip.tracks; | 1 |
Javascript | Javascript | convert all zone tests to utc offset | 4256ce79bacdf6bd53f0860fdbbc70b825b6a057 | <ide><path>test/moment/utc_offset.js
<ide> exports.offset = {
<ide> test.done();
<ide> },
<ide>
<add> 'utcOffset shorthand hours -> minutes' : function (test) {
<add> var i;
<add> for (i = -15; i <= 15; ++i) {
<add> test.equal(moment().utcOffset(i).utcOffset(), i * 60,
<add> '' + i + ' -> ' + i * 60);
<add> }
<add> test.equal(moment().utcOffset(-16).utcOffset(), -16, '-16 -> -16');
<add> test.equal(moment().utcOffset(16).utcOffset(), 16, '16 -> 16');
<add>
<add> test.done();
<add> },
<add>
<ide> 'isLocal, isUtc, isUtcOffset' : function (test) {
<ide> test.ok(moment().isLocal(), 'moment() creates objects in local time');
<ide> test.ok(!moment.utc().isLocal(), 'moment.utc creates objects NOT in local time');
<ide> exports.offset = {
<ide> test.ok(moment().utcOffset(0).isUTC(), 'utcOffset(0) is equivalent to utc mode');
<ide> test.ok(!moment().utcOffset(1).isUTC(), 'utcOffset(1) is NOT equivalent to utc mode');
<ide>
<add> test.done();
<add> },
<add>
<add> 'change hours when changing the utc offset' : function (test) {
<add> var m = moment.utc([2000, 0, 1, 6]);
<add> test.equal(m.hour(), 6, 'UTC 6AM should be 6AM at +0000');
<add>
<add> // sanity check
<add> m.utcOffset(0);
<add> test.equal(m.hour(), 6, 'UTC 6AM should be 6AM at +0000');
<add>
<add> m.utcOffset(-60);
<add> test.equal(m.hour(), 5, 'UTC 6AM should be 5AM at -0100');
<add>
<add> m.utcOffset(60);
<add> test.equal(m.hour(), 7, 'UTC 6AM should be 7AM at +0100');
<add>
<add> test.done();
<add> },
<add>
<add> 'change minutes when changing the utc offset' : function (test) {
<add> var m = moment.utc([2000, 0, 1, 6, 31]);
<add>
<add> m.utcOffset(0);
<add> test.equal(m.format('HH:mm'), '06:31', 'UTC 6:31AM should be 6:31AM at +0000');
<add>
<add> m.utcOffset(-30);
<add> test.equal(m.format('HH:mm'), '06:01', 'UTC 6:31AM should be 6:01AM at -0030');
<add>
<add> m.utcOffset(30);
<add> test.equal(m.format('HH:mm'), '07:01', 'UTC 6:31AM should be 7:01AM at +0030');
<add>
<add> m.utcOffset(-1380);
<add> test.equal(m.format('HH:mm'), '07:31', 'UTC 6:31AM should be 7:31AM at +1380');
<add>
<add> test.done();
<add> },
<add>
<add> 'distance from the unix epoch' : function (test) {
<add> var zoneA = moment(),
<add> zoneB = moment(zoneA),
<add> zoneC = moment(zoneA),
<add> zoneD = moment(zoneA),
<add> zoneE = moment(zoneA);
<add>
<add> zoneB.utc();
<add> test.equal(+zoneA, +zoneB, 'moment should equal moment.utc');
<add>
<add> zoneC.utcOffset(60);
<add> test.equal(+zoneA, +zoneC, 'moment should equal moment.utcOffset(60)');
<add>
<add> zoneD.utcOffset(-480);
<add> test.equal(+zoneA, +zoneD,
<add> 'moment should equal moment.utcOffset(-480)');
<add>
<add> zoneE.utcOffset(-1000);
<add> test.equal(+zoneA, +zoneE,
<add> 'moment should equal moment.utcOffset(-1000)');
<add>
<add> test.done();
<add> },
<add>
<add> 'update offset after changing any values' : function (test) {
<add> var oldOffset = moment.updateOffset,
<add> m = moment.utc([2000, 6, 1]);
<add>
<add> moment.updateOffset = function (mom, keepTime) {
<add> if (mom.__doChange) {
<add> if (+mom > 962409600000) {
<add> mom.utcOffset(-120, keepTime);
<add> } else {
<add> mom.utcOffset(-60, keepTime);
<add> }
<add> }
<add> };
<add>
<add> test.equal(m.format('ZZ'), '+0000', 'should be at +0000');
<add> test.equal(m.format('HH:mm'), '00:00', 'should start 12AM at +0000 timezone');
<add>
<add> m.__doChange = true;
<add> m.add(1, 'h');
<add>
<add> test.equal(m.format('ZZ'), '-0200', 'should be at -0200');
<add> test.equal(m.format('HH:mm'), '23:00', '1AM at +0000 should be 11PM at -0200 timezone');
<add>
<add> m.subtract(1, 'h');
<add>
<add> test.equal(m.format('ZZ'), '-0100', 'should be at -0100');
<add> test.equal(m.format('HH:mm'), '23:00', '12AM at +0000 should be 11PM at -0100 timezone');
<add>
<add> moment.updateOffset = oldOffset;
<add>
<add> test.done();
<add> },
<add>
<add> //////////////////
<add> 'getters and setters' : function (test) {
<add> var a = moment([2011, 5, 20]);
<add>
<add> test.equal(a.clone().utcOffset(-120).year(2012).year(), 2012, 'should get and set year correctly');
<add> test.equal(a.clone().utcOffset(-120).month(1).month(), 1, 'should get and set month correctly');
<add> test.equal(a.clone().utcOffset(-120).date(2).date(), 2, 'should get and set date correctly');
<add> test.equal(a.clone().utcOffset(-120).day(1).day(), 1, 'should get and set day correctly');
<add> test.equal(a.clone().utcOffset(-120).hour(1).hour(), 1, 'should get and set hour correctly');
<add> test.equal(a.clone().utcOffset(-120).minute(1).minute(), 1, 'should get and set minute correctly');
<add>
<add> test.done();
<add> },
<add>
<add> 'getters' : function (test) {
<add> var a = moment.utc([2012, 0, 1, 0, 0, 0]);
<add>
<add> test.equal(a.clone().utcOffset(-120).year(), 2011, 'should get year correctly');
<add> test.equal(a.clone().utcOffset(-120).month(), 11, 'should get month correctly');
<add> test.equal(a.clone().utcOffset(-120).date(), 31, 'should get date correctly');
<add> test.equal(a.clone().utcOffset(-120).hour(), 22, 'should get hour correctly');
<add> test.equal(a.clone().utcOffset(-120).minute(), 0, 'should get minute correctly');
<add>
<add> test.equal(a.clone().utcOffset(120).year(), 2012, 'should get year correctly');
<add> test.equal(a.clone().utcOffset(120).month(), 0, 'should get month correctly');
<add> test.equal(a.clone().utcOffset(120).date(), 1, 'should get date correctly');
<add> test.equal(a.clone().utcOffset(120).hour(), 2, 'should get hour correctly');
<add> test.equal(a.clone().utcOffset(120).minute(), 0, 'should get minute correctly');
<add>
<add> test.equal(a.clone().utcOffset(90).year(), 2012, 'should get year correctly');
<add> test.equal(a.clone().utcOffset(90).month(), 0, 'should get month correctly');
<add> test.equal(a.clone().utcOffset(90).date(), 1, 'should get date correctly');
<add> test.equal(a.clone().utcOffset(90).hour(), 1, 'should get hour correctly');
<add> test.equal(a.clone().utcOffset(90).minute(), 30, 'should get minute correctly');
<add>
<add> test.done();
<add> },
<add>
<add> 'from' : function (test) {
<add> var zoneA = moment(),
<add> zoneB = moment(zoneA).utcOffset(-720),
<add> zoneC = moment(zoneA).utcOffset(-360),
<add> zoneD = moment(zoneA).utcOffset(690),
<add> other = moment(zoneA).add(35, 'm');
<add>
<add> test.equal(zoneA.from(other), zoneB.from(other), 'moment#from should be the same in all zones');
<add> test.equal(zoneA.from(other), zoneC.from(other), 'moment#from should be the same in all zones');
<add> test.equal(zoneA.from(other), zoneD.from(other), 'moment#from should be the same in all zones');
<add>
<add> test.done();
<add> },
<add>
<add> 'diff' : function (test) {
<add> var zoneA = moment(),
<add> zoneB = moment(zoneA).utcOffset(-720),
<add> zoneC = moment(zoneA).utcOffset(-360),
<add> zoneD = moment(zoneA).utcOffset(690),
<add> other = moment(zoneA).add(35, 'm');
<add>
<add> test.equal(zoneA.diff(other), zoneB.diff(other), 'moment#diff should be the same in all zones');
<add> test.equal(zoneA.diff(other), zoneC.diff(other), 'moment#diff should be the same in all zones');
<add> test.equal(zoneA.diff(other), zoneD.diff(other), 'moment#diff should be the same in all zones');
<add>
<add> test.equal(zoneA.diff(other, 'minute', true), zoneB.diff(other, 'minute', true), 'moment#diff should be the same in all zones');
<add> test.equal(zoneA.diff(other, 'minute', true), zoneC.diff(other, 'minute', true), 'moment#diff should be the same in all zones');
<add> test.equal(zoneA.diff(other, 'minute', true), zoneD.diff(other, 'minute', true), 'moment#diff should be the same in all zones');
<add>
<add> test.equal(zoneA.diff(other, 'hour', true), zoneB.diff(other, 'hour', true), 'moment#diff should be the same in all zones');
<add> test.equal(zoneA.diff(other, 'hour', true), zoneC.diff(other, 'hour', true), 'moment#diff should be the same in all zones');
<add> test.equal(zoneA.diff(other, 'hour', true), zoneD.diff(other, 'hour', true), 'moment#diff should be the same in all zones');
<add>
<add> test.done();
<add> },
<add>
<add> 'unix offset and timestamp' : function (test) {
<add> var zoneA = moment(),
<add> zoneB = moment(zoneA).utcOffset(-720),
<add> zoneC = moment(zoneA).utcOffset(-360),
<add> zoneD = moment(zoneA).utcOffset(690);
<add>
<add> test.equal(zoneA.unix(), zoneB.unix(), 'moment#unix should be the same in all zones');
<add> test.equal(zoneA.unix(), zoneC.unix(), 'moment#unix should be the same in all zones');
<add> test.equal(zoneA.unix(), zoneD.unix(), 'moment#unix should be the same in all zones');
<add>
<add> test.equal(+zoneA, +zoneB, 'moment#valueOf should be the same in all zones');
<add> test.equal(+zoneA, +zoneC, 'moment#valueOf should be the same in all zones');
<add> test.equal(+zoneA, +zoneD, 'moment#valueOf should be the same in all zones');
<add>
<add> test.done();
<add> },
<add>
<add> 'cloning' : function (test) {
<add> test.equal(moment().utcOffset(-120).clone().utcOffset(), -120,
<add> 'explicit cloning should retain the offset');
<add> test.equal(moment().utcOffset(120).clone().utcOffset(), 120,
<add> 'explicit cloning should retain the offset');
<add> test.equal(moment(moment().utcOffset(-120)).utcOffset(), -120,
<add> 'implicit cloning should retain the offset');
<add> test.equal(moment(moment().utcOffset(120)).utcOffset(), 120,
<add> 'implicit cloning should retain the offset');
<add>
<add> test.done();
<add> },
<add>
<add> 'start of / end of' : function (test) {
<add> var a = moment.utc([2010, 1, 2, 0, 0, 0]).utcOffset(-450);
<add>
<add> test.equal(a.clone().startOf('day').hour(), 0,
<add> 'start of day should work on moments with utc offset');
<add> test.equal(a.clone().startOf('day').minute(), 0,
<add> 'start of day should work on moments with utc offset');
<add> test.equal(a.clone().startOf('hour').minute(), 0,
<add> 'start of hour should work on moments with utc offset');
<add>
<add> test.equal(a.clone().endOf('day').hour(), 23,
<add> 'end of day should work on moments with utc offset');
<add> test.equal(a.clone().endOf('day').minute(), 59,
<add> 'end of day should work on moments with utc offset');
<add> test.equal(a.clone().endOf('hour').minute(), 59,
<add> 'end of hour should work on moments with utc offset');
<add>
<add> test.done();
<add> },
<add>
<add> 'reset offset with moment#utc' : function (test) {
<add> var a = moment.utc([2012]).utcOffset(-480);
<add>
<add> test.equal(a.clone().hour(), 16, 'different utc offset should have different hour');
<add> test.equal(a.clone().utc().hour(), 0, 'calling moment#utc should reset the offset');
<add>
<add> test.done();
<add> },
<add>
<add> 'reset offset with moment#local' : function (test) {
<add> var a = moment([2012]).utcOffset(-480);
<add>
<add> test.equal(a.clone().local().hour(), 0, 'calling moment#local should reset the offset');
<add>
<add> test.done();
<add> },
<add>
<add> 'toDate' : function (test) {
<add> var zoneA = new Date(),
<add> zoneB = moment(zoneA).utcOffset(-720).toDate(),
<add> zoneC = moment(zoneA).utcOffset(-360).toDate(),
<add> zoneD = moment(zoneA).utcOffset(690).toDate();
<add>
<add> test.equal(+zoneA, +zoneB, 'moment#toDate should output a date with the right unix timestamp');
<add> test.equal(+zoneA, +zoneC, 'moment#toDate should output a date with the right unix timestamp');
<add> test.equal(+zoneA, +zoneD, 'moment#toDate should output a date with the right unix timestamp');
<add>
<add> test.done();
<add> },
<add>
<add> 'same / before / after' : function (test) {
<add> var zoneA = moment().utc(),
<add> zoneB = moment(zoneA).utcOffset(-120),
<add> zoneC = moment(zoneA).utcOffset(120);
<add>
<add> test.ok(zoneA.isSame(zoneB), 'two moments with different offsets should be the same');
<add> test.ok(zoneA.isSame(zoneC), 'two moments with different offsets should be the same');
<add>
<add> test.ok(zoneA.isSame(zoneB, 'hour'), 'two moments with different offsets should be the same hour');
<add> test.ok(zoneA.isSame(zoneC, 'hour'), 'two moments with different offsets should be the same hour');
<add>
<add> zoneA.add(1, 'hour');
<add>
<add> test.ok(zoneA.isAfter(zoneB), 'isAfter should work with two moments with different offsets');
<add> test.ok(zoneA.isAfter(zoneC), 'isAfter should work with two moments with different offsets');
<add>
<add> test.ok(zoneA.isAfter(zoneB, 'hour'), 'isAfter:hour should work with two moments with different offsets');
<add> test.ok(zoneA.isAfter(zoneC, 'hour'), 'isAfter:hour should work with two moments with different offsets');
<add>
<add> zoneA.subtract(2, 'hour');
<add>
<add> test.ok(zoneA.isBefore(zoneB), 'isBefore should work with two moments with different offsets');
<add> test.ok(zoneA.isBefore(zoneC), 'isBefore should work with two moments with different offsets');
<add>
<add> test.ok(zoneA.isBefore(zoneB, 'hour'), 'isBefore:hour should work with two moments with different offsets');
<add> test.ok(zoneA.isBefore(zoneC, 'hour'), 'isBefore:hour should work with two moments with different offsets');
<add>
<add> test.done();
<add> },
<add>
<add> 'add / subtract over dst' : function (test) {
<add> var oldOffset = moment.updateOffset,
<add> m = moment.utc([2000, 2, 31, 3]);
<add>
<add> moment.updateOffset = function (mom, keepTime) {
<add> if (mom.clone().utc().month() > 2) {
<add> mom.utcOffset(60, keepTime);
<add> } else {
<add> mom.utcOffset(0, keepTime);
<add> }
<add> };
<add>
<add> test.equal(m.hour(), 3, 'should start at 00:00');
<add>
<add> m.add(24, 'hour');
<add>
<add> test.equal(m.hour(), 4, 'adding 24 hours should disregard dst');
<add>
<add> m.subtract(24, 'hour');
<add>
<add> test.equal(m.hour(), 3, 'subtracting 24 hours should disregard dst');
<add>
<add> m.add(1, 'day');
<add>
<add> test.equal(m.hour(), 3, 'adding 1 day should have the same hour');
<add>
<add> m.subtract(1, 'day');
<add>
<add> test.equal(m.hour(), 3, 'subtracting 1 day should have the same hour');
<add>
<add> m.add(1, 'month');
<add>
<add> test.equal(m.hour(), 3, 'adding 1 month should have the same hour');
<add>
<add> m.subtract(1, 'month');
<add>
<add> test.equal(m.hour(), 3, 'subtracting 1 month should have the same hour');
<add>
<add> moment.updateOffset = oldOffset;
<add>
<add> test.done();
<add> },
<add>
<add> 'isDST' : function (test) {
<add> var oldOffset = moment.updateOffset;
<add>
<add> moment.updateOffset = function (mom, keepTime) {
<add> if (mom.month() > 2 && mom.month() < 9) {
<add> mom.utcOffset(60, keepTime);
<add> } else {
<add> mom.utcOffset(0, keepTime);
<add> }
<add> };
<add>
<add> test.ok(!moment().month(0).isDST(), 'Jan should not be summer dst');
<add> test.ok(moment().month(6).isDST(), 'Jul should be summer dst');
<add> test.ok(!moment().month(11).isDST(), 'Dec should not be summer dst');
<add>
<add> moment.updateOffset = function (mom) {
<add> if (mom.month() > 2 && mom.month() < 9) {
<add> mom.utcOffset(0);
<add> } else {
<add> mom.utcOffset(60);
<add> }
<add> };
<add>
<add> test.ok(moment().month(0).isDST(), 'Jan should be winter dst');
<add> test.ok(!moment().month(6).isDST(), 'Jul should not be winter dst');
<add> test.ok(moment().month(11).isDST(), 'Dec should be winter dst');
<add>
<add> moment.updateOffset = oldOffset;
<add>
<add> test.done();
<add> },
<add>
<add> 'zone names' : function (test) {
<add> test.expect(8);
<add>
<add> test.equal(moment().zoneAbbr(), '', 'Local zone abbr should be empty');
<add> test.equal(moment().format('z'), '', 'Local zone formatted abbr should be empty');
<add> test.equal(moment().zoneName(), '', 'Local zone name should be empty');
<add> test.equal(moment().format('zz'), '', 'Local zone formatted name should be empty');
<add>
<add> test.equal(moment.utc().zoneAbbr(), 'UTC', 'UTC zone abbr should be UTC');
<add> test.equal(moment.utc().format('z'), 'UTC', 'UTC zone formatted abbr should be UTC');
<add> test.equal(moment.utc().zoneName(), 'Coordinated Universal Time', 'UTC zone abbr should be Coordinated Universal Time');
<add> test.equal(moment.utc().format('zz'), 'Coordinated Universal Time', 'UTC zone formatted abbr should be Coordinated Universal Time');
<add>
<add> test.done();
<add> },
<add>
<add> 'hours alignment with UTC' : function (test) {
<add> test.expect(4);
<add>
<add> test.equals(moment().utcOffset(-120).hasAlignedHourOffset(), true);
<add> test.equals(moment().utcOffset(180).hasAlignedHourOffset(), true);
<add> test.equals(moment().utcOffset(-90).hasAlignedHourOffset(), false);
<add> test.equals(moment().utcOffset(90).hasAlignedHourOffset(), false);
<add>
<add> test.done();
<add> },
<add>
<add> 'hours alignment with other zone' : function (test) {
<add> test.expect(16);
<add>
<add> var m = moment().utcOffset(-120);
<add>
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(-180)), true);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(180)), true);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(-90)), false);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(90)), false);
<add>
<add> m = moment().utcOffset(-90);
<add>
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(-180)), false);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(180)), false);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(-30)), true);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(30)), true);
<add>
<add> m = moment().utcOffset(60);
<add>
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(-180)), true);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(180)), true);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(-90)), false);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(90)), false);
<add>
<add> m = moment().utcOffset(-25);
<add>
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(35)), true);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(-85)), true);
<add>
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(-35)), false);
<add> test.equals(m.hasAlignedHourOffset(moment().utcOffset(85)), false);
<add>
<add> test.done();
<add> },
<add>
<add> 'parse zone' : function (test) {
<add> test.expect(2);
<add> var m = moment('2013-01-01T00:00:00-13:00').parseZone();
<add> test.equal(m.utcOffset(), -13 * 60);
<add> test.equal(m.hours(), 0);
<add> test.done();
<add> },
<add>
<add> 'parse zone static' : function (test) {
<add> test.expect(2);
<add> var m = moment.parseZone('2013-01-01T00:00:00-13:00');
<add> test.equal(m.utcOffset(), -13 * 60);
<add> test.equal(m.hours(), 0);
<add> test.done();
<add> },
<add>
<add> 'parse zone with more arguments' : function (test) {
<add> var m;
<add> test.expect(3);
<add>
<add> m = moment.parseZone('2013 01 01 05 -13:00', 'YYYY MM DD HH ZZ');
<add> test.equal(m.format(), '2013-01-01T05:00:00-13:00', 'accept input and format');
<add> m = moment.parseZone('2013-01-01-13:00', 'YYYY MM DD ZZ', true);
<add> test.equal(m.isValid(), false, 'accept input, format and strict flag');
<add> m = moment.parseZone('2013-01-01-13:00', ['DD MM YYYY ZZ', 'YYYY MM DD ZZ']);
<add> test.equal(m.format(), '2013-01-01T00:00:00-13:00', 'accept input and array of formats');
<add>
<add> test.done();
<add> },
<add>
<add> 'parse zone with a timezone from the format string' : function (test) {
<add> test.expect(1);
<add>
<add> var m = moment('11-12-2013 -0400 +1100', 'DD-MM-YYYY ZZ #####').parseZone();
<add>
<add> test.equal(m.utcOffset(), -4 * 60);
<add> test.done();
<add> },
<add>
<add> 'parse zone without a timezone included in the format string' : function (test) {
<add> test.expect(1);
<add>
<add> var m = moment('11-12-2013 -0400 +1100', 'DD-MM-YYYY').parseZone();
<add>
<add> test.equal(m.utcOffset(), 11 * 60);
<add> test.done();
<add> },
<add>
<add> 'timezone format' : function (test) {
<add> test.equal(moment().utcOffset(60).format('ZZ'), '+0100', '-60 -> +0100');
<add> test.equal(moment().utcOffset(90).format('ZZ'), '+0130', '-90 -> +0130');
<add> test.equal(moment().utcOffset(120).format('ZZ'), '+0200', '-120 -> +0200');
<add>
<add> test.equal(moment().utcOffset(-60).format('ZZ'), '-0100', '+60 -> -0100');
<add> test.equal(moment().utcOffset(-90).format('ZZ'), '-0130', '+90 -> -0130');
<add> test.equal(moment().utcOffset(-120).format('ZZ'), '-0200', '+120 -> -0200');
<add> test.done();
<add> },
<add>
<add> 'local to utc, keepLocalTime = true' : function (test) {
<add> var m = moment(),
<add> fmt = 'YYYY-DD-MM HH:mm:ss';
<add> test.equal(m.clone().utc(true).format(fmt), m.format(fmt), 'local to utc failed to keep local time');
<add>
<add> test.done();
<add> },
<add>
<add> 'local to utc, keepLocalTime = false' : function (test) {
<add> var m = moment();
<add> test.equal(m.clone().utc().valueOf(), m.valueOf(), 'local to utc failed to keep utc time (implicit)');
<add> test.equal(m.clone().utc(false).valueOf(), m.valueOf(), 'local to utc failed to keep utc time (explicit)');
<add>
<add> test.done();
<add> },
<add>
<add> 'local to zone, keepLocalTime = true' : function (test) {
<add> var m = moment(),
<add> fmt = 'YYYY-DD-MM HH:mm:ss',
<add> z;
<add>
<add> // Apparently there is -12:00 and +14:00
<add> // http://en.wikipedia.org/wiki/UTC+14:00
<add> // http://en.wikipedia.org/wiki/UTC-12:00
<add> for (z = -12; z <= 14; ++z) {
<add> test.equal(m.clone().utcOffset(z * 60, true).format(fmt),
<add> m.format(fmt),
<add> 'local to utcOffset(' + z + ':00) failed to keep local time');
<add> }
<add>
<add> test.done();
<add> },
<add>
<add> 'local to zone, keepLocalTime = false' : function (test) {
<add> var m = moment(),
<add> z;
<add>
<add> // Apparently there is -12:00 and +14:00
<add> // http://en.wikipedia.org/wiki/UTC+14:00
<add> // http://en.wikipedia.org/wiki/UTC-12:00
<add> for (z = -12; z <= 14; ++z) {
<add> test.equal(m.clone().utcOffset(z * 60).valueOf(),
<add> m.valueOf(),
<add> 'local to utcOffset(' + z + ':00) failed to keep utc time (implicit)');
<add> test.equal(m.clone().utcOffset(z * 60, false).valueOf(),
<add> m.valueOf(),
<add> 'local to utcOffset(' + z + ':00) failed to keep utc time (explicit)');
<add> }
<add>
<add> test.done();
<add> },
<add>
<add> 'utc to local, keepLocalTime = true' : function (test) {
<add> var um = moment.utc(),
<add> fmt = 'YYYY-DD-MM HH:mm:ss';
<add>
<add> test.equal(um.clone().local(true).format(fmt), um.format(fmt), 'utc to local failed to keep local time');
<add>
<add> test.done();
<add> },
<add>
<add> 'utc to local, keepLocalTime = false' : function (test) {
<add> var um = moment.utc();
<add> test.equal(um.clone().local().valueOf(), um.valueOf(), 'utc to local failed to keep utc time (implicit)');
<add> test.equal(um.clone().local(false).valueOf(), um.valueOf(), 'utc to local failed to keep utc time (explicit)');
<add>
<add> test.done();
<add> },
<add>
<add> 'zone to local, keepLocalTime = true' : function (test) {
<add> var m = moment(),
<add> fmt = 'YYYY-DD-MM HH:mm:ss',
<add> z;
<add>
<add> // Apparently there is -12:00 and +14:00
<add> // http://en.wikipedia.org/wiki/UTC+14:00
<add> // http://en.wikipedia.org/wiki/UTC-12:00
<add> for (z = -12; z <= 14; ++z) {
<add> m.utcOffset(z * 60);
<add>
<add> test.equal(m.clone().local(true).format(fmt),
<add> m.format(fmt),
<add> 'utcOffset(' + z + ':00) to local failed to keep local time');
<add> }
<add>
<add> test.done();
<add> },
<add>
<add> 'zone to local, keepLocalTime = false' : function (test) {
<add> var m = moment(),
<add> z;
<add>
<add> // Apparently there is -12:00 and +14:00
<add> // http://en.wikipedia.org/wiki/UTC+14:00
<add> // http://en.wikipedia.org/wiki/UTC-12:00
<add> for (z = -12; z <= 14; ++z) {
<add> m.utcOffset(z * 60);
<add>
<add> test.equal(m.clone().local(false).valueOf(), m.valueOf(),
<add> 'utcOffset(' + z + ':00) to local failed to keep utc time (explicit)');
<add> test.equal(m.clone().local().valueOf(), m.valueOf(),
<add> 'utcOffset(' + z + ':00) to local failed to keep utc time (implicit)');
<add> }
<add>
<ide> test.done();
<ide> }
<ide> }; | 1 |
PHP | PHP | remove use of file from unloadtask | edb31ea550887122a3aa3b8714c6e6a9cf5e2d5e | <ide><path>src/Shell/Task/UnloadTask.php
<ide>
<ide> use Cake\Console\ConsoleOptionParser;
<ide> use Cake\Console\Shell;
<del>use Cake\Filesystem\File;
<ide>
<ide> /**
<ide> * Task for unloading plugins.
<ide> protected function _modifyBootstrap(string $plugin): bool
<ide> {
<ide> $finder = "@\nPlugin::load\((.|.\n|\n\s\s|\n\t|)+'$plugin'(.|.\n|)+\);\n@";
<ide>
<del> $bootstrap = new File($this->bootstrap, false);
<del> $content = $bootstrap->read();
<add> $content = file_get_contents($this->bootstrap);
<ide>
<ide> if (!preg_match("@\n\s*Plugin::loadAll@", $content)) {
<ide> $newContent = preg_replace($finder, '', $content);
<ide> protected function _modifyBootstrap(string $plugin): bool
<ide> return false;
<ide> }
<ide>
<del> $bootstrap->write($newContent);
<add> file_put_contents($this->bootstrap, $newContent);
<ide>
<ide> $this->out('');
<ide> $this->out(sprintf('%s modified', $this->bootstrap)); | 1 |
Python | Python | implement cors for the restful api | 8a51ba58aadbb7843b029d9561c6b7b7d4a0181c | <ide><path>glances/outputs/glances_bottle.py
<ide>
<ide> # Import mandatory Bottle lib
<ide> try:
<del> from bottle import Bottle, template, static_file, TEMPLATE_PATH, abort, response
<add> from bottle import Bottle, template, static_file, TEMPLATE_PATH, abort, response, request
<ide> except ImportError:
<ide> logger.critical('Bottle module not found. Glances cannot start in web server mode.')
<ide> sys.exit(2)
<ide> def __init__(self, args=None):
<ide>
<ide> # Init Bottle
<ide> self._app = Bottle()
<add> # Enable CORS (issue #479)
<add> self._app.install(EnableCors())
<add> # Define routes
<ide> self._route()
<ide>
<ide> # Update the template path (glances/outputs/bottle)
<ide> def _favicon(self):
<ide> # Return the static file
<ide> return static_file('favicon.ico', root=self.STATIC_PATH)
<ide>
<add> def enable_cors(self):
<add> """Enable CORS"""
<add> response.headers['Access-Control-Allow-Origin'] = '*'
<add> response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
<add> response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
<add>
<ide> def _api_plugins(self):
<ide> """
<ide> Glances API RESTFul implementation
<ide> def display(self, stats, refresh_time=None):
<ide> }
<ide>
<ide> return template('base', refresh_time=refresh_time, stats=stats)
<add>
<add>
<add>class EnableCors(object):
<add> name = 'enable_cors'
<add> api = 2
<add>
<add> def apply(self, fn, context):
<add> def _enable_cors(*args, **kwargs):
<add> # set CORS headers
<add> response.headers['Access-Control-Allow-Origin'] = '*'
<add> response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
<add> response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
<add>
<add> if request.method != 'OPTIONS':
<add> # actual request; reply with the actual response
<add> return fn(*args, **kwargs)
<add>
<add> return _enable_cors | 1 |
Javascript | Javascript | accept undefined bufferview.bytelength (for 1.0) | 5bef7d6947ba89e3f2f56c083521cd2b74e3224e | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> var arraybuffer = dependencies.buffers[ bufferView.buffer ];
<ide>
<del> return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength );
<add> var byteLength = bufferView.byteLength !== undefined ? bufferView.byteLength : 0;
<add>
<add> return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + byteLength );
<ide>
<ide> } );
<ide> | 1 |
Python | Python | add integration test case for | 0d6df0a1ca35a35388d41125feb3ff3faecfcb7a | <ide><path>t/integration/test_canvas.py
<ide> def test_chord_in_chords_with_chains(self, manager):
<ide> r = c.delay()
<ide>
<ide> assert r.get(timeout=TIMEOUT) == 4
<add>
<add> @flaky
<add> def test_chain_chord_chain_chord(self, manager):
<add> # test for #2573
<add> try:
<add> manager.app.backend.ensure_chords_allowed()
<add> except NotImplementedError as e:
<add> raise pytest.skip(e.args[0])
<add> c = chain(
<add> identity.si(1),
<add> chord(
<add> [
<add> identity.si(2),
<add> chain(
<add> identity.si(3),
<add> chord(
<add> [identity.si(4), identity.si(5)],
<add> identity.si(6)
<add> )
<add> )
<add> ],
<add> identity.si(7)
<add> )
<add> )
<add> res = c.delay()
<add> assert res.get(timeout=TIMEOUT) == 7 | 1 |
Ruby | Ruby | add timestamp and argument list to log files | 03abf834724714b29e7d44720953affc01dd7415 | <ide><path>Library/Homebrew/formula.rb
<ide> def system cmd, *args
<ide> wr.close
<ide>
<ide> File.open(logfn, 'w') do |f|
<add> f.puts Time.now, "", cmd, args, ""
<add>
<ide> while buf = rd.gets
<ide> f.puts buf
<ide> puts buf if ARGV.verbose? | 1 |
Ruby | Ruby | fix typo in it comment | 1e07b77f49e6893eccdcb9096acd445aa0351f36 | <ide><path>Library/Homebrew/test/bintray_spec.rb
<ide> expect(hash).to eq("449de5ea35d0e9431f367f1bb34392e450f6853cdccdc6bd04e6ad6471904ddb")
<ide> end
<ide>
<del> it "fails on a non-existant file" do
<add> it "fails on a non-existent file" do
<ide> hash = bintray.remote_checksum(repo: "bottles", remote_file: "my-fake-bottle-1.0.snow_hyena.tar.gz")
<ide> expect(hash).to be nil
<ide> end | 1 |
Python | Python | remove special cases for 0d arrays in quantile | 919a8258da892cb154c29b83521b913630820fda | <ide><path>numpy/lib/function_base.py
<ide> def _lerp(a, b, t, out=None):
<ide> def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
<ide> interpolation='linear', keepdims=False):
<ide> a = asarray(a)
<del> if q.ndim == 0:
<del> # Do not allow 0-d arrays because following code fails for scalar
<del> zerod = True
<del> q = q[None]
<del> else:
<del> zerod = False
<add>
<add> # ufuncs cause 0d array results to decay to scalars (see gh-13105), which
<add> # makes them problematic for __setitem__ and attribute access. As a
<add> # workaround, we call this on the result of every ufunc on a possibly-0d
<add> # array.
<add> not_scalar = np.asanyarray
<ide>
<ide> # prepare a for partitioning
<ide> if overwrite_input:
<ide> def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
<ide> if axis is None:
<ide> axis = 0
<ide>
<del> Nx = ap.shape[axis]
<del> indices = q * (Nx - 1)
<add> if q.ndim > 2:
<add> # The code below works fine for nd, but it might not have useful
<add> # semantics. For now, keep the supported dimensions the same as it was
<add> # before.
<add> raise ValueError("q must be a scalar or 1d")
<ide>
<add> Nx = ap.shape[axis]
<add> indices = not_scalar(q * (Nx - 1))
<ide> # round fractional indices according to interpolation method
<ide> if interpolation == 'lower':
<ide> indices = floor(indices).astype(intp)
<ide> def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
<ide> "interpolation can only be 'linear', 'lower' 'higher', "
<ide> "'midpoint', or 'nearest'")
<ide>
<del> n = np.array(False, dtype=bool) # check for nan's flag
<del> if np.issubdtype(indices.dtype, np.integer): # take the points along axis
<del> # Check if the array contains any nan's
<del> if np.issubdtype(a.dtype, np.inexact):
<del> indices = concatenate((indices, [-1]))
<add> # The dimensions of `q` are prepended to the output shape, so we need the
<add> # axis being sampled from `ap` to be first.
<add> ap = np.moveaxis(ap, axis, 0)
<add> del axis
<ide>
<del> ap.partition(indices, axis=axis)
<del> # ensure axis with q-th is first
<del> ap = np.moveaxis(ap, axis, 0)
<del> axis = 0
<add> if np.issubdtype(indices.dtype, np.integer):
<add> # take the points along axis
<ide>
<del> # Check if the array contains any nan's
<ide> if np.issubdtype(a.dtype, np.inexact):
<del> indices = indices[:-1]
<del> n = np.isnan(ap[-1:, ...])
<add> # may contain nan, which would sort to the end
<add> ap.partition(concatenate((indices.ravel(), [-1])), axis=0)
<add> n = np.isnan(ap[-1])
<add> else:
<add> # cannot contain nan
<add> ap.partition(indices.ravel(), axis=0)
<add> n = np.array(False, dtype=bool)
<ide>
<del> if zerod:
<del> indices = indices[0]
<del> r = take(ap, indices, axis=axis, out=out)
<add> r = take(ap, indices, axis=0, out=out)
<add> if out is not None:
<add> r = out # workaround for gh-16276
<add>
<add> else:
<add> # weight the points above and below the indices
<ide>
<del> else: # weight the points above and below the indices
<del> indices_below = floor(indices).astype(intp)
<del> indices_above = indices_below + 1
<add> indices_below = not_scalar(floor(indices)).astype(intp)
<add> indices_above = not_scalar(indices_below + 1)
<ide> indices_above[indices_above > Nx - 1] = Nx - 1
<ide>
<del> # Check if the array contains any nan's
<ide> if np.issubdtype(a.dtype, np.inexact):
<del> indices_above = concatenate((indices_above, [-1]))
<del>
<del> ap.partition(concatenate((indices_below, indices_above)), axis=axis)
<del>
<del> # ensure axis with q-th is first
<del> ap = np.moveaxis(ap, axis, 0)
<del> axis = 0
<del>
<del> weights_shape = [1] * ap.ndim
<del> weights_shape[axis] = len(indices)
<del> weights_above = (indices - indices_below).reshape(weights_shape)
<add> # may contain nan, which would sort to the end
<add> ap.partition(concatenate((
<add> indices_below.ravel(), indices_above.ravel(), [-1]
<add> )), axis=0)
<add> n = np.isnan(ap[-1])
<add> else:
<add> # cannot contain nan
<add> ap.partition(concatenate((
<add> indices_below.ravel(), indices_above.ravel()
<add> )), axis=0)
<add> n = np.array(False, dtype=bool)
<ide>
<del> # Check if the array contains any nan's
<del> if np.issubdtype(a.dtype, np.inexact):
<del> indices_above = indices_above[:-1]
<del> n = np.isnan(ap[-1:, ...])
<add> weights_shape = indices.shape + (1,) * (ap.ndim - 1)
<add> weights_above = not_scalar(indices - indices_below).reshape(weights_shape)
<ide>
<del> x1 = take(ap, indices_below, axis=axis)
<del> x2 = take(ap, indices_above, axis=axis)
<del> if zerod:
<del> x1 = x1.squeeze(0)
<del> x2 = x2.squeeze(0)
<del> weights_above = weights_above.squeeze(0)
<add> x_below = take(ap, indices_below, axis=0)
<add> x_above = take(ap, indices_above, axis=0)
<ide>
<del> r = _lerp(x1, x2, weights_above, out=out)
<add> r = _lerp(x_below, x_above, weights_above, out=out)
<ide>
<add> # if any slice contained a nan, then all results on that slice are also nan
<ide> if np.any(n):
<del> if zerod:
<del> if ap.ndim == 1:
<del> if out is not None:
<del> out[...] = a.dtype.type(np.nan)
<del> r = out
<del> else:
<del> r = a.dtype.type(np.nan)
<del> else:
<del> r[..., n.squeeze(0)] = a.dtype.type(np.nan)
<add> if r.ndim == 0 and out is None:
<add> # can't write to a scalar
<add> r = a.dtype.type(np.nan)
<ide> else:
<del> if r.ndim == 1:
<del> r[:] = a.dtype.type(np.nan)
<del> else:
<del> r[..., n.repeat(q.size, 0)] = a.dtype.type(np.nan)
<add> r[..., n] = a.dtype.type(np.nan)
<ide>
<ide> return r
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.