content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Python | Python | remove mock http methods which are not needed | 8f7ba3d757160aa3dd25d522fe85e9a093eea2b0 | <ide><path>libcloud/test/storage/test_s3.py
<ide> def _foo_bar_container_foo_bar_object_NO_BUFFER(self, method, url, body, headers
<ide> headers,
<ide> httplib.responses[httplib.OK])
<ide>
<del> def _foo_bar_container_foo_test_upload_INVALID_HASH1(self, method, url,
<del> body, headers):
<del> body = ''
<del> headers = {}
<del> headers['etag'] = '"foobar"'
<del> # test_upload_object_invalid_hash1
<del> return (httplib.OK,
<del> body,
<del> headers,
<del> httplib.responses[httplib.OK])
<del>
<del> def _foo_bar_container_foo_test_upload_INVALID_HASH2(self, method, url,
<del> body, headers):
<del> # test_upload_object_invalid_hash2
<del> body = ''
<del> headers = {'etag': '"hash343hhash89h932439jsaa89"'}
<del> return (httplib.OK,
<del> body,
<del> headers,
<del> httplib.responses[httplib.OK])
<del>
<ide> def _foo_bar_container_foo_test_upload(self, method, url, body, headers):
<ide> # test_upload_object_success
<ide> body = ''
<ide> def test_upload_object_invalid_hash1(self):
<ide> def upload_file(self, object_name=None, content_type=None,
<ide> request_path=None, request_method=None,
<ide> headers=None, file_path=None, stream=None):
<del> return {'response': make_response(200),
<add> headers = {'etag': '"foobar"'}
<add> return {'response': make_response(200, headers=headers),
<ide> 'bytes_transferred': 1000,
<ide> 'data_hash': 'hash343hhash89h932439jsaa89'}
<ide>
<del> self.mock_response_klass.type = 'INVALID_HASH1'
<del>
<ide> old_func = self.driver_type._upload_object
<ide> self.driver_type._upload_object = upload_file
<ide> file_path = os.path.abspath(__file__)
<ide> def test_upload_object_invalid_hash2(self):
<ide> def upload_file(self, object_name=None, content_type=None,
<ide> request_path=None, request_method=None,
<ide> headers=None, file_path=None, stream=None):
<del> return {'response': make_response(200, headers={'etag': 'woopwoopwoop'}),
<add> headers = {'etag': '"hash343hhash89h932439jsaa89"'}
<add> return {'response': make_response(200, headers=headers),
<ide> 'bytes_transferred': 1000,
<ide> 'data_hash': '0cc175b9c0f1b6a831c399e269772661'}
<ide>
<del> self.mock_response_klass.type = 'INVALID_HASH2'
<del>
<ide> old_func = self.driver_type._upload_object
<ide> self.driver_type._upload_object = upload_file
<ide> | 1 |
Javascript | Javascript | fix loading of limits | 59c06234f9b55e76c2e0c3f27274eb730dfea55e | <ide><path>glances/outputs/static/js/stats_controller.js
<ide> glancesApp.controller('statsController', function($scope, $http, $interval, $q,
<ide> }
<ide>
<ide> $scope.init_limits = function() {
<del> $scope.plugins_limits();
<add> $http.get('/api/2/all/limits').success(function(response, status, headers, config) {
<add> $scope.pluginLimits = response
<add> }).error(function(response, status, headers, config) {
<add> console.log('error : ' + response+ status + headers + config);
<add> });
<ide> }
<ide>
<ide> $scope.init_help = function() {
<ide> glancesApp.controller('statsController', function($scope, $http, $interval, $q,
<ide> }
<ide> }
<ide>
<del> $scope.plugins_limits = function() {
<del> $http.get('/api/2/all/limits').success(function(response, status, headers, config) {
<del> $scope.limits = response
<del> }).error(function(response, status, headers, config) {
<del> console.log('error : ' + response+ status + headers + config);
<del> });
<del> }
<del>
<ide> var canceler = undefined;
<ide>
<ide> /** | 1 |
Go | Go | replace newtimer().c with after | 1a517a4a429d2b4db15383fc9d514fc8db66f8d3 | <ide><path>api/server/router/system/system_routes.go
<ide> func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *
<ide>
<ide> if !onlyPastEvents {
<ide> dur := until.Sub(now)
<del> timeout = time.NewTimer(dur).C
<add> timeout = time.After(dur)
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | keep decimals in results | 7889416b8a93b70fbc1ebfe65b8918f84216c347 | <ide><path>benchmark/common.js
<ide> function formatResult(data) {
<ide> conf += ' ' + key + '=' + JSON.stringify(data.conf[key]);
<ide> }
<ide>
<del> const rate = Math.floor(data.rate)
<del> .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
<add> var rate = data.rate.toString().split('.');
<add> rate[0] = rate[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
<add> rate = (rate[1] ? rate.join('.') : rate[0]);
<ide> return `${data.name}${conf}: ${rate}`;
<ide> }
<ide>
<ide><path>benchmark/run.js
<ide> if (format === 'csv') {
<ide> conf = conf.replace(/"/g, '""');
<ide> console.log(`"${data.name}", "${conf}", ${data.rate}, ${data.time}`);
<ide> } else {
<del> const rate = Math.floor(data.rate)
<del> .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
<add> var rate = data.rate.toString().split('.');
<add> rate[0] = rate[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
<add> rate = (rate[1] ? rate.join('.') : rate[0]);
<ide> console.log(`${data.name} ${conf}: ${rate}`);
<ide> }
<ide> }); | 2 |
Python | Python | fix minor typo and add matrix dimension check | 91c671ebabb3449fbbaefc2c4d959566eaed48dc | <ide><path>matrix/inverse_of_matrix.py
<ide> def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]:
<ide> [[0.25, -0.5], [-0.3, 1.0]]
<ide> """
<ide>
<del> D = Decimal # An abbreviation to be conciseness
<add> D = Decimal # An abbreviation for conciseness
<add>
<add> # Check if the provided matrix has 2 rows and 2 columns, since this implementation only works for 2x2 matrices
<add> if len(matrix) != 2 or len(matrix[0]) != 2 or len(matrix[1]) != 2:
<add> raise ValueError("Please provide a matrix of size 2x2.")
<add>
<ide> # Calculate the determinant of the matrix
<ide> determinant = D(matrix[0][0]) * D(matrix[1][1]) - D(matrix[1][0]) * D(matrix[0][1])
<ide> if determinant == 0:
<ide> raise ValueError("This matrix has no inverse.")
<add>
<ide> # Creates a copy of the matrix with swapped positions of the elements
<ide> swapped_matrix = [[0.0, 0.0], [0.0, 0.0]]
<ide> swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0]
<ide> swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1]
<add>
<ide> # Calculate the inverse of the matrix
<ide> return [[float(D(n) / determinant) or 0.0 for n in row] for row in swapped_matrix] | 1 |
Javascript | Javascript | add tests for compiler dependency errors | 339add578ddd09a5f2c9b17444b8a59f1d040829 | <ide><path>test/MultiCompiler.test.js
<ide> describe("MultiCompiler", () => {
<ide> env.callback.callCount.should.be.exactly(1);
<ide> });
<ide> });
<add>
<add> describe("with missing compiler dependencies", () => {
<add> beforeEach(() => {
<add> setupTwoCompilerEnvironment(env, {
<add> name: "compiler1",
<add> dependencies: ["compiler2"]
<add> }, {
<add> name: "compiler3"
<add> });
<add> env.callback = sinon.spy();
<add> env.options = [{
<add> testWatchOptions: true
<add> }, {
<add> testWatchOptions2: true
<add> }];
<add> env.result = env.myMultiCompiler.watch(env.options, env.callback);
<add> });
<add>
<add> it("should call the callback with an error message", () => {
<add> env.compiler1WatchCallbacks.length.should.be.exactly(0);
<add> env.compiler2WatchCallbacks.length.should.be.exactly(0);
<add> env.callback.callCount.should.be.exactly(1);
<add> env.callback.getCall(0).args[0].should.match(/`compiler2` not found/);
<add> });
<add> });
<add>
<add> describe("with circular compiler dependencies", () => {
<add> beforeEach(() => {
<add> setupTwoCompilerEnvironment(env, {
<add> name: "compiler1",
<add> dependencies: ["compiler2"]
<add> }, {
<add> name: "compiler2",
<add> dependencies: ["compiler1"]
<add> });
<add> env.callback = sinon.spy();
<add> env.options = [{
<add> testWatchOptions: true
<add> }, {
<add> testWatchOptions2: true
<add> }];
<add> env.result = env.myMultiCompiler.watch(env.options, env.callback);
<add> });
<add>
<add> it("should call the callback with an error message", () => {
<add> env.compiler1WatchCallbacks.length.should.be.exactly(0);
<add> env.compiler2WatchCallbacks.length.should.be.exactly(0);
<add> env.callback.callCount.should.be.exactly(1);
<add> env.callback.getCall(0).args[0].should.equal("Circular dependency found in compiler dependencies.");
<add> });
<add> });
<ide> });
<ide>
<ide> describe("run", () => {
<ide> describe("MultiCompiler", () => {
<ide> env.callback.callCount.should.be.exactly(1);
<ide> });
<ide> });
<add>
<add> describe("with missing compiler dependencies", () => {
<add> beforeEach(() => {
<add> setupTwoCompilerEnvironment(env, {
<add> name: "compiler1",
<add> dependencies: ["compiler2"]
<add> }, {
<add> name: "compiler3"
<add> });
<add> env.callback = sinon.spy();
<add> env.myMultiCompiler.run(env.callback);
<add> });
<add>
<add> it("should call the callback with an error message", () => {
<add> env.compiler1RunCallbacks.length.should.be.exactly(0);
<add> env.compiler2RunCallbacks.length.should.be.exactly(0);
<add> env.callback.callCount.should.be.exactly(1);
<add> env.callback.getCall(0).args[0].should.match(/`compiler2` not found/);
<add> });
<add> });
<add>
<add> describe("with circular compiler dependencies", () => {
<add> beforeEach(() => {
<add> setupTwoCompilerEnvironment(env, {
<add> name: "compiler1",
<add> dependencies: ["compiler2"]
<add> }, {
<add> name: "compiler2",
<add> dependencies: ["compiler1"]
<add> });
<add> env.callback = sinon.spy();
<add> env.myMultiCompiler.run(env.callback);
<add> });
<add>
<add> it("should call the callback with an error message", () => {
<add> env.compiler1RunCallbacks.length.should.be.exactly(0);
<add> env.compiler2RunCallbacks.length.should.be.exactly(0);
<add> env.callback.callCount.should.be.exactly(1);
<add> env.callback.getCall(0).args[0].should.equal("Circular dependency found in compiler dependencies.");
<add> });
<add> });
<ide> });
<ide>
<ide> describe("purgeInputFileSystem", () => { | 1 |
Text | Text | fix typo in parseargs default value | b4efac4820e308daeea87cf5283cbcb0c9e2c950 | <ide><path>doc/api/util.md
<ide> changes:
<ide> * `short` {string} A single character alias for the option.
<ide> * `default` {string | boolean | string\[] | boolean\[]} The default option
<ide> value when it is not set by args. It must be of the same type as the
<del> the `type` property. When `multiple` is `true`, it must be an array.
<add> `type` property. When `multiple` is `true`, it must be an array.
<ide> * `strict` {boolean} Should an error be thrown when unknown arguments
<ide> are encountered, or when arguments are passed that do not match the
<ide> `type` configured in `options`. | 1 |
Javascript | Javascript | add pointer support | d9b42ddbbd22cc1cba9aa447926be8026674c73f | <ide><path>src/ngTouch/swipe.js
<ide> ngTouch.factory('$swipe', [function() {
<ide> move: 'touchmove',
<ide> end: 'touchend',
<ide> cancel: 'touchcancel'
<add> },
<add> 'pointer': {
<add> start: 'pointerdown',
<add> move: 'pointermove',
<add> end: 'pointerup',
<add> cancel: 'pointercancel'
<ide> }
<ide> };
<ide>
<ide> ngTouch.factory('$swipe', [function() {
<ide> * The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
<ide> * object containing event handlers.
<ide> * The pointer types that should be used can be specified via the optional
<del> * third argument, which is an array of strings `'mouse'` and `'touch'`. By default,
<del> * `$swipe` will listen for `mouse` and `touch` events.
<add> * third argument, which is an array of strings `'mouse'`, `'touch'` and `'pointer'`. By default,
<add> * `$swipe` will listen for `mouse`, `touch` and `pointer` events.
<ide> *
<ide> * The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
<ide> * receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }` and the raw
<ide> * `event`. `cancel` receives the raw `event` as its single parameter.
<ide> *
<del> * `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
<del> * watching for `touchmove` or `mousemove` events. These events are ignored until the total
<add> * `start` is called on either `mousedown`, `touchstart` or `pointerdown`. After this event, `$swipe` is
<add> * watching for `touchmove`, `mousemove` or `pointermove` events. These events are ignored until the total
<ide> * distance moved in either dimension exceeds a small threshold.
<ide> *
<ide> * Once this threshold is exceeded, either the horizontal or vertical delta is greater.
<ide> * - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
<ide> * - If the vertical distance is greater, this is a scroll, and we let the browser take over.
<ide> * A `cancel` event is sent.
<ide> *
<del> * `move` is called on `mousemove` and `touchmove` after the above logic has determined that
<add> * `move` is called on `mousemove`, `touchmove` and `pointermove` after the above logic has determined that
<ide> * a swipe is in progress.
<ide> *
<del> * `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
<add> * `end` is called when a swipe is successfully completed with a `touchend`, `mouseup` or `pointerup`.
<ide> *
<del> * `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
<add> * `cancel` is called either on a `touchcancel` or `pointercancel` from the browser, or when we begin scrolling
<ide> * as described above.
<ide> *
<ide> */
<ide> ngTouch.factory('$swipe', [function() {
<ide> // Whether a swipe is active.
<ide> var active = false;
<ide>
<del> pointerTypes = pointerTypes || ['mouse', 'touch'];
<add> pointerTypes = pointerTypes || ['mouse', 'touch', 'pointer'];
<ide> element.on(getEvents(pointerTypes, 'start'), function(event) {
<ide> startCoords = getCoordinates(event);
<ide> active = true;
<ide><path>test/ngTouch/swipeSpec.js
<ide> describe('$swipe', function() {
<ide> var usedEvents;
<ide> var MOUSE_EVENTS = ['mousedown','mousemove','mouseup'].sort();
<ide> var TOUCH_EVENTS = ['touchcancel','touchend','touchmove','touchstart'].sort();
<del> var ALL_EVENTS = MOUSE_EVENTS.concat(TOUCH_EVENTS).sort();
<add> var POINTER_EVENTS = ['pointerdown', 'pointermove', 'pointerup', 'pointercancel'].sort();
<add> var ALL_EVENTS = MOUSE_EVENTS.concat(TOUCH_EVENTS, POINTER_EVENTS).sort();
<ide>
<ide> beforeEach(function() {
<ide> usedEvents = [];
<ide> describe('$swipe', function() {
<ide> });
<ide> });
<ide>
<del> it('should use mouse and touch by default', inject(function($swipe) {
<add> it('should use mouse, touch and pointer by default', inject(function($swipe) {
<ide> $swipe.bind(element, events);
<ide> expect(usedEvents.sort()).toEqual(ALL_EVENTS);
<ide> }));
<ide> describe('$swipe', function() {
<ide> expect(usedEvents.sort()).toEqual(TOUCH_EVENTS);
<ide> }));
<ide>
<add> it('should only use pointer events for pointerType "pointer"', inject(function($swipe) {
<add> $swipe.bind(element, events, ['pointer']);
<add> expect(usedEvents.sort()).toEqual(POINTER_EVENTS);
<add> }));
<add>
<ide> it('should use mouse and touch if both are specified', inject(function($swipe) {
<ide> $swipe.bind(element, events, ['touch', 'mouse']);
<add> expect(usedEvents.sort()).toEqual(MOUSE_EVENTS.concat(TOUCH_EVENTS).sort());
<add> }));
<add>
<add> it('should use mouse and pointer if both are specified', inject(function($swipe) {
<add> $swipe.bind(element, events, ['mouse', 'pointer']);
<add> expect(usedEvents.sort()).toEqual(MOUSE_EVENTS.concat(POINTER_EVENTS).sort());
<add> }));
<add>
<add> it('should use touch and pointer if both are specified', inject(function($swipe) {
<add> $swipe.bind(element, events, ['touch', 'pointer']);
<add> expect(usedEvents.sort()).toEqual(TOUCH_EVENTS.concat(POINTER_EVENTS).sort());
<add> }));
<add>
<add> it('should use mouse, touch and pointer if they are specified', inject(function($swipe) {
<add> $swipe.bind(element, events, ['mouse', 'touch', 'pointer']);
<ide> expect(usedEvents.sort()).toEqual(ALL_EVENTS);
<ide> }));
<ide>
<ide> });
<ide>
<ide> swipeTests('touch', /* restrictBrowers */ true, 'touchstart', 'touchmove', 'touchend');
<add> swipeTests('pointer', /* restrictBrowers */ true, 'pointerdown', 'pointermove', 'pointerup');
<ide> swipeTests('mouse', /* restrictBrowers */ false, 'mousedown', 'mousemove', 'mouseup');
<ide>
<ide> // Wrapper to abstract over using touch events or mouse events. | 2 |
Python | Python | use absolute imports | d4b88c1dbd6898fb6fcebc97f36b421999340f71 | <ide><path>doc/cdoc/numpyfilter.py
<ide> Also, add Doxygen /** and /**< syntax automatically where appropriate.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import re
<ide><path>doc/cython/run_test.py
<ide> #!/usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpyx import test
<ide> test()
<ide><path>doc/example.py
<ide> a line by itself, preferably preceeded by a blank line.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os # standard library imports first
<ide>
<ide><path>doc/newdtype_example/example.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import floatint.floatint as ff
<ide> import numpy as np
<ide><path>doc/newdtype_example/floatint/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide>
<ide><path>doc/numpybook/comparison/ctypes/filter.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['filter2d']
<ide>
<ide><path>doc/numpybook/comparison/ctypes/interface.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['add', 'filter2d']
<ide>
<ide><path>doc/numpybook/comparison/timing.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import timeit
<ide>
<ide><path>doc/numpybook/comparison/weave/filter.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from scipy import weave, zeros_like
<ide>
<ide><path>doc/numpybook/comparison/weave/inline.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from scipy import weave
<ide> from numpy import rand, zeros_like
<ide><path>doc/numpybook/runcode.py
<ide> -n name of code section (default MyCode)
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import optparse
<ide><path>doc/postprocess.py
<ide> MODE is either 'html' or 'tex'.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import re, optparse
<ide>
<ide><path>doc/pyrex/run_test.py
<ide> #!/usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpyx import test
<ide> test()
<ide><path>doc/source/conf.py
<ide> # -*- coding: utf-8 -*-
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys, os, re
<ide>
<ide><path>doc/sphinxext/numpydoc/comment_eater.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> if sys.version_info[0] >= 3:
<ide><path>doc/sphinxext/numpydoc/compiler_unparse.py
<ide> fixme: We may want to move to using _ast trees because the compiler for
<ide> them is about 6 times faster than compiler.compile.
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add
<ide><path>doc/sphinxext/numpydoc/docscrape.py
<ide> """Extract reference documentation from the NumPy source tree.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import inspect
<ide><path>doc/sphinxext/numpydoc/docscrape_sphinx.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import re, inspect, textwrap, pydoc
<ide> import sphinx
<ide><path>doc/sphinxext/numpydoc/linkcode.py
<ide> :license: BSD, see LICENSE for details.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import warnings
<ide> import collections
<ide><path>doc/sphinxext/numpydoc/numpydoc.py
<ide> .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sphinx
<ide> import collections
<ide><path>doc/sphinxext/numpydoc/phantom_import.py
<ide> .. [1] http://code.google.com/p/pydocweb
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import imp, sys, compiler, types, os, inspect, re
<ide>
<ide><path>doc/sphinxext/numpydoc/plot_directive.py
<ide> to make them appear side-by-side, or in floats.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys, os, glob, shutil, imp, warnings, re, textwrap, traceback
<ide> import sphinx
<ide><path>doc/sphinxext/numpydoc/tests/test_docscrape.py
<ide> # -*- encoding:utf-8 -*-
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys, textwrap
<ide>
<ide><path>doc/sphinxext/numpydoc/traitsdoc.py
<ide> .. [2] http://code.enthought.com/projects/traits/
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import inspect
<ide> import os
<ide><path>doc/summarize.py
<ide> Show a summary about which Numpy functions are documented and which are not.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os, glob, re, sys, inspect, optparse
<ide> import collections
<ide><path>doc/swig/test/testArray.py
<ide> #! /usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # System imports
<ide> from distutils.util import get_platform
<ide><path>doc/swig/test/testFarray.py
<ide> #! /usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # System imports
<ide> from distutils.util import get_platform
<ide><path>doc/swig/test/testFortran.py
<ide> #! /usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # System imports
<ide> from distutils.util import get_platform
<ide><path>doc/swig/test/testMatrix.py
<ide> #! /usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # System imports
<ide> from distutils.util import get_platform
<ide><path>doc/swig/test/testTensor.py
<ide> #! /usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # System imports
<ide> from distutils.util import get_platform
<ide><path>doc/swig/test/testVector.py
<ide> #! /usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # System imports
<ide> from distutils.util import get_platform
<ide><path>numpy/__init__.py
<ide> Exceptions to this rule are documented.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # We first need to detect if we're being called as part of the numpy setup
<ide> # procedure itself in a reliable manner.
<ide> its source directory; please exit the numpy source tree, and relaunch
<ide> your python intepreter from there."""
<ide> raise ImportError(msg)
<del> from version import git_revision as __git_revision__
<del> from version import version as __version__
<add> from .version import git_revision as __git_revision__
<add> from .version import version as __version__
<ide>
<del> from _import_tools import PackageLoader
<add> from ._import_tools import PackageLoader
<ide>
<ide> def pkgload(*packages, **options):
<ide> loader = PackageLoader(infunc=True)
<ide> return loader(*packages, **options)
<ide>
<del> import add_newdocs
<add> from . import add_newdocs
<ide> __all__ = ['add_newdocs']
<ide>
<ide> pkgload.__doc__ = PackageLoader.__call__.__doc__
<ide>
<del> from testing import Tester
<add> from .testing import Tester
<ide> test = Tester().test
<ide> bench = Tester().bench
<ide>
<del> import core
<del> from core import *
<del> import compat
<del> import lib
<del> from lib import *
<del> import linalg
<del> import fft
<del> import polynomial
<del> import random
<del> import ctypeslib
<del> import ma
<del> import matrixlib as _mat
<del> from matrixlib import *
<add> from . import core
<add> from .core import *
<add> from . import compat
<add> from . import lib
<add> from .lib import *
<add> from . import linalg
<add> from . import fft
<add> from . import polynomial
<add> from . import random
<add> from . import ctypeslib
<add> from . import ma
<add> from . import matrixlib as _mat
<add> from .matrixlib import *
<ide>
<ide> # Make these accessible from numpy name-space
<ide> # but not imported in from numpy import *
<ide> from __builtin__ import bool, int, long, float, complex, \
<ide> object, unicode, str
<del> from core import round, abs, max, min
<add> from .core import round, abs, max, min
<ide>
<ide> __all__.extend(['__version__', 'pkgload', 'PackageLoader',
<ide> 'show_config'])
<ide><path>numpy/_import_tools.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import sys
<ide><path>numpy/add_newdocs.py
<ide> core/fromnumeric.py, core/defmatrix.py up-to-date.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.lib import add_newdoc
<ide>
<ide><path>numpy/build_utils/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide><path>numpy/build_utils/common.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import copy
<ide><path>numpy/build_utils/waf.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import re
<ide> import waflib.Tools.c_config
<ide> from waflib import Logs, Utils
<ide>
<del>from common \
<add>from .common \
<ide> import \
<ide> LONG_DOUBLE_REPRESENTATION_SRC, pyod, \
<ide> long_double_representation
<ide><path>numpy/compat/__init__.py
<ide> * we may only need a small subset of the copied library/module
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<del>import _inspect
<del>import py3k
<del>from _inspect import getargspec, formatargspec
<del>from py3k import *
<add>from . import _inspect
<add>from . import py3k
<add>from ._inspect import getargspec, formatargspec
<add>from .py3k import *
<ide>
<ide> __all__ = []
<ide> __all__.extend(_inspect.__all__)
<ide><path>numpy/compat/_inspect.py
<ide> no overhead.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import types
<ide>
<ide><path>numpy/compat/py3k.py
<ide> Python 3 compatibility tools.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
<ide> 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
<ide><path>numpy/core/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<del>from info import __doc__
<add>from .info import __doc__
<ide> from numpy.version import version as __version__
<ide>
<del>import multiarray
<del>import umath
<del>import _internal # for freeze programs
<del>import numerictypes as nt
<add>from . import multiarray
<add>from . import umath
<add>from . import _internal # for freeze programs
<add>from . import numerictypes as nt
<ide> multiarray.set_typeDict(nt.sctypeDict)
<del>import numeric
<del>from numeric import *
<del>import fromnumeric
<del>from fromnumeric import *
<del>import defchararray as char
<del>import records as rec
<del>from records import *
<del>from memmap import *
<del>from defchararray import chararray
<del>import scalarmath
<del>import function_base
<del>from function_base import *
<del>import machar
<del>from machar import *
<del>import getlimits
<del>from getlimits import *
<del>import shape_base
<del>from shape_base import *
<add>from . import numeric
<add>from .numeric import *
<add>from . import fromnumeric
<add>from .fromnumeric import *
<add>from . import defchararray as char
<add>from . import records as rec
<add>from .records import *
<add>from .memmap import *
<add>from .defchararray import chararray
<add>from . import scalarmath
<add>from . import function_base
<add>from .function_base import *
<add>from . import machar
<add>from .machar import *
<add>from . import getlimits
<add>from .getlimits import *
<add>from . import shape_base
<add>from .shape_base import *
<ide> del nt
<ide>
<del>from fromnumeric import amax as max, amin as min, \
<add>from .fromnumeric import amax as max, amin as min, \
<ide> round_ as round
<del>from numeric import absolute as abs
<add>from .numeric import absolute as abs
<ide>
<ide> __all__ = ['char','rec','memmap']
<ide> __all__ += numeric.__all__
<ide><path>numpy/core/_internal.py
<ide> Some things are more easily handled Python.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import re
<ide> import sys
<ide> _nbo = asbytes('>')
<ide>
<ide> def _makenames_list(adict, align):
<del> from multiarray import dtype
<add> from .multiarray import dtype
<ide> allfields = []
<ide> fnames = adict.keys()
<ide> for fname in fnames:
<ide> def _makenames_list(adict, align):
<ide> # a dictionary without "names" and "formats"
<ide> # fields is used as a data-type descriptor.
<ide> def _usefields(adict, align):
<del> from multiarray import dtype
<add> from .multiarray import dtype
<ide> try:
<ide> names = adict[-1]
<ide> except KeyError:
<ide> def _array_descr(descriptor):
<ide> # so don't remove the name here, or you'll
<ide> # break backward compatibilty.
<ide> def _reconstruct(subtype, shape, dtype):
<del> from multiarray import ndarray
<add> from .multiarray import ndarray
<ide> return ndarray.__new__(subtype, shape, dtype)
<ide>
<ide>
<ide> def _commastring(astr):
<ide> return result
<ide>
<ide> def _getintp_ctype():
<del> from multiarray import dtype
<add> from .multiarray import dtype
<ide> val = _getintp_ctype.cache
<ide> if val is not None:
<ide> return val
<ide> def _newnames(datatype, order):
<ide> # Given an array with fields and a sequence of field names
<ide> # construct a new array with just those fields copied over
<ide> def _index_fields(ary, fields):
<del> from multiarray import empty, dtype, array
<add> from .multiarray import empty, dtype, array
<ide> dt = ary.dtype
<ide>
<ide> names = [name for name in fields if name in dt.names]
<ide><path>numpy/core/_methods.py
<ide> and the Python code for the NumPy-namespace function
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.core import multiarray as mu
<ide> from numpy.core import umath as um
<ide><path>numpy/core/arrayprint.py
<ide> $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ["array2string", "set_printoptions", "get_printoptions"]
<ide> __docformat__ = 'restructuredtext'
<ide> # and by Travis Oliphant 2005-8-22 for numpy
<ide>
<ide> import sys
<del>import numerictypes as _nt
<del>from umath import maximum, minimum, absolute, not_equal, isnan, isinf
<del>from multiarray import format_longfloat, datetime_as_string, datetime_data
<del>from fromnumeric import ravel
<add>from . import numerictypes as _nt
<add>from .umath import maximum, minimum, absolute, not_equal, isnan, isinf
<add>from .multiarray import format_longfloat, datetime_as_string, datetime_data
<add>from .fromnumeric import ravel
<ide>
<ide>
<ide> def product(x, y): return x*y
<ide> def get_printoptions():
<ide> return d
<ide>
<ide> def _leading_trailing(a):
<del> import numeric as _nc
<add> from . import numeric as _nc
<ide> if a.ndim == 1:
<ide> if len(a) > 2*_summaryEdgeItems:
<ide> b = _nc.concatenate((a[:_summaryEdgeItems],
<ide> def _array2string(a, max_line_width, precision, suppress_small, separator=' ',
<ide> return lst
<ide>
<ide> def _convert_arrays(obj):
<del> import numeric as _nc
<add> from . import numeric as _nc
<ide> newtup = []
<ide> for k in obj:
<ide> if isinstance(k, _nc.ndarray):
<ide> def __init__(self, data, precision, suppress_small, sign=False):
<ide> pass
<ide>
<ide> def fillFormat(self, data):
<del> import numeric as _nc
<add> from . import numeric as _nc
<ide> errstate = _nc.seterr(all='ignore')
<ide> try:
<ide> special = isnan(data) | isinf(data)
<ide> def fillFormat(self, data):
<ide> self.format = format
<ide>
<ide> def __call__(self, x, strip_zeros=True):
<del> import numeric as _nc
<add> from . import numeric as _nc
<ide> err = _nc.seterr(invalid='ignore')
<ide> try:
<ide> if isnan(x):
<ide><path>numpy/core/code_generators/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide><path>numpy/core/code_generators/cversions.py
<ide> The API has is defined by numpy_api_order and ufunc_api_order.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from os.path import dirname
<ide>
<del>from genapi import fullapi_hash
<del>import numpy_api
<add>from .genapi import fullapi_hash
<add>from . import numpy_api
<ide>
<ide>
<ide> if __name__ == '__main__':
<ide><path>numpy/core/code_generators/genapi.py
<ide> specified.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys, os, re
<ide> try:
<ide><path>numpy/core/code_generators/numpy_api.py
<ide> exception, so it should hopefully not get unnoticed).
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> multiarray_global_vars = {
<ide> 'NPY_NUMUSERTYPES': 7,
<ide><path>numpy/core/code_generators/ufunc_docstrings.py
<ide> at compile time.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> docdict = {}
<ide>
<ide><path>numpy/core/defchararray.py
<ide> The preferred alias for `defchararray` is `numpy.char`.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<del>from numerictypes import string_, unicode_, integer, object_, bool_, character
<del>from numeric import ndarray, compare_chararrays
<del>from numeric import array as narray
<add>from .numerictypes import string_, unicode_, integer, object_, bool_, character
<add>from .numeric import ndarray, compare_chararrays
<add>from .numeric import array as narray
<ide> from numpy.core.multiarray import _vec_string
<ide> from numpy.compat import asbytes
<ide> import numpy
<ide><path>numpy/core/fromnumeric.py
<ide> """Module containing non-deprecated functions borrowed from Numeric.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __docformat__ = "restructuredtext en"
<ide>
<ide> 'amax', 'amin',
<ide> ]
<ide>
<del>import multiarray as mu
<del>import umath as um
<del>import numerictypes as nt
<del>from numeric import asarray, array, asanyarray, concatenate
<del>import _methods
<add>from . import multiarray as mu
<add>from . import umath as um
<add>from . import numerictypes as nt
<add>from .numeric import asarray, array, asanyarray, concatenate
<add>from . import _methods
<ide> _dt_ = nt.sctype2char
<ide>
<ide> import types
<ide><path>numpy/core/function_base.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['logspace', 'linspace']
<ide>
<del>import numeric as _nx
<del>from numeric import array
<add>from . import numeric as _nx
<add>from .numeric import array
<ide>
<ide> def linspace(start, stop, num=50, endpoint=True, retstep=False):
<ide> """
<ide><path>numpy/core/getlimits.py
<ide> """Machine limits for Float32 and Float64 and (long double) if available...
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['finfo','iinfo']
<ide>
<del>from machar import MachAr
<del>import numeric
<del>import numerictypes as ntypes
<del>from numeric import array
<add>from .machar import MachAr
<add>from . import numeric
<add>from . import numerictypes as ntypes
<add>from .numeric import array
<ide>
<ide> def _frz(a):
<ide> """fix rank-0 --> rank-1"""
<ide><path>numpy/core/info.py
<ide> arccosh arcsinh arctanh
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> depends = ['testing']
<ide> global_symbols = ['*']
<ide><path>numpy/core/machar.py
<ide> Author: Pearu Peterson, September 2003
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['MachAr']
<ide>
<ide><path>numpy/core/memmap.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['memmap']
<ide>
<ide> import warnings
<del>from numeric import uint8, ndarray, dtype
<add>from .numeric import uint8, ndarray, dtype
<ide> import sys
<ide>
<ide> import numpy as np
<ide><path>numpy/core/numeric.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
<ide> 'arange', 'array', 'zeros', 'count_nonzero',
<ide>
<ide> import sys
<ide> import warnings
<del>import multiarray
<del>import umath
<del>from umath import *
<del>import numerictypes
<del>from numerictypes import *
<add>from . import multiarray
<add>from . import umath
<add>from .umath import *
<add>from . import numerictypes
<add>from .numerictypes import *
<ide> import collections
<ide>
<ide>
<ide> def outer(a,b):
<ide> try:
<ide> # importing this changes the dot function for basic 4 types
<ide> # to blas-optimized versions.
<del> from _dotblas import dot, vdot, inner, alterdot, restoredot
<add> from ._dotblas import dot, vdot, inner, alterdot, restoredot
<ide> except ImportError:
<ide> # docstrings are in add_newdocs.py
<ide> inner = multiarray.inner
<ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
<ide>
<ide>
<ide> #Use numarray's printing function
<del>from arrayprint import array2string, get_printoptions, set_printoptions
<add>from .arrayprint import array2string, get_printoptions, set_printoptions
<ide>
<ide> _typelessdata = [int_, float_, complex_]
<ide> if issubclass(intc, int):
<ide> def _setdef():
<ide> False_ = bool_(False)
<ide> True_ = bool_(True)
<ide>
<del>import fromnumeric
<del>from fromnumeric import *
<add>from . import fromnumeric
<add>from .fromnumeric import *
<ide> extend_all(fromnumeric)
<ide><path>numpy/core/numerictypes.py
<ide> \\-> object_ (not used much) (kind=O)
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # we add more at the bottom
<ide> __all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes',
<ide><path>numpy/core/records.py
<ide> array([ 2., 2.])
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # All of the functions allow formats to be a dtype
<ide> __all__ = ['record', 'recarray', 'format_parser']
<ide>
<del>import numeric as sb
<del>from defchararray import chararray
<del>import numerictypes as nt
<add>from . import numeric as sb
<add>from .defchararray import chararray
<add>from . import numerictypes as nt
<ide> import types
<ide> import os
<ide> import sys
<ide><path>numpy/core/setup_common.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # Code common to build tools
<ide> import sys
<ide><path>numpy/core/shape_base.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack']
<ide>
<del>import numeric as _nx
<del>from numeric import array, asanyarray, newaxis
<add>from . import numeric as _nx
<add>from .numeric import array, asanyarray, newaxis
<ide>
<ide> def atleast_1d(*arys):
<ide> """
<ide><path>numpy/core/src/multiarray/testcalcs.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from scipy import weave
<ide>
<ide><path>numpy/core/tests/test_api.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide><path>numpy/core/tests/test_arrayprint.py
<ide> #!/usr/bin/python
<ide> # -*- coding: utf-8 -*-
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import numpy as np
<ide><path>numpy/core/tests/test_blasdot.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> import sys
<ide><path>numpy/core/tests/test_datetime.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os, pickle
<ide> import numpy
<ide><path>numpy/core/tests/test_defchararray.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy.core import *
<ide><path>numpy/core/tests/test_deprecations.py
<ide> to document how deprecations should eventually be turned into errors.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import warnings
<ide><path>numpy/core/tests/test_dtype.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import numpy as np
<ide><path>numpy/core/tests/test_einsum.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from decimal import Decimal
<ide><path>numpy/core/tests/test_errstate.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import platform
<ide>
<ide><path>numpy/core/tests/test_function_base.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy import logspace, linspace
<ide><path>numpy/core/tests/test_getlimits.py
<ide> """ Test functions for limits module.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide>
<ide><path>numpy/core/tests/test_half.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import platform
<ide>
<ide><path>numpy/core/tests/test_indexerrors.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import TestCase, run_module_suite, assert_raises, assert_equal, assert_
<ide><path>numpy/core/tests/test_indexing.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.compat import asbytes
<ide><path>numpy/core/tests/test_item_selection.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import *
<ide><path>numpy/core/tests/test_machar.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide>
<ide><path>numpy/core/tests/test_memmap.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from tempfile import NamedTemporaryFile, mktemp
<ide><path>numpy/core/tests/test_multiarray.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import tempfile
<ide> import sys
<ide><path>numpy/core/tests/test_multiarray_assignment.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import TestCase
<ide><path>numpy/core/tests/test_nditer.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy import array, arange, nditer, all
<ide><path>numpy/core/tests/test_numeric.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import platform
<ide><path>numpy/core/tests/test_numerictypes.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.testing import *
<ide><path>numpy/core/tests/test_print.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import *
<ide><path>numpy/core/tests/test_records.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from os import path
<ide> import numpy as np
<ide><path>numpy/core/tests/test_regression.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import pickle
<ide> import sys
<ide><path>numpy/core/tests/test_scalarmath.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.testing import *
<ide><path>numpy/core/tests/test_scalarprint.py
<ide> """ Test printing of scalar types.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import TestCase, assert_, run_module_suite
<ide><path>numpy/core/tests/test_shape_base.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import warnings
<ide> import numpy as np
<ide><path>numpy/core/tests/test_ufunc.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide><path>numpy/core/tests/test_umath.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import platform
<ide><path>numpy/core/tests/test_umath_complex.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import platform
<ide><path>numpy/core/tests/test_unicode.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide><path>numpy/ctypeslib.py
<ide> >>> _lib.foo_func(out, len(out)) #doctest: +SKIP
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library',
<ide> 'c_intp', 'as_ctypes', 'as_array']
<ide><path>numpy/distutils/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide> if sys.version_info[0] < 3:
<del> from __version__ import version as __version__
<add> from .__version__ import version as __version__
<ide> # Must import local ccompiler ASAP in order to get
<ide> # customized CCompiler.spawn effective.
<del> import ccompiler
<del> import unixccompiler
<add> from . import ccompiler
<add> from . import unixccompiler
<ide>
<del> from info import __doc__
<del> from npy_pkg_config import *
<add> from .info import __doc__
<add> from .npy_pkg_config import *
<ide>
<ide> try:
<ide> import __config__
<ide><path>numpy/distutils/__version__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> major = 0
<ide> minor = 4
<ide><path>numpy/distutils/ccompiler.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import re
<ide> import os
<ide> def CCompiler_compile(self, sources, output_dir=None, macros=None,
<ide> return []
<ide> # FIXME:RELATIVE_IMPORT
<ide> if sys.version_info[0] < 3:
<del> from fcompiler import FCompiler
<add> from .fcompiler import FCompiler
<ide> else:
<ide> from numpy.distutils.fcompiler import FCompiler
<ide> if isinstance(self, FCompiler):
<ide><path>numpy/distutils/command/__init__.py
<ide> commands.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> def test_na_writable_attributes_deletion():
<ide> a = np.NA(2)
<ide><path>numpy/distutils/command/autodist.py
<ide> """This module implements additional tests ala autoconf which can be useful.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide>
<ide> # We put them here since they could be easily reused outside numpy.distutils
<ide><path>numpy/distutils/command/bdist_rpm.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import sys
<ide><path>numpy/distutils/command/build.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import sys
<ide><path>numpy/distutils/command/build_clib.py
<ide> """ Modified version of build_clib that handles fortran source files.
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> from glob import glob
<ide><path>numpy/distutils/command/build_ext.py
<ide> """ Modified version of build_ext that handles fortran source files.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import sys
<ide><path>numpy/distutils/command/build_py.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from distutils.command.build_py import build_py as old_build_py
<ide> from numpy.distutils.misc_util import is_string
<ide><path>numpy/distutils/command/build_scripts.py
<ide> """ Modified version of build_scripts that handles building scripts from functions.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from distutils.command.build_scripts import build_scripts as old_build_scripts
<ide> from numpy.distutils import log
<ide><path>numpy/distutils/command/build_src.py
<ide> """ Build swig, f2py, pyrex sources.
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import re
<ide><path>numpy/distutils/command/config.py
<ide> # try_compile call. try_run works but is untested for most of Fortran
<ide> # compilers (they must define linker_exe first).
<ide> # Pearu Peterson
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os, signal
<ide> import warnings
<ide><path>numpy/distutils/command/config_compiler.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from distutils.core import Command
<ide> from numpy.distutils import log
<ide><path>numpy/distutils/command/develop.py
<ide> files with filenames.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from setuptools.command.develop import develop as old_develop
<ide>
<ide><path>numpy/distutils/command/egg_info.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from setuptools.command.egg_info import egg_info as _egg_info
<ide>
<ide><path>numpy/distutils/command/install.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> if 'setuptools' in sys.modules:
<ide><path>numpy/distutils/command/install_clib.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> from distutils.core import Command
<ide><path>numpy/distutils/command/install_data.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> have_setuptools = ('setuptools' in sys.modules)
<ide><path>numpy/distutils/command/install_headers.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> from distutils.command.install_headers import install_headers as old_install_headers
<ide><path>numpy/distutils/command/sdist.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> if 'setuptools' in sys.modules:
<ide><path>numpy/distutils/compat.py
<ide> numpy.distutils
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide><path>numpy/distutils/conv_template.py
<ide> 3, 3, jim
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide>
<ide> __all__ = ['process_str', 'process_file']
<ide><path>numpy/distutils/core.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from distutils.core import *
<ide><path>numpy/distutils/cpuinfo.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['cpu']
<ide>
<ide><path>numpy/distutils/environment.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> from distutils.dist import Distribution
<ide><path>numpy/distutils/exec_command.py
<ide> - Tests, that send messages to stderr, fail when executed from MSYS prompt
<ide> because the messages are lost at some point.
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['exec_command','find_executable']
<ide>
<ide><path>numpy/distutils/extension.py
<ide> Overridden to support f2py.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __revision__ = "$Id: extension.py,v 1.1 2005/04/09 19:29:34 pearu Exp $"
<ide>
<ide><path>numpy/distutils/fcompiler/__init__.py
<ide> But note that FCompiler.executables is actually a dictionary of commands.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['FCompiler','new_fcompiler','show_fcompilers',
<ide> 'dummy_fortran_file']
<ide><path>numpy/distutils/fcompiler/absoft.py
<ide> # Notes:
<ide> # - when using -g77 then use -DUNDERSCORE_G77 to compile f2py
<ide> # generated extension modules (works for f2py v2.45.241_1936 and up)
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide>
<ide><path>numpy/distutils/fcompiler/compaq.py
<ide>
<ide> #http://www.compaq.com/fortran/docs/
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import sys
<ide><path>numpy/distutils/fcompiler/g95.py
<ide> # http://g95.sourceforge.net/
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.distutils.fcompiler import FCompiler
<ide>
<ide><path>numpy/distutils/fcompiler/gnu.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import re
<ide> import os
<ide><path>numpy/distutils/fcompiler/hpux.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.distutils.fcompiler import FCompiler
<ide>
<ide><path>numpy/distutils/fcompiler/ibm.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import re
<ide><path>numpy/distutils/fcompiler/intel.py
<ide> # http://developer.intel.com/software/products/compilers/flin/
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide><path>numpy/distutils/fcompiler/lahey.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide>
<ide><path>numpy/distutils/fcompiler/mips.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.distutils.cpuinfo import cpu
<ide> from numpy.distutils.fcompiler import FCompiler
<ide><path>numpy/distutils/fcompiler/nag.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.distutils.fcompiler import FCompiler
<ide><path>numpy/distutils/fcompiler/none.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.distutils.fcompiler import FCompiler
<ide>
<ide><path>numpy/distutils/fcompiler/pathf95.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.distutils.fcompiler import FCompiler
<ide>
<ide><path>numpy/distutils/fcompiler/pg.py
<ide> # http://www.pgroup.com
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.distutils.fcompiler import FCompiler
<ide> from sys import platform
<ide><path>numpy/distutils/fcompiler/sun.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.distutils.ccompiler import simple_version_match
<ide> from numpy.distutils.fcompiler import FCompiler
<ide><path>numpy/distutils/fcompiler/vast.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide>
<ide><path>numpy/distutils/from_template.py
<ide> <ctypereal=float,double,\\0,\\1>
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['process_str','process_file']
<ide>
<ide><path>numpy/distutils/info.py
<ide> """
<ide> Enhanced distutils with Fortran compilers support and more.
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> postpone_import = True
<ide><path>numpy/distutils/intelccompiler.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from distutils.unixccompiler import UnixCCompiler
<ide> from numpy.distutils.exec_command import find_executable
<ide><path>numpy/distutils/lib2def.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import re
<ide> import sys
<ide><path>numpy/distutils/line_endings.py
<ide> """ Functions for converting from DOS to UNIX line endings
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys, re, os
<ide>
<ide><path>numpy/distutils/log.py
<ide> # Colored log, requires Python 2.3 or up.
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from distutils.log import *
<ide> from distutils.log import Log as old_Log
<ide> from distutils.log import _global_log
<ide>
<ide> if sys.version_info[0] < 3:
<del> from misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string
<add> from .misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string
<ide> else:
<ide> from numpy.distutils.misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string
<ide>
<ide><path>numpy/distutils/mingw32ccompiler.py
<ide> # 3. Force windows to use g77
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import subprocess
<ide> import numpy.distutils.ccompiler
<ide>
<ide> if sys.version_info[0] < 3:
<del> import log
<add> from . import log
<ide> else:
<ide> from numpy.distutils import log
<ide> # NT stuff
<ide><path>numpy/distutils/misc_util.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import re
<ide> def get_info(self,*names):
<ide> Return information (from system_info.get_info) for all of the names in
<ide> the argument list in a single dictionary.
<ide> """
<del> from system_info import get_info, dict_append
<add> from .system_info import get_info, dict_append
<ide> info_dict = {}
<ide> for a in names:
<ide> dict_append(info_dict,**get_info(a))
<ide><path>numpy/distutils/npy_pkg_config.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> if sys.version_info[0] < 3:
<ide><path>numpy/distutils/numpy_distribution.py
<ide> # XXX: Handle setuptools ?
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from distutils.core import Distribution
<ide>
<ide><path>numpy/distutils/pathccompiler.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from distutils.unixccompiler import UnixCCompiler
<ide>
<ide><path>numpy/distutils/system_info.py
<ide> NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import os
<ide> def __init__(self):
<ide> if mklroot is None:
<ide> system_info.__init__(self)
<ide> else:
<del> from cpuinfo import cpu
<add> from .cpuinfo import cpu
<ide> l = 'mkl' # use shared library
<ide> if cpu.is_Itanium():
<ide> plt = '64'
<ide><path>numpy/distutils/tests/f2py_ext/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide><path>numpy/distutils/tests/f2py_ext/tests/test_fib2.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.testing import *
<ide><path>numpy/distutils/tests/f2py_f90_ext/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide><path>numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.testing import *
<ide><path>numpy/distutils/tests/gen_ext/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide><path>numpy/distutils/tests/gen_ext/tests/test_fib3.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.testing import *
<ide><path>numpy/distutils/tests/pyrex_ext/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide><path>numpy/distutils/tests/pyrex_ext/tests/test_primes.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.testing import *
<ide><path>numpy/distutils/tests/swig_ext/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide><path>numpy/distutils/tests/swig_ext/tests/test_example.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.testing import *
<ide><path>numpy/distutils/tests/swig_ext/tests/test_example2.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> from numpy.testing import *
<ide><path>numpy/distutils/tests/test_fcompiler_gnu.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide>
<ide><path>numpy/distutils/tests/test_fcompiler_intel.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide>
<ide><path>numpy/distutils/tests/test_misc_util.py
<ide> #!/usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy.distutils.misc_util import appendpath, minrelpath, gpaths, rel_path
<ide><path>numpy/distutils/tests/test_npy_pkg_config.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> from tempfile import mkstemp
<ide><path>numpy/distutils/unixccompiler.py
<ide> unixccompiler - can handle very long argument lists for ar.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide>
<ide> from numpy.distutils.compat import get_exception
<ide>
<ide> if sys.version_info[0] < 3:
<del> import log
<add> from . import log
<ide> else:
<ide> from numpy.distutils import log
<ide>
<ide><path>numpy/doc/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide>
<ide><path>numpy/doc/basics.py
<ide> methods arrays do.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/broadcasting.py
<ide> for illustrations of broadcasting concepts.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/byteswapping.py
<ide> False
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/constants.py
<ide> #
<ide> # Note: the docstring is autogenerated.
<ide> #
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import textwrap, re
<ide>
<ide><path>numpy/doc/creation.py
<ide> diagonal).
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/glossary.py
<ide> and f2py (which wraps Fortran).
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/howtofind.py
<ide> How to find things in NumPy.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/indexing.py
<ide> 40
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/internals.py
<ide> it is more in line with Python semantics and the natural order of the data.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/io.py
<ide> Placeholder for array I/O documentation.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/jargon.py
<ide> Placeholder for computer science, engineering and other jargon.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/methods_vs_functions.py
<ide> Placeholder for Methods vs. Functions documentation.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/misc.py
<ide> 5) SIP (used mainly in PyQT)
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/performance.py
<ide> Placeholder for Improving Performance documentation.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/structured_arrays.py
<ide> <http://www.scipy.org/Cookbook/Recarray>`_.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/subclassing.py
<ide> def __array_wrap__(self, arr, context=None):
<ide>
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/doc/ufuncs.py
<ide> a convenient way to apply these operators.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide><path>numpy/dual.py
<ide> .. _Scipy : http://www.scipy.org
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # This module should be used for functions both in numpy and scipy if
<ide> # you want to use the numpy version if available but the scipy version
<ide><path>numpy/f2py/__init__.py
<ide> #!/usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['run_main','compile','f2py_testing']
<ide>
<ide> import os
<ide> import sys
<ide> import commands
<ide>
<del>import f2py2e
<del>import f2py_testing
<del>import diagnose
<add>from . import f2py2e
<add>from . import f2py_testing
<add>from . import diagnose
<ide>
<del>from info import __doc__
<add>from .info import __doc__
<ide>
<ide> run_main = f2py2e.run_main
<ide> main = f2py2e.main
<ide><path>numpy/f2py/__version__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> major = 2
<ide>
<ide><path>numpy/f2py/auxfuncs.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.65 $"[10:-1]
<ide>
<del>import __version__
<add>from . import __version__
<ide> f2py_version = __version__.version
<ide>
<ide> import pprint
<ide> import sys
<ide> import types
<del>import cfuncs
<add>from . import cfuncs
<ide>
<ide>
<ide> errmess=sys.stderr.write
<ide> def getcallprotoargument(rout,cb_map={}):
<ide> if hascallstatement(rout):
<ide> outmess('warning: callstatement is defined without callprotoargument\n')
<ide> return
<del> from capi_maps import getctype
<add> from .capi_maps import getctype
<ide> arg_types,arg_types2 = [],[]
<ide> if l_and(isstringfunction,l_not(isfunction_wrap))(rout):
<ide> arg_types.extend(['char*','size_t'])
<ide><path>numpy/f2py/capi_maps.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.60 $"[10:-1]
<ide>
<del>import __version__
<add>from . import __version__
<ide> f2py_version = __version__.version
<ide>
<ide> import copy
<ide> import re
<ide> import os
<ide> import sys
<del>from auxfuncs import *
<del>from crackfortran import markoutercomma
<del>import cb_rules
<add>from .auxfuncs import *
<add>from .crackfortran import markoutercomma
<add>from . import cb_rules
<ide>
<ide> # Numarray and Numeric users should set this False
<ide> using_newcore = True
<ide><path>numpy/f2py/cb_rules.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.53 $"[10:-1]
<ide>
<del>import __version__
<add>from . import __version__
<ide> f2py_version = __version__.version
<ide>
<ide>
<ide> outmess=sys.stdout.write
<ide> show=pprint.pprint
<ide>
<del>from auxfuncs import *
<del>import cfuncs
<add>from .auxfuncs import *
<add>from . import cfuncs
<ide>
<ide> ################## Rules for callback function ##############
<ide>
<ide> def buildcallbacks(m):
<ide>
<ide> def buildcallback(rout,um):
<ide> global cb_map
<del> import capi_maps
<add> from . import capi_maps
<ide>
<ide> outmess('\tConstructing call-back function "cb_%s_in_%s"\n'%(rout['name'],um))
<ide> args,depargs=getargs(rout)
<ide><path>numpy/f2py/cfuncs.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.75 $"[10:-1]
<ide>
<del>import __version__
<add>from . import __version__
<ide> f2py_version = __version__.version
<ide>
<ide> import types
<ide> """
<ide>
<ide> def buildcfuncs():
<del> from capi_maps import c2capi_map
<add> from .capi_maps import c2capi_map
<ide> for k in c2capi_map.keys():
<ide> m='pyarr_from_p_%s1'%k
<ide> cppmacros[m]='#define %s(v) (PyArray_SimpleNewFromData(0,NULL,%s,(char *)v))'%(m,c2capi_map[k])
<ide><path>numpy/f2py/common_rules.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.19 $"[10:-1]
<ide>
<del>import __version__
<add>from . import __version__
<ide> f2py_version = __version__.version
<ide>
<ide> import pprint
<ide> outmess=sys.stdout.write
<ide> show=pprint.pprint
<ide>
<del>from auxfuncs import *
<del>import capi_maps
<del>import func2subr
<del>from crackfortran import rmbadname
<add>from .auxfuncs import *
<add>from . import capi_maps
<add>from . import func2subr
<add>from .crackfortran import rmbadname
<ide> ##############
<ide>
<ide> def findcommonblocks(block,top=1):
<ide><path>numpy/f2py/crackfortran.py
<ide> The above may be solved by creating appropriate preprocessor program, for example.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.177 $"[10:-1]
<ide> import platform
<del>import __version__
<add>from . import __version__
<ide> f2py_version = __version__.version
<ide>
<ide> #
<ide> import pprint
<ide> import os
<ide> import copy
<del>from auxfuncs import *
<add>from .auxfuncs import *
<ide>
<ide> # Global flags:
<ide> strictf77=1 # Ignore `!' comments unless line[0]=='!'
<ide><path>numpy/f2py/diagnose.py
<ide> #!/usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import sys
<ide><path>numpy/f2py/doc/collectinput.py
<ide> collectinput # in and out are stdin and stdout
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "0.0"
<ide>
<ide><path>numpy/f2py/docs/pytest.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> #File: pytest.py
<ide> import Numeric
<ide><path>numpy/f2py/docs/usersguide/setup_example.py
<ide> #!/usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # File: setup_example.py
<ide>
<ide><path>numpy/f2py/f2py2e.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<del>import __version__
<add>from . import __version__
<ide> f2py_version = __version__.version
<ide>
<ide> import sys
<ide> #outmess=sys.stdout.write
<ide> show=pprint.pprint
<ide>
<del>import crackfortran
<del>import rules
<del>import cb_rules
<del>import auxfuncs
<del>import cfuncs
<del>import f90mod_rules
<add>from . import crackfortran
<add>from . import rules
<add>from . import cb_rules
<add>from . import auxfuncs
<add>from . import cfuncs
<add>from . import f90mod_rules
<ide>
<ide> outmess = auxfuncs.outmess
<ide>
<ide><path>numpy/f2py/f2py_testing.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import re
<ide><path>numpy/f2py/f90mod_rules.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.27 $"[10:-1]
<ide>
<ide> outmess=sys.stdout.write
<ide> show=pprint.pprint
<ide>
<del>from auxfuncs import *
<add>from .auxfuncs import *
<ide> import numpy as np
<del>import capi_maps
<del>import func2subr
<del>from crackfortran import undo_rmbadname, undo_rmbadname1
<add>from . import capi_maps
<add>from . import func2subr
<add>from .crackfortran import undo_rmbadname, undo_rmbadname1
<ide>
<ide> options={}
<ide>
<ide> def findf90modules(m):
<ide>
<ide> def buildhooks(pymod):
<ide> global fgetdims1,fgetdims2
<del> import rules
<add> from . import rules
<ide> ret = {'f90modhooks':[],'initf90modhooks':[],'body':[],
<ide> 'need':['F_FUNC','arrayobject.h'],
<ide> 'separatorsfor':{'includes0':'\n','includes':'\n'},
<ide><path>numpy/f2py/func2subr.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.16 $"[10:-1]
<ide>
<ide> outmess=sys.stdout.write
<ide> show=pprint.pprint
<ide>
<del>from auxfuncs import *
<add>from .auxfuncs import *
<ide> def var2fixfortran(vars,a,fa=None,f90mode=None):
<ide> if fa is None:
<ide> fa = a
<ide><path>numpy/f2py/info.py
<ide> """Fortran to Python Interface Generator.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> postpone_import = True
<ide><path>numpy/f2py/rules.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.129 $"[10:-1]
<ide>
<del>import __version__
<add>from . import __version__
<ide> f2py_version = __version__.version
<ide>
<ide> import pprint
<ide> outmess=sys.stdout.write
<ide> show=pprint.pprint
<ide>
<del>from auxfuncs import *
<del>import capi_maps
<del>from capi_maps import *
<del>import cfuncs
<del>import common_rules
<del>import use_rules
<del>import f90mod_rules
<del>import func2subr
<add>from .auxfuncs import *
<add>from . import capi_maps
<add>from .capi_maps import *
<add>from . import cfuncs
<add>from . import common_rules
<add>from . import use_rules
<add>from . import f90mod_rules
<add>from . import func2subr
<ide> options={}
<ide>
<ide> sepdict={}
<ide><path>numpy/f2py/tests/test_array_from_pyobj.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import unittest
<ide> import os
<ide><path>numpy/f2py/tests/test_assumed_shape.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import math
<ide><path>numpy/f2py/tests/test_callback.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy import array
<ide><path>numpy/f2py/tests/test_kind.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import math
<ide><path>numpy/f2py/tests/test_mixed.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import math
<ide><path>numpy/f2py/tests/test_return_character.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy import array
<ide><path>numpy/f2py/tests/test_return_complex.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy import array
<ide><path>numpy/f2py/tests/test_return_integer.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy import array
<ide><path>numpy/f2py/tests/test_return_logical.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy import array
<ide><path>numpy/f2py/tests/test_return_real.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy import array
<ide><path>numpy/f2py/tests/test_size.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import math
<ide><path>numpy/f2py/tests/util.py
<ide> - detecting if compilers are present
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import sys
<ide><path>numpy/f2py/use_rules.py
<ide> Pearu Peterson
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __version__ = "$Revision: 1.3 $"[10:-1]
<ide>
<ide> outmess=sys.stdout.write
<ide> show=pprint.pprint
<ide>
<del>from auxfuncs import *
<add>from .auxfuncs import *
<ide> ##############
<ide>
<ide> usemodule_rules={
<ide><path>numpy/fft/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # To get sub-modules
<del>from info import __doc__
<add>from .info import __doc__
<ide>
<del>from fftpack import *
<del>from helper import *
<add>from .fftpack import *
<add>from .helper import *
<ide>
<ide> from numpy.testing import Tester
<ide> test = Tester().test
<ide><path>numpy/fft/fftpack.py
<ide> version of the FFTPACK routines.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['fft','ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn',
<ide> 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn']
<ide>
<ide> from numpy.core import asarray, zeros, swapaxes, shape, conjugate, \
<ide> take
<del>import fftpack_lite as fftpack
<add>from . import fftpack_lite as fftpack
<ide>
<ide> _fft_cache = {}
<ide> _real_fft_cache = {}
<ide><path>numpy/fft/helper.py
<ide> Discrete Fourier Transforms - helper.py
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # Created by Pearu Peterson, September 2002
<ide>
<ide><path>numpy/fft/info.py
<ide> For examples, see the various functions.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> depends = ['core']
<ide><path>numpy/fft/tests/test_fftpack.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal
<ide><path>numpy/fft/tests/test_helper.py
<ide> Copied from fftpack.helper by Pearu Peterson, October 2005
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal
<ide><path>numpy/lib/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<del>from info import __doc__
<add>from .info import __doc__
<ide> from numpy.version import version as __version__
<ide>
<del>from type_check import *
<del>from index_tricks import *
<del>from function_base import *
<del>from shape_base import *
<del>from stride_tricks import *
<del>from twodim_base import *
<del>from ufunclike import *
<add>from .type_check import *
<add>from .index_tricks import *
<add>from .function_base import *
<add>from .shape_base import *
<add>from .stride_tricks import *
<add>from .twodim_base import *
<add>from .ufunclike import *
<ide>
<del>import scimath as emath
<del>from polynomial import *
<add>from . import scimath as emath
<add>from .polynomial import *
<ide> #import convertcode
<del>from utils import *
<del>from arraysetops import *
<del>from npyio import *
<del>from financial import *
<add>from .utils import *
<add>from .arraysetops import *
<add>from .npyio import *
<add>from .financial import *
<ide> import math
<del>from arrayterator import *
<del>from arraypad import *
<add>from .arrayterator import *
<add>from .arraypad import *
<ide>
<ide> __all__ = ['emath','math']
<ide> __all__ += type_check.__all__
<ide><path>numpy/lib/_datasource.py
<ide> >>> fp.close()
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __docformat__ = "restructuredtext en"
<ide>
<ide><path>numpy/lib/_iotools.py
<ide> """A collection of functions designed to help I/O with ascii files.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __docformat__ = "restructuredtext en"
<ide>
<ide><path>numpy/lib/arraypad.py
<ide> of an n-dimensional array.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide>
<ide><path>numpy/lib/arraysetops.py
<ide> :Author: Robert Cimrman
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d',
<ide> 'unique', 'in1d']
<ide><path>numpy/lib/arrayterator.py
<ide> a user-specified number of elements.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from operator import mul
<ide>
<ide><path>numpy/lib/financial.py
<ide> or arrays (or other sequences).
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide>
<ide><path>numpy/lib/format.py
<ide> alternatives, is described fully in the "npy-format" NEP.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import cPickle
<ide>
<ide><path>numpy/lib/function_base.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __docformat__ = "restructuredtext en"
<ide> __all__ = ['select', 'piecewise', 'trim_zeros', 'copy', 'iterable',
<ide> from numpy.core.numerictypes import typecodes, number
<ide> from numpy.core import atleast_1d, atleast_2d
<ide> from numpy.lib.twodim_base import diag
<del>from _compiled_base import _insert, add_docstring
<del>from _compiled_base import digitize, bincount, interp as compiled_interp
<del>from arraysetops import setdiff1d
<del>from utils import deprecate
<del>from _compiled_base import add_newdoc_ufunc
<add>from ._compiled_base import _insert, add_docstring
<add>from ._compiled_base import digitize, bincount, interp as compiled_interp
<add>from .arraysetops import setdiff1d
<add>from .utils import deprecate
<add>from ._compiled_base import add_newdoc_ufunc
<ide> import numpy as np
<ide> import collections
<ide>
<ide><path>numpy/lib/index_tricks.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['ravel_multi_index',
<ide> 'unravel_index',
<ide> from numpy.core.numerictypes import find_common_type
<ide> import math
<ide>
<del>import function_base
<add>from . import function_base
<ide> import numpy.matrixlib as matrix
<del>from function_base import diff
<add>from .function_base import diff
<ide> from numpy.lib._compiled_base import ravel_multi_index, unravel_index
<ide> from numpy.lib.stride_tricks import as_strided
<ide> makemat = matrix.matrix
<ide><path>numpy/lib/info.py
<ide> ================ ===================
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> depends = ['core','testing']
<ide> global_symbols = ['*']
<ide><path>numpy/lib/npyio.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['savetxt', 'loadtxt', 'genfromtxt', 'ndfromtxt', 'mafromtxt',
<ide> 'recfromtxt', 'recfromcsv', 'load', 'loads', 'save', 'savez',
<ide> 'savez_compressed', 'packbits', 'unpackbits', 'fromregex', 'DataSource']
<ide>
<ide> import numpy as np
<del>import format
<add>from . import format
<ide> import sys
<ide> import os
<ide> import re
<ide> from operator import itemgetter
<ide>
<ide> from cPickle import load as _cload, loads
<del>from _datasource import DataSource
<del>from _compiled_base import packbits, unpackbits
<add>from ._datasource import DataSource
<add>from ._compiled_base import packbits, unpackbits
<ide>
<del>from _iotools import LineSplitter, NameValidator, StringConverter, \
<add>from ._iotools import LineSplitter, NameValidator, StringConverter, \
<ide> ConverterError, ConverterLockError, ConversionWarning, \
<ide> _is_string_like, has_nested_fields, flatten_dtype, \
<ide> easy_dtype, _bytes_to_name
<ide><path>numpy/lib/polynomial.py
<ide> Functions to operate on polynomials.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd',
<ide> 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d',
<ide><path>numpy/lib/recfunctions.py
<ide> They have been rewritten and extended for convenience.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import itertools
<ide><path>numpy/lib/scimath.py
<ide> correctly handled. See their respective docstrings for specific examples.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['sqrt', 'log', 'log2', 'logn','log10', 'power', 'arccos',
<ide> 'arcsin', 'arctanh']
<ide><path>numpy/lib/shape_base.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['column_stack','row_stack', 'dstack','array_split','split','hsplit',
<ide> 'vsplit','dsplit','apply_over_axes','expand_dims',
<ide><path>numpy/lib/stride_tricks.py
<ide> NumPy reference guide.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide>
<ide><path>numpy/lib/tests/test__datasource.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> from tempfile import mkdtemp, mkstemp, NamedTemporaryFile
<ide><path>numpy/lib/tests/test__iotools.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide><path>numpy/lib/tests/test_arraypad.py
<ide> """Tests for the pad functions.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import TestCase, run_module_suite, assert_array_equal
<ide> from numpy.testing import assert_raises, assert_array_almost_equal
<ide><path>numpy/lib/tests/test_arraysetops.py
<ide> """Test functions for 1D array set operations.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> import numpy as np
<ide><path>numpy/lib/tests/test_arrayterator.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from operator import mul
<ide>
<ide><path>numpy/lib/tests/test_financial.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> import numpy as np
<ide><path>numpy/lib/tests/test_format.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> r''' Test the .npy file format.
<ide>
<ide><path>numpy/lib/tests/test_function_base.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import warnings
<ide> import numpy as np
<ide><path>numpy/lib/tests/test_index_tricks.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> import numpy as np
<ide><path>numpy/lib/tests/test_io.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide> import gzip
<ide><path>numpy/lib/tests/test_polynomial.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> '''
<ide> >>> p = np.poly1d([1.,2,3])
<ide><path>numpy/lib/tests/test_recfunctions.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide><path>numpy/lib/tests/test_regression.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy.testing.utils import _assert_valid_refcount
<ide><path>numpy/lib/tests/test_shape_base.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy.lib import *
<ide><path>numpy/lib/tests/test_stride_tricks.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import *
<ide><path>numpy/lib/tests/test_twodim_base.py
<ide> """Test functions for matrix module
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide>
<ide><path>numpy/lib/tests/test_type_check.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy.lib import *
<ide><path>numpy/lib/tests/test_ufunclike.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> import numpy.core as nx
<ide><path>numpy/lib/tests/test_utils.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> import numpy.lib.utils as utils
<ide><path>numpy/lib/twodim_base.py
<ide> """ Basic functions for manipulating 2d arrays
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['diag','diagflat','eye','fliplr','flipud','rot90','tri','triu',
<ide> 'tril','vander','histogram2d','mask_indices',
<ide><path>numpy/lib/type_check.py
<ide> """Automatically adapted for numpy Sep 19, 2005 by convertcode.py
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['iscomplexobj','isrealobj','imag','iscomplex',
<ide> 'isreal','nan_to_num','real','real_if_close',
<ide> import numpy.core.numeric as _nx
<ide> from numpy.core.numeric import asarray, asanyarray, array, isnan, \
<ide> obj2sctype, zeros
<del>from ufunclike import isneginf, isposinf
<add>from .ufunclike import isneginf, isposinf
<ide>
<ide> _typecodes_by_elsize = 'GDFgdfQqLlIiHhBb?'
<ide>
<ide><path>numpy/lib/ufunclike.py
<ide> storing results in an output array.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['fix', 'isneginf', 'isposinf']
<ide>
<ide><path>numpy/lib/user_array.py
<ide> complete.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.core import array, asarray, absolute, add, subtract, multiply, \
<ide> divide, remainder, power, left_shift, right_shift, bitwise_and, \
<ide><path>numpy/lib/utils.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import os
<ide> import sys
<ide><path>numpy/linalg/__init__.py
<ide> =============== ==========================================================
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> # To get sub-modules
<del>from info import __doc__
<add>from .info import __doc__
<ide>
<del>from linalg import *
<add>from .linalg import *
<ide>
<ide> from numpy.testing import Tester
<ide> test = Tester().test
<ide><path>numpy/linalg/info.py
<ide> - LinAlgError Indicates a failed linear algebra operation
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> depends = ['core']
<ide><path>numpy/linalg/lapack_lite/clapack_scrub.py
<ide> #!/usr/bin/env python2.4
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys, os
<ide> from cStringIO import StringIO
<ide><path>numpy/linalg/lapack_lite/fortran.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import re
<ide> import itertools
<ide><path>numpy/linalg/lapack_lite/make_lite.py
<ide> #!/usr/bin/env python
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys, os
<ide> import fortran
<ide><path>numpy/linalg/linalg.py
<ide> dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf,
<ide> zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr.
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide>
<ide> __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',
<ide><path>numpy/linalg/tests/test_build.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from subprocess import call, PIPE, Popen
<ide> import sys
<ide><path>numpy/linalg/tests/test_linalg.py
<ide> """ Test functions for linalg module
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import sys
<ide>
<ide><path>numpy/linalg/tests/test_regression.py
<ide> """ Test functions for linalg module
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide>
<ide> from numpy.testing import *
<ide><path>numpy/ma/__init__.py
<ide> invalid operation.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)"
<ide> __version__ = '1.0'
<ide> __revision__ = "$Revision: 3473 $"
<ide> __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
<ide>
<del>import core
<del>from core import *
<add>from . import core
<add>from .core import *
<ide>
<del>import extras
<del>from extras import *
<add>from . import extras
<add>from .extras import *
<ide>
<ide> __all__ = ['core', 'extras']
<ide> __all__ += core.__all__
<ide><path>numpy/ma/bench.py
<ide> #! python
<ide> # encoding: utf-8
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import timeit
<ide> #import IPython.ipapi
<ide><path>numpy/ma/core.py
<ide>
<ide> """
<ide> # pylint: disable-msg=E1002
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide>
<ide> __author__ = "Pierre GF Gerard-Marchant"
<ide><path>numpy/ma/extras.py
<ide> :version: $Id: extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)"
<ide> __version__ = '1.0'
<ide> import itertools
<ide> import warnings
<ide>
<del>import core as ma
<del>from core import MaskedArray, MAError, add, array, asarray, concatenate, count, \
<add>from . import core as ma
<add>from .core import MaskedArray, MAError, add, array, asarray, concatenate, count, \
<ide> filled, getmask, getmaskarray, make_mask_descr, masked, masked_array, \
<ide> mask_or, nomask, ones, sort, zeros
<ide> #from core import *
<ide><path>numpy/ma/mrecords.py
<ide> :author: Pierre Gerard-Marchant
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> #!!!: * We should make sure that no field is called '_mask','mask','_fieldmask',
<ide> #!!!: or whatever restricted keywords.
<ide><path>numpy/ma/tests/test_core.py
<ide> :author: Pierre Gerard-Marchant
<ide> :contact: pierregm_at_uga_dot_edu
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __author__ = "Pierre GF Gerard-Marchant"
<ide>
<ide><path>numpy/ma/tests/test_extras.py
<ide> :version: $Id: test_extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)"
<ide> __version__ = '1.0'
<ide><path>numpy/ma/tests/test_mrecords.py
<ide> :contact: pierregm_at_uga_dot_edu
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)"
<ide> __revision__ = "$Revision: 3473 $"
<ide><path>numpy/ma/tests/test_old_ma.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy
<ide> import types
<ide><path>numpy/ma/tests/test_regression.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> import numpy as np
<ide><path>numpy/ma/tests/test_subclassing.py
<ide> :version: $Id: test_subclassing.py 3473 2007-10-29 15:18:13Z jarrod.millman $
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)"
<ide> __version__ = '1.0'
<ide><path>numpy/ma/testutils.py
<ide> :version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)"
<ide> __version__ = "1.0"
<ide> from numpy.testing import *
<ide> import numpy.testing.utils as utils
<ide>
<del>from core import mask_or, getmask, masked_array, nomask, masked, filled, \
<add>from .core import mask_or, getmask, masked_array, nomask, masked, filled, \
<ide> equal, less
<ide>
<ide> #------------------------------------------------------------------------------
<ide><path>numpy/ma/timer_comparison.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import timeit
<ide>
<ide><path>numpy/ma/version.py
<ide> """Version number
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> version = '1.00'
<ide> release = False
<ide>
<ide> if not release:
<del> import core
<del> import extras
<add> from . import core
<add> from . import extras
<ide> revision = [core.__revision__.split(':')[-1][:-1].strip(),
<ide> extras.__revision__.split(':')[-1][:-1].strip(),]
<ide> version += '.dev%04i' % max([int(rev) for rev in revision])
<ide><path>numpy/matlib.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.matrixlib.defmatrix import matrix, asmatrix
<ide><path>numpy/matrixlib/__init__.py
<ide> """Sub-package containing the matrix class and related functions.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<del>from defmatrix import *
<add>from .defmatrix import *
<ide>
<ide> __all__ = defmatrix.__all__
<ide>
<ide><path>numpy/matrixlib/defmatrix.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['matrix', 'bmat', 'mat', 'asmatrix']
<ide>
<ide><path>numpy/matrixlib/tests/test_defmatrix.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> from numpy.core import *
<ide><path>numpy/matrixlib/tests/test_multiarray.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> import numpy as np
<ide> from numpy.testing import *
<ide><path>numpy/matrixlib/tests/test_numeric.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import assert_equal, TestCase
<ide> from numpy.core import ones
<ide><path>numpy/matrixlib/tests/test_regression.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.testing import *
<ide> import numpy as np
<ide><path>numpy/numarray/__init__.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<del>from util import *
<del>from numerictypes import *
<del>from functions import *
<del>from ufuncs import *
<del>from compat import *
<del>from session import *
<add>from .util import *
<add>from .numerictypes import *
<add>from .functions import *
<add>from .ufuncs import *
<add>from .compat import *
<add>from .session import *
<ide>
<del>import util
<del>import numerictypes
<del>import functions
<del>import ufuncs
<del>import compat
<del>import session
<add>from . import util
<add>from . import numerictypes
<add>from . import functions
<add>from . import ufuncs
<add>from . import compat
<add>from . import session
<ide>
<ide> __all__ = ['session', 'numerictypes']
<ide> __all__ += util.__all__
<ide><path>numpy/numarray/alter_code1.py
<ide> - .setimaginary() --> .imag
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc']
<ide>
<ide><path>numpy/numarray/alter_code2.py
<ide> FIXME: finish this.
<ide>
<ide> """
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = []
<ide>
<ide><path>numpy/numarray/compat.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> __all__ = ['NewAxis', 'ArrayType']
<ide>
<ide><path>numpy/numarray/convolve.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> try:
<ide> from stsci.convolve import *
<ide><path>numpy/numarray/fft.py
<del>from __future__ import division
<add>from __future__ import division, absolute_import
<ide>
<ide> from numpy.oldnumeric.fft import *
<ide> import numpy.oldnumeric.fft as nof | 300 |
Javascript | Javascript | reject public keys properly | c64ed10d8067fc3b21578d3eafe322d0e9496980 | <ide><path>lib/internal/crypto/keys.js
<ide> function prepareAsymmetricKey(key, ctx) {
<ide> ...(ctx !== kCreatePrivate ? ['KeyObject'] : [])],
<ide> key);
<ide> }
<del> return { data, ...parseKeyEncoding(key, undefined) };
<add>
<add> const isPublic =
<add> (ctx === kConsumePrivate || ctx === kCreatePrivate) ? false : undefined;
<add> return { data, ...parseKeyEncoding(key, undefined, isPublic) };
<ide> } else {
<ide> throw new ERR_INVALID_ARG_TYPE(
<ide> 'key',
<ide><path>test/parallel/test-crypto-key-objects.js
<ide> const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
<ide> library: 'BIO routines',
<ide> function: 'BIO_new_mem_buf',
<ide> });
<add>
<add> // This should not abort either: https://github.com/nodejs/node/issues/29904
<add> assert.throws(() => {
<add> createPrivateKey({ key: Buffer.alloc(0), format: 'der', type: 'spki' });
<add> }, {
<add> code: 'ERR_INVALID_OPT_VALUE',
<add> message: 'The value "spki" is invalid for option "type"'
<add> });
<add>
<add> // Unlike SPKI, PKCS#1 is a valid encoding for private keys (and public keys),
<add> // so it should be accepted by createPrivateKey, but OpenSSL won't parse it.
<add> assert.throws(() => {
<add> const key = createPublicKey(publicPem).export({
<add> format: 'der',
<add> type: 'pkcs1'
<add> });
<add> createPrivateKey({ key, format: 'der', type: 'pkcs1' });
<add> }, {
<add> message: /asn1 encoding/,
<add> library: 'asn1 encoding routines'
<add> });
<ide> }
<ide>
<ide> [ | 2 |
PHP | PHP | apply fixes from styleci | 3d432b4d3eba328ab80c9c180042385b519228c7 | <ide><path>src/Illuminate/Foundation/Testing/Constraints/SeeInOrder.php
<ide> public function __construct($content)
<ide> * @param array $values
<ide> * @return bool
<ide> */
<del> public function matches($values) : bool
<add> public function matches($values): bool
<ide> {
<ide> $position = 0;
<ide>
<ide> public function matches($values) : bool
<ide> * @param array $values
<ide> * @return string
<ide> */
<del> public function failureDescription($values) : string
<add> public function failureDescription($values): string
<ide> {
<ide> return sprintf(
<ide> 'Failed asserting that \'%s\' contains "%s" in specified order.',
<ide> public function failureDescription($values) : string
<ide> *
<ide> * @return string
<ide> */
<del> public function toString() : string
<add> public function toString(): string
<ide> {
<ide> return (new ReflectionClass($this))->name;
<ide> }
<ide><path>tests/Foundation/Http/Middleware/TrimStringsTest.php
<ide>
<ide> class TrimStringsTest extends TestCase
<ide> {
<del> public function testTrimStringsIgnoringExceptAttribute() : void
<add> public function testTrimStringsIgnoringExceptAttribute(): void
<ide> {
<ide> $middleware = new TrimStringsWithExceptAttribute();
<ide> $symfonyRequest = new SymfonyRequest([ | 2 |
Javascript | Javascript | add `byteswritten` test for `http2stream` | 1aa491a88fdaf8695dc49ede67fce82ee44e53b6 | <ide><path>test/parallel/test-http2-byteswritten-server.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>const assert = require('assert');
<add>const http2 = require('http2');
<add>
<add>const http2Server = http2.createServer(common.mustCall(function(req, res) {
<add> res.socket.on('finish', common.mustCall(() => {
<add> assert(req.socket.bytesWritten > 0); // 1094
<add> }));
<add> res.writeHead(200, { 'Content-Type': 'text/plain' });
<add> res.write(Buffer.from('1'.repeat(1024)));
<add> res.end();
<add>}));
<add>
<add>http2Server.listen(0, common.mustCall(function() {
<add> const URL = `http://localhost:${http2Server.address().port}`;
<add> const http2client = http2.connect(URL, { protocol: 'http:' });
<add> const req = http2client.request({ ':method': 'GET', ':path': '/' });
<add> req.on('data', common.mustCall());
<add> req.on('end', common.mustCall(function() {
<add> http2client.close();
<add> http2Server.close();
<add> }));
<add> req.end();
<add>})); | 1 |
Ruby | Ruby | add missing cpath environment variable | 61076c1a11b932a7803b5c2748a2baa5b1d4bda9 | <ide><path>Library/Homebrew/cmd/--env.rb
<ide> def build_env_keys env
<ide> HOMEBREW_USE_GCC HOMEBREW_USE_LLVM HOMEBREW_SVN HOMEBREW_GIT
<ide> HOMEBREW_SDKROOT HOMEBREW_BUILD_FROM_SOURCE
<ide> MAKE GIT CPP
<del> ACLOCAL_PATH OBJC PATH ].select{ |key| env.fetch(key) if env.key? key }
<add> ACLOCAL_PATH OBJC PATH CPATH].select{ |key| env.fetch(key) if env.key? key }
<ide> end
<ide>
<ide> def dump_build_env env | 1 |
Go | Go | fix missing host, remove urlutil.istransporturl() | 12424cfa6fce22420423520078bd4d7e0a2de3db | <ide><path>daemon/logger/fluentd/fluentd.go
<ide> package fluentd // import "github.com/docker/docker/daemon/logger/fluentd"
<ide>
<ide> import (
<ide> "math"
<del> "net"
<ide> "net/url"
<ide> "strconv"
<ide> "strings"
<ide> import (
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/daemon/logger/loggerutils"
<ide> "github.com/docker/docker/errdefs"
<del> "github.com/docker/docker/pkg/urlutil"
<ide> units "github.com/docker/go-units"
<ide> "github.com/fluent/fluent-logger-golang/fluent"
<ide> "github.com/pkg/errors"
<ide> func parseAddress(address string) (*location, error) {
<ide> address = defaultProtocol + "://" + address
<ide> }
<ide>
<del> protocol := defaultProtocol
<del> if urlutil.IsTransportURL(address) {
<del> addr, err := url.Parse(address)
<del> if err != nil {
<del> return nil, err
<del> }
<del> // unix and unixgram socket
<del> if addr.Scheme == "unix" || addr.Scheme == "unixgram" {
<del> if strings.TrimLeft(addr.Path, "/") == "" {
<del> return nil, errors.New("path is empty")
<del> }
<del> return &location{
<del> protocol: addr.Scheme,
<del> host: "",
<del> port: 0,
<del> path: addr.Path,
<del> }, nil
<del> }
<del> // tcp|udp
<del> protocol = addr.Scheme
<del> address = addr.Host
<add> addr, err := url.Parse(address)
<add> if err != nil {
<add> return nil, err
<add> }
<ide>
<del> if addr.Path != "" {
<del> return nil, errors.New("should not contain a path element")
<add> switch addr.Scheme {
<add> case "unix", "unixgram":
<add> if strings.TrimLeft(addr.Path, "/") == "" {
<add> return nil, errors.New("path is empty")
<ide> }
<add> return &location{protocol: addr.Scheme, path: addr.Path}, nil
<add> case "tcp", "tcp+tls", "udp":
<add> // continue processing below
<add> default:
<add> return nil, errors.Errorf("unsupported scheme: '%s'", addr.Scheme)
<ide> }
<ide>
<del> host, port, err := net.SplitHostPort(address)
<del> if err != nil {
<del> if !strings.Contains(err.Error(), "missing port in address") {
<del> return nil, err
<del> }
<del> return &location{
<del> protocol: protocol,
<del> host: host,
<del> port: defaultPort,
<del> path: "",
<del> }, nil
<add> if addr.Path != "" {
<add> return nil, errors.New("should not contain a path element")
<ide> }
<ide>
<del> portnum, err := strconv.Atoi(port)
<del> if err != nil {
<del> return nil, err
<add> host := defaultHost
<add> port := defaultPort
<add>
<add> if h := addr.Hostname(); h != "" {
<add> host = h
<add> }
<add> if p := addr.Port(); p != "" {
<add> // Port numbers are 16 bit: https://www.ietf.org/rfc/rfc793.html#section-3.1
<add> portNum, err := strconv.ParseUint(p, 10, 16)
<add> if err != nil {
<add> return nil, errors.Wrap(err, "invalid port")
<add> }
<add> port = int(portNum)
<ide> }
<ide> return &location{
<del> protocol: protocol,
<add> protocol: addr.Scheme,
<ide> host: host,
<del> port: portnum,
<add> port: port,
<ide> path: "",
<ide> }, nil
<ide> }
<ide><path>daemon/logger/fluentd/fluentd_test.go
<ide> func TestValidateLogOptReconnectInterval(t *testing.T) {
<ide> }
<ide>
<ide> func TestValidateLogOptAddress(t *testing.T) {
<del>
<del> // paths to try
<add> // ports to try, and their results
<add> validPorts := map[string]int{
<add> "": defaultPort,
<add> ":": defaultPort,
<add> ":123": 123,
<add> ":65535": 65535,
<add> }
<add> // paths to try, which should result in an error
<ide> paths := []string{"/", "/some-path"}
<ide>
<ide> tests := []struct {
<ide> addr string
<del> paths []string // paths to append to addr, should be an error for tcp/udp
<add> ports map[string]int // combinations of addr + port -> expected port
<add> paths []string // paths to append to addr, should be an error for tcp/udp
<ide> expected location
<ide> expectedErr string
<ide> }{
<ide> func TestValidateLogOptAddress(t *testing.T) {
<ide> },
<ide> {
<ide> addr: "192.168.1.1",
<add> ports: validPorts,
<ide> paths: paths,
<ide> expected: location{
<del> port: defaultPort,
<ide> protocol: defaultProtocol,
<add> host: "192.168.1.1",
<ide> },
<ide> },
<ide> {
<ide> addr: "[::1]",
<add> ports: validPorts,
<ide> paths: paths,
<ide> expected: location{
<del> port: defaultPort,
<ide> protocol: defaultProtocol,
<add> host: "::1",
<ide> },
<ide> },
<ide> {
<ide> addr: "example.com",
<add> ports: validPorts,
<ide> paths: paths,
<ide> expected: location{
<del> port: defaultPort,
<ide> protocol: defaultProtocol,
<add> host: "example.com",
<ide> },
<ide> },
<ide> {
<ide> addr: "tcp://",
<ide> paths: paths,
<ide> expected: location{
<ide> protocol: "tcp",
<add> host: defaultHost,
<ide> port: defaultPort,
<ide> },
<ide> },
<ide> {
<ide> addr: "tcp://example.com",
<del> paths: paths,
<del> expected: location{
<del> protocol: "tcp",
<del> port: defaultPort,
<del> },
<del> },
<del> {
<del> addr: "tcp://example.com:65535",
<add> ports: validPorts,
<ide> paths: paths,
<ide> expected: location{
<ide> protocol: "tcp",
<ide> host: "example.com",
<del> port: 65535,
<ide> },
<ide> },
<ide> {
<ide> addr: "://",
<del> expectedErr: "invalid syntax",
<add> expectedErr: "missing protocol scheme",
<ide> },
<ide> {
<ide> addr: "something://",
<del> expectedErr: "invalid syntax",
<add> expectedErr: "unsupported scheme: 'something'",
<ide> },
<ide> {
<ide> addr: "corrupted:c",
<ide> func TestValidateLogOptAddress(t *testing.T) {
<ide> addr: "tcp://example.com:-1",
<ide> expectedErr: "invalid port",
<ide> },
<add> {
<add> addr: "tcp://example.com:65536",
<add> expectedErr: "invalid port",
<add> },
<ide> {
<ide> addr: "unix://",
<ide> expectedErr: "path is empty",
<ide> func TestValidateLogOptAddress(t *testing.T) {
<ide> }
<ide> for _, tc := range tests {
<ide> tc := tc
<del> if len(tc.paths) == 0 {
<del> tc.paths = []string{""}
<add> if len(tc.ports) == 0 {
<add> tc.ports = map[string]int{"": tc.expected.port}
<ide> }
<del> for _, path := range tc.paths {
<del> address := tc.addr + path
<del> t.Run(address, func(t *testing.T) {
<del> err := ValidateLogOpt(map[string]string{addressKey: address})
<del> if path != "" {
<del> assert.ErrorContains(t, err, "should not contain a path element")
<del> return
<del> }
<del> if tc.expectedErr != "" {
<del> assert.ErrorContains(t, err, tc.expectedErr)
<del> return
<del> }
<ide>
<del> assert.NilError(t, err)
<del> addr, _ := parseAddress(address)
<del> assert.DeepEqual(t, tc.expected, *addr, cmp.AllowUnexported(location{}))
<del> })
<add> // always try empty paths; add paths to try if the test specifies it
<add> tc.paths = append([]string{""}, tc.paths...)
<add> for port, expectedPort := range tc.ports {
<add> for _, path := range tc.paths {
<add> address := tc.addr + port + path
<add> expected := tc.expected
<add> expected.port = expectedPort
<add> t.Run(address, func(t *testing.T) {
<add> err := ValidateLogOpt(map[string]string{addressKey: address})
<add> if path != "" {
<add> assert.ErrorContains(t, err, "should not contain a path element")
<add> return
<add> }
<add> if tc.expectedErr != "" {
<add> assert.ErrorContains(t, err, tc.expectedErr)
<add> return
<add> }
<add>
<add> assert.NilError(t, err)
<add> addr, _ := parseAddress(address)
<add> assert.DeepEqual(t, expected, *addr, cmp.AllowUnexported(location{}))
<add> })
<add> }
<ide> }
<ide> }
<ide> } | 2 |
PHP | PHP | apply fixes from styleci | 417bfdb24d703fd75e256fc1f070ec12c526b215 | <ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php
<ide> protected function shouldBlockPhpUpload($value, $parameters)
<ide> }
<ide>
<ide> $phpExtensions = [
<del> 'php', 'php3', 'php4', 'php5', 'phtml', 'phar'
<add> 'php', 'php3', 'php4', 'php5', 'phtml', 'phar',
<ide> ];
<ide>
<ide> return ($value instanceof UploadedFile) | 1 |
Text | Text | add lambdas in conditional validations | 3cb491f327de27d2d5106f4340e7b36c70cb9403 | <ide><path>guides/source/active_record_validations.md
<ide> class Account < ApplicationRecord
<ide> end
<ide> ```
<ide>
<add>As `Lambdas` are a type of `Proc`, they can also be used to write inline
<add>conditions in a shorter way.
<add>
<add>```ruby
<add>validates :password, confirmation: true, unless: -> { password.blank? }
<add>```
<add>
<ide> ### Grouping Conditional validations
<ide>
<ide> Sometimes it is useful to have multiple validations use one condition. It can | 1 |
Text | Text | add link for domain-specific language [ci skip] | f57e1a224540b40a552f2f79da181caf969bdbc8 | <ide><path>guides/source/getting_started.md
<ide> Rails.application.routes.draw do
<ide> # ...
<ide> ```
<ide>
<del>This is your application's _routing file_ which holds entries in a special DSL
<del>(domain-specific language) that tells Rails how to connect incoming requests to
<add>This is your application's _routing file_ which holds entries in a special
<add>[DSL (domain-specific language)](http://en.wikipedia.org/wiki/Domain-specific_language)
<add>that tells Rails how to connect incoming requests to
<ide> controllers and actions. This file contains many sample routes on commented
<ide> lines, and one of them actually shows you how to connect the root of your site
<ide> to a specific controller and action. Find the line beginning with `root` and | 1 |
PHP | PHP | improve exception message | 58655bee45acf5d6d808d1f4e6e4e941984e4a25 | <ide><path>src/View/Form/ContextFactory.php
<ide> public function get(ServerRequest $request, array $data = []): ContextInterface
<ide>
<ide> if (!isset($context)) {
<ide> throw new RuntimeException(sprintf(
<del> 'No context provider found for entity of type `%s`.',
<add> 'No context provider found for value of type `%s`.'
<add> . ' Use `null` as 1st argument of FormHelper::create() to create a context-less form.',
<ide> getTypeName($data['entity'])
<ide> ));
<ide> }
<ide><path>src/View/Helper/FormHelper.php
<ide> public function contextFactory(?ContextFactory $instance = null, array $contexts
<ide> *
<ide> * @param mixed $context The context for which the form is being defined.
<ide> * Can be a ContextInterface instance, ORM entity, ORM resultset, or an
<del> * array of meta data. You can use false or null to make a context-less form.
<add> * array of meta data. You can use `null `to make a context-less form.
<ide> * @param array $options An array of html attributes and options.
<ide> * @return string An formatted opening FORM tag.
<ide> * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#Cake\View\Helper\FormHelper::create
<ide><path>tests/TestCase/View/Form/ContextFactoryTest.php
<ide> class ContextFactoryTest extends TestCase
<ide> public function testGetException()
<ide> {
<ide> $this->expectException(\RuntimeException::class);
<del> $this->expectExceptionMessage('No context provider found for entity of type `boolean`.');
<add> $this->expectExceptionMessage(
<add> 'No context provider found for value of type `boolean`.'
<add> . ' Use `null` as 1st argument of FormHelper::create() to create a context-less form.'
<add> );
<ide>
<ide> $factory = new ContextFactory();
<ide> $factory->get(new ServerRequest(), ['entity' => false]); | 3 |
Go | Go | fix failing test to use kill instead of stop | 4434dcee89f7d0d0239f6b492b24e940cdbafb21 | <ide><path>integration/server_test.go
<ide> func TestRestartKillWait(t *testing.T) {
<ide> })
<ide> }
<ide>
<del>func TestCreateStartRestartStopStartKillRm(t *testing.T) {
<add>func TestCreateStartRestartKillStartKillRm(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> srv := mkServerFromEngine(eng, t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<ide> func TestCreateStartRestartStopStartKillRm(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> job = eng.Job("stop", id)
<del> job.SetenvInt("t", 15)
<add> job = eng.Job("kill", id)
<ide> if err := job.Run(); err != nil {
<ide> t.Fatal(err)
<ide> } | 1 |
Ruby | Ruby | stop mutating revisions hash | e27574b27bf6ce11ce0dc5a139c09b228c672480 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def fetch
<ide> fetch_repo @co, @url, @ref
<ide> when :revisions
<ide> # nil is OK for main_revision, as fetch_repo will then get latest
<del> main_revision = @ref.delete :trunk
<add> main_revision = @ref[:trunk]
<ide> fetch_repo @co, @url, main_revision, true
<ide>
<ide> get_externals do |external_name, external_url| | 1 |
Python | Python | remove old code | 4c9e5e969ff7b62537500bdf151033d04ddca855 | <ide><path>celery/buckets.py
<ide> from Queue import Queue
<ide> from Queue import Empty as QueueEmpty
<ide>
<del>
<ide> RATE_MODIFIER_MAP = {"s": lambda n: n,
<ide> "m": lambda n: n / 60.0,
<ide> "h": lambda n: n / 60.0 / 60.0}
<ide> def get(self, block=True, timeout=None):
<ide> def get_nowait(self):
<ide> return self.get(block=False)
<ide>
<del> def __old_get(self, block=True, timeout=None):
<del> time_spent = 0
<del> for bucket in self.buckets.values():
<del> remaining_times = []
<del> try:
<del> return bucket.get_nowait()
<del> except RateLimitExceeded:
<del> remaining_times.append(bucket.expected_time())
<del> except QueueEmpty:
<del> pass
<del>
<del> if not remaining_times:
<del> if not block or (timeout and time_spent >= timeout):
<del> raise QueueEmpty
<del> else:
<del> shortest_wait = min(remaining_times or [self.min_wait])
<del> time_spent += shortest_wait
<del> time.sleep(shortest_wait)
<del>
<ide> def init_with_registry(self):
<ide> """Initialize with buckets for all the task types in the registry."""
<ide> map(self.add_bucket_for_type, self.task_registry.keys())
<ide>
<ide> def get_bucket_for_type(self, task_name):
<ide> """Get the bucket for a particular task type."""
<del> if not task_name in self.buckets:
<add> if task_name not in self.buckets:
<ide> return self.add_bucket_for_type(task_name)
<ide> return self.buckets[task_name]
<ide>
<ide> def add_bucket_for_type(self, task_name):
<ide> will be used.
<ide>
<ide> """
<add> assert task_name not in self.buckets
<ide> task_type = self.task_registry[task_name]
<ide> task_queue = Queue()
<ide> rate_limit = getattr(task_type, "rate_limit", None) | 1 |
Text | Text | fix some flaws in man | 877e6d76a4f16a1825a1e98cbfa9f5fef7a60c59 | <ide><path>man/docker-cp.1.md
<ide> You can copy from the container's file system to the local machine or the
<ide> reverse, from the local filesystem to the container. If `-` is specified for
<ide> either the `SRC_PATH` or `DEST_PATH`, you can also stream a tar archive from
<ide> `STDIN` or to `STDOUT`. The `CONTAINER` can be a running or stopped container.
<del>The `SRC_PATH` or `DEST_PATH` be a file or directory.
<add>The `SRC_PATH` or `DEST_PATH` can be a file or directory.
<ide>
<ide> The `docker cp` command assumes container paths are relative to the container's
<ide> `/` (root) directory. This means supplying the initial forward slash is optional;
<ide> It is not possible to copy certain system files such as resources under
<ide> Using `-` as the `SRC_PATH` streams the contents of `STDIN` as a tar archive.
<ide> The command extracts the content of the tar to the `DEST_PATH` in container's
<ide> filesystem. In this case, `DEST_PATH` must specify a directory. Using `-` as
<del>`DEST_PATH` streams the contents of the resource as a tar archive to `STDOUT`.
<add>the `DEST_PATH` streams the contents of the resource as a tar archive to `STDOUT`.
<ide>
<ide> # OPTIONS
<ide> **-L**, **--follow-link**=*true*|*false*
<ide><path>man/docker-events.1.md
<ide> and Docker images will report:
<ide>
<ide> The `--since` and `--until` parameters can be Unix timestamps, date formatted
<ide> timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed
<del>relative to the client machine’s time. If you do not provide the --since option,
<add>relative to the client machine’s time. If you do not provide the `--since` option,
<ide> the command returns only new and/or live events. Supported formats for date
<ide> formatted time stamps include RFC3339Nano, RFC3339, `2006-01-02T15:04:05`,
<ide> `2006-01-02T15:04:05.999999999`, `2006-01-02Z07:00`, and `2006-01-02`. The local
<ide><path>man/docker-import.1.md
<ide> Import to docker via pipe and stdin:
<ide>
<ide> # cat exampleimage.tgz | docker import - example/imagelocal
<ide>
<del>Import with a commit message
<add>Import with a commit message.
<ide>
<ide> # cat exampleimage.tgz | docker import --message "New image imported from tarball" - exampleimagelocal:new
<ide>
<ide><path>man/docker-network-ls.1.md
<ide> NETWORK ID NAME DRIVER
<ide> You can also filter for a substring in a name as this shows:
<ide>
<ide> ```bash
<del>$ docker ps --filter name=foo
<add>$ docker network ls --filter name=foo
<ide> NETWORK ID NAME DRIVER
<ide> 95e74588f40d foo bridge
<ide> 06e7eef0a170 foobar bridge
<ide> NETWORK ID NAME DRIVER
<ide>
<ide> The `id` filter matches on all or part of a network's ID.
<ide>
<del>The following filter matches all networks with a name containing the
<del>`06e7eef01700` string.
<add>The following filter matches all networks with an ID containing the
<add>`63d1ff1f77b0...` string.
<ide>
<ide> ```bash
<ide> $ docker network ls --filter id=63d1ff1f77b07ca51070a8c227e962238358bd310bde1529cf62e6c307ade161
<ide> NETWORK ID NAME DRIVER
<ide> 63d1ff1f77b0 dev bridge
<ide> ```
<ide>
<del>You can also filter for a substring in a ID as this shows:
<add>You can also filter for a substring in an ID as this shows:
<ide>
<ide> ```bash
<del>$ docker ps --filter id=95e74588f40d
<add>$ docker network ls --filter id=95e74588f40d
<ide> NETWORK ID NAME DRIVER
<ide> 95e74588f40d foo bridge
<ide>
<del>$ docker ps --filter id=95e
<add>$ docker network ls --filter id=95e
<ide> NETWORK ID NAME DRIVER
<ide> 95e74588f40d foo bridge
<ide> ```
<ide><path>man/docker-network-rm.1.md
<ide> To remove the network named 'my-network':
<ide> ```
<ide>
<ide> To delete multiple networks in a single `docker network rm` command, provide
<del>multiple network names or id's. The following example deletes a network with id
<add>multiple network names or ids. The following example deletes a network with id
<ide> `3695c422697f` and a network named `my-network`:
<ide>
<ide> ```bash
<ide><path>man/docker-rm.1.md
<ide> command. The use that name as follows:
<ide>
<ide> ## Removing a container and all associated volumes
<ide>
<del> $ docker rm -v redis
<del> redis
<add> $ docker rm -v redis
<add> redis
<ide>
<ide> This command will remove the container and any volumes associated with it.
<ide> Note that if a volume was specified with a name, it will not be removed.
<ide>
<del> $ docker create -v awesome:/foo -v /bar --name hello redis
<del> hello
<del> $ docker rm -v hello
<add> $ docker create -v awesome:/foo -v /bar --name hello redis
<add> hello
<add> $ docker rm -v hello
<ide>
<ide> In this example, the volume for `/foo` will remain in tact, but the volume for
<ide> `/bar` will be removed. The same behavior holds for volumes inherited with | 6 |
Text | Text | add dead state to container inspect 1.21 api | 836d0127fdf39d5e5978bc27f54a99aea636061b | <ide><path>docs/reference/api/docker_remote_api_v1.22.md
<ide> Return low-level information on the container `id`
<ide> "ExitCode": 9,
<ide> "FinishedAt": "2015-01-06T15:47:32.080254511Z",
<ide> "OOMKilled": false,
<add> "Dead": false,
<ide> "Paused": false,
<ide> "Pid": 0,
<ide> "Restarting": false, | 1 |
Text | Text | add docs for `display_value` | 66ae19229e8e0d1f99c21501e821facfb5d0566d | <ide><path>docs/api-guide/relations.md
<ide> If you explicitly specify a relational field pointing to a
<ide> ``ManyToManyField`` with a through model, be sure to set ``read_only``
<ide> to ``True``.
<ide>
<add>## The `display_value` method
<add>
<add>The `__str__` (`__unicode__` on Python 2) method of the model will be called to generate string representations of the objects used to populate the `choices` property. To provide customized representations, override `display_value` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example:
<add>
<add> class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
<add> def display_value(self, instance):
<add> return 'Track: %s' % (instance.title)
<add>
<ide> ---
<ide>
<ide> # Third Party Packages | 1 |
Text | Text | add misc note about localization | 8ba4e7bafe07a3267fd8baedb3d94986c4f26af4 | <ide><path>docs/topics/3.0-announcement.md
<ide> The default JSON renderer will return float objects for un-coerced `Decimal` ins
<ide>
<ide> * The serializer `ChoiceField` does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.
<ide> * Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.
<add>* Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still [create language files with Django][django-localization] if you wish to localize them.
<ide>
<ide> ---
<ide>
<ide> You can follow development on the GitHub site, where we use [milestones to indic
<ide> [kickstarter]: http://kickstarter.com/projects/tomchristie/django-rest-framework-3
<ide> [sponsors]: http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors
<ide> [mixins.py]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py
<add>[django-localization]: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#localization-how-to-create-language-files | 1 |
Javascript | Javascript | fix == to === | bfdf0c9590d239adf20bfb771f7bcddd1429f0bb | <ide><path>examples/js/loaders/SVGLoader.js
<ide> THREE.SVGLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype
<ide>
<ide> function getNodeTransform( node ) {
<ide>
<del> if ( ! ( node.hasAttribute( 'transform' ) || ( node.nodeName == 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) ) ) {
<add> if ( ! ( node.hasAttribute( 'transform' ) || ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) ) ) {
<ide>
<ide> return null;
<ide>
<ide> THREE.SVGLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype
<ide> var transform = new Matrix3();
<ide> var currentTransform = tempTransform0;
<ide>
<del> if ( node.nodeName == 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) {
<add> if ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) {
<ide>
<ide> var tx = parseFloatWithUnits( node.getAttribute( 'x' ) );
<ide> var ty = parseFloatWithUnits( node.getAttribute( 'y' ) ); | 1 |
Javascript | Javascript | add implicit declaration | cb908242866321e223ccd473d38657382a8e2909 | <ide><path>examples/js/postprocessing/ShaderPass.js
<ide> * @author alteredq / http://alteredqualia.com/
<ide> */
<ide>
<del>THREE.ShaderPass = function ( shader, textureID ) {
<add>THREE.ShaderPass = function( shader, textureID ) {
<ide>
<ide> this.textureID = ( textureID !== undefined ) ? textureID : "tDiffuse";
<ide>
<del> this.uniforms = THREE.UniformsUtils.clone( shader.uniforms );
<add> if ( shader instanceof THREE.ShaderMaterial ) {
<ide>
<del> this.material = new THREE.ShaderMaterial( {
<add> this.uniforms = shader.uniforms;
<ide>
<del> defines: shader.defines || {},
<del> uniforms: this.uniforms,
<del> vertexShader: shader.vertexShader,
<del> fragmentShader: shader.fragmentShader
<add> this.material = shader;
<ide>
<del> } );
<add> }
<add> else if ( shader ) {
<add>
<add> this.uniforms = THREE.UniformsUtils.clone( shader.uniforms );
<add>
<add> this.material = new THREE.ShaderMaterial( {
<add>
<add> defines: shader.defines || {},
<add> uniforms: this.uniforms,
<add> vertexShader: shader.vertexShader,
<add> fragmentShader: shader.fragmentShader
<add>
<add> } );
<add>
<add> }
<ide>
<ide> this.renderToScreen = false;
<ide>
<ide> THREE.ShaderPass = function ( shader, textureID ) {
<ide>
<ide>
<ide> this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
<del> this.scene = new THREE.Scene();
<add> this.scene = new THREE.Scene();
<ide>
<ide> this.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), null );
<ide> this.scene.add( this.quad );
<ide> THREE.ShaderPass = function ( shader, textureID ) {
<ide>
<ide> THREE.ShaderPass.prototype = {
<ide>
<del> render: function ( renderer, writeBuffer, readBuffer, delta ) {
<add> render: function( renderer, writeBuffer, readBuffer, delta ) {
<ide>
<ide> if ( this.uniforms[ this.textureID ] ) {
<ide> | 1 |
Java | Java | fix assert.instanceof exception message | 7bbb4ec7aff9ca171f2d34f747d7e0d96a6ce1b0 | <ide><path>spring-core/src/main/java/org/springframework/util/Assert.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License"); you may not
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> public static void isInstanceOf(Class clazz, Object obj) {
<ide> public static void isInstanceOf(Class type, Object obj, String message) {
<ide> notNull(type, "Type to check against must not be null");
<ide> if (!type.isInstance(obj)) {
<del> throw new IllegalArgumentException(message +
<del> ". Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
<add> throw new IllegalArgumentException(
<add> (StringUtils.hasLength(message) ? message + " " : "") +
<add> "Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
<ide> "] must be an instance of " + type);
<ide> }
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/util/AssertTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<add>import org.junit.Rule;
<ide> import org.junit.Test;
<add>import org.junit.rules.ExpectedException;
<ide>
<ide> /**
<ide> * Unit tests for the {@link Assert} class.
<ide> */
<ide> public class AssertTests {
<ide>
<add> @Rule
<add> public ExpectedException thrown = ExpectedException.none();
<add>
<ide> @Test(expected = IllegalArgumentException.class)
<ide> public void instanceOf() {
<ide> final Set<?> set = new HashSet<Object>();
<ide> Assert.isInstanceOf(HashSet.class, set);
<ide> Assert.isInstanceOf(HashMap.class, set);
<ide> }
<ide>
<add> @Test
<add> public void instanceOfNoMessage() throws Exception {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Object of class [java.lang.Object] must be an instance " +
<add> "of interface java.util.Set");
<add> Assert.isInstanceOf(Set.class, new Object(), null);
<add> }
<add>
<add> @Test
<add> public void instanceOfMessage() throws Exception {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Custom message. Object of class [java.lang.Object] must " +
<add> "be an instance of interface java.util.Set");
<add> Assert.isInstanceOf(Set.class, new Object(), "Custom message.");
<add> }
<add>
<ide> @Test
<ide> public void isNullDoesNotThrowExceptionIfArgumentIsNullWithMessage() {
<ide> Assert.isNull(null, "Bla"); | 2 |
PHP | PHP | pull url from config | 126adb781c204129600363f243b9d73e202d229e | <ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php
<ide> protected function prepareUrlForRequest($uri)
<ide> }
<ide>
<ide> if (! Str::startsWith($uri, 'http')) {
<del> $uri = $this->baseUrl.'/'.$uri;
<add> $uri = config('app.url').'/'.$uri;
<ide> }
<ide>
<ide> return trim($uri, '/'); | 1 |
Python | Python | fix incorrect usage of optional[bool] | e3f96ce7a8ac098aeef5e9930e6de6c428274d57 | <ide><path>airflow/models/dagrun.py
<ide> def find(
<ide> execution_date: Optional[datetime] = None,
<ide> state: Optional[str] = None,
<ide> external_trigger: Optional[bool] = None,
<del> no_backfills: Optional[bool] = False,
<add> no_backfills: bool = False,
<ide> run_type: Optional[DagRunType] = None,
<ide> session: Session = None,
<ide> execution_start_date: Optional[datetime] = None,
<ide><path>airflow/models/taskinstance.py
<ide> def command_as_list( # pylint: disable=too-many-arguments
<ide> def generate_command(dag_id: str, # pylint: disable=too-many-arguments
<ide> task_id: str,
<ide> execution_date: datetime,
<del> mark_success: Optional[bool] = False,
<del> ignore_all_deps: Optional[bool] = False,
<del> ignore_depends_on_past: Optional[bool] = False,
<del> ignore_task_deps: Optional[bool] = False,
<del> ignore_ti_state: Optional[bool] = False,
<del> local: Optional[bool] = False,
<add> mark_success: bool = False,
<add> ignore_all_deps: bool = False,
<add> ignore_depends_on_past: bool = False,
<add> ignore_task_deps: bool = False,
<add> ignore_ti_state: bool = False,
<add> local: bool = False,
<ide> pickle_id: Optional[int] = None,
<ide> file_path: Optional[str] = None,
<del> raw: Optional[bool] = False,
<add> raw: bool = False,
<ide> job_id: Optional[str] = None,
<ide> pool: Optional[str] = None,
<ide> cfg_path: Optional[str] = None
<ide> def generate_command(dag_id: str, # pylint: disable=too-many-arguments
<ide> :param execution_date: Execution date for the task
<ide> :type execution_date: datetime
<ide> :param mark_success: Whether to mark the task as successful
<del> :type mark_success: Optional[bool]
<add> :type mark_success: bool
<ide> :param ignore_all_deps: Ignore all ignorable dependencies.
<ide> Overrides the other ignore_* parameters.
<del> :type ignore_all_deps: Optional[bool]
<add> :type ignore_all_deps: bool
<ide> :param ignore_depends_on_past: Ignore depends_on_past parameter of DAGs
<ide> (e.g. for Backfills)
<del> :type ignore_depends_on_past: Optional[bool]
<add> :type ignore_depends_on_past: bool
<ide> :param ignore_task_deps: Ignore task-specific dependencies such as depends_on_past
<ide> and trigger rule
<del> :type ignore_task_deps: Optional[bool]
<add> :type ignore_task_deps: bool
<ide> :param ignore_ti_state: Ignore the task instance's previous failure/success
<del> :type ignore_ti_state: Optional[bool]
<add> :type ignore_ti_state: bool
<ide> :param local: Whether to run the task locally
<del> :type local: Optional[bool]
<add> :type local: bool
<ide> :param pickle_id: If the DAG was serialized to the DB, the ID
<ide> associated with the pickled DAG
<ide> :type pickle_id: Optional[int]
<ide><path>airflow/operators/sql.py
<ide> def __init__(
<ide> date_filter_column: Optional[str] = "ds",
<ide> days_back: SupportsAbs[int] = -7,
<ide> ratio_formula: Optional[str] = "max_over_min",
<del> ignore_zero: Optional[bool] = True,
<add> ignore_zero: bool = True,
<ide> conn_id: Optional[str] = None,
<ide> **kwargs,
<ide> ):
<ide><path>airflow/providers/amazon/aws/operators/s3_bucket.py
<ide> class S3DeleteBucketOperator(BaseOperator):
<ide> def __init__(
<ide> self,
<ide> bucket_name,
<del> force_delete: Optional[bool] = False,
<add> force_delete: bool = False,
<ide> aws_conn_id: Optional[str] = "aws_default",
<ide> **kwargs,
<ide> ) -> None:
<ide><path>airflow/providers/amazon/aws/transfers/mysql_to_s3.py
<ide> def __init__(
<ide> aws_conn_id: str = 'aws_default',
<ide> verify: Optional[Union[bool, str]] = None,
<ide> pd_csv_kwargs: Optional[dict] = None,
<del> index: Optional[bool] = False,
<del> header: Optional[bool] = False,
<add> index: bool = False,
<add> header: bool = False,
<ide> **kwargs,
<ide> ) -> None:
<ide> super().__init__(**kwargs)
<ide><path>airflow/providers/apache/hive/hooks/hive.py
<ide> def run_cli(
<ide> self,
<ide> hql: Union[str, Text],
<ide> schema: Optional[str] = None,
<del> verbose: Optional[bool] = True,
<add> verbose: bool = True,
<ide> hive_conf: Optional[Dict[Any, Any]] = None,
<ide> ) -> Any:
<ide> """
<ide><path>airflow/providers/apache/kylin/operators/kylin_cube.py
<ide> def __init__(
<ide> offset_start: Optional[str] = None,
<ide> offset_end: Optional[str] = None,
<ide> segment_name: Optional[str] = None,
<del> is_track_job: Optional[bool] = False,
<add> is_track_job: bool = False,
<ide> interval: int = 60,
<ide> timeout: int = 60 * 60 * 24,
<ide> eager_error_status=("ERROR", "DISCARDED", "KILLED", "SUICIDAL", "STOPPED"),
<ide><path>airflow/providers/apache/pinot/hooks/pinot.py
<ide> def __init__(
<ide> def get_conn(self) -> Any:
<ide> return self.conn
<ide>
<del> def add_schema(self, schema_file: str, with_exec: Optional[bool] = True) -> Any:
<add> def add_schema(self, schema_file: str, with_exec: bool = True) -> Any:
<ide> """
<ide> Add Pinot schema by run AddSchema command
<ide>
<ide> :param schema_file: Pinot schema file
<ide> :type schema_file: str
<ide> :param with_exec: bool
<del> :type with_exec: Optional[bool]
<add> :type with_exec: bool
<ide> """
<ide> cmd = ["AddSchema"]
<ide> cmd += ["-controllerHost", self.host]
<ide> def add_schema(self, schema_file: str, with_exec: Optional[bool] = True) -> Any:
<ide> cmd += ["-exec"]
<ide> self.run_cli(cmd)
<ide>
<del> def add_table(self, file_path: str, with_exec: Optional[bool] = True) -> Any:
<add> def add_table(self, file_path: str, with_exec: bool = True) -> Any:
<ide> """
<ide> Add Pinot table with run AddTable command
<ide>
<ide> :param file_path: Pinot table configure file
<ide> :type file_path: str
<ide> :param with_exec: bool
<del> :type with_exec: Optional[bool]
<add> :type with_exec: bool
<ide> """
<ide> cmd = ["AddTable"]
<ide> cmd += ["-controllerHost", self.host]
<ide> def upload_segment(self, segment_dir: str, table_name: Optional[str] = None) ->
<ide> cmd += ["-tableName", table_name]
<ide> self.run_cli(cmd)
<ide>
<del> def run_cli(self, cmd: List[str], verbose: Optional[bool] = True) -> str:
<add> def run_cli(self, cmd: List[str], verbose: bool = True) -> str:
<ide> """
<ide> Run command with pinot-admin.sh
<ide>
<ide> :param cmd: List of command going to be run by pinot-admin.sh script
<ide> :type cmd: list
<ide> :param verbose:
<del> :type verbose: Optional[bool]
<add> :type verbose: bool
<ide> """
<ide> command = [self.cmd_path]
<ide> command.extend(cmd)
<ide><path>airflow/providers/cncf/kubernetes/sensors/spark_kubernetes.py
<ide> def __init__(
<ide> self,
<ide> *,
<ide> application_name: str,
<del> attach_log: Optional[bool] = False,
<add> attach_log: bool = False,
<ide> namespace: Optional[str] = None,
<ide> kubernetes_conn_id: str = "kubernetes_default",
<ide> **kwargs,
<ide><path>airflow/providers/docker/operators/docker.py
<ide> def __init__(
<ide> dns_search: Optional[List[str]] = None,
<ide> auto_remove: bool = False,
<ide> shm_size: Optional[int] = None,
<del> tty: Optional[bool] = False,
<add> tty: bool = False,
<ide> cap_add: Optional[Iterable[str]] = None,
<ide> extra_hosts: Optional[Dict[str, str]] = None,
<ide> **kwargs,
<ide><path>airflow/providers/google/cloud/operators/bigquery.py
<ide> def __init__(
<ide> sql: Union[str, Iterable],
<ide> destination_dataset_table: Optional[str] = None,
<ide> write_disposition: Optional[str] = 'WRITE_EMPTY',
<del> allow_large_results: Optional[bool] = False,
<add> allow_large_results: bool = False,
<ide> flatten_results: Optional[bool] = None,
<ide> gcp_conn_id: Optional[str] = 'google_cloud_default',
<ide> bigquery_conn_id: Optional[str] = None,
<ide> delegate_to: Optional[str] = None,
<ide> udf_config: Optional[list] = None,
<del> use_legacy_sql: Optional[bool] = True,
<add> use_legacy_sql: bool = True,
<ide> maximum_billing_tier: Optional[int] = None,
<ide> maximum_bytes_billed: Optional[float] = None,
<ide> create_disposition: Optional[str] = 'CREATE_IF_NEEDED', | 11 |
PHP | PHP | remove dead code in test stub | 66c2b2528073367d5244435c06d32a8dcdf0566b | <ide><path>tests/test_app/TestApp/Controller/Component/AppleComponent.php
<ide> class AppleComponent extends Component {
<ide> */
<ide> public $components = array('Orange');
<ide>
<del>/**
<del> * testName property
<del> *
<del> * @var mixed
<del> */
<del> public $testName = null;
<del>
<ide> /**
<ide> * startup method
<ide> *
<ide> class AppleComponent extends Component {
<ide> * @return void
<ide> */
<ide> public function startup(Event $event) {
<del> $this->testName = $controller->name;
<ide> }
<ide> } | 1 |
Text | Text | add tutorial link in docs | f0175de8296069c6c5c6e36c145da641f7aa5bc0 | <ide><path>docs/templates/why-use-keras.md
<ide> Keras has also been adopted by researchers at large scientific organizations, in
<ide>
<ide> Your Keras models can be easily deployed across a greater range of platforms than any other deep learning framework:
<ide>
<del>- On iOS, via [Apple’s CoreML](https://developer.apple.com/documentation/coreml) (Keras support officially provided by Apple)
<del>- On Android, via the TensorFlow Android runtime. Example: [Not Hotdog app](https://medium.com/@timanglade/how-hbos-silicon-valley-built-not-hotdog-with-mobile-tensorflow-keras-react-native-ef03260747f3)
<del>- In the browser, via GPU-accelerated JavaScript runtimes such as [Keras.js](https://transcranial.github.io/keras-js/#/) and [WebDNN](https://mil-tokyo.github.io/webdnn/)
<del>- On Google Cloud, via [TensorFlow-Serving](https://www.tensorflow.org/serving/)
<del>- [In a Python webapp backend (such as a Flask app)](https://blog.keras.io/building-a-simple-keras-deep-learning-rest-api.html)
<del>- On the JVM, via [DL4J model import provided by SkyMind](https://deeplearning4j.org/model-import-keras)
<del>- On Raspberry Pi
<add>- On iOS, via [Apple’s CoreML](https://developer.apple.com/documentation/coreml) (Keras support officially provided by Apple). Here's [a tutorial](https://www.pyimagesearch.com/2018/04/23/running-keras-models-on-ios-with-coreml/).
<add>- On Android, via the TensorFlow Android runtime. Example: [Not Hotdog app](https://medium.com/@timanglade/how-hbos-silicon-valley-built-not-hotdog-with-mobile-tensorflow-keras-react-native-ef03260747f3).
<add>- In the browser, via GPU-accelerated JavaScript runtimes such as [Keras.js](https://transcranial.github.io/keras-js/#/) and [WebDNN](https://mil-tokyo.github.io/webdnn/).
<add>- On Google Cloud, via [TensorFlow-Serving](https://www.tensorflow.org/serving/).
<add>- [In a Python webapp backend (such as a Flask app)](https://blog.keras.io/building-a-simple-keras-deep-learning-rest-api.html).
<add>- On the JVM, via [DL4J model import provided by SkyMind](https://deeplearning4j.org/model-import-keras).
<add>- On Raspberry Pi.
<ide>
<ide> ---
<ide> | 1 |
Python | Python | fix auto-naming in records.py | c0c1bea69b11881bebf483ce0c961812a27f061c | <ide><path>numpy/core/records.py
<ide> def _setfieldnames(self, names, titles):
<ide> else:
<ide> self._names = []
<ide>
<del> # if the names are not specified, they will be assigned as "f1, f2,..."
<del> # if not enough names are specified, they will be assigned as "f[n+1],
<del> # f[n+2],..." etc. where n is the number of specified names..."
<del> self._names += ['f%d' % i for i in range(len(self._names)+1,
<del> self._nfields+1)]
<add> # if the names are not specified, they will be assigned as
<add> # "f0, f1, f2,..."
<add> # if not enough names are specified, they will be assigned as "f[n],
<add> # f[n+1],..." etc. where n is the number of specified names..."
<add> self._names += ['f%d' % i for i in range(len(self._names),
<add> self._nfields)]
<ide> # check for redundant names
<ide> _dup = find_duplicate(self._names)
<ide> if _dup: | 1 |
Text | Text | add legacy status to stability index | a8d05ba2535d05ac1f1d74c183d4b7b1206f6fcf | <ide><path>doc/api/documentation.md
<ide> The stability indices are as follows:
<ide> > Stability: 2 - Stable. Compatibility with the npm ecosystem is a high
<ide> > priority.
<ide>
<add><!-- separator -->
<add>
<add>> Stability: 3 - Legacy. The feature is no longer recommended for use. While it
<add>likely will not be removed, and is still covered by semantic-versioning
<add>guarantees, use of the feature should be avoided.
<add>
<ide> Use caution when making use of Experimental features, particularly within
<ide> modules. Users may not be aware that experimental features are being used.
<ide> Bugs or behavior changes may surprise users when Experimental API | 1 |
Python | Python | add a timeout (7 secondes) on client connection | 81caa9de82b018db32af0c4ba4096b4917878f85 | <ide><path>glances/core/glances_client.py
<ide> import socket
<ide> import sys
<ide> try:
<del> from xmlrpc.client import ServerProxy, ProtocolError, Fault
<add> from xmlrpc.client import Transport, ServerProxy, ProtocolError, Fault
<ide> except ImportError: # Python 2
<del> from xmlrpclib import ServerProxy, ProtocolError, Fault
<add> from xmlrpclib import Transport, ServerProxy, ProtocolError, Fault
<add>import httplib
<ide>
<ide> # Import Glances libs
<ide> from glances.core.glances_globals import version, logger
<ide> from glances.core.glances_stats import GlancesStatsClient
<ide> from glances.outputs.glances_curses import GlancesCurses
<ide>
<ide>
<del>class GlancesClient(object):
<add>class GlancesClientTransport(Transport):
<add> """This class overwrite the default XML-RPC transport and manage timeout"""
<add>
<add> def set_timeout(self, timeout):
<add> self.timeout = timeout
<add>
<add> def make_connection(self, host):
<add> return httplib.HTTPConnection(host, timeout=self.timeout)
<ide>
<add>
<add>class GlancesClient(object):
<ide> """This class creates and manages the TCP client."""
<ide>
<ide> def __init__(self, config=None, args=None):
<ide> def __init__(self, config=None, args=None):
<ide> uri = 'http://{0}:{1}'.format(args.client, args.port)
<ide>
<ide> # Try to connect to the URI
<add> transport = GlancesClientTransport()
<add> transport.set_timeout(5)
<ide> try:
<del> self.client = ServerProxy(uri)
<add> self.client = ServerProxy(uri, transport = transport)
<ide> except Exception as e:
<ide> logger.error(_("Couldn't create socket {0}: {1}").format(uri, e))
<ide> sys.exit(2)
<ide> def login(self):
<ide> if not self.args.snmp_force:
<ide> # First of all, trying to connect to a Glances server
<ide> self.set_mode('glances')
<add> client_version = None
<ide> try:
<ide> client_version = self.client.init()
<ide> except socket.error as err:
<ide> def login(self):
<ide> self.set_mode('snmp')
<ide> fallbackmsg = _("Trying fallback to SNMP...")
<ide> print(fallbackmsg)
<del> logger.info(fallbackmsg)
<ide> except ProtocolError as err:
<ide> # Others errors
<ide> if str(err).find(" 401 ") > 0:
<ide> def login(self):
<ide> # Init stats
<ide> self.stats = GlancesStatsClient()
<ide> self.stats.set_plugins(json.loads(self.client.getAllPlugins()))
<add> else:
<add> logger.error("Client version: %s / Server version: %s" % (version, client_version))
<add>
<ide> else:
<ide> self.set_mode('snmp')
<del> logger.info(_("Trying to grab stats by SNMP..."))
<ide>
<ide> if self.get_mode() == 'snmp':
<add> logger.info(_("Trying to grab stats by SNMP..."))
<ide> # Fallback to SNMP if needed
<ide> from glances.core.glances_stats import GlancesStatsClientSNMP
<ide>
<ide> def login(self):
<ide> if not self.stats.check_snmp():
<ide> logger.error(_("Connection to SNMP server failed"))
<ide> sys.exit(2)
<del> else:
<del> # Unknow mode...
<del> ret = False
<ide>
<ide> if ret:
<ide> # Load limits from the configuration file | 1 |
Javascript | Javascript | fix typo in rails-ujs html content test | e06b67205072e39ac02e5467b71c600167fa9435 | <ide><path>actionview/test/ujs/public/test/call-remote.js
<ide> asyncTest('HTML content should be plain-text', 1, function() {
<ide> $('form').append('<input type="text" name="content" value="<p>hello</p>">')
<ide>
<ide> submit(function(e, data, status, xhr) {
<del> ok(data === '<p>hello</ps>', 'returned data should be a plain-text string')
<add> ok(data === '<p>hello</p>', 'returned data should be a plain-text string')
<ide> })
<ide> })
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 27bb66632aa805a88474e4f8694864a6c7d4a5d6 | <ide><path>src/Illuminate/Routing/Controller.php
<ide> public function callAction($method, $parameters)
<ide> */
<ide> public function __call($method, $parameters)
<ide> {
<del> throw new BadMethodCallException("Method [{$method}] does not exist on [".get_class($this)."].");
<add> throw new BadMethodCallException("Method [{$method}] does not exist on [".get_class($this).'].');
<ide> }
<ide> } | 1 |
Text | Text | add nvidia bert | 4c71470d8b204a09f010cf5ba38a2d489e01f73f | <ide><path>community/README.md
<ide> This repository provides a curated list of the GitHub repositories with machine
<ide> | [Transformer-LT (MLPerf)](https://github.com/IntelAI/models/tree/master/benchmarks/language_translation/tensorflow/transformer_mlperf) | [Attention Is All You Need](https://arxiv.org/pdf/1706.03762) | • FP32 Training | [Intel](https://github.com/IntelAI) |
<ide> | [Transformer-LT (Official)](https://github.com/IntelAI/models/tree/master/benchmarks/language_translation/tensorflow/transformer_lt_official) | [Attention Is All You Need](https://arxiv.org/pdf/1706.03762) | • FP32 Inference | [Intel](https://github.com/IntelAI) |
<ide> | [ELECTRA](https://github.com/NVIDIA/DeepLearningExamples/tree/master/TensorFlow2/LanguageModeling/ELECTRA) | [ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators](https://openreview.net/forum?id=r1xMH1BtvB) | • Automatic Mixed Precision<br/>• Multi-GPU training support with Horovod<br/>• Multi-node training on a Pyxis/Enroot Slurm cluster | [NVIDIA](https://github.com/NVIDIA) |
<add>| [BERT](https://github.com/NVIDIA/DeepLearningExamples/tree/master/TensorFlow2/LanguageModeling/BERT) | [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/pdf/1810.04805) | • Horovod Multi-GPU<br/>• Multi-node with Horovod and Pyxis/Enroot Slurm cluster<br/>• XLA<br/>• Automatic mixed precision<br/>• LAMB | [NVIDIA](https://github.com/NVIDIA) |
<add>
<ide>
<ide> ## Recommendation Systems
<ide> | 1 |
PHP | PHP | finish another block of link tag updates | dfda9e8ab3449fb203a4f2a0f3bfe044554a13bc | <ide><path>src/Error/Debugger.php
<ide> public static function dump($var, $depth = 3) {
<ide> * @param int|string $level type of log to use. Defaults to 'debug'
<ide> * @param int $depth The depth to output to. Defaults to 3.
<ide> * @return void
<del> * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::log
<ide> */
<ide> public static function log($var, $level = 'debug', $depth = 3) {
<ide> $source = static::trace(array('start' => 1)) . "\n";
<ide><path>src/I18n/Number.php
<ide> *
<ide> * Methods to make numbers more readable.
<ide> *
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/number.html
<ide> */
<ide> class Number {
<ide>
<ide> class Number {
<ide> * @param float $value A floating point number.
<ide> * @param int $precision The precision of the returned number.
<ide> * @return string Formatted float.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/number.html#formatting-floating-point-numbers
<ide> */
<ide> public static function precision($value, $precision = 3) {
<ide> $formatter = static::formatter(['precision' => $precision, 'places' => $precision]);
<ide> public static function precision($value, $precision = 3) {
<ide> *
<ide> * @param int $size Size in bytes
<ide> * @return string Human readable size
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/number.html#interacting-with-human-readable-values
<ide> */
<ide> public static function toReadableSize($size) {
<ide> switch (true) {
<ide> public static function toReadableSize($size) {
<ide> * @param int $precision The precision of the returned number
<ide> * @param array $options Options
<ide> * @return string Percentage string
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/number.html#formatting-percentages
<ide> */
<ide> public static function toPercentage($value, $precision = 2, array $options = array()) {
<ide> $options += array('multiply' => false);
<ide><path>src/I18n/Time.php
<ide> public function __toString() {
<ide> * @param bool $group If true (default value) groups the identifiers list by primary region
<ide> * @return array List of timezone identifiers
<ide> * @since 2.2
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::listTimezones
<ide> */
<ide> public static function listTimezones($filter = null, $country = null, $group = true) {
<ide> $regex = null;
<ide><path>src/Network/Exception/BadRequestException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Network/Exception/ForbiddenException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Network/Exception/HttpException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Network/Exception/InternalErrorException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Network/Exception/MethodNotAllowedException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Network/Exception/NotFoundException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Network/Exception/NotImplementedException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Network/Exception/SocketException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Network/Exception/UnauthorizedException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/ORM/Exception/MissingBehaviorException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Routing/Exception/MissingControllerException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Routing/Exception/MissingDispatcherFilterException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Routing/Exception/MissingRouteException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Shell/ServerShell.php
<ide> public function initialize() {
<ide> * or otherwise modify the pre-command flow.
<ide> *
<ide> * @return void
<del> * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::startup
<add> * @link http://book.cakephp.org/3.0/en/console-and-shells.html#hook-methods
<ide> */
<ide> public function startup() {
<ide> if (!empty($this->params['host'])) {
<ide><path>src/Shell/TestShell.php
<ide> * Redistributions of files must retain the above copyright notice
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 1.2.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/TestSuite/ControllerTestCase.php
<ide> * Redistributions of files must retain the above copyright notice
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<ide> * @since 2.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/TestSuite/Fixture/TestFixture.php
<ide> * Redistributions of files must retain the above copyright notice
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<ide> * @since 1.2.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> * Redistributions of files must retain the above copyright notice
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/TestSuite/Stub/Response.php
<ide> * Redistributions of files must retain the above copyright notice
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/TestSuite/TestCase.php
<ide> * Redistributions of files must retain the above copyright notice
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<ide> * @since 1.2.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Utility/Exception/XmlException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/Utility/Hash.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://cakephp.org CakePHP(tm) Project
<ide> * @since 2.2.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> * support for pseudo Xpath, its more fully featured dot notation provides
<ide> * similar features in a more consistent implementation.
<ide> *
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html
<ide> */
<ide> class Hash {
<ide>
<ide> class Hash {
<ide> * @param mixed $default The return value when the path does not exist
<ide> * @throws \InvalidArgumentException
<ide> * @return mixed The value fetched from the array, or null.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::get
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::get
<ide> */
<ide> public static function get(array $data, $path, $default = null) {
<ide> if (empty($data)) {
<ide> public static function get(array $data, $path, $default = null) {
<ide> * @param string $path The path to extract.
<ide> * @return array An array of the extracted values. Returns an empty array
<ide> * if there are no matches.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::extract
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::extract
<ide> */
<ide> public static function extract(array $data, $path) {
<ide> if (empty($path)) {
<ide> protected static function _matches(array $data, $selector) {
<ide> * @param string $path The path to insert at.
<ide> * @param array $values The values to insert.
<ide> * @return array The data with $values inserted.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::insert
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::insert
<ide> */
<ide> public static function insert(array $data, $path, $values = null) {
<ide> $noTokens = strpos($path, '[') === false;
<ide> protected static function _simpleOp($op, $data, $path, $values = null) {
<ide> * @param array $data The data to operate on
<ide> * @param string $path A path expression to use to remove.
<ide> * @return array The modified array.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::remove
<add> * @link http://book.cakephp.org/3.0/en/core--libraries/hash.html#Hash::remove
<ide> */
<ide> public static function remove(array $data, $path) {
<ide> $noTokens = strpos($path, '[') === false;
<ide> public static function remove(array $data, $path) {
<ide> * @param string $valuePath A dot-separated string.
<ide> * @param string $groupPath A dot-separated string.
<ide> * @return array Combined array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::combine
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::combine
<ide> * @throws \RuntimeException When keys and values count is unequal.
<ide> */
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupPath = null) {
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupP
<ide> * @param array $paths An array containing one or more Hash::extract()-style key paths
<ide> * @param string $format Format string into which values will be inserted, see sprintf()
<ide> * @return array An array of strings extracted from `$path` and formatted with `$format`
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::format
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::format
<ide> * @see sprintf()
<ide> * @see Hash::extract()
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::format
<ide> */
<ide> public static function format(array $data, array $paths, $format) {
<ide> $extracted = array();
<ide> public static function format(array $data, array $paths, $format) {
<ide> * @param array $data The data to search through.
<ide> * @param array $needle The values to file in $data
<ide> * @return bool true if $data contains $needle, false otherwise
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::contains
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::contains
<ide> */
<ide> public static function contains(array $data, array $needle) {
<ide> if (empty($data) || empty($needle)) {
<ide> public static function contains(array $data, array $needle) {
<ide> * @param string $path The path to check for.
<ide> * @return bool Existence of path.
<ide> * @see Hash::extract()
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::check
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::check
<ide> */
<ide> public static function check(array $data, $path) {
<ide> $results = static::extract($data, $path);
<ide> public static function check(array $data, $path) {
<ide> * @param callable $callback A function to filter the data with. Defaults to
<ide> * `static::_filter()` Which strips out all non-zero empty values.
<ide> * @return array Filtered array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::filter
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::filter
<ide> */
<ide> public static function filter(array $data, $callback = array('self', '_filter')) {
<ide> foreach ($data as $k => $v) {
<ide> protected static function _filter($var) {
<ide> * @param array $data Array to flatten
<ide> * @param string $separator String used to separate array key elements in a path, defaults to '.'
<ide> * @return array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::flatten
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::flatten
<ide> */
<ide> public static function flatten(array $data, $separator = '.') {
<ide> $result = array();
<ide> public static function flatten(array $data, $separator = '.') {
<ide> * @param array $data Flattened array
<ide> * @param string $separator The delimiter used
<ide> * @return array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::expand
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::expand
<ide> */
<ide> public static function expand(array $data, $separator = '.') {
<ide> $result = [];
<ide> public static function expand(array $data, $separator = '.') {
<ide> * @param array $data Array to be merged
<ide> * @param mixed $merge Array to merge with. The argument and all trailing arguments will be array cast when merged
<ide> * @return array Merged array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::merge
<ide> */
<ide> public static function merge(array $data, $merge) {
<ide> $args = array_slice(func_get_args(), 1);
<ide> protected static function _merge($stack, &$return) {
<ide> *
<ide> * @param array $data The array to check.
<ide> * @return bool true if values are numeric, false otherwise
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::numeric
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::numeric
<ide> */
<ide> public static function numeric(array $data) {
<ide> if (empty($data)) {
<ide> public static function numeric(array $data) {
<ide> *
<ide> * @param array $data Array to count dimensions on
<ide> * @return int The number of dimensions in $data
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::dimensions
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::dimensions
<ide> */
<ide> public static function dimensions(array $data) {
<ide> if (empty($data)) {
<ide> public static function dimensions(array $data) {
<ide> *
<ide> * @param array $data Array to count dimensions on
<ide> * @return int The maximum number of dimensions in $data
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::maxDimensions
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::maxDimensions
<ide> */
<ide> public static function maxDimensions(array $data) {
<ide> $depth = array();
<ide> public static function maxDimensions(array $data) {
<ide> * @param string $path The path to extract for mapping over.
<ide> * @param callable $function The function to call on each extracted value.
<ide> * @return array An array of the modified values.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::map
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::map
<ide> */
<ide> public static function map(array $data, $path, $function) {
<ide> $values = (array)static::extract($data, $path);
<ide> public static function map(array $data, $path, $function) {
<ide> * @param string $path The path to extract from $data.
<ide> * @param callable $function The function to call on each extracted value.
<ide> * @return mixed The reduced value.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::reduce
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::reduce
<ide> */
<ide> public static function reduce(array $data, $path, $function) {
<ide> $values = (array)static::extract($data, $path);
<ide> public static function apply(array $data, $path, $function) {
<ide> * @param string $dir See directions above. Defaults to 'asc'.
<ide> * @param string $type See direction types above. Defaults to 'regular'.
<ide> * @return array Sorted array of data
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::sort
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::sort
<ide> */
<ide> public static function sort(array $data, $path, $dir = 'asc', $type = 'regular') {
<ide> if (empty($data)) {
<ide> protected static function _squash(array $data, $key = null) {
<ide> * @param array $compare Second value
<ide> * @return array Returns the key => value pairs that are not common in $data and $compare
<ide> * The expression for this function is ($data - $compare) + ($compare - ($data - $compare))
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::diff
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::diff
<ide> */
<ide> public static function diff(array $data, array $compare) {
<ide> if (empty($data)) {
<ide> public static function diff(array $data, array $compare) {
<ide> * @param array $data The data to append onto.
<ide> * @param array $compare The data to compare and append onto.
<ide> * @return array The merged array.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::mergeDiff
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::mergeDiff
<ide> */
<ide> public static function mergeDiff(array $data, array $compare) {
<ide> if (empty($data) && !empty($compare)) {
<ide> public static function mergeDiff(array $data, array $compare) {
<ide> * @param array $data List to normalize
<ide> * @param bool $assoc If true, $data will be converted to an associative array.
<ide> * @return array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::normalize
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::normalize
<ide> */
<ide> public static function normalize(array $data, $assoc = true) {
<ide> $keys = array_keys($data);
<ide> public static function normalize(array $data, $assoc = true) {
<ide> * @return array of results, nested
<ide> * @see Hash::extract()
<ide> * @throws \InvalidArgumentException When providing invalid data.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::nest
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::nest
<ide> */
<ide> public static function nest(array $data, array $options = array()) {
<ide> if (!$data) {
<ide><path>src/Utility/Inflector.php
<ide> * Inflector pluralizes and singularizes English nouns.
<ide> * Used by CakePHP's naming conventions throughout the framework.
<ide> *
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html
<ide> */
<ide> class Inflector {
<ide>
<ide> public static function rules($type, $rules, $reset = false) {
<ide> *
<ide> * @param string $word Word in singular
<ide> * @return string Word in plural
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::pluralize
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-plural-singular-forms
<ide> */
<ide> public static function pluralize($word) {
<ide> if (isset(static::$_cache['pluralize'][$word])) {
<ide> public static function pluralize($word) {
<ide> *
<ide> * @param string $word Word in plural
<ide> * @return string Word in singular
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::singularize
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-plural-singular-forms
<ide> */
<ide> public static function singularize($word) {
<ide> if (isset(static::$_cache['singularize'][$word])) {
<ide> public static function singularize($word) {
<ide> *
<ide> * @param string $lowerCaseAndUnderscoredWord Word to camelize
<ide> * @return string Camelized word. LikeThis.
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::camelize
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-camelcase-and-under-scored-forms
<ide> */
<ide> public static function camelize($lowerCaseAndUnderscoredWord) {
<ide> if (!($result = static::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) {
<ide> public static function camelize($lowerCaseAndUnderscoredWord) {
<ide> *
<ide> * @param string $camelCasedWord Camel-cased word to be "underscorized"
<ide> * @return string Underscore-syntaxed version of the $camelCasedWord
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::underscore
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-camelcase-and-under-scored-forms
<ide> */
<ide> public static function underscore($camelCasedWord) {
<ide> if (!($result = static::_cache(__FUNCTION__, $camelCasedWord))) {
<ide> public static function dasherize($wordGroup) {
<ide> *
<ide> * @param string $lowerCaseAndUnderscoredWord String to be made more readable
<ide> * @return string Human-readable string
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::humanize
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-human-readable-forms
<ide> */
<ide> public static function humanize($lowerCaseAndUnderscoredWord) {
<ide> if (!($result = static::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) {
<ide> public static function humanize($lowerCaseAndUnderscoredWord) {
<ide> *
<ide> * @param string $className Name of class to get database table name for
<ide> * @return string Name of the database table for given class
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::tableize
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-table-and-class-name-forms
<ide> */
<ide> public static function tableize($className) {
<ide> if (!($result = static::_cache(__FUNCTION__, $className))) {
<ide> public static function tableize($className) {
<ide> *
<ide> * @param string $tableName Name of database table to get class name for
<ide> * @return string Class name
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::classify
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-table-and-class-name-forms
<ide> */
<ide> public static function classify($tableName) {
<ide> if (!($result = static::_cache(__FUNCTION__, $tableName))) {
<ide> public static function classify($tableName) {
<ide> *
<ide> * @param string $string String to convert.
<ide> * @return string in variable form
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::variable
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-variable-names
<ide> */
<ide> public static function variable($string) {
<ide> if (!($result = static::_cache(__FUNCTION__, $string))) {
<ide> public static function variable($string) {
<ide> * @param string $string the string you want to slug
<ide> * @param string $replacement will replace keys in map
<ide> * @return string
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::slug
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/inflector.html#creating-url-safe-strings
<ide> */
<ide> public static function slug($string, $replacement = '-') {
<ide> $quotedReplacement = preg_quote($replacement, '/');
<ide><path>src/Utility/Security.php
<ide> public static function generateAuthKey() {
<ide> * @param mixed $salt If true, automatically prepends the application's salt
<ide> * value to $string (Security.salt).
<ide> * @return string Hash
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/security.html#Security::hash
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/security.html#hashing-data
<ide> */
<ide> public static function hash($string, $type = null, $salt = false) {
<ide> if (empty($type)) {
<ide><path>src/Utility/String.php
<ide> public static function wordWrap($text, $width = 72, $break = "\n", $cut = false)
<ide> * @param string|array $phrase The phrase or phrases that will be searched.
<ide> * @param array $options An array of html attributes and options.
<ide> * @return string The highlighted text
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/string.html#highlighting-substrings
<ide> */
<ide> public static function highlight($text, $phrase, array $options = array()) {
<ide> if (empty($phrase)) {
<ide> public static function highlight($text, $phrase, array $options = array()) {
<ide> *
<ide> * @param string $text Text
<ide> * @return string The text without links
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
<ide> */
<ide> public static function stripLinks($text) {
<ide> return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
<ide> public static function tail($text, $length = 100, array $options = array()) {
<ide> * @param int $length Length of returned string, including ellipsis.
<ide> * @param array $options An array of html attributes and options.
<ide> * @return string Trimmed string.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/string.html#truncating-text
<ide> */
<ide> public static function truncate($text, $length = 100, array $options = array()) {
<ide> $default = array(
<ide> public static function truncate($text, $length = 100, array $options = array())
<ide> * @param int $radius The amount of characters that will be returned on each side of the founded phrase
<ide> * @param string $ellipsis Ending that will be appended
<ide> * @return string Modified string
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/string.html#extracting-an-excerpt
<ide> */
<ide> public static function excerpt($text, $phrase, $radius = 100, $ellipsis = '...') {
<ide> if (empty($text) || empty($phrase)) {
<ide> public static function excerpt($text, $phrase, $radius = 100, $ellipsis = '...')
<ide> * @param string $and The word used to join the last and second last items together with. Defaults to 'and'.
<ide> * @param string $separator The separator used to join all the other items together. Defaults to ', '.
<ide> * @return string The glued together string.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/string.html#converting-an-array-to-sentence-form
<ide> */
<ide> public static function toList(array $list, $and = null, $separator = ', ') {
<ide> if ($and === null) {
<ide><path>src/Validation/ValidationRule.php
<ide> /**
<ide> * ValidationRule object. Represents a validation method, error message and
<ide> * rules for applying such method to a field.
<del> *
<del> * @link http://book.cakephp.org/2.0/en/data-validation.html
<ide> */
<ide> class ValidationRule {
<ide>
<ide><path>src/Validation/ValidationSet.php
<ide> /**
<ide> * ValidationSet object. Holds all validation rules for a field and exposes
<ide> * methods to dynamically add or remove validation rules
<del> *
<del> * @link http://book.cakephp.org/2.0/en/data-validation.html
<ide> */
<ide> class ValidationSet implements \ArrayAccess, \IteratorAggregate, \Countable {
<ide>
<ide><path>src/View/Exception/MissingCellViewException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/View/Exception/MissingElementException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/View/Exception/MissingHelperException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/View/Exception/MissingLayoutException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/View/Exception/MissingTemplateException.php
<ide> * Redistributions of files must retain the above copyright notice.
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<del> * @link http://book.cakephp.org/2.0/en/development/testing.html
<ide> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide><path>src/View/Helper/FormHelper.php
<ide> protected function _csrfField() {
<ide> * @param array $secureAttributes will be passed as html attributes into the hidden input elements generated for the
<ide> * Security Component.
<ide> * @return string A closing FORM tag.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#closing-the-form
<ide> */
<ide> public function end($secureAttributes = []) {
<ide> $out = '';
<ide> public function end($secureAttributes = []) {
<ide> * @param array $secureAttributes will be passed as html attributes into the hidden
<ide> * input elements generated for the Security Component.
<ide> * @return string A hidden input field with a security hash
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secure
<ide> */
<ide> public function secure(array $fields = array(), array $secureAttributes = array()) {
<ide> if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
<ide> public function secure(array $fields = array(), array $secureAttributes = array(
<ide> *
<ide> * @param string $name The dot separated name for the field.
<ide> * @return mixed Either null, or the list of fields.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockField
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#working-with-securitycomponent
<ide> */
<ide> public function unlockField($name = null) {
<ide> if ($name === null) {
<ide> protected function _secure($lock, $field, $value = null) {
<ide> *
<ide> * @param string $field This should be "Modelname.fieldname"
<ide> * @return bool If there are errors this method returns true, else false.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#displaying-and-checking-errors
<ide> */
<ide> public function isFieldError($field) {
<ide> return $this->_getContext()->hasError($field);
<ide> public function isFieldError($field) {
<ide> * it should be a hash of key names => messages.
<ide> * @param array $options See above.
<ide> * @return string Formatted errors or ''.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#displaying-and-checking-errors
<ide> */
<ide> public function error($field, $text = null, array $options = []) {
<ide> $options += ['escape' => true];
<ide> public function error($field, $text = null, array $options = []) {
<ide> * fieldName.
<ide> * @param array $options An array of HTML attributes.
<ide> * @return string The formatted LABEL element
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-labels
<ide> */
<ide> public function label($fieldName, $text = null, array $options = []) {
<ide> if ($text === null) {
<ide> public function label($fieldName, $text = null, array $options = []) {
<ide> * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
<ide> * to customize the legend text.
<ide> * @return string Completed form inputs.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#generating-entire-forms
<ide> */
<ide> public function allInputs(array $fields = [], array $options = []) {
<ide> $context = $this->_getContext();
<ide> public function allInputs(array $fields = [], array $options = []) {
<ide> * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
<ide> * to customize the legend text.
<ide> * @return string Completed form inputs.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#generating-entire-forms
<ide> */
<ide> public function inputs(array $fields, array $options = []) {
<ide> $fields = Hash::normalize($fields);
<ide> public function inputs(array $fields, array $options = []) {
<ide> * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
<ide> * to customize the legend text.
<ide> * @return string Completed form inputs.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
<ide> */
<ide> public function fieldset($fields = '', array $options = []) {
<ide> $fieldset = $legend = true;
<ide> public function fieldset($fields = '', array $options = []) {
<ide> * @param string $fieldName This should be "Modelname.fieldname"
<ide> * @param array $options Each type of input takes different options.
<ide> * @return string Completed form widget.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-form-inputs
<ide> */
<ide> public function input($fieldName, array $options = []) {
<ide> $options += [
<ide> protected function _inputLabel($fieldName, $label, $options) {
<ide> * @param string $fieldName Name of a field, like this "Modelname.fieldname"
<ide> * @param array $options Array of HTML attributes.
<ide> * @return string|array An HTML text input element.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-checkboxes
<ide> */
<ide> public function checkbox($fieldName, array $options = []) {
<ide> $options += ['hiddenField' => true, 'value' => 1];
<ide> public function checkbox($fieldName, array $options = []) {
<ide> * @param array|\Traversable $options Radio button options array.
<ide> * @param array $attributes Array of HTML attributes, and special attributes above.
<ide> * @return string Completed radio widget set.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-radio-buttons
<ide> */
<ide> public function radio($fieldName, $options = [], array $attributes = []) {
<ide> $attributes = $this->_initInputField($fieldName, $attributes);
<ide> public function __call($method, $params) {
<ide> * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
<ide> * @param array $options Array of HTML attributes, and special options above.
<ide> * @return string A generated HTML text input element
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-textareas
<ide> */
<ide> public function textarea($fieldName, array $options = array()) {
<ide> $options = $this->_initInputField($fieldName, $options);
<ide> public function textarea($fieldName, array $options = array()) {
<ide> * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
<ide> * @param array $options Array of HTML attributes.
<ide> * @return string A generated hidden input
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-hidden-inputs
<ide> */
<ide> public function hidden($fieldName, array $options = array()) {
<ide> $options += array('required' => false, 'secure' => true);
<ide> public function hidden($fieldName, array $options = array()) {
<ide> * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
<ide> * @param array $options Array of HTML attributes.
<ide> * @return string A generated file input.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-file-inputs
<ide> */
<ide> public function file($fieldName, array $options = array()) {
<ide> $options += array('secure' => true);
<ide> public function file($fieldName, array $options = array()) {
<ide> * @param string $title The button's caption. Not automatically HTML encoded
<ide> * @param array $options Array of options and HTML attributes.
<ide> * @return string A HTML button tag.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-button-elements
<ide> */
<ide> public function button($title, array $options = array()) {
<ide> $options += array('type' => 'submit', 'escape' => false, 'secure' => false);
<ide> public function button($title, array $options = array()) {
<ide> * @param string|array $url URL as string or array
<ide> * @param array $options Array of options and HTML attributes.
<ide> * @return string A HTML button tag.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButton
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
<ide> */
<ide> public function postButton($title, $url, array $options = array()) {
<ide> $out = $this->create(false, array('url' => $url));
<ide> public function postButton($title, $url, array $options = array()) {
<ide> * external URL (starts with http://)
<ide> * @param array $options Array of HTML attributes.
<ide> * @return string An `<a />` element.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
<ide> */
<ide> public function postLink($title, $url = null, array $options = array()) {
<ide> $options += array('block' => null, 'confirm' => null);
<ide> public function postLink($title, $url = null, array $options = array()) {
<ide> * OR if the first character is not /, image is relative to webroot/img.
<ide> * @param array $options Array of options. See above.
<ide> * @return string A HTML submit button
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-buttons-and-submit-elements
<ide> */
<ide> public function submit($caption = null, array $options = []) {
<ide> if (!is_string($caption) && empty($caption)) {
<ide> public function submit($caption = null, array $options = []) {
<ide> * SELECT element
<ide> * @param array $attributes The HTML attributes of the select element.
<ide> * @return string Formatted SELECT element
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
<ide> * @see \Cake\View\Helper\FormHelper::multiCheckbox() for creating multiple checkboxes.
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-select-pickers
<ide> */
<ide> public function select($fieldName, $options = [], array $attributes = []) {
<ide> $attributes += [
<ide> protected function _singleDatetime($options, $keep) {
<ide> * @param string $fieldName Prefix name for the SELECT element
<ide> * @param array $options Options & HTML attributes for the select element
<ide> * @return string A generated day select box.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-day-inputs
<ide> */
<ide> public function day($fieldName = null, array $options = []) {
<ide> $options = $this->_singleDatetime($options, 'day');
<ide> public function day($fieldName = null, array $options = []) {
<ide> * @param string $fieldName Prefix name for the SELECT element
<ide> * @param array $options Options & attributes for the select elements.
<ide> * @return string Completed year select input
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-year-inputs
<ide> */
<ide> public function year($fieldName, array $options = []) {
<ide> $options = $this->_singleDatetime($options, 'year');
<ide> public function year($fieldName, array $options = []) {
<ide> * @param string $fieldName Prefix name for the SELECT element
<ide> * @param array $options Attributes for the select element
<ide> * @return string A generated month select dropdown.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-month-inputs
<ide> */
<ide> public function month($fieldName, array $options = array()) {
<ide> $options = $this->_singleDatetime($options, 'month');
<ide> public function month($fieldName, array $options = array()) {
<ide> * @param string $fieldName Prefix name for the SELECT element
<ide> * @param array $options List of HTML attributes
<ide> * @return string Completed hour select input
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-hour-inputs
<ide> */
<ide> public function hour($fieldName, array $options = []) {
<ide> $options += ['format' => 24];
<ide> public function hour($fieldName, array $options = []) {
<ide> * @param string $fieldName Prefix name for the SELECT element
<ide> * @param array $options Array of options.
<ide> * @return string Completed minute select input.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-minute-inputs
<ide> */
<ide> public function minute($fieldName, array $options = []) {
<ide> $options = $this->_singleDatetime($options, 'minute');
<ide> public function minute($fieldName, array $options = []) {
<ide> * @param string $fieldName Prefix name for the SELECT element
<ide> * @param array $options Array of options
<ide> * @return string Completed meridian select input
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-meridian-inputs
<ide> */
<ide> public function meridian($fieldName, array $options = array()) {
<ide> $options = $this->_singleDatetime($options, 'meridian');
<ide> public function meridian($fieldName, array $options = array()) {
<ide> * @param string $fieldName Prefix name for the SELECT element
<ide> * @param array $options Array of Options
<ide> * @return string Generated set of select boxes for the date and time formats chosen.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-date-and-time-inputs
<ide> */
<ide> public function dateTime($fieldName, array $options = array()) {
<ide> $options += [
<ide><path>src/View/Helper/HtmlHelper.php
<ide> *
<ide> * HtmlHelper encloses all methods needed while working with HTML pages.
<ide> *
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html
<ide> */
<ide> class HtmlHelper extends Helper {
<ide>
<ide> public function __construct(View $View, array $config = array()) {
<ide> * @param string|array $options Link attributes e.g. array('id' => 'selected')
<ide> * @return $this
<ide> * @see HtmlHelper::link() for details on $options that can be used.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
<ide> */
<ide> public function addCrumb($name, $link = null, array $options = array()) {
<ide> $this->_crumbs[] = array($name, $link, $options);
<ide> public function addCrumb($name, $link = null, array $options = array()) {
<ide> *
<ide> * @param string $type Doctype to use.
<ide> * @return string|null Doctype string
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::docType
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-doctype-tags
<ide> */
<ide> public function docType($type = 'html5') {
<ide> if (isset($this->_docTypes[$type])) {
<ide> public function docType($type = 'html5') {
<ide> * @param array $options Other attributes for the generated tag. If the type attribute is html,
<ide> * rss, atom, or icon, the mime-type is returned.
<ide> * @return string A completed `<link />` element.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::meta
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-meta-tags
<ide> */
<ide> public function meta($type, $content = null, array $options = array()) {
<ide> $options += array('block' => null);
<ide> public function meta($type, $content = null, array $options = array()) {
<ide> * @param string $charset The character set to be used in the meta tag. If empty,
<ide> * The App.encoding value will be used. Example: "utf-8".
<ide> * @return string A meta tag containing the specified character set.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::charset
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-charset-tags
<ide> */
<ide> public function charset($charset = null) {
<ide> if (empty($charset)) {
<ide> public function charset($charset = null) {
<ide> * external URL (starts with http://)
<ide> * @param array $options Array of options and HTML attributes.
<ide> * @return string An `<a />` element.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::link
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-links
<ide> */
<ide> public function link($title, $url = null, array $options = array()) {
<ide> $escapeTitle = true;
<ide> public function link($title, $url = null, array $options = array()) {
<ide> * of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
<ide> * @param array $options Array of options and HTML arguments.
<ide> * @return string CSS <link /> or <style /> tag, depending on the type of link.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::css
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-css-files
<ide> */
<ide> public function css($path, array $options = array()) {
<ide> $options += array('once' => true, 'block' => null, 'rel' => 'stylesheet');
<ide> public function css($path, array $options = array()) {
<ide> * @param array $options Array of options, and html attributes see above.
<ide> * @return mixed String of `<script />` tags or null if block is specified in options
<ide> * or if $once is true and the file has been included before.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::script
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-javascript-files
<ide> */
<ide> public function script($url, array $options = array()) {
<ide> $defaults = array('block' => null, 'once' => true);
<ide> public function script($url, array $options = array()) {
<ide> * @param array $options The options to use. Options not listed above will be
<ide> * treated as HTML attributes.
<ide> * @return mixed string or null depending on the value of `$options['block']`
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptBlock
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-inline-javascript-blocks
<ide> */
<ide> public function scriptBlock($script, array $options = array()) {
<ide> $options += array('safe' => true, 'block' => null);
<ide> public function scriptBlock($script, array $options = array()) {
<ide> *
<ide> * @param array $options Options for the code block.
<ide> * @return void
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptStart
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-javascript-blocks
<ide> */
<ide> public function scriptStart(array $options = array()) {
<ide> $options += array('safe' => true, 'block' => null);
<ide> public function scriptStart(array $options = array()) {
<ide> * the settings used when the scriptBlock was started
<ide> *
<ide> * @return mixed depending on the settings of scriptStart() either a script tag or null
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptEnd
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-javascript-blocks
<ide> */
<ide> public function scriptEnd() {
<ide> $buffer = ob_get_clean();
<ide> public function scriptEnd() {
<ide> * @param array $data Style data array, keys will be used as property names, values as property values.
<ide> * @param bool $oneLine Whether or not the style block should be displayed on one line.
<ide> * @return string CSS styling data
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::style
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-css-programatically
<ide> */
<ide> public function style(array $data, $oneLine = true) {
<ide> $out = array();
<ide> public function style(array $data, $oneLine = true) {
<ide> * @param string|array|bool $startText This will be the first crumb, if false it defaults to first crumb in array. Can
<ide> * also be an array, see above for details.
<ide> * @return string|null Composed bread crumbs
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
<ide> */
<ide> public function getCrumbs($separator = '»', $startText = false) {
<ide> $crumbs = $this->_prepareCrumbs($startText);
<ide> public function getCrumbs($separator = '»', $startText = false) {
<ide> * @param string|array|bool $startText This will be the first crumb, if false it defaults to first crumb in array. Can
<ide> * also be an array, see `HtmlHelper::getCrumbs` for details.
<ide> * @return string|null breadcrumbs html list
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
<ide> */
<ide> public function getCrumbList(array $options = array(), $startText = false) {
<ide> $defaults = array('firstClass' => 'first', 'lastClass' => 'last', 'separator' => '', 'escape' => true);
<ide> protected function _prepareCrumbs($startText, $escape = true) {
<ide> * @param string $path Path to the image file, relative to the app/webroot/img/ directory.
<ide> * @param array $options Array of HTML attributes. See above for special options.
<ide> * @return string completed img tag
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::image
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-images
<ide> */
<ide> public function image($path, array $options = array()) {
<ide> $path = $this->Url->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
<ide> public function image($path, array $options = array()) {
<ide> * @param array $trOptions HTML options for TR elements.
<ide> * @param array $thOptions HTML options for TH elements.
<ide> * @return string Completed table headers
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tableHeaders
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-table-headings
<ide> */
<ide> public function tableHeaders(array $names, array $trOptions = null, array $thOptions = null) {
<ide> $out = array();
<ide> public function tableHeaders(array $names, array $trOptions = null, array $thOpt
<ide> * @param bool $continueOddEven If false, will use a non-static $count variable,
<ide> * so that the odd/even count is reset to zero just for that call.
<ide> * @return string Formatted HTML
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tableCells
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-table-cells
<ide> */
<ide> public function tableCells($data, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true) {
<ide> if (empty($data[0]) || !is_array($data[0])) {
<ide> public function tableCells($data, $oddTrOptions = null, $evenTrOptions = null, $
<ide> * If null, only a start tag will be printed
<ide> * @param array $options Additional HTML attributes of the DIV tag, see above.
<ide> * @return string The formatted tag element
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tag
<ide> */
<ide> public function tag($name, $text = null, array $options = array()) {
<ide> if (empty($name)) {
<ide> public function tag($name, $text = null, array $options = array()) {
<ide> * If null, only a start tag will be printed
<ide> * @param array $options Additional HTML attributes of the DIV tag
<ide> * @return string The formatted DIV element
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::div
<ide> */
<ide> public function div($class = null, $text = null, array $options = array()) {
<ide> if (!empty($class)) {
<ide> public function div($class = null, $text = null, array $options = array()) {
<ide> * @param string $text String content that will appear inside the p element.
<ide> * @param array $options Additional HTML attributes of the P tag
<ide> * @return string The formatted P element
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::para
<ide> */
<ide> public function para($class, $text, array $options = array()) {
<ide> if (isset($options['escape'])) {
<ide> public function media($path, array $options = array()) {
<ide> * @param array $options Options and additional HTML attributes of the list (ol/ul) tag.
<ide> * @param array $itemOptions Options and additional HTML attributes of the list item (LI) tag.
<ide> * @return string The nested list
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::nestedList
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-nested-lists
<ide> */
<ide> public function nestedList(array $list, array $options = [], array $itemOptions = []) {
<ide> $options += array('tag' => 'ul');
<ide><path>src/View/Helper/NumberHelper.php
<ide> *
<ide> * Methods to make numbers more readable.
<ide> *
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/number.html
<ide> * @see \Cake\I18n\Number
<ide> */
<ide> class NumberHelper extends Helper {
<ide> public function __call($method, $params) {
<ide> * @param int $precision The precision of the returned number.
<ide> * @return float Formatted float.
<ide> * @see \Cake\I18n\Number::precision()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/number.html#formatting-floating-point-numbers
<ide> */
<ide> public function precision($number, $precision = 3) {
<ide> return $this->_engine->precision($number, $precision);
<ide> public function precision($number, $precision = 3) {
<ide> * @param int $size Size in bytes
<ide> * @return string Human readable size
<ide> * @see \Cake\I18n\Number::toReadableSize()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/number.html#interacting-with-human-readable-values
<ide> */
<ide> public function toReadableSize($size) {
<ide> return $this->_engine->toReadableSize($size);
<ide> public function toReadableSize($size) {
<ide> * @param array $options Options
<ide> * @return string Percentage string
<ide> * @see \Cake\I18n\Number::toPercentage()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/number.html#formatting-percentages
<ide> */
<ide> public function toPercentage($number, $precision = 2, array $options = array()) {
<ide> return $this->_engine->toPercentage($number, $precision, $options);
<ide> public function toPercentage($number, $precision = 2, array $options = array())
<ide> * @param float $number A floating point number.
<ide> * @param array $options An array with options.
<ide> * @return string Formatted number
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::format
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/number.html#formatting-numbers
<ide> */
<ide> public function format($number, array $options = []) {
<ide> $formatted = $this->_engine->format($number, $options);
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> *
<ide> * PaginationHelper encloses all methods needed when working with pagination.
<ide> *
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html
<ide> */
<ide> class PaginatorHelper extends Helper {
<ide>
<ide> public function __construct(View $View, array $config = array()) {
<ide> *
<ide> * @param string $model Optional model name. Uses the default if none is specified.
<ide> * @return array The array of paging parameters for the paginated resultset.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::params
<ide> */
<ide> public function params($model = null) {
<ide> if (empty($model)) {
<ide> public function params($model = null) {
<ide> * @param string $key Key of the paginator params array to retrieve.
<ide> * @param string $model Optional model name. Uses the default if none is specified.
<ide> * @return mixed Content of the requested param.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::params
<ide> */
<ide> public function param($key, $model = null) {
<ide> $params = $this->params($model);
<ide> public function param($key, $model = null) {
<ide> * @param array $options Default options for pagination links.
<ide> * See PaginatorHelper::$options for list of keys.
<ide> * @return void
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::options
<ide> */
<ide> public function options(array $options = array()) {
<ide> if (!empty($options['paging'])) {
<ide> public function options(array $options = array()) {
<ide> *
<ide> * @param string $model Optional model name. Uses the default if none is specified.
<ide> * @return string The current page number of the recordset.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::current
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state
<ide> */
<ide> public function current($model = null) {
<ide> $params = $this->params($model);
<ide> public function current($model = null) {
<ide> * @param array $options Options for pagination links. See #options for list of keys.
<ide> * @return string|null The name of the key by which the recordset is being sorted, or
<ide> * null if the results are not currently sorted.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::sortKey
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-sort-links
<ide> */
<ide> public function sortKey($model = null, array $options = array()) {
<ide> if (empty($options)) {
<ide> public function sortKey($model = null, array $options = array()) {
<ide> * @param array $options Options for pagination links. See #options for list of keys.
<ide> * @return string The direction by which the recordset is being sorted, or
<ide> * null if the results are not currently sorted.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::sortDir
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-sort-links
<ide> */
<ide> public function sortDir($model = null, array $options = array()) {
<ide> $dir = null;
<ide> protected function _toggledLink($text, $enabled, $options, $templates) {
<ide> * @param string $title Title for the link. Defaults to '<< Previous'.
<ide> * @param array $options Options for pagination link. See above for list of keys.
<ide> * @return string A "previous" link or a disabled link.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::prev
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-jump-links
<ide> */
<ide> public function prev($title = '<< Previous', array $options = []) {
<ide> $defaults = [
<ide> public function prev($title = '<< Previous', array $options = []) {
<ide> * @param string $title Title for the link. Defaults to 'Next >>'.
<ide> * @param array $options Options for pagination link. See above for list of keys.
<ide> * @return string A "next" link or $disabledTitle text if the link is disabled.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::next
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-jump-links
<ide> */
<ide> public function next($title = 'Next >>', array $options = []) {
<ide> $defaults = [
<ide> public function next($title = 'Next >>', array $options = []) {
<ide> *
<ide> * @param string $key The name of the key that the recordset should be sorted.
<ide> * @param string $title Title for the link. If $title is null $key will be used
<del> * for the title and will be generated by inflection.
<add> * for the title and will be generated by inflection.
<ide> * @param array $options Options for sorting link. See above for list of keys.
<ide> * @return string A link sorting default by 'asc'. If the resultset is sorted 'asc' by the specified
<ide> * key the returned link will sort by 'desc'.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::sort
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-sort-links
<ide> */
<ide> public function sort($key, $title = null, array $options = []) {
<ide> $options += ['url' => array(), 'model' => null, 'escape' => true];
<ide> public function sort($key, $title = null, array $options = []) {
<ide> * @param string $model Which model to paginate on
<ide> * @param bool $full If true, the full base URL will be prepended to the result
<ide> * @return mixed By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript)
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::url
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#generating-pagination-urls
<ide> */
<ide> public function generateUrl(array $options = array(), $model = null, $full = false) {
<ide> $paging = $this->params($model);
<ide> public function generateUrl(array $options = array(), $model = null, $full = fal
<ide> *
<ide> * @param string $model Optional model name. Uses the default if none is specified.
<ide> * @return bool True if the result set is not at the first page.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::hasPrev
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state
<ide> */
<ide> public function hasPrev($model = null) {
<ide> return $this->_hasPage($model, 'prev');
<ide> public function hasPrev($model = null) {
<ide> *
<ide> * @param string $model Optional model name. Uses the default if none is specified.
<ide> * @return bool True if the result set is not at the last page.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::hasNext
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state
<ide> */
<ide> public function hasNext($model = null) {
<ide> return $this->_hasPage($model, 'next');
<ide> public function hasNext($model = null) {
<ide> * @param string $model Optional model name. Uses the default if none is specified.
<ide> * @param int $page The page number - if not set defaults to 1.
<ide> * @return bool True if the given result set has the specified page number.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::hasPage
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#checking-the-pagination-state
<ide> */
<ide> public function hasPage($model = null, $page = 1) {
<ide> if (is_numeric($model)) {
<ide> protected function _hasPage($model, $page) {
<ide> * Gets the default model of the paged sets
<ide> *
<ide> * @return string|null Model name or null if the pagination isn't initialized.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::defaultModel
<ide> */
<ide> public function defaultModel() {
<ide> if ($this->_defaultModel) {
<ide> public function defaultModel() {
<ide> * @param string|array $options Options for the counter string. See #options for list of keys.
<ide> * If string it will be used as format.
<ide> * @return string Counter string.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::counter
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-a-page-counter
<ide> */
<ide> public function counter($options = []) {
<ide> if (is_string($options)) {
<ide> public function counter($options = []) {
<ide> *
<ide> * @param array $options Options for the numbers.
<ide> * @return string numbers string.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::numbers
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-page-number-links
<ide> */
<ide> public function numbers(array $options = array()) {
<ide> $defaults = array(
<ide> public function numbers(array $options = array()) {
<ide> * you want at the beginning of the range.
<ide> * @param array $options An array of options.
<ide> * @return string numbers string.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::first
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-jump-links
<ide> */
<ide> public function first($first = '<< first', array $options = []) {
<ide> $options += ['model' => $this->defaultModel(), 'escape' => true];
<ide> public function first($first = '<< first', array $options = []) {
<ide> * @param string|int $last if string use as label for the link, if numeric print page numbers
<ide> * @param array $options Array of options
<ide> * @return string numbers string.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::last
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-jump-links
<ide> */
<ide> public function last($last = 'last >>', array $options = array()) {
<ide> $options += ['model' => $this->defaultModel(), 'escape' => true];
<ide><path>src/View/Helper/RssHelper.php
<ide> /**
<ide> * RSS Helper class for easy output RSS structures.
<ide> *
<del> * @property TimeHelper $Time
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html
<add> * @property TimeHelper $Time
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/rss.html
<ide> */
<ide> class RssHelper extends Helper {
<ide>
<ide> class RssHelper extends Helper {
<ide> * @param array $attrib `<rss />` tag attributes
<ide> * @param string $content Tag content.
<ide> * @return string An RSS document
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html#RssHelper::document
<ide> */
<ide> public function document($attrib = array(), $content = null) {
<ide> if ($content === null) {
<ide> public function document($attrib = array(), $content = null) {
<ide> * @param array $elements Named array elements which are converted to tags
<ide> * @param string $content Content (`<item />`'s belonging to this channel
<ide> * @return string An RSS `<channel />`
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html#RssHelper::channel
<ide> */
<ide> public function channel($attrib = array(), $elements = array(), $content = null) {
<ide> if (!isset($elements['link'])) {
<ide> public function channel($attrib = array(), $elements = array(), $content = null)
<ide> * @param string|array $callback A string function name, or array containing an object
<ide> * and a string method name
<ide> * @return string A set of RSS `<item />` elements
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html#RssHelper::items
<ide> */
<ide> public function items($items, $callback = null) {
<ide> if ($callback) {
<ide> public function items($items, $callback = null) {
<ide> * @param array $att The attributes of the `<item />` element
<ide> * @param array $elements The list of elements contained in this `<item />`
<ide> * @return string An RSS `<item />` element
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html#RssHelper::item
<ide> */
<ide> public function item($att = array(), $elements = array()) {
<ide> $content = null;
<ide> public function item($att = array(), $elements = array()) {
<ide> * @param int|string|\DateTime $time UNIX timestamp or valid time string or DateTime object.
<ide> * @return string An RSS-formatted timestamp
<ide> * @see TimeHelper::toRSS
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html#RssHelper::time
<ide> */
<ide> public function time($time) {
<ide> return $this->Time->toRSS($time);
<ide> public function time($time) {
<ide> * @param string|array $content XML element content
<ide> * @param bool $endTag Whether the end tag of the element should be printed
<ide> * @return string XML
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html#RssHelper::elem
<ide> */
<ide> public function elem($name, $attrib = array(), $content = null, $endTag = true) {
<ide> $namespace = null;
<ide><path>src/View/Helper/SessionHelper.php
<ide> *
<ide> * Session reading from the view.
<ide> *
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/session.html
<ide> */
<ide> class SessionHelper extends Helper {
<ide>
<ide> class SessionHelper extends Helper {
<ide> *
<ide> * @param string $name the name of the session key you want to read
<ide> * @return mixed values from the session vars
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#SessionHelper::read
<ide> */
<ide> public function read($name = null) {
<ide> return $this->request->session()->read($name);
<ide> public function read($name = null) {
<ide> *
<ide> * @param string $name Session key to check.
<ide> * @return bool
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#SessionHelper::check
<ide> */
<ide> public function check($name) {
<ide> return $this->request->session()->check($name);
<ide> public function check($name) {
<ide> * Supports the 'params', and 'element' keys that are used in the helper.
<ide> * @return string
<ide> * @deprecated 3.0 Use FlashHelper::render() instead.
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#SessionHelper::flash
<ide> */
<ide> public function flash($key = 'flash', $attrs = []) {
<ide> $flash = $this->request->session()->read('Flash.' . $key);
<ide><path>src/View/Helper/TextHelper.php
<ide> *
<ide> * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
<ide> *
<del> * @property HtmlHelper $Html
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html
<del> * @see String
<add> * @property HtmlHelper $Html
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html
<add> * @see \Cake\Utility\String
<ide> */
<ide> class TextHelper extends Helper {
<ide>
<ide> public function __call($method, $params) {
<ide> * @param string $text Text
<ide> * @param array $options Array of HTML options, and options listed above.
<ide> * @return string The text with links
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkUrls
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#linking-urls
<ide> */
<ide> public function autoLinkUrls($text, array $options = array()) {
<ide> $this->_placeholders = array();
<ide> protected function _linkEmails($text, $options) {
<ide> * @param string $text Text
<ide> * @param array $options Array of HTML options, and options listed above.
<ide> * @return string The text with links
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkEmails
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#linking-email-addresses
<ide> */
<ide> public function autoLinkEmails($text, array $options = array()) {
<ide> $options += array('escape' => true);
<ide> public function autoLinkEmails($text, array $options = array()) {
<ide> * @param string $text Text
<ide> * @param array $options Array of HTML options, and options listed above.
<ide> * @return string The text with links
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLink
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#linking-both-urls-and-email-addresses
<ide> */
<ide> public function autoLink($text, array $options = array()) {
<ide> $text = $this->autoLinkUrls($text, $options);
<ide> public function autoLink($text, array $options = array()) {
<ide> * @param array $options An array of html attributes and options.
<ide> * @return string The highlighted text
<ide> * @see String::highlight()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#highlighting-substrings
<ide> */
<ide> public function highlight($text, $phrase, array $options = array()) {
<ide> return $this->_engine->highlight($text, $phrase, $options);
<ide> public function highlight($text, $phrase, array $options = array()) {
<ide> *
<ide> * @param string $text Text
<ide> * @return string The text with proper <p> and <br /> tags
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoParagraph
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#converting-text-into-paragraphs
<ide> */
<ide> public function autoParagraph($text) {
<ide> if (trim($text) !== '') {
<ide> public function autoParagraph($text) {
<ide> * @param string $text Text
<ide> * @return string The text without links
<ide> * @see String::stripLinks()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#removing-links
<ide> */
<ide> public function stripLinks($text) {
<ide> return $this->_engine->stripLinks($text);
<ide> public function stripLinks($text) {
<ide> * @param array $options An array of html attributes and options.
<ide> * @return string Trimmed string.
<ide> * @see String::truncate()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#truncating-text
<ide> */
<ide> public function truncate($text, $length = 100, array $options = array()) {
<ide> return $this->_engine->truncate($text, $length, $options);
<ide> public function truncate($text, $length = 100, array $options = array()) {
<ide> * @param int $length Length of returned string, including ellipsis.
<ide> * @param array $options An array of html attributes and options.
<ide> * @return string Trimmed string.
<del> * @see String::tail()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::tail
<add> * @see \Cake\Utility\String::tail()
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#truncating-the-tail-of-a-string
<ide> */
<ide> public function tail($text, $length = 100, array $options = array()) {
<ide> return $this->_engine->tail($text, $length, $options);
<ide> public function tail($text, $length = 100, array $options = array()) {
<ide> * @param int $radius The amount of characters that will be returned on each side of the founded phrase
<ide> * @param string $ending Ending that will be appended
<ide> * @return string Modified string
<del> * @see String::excerpt()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
<add> * @see \Cake\Utility\String::excerpt()
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#extracting-an-excerpt
<ide> */
<ide> public function excerpt($text, $phrase, $radius = 100, $ending = '...') {
<ide> return $this->_engine->excerpt($text, $phrase, $radius, $ending);
<ide> public function excerpt($text, $phrase, $radius = 100, $ending = '...') {
<ide> * @param string $and The word used to join the last and second last items together with. Defaults to 'and'.
<ide> * @param string $separator The separator used to join all the other items together. Defaults to ', '.
<ide> * @return string The glued together string.
<del> * @see String::toList()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
<add> * @see \Cake\Utility\String::toList()
<add> * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#converting-an-array-to-sentence-form
<ide> */
<ide> public function toList($list, $and = null, $separator = ', ') {
<ide> return $this->_engine->toList($list, $and, $separator);
<ide><path>src/View/Helper/TimeHelper.php
<ide> *
<ide> * Manipulation of time data.
<ide> *
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html
<add> * @link http://book.cakephp.org/3.0/en/core-libraries/helpers/time.html
<ide> * @see \Cake\I18n\Time
<ide> */
<ide> class TimeHelper extends Helper {
<ide> class TimeHelper extends Helper {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return \Cake\I18n\Time
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function fromString($dateString, $timezone = null) {
<ide> return (new Time($dateString))->timezone($timezone);
<ide> public function fromString($dateString, $timezone = null) {
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @param string $locale Locale string.
<ide> * @return string Formatted date string
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function nice($dateString = null, $timezone = null, $locale = null) {
<ide> return (new Time($dateString))->nice($timezone, $locale);
<ide> public function nice($dateString = null, $timezone = null, $locale = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool True if datetime string is today
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function isToday($dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->isToday();
<ide> public function isToday($dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool True if datetime string is today
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function isFuture($dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->isFuture();
<ide> public function isFuture($dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool True if datetime string is today
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function isPast($dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->isPast();
<ide> public function isPast($dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool True if datetime string is within current week
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function isThisWeek($dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->isThisWeek();
<ide> public function isThisWeek($dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool True if datetime string is within the current month
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function isThisMonth($dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->isThisMonth();
<ide> public function isThisMonth($dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool True if datetime string is within current year
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function isThisYear($dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->isThisYear();
<ide> public function isThisYear($dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool True if datetime string was yesterday
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> *
<ide> */
<ide> public function wasYesterday($dateString, $timezone = null) {
<ide> public function wasYesterday($dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool True if datetime string was yesterday
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function isTomorrow($dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->isTomorrow();
<ide> public function isTomorrow($dateString, $timezone = null) {
<ide> * @param bool $range if true returns a range in Y-m-d format
<ide> * @return mixed 1, 2, 3, or 4 quarter of year or array if $range true
<ide> * @see \Cake\I18n\Time::toQuarter()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function toQuarter($dateString, $range = false) {
<ide> return (new Time($dateString))->toQuarter($range);
<ide> public function toQuarter($dateString, $range = false) {
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return int Unix timestamp
<ide> * @see \Cake\I18n\Time::toUnix()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function toUnix($dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->toUnixString();
<ide> public function toUnix($dateString, $timezone = null) {
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return string Formatted date string
<ide> * @see \Cake\I18n\Time::toAtom()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function toAtom($dateString, $timezone = null) {
<ide> $timezone = $timezone ?: date_default_timezone_get();
<ide> public function toAtom($dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return string Formatted date string
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function toRss($dateString, $timezone = null) {
<ide> $timezone = $timezone ?: date_default_timezone_get();
<ide> public function toRss($dateString, $timezone = null) {
<ide> * @param array $options Default format if timestamp is used in $dateString
<ide> * @return string Relative time string.
<ide> * @see \Cake\I18n\Time::timeAgoInWords()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function timeAgoInWords($dateTime, array $options = array()) {
<ide> $element = null;
<ide> public function timeAgoInWords($dateTime, array $options = array()) {
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool
<ide> * @see \Cake\I18n\Time::wasWithinLast()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function wasWithinLast($timeInterval, $dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->wasWithinLast($timeInterval);
<ide> public function wasWithinLast($timeInterval, $dateString, $timezone = null) {
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return bool
<ide> * @see \Cake\I18n\Time::wasWithinLast()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
<ide> */
<ide> public function isWithinNext($timeInterval, $dateString, $timezone = null) {
<ide> return (new Time($dateString, $timezone))->isWithinNext($timeInterval);
<ide> public function isWithinNext($timeInterval, $dateString, $timezone = null) {
<ide> * @param int|string|\DateTime $string UNIX timestamp, strtotime() valid string or DateTime object
<ide> * @return int UNIX timestamp
<ide> * @see \Cake\I18n\Time::gmt()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function gmt($string = null) {
<ide> return (new Time($string))->toUnixString();
<ide> public function gmt($string = null) {
<ide> * @param string|\DateTimeZone $timezone User's timezone string or DateTimeZone object
<ide> * @return string Formatted and translated date string
<ide> * @see \Cake\I18n\Time::i18nFormat()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function format($date, $format = null, $invalid = false, $timezone = null) {
<ide> return $this->i18nFormat($date, $format, $invalid, $timezone);
<ide> public function format($date, $format = null, $invalid = false, $timezone = null
<ide> * @return string Formatted and translated date string
<ide> * @throws \InvalidArgumentException When the date cannot be parsed
<ide> * @see \Cake\I18n\Time::i18nFormat()
<del> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
<ide> */
<ide> public function i18nFormat($date, $format = null, $invalid = false, $timezone = null) {
<ide> try {
<ide><path>src/View/Helper/UrlHelper.php
<ide> class UrlHelper extends Helper {
<ide> * the reverse routing features of CakePHP.
<ide> * @param bool $full If true, the full base URL will be prepended to the result
<ide> * @return string Full translated URL with base path.
<del> * @link http://book.cakephp.org/2.0/en/views/helpers.html
<ide> */
<ide> public function build($url = null, $full = false) {
<ide> return h(Router::url($url, $full)); | 44 |
Python | Python | fix python 3 syntax errors (en masse) | ae0a9409212d0072938fa60c9f85740bb89ced7e | <ide><path>research/cognitive_mapping_and_planning/scripts/script_env_vis.py
<ide> import datasets.nav_env_config as nec
<ide> import datasets.nav_env as nav_env
<ide> import cv2
<del>from datasets import factory
<del>import render.swiftshader_renderer as renderer
<add>from datasets import factory
<add>import render.swiftshader_renderer as renderer
<ide>
<ide> SwiftshaderRenderer = renderer.SwiftshaderRenderer
<ide> VisualNavigationEnv = nav_env.VisualNavigationEnv
<ide> def get_args():
<ide> navtask.camera_param.width = sz
<ide> navtask.task_params.img_height = sz
<ide> navtask.task_params.img_width = sz
<del>
<add>
<ide> # navtask.task_params.semantic_task.class_map_names = ['chair', 'door', 'table']
<ide> # navtask.task_params.type = 'to_nearest_obj_acc'
<del>
<add>
<ide> logging.info('navtask: %s', navtask)
<ide> return navtask
<ide>
<ide> def walk_through(b):
<ide>
<ide> root = tk.Tk()
<ide> image = b.render_nodes(b.task.nodes[[current_node],:])[0]
<del> print image.shape
<add> print(image.shape)
<ide> image = image.astype(np.uint8)
<ide> im = Image.fromarray(image)
<ide> im = ImageTk.PhotoImage(im)
<ide> panel = tk.Label(root, image=im)
<del>
<add>
<ide> map_size = b.traversible.shape
<ide> sc = np.max(map_size)/256.
<ide> loc = np.array([[map_size[1]/2., map_size[0]/2.]])
<ide> def up_key(event):
<ide> global current_node
<ide> current_node = b.take_action([current_node], [3], 1)[0][0]
<ide> refresh()
<del>
<add>
<ide> def right_key(event):
<ide> global current_node
<ide> current_node = b.take_action([current_node], [1], 1)[0][0]
<ide> refresh()
<ide>
<ide> def quit(event):
<del> root.destroy()
<del>
<add> root.destroy()
<add>
<ide> panel_overhead.grid(row=4, column=5, rowspan=1, columnspan=1,
<ide> sticky=tk.W+tk.E+tk.N+tk.S)
<ide> panel.bind('<Left>', left_key)
<ide> def quit(event):
<ide>
<ide> def simple_window():
<ide> root = tk.Tk()
<del>
<add>
<ide> image = np.zeros((128, 128, 3), dtype=np.uint8)
<ide> image[32:96, 32:96, 0] = 255
<ide> im = Image.fromarray(image)
<ide> im = ImageTk.PhotoImage(im)
<del>
<add>
<ide> image = np.zeros((128, 128, 3), dtype=np.uint8)
<ide> image[32:96, 32:96, 1] = 255
<ide> im2 = Image.fromarray(image)
<ide> im2 = ImageTk.PhotoImage(im2)
<del>
<add>
<ide> panel = tk.Label(root, image=im)
<del>
<add>
<ide> def left_key(event):
<ide> panel.configure(image=im2)
<ide> panel.image = im2
<ide> def quit(event):
<ide> panel.bind('q', quit)
<ide> panel.focus_set()
<ide> panel.pack(side = "bottom", fill = "both", expand = "yes")
<del> root.mainloop()
<add> root.mainloop()
<ide>
<ide> def main(_):
<ide> b = load_building(FLAGS.dataset_name, FLAGS.building_name)
<ide><path>research/cognitive_mapping_and_planning/scripts/script_plot_trajectory.py
<ide> Code for plotting trajectories in the top view, and also plot first person views
<ide> from saved trajectories. Does not run the network but only loads the mesh data
<ide> to plot the view points.
<del> CUDA_VISIBLE_DEVICES=0 LD_LIBRARY_PATH=/opt/cuda-8.0/lib64:/opt/cudnnv51/lib64
<add> CUDA_VISIBLE_DEVICES=0 LD_LIBRARY_PATH=/opt/cuda-8.0/lib64:/opt/cudnnv51/lib64
<ide> PYTHONPATH='.' PYOPENGL_PLATFORM=egl python scripts/script_plot_trajectory.py \
<ide> --first_person --num_steps 40 \
<ide> --config_name cmp.lmap_Msc.clip5.sbpd_d_r2r \
<ide> import cv2
<ide> import logging
<ide> from tensorflow.python.platform import gfile
<del>from tensorflow.python.platform import app
<del>from tensorflow.python.platform import flags
<add>from tensorflow.python.platform import app
<add>from tensorflow.python.platform import flags
<ide>
<ide> from datasets import nav_env
<del>import scripts.script_nav_agent_release as sna
<add>import scripts.script_nav_agent_release as sna
<ide> import src.file_utils as fu
<del>from src import graph_utils
<add>from src import graph_utils
<ide> from src import utils
<ide> FLAGS = flags.FLAGS
<ide>
<ide> def _compute_hardness():
<ide> # Initialize the agent.
<ide> init_env_state = e.reset(rng_data)
<ide>
<del> gt_dist_to_goal = [e.episode.dist_to_goal[0][j][s]
<add> gt_dist_to_goal = [e.episode.dist_to_goal[0][j][s]
<ide> for j, s in enumerate(e.episode.start_node_ids)]
<ide>
<ide> for j in range(args.navtask.task_params.batch_size):
<ide> def plot_trajectory_first_person(dt, orig_maps, out_dir):
<ide> out_dir = os.path.join(out_dir, FLAGS.config_name+_get_suffix_str(),
<ide> FLAGS.imset)
<ide> fu.makedirs(out_dir)
<del>
<add>
<ide> # Load the model so that we can render.
<ide> plt.set_cmap('gray')
<ide> samples_per_action = 8; wait_at_action = 0;
<del>
<add>
<ide> Writer = animation.writers['mencoder']
<del> writer = Writer(fps=3*(samples_per_action+wait_at_action),
<add> writer = Writer(fps=3*(samples_per_action+wait_at_action),
<ide> metadata=dict(artist='anonymous'), bitrate=1800)
<del>
<add>
<ide> args = sna.get_args_for_config(FLAGS.config_name + '+bench_'+FLAGS.imset)
<ide> args.navtask.logdir = None
<ide> navtask_ = copy.deepcopy(args.navtask)
<ide> def plot_trajectory_first_person(dt, orig_maps, out_dir):
<ide> R = lambda: nav_env.get_multiplexer_class(navtask_, 0)
<ide> R = R()
<ide> b = R.buildings[0]
<del>
<add>
<ide> f = [0 for _ in range(wait_at_action)] + \
<ide> [float(_)/samples_per_action for _ in range(samples_per_action)];
<del>
<add>
<ide> # Generate things for it to render.
<ide> inds_to_do = []
<ide> inds_to_do += [1, 4, 10] #1291, 1268, 1273, 1289, 1302, 1426, 1413, 1449, 1399, 1390]
<ide> def plot_trajectory_first_person(dt, orig_maps, out_dir):
<ide> # axes = [ax]
<ide> for ax in axes:
<ide> ax.set_axis_off()
<del>
<add>
<ide> node_ids = dt['all_node_ids'][i, :, 0]*1
<ide> # Prune so that last node is not repeated more than 3 times?
<ide> if np.all(node_ids[-4:] == node_ids[-1]):
<ide> def plot_trajectory_first_person(dt, orig_maps, out_dir):
<ide> node_ids_all = np.reshape(node_ids_all[:-1,:], -1)
<ide> perturbs_all = np.reshape(perturbs_all, [-1, 4])
<ide> imgs = b.render_nodes(b.task.nodes[node_ids_all,:], perturb=perturbs_all)
<del>
<add>
<ide> # Get action at each node.
<ide> actions = []
<ide> _, action_to_nodes = b.get_feasible_actions(node_ids)
<ide> for j in range(num_steps-1):
<ide> action_to_node = action_to_nodes[j]
<ide> node_to_action = dict(zip(action_to_node.values(), action_to_node.keys()))
<ide> actions.append(node_to_action[node_ids[j+1]])
<del>
<add>
<ide> def init_fn():
<ide> return fig,
<ide> gt_dist_to_goal = []
<ide> def worker(j):
<ide> img = imgs[j]; ax = axes[0]; ax.clear(); ax.set_axis_off();
<ide> img = img.astype(np.uint8); ax.imshow(img);
<ide> tt = ax.set_title(
<del> "First Person View\n" +
<del> "Top corners show diagnostics (distance, agents' action) not input to agent.",
<add> "First Person View\n" +
<add> "Top corners show diagnostics (distance, agents' action) not input to agent.",
<ide> fontsize=12)
<ide> plt.setp(tt, color='white')
<ide>
<ide> def worker(j):
<ide> fontsize=20, color='red',
<ide> transform=ax.transAxes, alpha=1.0)
<ide> t.set_bbox(dict(color='white', alpha=0.85, pad=-0.1))
<del>
<add>
<ide> # Action to take.
<ide> action_latex = ['$\odot$ ', '$\curvearrowright$ ', '$\curvearrowleft$ ', '$\Uparrow$ ']
<ide> t = ax.text(0.99, 0.99, action_latex[actions[step_number]],
<ide> def worker(j):
<ide> locs = np.expand_dims(locs, axis=0)
<ide> ax.plot(locs[:,0], locs[:,1], 'r.', alpha=1.0, linewidth=0, markersize=4)
<ide> tt = ax.set_title('Trajectory in topview', fontsize=14)
<del> plt.setp(tt, color='white')
<add> plt.setp(tt, color='white')
<ide> return fig,
<ide>
<ide> line_ani = animation.FuncAnimation(fig, worker,
<ide> def worker(j):
<ide> tmp_file_name = 'tmp.mp4'
<ide> line_ani.save(tmp_file_name, writer=writer, savefig_kwargs={'facecolor':'black'})
<ide> out_file_name = os.path.join(out_dir, 'vis_{:04d}.mp4'.format(i))
<del> print out_file_name
<add> print(out_file_name)
<ide>
<ide> if fu.exists(out_file_name):
<ide> gfile.Remove(out_file_name)
<ide> def plot_trajectory(dt, hardness, orig_maps, out_dir):
<ide> out_file = os.path.join(out_dir, 'all_locs_at_t.pkl')
<ide> dt['hardness'] = hardness
<ide> utils.save_variables(out_file, dt.values(), dt.keys(), overwrite=True)
<del>
<add>
<ide> #Plot trajectories onto the maps
<ide> plt.set_cmap('gray')
<ide> for i in range(4000):
<ide> goal_loc = dt['all_goal_locs'][i, :, :]
<del> locs = np.concatenate((dt['all_locs'][i,:,:],
<add> locs = np.concatenate((dt['all_locs'][i,:,:],
<ide> dt['all_locs'][i,:,:]), axis=0)
<ide> xymin = np.minimum(np.min(goal_loc, axis=0), np.min(locs, axis=0))
<ide> xymax = np.maximum(np.max(goal_loc, axis=0), np.max(locs, axis=0))
<ide> def plot_trajectory(dt, hardness, orig_maps, out_dir):
<ide> uniq = np.array(uniq)
<ide> all_locs = all_locs[uniq, :]
<ide>
<del> ax.plot(dt['all_locs'][i, 0, 0],
<add> ax.plot(dt['all_locs'][i, 0, 0],
<ide> dt['all_locs'][i, 0, 1], 'b.', markersize=24)
<del> ax.plot(dt['all_goal_locs'][i, 0, 0],
<add> ax.plot(dt['all_goal_locs'][i, 0, 0],
<ide> dt['all_goal_locs'][i, 0, 1], 'g*', markersize=19)
<ide> ax.plot(all_locs[:,0], all_locs[:,1], 'r', alpha=0.4, linewidth=2)
<ide> ax.scatter(all_locs[:,0], all_locs[:,1],
<del> c=5+np.arange(all_locs.shape[0])*1./all_locs.shape[0],
<add> c=5+np.arange(all_locs.shape[0])*1./all_locs.shape[0],
<ide> cmap='Reds', s=30, linewidth=0)
<ide> ax.imshow(orig_maps, origin='lower', vmin=-1.0, vmax=2.0, aspect='equal')
<ide> ax.set_xlim([xy1[0], xy2[0]])
<ide> ax.set_ylim([xy1[1], xy2[1]])
<del>
<add>
<ide> file_name = os.path.join(out_dir, 'trajectory_{:04d}.png'.format(i))
<del> print file_name
<del> with fu.fopen(file_name, 'w') as f:
<add> print(file_name)
<add> with fu.fopen(file_name, 'w') as f:
<ide> plt.savefig(f)
<ide> plt.close(fig)
<del>
<add>
<ide>
<ide> def main(_):
<ide> a = _load_trajectory()
<ide> h_dists, gt_dists, orig_maps = _compute_hardness()
<ide> hardness = 1.-h_dists*1./ gt_dists
<del>
<add>
<ide> if FLAGS.top_view:
<ide> plot_trajectory(a, hardness, orig_maps, out_dir=FLAGS.out_dir)
<ide>
<ide> if FLAGS.first_person:
<ide> plot_trajectory_first_person(a, orig_maps, out_dir=FLAGS.out_dir)
<del>
<add>
<ide> if __name__ == '__main__':
<ide> app.run()
<ide><path>research/cognitive_mapping_and_planning/src/utils.py
<ide> """
<ide>
<ide> import numpy as np, cPickle, os, time
<add>from six.moves import xrange
<ide> import src.file_utils as fu
<ide> import logging
<ide>
<ide> def tic_toc_print(interval, string):
<ide> global tic_toc_print_time_old
<ide> if 'tic_toc_print_time_old' not in globals():
<ide> tic_toc_print_time_old = time.time()
<del> print string
<add> print(string)
<ide> else:
<ide> new_time = time.time()
<ide> if new_time - tic_toc_print_time_old > interval:
<ide> tic_toc_print_time_old = new_time;
<del> print string
<add> print(string)
<ide>
<ide> def mkdir_if_missing(output_dir):
<ide> if not fu.exists(output_dir):
<ide> def load_variables(pickle_file_name):
<ide> def voc_ap(rec, prec):
<ide> rec = rec.reshape((-1,1))
<ide> prec = prec.reshape((-1,1))
<del> z = np.zeros((1,1))
<add> z = np.zeros((1,1))
<ide> o = np.ones((1,1))
<ide> mrec = np.vstack((z, rec, o))
<ide> mpre = np.vstack((z, prec, z))
<ide> def calc_pr(gt, out, wt=None):
<ide>
<ide> ap = voc_ap(rec, prec)
<ide> return ap, rec, prec
<del>
<ide><path>research/compression/entropy_coder/core/entropy_coder_single.py
<ide> def main(_):
<ide> #iteration = FLAGS.iteration
<ide>
<ide> if not tf.gfile.Exists(FLAGS.input_codes):
<del> print '\nInput codes not found.\n'
<add> print('\nInput codes not found.\n')
<ide> return
<ide>
<ide> with tf.gfile.FastGFile(FLAGS.input_codes, 'rb') as code_file:
<ide><path>research/compression/entropy_coder/core/entropy_coder_train.py
<ide> def train():
<ide> 'code_length': model.average_code_length
<ide> }
<ide> np_tensors = sess.run(tf_tensors, feed_dict=feed_dict)
<del> print np_tensors['code_length']
<add> print(np_tensors['code_length'])
<ide>
<ide> sv.Stop()
<ide>
<ide><path>research/differential_privacy/multiple_teachers/analysis.py
<ide> import os
<ide> import math
<ide> import numpy as np
<add>from six.moves import xrange
<ide> import tensorflow as tf
<ide>
<ide> from differential_privacy.multiple_teachers.input import maybe_download
<ide> def logmgf_exact(q, priv_eps, l):
<ide> try:
<ide> log_t = math.log(t)
<ide> except ValueError:
<del> print "Got ValueError in math.log for values :" + str((q, priv_eps, l, t))
<add> print("Got ValueError in math.log for values :" + str((q, priv_eps, l, t)))
<ide> log_t = priv_eps * l
<ide> else:
<ide> log_t = priv_eps * l
<ide> def sens_at_k(counts, noise_eps, l, k):
<ide> """
<ide> counts_sorted = sorted(counts, reverse=True)
<ide> if 0.5 * noise_eps * l > 1:
<del> print "l too large to compute sensitivity"
<add> print("l too large to compute sensitivity")
<ide> return 0
<ide> # Now we can assume that at k, gap remains positive
<ide> # or we have reached the point where logmgf_exact is
<ide> def main(unused_argv):
<ide> # Solving gives eps = (alpha - ln (delta))/l
<ide> eps_list_nm = (total_log_mgf_nm - math.log(delta)) / l_list
<ide>
<del> print "Epsilons (Noisy Max): " + str(eps_list_nm)
<del> print "Smoothed sensitivities (Noisy Max): " + str(total_ss_nm / l_list)
<add> print("Epsilons (Noisy Max): " + str(eps_list_nm))
<add> print("Smoothed sensitivities (Noisy Max): " + str(total_ss_nm / l_list))
<ide>
<ide> # If beta < eps / 2 ln (1/delta), then adding noise Lap(1) * 2 SS/eps
<ide> # is eps,delta DP
<ide> def main(unused_argv):
<ide> # Print the first one's scale
<ide> ss_eps = 2.0 * beta * math.log(1/delta)
<ide> ss_scale = 2.0 / ss_eps
<del> print "To get an " + str(ss_eps) + "-DP estimate of epsilon, "
<del> print "..add noise ~ " + str(ss_scale)
<del> print "... times " + str(total_ss_nm / l_list)
<del> print "Epsilon = " + str(min(eps_list_nm)) + "."
<add> print("To get an " + str(ss_eps) + "-DP estimate of epsilon, ")
<add> print("..add noise ~ " + str(ss_scale))
<add> print("... times " + str(total_ss_nm / l_list))
<add> print("Epsilon = " + str(min(eps_list_nm)) + ".")
<ide> if min(eps_list_nm) == eps_list_nm[-1]:
<del> print "Warning: May not have used enough values of l"
<add> print("Warning: May not have used enough values of l")
<ide>
<ide> # Data independent bound, as mechanism is
<ide> # 2*noise_eps DP.
<ide> def main(unused_argv):
<ide> [logmgf_exact(1.0, 2.0 * noise_eps, l) for l in l_list])
<ide>
<ide> data_ind_eps_list = (data_ind_log_mgf - math.log(delta)) / l_list
<del> print "Data independent bound = " + str(min(data_ind_eps_list)) + "."
<add> print("Data independent bound = " + str(min(data_ind_eps_list)) + ".")
<ide>
<ide> return
<ide>
<ide><path>research/differential_privacy/privacy_accountant/python/gaussian_moments.py
<ide> accountant.py for the context), run the same loop above with verify=True
<ide> passed to compute_log_moment.
<ide> """
<add>from __future__ import print_function
<add>
<ide> import math
<ide> import sys
<ide>
<ide> import numpy as np
<ide> import scipy.integrate as integrate
<ide> import scipy.stats
<add>from six.moves import xrange
<ide> from sympy.mpmath import mp
<ide>
<ide>
<ide> def compute_a(sigma, q, lmbd, verbose=False):
<ide> a_lambda_exact = ((1.0 - q) * a_lambda_first_term_exact +
<ide> q * a_lambda_second_term_exact)
<ide> if verbose:
<del> print "A: by binomial expansion {} = {} + {}".format(
<add> print("A: by binomial expansion {} = {} + {}".format(
<ide> a_lambda_exact,
<ide> (1.0 - q) * a_lambda_first_term_exact,
<del> q * a_lambda_second_term_exact)
<add> q * a_lambda_second_term_exact))
<ide> return _to_np_float64(a_lambda_exact)
<ide>
<ide>
<ide> def compute_b(sigma, q, lmbd, verbose=False):
<ide> b_fn = lambda z: (np.power(mu0(z) / mu(z), lmbd) -
<ide> np.power(mu(-z) / mu0(z), lmbd))
<ide> if verbose:
<del> print "M =", m
<del> print "f(-M) = {} f(M) = {}".format(b_fn(-m), b_fn(m))
<add> print("M =", m)
<add> print("f(-M) = {} f(M) = {}".format(b_fn(-m), b_fn(m)))
<ide> assert b_fn(-m) < 0 and b_fn(m) < 0
<ide>
<ide> b_lambda_int1_fn = lambda z: (mu0(z) *
<ide> def compute_b(sigma, q, lmbd, verbose=False):
<ide> b_bound = a_lambda_m1 + b_int1 - b_int2
<ide>
<ide> if verbose:
<del> print "B: by numerical integration", b_lambda
<del> print "B must be no more than ", b_bound
<del> print b_lambda, b_bound
<add> print("B: by numerical integration", b_lambda)
<add> print("B must be no more than ", b_bound)
<add> print(b_lambda, b_bound)
<ide> return _to_np_float64(b_lambda)
<ide>
<ide>
<ide> def compute_a_mp(sigma, q, lmbd, verbose=False):
<ide> a_lambda_second_term = integral_inf_mp(a_lambda_second_term_fn)
<ide>
<ide> if verbose:
<del> print "A: by numerical integration {} = {} + {}".format(
<add> print("A: by numerical integration {} = {} + {}".format(
<ide> a_lambda,
<ide> (1 - q) * a_lambda_first_term,
<del> q * a_lambda_second_term)
<add> q * a_lambda_second_term))
<ide>
<ide> return _to_np_float64(a_lambda)
<ide>
<ide> def compute_b_mp(sigma, q, lmbd, verbose=False):
<ide> b_fn = lambda z: ((mu0(z) / mu(z)) ** lmbd_int -
<ide> (mu(-z) / mu0(z)) ** lmbd_int)
<ide> if verbose:
<del> print "M =", m
<del> print "f(-M) = {} f(M) = {}".format(b_fn(-m), b_fn(m))
<add> print("M =", m)
<add> print("f(-M) = {} f(M) = {}".format(b_fn(-m), b_fn(m)))
<ide> assert b_fn(-m) < 0 and b_fn(m) < 0
<ide>
<ide> b_lambda_int1_fn = lambda z: mu0(z) * (mu0(z) / mu(z)) ** lmbd_int
<ide> def compute_b_mp(sigma, q, lmbd, verbose=False):
<ide> b_bound = a_lambda_m1 + b_int1 - b_int2
<ide>
<ide> if verbose:
<del> print "B by numerical integration", b_lambda
<del> print "B must be no more than ", b_bound
<add> print("B by numerical integration", b_lambda)
<add> print("B must be no more than ", b_bound)
<ide> assert b_lambda < b_bound + 1e-5
<ide> return _to_np_float64(b_lambda)
<ide>
<ide><path>research/neural_gpu/neural_gpu.py
<ide> import time
<ide>
<ide> import numpy as np
<add>from six.moves import xrange
<ide> import tensorflow as tf
<ide>
<ide> from tensorflow.python.framework import function
<ide> def attention_query(query, attn_v):
<ide> return tf.reduce_sum(encoder_outputs * tf.expand_dims(mask, 2), 1)
<ide>
<ide> with tf.variable_scope("decoder"):
<del> def decoder_loop_fn((state, prev_cell_out, _), (cell_inp, cur_tgt)):
<add> def decoder_loop_fn(state__prev_cell_out__unused, cell_inp__cur_tgt):
<ide> """Decoder loop function."""
<add> state, prev_cell_out, _ = state__prev_cell_out__unused
<add> cell_inp, cur_tgt = cell_inp__cur_tgt
<ide> attn_q = tf.layers.dense(prev_cell_out, height * nmaps,
<ide> name="attn_query")
<ide> attn_res = attention_query(attn_q, tf.get_variable(
<ide><path>research/neural_gpu/neural_gpu_trainer.py
<ide> import time
<ide>
<ide> import numpy as np
<add>from six.moves import xrange
<ide> import tensorflow as tf
<ide>
<ide> import program_utils
<ide> def read_data(source_path, target_path, buckets, max_size=None, print_out=True):
<ide> while source and target and (not max_size or counter < max_size):
<ide> counter += 1
<ide> if counter % 100000 == 0 and print_out:
<del> print " reading data line %d" % counter
<add> print(" reading data line %d" % counter)
<ide> sys.stdout.flush()
<ide> source_ids = [int(x) for x in source.split()]
<ide> target_ids = [int(x) for x in target.split()]
<ide> def read_data_into_global(source_path, target_path, buckets,
<ide> global_train_set["wmt"].append(data_set)
<ide> train_total_size = calculate_buckets_scale(data_set, buckets, "wmt")
<ide> if print_out:
<del> print " Finished global data reading (%d)." % train_total_size
<add> print(" Finished global data reading (%d)." % train_total_size)
<ide>
<ide>
<ide> def initialize(sess=None):
<ide> def score_beams_prog(beams, target, inp, history, print_out=False,
<ide> for h in history]
<ide> tgt_set = set(target)
<ide> if print_out:
<del> print "target: ", tgt_prog
<add> print("target: ", tgt_prog)
<ide> inps, tgt_outs = [], []
<ide> for i in xrange(3):
<ide> ilist = [inp[i + 1, l] for l in xrange(inp.shape[1])]
<ide> def score_beams_prog(beams, target, inp, history, print_out=False,
<ide> if len(olist) == 1:
<ide> tgt_outs.append(olist[0])
<ide> else:
<del> print [program_utils.prog_vocab[x] for x in ilist if x > 0]
<del> print olist
<del> print tgt_prog
<del> print program_utils.evaluate(tgt_prog, {"a": inps[-1]})
<del> print "AAAAA"
<add> print([program_utils.prog_vocab[x] for x in ilist if x > 0])
<add> print(olist)
<add> print(tgt_prog)
<add> print(program_utils.evaluate(tgt_prog, {"a": inps[-1]}))
<add> print("AAAAA")
<ide> tgt_outs.append(olist[0])
<ide> if not test_mode:
<ide> for _ in xrange(7):
<ide> def score_beams_prog(beams, target, inp, history, print_out=False,
<ide> best_prog = b_prog
<ide> best_score = score
<ide> if print_out:
<del> print "best score: ", best_score, " best prog: ", best_prog
<add> print("best score: ", best_score, " best prog: ", best_prog)
<ide> return best, best_score
<ide>
<ide>
<ide> def train():
<ide> inp = new_inp
<ide> # If all results are great, stop (todo: not to wait for all?).
<ide> if FLAGS.nprint > 1:
<del> print scores
<add> print(scores)
<ide> if sum(scores) / float(len(scores)) >= 10.0:
<ide> break
<ide> # The final step with the true target.
<ide> def train():
<ide> errors, total, seq_err = data.accuracy(
<ide> inp, res, target, batch_size, 0, new_target, scores)
<ide> if FLAGS.nprint > 1:
<del> print "seq_err: ", seq_err
<add> print("seq_err: ", seq_err)
<ide> acc_total += total
<ide> acc_errors += errors
<ide> acc_seq_err += seq_err
<ide> def interactive():
<ide> for v in tf.trainable_variables():
<ide> shape = v.get_shape().as_list()
<ide> total += mul(shape)
<del> print (v.name, shape, mul(shape))
<del> print total
<add> print(v.name, shape, mul(shape))
<add> print(total)
<ide> # Start interactive loop.
<ide> sys.stdout.write("Input to Neural GPU Translation Model.\n")
<ide> sys.stdout.write("> ")
<ide> def interactive():
<ide> normalize_digits=FLAGS.normalize_digits)
<ide> else:
<ide> token_ids = wmt.sentence_to_token_ids(inpt, en_vocab)
<del> print [rev_en_vocab[t] for t in token_ids]
<add> print([rev_en_vocab[t] for t in token_ids])
<ide> # Which bucket does it belong to?
<ide> buckets = [b for b in xrange(len(data.bins))
<ide> if data.bins[b] >= max(len(token_ids), len(cures))]
<ide> def interactive():
<ide> loss = loss[0] - (data.bins[bucket_id] * FLAGS.length_norm)
<ide> outputs = [int(np.argmax(logit, axis=1))
<ide> for logit in output_logits]
<del> print [rev_fr_vocab[t] for t in outputs]
<del> print loss, data.bins[bucket_id]
<del> print linearize(outputs, rev_fr_vocab)
<add> print([rev_fr_vocab[t] for t in outputs])
<add> print(loss, data.bins[bucket_id])
<add> print(linearize(outputs, rev_fr_vocab))
<ide> cures.append(outputs[gen_idx])
<del> print cures
<del> print linearize(cures, rev_fr_vocab)
<add> print(cures)
<add> print(linearize(cures, rev_fr_vocab))
<ide> if FLAGS.simple_tokenizer:
<ide> cur_out = outputs
<ide> if wmt.EOS_ID in cur_out:
<ide> def interactive():
<ide> if loss < result_cost:
<ide> result = outputs
<ide> result_cost = loss
<del> print ("FINAL", result_cost)
<del> print [rev_fr_vocab[t] for t in result]
<del> print linearize(result, rev_fr_vocab)
<add> print("FINAL", result_cost)
<add> print([rev_fr_vocab[t] for t in result])
<add> print(linearize(result, rev_fr_vocab))
<ide> else:
<del> print "TOOO_LONG"
<add> print("TOOO_LONG")
<ide> sys.stdout.write("> ")
<ide> sys.stdout.flush()
<ide> inpt = sys.stdin.readline(), ""
<ide><path>research/neural_gpu/program_utils.py
<ide> def __eq__(self, other):
<ide> if not isinstance(other, ListType):
<ide> return False
<ide> return self.arg == other.arg
<del>
<add>
<ide> def __hash__(self):
<ide> return hash(self.arg)
<ide>
<ide> def __hash__(self):
<ide>
<ide> class Function(object):
<ide> def __init__(self, name, arg_types, output_type, fn_arg_types = None):
<del> self.name = name
<add> self.name = name
<ide> self.arg_types = arg_types
<ide> self.fn_arg_types = fn_arg_types or []
<ide> self.output_type = output_type
<ide> def minus_one(x): return x - 1
<ide> def times_two(x): return x * 2
<ide> def neg(x): return x * (-1)
<ide> def div_two(x): return int(x/2)
<del>def sq(x): return x**2
<add>def sq(x): return x**2
<ide> def times_three(x): return x * 3
<ide> def div_three(x): return int(x/3)
<ide> def times_four(x): return x * 4
<ide> def div_four(x): return int(x/4)
<ide>
<del># Int -> Bool
<del>def pos(x): return x > 0
<add># Int -> Bool
<add>def pos(x): return x > 0
<ide> def neg(x): return x < 0
<ide> def even(x): return x%2 == 0
<ide> def odd(x): return x%2 == 1
<ide> def sub(x, y): return x - y
<ide> def mul(x, y): return x * y
<ide>
<ide> # HOFs
<del>f_map = Function("map", [ListType("Int")],
<del> ListType("Int"),
<add>f_map = Function("map", [ListType("Int")],
<add> ListType("Int"),
<ide> [FunctionType(["Int", "Int"])])
<del>f_filter = Function("filter", [ListType("Int")],
<del> ListType("Int"),
<add>f_filter = Function("filter", [ListType("Int")],
<add> ListType("Int"),
<ide> [FunctionType(["Int", "Bool"])])
<del>f_count = Function("c_count", [ListType("Int")],
<del> "Int",
<add>f_count = Function("c_count", [ListType("Int")],
<add> "Int",
<ide> [FunctionType(["Int", "Bool"])])
<ide> def c_count(f, xs): return len([x for x in xs if f(x)])
<ide>
<del>f_zipwith = Function("c_zipwith", [ListType("Int"), ListType("Int")],
<del> ListType("Int"),
<add>f_zipwith = Function("c_zipwith", [ListType("Int"), ListType("Int")],
<add> ListType("Int"),
<ide> [FunctionType(["Int", "Int", "Int"])]) #FIX
<ide> def c_zipwith(f, xs, ys): return [f(x, y) for (x, y) in zip(xs, ys)]
<ide>
<ide> f_scan = Function("c_scan", [ListType("Int")],
<del> ListType("Int"),
<add> ListType("Int"),
<ide> [FunctionType(["Int", "Int", "Int"])])
<ide> def c_scan(f, xs):
<ide> out = xs
<ide> def evaluate(program_str, input_names_to_vals, default="ERROR"):
<ide> with stdoutIO() as s:
<ide> # pylint: disable=bare-except
<ide> try:
<del> exec exec_str + " print(out)"
<add> exec(exec_str + " print(out)")
<ide> return s.getvalue()[:-1]
<ide> except:
<ide> return default
<ide> def evaluate(program_str, input_names_to_vals, default="ERROR"):
<ide>
<ide> class Statement(object):
<ide> """Statement class."""
<del>
<add>
<ide> def __init__(self, fn, output_var, arg_vars, fn_args=None):
<ide> self.fn = fn
<ide> self.output_var = output_var
<ide> def evaluate(self, inputs):
<ide>
<ide> with stdoutIO() as s:
<ide> # pylint: disable=exec-used
<del> exec inp_str + self.body + "; print(out)"
<add> exec(inp_str + self.body + "; print(out)")
<ide> # pylint: enable=exec-used
<ide> return s.getvalue()[:-1]
<ide>
<ide> def mk_inp(l):
<ide> else:
<ide> outcomes_to_programs[outcome_str] = t.flat_str()
<ide> if counter % 5000 == 0:
<del> print "== proggen: tried: " + str(counter)
<del> print "== proggen: kept: " + str(len(outcomes_to_programs))
<add> print("== proggen: tried: " + str(counter))
<add> print("== proggen: kept: " + str(len(outcomes_to_programs)))
<ide>
<ide> if counter % 250000 == 0 and save_prefix is not None:
<del> print "saving..."
<add> print("saving...")
<ide> save_counter = 0
<ide> progfilename = os.path.join(save_prefix, "prog_" + str(counter) + ".txt")
<ide> iofilename = os.path.join(save_prefix, "io_" + str(counter) + ".txt")
<ide> def mk_inp(l):
<ide> for (o, p) in outcomes_to_programs.iteritems():
<ide> save_counter += 1
<ide> if save_counter % 500 == 0:
<del> print "saving %d of %d" % (save_counter, len(outcomes_to_programs))
<add> print("saving %d of %d" % (save_counter, len(outcomes_to_programs)))
<ide> fp.write(p+"\n")
<ide> fi.write(o+"\n")
<ide> ftp.write(str(tokenize(p, tokens))+"\n")
<ide><path>research/neural_gpu/wmt_utils.py
<ide> # ==============================================================================
<ide> """Utilities for downloading data from WMT, tokenizing, vocabularies."""
<ide>
<add>from __future__ import print_function
<add>
<ide> import gzip
<ide> import os
<ide> import re
<ide> def maybe_download(directory, filename, url):
<ide> """Download filename from url unless it's already in directory."""
<ide> if not tf.gfile.Exists(directory):
<del> print "Creating directory %s" % directory
<add> print("Creating directory %s" % directory)
<ide> os.mkdir(directory)
<ide> filepath = os.path.join(directory, filename)
<ide> if not tf.gfile.Exists(filepath):
<del> print "Downloading %s to %s" % (url, filepath)
<add> print("Downloading %s to %s" % (url, filepath))
<ide> filepath, _ = urllib.request.urlretrieve(url, filepath)
<ide> statinfo = os.stat(filepath)
<del> print "Successfully downloaded", filename, statinfo.st_size, "bytes"
<add> print("Successfully downloaded", filename, statinfo.st_size, "bytes")
<ide> return filepath
<ide>
<ide>
<ide> def gunzip_file(gz_path, new_path):
<ide> """Unzips from gz_path into new_path."""
<del> print "Unpacking %s to %s" % (gz_path, new_path)
<add> print("Unpacking %s to %s" % (gz_path, new_path))
<ide> with gzip.open(gz_path, "rb") as gz_file:
<ide> with open(new_path, "wb") as new_file:
<ide> for line in gz_file:
<ide> def get_wmt_enfr_train_set(directory):
<ide> tf.gfile.Exists(train_path +".en")):
<ide> corpus_file = maybe_download(directory, "training-giga-fren.tar",
<ide> _WMT_ENFR_TRAIN_URL)
<del> print "Extracting tar file %s" % corpus_file
<add> print("Extracting tar file %s" % corpus_file)
<ide> with tarfile.open(corpus_file, "r") as corpus_tar:
<ide> corpus_tar.extractall(directory)
<ide> gunzip_file(train_path + ".fr.gz", train_path + ".fr")
<ide> def get_wmt_enfr_dev_set(directory):
<ide> if not (tf.gfile.Exists(dev_path + ".fr") and
<ide> tf.gfile.Exists(dev_path + ".en")):
<ide> dev_file = maybe_download(directory, "dev-v2.tgz", _WMT_ENFR_DEV_URL)
<del> print "Extracting tgz file %s" % dev_file
<add> print("Extracting tgz file %s" % dev_file)
<ide> with tarfile.open(dev_file, "r:gz") as dev_tar:
<ide> fr_dev_file = dev_tar.getmember("dev/" + dev_name + ".fr")
<ide> en_dev_file = dev_tar.getmember("dev/" + dev_name + ".en")
<ide> def create_vocabulary(vocabulary_path, data_path, max_vocabulary_size,
<ide> normalize_digits: Boolean; if true, all digits are replaced by 0s.
<ide> """
<ide> if not tf.gfile.Exists(vocabulary_path):
<del> print "Creating vocabulary %s from data %s" % (vocabulary_path, data_path)
<add> print("Creating vocabulary %s from data %s" % (vocabulary_path, data_path))
<ide> vocab, chars = {}, {}
<ide> for c in _PUNCTUATION:
<ide> chars[c] = 1
<ide> def create_vocabulary(vocabulary_path, data_path, max_vocabulary_size,
<ide> line = " ".join(line_in.split())
<ide> counter += 1
<ide> if counter % 100000 == 0:
<del> print " processing fr line %d" % counter
<add> print(" processing fr line %d" % counter)
<ide> for c in line:
<ide> if c in chars:
<ide> chars[c] += 1
<ide> def create_vocabulary(vocabulary_path, data_path, max_vocabulary_size,
<ide> line = " ".join(line_in.split())
<ide> counter += 1
<ide> if counter % 100000 == 0:
<del> print " processing en line %d" % counter
<add> print(" processing en line %d" % counter)
<ide> for c in line:
<ide> if c in chars:
<ide> chars[c] += 1
<ide> def data_to_token_ids(data_path, target_path, vocabulary_path,
<ide> normalize_digits: Boolean; if true, all digits are replaced by 0s.
<ide> """
<ide> if not tf.gfile.Exists(target_path):
<del> print "Tokenizing data in %s" % data_path
<add> print("Tokenizing data in %s" % data_path)
<ide> vocab, _ = initialize_vocabulary(vocabulary_path)
<ide> with tf.gfile.GFile(data_path, mode="rb") as data_file:
<ide> with tf.gfile.GFile(target_path, mode="w") as tokens_file:
<ide> counter = 0
<ide> for line in data_file:
<ide> counter += 1
<ide> if counter % 100000 == 0:
<del> print " tokenizing line %d" % counter
<add> print(" tokenizing line %d" % counter)
<ide> token_ids = sentence_to_token_ids(line, vocab, tokenizer,
<ide> normalize_digits)
<ide> tokens_file.write(" ".join([str(tok) for tok in token_ids]) + "\n")
<ide><path>research/neural_programmer/data_utils.py
<ide> """Functions for constructing vocabulary, converting the examples to integer format and building the required masks for batch computation Author: aneelakantan (Arvind Neelakantan)
<ide> """
<ide>
<add>from __future__ import print_function
<add>
<ide> import copy
<ide> import numbers
<ide> import numpy as np
<ide> def add_special_words(utility):
<ide> utility.reverse_word_ids[utility.word_ids[
<ide> utility.entry_match_token]] = utility.entry_match_token
<ide> utility.entry_match_token_id = utility.word_ids[utility.entry_match_token]
<del> print "entry match token: ", utility.word_ids[
<del> utility.entry_match_token], utility.entry_match_token_id
<add> print("entry match token: ", utility.word_ids[
<add> utility.entry_match_token], utility.entry_match_token_id)
<ide> utility.words.append(utility.column_match_token)
<ide> utility.word_ids[utility.column_match_token] = len(utility.word_ids)
<ide> utility.reverse_word_ids[utility.word_ids[
<ide> utility.column_match_token]] = utility.column_match_token
<ide> utility.column_match_token_id = utility.word_ids[utility.column_match_token]
<del> print "entry match token: ", utility.word_ids[
<del> utility.column_match_token], utility.column_match_token_id
<add> print("entry match token: ", utility.word_ids[
<add> utility.column_match_token], utility.column_match_token_id)
<ide> utility.words.append(utility.dummy_token)
<ide> utility.word_ids[utility.dummy_token] = len(utility.word_ids)
<ide> utility.reverse_word_ids[utility.word_ids[
<ide><path>research/neural_programmer/model.py
<ide> """Author: aneelakantan (Arvind Neelakantan)
<ide> """
<ide>
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<ide> import tensorflow as tf
<ide> import nn_utils
<ide> def batch_process(self):
<ide> self.batch_log_prob = tf.zeros([self.batch_size], dtype=self.data_type)
<ide> #Perform max_passes and at each pass select operation and column
<ide> for curr_pass in range(max_passes):
<del> print "step: ", curr_pass
<add> print("step: ", curr_pass)
<ide> output, select, softmax, soft_softmax, column_softmax, soft_column_softmax = self.one_pass(
<ide> select, question_embedding, hidden_vectors, hprev, prev_select_1,
<ide> curr_pass)
<ide> def create_graph(self, params, global_step):
<ide> self.params = params
<ide> batch_size = self.batch_size
<ide> learning_rate = tf.cast(self.utility.FLAGS.learning_rate, self.data_type)
<del> self.total_cost = self.compute_error()
<add> self.total_cost = self.compute_error()
<ide> optimize_params = self.params.values()
<ide> optimize_names = self.params.keys()
<del> print "optimize params ", optimize_names
<add> print("optimize params ", optimize_names)
<ide> if (self.utility.FLAGS.l2_regularizer > 0.0):
<ide> reg_cost = 0.0
<ide> for ind_param in self.params.keys():
<ide> def create_graph(self, params, global_step):
<ide> grads = tf.gradients(self.total_cost, optimize_params, name="gradients")
<ide> grad_norm = 0.0
<ide> for p, name in zip(grads, optimize_names):
<del> print "grads: ", p, name
<add> print("grads: ", p, name)
<ide> if isinstance(p, tf.IndexedSlices):
<ide> grad_norm += tf.reduce_sum(p.values * p.values)
<ide> elif not (p == None):
<ide> def create_graph(self, params, global_step):
<ide> learning_rate,
<ide> epsilon=tf.cast(self.utility.FLAGS.eps, self.data_type),
<ide> use_locking=True)
<del> self.step = adam.apply_gradients(zip(grads, optimize_params),
<add> self.step = adam.apply_gradients(zip(grads, optimize_params),
<ide> global_step=self.global_step)
<ide> self.init_op = tf.global_variables_initializer()
<del>
<ide><path>research/neural_programmer/neural_programmer.py
<ide> def evaluate(sess, data, batch_size, graph, i):
<ide> graph))
<ide> gc += ct * batch_size
<ide> num_examples += batch_size
<del> print "dev set accuracy after ", i, " : ", gc / num_examples
<del> print num_examples, len(data)
<del> print "--------"
<add> print("dev set accuracy after ", i, " : ", gc / num_examples)
<add> print(num_examples, len(data))
<add> print("--------")
<ide>
<ide>
<ide> def Train(graph, utility, batch_size, train_data, sess, model_dir,
<ide> def Train(graph, utility, batch_size, train_data, sess, model_dir,
<ide> if (i > 0 and i % FLAGS.eval_cycle == 0):
<ide> end = time.time()
<ide> time_taken = end - start
<del> print "step ", i, " ", time_taken, " seconds "
<add> print("step ", i, " ", time_taken, " seconds ")
<ide> start = end
<del> print " printing train set loss: ", train_set_loss / utility.FLAGS.eval_cycle
<add> print(" printing train set loss: ", train_set_loss / utility.FLAGS.eval_cycle)
<ide> train_set_loss = 0.0
<ide>
<ide>
<ide> def master(train_data, dev_data, utility):
<ide> #creates TF graph and calls trainer or evaluator
<del> batch_size = utility.FLAGS.batch_size
<add> batch_size = utility.FLAGS.batch_size
<ide> model_dir = utility.FLAGS.output_dir + "/model" + utility.FLAGS.job_id + "/"
<ide> #create all paramters of the model
<ide> param_class = parameters.Parameters(utility)
<ide> def master(train_data, dev_data, utility):
<ide> file_list = sorted(selected_models.items(), key=lambda x: x[0])
<ide> if (len(file_list) > 0):
<ide> file_list = file_list[0:len(file_list) - 1]
<del> print "list of models: ", file_list
<add> print("list of models: ", file_list)
<ide> for model_file in file_list:
<ide> model_file = model_file[1]
<del> print "restoring: ", model_file
<add> print("restoring: ", model_file)
<ide> saver.restore(sess, model_dir + "/" + model_file)
<ide> model_step = int(
<ide> model_file.split("_")[len(model_file.split("_")) - 1])
<del> print "evaluating on dev ", model_file, model_step
<add> print("evaluating on dev ", model_file, model_step)
<ide> evaluate(sess, dev_data, batch_size, graph, model_step)
<ide> else:
<ide> ckpt = tf.train.get_checkpoint_state(model_dir)
<del> print "model dir: ", model_dir
<add> print("model dir: ", model_dir)
<ide> if (not (tf.gfile.IsDirectory(utility.FLAGS.output_dir))):
<del> print "create dir: ", utility.FLAGS.output_dir
<add> print("create dir: ", utility.FLAGS.output_dir)
<ide> tf.gfile.MkDir(utility.FLAGS.output_dir)
<ide> if (not (tf.gfile.IsDirectory(model_dir))):
<del> print "create dir: ", model_dir
<add> print("create dir: ", model_dir)
<ide> tf.gfile.MkDir(model_dir)
<ide> Train(graph, utility, batch_size, train_data, sess, model_dir,
<ide> saver)
<ide> def main(args):
<ide> train_data = data_utils.complete_wiki_processing(train_data, utility, True)
<ide> dev_data = data_utils.complete_wiki_processing(dev_data, utility, False)
<ide> test_data = data_utils.complete_wiki_processing(test_data, utility, False)
<del> print "# train examples ", len(train_data)
<del> print "# dev examples ", len(dev_data)
<del> print "# test examples ", len(test_data)
<del> print "running open source"
<add> print("# train examples ", len(train_data))
<add> print("# dev examples ", len(dev_data))
<add> print("# test examples ", len(test_data))
<add> print("running open source")
<ide> #construct TF graph and train or evaluate
<ide> master(train_data, dev_data, utility)
<ide>
<ide><path>research/neural_programmer/parameters.py
<ide> def parameters(self, utility):
<ide> #Biases for the gates and cell
<ide> for bias in ["i", "f", "c", "o"]:
<ide> if (bias == "f"):
<del> print "forget gate bias"
<add> print("forget gate bias")
<ide> params[key + "_" + bias] = tf.Variable(
<ide> tf.random_uniform([embedding_dims], 1.0, 1.1, self.utility.
<ide> tf_data_type[self.utility.FLAGS.data_type]))
<ide><path>research/neural_programmer/wiki_data.py
<ide> lookup answer (or matrix) is also split into number and word lookup matrix
<ide> Author: aneelakantan (Arvind Neelakantan)
<ide> """
<add>from __future__ import print_function
<add>
<ide> import math
<ide> import os
<ide> import re
<ide> def correct_unicode(string):
<ide> #string = re.sub("[“â€Â«Â»]", "\"", string)
<ide> #string = re.sub("[•†‡]", "", string)
<ide> #string = re.sub("[â€â€‘–—]", "-", string)
<del> string = re.sub(ur'[\u2E00-\uFFFF]', "", string)
<add> string = re.sub(r'[\u2E00-\uFFFF]', "", string)
<ide> string = re.sub("\\s+", " ", string).strip()
<ide> return string
<ide>
<ide> def full_normalize(string):
<ide> # Remove trailing info in brackets
<ide> string = re.sub("\[[^\]]*\]", "", string)
<ide> # Remove most unicode characters in other languages
<del> string = re.sub(ur'[\u007F-\uFFFF]', "", string.strip())
<add> string = re.sub(r'[\u007F-\uFFFF]', "", string.strip())
<ide> # Remove trailing info in parenthesis
<ide> string = re.sub("\([^)]*\)$", "", string.strip())
<ide> string = final_normalize(string)
<ide> def __init__(self, train_name, dev_name, test_name, root_folder):
<ide> self.dev_loader = WikiQuestionLoader(dev_name, root_folder)
<ide> self.test_loader = WikiQuestionLoader(test_name, root_folder)
<ide> self.bad_examples = 0
<del> self.root_folder = root_folder
<add> self.root_folder = root_folder
<ide> self.data_folder = os.path.join(self.root_folder, "annotated/data")
<ide> self.annotated_examples = {}
<ide> self.annotated_tables = {}
<ide> def load_annotated_data(self, in_file):
<ide> question_id, question, target_canon, context)
<ide> self.annotated_tables[context] = []
<ide> counter += 1
<del> print "Annotated examples loaded ", len(self.annotated_examples)
<add> print("Annotated examples loaded ", len(self.annotated_examples))
<ide> f.close()
<ide>
<ide> def is_number_column(self, a):
<ide><path>research/object_detection/utils/visualization_utils_test.py
<ide> def test_draw_bounding_boxes_on_image_tensors(self):
<ide> for i in range(images_with_boxes_np.shape[0]):
<ide> img_name = 'image_' + str(i) + '.png'
<ide> output_file = os.path.join(self.get_temp_dir(), img_name)
<del> print 'Writing output image %d to %s' % (i, output_file)
<add> print('Writing output image %d to %s' % (i, output_file))
<ide> image_pil = Image.fromarray(images_with_boxes_np[i, ...])
<ide> image_pil.save(output_file)
<ide>
<ide><path>research/real_nvp/celeba_formatting.py
<ide>
<ide> """
<ide>
<add>from __future__ import print_function
<add>
<ide> import os
<ide> import os.path
<ide>
<ide> def main():
<ide> writer = tf.python_io.TFRecordWriter(file_out)
<ide> for example_idx, img_fn in enumerate(img_fn_list):
<ide> if example_idx % 1000 == 0:
<del> print example_idx, "/", num_examples
<add> print(example_idx, "/", num_examples)
<ide> image_raw = scipy.ndimage.imread(os.path.join(fn_root, img_fn))
<ide> rows = image_raw.shape[0]
<ide> cols = image_raw.shape[1]
<ide><path>research/real_nvp/imnet_formatting.py
<ide>
<ide> """
<ide>
<add>from __future__ import print_function
<add>
<ide> import os
<ide> import os.path
<ide>
<ide> def main():
<ide> file_out = "%s_%05d.tfrecords"
<ide> file_out = file_out % (FLAGS.file_out,
<ide> example_idx // n_examples_per_file)
<del> print "Writing on:", file_out
<add> print("Writing on:", file_out)
<ide> writer = tf.python_io.TFRecordWriter(file_out)
<ide> if example_idx % 1000 == 0:
<del> print example_idx, "/", num_examples
<add> print(example_idx, "/", num_examples)
<ide> image_raw = scipy.ndimage.imread(os.path.join(fn_root, img_fn))
<ide> rows = image_raw.shape[0]
<ide> cols = image_raw.shape[1]
<ide><path>research/real_nvp/lsun_formatting.py
<ide> --fn_root [LSUN_FOLDER]
<ide>
<ide> """
<add>from __future__ import print_function
<ide>
<ide> import os
<ide> import os.path
<ide> def main():
<ide> file_out = "%s_%05d.tfrecords"
<ide> file_out = file_out % (FLAGS.file_out,
<ide> example_idx // n_examples_per_file)
<del> print "Writing on:", file_out
<add> print("Writing on:", file_out)
<ide> writer = tf.python_io.TFRecordWriter(file_out)
<ide> if example_idx % 1000 == 0:
<del> print example_idx, "/", num_examples
<add> print(example_idx, "/", num_examples)
<ide> image_raw = numpy.array(Image.open(os.path.join(fn_root, img_fn)))
<ide> rows = image_raw.shape[0]
<ide> cols = image_raw.shape[1]
<ide><path>research/real_nvp/real_nvp_multiscale_dataset.py
<ide> --data_path [DATA_PATH]
<ide> """
<ide>
<add>from __future__ import print_function
<add>
<ide> import time
<ide> from datetime import datetime
<ide> import os
<ide>
<ide> import numpy
<add>from six.moves import xrange
<ide> import tensorflow as tf
<ide>
<ide> from tensorflow import gfile
<ide> def eval_epoch(self, hps):
<ide> n_equal = int(n_equal)
<ide> n_dash = bar_len - n_equal
<ide> progress_bar = "[" + "=" * n_equal + "-" * n_dash + "]\r"
<del> print progress_bar,
<add> print(progress_bar, end=' ')
<ide> cost = self.bit_per_dim.eval()
<ide> eval_costs.append(cost)
<del> print ""
<add> print("")
<ide> return float(numpy.mean(eval_costs))
<ide>
<ide>
<ide> def train_model(hps, logdir):
<ide>
<ide> ckpt_state = tf.train.get_checkpoint_state(logdir)
<ide> if ckpt_state and ckpt_state.model_checkpoint_path:
<del> print "Loading file %s" % ckpt_state.model_checkpoint_path
<add> print("Loading file %s" % ckpt_state.model_checkpoint_path)
<ide> saver.restore(sess, ckpt_state.model_checkpoint_path)
<ide>
<ide> # Start the queue runners.
<ide> def train_model(hps, logdir):
<ide> format_str = ('%s: step %d, loss = %.2f '
<ide> '(%.1f examples/sec; %.3f '
<ide> 'sec/batch)')
<del> print format_str % (datetime.now(), global_step_val, loss,
<del> examples_per_sec, duration)
<add> print(format_str % (datetime.now(), global_step_val, loss,
<add> examples_per_sec, duration))
<ide>
<ide> if should_eval_summaries:
<ide> summary_str = outputs[-1]
<ide> def evaluate(hps, logdir, traindir, subset="valid", return_val=False):
<ide> while True:
<ide> ckpt_state = tf.train.get_checkpoint_state(traindir)
<ide> if not (ckpt_state and ckpt_state.model_checkpoint_path):
<del> print "No model to eval yet at %s" % traindir
<add> print("No model to eval yet at %s" % traindir)
<ide> time.sleep(30)
<ide> continue
<del> print "Loading file %s" % ckpt_state.model_checkpoint_path
<add> print("Loading file %s" % ckpt_state.model_checkpoint_path)
<ide> saver.restore(sess, ckpt_state.model_checkpoint_path)
<ide>
<ide> current_step = tf.train.global_step(sess, eval_model.step)
<ide> if current_step == previous_global_step:
<del> print "Waiting for the checkpoint to be updated."
<add> print("Waiting for the checkpoint to be updated.")
<ide> time.sleep(30)
<ide> continue
<ide> previous_global_step = current_step
<ide>
<del> print "Evaluating..."
<add> print("Evaluating...")
<ide> bit_per_dim = eval_model.eval_epoch(hps)
<del> print ("Epoch: %d, %s -> %.3f bits/dim"
<del> % (current_step, subset, bit_per_dim))
<del> print "Writing summary..."
<add> print("Epoch: %d, %s -> %.3f bits/dim"
<add> % (current_step, subset, bit_per_dim))
<add> print("Writing summary...")
<ide> summary = tf.Summary()
<ide> summary.value.extend(
<ide> [tf.Summary.Value(
<ide> def sample_from_model(hps, logdir, traindir):
<ide> ckpt_state = tf.train.get_checkpoint_state(traindir)
<ide> if not (ckpt_state and ckpt_state.model_checkpoint_path):
<ide> if not initialized:
<del> print "No model to eval yet at %s" % traindir
<add> print("No model to eval yet at %s" % traindir)
<ide> time.sleep(30)
<ide> continue
<ide> else:
<ide> def sample_from_model(hps, logdir, traindir):
<ide>
<ide> current_step = tf.train.global_step(sess, eval_model.step)
<ide> if current_step == previous_global_step:
<del> print "Waiting for the checkpoint to be updated."
<add> print("Waiting for the checkpoint to be updated.")
<ide> time.sleep(30)
<ide> continue
<ide> previous_global_step = current_step
<ide><path>research/street/python/vgsl_model.py
<ide> # ==============================================================================
<ide>
<ide> """String network description language to define network layouts."""
<add>from __future__ import print_function
<add>
<ide> import re
<ide> import time
<ide>
<ide> def Eval(train_dir,
<ide> _AddRateToSummary('Sequence error rate', rates.sequence_error, step,
<ide> sw)
<ide> sw.flush()
<del> print 'Error rates=', rates
<add> print('Error rates=', rates)
<ide> else:
<ide> raise ValueError('Non-softmax decoder evaluation not implemented!')
<ide> if eval_interval_secs:
<ide><path>research/swivel/prep.py
<ide> import struct
<ide> import sys
<ide>
<add>from six.moves import xrange
<ide> import tensorflow as tf
<ide>
<ide> flags = tf.app.flags
<ide> def create_vocabulary(lines):
<ide> if not num_words:
<ide> raise Exception('empty vocabulary')
<ide>
<del> print 'vocabulary contains %d tokens' % num_words
<add> print('vocabulary contains %d tokens' % num_words)
<ide>
<ide> vocab = vocab[:num_words]
<ide> return [tok for tok, n in vocab]
<ide> def main(_):
<ide> write_vocab_and_sums(vocab, sums, 'row_vocab.txt', 'row_sums.txt')
<ide> write_vocab_and_sums(vocab, sums, 'col_vocab.txt', 'col_sums.txt')
<ide>
<del> print 'done!'
<add> print('done!')
<ide>
<ide>
<ide> if __name__ == '__main__':
<ide><path>research/swivel/text2bin.py
<ide> try:
<ide> opts, args = getopt(
<ide> sys.argv[1:], 'o:v:', ['output=', 'vocab='])
<del>except GetoptError, e:
<add>except GetoptError as e:
<ide> print >> sys.stderr, e
<ide> sys.exit(2)
<ide>
<ide><path>research/syntaxnet/dragnn/python/graph_builder.py
<ide>
<ide> try:
<ide> tf.NotDifferentiable('ExtractFixedFeatures')
<del>except KeyError, e:
<add>except KeyError as e:
<ide> logging.info(str(e))
<ide>
<ide>
<ide><path>research/syntaxnet/syntaxnet/conll2tree.py
<ide> def main(unused_argv):
<ide> sentence.ParseFromString(d)
<ide> tr = asciitree.LeftAligned()
<ide> d = to_dict(sentence)
<del> print 'Input: %s' % sentence.text
<del> print 'Parse:'
<add> print('Input: %s' % sentence.text)
<add> print('Parse:')
<ide> tr_str = tr(d)
<ide> pat = re.compile(r'\s*@\d+$')
<ide> for tr_ln in tr_str.splitlines():
<del> print pat.sub('', tr_ln)
<add> print(pat.sub('', tr_ln))
<ide>
<ide> if finished:
<ide> break
<ide><path>research/tcn/alignment.py
<ide> def compute_average_alignment(
<ide> alignment = np.mean(
<ide> np.abs(np.array(times_i)-np.array(times_j))/float(seq_len))
<ide> all_alignments.append(alignment)
<del> print 'alignment so far %f' % alignment
<add> print('alignment so far %f' % alignment)
<ide> average_alignment = np.mean(all_alignments)
<del> print 'Average alignment %f' % average_alignment
<add> print('Average alignment %f' % average_alignment)
<ide> summ = tf.Summary(value=[tf.Summary.Value(
<ide> tag='validation/alignment', simple_value=average_alignment)])
<ide> summary_writer.add_summary(summ, int(training_step))
<ide><path>research/tcn/dataset/webcam.py
<ide> from matplotlib import animation # pylint: disable=g-import-not-at-top
<ide> import matplotlib.pyplot as plt
<ide> import numpy as np
<add>from six.moves import input
<ide> import tensorflow as tf
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide>
<ide> def main(_):
<ide> tf.logging.info('About to write to:')
<ide> for v in view_dirs:
<ide> tf.logging.info(v)
<del> raw_input('Press Enter to continue...')
<add> input('Press Enter to continue...')
<ide> except SyntaxError:
<ide> pass
<ide> | 28 |
Javascript | Javascript | improve $parsers/$formatters with example | 0cb87f91ae8660016f9a79a62166ae03d0e7070d | <ide><path>src/ng/directive/input.js
<ide> var VALID_CLASS = 'ng-valid',
<ide> *
<ide> * @property {string} $viewValue Actual string value in the view.
<ide> * @property {*} $modelValue The value in the model, that the control is bound to.
<del> * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
<del> * all of these functions to sanitize / convert the value as well as validate.
<del> *
<del> * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
<del> * these functions to convert the value as well as validate.
<add> * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
<add> the control reads value from the DOM. Each function is called, in turn, passing the value
<add> through to the next. Used to sanitize / convert the value as well as validation.
<ide> *
<add> * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
<add> the model value changes. Each function is called, in turn, passing the value through to the
<add> next. Used to format / convert values for display in the control and validation.
<add> * <pre>
<add> * function formatter(value) {
<add> * if (value) {
<add> * return value.toUpperCase();
<add> * }
<add> * }
<add> * ngModel.$formatters.push(formatter);
<add> * </pre>
<ide> * @property {Object} $error An object hash with all errors as keys.
<ide> *
<ide> * @property {boolean} $pristine True if user has not interacted with the control yet. | 1 |
Javascript | Javascript | fix typo in unexpected ref object warning | d38616d6936542cbf8ca34d3c75cd3b9e44945c9 | <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.js
<ide> export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
<ide> warning(
<ide> false,
<ide> 'Unexpected ref object provided for %s. ' +
<del> 'Use either a ref-setter function or Reacte.createRef().%s',
<add> 'Use either a ref-setter function or React.createRef().%s',
<ide> getComponentName(finishedWork),
<ide> getStackAddendumByWorkInProgressFiber(finishedWork),
<ide> );
<ide><path>packages/react/src/__tests__/ReactCreateRef-test.js
<ide> describe('ReactCreateRef', () => {
<ide> ),
<ide> ).toWarnDev(
<ide> 'Unexpected ref object provided for div. ' +
<del> 'Use either a ref-setter function or Reacte.createRef().\n' +
<add> 'Use either a ref-setter function or React.createRef().\n' +
<ide> ' in div (at **)\n' +
<ide> ' in Wrapper (at **)',
<ide> );
<ide> describe('ReactCreateRef', () => {
<ide> ),
<ide> ).toWarnDev(
<ide> 'Unexpected ref object provided for ExampleComponent. ' +
<del> 'Use either a ref-setter function or Reacte.createRef().\n' +
<add> 'Use either a ref-setter function or React.createRef().\n' +
<ide> ' in ExampleComponent (at **)\n' +
<ide> ' in Wrapper (at **)',
<ide> ); | 2 |
Python | Python | fix pytest implementation errors | c6db7da2c932470f70ce9c9ab4dd49fc1a64b789 | <ide><path>numpy/testing/pytest_tools/utils.py
<ide> class KnownFailureException(Exception):
<ide> def __new__(cls, *args, **kwargs):
<ide> # import _pytest here to avoid hard dependency
<ide> import _pytest
<del> return _pytest.skipping.XFailed(*args, **kwargs)
<add> return _pytest.skipping.xfail(*args, **kwargs)
<ide>
<ide>
<ide> class SkipTest(Exception):
<ide> def raiser(*args, **kwargs):
<ide> return raises_decorator
<ide>
<ide>
<del>def assert_raises(*args, **kwargs):
<add>def assert_raises(exception_class, fn=None, *args, **kwargs):
<ide> """
<ide> assert_raises(exception_class, callable, *args, **kwargs)
<ide> assert_raises(exception_class)
<ide> def assert_raises(*args, **kwargs):
<ide> import pytest
<ide>
<ide> __tracebackhide__ = True # Hide traceback for py.test
<del> pytest.raises(*args,**kwargs)
<add>
<add> if fn is not None:
<add> pytest.raises(exception_class, fn, *args,**kwargs)
<add> else:
<add> @contextlib.contextmanager
<add> def assert_raises_context():
<add> try:
<add> yield
<add> except BaseException as raised_exception:
<add> assert isinstance(raised_exception, exception_class)
<add> else:
<add> raise ValueError('Function did not raise an exception')
<add>
<add> return assert_raises_context()
<ide>
<ide>
<ide> def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
<ide> class Dummy(unittest.TestCase):
<ide> def do_nothing(self):
<ide> pass
<ide>
<del> tmp = Dummy('')
<add> tmp = Dummy('do_nothing')
<ide>
<ide> __tracebackhide__ = True # Hide traceback for py.test
<ide> res = pytest.raises(exception_class, *args, **kwargs) | 1 |
Ruby | Ruby | remove uneeded local var definition | 9c161599ac1e37eedd56bece4d975dde8cdaa151 | <ide><path>activerecord/lib/active_record/nested_attributes.rb
<ide> def _destroy
<ide> def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
<ide> options = self.nested_attributes_options[association_name]
<ide> attributes = attributes.with_indifferent_access
<del> check_existing_record = (options[:update_only] || !attributes['id'].blank?)
<ide>
<del> if check_existing_record && (record = send(association_name)) &&
<add> if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
<ide> (options[:update_only] || record.id.to_s == attributes['id'].to_s)
<ide> assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
<ide> | 1 |
Python | Python | fix test_retry_kwargs_can_be_empty on pypy3 | ed79ccfb8b42404c71db6dd1d0cecd57a0165b97 | <ide><path>celery/utils/serialization.py
<ide> except ImportError:
<ide> import pickle # noqa
<ide>
<del>PY3 = sys.version_info[0] >= 3
<add>PY33 = sys.version_info >= (3, 3)
<ide>
<ide> __all__ = [
<ide> 'UnpickleableExceptionWrapper', 'subclass_exception',
<ide> def jsonify(obj,
<ide> return unknown_type_filter(obj)
<ide>
<ide>
<del>if PY3:
<add># Since PyPy 3 targets Python 3.2, 'raise exc from None' will
<add># raise a TypeError so we need to look for Python 3.3 or newer
<add>if PY33:
<ide> from vine.five import exec_
<ide> _raise_with_context = None # for flake8
<ide> exec_("""def _raise_with_context(exc, ctx): raise exc from ctx""") | 1 |
Text | Text | define "browser", "production", "development" | 088a7e5247451092990d80a91f77de0ecefe8619 | <ide><path>doc/api/packages.md
<ide> For example, a package that wants to provide different ES module exports for
<ide> }
<ide> ```
<ide>
<del>Node.js supports the following conditions out of the box:
<add>Node.js implements the following conditions:
<ide>
<ide> * `"import"` - matches when the package is loaded via `import` or
<ide> `import()`, or via any top-level import or resolve operation by the
<ide> matching, earlier entries have higher priority and take precedence over later
<ide> entries. _The general rule is that conditions should be from most specific to
<ide> least specific in object order_.
<ide>
<del>Other conditions such as `"browser"`, `"electron"`, `"deno"`, `"react-native"`,
<del>etc., are unknown to Node.js, and thus ignored. Runtimes or tools other than
<del>Node.js can use them at their discretion. Further restrictions, definitions, or
<del>guidance on condition names might occur in the future.
<del>
<ide> Using the `"import"` and `"require"` conditions can lead to some hazards,
<ide> which are further explained in [the dual CommonJS/ES module packages section][].
<ide>
<ide> exports, while resolving the existing `"node"`, `"default"`, `"import"`, and
<ide>
<ide> Any number of custom conditions can be set with repeat flags.
<ide>
<add>### Conditions Definitions
<add>
<add>The `"import"`, `"require"`, `"node"` and `"default"` conditions are defined
<add>and implemented in Node.js core,
<add>[as specified above](#esm_conditional_exports).
<add>
<add>Other condition strings are unknown to Node.js and thus ignored by default.
<add>Runtimes or tools other than Node.js can use them at their discretion.
<add>
<add>These user conditions can be enabled in Node.js via the [`--conditions`
<add>flag](#packages_resolving_user_conditions).
<add>
<add>The following condition definitions are currently endorsed by Node.js:
<add>
<add>* `"browser"` - any environment which implements a standard subset of global
<add> browser APIs available from JavaScript in web browsers, including the DOM
<add> APIs.
<add>* `"development"` - can be used to define a development-only environment
<add> entry point. _Must always be mutually exclusive with `"production"`._
<add>* `"production"` - can be used to define a production environment entry
<add> point. _Must always be mutually exclusive with `"development"`._
<add>
<add>The above user conditions can be enabled in Node.js via the [`--conditions`
<add>flag](#packages_resolving_user_conditions).
<add>
<add>Platform specific conditions such as `"deno"`, `"electron"`, or `"react-native"`
<add>may be used, but while there remain no implementation or integration intent
<add>from these platforms, the above are not explicitly endorsed by Node.js.
<add>
<add>New conditions definitions may be added to this list by creating a PR to the
<add>[Node.js documentation for this section][]. The requirements for listing a
<add>new condition definition here are that:
<add>
<add>* The definition should be clear and unambigious for all implementers.
<add>* The use case for why the condition is needed should be clearly justified.
<add>* There should exist sufficient existing implementation usage.
<add>* The condition name should not conflict with another condition definition or
<add> condition in wide usage.
<add>* The listing of the condition definition should provide a coordination
<add> benefit to the ecosystem that wouldn't otherwise be possible. For example,
<add> this would not necessarily be the case for company-specific or
<add> application-specific conditions.
<add>
<add>The above definitions may be moved to a dedicated conditions registry in due
<add>course.
<add>
<ide> ### Self-referencing a package using its name
<ide>
<ide> Within a package, the values defined in the package’s
<ide> This field defines [subpath imports][] for the current package.
<ide> [CommonJS]: modules.md
<ide> [ES module]: esm.md
<ide> [ES modules]: esm.md
<add>[Node.js documentation for this section]: https://github.com/nodejs/node/blob/master/doc/api/packages.md#conditions-definitions
<ide> [`ERR_PACKAGE_PATH_NOT_EXPORTED`]: errors.md#errors_err_package_path_not_exported
<ide> [`esm`]: https://github.com/standard-things/esm#readme
<ide> [`"exports"`]: #packages_exports | 1 |
Javascript | Javascript | use strict and expose in build version | 10fb0dc3833c9c48878dca712ed112479bea1afd | <ide><path>src/metadata.js
<del>var Metadata = (function MetadataClosure() {
<add>'use strict';
<add>
<add>var Metadata = PDFJS.Metadata = (function MetadataClosure() {
<ide> function Metadata(meta) {
<ide> if (typeof meta === 'string') {
<ide> var parser = new DOMParser();
<ide><path>web/viewer.js
<ide> var PDFView = {
<ide> var pdfTitle;
<ide>
<ide> if (metadata) {
<del> this.metadata = metadata = new Metadata(metadata);
<add> this.metadata = metadata = new PDFJS.Metadata(metadata);
<ide>
<ide> if (metadata.has('dc:title'))
<ide> pdfTitle = metadata.get('dc:title'); | 2 |
Text | Text | remove extra "docker" from docs index | 3be683a0bbf25f41e9f4b1652f8f0784cafbd05b | <ide><path>docs/sources/index.md
<ide> Docker consists of:
<ide> * Since Docker runs on so many platforms, it's easy to move your
<ide> applications around. You can easily move an application from a
<ide> testing environment into the cloud and back whenever you need.
<del> * Docker's lightweight containers Docker also make scaling up and
<add> * Docker's lightweight containers also make scaling up and
<ide> down fast and easy. You can quickly launch more containers when
<ide> needed and then shut them down easily when they're no longer needed.
<ide> | 1 |
Ruby | Ruby | prefer interpolation to concatenation | 23c2ec56f8d7f7fd39528851f7670559c8f1f588 | <ide><path>Library/Homebrew/cmd/--config.rb
<ide> def describe_path path
<ide>
<ide> def describe_x11
<ide> return "N/A" unless MacOS::XQuartz.installed?
<del> return "#{MacOS::XQuartz.version} => " + describe_path(MacOS::XQuartz.prefix)
<add> return "#{MacOS::XQuartz.version} => #{describe_path(MacOS::XQuartz.prefix)}"
<ide> end
<ide>
<ide> def describe_perl | 1 |
Ruby | Ruby | use a better test description | 008870e6a4043bd217738aa6f3cdda1f0ea74947 | <ide><path>activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
<ide> def test_custom_join_table
<ide> assert_equal 'edges', Vertex.reflect_on_association(:sources).join_table
<ide> end
<ide>
<del> def test_namespaced_habtm
<add> def test_has_and_belongs_to_many_in_a_namespaced_model_pointing_to_a_namespaced_model
<ide> magazine = Publisher::Magazine.create
<ide> article = Publisher::Article.create
<ide> magazine.articles << article | 1 |
Text | Text | add 3.7.5 release notes | 0d96be9266488d0f7de0dcffad1092316d98e4bf | <ide><path>docs/topics/release-notes.md
<ide> You can determine your currently installed version using `pip freeze`:
<ide>
<ide> ### 3.7.4
<ide>
<add>**Date**: [21st December 2017][3.7.5-milestone]
<add>
<add>* Add missing *.woff2 font files to packaging. [#5692][gh5692]
<add>* Add missing *.mo locale files to packaging. [#5695][gh5695], [#5696][gh5696]
<add>
<add>### 3.7.4
<add>
<ide> **Date**: [20th December 2017][3.7.4-milestone]
<ide>
<ide> * Schema: Extract method for `manual_fields` processing [#5633][gh5633]
<ide> For older release notes, [please see the version 2.x documentation][old-release-
<ide> [3.7.2-milestone]: https://github.com/encode/django-rest-framework/milestone/59?closed=1
<ide> [3.7.3-milestone]: https://github.com/encode/django-rest-framework/milestone/60?closed=1
<ide> [3.7.4-milestone]: https://github.com/encode/django-rest-framework/milestone/62?closed=1
<del>
<add>[3.7.5-milestone]: https://github.com/encode/django-rest-framework/milestone/63?closed=1
<ide>
<ide> <!-- 3.0.1 -->
<ide> [gh2013]: https://github.com/encode/django-rest-framework/issues/2013
<ide> For older release notes, [please see the version 2.x documentation][old-release-
<ide> [gh5579]: https://github.com/encode/django-rest-framework/issues/5579
<ide> [gh5633]: https://github.com/encode/django-rest-framework/issues/5633
<ide>
<add><!-- 3.7.5 -->
<add>[gh5692]: https://github.com/encode/django-rest-framework/issues/5692
<add>[gh5695]: https://github.com/encode/django-rest-framework/issues/5695
<add>[gh5696]: https://github.com/encode/django-rest-framework/issues/5696 | 1 |
Text | Text | add geoffrey booth to tsc | b985ad55eafc958db6f2ee7cd86b6be498fbbff2 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Danielle Adams** <<adamzdanielle@gmail.com>> (she/her)
<ide> * [fhinkel](https://github.com/fhinkel) -
<ide> **Franziska Hinkelmann** <<franziska.hinkelmann@gmail.com>> (she/her)
<add>* [GeoffreyBooth](https://github.com/geoffreybooth) -
<add> **Geoffrey Booth** <<webadmin@geoffreybooth.com>> (he/him)
<ide> * [gireeshpunathil](https://github.com/gireeshpunathil) -
<ide> **Gireesh Punathil** <<gpunathi@in.ibm.com>> (he/him)
<ide> * [jasnell](https://github.com/jasnell) - | 1 |
Text | Text | add documentation styleguide to contribubing.md | 1ab12b436a0a69d145570628e4ba727c8532ce70 | <ide><path>CONTRIBUTING.md
<ide> in the proper package's repository.
<ide>
<ide> * Set parameter defaults without spaces around the equal sign
<ide> * `clear = (count=1) ->` instead of `clear = (count = 1) ->`
<add>
<add>## Documentation Styleguide
<add>
<add>* Use [TomDoc](http://tomdoc.org/).
<add>* Use [Markdown](https://daringfireball.net/projects/markdown/).
<add>* Reference classes with `{ClassName}` style notation.
<add>* Delegate to comments elsewhere with `{Delegates to: ClassName.methodName}`
<add> style notation. | 1 |
Ruby | Ruby | remove unused ddlhelper in foreignkeytest | 89febead042cc1312a33d431abd23e2b28271336 | <ide><path>activerecord/test/cases/migration/foreign_key_test.rb
<ide> require "cases/helper"
<del>require "support/ddl_helper"
<ide> require "support/schema_dumping_helper"
<ide>
<ide> if ActiveRecord::Base.connection.supports_foreign_keys_in_create?
<ide> def test_foreign_keys
<ide> module ActiveRecord
<ide> class Migration
<ide> class ForeignKeyTest < ActiveRecord::TestCase
<del> include DdlHelper
<ide> include SchemaDumpingHelper
<ide> include ActiveSupport::Testing::Stream
<ide> | 1 |
Ruby | Ruby | fix homebrew_bottle_domain usage | 7fc52d20655522f7d984174b37c675796ee1abad | <ide><path>Library/Homebrew/github_packages.rb
<ide> class GitHubPackages
<ide> include Context
<ide> include Utils::Curl
<ide>
<del> URL_REGEX = %r{https://ghcr.io/v2/([\w-]+)/([\w-]+)}.freeze
<add> URL_PREFIX = "https://ghcr.io/v2/"
<add> URL_REGEX = %r{#{Regexp.escape(URL_PREFIX)}([\w-]+)/([\w-]+)}.freeze
<ide>
<ide> sig { returns(String) }
<ide> def inspect
<ide><path>Library/Homebrew/software_spec.rb
<ide> def prefix=(prefix)
<ide>
<ide> def root_url(var = nil, specs = {})
<ide> if var.nil?
<del> @root_url ||= "#{Homebrew::EnvConfig.bottle_domain}/#{Utils::Bottles::Bintray.repository(tap)}"
<add> @root_url ||= if Homebrew::EnvConfig.bottle_domain.start_with?(GitHubPackages::URL_PREFIX)
<add> "#{GitHubPackages::URL_PREFIX}#{tap.full_name}"
<add> else
<add> "#{Homebrew::EnvConfig.bottle_domain}/#{Utils::Bottles::Bintray.repository(tap)}"
<add> end
<ide> else
<ide> @root_url = var
<ide> @root_url_specs.merge!(specs) | 2 |
Go | Go | fix some wrap[f]/warn[f] errors | 3737194b9f2875c10f3f2117c1816054ba0ff262 | <ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) DaemonLeavesCluster() {
<ide> select {
<ide> case <-done:
<ide> case <-time.After(5 * time.Second):
<del> logrus.Warnf("timeout while waiting for ingress network removal")
<add> logrus.Warn("timeout while waiting for ingress network removal")
<ide> }
<ide> } else {
<ide> logrus.Warnf("failed to initiate ingress network removal: %v", err)
<ide><path>daemon/daemon_unix.go
<ide> func (daemon *Daemon) initRuntimes(runtimes map[string]types.Runtime) (err error
<ide> os.RemoveAll(runtimeDir + "-old")
<ide> tmpDir, err := ioutils.TempDir(daemon.configStore.Root, "gen-runtimes")
<ide> if err != nil {
<del> return errors.Wrapf(err, "failed to get temp dir to generate runtime scripts")
<add> return errors.Wrap(err, "failed to get temp dir to generate runtime scripts")
<ide> }
<ide> defer func() {
<ide> if err != nil {
<ide> if err1 := os.RemoveAll(tmpDir); err1 != nil {
<ide> logrus.WithError(err1).WithField("dir", tmpDir).
<del> Warnf("failed to remove tmp dir")
<add> Warn("failed to remove tmp dir")
<ide> }
<ide> return
<ide> }
<ide> func (daemon *Daemon) initRuntimes(runtimes map[string]types.Runtime) (err error
<ide> return
<ide> }
<ide> if err = os.Rename(tmpDir, runtimeDir); err != nil {
<del> err = errors.Wrapf(err, "failed to setup runtimes dir, new containers may not start")
<add> err = errors.Wrap(err, "failed to setup runtimes dir, new containers may not start")
<ide> return
<ide> }
<ide> if err = os.RemoveAll(runtimeDir + "-old"); err != nil {
<ide> logrus.WithError(err).WithField("dir", tmpDir).
<del> Warnf("failed to remove old runtimes dir")
<add> Warn("failed to remove old runtimes dir")
<ide> }
<ide> }()
<ide>
<ide> func setupRemappedRoot(config *config.Config) (*idtools.IDMappings, error) {
<ide>
<ide> mappings, err := idtools.NewIDMappings(username, groupname)
<ide> if err != nil {
<del> return nil, errors.Wrapf(err, "Can't create ID mappings: %v")
<add> return nil, errors.Wrap(err, "Can't create ID mappings")
<ide> }
<ide> return mappings, nil
<ide> }
<ide><path>daemon/kill.go
<ide> func (daemon *Daemon) killWithSignal(container *containerpkg.Container, sig int)
<ide> if unpause {
<ide> // above kill signal will be sent once resume is finished
<ide> if err := daemon.containerd.Resume(context.Background(), container.ID); err != nil {
<del> logrus.Warn("Cannot unpause container %s: %s", container.ID, err)
<add> logrus.Warnf("Cannot unpause container %s: %s", container.ID, err)
<ide> }
<ide> }
<ide>
<ide><path>daemon/monitor.go
<ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc
<ide> "container": c.ID,
<ide> "exec-id": ei.ProcessID,
<ide> "exec-pid": ei.Pid,
<del> }).Warnf("Ignoring Exit Event, no such exec command found")
<add> }).Warn("Ignoring Exit Event, no such exec command found")
<ide> }
<ide> case libcontainerd.EventStart:
<ide> c.Lock()
<ide><path>daemon/reload.go
<ide> func (daemon *Daemon) reloadClusterDiscovery(conf *config.Config, attributes map
<ide> }
<ide> netOptions, err := daemon.networkOptions(daemon.configStore, daemon.PluginStore, nil)
<ide> if err != nil {
<del> logrus.WithError(err).Warnf("failed to get options with network controller")
<add> logrus.WithError(err).Warn("failed to get options with network controller")
<ide> return nil
<ide> }
<ide> err = daemon.netController.ReloadConfiguration(netOptions...)
<ide><path>daemon/unpause.go
<ide> func (daemon *Daemon) containerUnpause(container *container.Container) error {
<ide> daemon.LogContainerEvent(container, "unpause")
<ide>
<ide> if err := container.CheckpointTo(daemon.containersReplica); err != nil {
<del> logrus.WithError(err).Warnf("could not save container to disk")
<add> logrus.WithError(err).Warn("could not save container to disk")
<ide> }
<ide>
<ide> return nil | 6 |
Javascript | Javascript | add test of stream transform | 9de15de05a47d645583699a5135bfb4b8ea1c5c2 | <ide><path>test/parallel/test-stream2-transform.js
<ide> const Transform = require('_stream_transform');
<ide> assert(pt instanceof PassThrough);
<ide> }
<ide>
<add>{
<add> // Verify transform constructor behavior
<add> const pt = Transform();
<add>
<add> assert(pt instanceof Transform);
<add>}
<add>
<ide> {
<ide> // Perform a simple transform
<ide> const pt = new Transform(); | 1 |
PHP | PHP | add partial queue faking | 9684a047dd9d29654a200d194a0f34ea390bb987 | <ide><path>src/Illuminate/Support/Facades/Queue.php
<ide> public static function popUsing($workerName, $callback)
<ide> /**
<ide> * Replace the bound instance with a fake.
<ide> *
<add> * @param array|string $jobsToFake
<ide> * @return \Illuminate\Support\Testing\Fakes\QueueFake
<ide> */
<del> public static function fake()
<add> public static function fake($jobsToFake = [])
<ide> {
<del> static::swap($fake = new QueueFake(static::getFacadeApplication()));
<add> static::swap($fake = new QueueFake(static::getFacadeApplication(), $jobsToFake, static::getFacadeRoot()));
<ide>
<ide> return $fake;
<ide> }
<ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php
<ide> use Closure;
<ide> use Illuminate\Contracts\Queue\Queue;
<ide> use Illuminate\Queue\QueueManager;
<add>use Illuminate\Support\Collection;
<ide> use Illuminate\Support\Traits\ReflectsClosures;
<ide> use PHPUnit\Framework\Assert as PHPUnit;
<ide>
<ide> class QueueFake extends QueueManager implements Queue
<ide> {
<ide> use ReflectsClosures;
<ide>
<add> /**
<add> * The original queue manager.
<add> *
<add> * @var \Illuminate\Contracts\Queue\Queue
<add> */
<add> protected $queue;
<add>
<add> /**
<add> * The job types that should be intercepted instead of pushed to the queue.
<add> *
<add> * @var array
<add> */
<add> protected $jobsToFake;
<add>
<ide> /**
<ide> * All of the jobs that have been pushed.
<ide> *
<ide> * @var array
<ide> */
<ide> protected $jobs = [];
<ide>
<add> /**
<add> * Create a new fake queue instance.
<add> *
<add> * @param \Illuminate\Contracts\Foundation\Application $app
<add> * @param array $jobsToFake
<add> * @param \Illuminate\Queue\QueueManager|null $queue
<add> * @return void
<add> */
<add> public function __construct($app, $jobsToFake = [], $queue = null)
<add> {
<add> parent::__construct($app);
<add>
<add> $this->jobsToFake = Collection::wrap($jobsToFake);
<add> $this->queue = $queue;
<add> }
<add>
<ide> /**
<ide> * Assert if a job was pushed based on a truth-test callback.
<ide> *
<ide> public function size($queue = null)
<ide> */
<ide> public function push($job, $data = '', $queue = null)
<ide> {
<del> $this->jobs[is_object($job) ? get_class($job) : $job][] = [
<del> 'job' => $job,
<del> 'queue' => $queue,
<del> ];
<add> if ($this->shouldFakeJob($job)) {
<add> $this->jobs[is_object($job) ? get_class($job) : $job][] = [
<add> 'job' => $job,
<add> 'queue' => $queue,
<add> ];
<add> } else {
<add> is_object($job) && isset($job->connection)
<add> ? $this->queue->connection($job->connection)->push($job, $data, $queue)
<add> : $this->queue->push($job, $data, $queue);
<add> }
<add> }
<add>
<add> /**
<add> * Determine if a job should be faked or actually dispatched.
<add> *
<add> * @param object $job
<add> * @return bool
<add> */
<add> public function shouldFakeJob($job)
<add> {
<add> if ($this->jobsToFake->isEmpty()) {
<add> return true;
<add> }
<add>
<add> return $this->jobsToFake->contains(function ($jobToFake) use ($job) {
<add> return $job instanceof ((string) $jobToFake);
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>tests/Support/SupportTestingQueueFakeTest.php
<ide> use BadMethodCallException;
<ide> use Illuminate\Bus\Queueable;
<ide> use Illuminate\Foundation\Application;
<add>use Illuminate\Queue\QueueManager;
<ide> use Illuminate\Support\Testing\Fakes\QueueFake;
<add>use Mockery as m;
<ide> use PHPUnit\Framework\Constraint\ExceptionMessage;
<ide> use PHPUnit\Framework\ExpectationFailedException;
<ide> use PHPUnit\Framework\TestCase;
<ide> protected function setUp(): void
<ide> $this->job = new JobStub;
<ide> }
<ide>
<add> protected function tearDown(): void
<add> {
<add> parent::tearDown();
<add>
<add> m::close();
<add> }
<add>
<ide> public function testAssertPushed()
<ide> {
<ide> try {
<ide> public function testAssertPushed()
<ide> $this->fake->assertPushed(JobStub::class);
<ide> }
<ide>
<add> public function testAssertPushedWithIgnore()
<add> {
<add> $job = new JobStub;
<add>
<add> $manager = m::mock(QueueManager::class);
<add> $manager->shouldReceive('push')->once()->withArgs(function ($passedJob) use ($job) {
<add> return $passedJob === $job;
<add> });
<add>
<add> $fake = new QueueFake(new Application, JobToFakeStub::class, $manager);
<add>
<add> $fake->push($job);
<add> $fake->push(new JobToFakeStub());
<add>
<add> $fake->assertNotPushed(JobStub::class);
<add> $fake->assertPushed(JobToFakeStub::class);
<add> }
<add>
<ide> public function testAssertPushedWithClosure()
<ide> {
<ide> $this->fake->push($this->job);
<ide> public function handle()
<ide> }
<ide> }
<ide>
<add>class JobToFakeStub
<add>{
<add> public function handle()
<add> {
<add> //
<add> }
<add>}
<add>
<ide> class JobWithChainStub
<ide> {
<ide> use Queueable; | 3 |
Text | Text | fix punctuation in doc/releases.md | 38c97f5dc7ff3fbf83982d0268fc9e93cfc00c7d | <ide><path>doc/releases.md
<ide> commit metadata, as well as the `semver-minor` and `semver-major` GitHub labels.
<ide> One drawback is that when the `PR-URL` metadata is accidentally omitted from a
<ide> commit, the commit will show up because it's unsure if it's a duplicate or not.
<ide>
<del>For a list of commits that could be landed in a patch release on v5.x
<add>For a list of commits that could be landed in a patch release on v5.x:
<ide>
<ide> ```console
<ide> $ branch-diff v5.x master --exclude-label=semver-major,semver-minor,dont-land-on-v5.x --filter-release --format=simple
<ide> Commits may need to be reverted or a major version bump may need to happen.
<ide> #### Step 1: Collecting the formatted list of changes:
<ide>
<ide> Collect a formatted list of commits since the last release. Use
<del>[`changelog-maker`](https://github.com/rvagg/changelog-maker) to do this.
<add>[`changelog-maker`](https://github.com/rvagg/changelog-maker) to do this:
<ide>
<ide> ```console
<ide> $ changelog-maker --group
<ide> doc/api/*.md`, and substitute this node version with `sed -i
<ide> "s/REPLACEME/$VERSION/g" doc/api/*.md` or `perl -pi -e "s/REPLACEME/$VERSION/g"
<ide> doc/api/*.md`.
<ide>
<del>*Note*: `$VERSION` should be prefixed with a `v`
<add>*Note*: `$VERSION` should be prefixed with a `v`.
<ide>
<ide> If this release includes any new deprecations it is necessary to ensure that
<ide> those are assigned a proper static deprecation code. These are listed in the | 1 |
Text | Text | fix instructions to be coherent with the tests | 4ec558ea3f3df228e338b37e50e4317404051376 | <ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.spanish.md
<ide> localeTitle: Encadenamiento en caso contrario
<ide> <section id="description"> <code>if/else</code> declaraciones <code>if/else</code> se pueden encadenar para una lógica compleja. Aquí está el <dfn>pseudocódigo</dfn> de múltiples sentencias <code>if</code> / <code>else if</code> encadenadas: <blockquote> if ( <em>condición1</em> ) { <br> <em>declaración1</em> <br> } else if ( <em>condition2</em> ) { <br> <em>declaración2</em> <br> } else if ( <em>condition3</em> ) { <br> <em>declaración3</em> <br> . . . <br> } else { <br> <em>declaraciónN</em> <br> } </blockquote></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> Escriba en cadena las sentencias <code>if</code> / <code>else if</code> para cumplir las siguientes condiciones: <code>num < 5</code> - return "Tiny" <br> <code>num < 10</code> - devuelve "Small" <br> <code>num < 15</code> - devuelve "Medio" <br> <code>num < 20</code> - devuelve "Large" <br> <code>num >= 20</code> - devuelve "Enorme" </section>
<add><section id="instructions"> Escriba en cadena las sentencias <code>if</code> / <code>else if</code> para cumplir las siguientes condiciones: <code>num < 5</code> - return "Tiny" <br> <code>num < 10</code> - devuelve "Small" <br> <code>num < 15</code> - devuelve "Medium" <br> <code>num < 20</code> - devuelve "Large" <br> <code>num >= 20</code> - devuelve "Huge" </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'> | 1 |
Ruby | Ruby | show total disk space freed on cleanup | 6642801b04b7522d6f89599660e448e49b1411f6 | <ide><path>Library/Homebrew/cleanup.rb
<ide> def cleanup_path(path)
<ide> return unless path.exist?
<ide> return unless @cleaned_up_paths.add?(path)
<ide>
<del> disk_usage = path.disk_usage
<add> @disk_cleanup_size += path.disk_usage
<ide>
<ide> if dry_run?
<ide> puts "Would remove: #{path} (#{path.abv})"
<del> @disk_cleanup_size += disk_usage
<ide> else
<ide> puts "Removing: #{path}... (#{path.abv})"
<ide> yield
<del> @disk_cleanup_size += disk_usage - path.disk_usage
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | use option parser for `brew cleanup` | 03b93da2969914193a16b52b273f4b0fb1850c82 | <ide><path>Library/Homebrew/cleanup.rb
<ide> require "utils/bottles"
<ide> require "formula"
<add>require "hbc/cask_loader"
<ide>
<ide> module CleanupRefinement
<ide> refine Pathname do
<ide> def stale_formula?(scrub)
<ide> using CleanupRefinement
<ide>
<ide> module Homebrew
<del> module Cleanup
<del> @disk_cleanup_size = 0
<del>
<del> class << self
<del> attr_reader :disk_cleanup_size
<del> end
<add> class Cleanup
<add> extend Predicable
<add>
<add> attr_predicate :dry_run?, :scrub?
<add> attr_reader :args, :days, :cache
<add> attr_reader :disk_cleanup_size
<add>
<add> def initialize(*args, dry_run: false, scrub: false, days: nil, cache: HOMEBREW_CACHE)
<add> @disk_cleanup_size = 0
<add> @args = args
<add> @dry_run = dry_run
<add> @scrub = scrub
<add> @days = days
<add> @cache = cache
<add> end
<add>
<add> def clean!
<add> if args.empty?
<add> Formula.installed.each do |formula|
<add> cleanup_formula(formula)
<add> end
<add> cleanup_cache
<add> cleanup_logs
<add> return if dry_run?
<add> cleanup_lockfiles
<add> rm_ds_store
<add> else
<add> args.each do |arg|
<add> formula = begin
<add> Formula[arg]
<add> rescue FormulaUnavailableError, TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError
<add> nil
<add> end
<ide>
<del> module_function
<add> cask = begin
<add> Hbc::CaskLoader.load(arg)
<add> rescue Hbc::CaskUnavailableError
<add> nil
<add> end
<ide>
<del> def cleanup
<del> cleanup_cellar
<del> cleanup_cache
<del> cleanup_logs
<del> return if ARGV.dry_run?
<del> cleanup_lockfiles
<del> rm_ds_store
<add> cleanup_formula(formula) if formula
<add> cleanup_cask(cask) if cask
<add> end
<add> end
<ide> end
<ide>
<ide> def update_disk_cleanup_size(path_size)
<ide> def unremovable_kegs
<ide> @unremovable_kegs ||= []
<ide> end
<ide>
<del> def cleanup_cellar(formulae = Formula.installed)
<del> formulae.each(&method(:cleanup_formula))
<del> end
<del>
<ide> def cleanup_formula(formula)
<ide> formula.eligible_kegs_for_cleanup.each(&method(:cleanup_keg))
<ide> end
<ide>
<add> def cleanup_cask(cask); end
<add>
<ide> def cleanup_keg(keg)
<ide> cleanup_path(keg) { keg.uninstall }
<ide> rescue Errno::EACCES => e
<ide> def cleanup_keg(keg)
<ide> def cleanup_logs
<ide> return unless HOMEBREW_LOGS.directory?
<ide> HOMEBREW_LOGS.subdirs.each do |dir|
<del> cleanup_path(dir) { dir.rmtree } if dir.prune?(ARGV.value("prune")&.to_i || DEFAULT_LOG_DAYS)
<add> cleanup_path(dir) { dir.rmtree } if dir.prune?(days || DEFAULT_LOG_DAYS)
<ide> end
<ide> end
<ide>
<del> def cleanup_cache(cache = HOMEBREW_CACHE)
<add> def cleanup_cache
<ide> return unless cache.directory?
<ide> cache.children.each do |path|
<ide> next cleanup_path(path) { path.unlink } if path.incomplete?
<ide> next cleanup_path(path) { FileUtils.rm_rf path } if path.nested_cache?
<ide>
<del> if path.prune?(ARGV.value("prune")&.to_i)
<add> if path.prune?(days)
<ide> if path.file?
<ide> cleanup_path(path) { path.unlink }
<ide> elsif path.directory? && path.to_s.include?("--")
<ide> def cleanup_cache(cache = HOMEBREW_CACHE)
<ide> def cleanup_path(path)
<ide> disk_usage = path.disk_usage
<ide>
<del> if ARGV.dry_run?
<add> if dry_run?
<ide> puts "Would remove: #{path} (#{path.abv})"
<ide> else
<ide> puts "Removing: #{path}... (#{path.abv})"
<ide><path>Library/Homebrew/cmd/cleanup.rb
<ide> #: deleted. If you want to delete those too: `rm -rf $(brew --cache)`
<ide>
<ide> require "cleanup"
<add>require "cli_parser"
<ide>
<ide> module Homebrew
<ide> module_function
<ide>
<ide> def cleanup
<del> if ARGV.named.empty?
<del> Cleanup.cleanup
<del> else
<del> Cleanup.cleanup_cellar(ARGV.resolved_formulae)
<add> CLI::Parser.parse do
<add> switch "-n", "--dry-run"
<add> switch "-s"
<add> flag "--prune="
<ide> end
<ide>
<del> report_disk_usage unless Cleanup.disk_cleanup_size.zero?
<del> report_unremovable_kegs unless Cleanup.unremovable_kegs.empty?
<del> end
<add> cleanup = Cleanup.new(*args.remaining, dry_run: args.dry_run?, scrub: args.s?, days: args.prune&.to_i)
<add>
<add> cleanup.clean!
<ide>
<del> def report_disk_usage
<del> disk_space = disk_usage_readable(Cleanup.disk_cleanup_size)
<del> if ARGV.dry_run?
<del> ohai "This operation would free approximately #{disk_space} of disk space."
<del> else
<del> ohai "This operation has freed approximately #{disk_space} of disk space."
<add> unless cleanup.disk_cleanup_size.zero?
<add> disk_space = disk_usage_readable(cleanup.disk_cleanup_size)
<add> if args.dry_run?
<add> ohai "This operation would free approximately #{disk_space} of disk space."
<add> else
<add> ohai "This operation has freed approximately #{disk_space} of disk space."
<add> end
<ide> end
<del> end
<ide>
<del> def report_unremovable_kegs
<add> return if cleanup.unremovable_kegs.empty?
<add>
<ide> ofail <<~EOS
<ide> Could not cleanup old kegs! Fix your permissions on:
<del> #{Cleanup.unremovable_kegs.join "\n "}
<add> #{cleanup.unremovable_kegs.join "\n "}
<ide> EOS
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def migrate_legacy_cache_if_necessary
<ide> return unless legacy_cache.writable_real?
<ide> FileUtils.touch migration_attempted_file
<ide>
<del> # Cleanup to avoid copying files unnecessarily
<del> ohai "Cleaning up #{legacy_cache}..."
<del> Cleanup.cleanup_cache legacy_cache
<del>
<ide> # This directory could have been compromised if it's world-writable/
<ide> # a symlink/owned by another user so don't copy files in those cases.
<ide> world_writable = legacy_cache.stat.mode & 0777 == 0777
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade
<ide> upgrade_formula(f)
<ide> next if !ARGV.include?("--cleanup") && !ENV["HOMEBREW_UPGRADE_CLEANUP"]
<ide> next unless f.installed?
<del> Homebrew::Cleanup.cleanup_formula f
<add> Cleanup.new.cleanup_formula(f)
<ide> rescue UnsatisfiedRequirements => e
<ide> Homebrew.failed = true
<ide> onoe "#{f}: #{e}"
<ide><path>Library/Homebrew/test/cleanup_spec.rb
<ide>
<ide> describe "::cleanup" do
<ide> it "removes .DS_Store and lock files" do
<del> described_class.cleanup
<add> subject.clean!
<ide>
<ide> expect(ds_store).not_to exist
<ide> expect(lock_file).not_to exist
<ide> end
<ide>
<del> it "doesn't remove anything if `--dry-run` is specified" do
<del> ARGV << "--dry-run"
<del>
<del> described_class.cleanup
<add> it "doesn't remove anything if `dry_run` is true" do
<add> described_class.new(dry_run: true).clean!
<ide>
<ide> expect(ds_store).to exist
<ide> expect(lock_file).to exist
<ide> it "doesn't remove the lock file if it is locked" do
<ide> lock_file.open(File::RDWR | File::CREAT).flock(File::LOCK_EX | File::LOCK_NB)
<ide>
<del> described_class.cleanup
<add> subject.clean!
<ide>
<ide> expect(lock_file).to exist
<ide> end
<ide>
<ide> context "when it can't remove a keg" do
<ide> let(:f1) { Class.new(Testball) { version "0.1" }.new }
<ide> let(:f2) { Class.new(Testball) { version "0.2" }.new }
<del> let(:unremovable_kegs) { [] }
<ide>
<ide> before do
<del> described_class.instance_variable_set(:@unremovable_kegs, [])
<ide> [f1, f2].each do |f|
<ide> f.brew do
<ide> f.install
<ide> end
<ide>
<ide> it "doesn't remove any kegs" do
<del> described_class.cleanup_formula f2
<add> subject.cleanup_formula f2
<ide> expect(f1.installed_kegs.size).to eq(2)
<ide> end
<ide>
<ide> it "lists the unremovable kegs" do
<del> described_class.cleanup_formula f2
<del> expect(described_class.unremovable_kegs).to contain_exactly(f1.installed_kegs[0])
<add> subject.cleanup_formula f2
<add> expect(subject.unremovable_kegs).to contain_exactly(f1.installed_kegs[0])
<ide> end
<ide> end
<ide> end
<ide> expect(f3).to be_installed
<ide> expect(f4).to be_installed
<ide>
<del> described_class.cleanup_formula f3
<add> subject.cleanup_formula f3
<ide>
<ide> expect(f1).not_to be_installed
<ide> expect(f2).not_to be_installed
<ide> path.mkpath
<ide> end
<ide>
<del> it "cleans all logs if prune all" do
<del> ARGV << "--prune=all"
<del> described_class.cleanup_logs
<add> it "cleans all logs if prune is 0" do
<add> described_class.new(days: 0).cleanup_logs
<ide> expect(path).not_to exist
<ide> end
<ide>
<ide> it "cleans up logs if older than 14 days" do
<ide> allow_any_instance_of(Pathname).to receive(:mtime).and_return(Time.now - 15 * 60 * 60 * 24)
<del> described_class.cleanup_logs
<add> subject.cleanup_logs
<ide> expect(path).not_to exist
<ide> end
<ide>
<ide> it "does not clean up logs less than 14 days old" do
<ide> allow_any_instance_of(Pathname).to receive(:mtime).and_return(Time.now - 2 * 60 * 60 * 24)
<del> described_class.cleanup_logs
<add> subject.cleanup_logs
<ide> expect(path).to exist
<ide> end
<ide> end
<ide> incomplete = (HOMEBREW_CACHE/"something.incomplete")
<ide> incomplete.mkpath
<ide>
<del> described_class.cleanup_cache
<add> subject.cleanup_cache
<ide>
<ide> expect(incomplete).not_to exist
<ide> end
<ide> glide_home = (HOMEBREW_CACHE/"glide_home")
<ide> glide_home.mkpath
<ide>
<del> described_class.cleanup_cache
<add> subject.cleanup_cache
<ide>
<ide> expect(glide_home).not_to exist
<ide> end
<ide> java_cache = (HOMEBREW_CACHE/"java_cache")
<ide> java_cache.mkpath
<ide>
<del> described_class.cleanup_cache
<add> subject.cleanup_cache
<ide>
<ide> expect(java_cache).not_to exist
<ide> end
<ide> npm_cache = (HOMEBREW_CACHE/"npm_cache")
<ide> npm_cache.mkpath
<ide>
<del> described_class.cleanup_cache
<add> subject.cleanup_cache
<ide>
<ide> expect(npm_cache).not_to exist
<ide> end
<ide> gist.mkpath
<ide> FileUtils.touch svn
<ide>
<del> allow(ARGV).to receive(:value).with("prune").and_return("all")
<del>
<del> described_class.cleanup_cache
<add> described_class.new(days: 0).cleanup_cache
<ide>
<ide> expect(git).not_to exist
<ide> expect(gist).to exist
<ide> it "does not clean up directories that are not VCS checkouts" do
<ide> git = (HOMEBREW_CACHE/"git")
<ide> git.mkpath
<del> allow(ARGV).to receive(:value).with("prune").and_return("all")
<ide>
<del> described_class.cleanup_cache
<add> described_class.new(days: 0).cleanup_cache
<ide>
<ide> expect(git).to exist
<ide> end
<ide>
<ide> it "cleans up VCS checkout directories with modified time < prune time" do
<ide> foo = (HOMEBREW_CACHE/"--foo")
<ide> foo.mkpath
<del> allow(ARGV).to receive(:value).with("prune").and_return("1")
<ide> allow_any_instance_of(Pathname).to receive(:mtime).and_return(Time.now - 2 * 60 * 60 * 24)
<del> described_class.cleanup_cache
<add> described_class.new(days: 1).cleanup_cache
<ide> expect(foo).not_to exist
<ide> end
<ide>
<ide> it "does not clean up VCS checkout directories with modified time >= prune time" do
<ide> foo = (HOMEBREW_CACHE/"--foo")
<ide> foo.mkpath
<del> allow(ARGV).to receive(:value).with("prune").and_return("1")
<del> described_class.cleanup_cache
<add> described_class.new(days: 1).cleanup_cache
<ide> expect(foo).to exist
<ide> end
<ide>
<ide>
<ide> it "cleans up file if outdated" do
<ide> allow(Utils::Bottles).to receive(:file_outdated?).with(any_args).and_return(true)
<del> described_class.cleanup_cache
<add> subject.cleanup_cache
<ide> expect(bottle).not_to exist
<ide> expect(testball).not_to exist
<ide> end
<ide>
<del> it "cleans up file if ARGV has -s and formula not installed" do
<del> ARGV << "-s"
<del> described_class.cleanup_cache
<add> it "cleans up file if `scrub` is true and formula not installed" do
<add> described_class.new(scrub: true).cleanup_cache
<ide> expect(bottle).not_to exist
<ide> expect(testball).not_to exist
<ide> end
<ide>
<ide> it "cleans up file if stale" do
<del> described_class.cleanup_cache
<add> subject.cleanup_cache
<ide> expect(bottle).not_to exist
<ide> expect(testball).not_to exist
<ide> end | 5 |
Text | Text | add change info for async_hooks.executionasyncid() | dadf28271c96f11aea77878a79263e2bfa4f8bf8 | <ide><path>doc/api/async_hooks.md
<ide> init for PROMISE with id 6, trigger id: 5 # the Promise returned by then()
<ide>
<ide> #### `async_hooks.executionAsyncId()`
<ide>
<add><!-- YAML
<add>added: v8.1.0
<add>changes:
<add> - version: v8.2.0
<add> pr-url: https://github.com/nodejs/node/pull/13490
<add> description: Renamed from currentId
<add>-->
<add>
<ide> * Returns: {number} The `asyncId` of the current execution context. Useful to
<ide> track when something calls.
<ide> | 1 |
Text | Text | add more information about do while loop | 338d94b517cbda5de27bfe9c889e0ba231b6e1fb | <ide><path>client/src/pages/guide/english/cplusplus/loops/index.md
<ide> Therefore, in order to solve such problems loops are introduced.
<ide> There are different types of loop functions:
<ide> ### While and do while loops
<ide>
<del>While and do while loops allow you to make the loop until a condition finishes.
<del>The difference between While and Do while is that Do while always executes once.
<add>While and do while loops allow you to run the loop until a condition finishes.
<add>The difference between While and Do while is that Do while loop always executes atleast once.
<add>The very use of Do while loop can be seen in the scenarios when the number of times that the loop will run depends upon the first iteration of the loop.
<ide> Here you can see an example:
<ide> ``` c++
<ide> while (condition){ | 1 |
Python | Python | update changelog.py for python 3 | 8bb395841605948b5003701b8fc2e3bc36f24bde | <ide><path>tools/changelog.py
<ide> from git import Repo
<ide> from github import Github
<ide>
<del>UTF8Writer = codecs.getwriter('utf8')
<del>sys.stdout = UTF8Writer(sys.stdout)
<add>if sys.version_info.major < 3:
<add> UTF8Writer = codecs.getwriter('utf8')
<add> sys.stdout = UTF8Writer(sys.stdout)
<add>
<ide> this_repo = Repo(os.path.join(os.path.dirname(__file__), ".."))
<ide>
<ide> author_msg =\ | 1 |
Python | Python | recover global policy between tests | b37c3fc1762155d592d99398158e74aae69f1b9f | <ide><path>official/vision/image_classification/resnet_ctl_imagenet_test.py
<ide> def setUpClass(cls):
<ide> def setUp(self):
<ide> super(CtlImagenetTest, self).setUp()
<ide> imagenet_preprocessing.NUM_IMAGES['validation'] = 4
<add> self.policy = \
<add> tf.compat.v2.keras.mixed_precision.experimental.global_policy()
<ide>
<ide> def tearDown(self):
<ide> super(CtlImagenetTest, self).tearDown()
<ide> tf.io.gfile.rmtree(self.get_temp_dir())
<add> tf.compat.v2.keras.mixed_precision.experimental.set_policy(self.policy)
<ide>
<ide> def test_end_to_end_no_dist_strat(self):
<ide> """Test Keras model with 1 GPU, no distribution strategy."""
<ide><path>official/vision/image_classification/resnet_imagenet_test.py
<ide> def setUpClass(cls): # pylint: disable=invalid-name
<ide> def setUp(self):
<ide> super(KerasImagenetTest, self).setUp()
<ide> imagenet_preprocessing.NUM_IMAGES["validation"] = 4
<add> self.policy = \
<add> tf.compat.v2.keras.mixed_precision.experimental.global_policy()
<ide>
<ide> def tearDown(self):
<ide> super(KerasImagenetTest, self).tearDown()
<ide> tf.io.gfile.rmtree(self.get_temp_dir())
<add> tf.compat.v2.keras.mixed_precision.experimental.set_policy(self.policy)
<ide>
<ide> def test_end_to_end_no_dist_strat(self):
<ide> """Test Keras model with 1 GPU, no distribution strategy.""" | 2 |
PHP | PHP | require value on set | 8af77643ecadd3b6fcff6867d505ce77c343c0d2 | <ide><path>src/Http/ServerRequest.php
<ide> public function getEnv($key, $default = null)
<ide> * Set a value to the request's environment data.
<ide> *
<ide> * @param string $key The key you want to write to.
<del> * @param string|null $value Value to set. Default null.
<add> * @param string $value Value to set
<ide> * @return $this
<ide> */
<del> public function setEnv($key, $value = null)
<add> public function setEnv($key, $value)
<ide> {
<ide> $this->_environment[$key] = $value;
<ide> $this->clearDetectorCache(); | 1 |
Ruby | Ruby | update parser tests | 35500130c4ccf7886848cb5073ae9d63e91d253a | <ide><path>Library/Homebrew/cli/args.rb
<ide> def spec(default = :stable)
<ide> end
<ide>
<ide> def respond_to_missing?(method_name, *)
<del> !frozen? || @table.key?(method_name)
<add> @table.key?(method_name)
<ide> end
<ide>
<ide> def method_missing(method_name, *args)
<ide><path>Library/Homebrew/test/cli/named_args_spec.rb
<ide> def setup_unredable_cask(name)
<ide> expect { described_class.new("foo").to_formulae_and_casks }.to raise_error(FormulaOrCaskUnavailableError)
<ide> end
<ide>
<del> it "raises an error when formula is absent and cask is available on linux", :needs_linux do
<del> stub_cask_loader foo_cask
<del>
<del> expect { described_class.new("foo").to_formulae_and_casks }.to raise_error(FormulaUnavailableError)
<del> end
<del>
<ide> it "returns formula when formula is present and cask is unreadable", :needs_macos do
<ide> stub_formula_loader foo
<ide> setup_unredable_cask "foo"
<ide> def setup_unredable_cask(name)
<ide>
<ide> expect(described_class.new("foo", "baz").to_paths(only: :cask)).to eq [cask_path, Cask::CaskLoader.path("baz")]
<ide> end
<del>
<del> it "returns only formulae by default on linux", :needs_linux do
<del> expect(Formulary).to receive(:path).with("foo").and_return(formula_path)
<del>
<del> expect(described_class.new("foo", "baz").to_paths).to eq [formula_path, Formulary.path("baz")]
<del> end
<ide> end
<ide>
<ide> describe "#to_taps" do
<ide><path>Library/Homebrew/test/cli/parser_spec.rb
<ide> end
<ide> end
<ide>
<del> it "throws an error by default" do
<add> it "throws an error when defined" do
<ide> expect { parser.parse(["--cask"]) }.to raise_error UsageError, /Casks are not supported on Linux/
<ide> end
<add> end
<add>
<add> describe "--formula on linux", :needs_linux do
<add> it "doesn't set --formula when not defined" do
<add> parser = described_class.new
<add> args = parser.parse([])
<add> expect(args.respond_to?(:formula?)).to be(false)
<add> end
<ide>
<del> it "only warns developers", :needs_macos do
<del> expect { parser.parse(["--cask"]) }.not_to raise_error
<add> it "sets --formula to true when defined" do
<add> parser = described_class.new do
<add> switch "--formula"
<add> end
<add> args = parser.parse([])
<add> expect(args.formula?).to be(true)
<ide> end
<ide> end
<ide> end | 3 |
PHP | PHP | fix function name to proper camelbacked casing | 2b1feeaaaf2d0c0ad7141e591cd40fa3d3424ca1 | <ide><path>lib/Cake/Model/Validator/ValidationSet.php
<ide> public function validate($data, $isUpdate = false) {
<ide> $this->reset();
<ide> $this->_isUpdate = $isUpdate;
<ide>
<del> if ($this->checkvalidatePresent($this->field, $data)) {
<add> if ($this->checkValidatePresent($this->field, $data)) {
<ide> return array(__d('cake', 'This field must exist in data'));
<ide> }
<ide>
<ide> public function isEmptyAllowed() {
<ide> * @param array $data data to check against
<ide> * @return boolean
<ide> */
<del> public function checkvalidatePresent($field, $data) {
<add> public function checkValidatePresent($field, $data) {
<ide> if (array_key_exists($field, $data)) {
<ide> return false;
<ide> } | 1 |
Java | Java | fix buffering issue in stringdecoder | f738273486204becf7bce1f25df9bf6d6d8b0507 | <ide><path>spring-core/src/main/java/org/springframework/core/codec/StringDecoder.java
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<add>import org.springframework.core.io.buffer.PooledDataBuffer;
<ide> import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> public Flux<String> decode(Publisher<DataBuffer> inputStream, ResolvableType ele
<ide> Flux<DataBuffer> inputFlux = Flux.from(inputStream)
<ide> .flatMap(dataBuffer -> splitOnDelimiter(dataBuffer, delimiterBytes))
<ide> .bufferUntil(StringDecoder::isEndFrame)
<del> .flatMap(StringDecoder::joinUntilEndFrame);
<add> .flatMap(StringDecoder::joinUntilEndFrame)
<add> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<ide> return super.decode(inputFlux, elementType, mimeType, hints);
<ide> }
<ide>
<ide><path>spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java
<ide> public void decodeEmptyDataBuffer() {
<ide> @Test
<ide> public void decodeError() {
<ide> DataBuffer fooBuffer = stringBuffer("foo\n");
<add> DataBuffer barBuffer = stringBuffer("bar");
<ide> Flux<DataBuffer> source =
<del> Flux.just(fooBuffer).concatWith(Flux.error(new RuntimeException()));
<add> Flux.just(fooBuffer, barBuffer).concatWith(Flux.error(new RuntimeException()));
<ide>
<ide> Flux<String> output = this.decoder.decode(source,
<ide> ResolvableType.forClass(String.class), null, Collections.emptyMap()); | 2 |
Python | Python | fix lxd tests | 5bc59acc6f7b0165ab42550394329cd4b91275a6 | <ide><path>libcloud/test/container/test_lxd.py
<ide> def test_ex_get_server_configuration(self):
<ide> self.assertEqual(server_config.public, False)
<ide>
<ide> def test_list_images(self):
<add> img_id = "54c8caac1f61901ed86c68f24af5f5d3672bdc62c71d04f06df3a59e95684473"
<ide> for driver in self.drivers:
<ide> images = driver.list_images()
<ide> self.assertEqual(len(images), 1)
<ide> self.assertIsInstance(images[0], ContainerImage)
<del> self.assertEqual(images[0].id, 'trusty')
<add> self.assertEqual(images[0].id, img_id)
<ide> self.assertEqual(images[0].name, 'trusty')
<ide>
<ide> def test_list_containers(self): | 1 |
Python | Python | remove dns from master flag description | 745a4481c5cbab8f7e7740802474cf4f34bbffee | <ide><path>research/object_detection/train.py
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide>
<ide> flags = tf.app.flags
<del>flags.DEFINE_string('master', '', 'DNS name of the TensorFlow master to use.')
<add>flags.DEFINE_string('master', '', 'Name of the TensorFlow master to use.')
<ide> flags.DEFINE_integer('task', 0, 'task id')
<ide> flags.DEFINE_integer('num_clones', 1, 'Number of clones to deploy per worker.')
<ide> flags.DEFINE_boolean('clone_on_cpu', False, | 1 |
Go | Go | add break after key is found in for loop | a5be8034589fe024ce421b4a7d34739be2a1a8af | <ide><path>runconfig/merge.go
<ide> func Merge(userConf, imageConf *Config) error {
<ide> userEnvKey := strings.Split(userEnv, "=")[0]
<ide> if imageEnvKey == userEnvKey {
<ide> found = true
<add> break
<ide> }
<ide> }
<ide> if !found { | 1 |
Mixed | Javascript | remove unused function converttocontext | 3d9e7bb1d467765c0dc391798d8f954c98be095e | <ide><path>doc/api/deprecations.md
<ide> The `os.getNetworkInterfaces()` method is deprecated. Please use the
<ide> <a id="DEP0024"></a>
<ide> ### DEP0024: REPLServer.prototype.convertToContext()
<ide>
<del>Type: Runtime
<add>Type: End-of-Life
<ide>
<ide> The `REPLServer.prototype.convertToContext()` API is deprecated and should
<ide> not be used.
<ide><path>lib/repl.js
<ide> function regexpEscape(s) {
<ide> return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
<ide> }
<ide>
<del>
<del>/**
<del> * Converts commands that use var and function <name>() to use the
<del> * local exports.context when evaled. This provides a local context
<del> * on the REPL.
<del> *
<del> * @param {String} cmd The cmd to convert.
<del> * @return {String} The converted command.
<del> */
<del>// TODO(princejwesley): Remove it prior to v8.0.0 release
<del>// Reference: https://github.com/nodejs/node/pull/7829
<del>REPLServer.prototype.convertToContext = util.deprecate(function(cmd) {
<del> const scopeVar = /^\s*var\s*([\w$]+)(.*)$/m;
<del> const scopeFunc = /^\s*function\s*([\w$]+)/;
<del> var matches;
<del>
<del> // Replaces: var foo = "bar"; with: self.context.foo = bar;
<del> matches = scopeVar.exec(cmd);
<del> if (matches && matches.length === 3) {
<del> return 'self.context.' + matches[1] + matches[2];
<del> }
<del>
<del> // Replaces: function foo() {}; with: foo = function foo() {};
<del> matches = scopeFunc.exec(this.bufferedCommand);
<del> if (matches && matches.length === 2) {
<del> return matches[1] + ' = ' + this.bufferedCommand;
<del> }
<del>
<del> return cmd;
<del>}, 'replServer.convertToContext() is deprecated', 'DEP0024');
<del>
<ide> // If the error is that we've unexpectedly ended the input,
<ide> // then let the user try to recover by adding more input.
<ide> function isRecoverableError(e, code) {
<ide><path>test/parallel/test-repl-deprecated.js
<del>'use strict';
<del>const common = require('../common');
<del>const assert = require('assert');
<del>const repl = require('repl');
<del>
<del>common.expectWarning('DeprecationWarning',
<del> 'replServer.convertToContext() is deprecated');
<del>
<del>// Create a dummy stream that does nothing
<del>const stream = new common.ArrayStream();
<del>
<del>const replServer = repl.start({
<del> input: stream,
<del> output: stream
<del>});
<del>
<del>const cmd = replServer.convertToContext('var name = "nodejs"');
<del>assert.strictEqual(cmd, 'self.context.name = "nodejs"'); | 3 |
Text | Text | update prod commands for api-server | 58a74023ef7b69fd93a0a4f59efab0b647cb0572 | <ide><path>docs/devops.md
<ide> Provisioning VMs with the Code
<ide> 8. Start Instances
<ide>
<ide> ```console
<del> pm2 start api-server/lib/production-start.js -i max --max-memory-restart 600M --name org
<add> cd api-server
<add> pm2 start ./lib/production-start.js -i max --max-memory-restart 600M --name org
<ide> ```
<ide>
<ide> ### Logging and Monitoring | 1 |
Javascript | Javascript | fix spelling of meta_desc.configurable | 18761cc3d1b65152083a80e7fb6b3f00fb8e2b56 | <ide><path>packages/sproutcore-metal/lib/utils.js
<ide> SC.guidFor = function(obj) {
<ide>
<ide> var META_DESC = {
<ide> writable: true,
<del> confgurable: false,
<add> configurable: false,
<ide> enumerable: false,
<ide> value: null
<ide> }; | 1 |
Javascript | Javascript | update workaround for desktop webkit quirk | bc42950b514b60f319812eeb87aae2915e394237 | <ide><path>src/ngTouch/directive/ngClick.js
<ide> ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
<ide> var ACTIVE_CLASS_NAME = 'ng-click-active';
<ide> var lastPreventedTime;
<ide> var touchCoordinates;
<add> var lastLabelClickCoordinates;
<ide>
<ide>
<ide> // TAP EVENTS AND GHOST CLICKS
<ide> ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
<ide> var y = touches[0].clientY;
<ide> // Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label
<ide> // and on the input element). Depending on the exact browser, this second click we don't want
<del> // to bust has either (0,0) or negative coordinates.
<add> // to bust has either (0,0), negative coordinates, or coordinates equal to triggering label
<add> // click event
<ide> if (x < 1 && y < 1) {
<ide> return; // offscreen
<ide> }
<add> if (lastLabelClickCoordinates &&
<add> lastLabelClickCoordinates[0] === x && lastLabelClickCoordinates[1] === y) {
<add> return; // input click triggered by label click
<add> }
<add> // reset label click coordinates on first subsequent click
<add> if (lastLabelClickCoordinates) {
<add> lastLabelClickCoordinates = null;
<add> }
<add> // remember label click coordinates to prevent click busting of trigger click event on input
<add> if (event.target.tagName.toLowerCase() === 'label') {
<add> lastLabelClickCoordinates = [x, y];
<add> }
<ide>
<ide> // Look for an allowable region containing this click.
<ide> // If we find one, that means it was created by touchstart and not removed by
<ide><path>test/ngTouch/directive/ngClickSpec.js
<ide> describe('ngClick (touch)', function() {
<ide> }));
<ide>
<ide>
<del> it('should not cancel clicks that come long after', inject(function($rootScope, $compile) {
<del> element1 = $compile('<div ng-click="count = count + 1"></div>')($rootScope);
<add> describe('when clicking on a label immediately following a touch event', function() {
<add> var touch = function(element, x, y) {
<add> time = 10;
<add> browserTrigger(element, 'touchstart',{
<add> keys: [],
<add> x: x,
<add> y: y
<add> });
<ide>
<del> $rootScope.count = 0;
<add> time = 50;
<add> browserTrigger(element, 'touchend',{
<add> keys: [],
<add> x: x,
<add> y: y
<add> });
<add> };
<ide>
<del> $rootScope.$digest();
<add> var click = function(element, x, y) {
<add> browserTrigger(element, 'click',{
<add> keys: [],
<add> x: x,
<add> y: y
<add> });
<add> };
<ide>
<del> expect($rootScope.count).toBe(0);
<add> var $rootScope;
<add> var container, otherElement, input, label;
<add> beforeEach(inject(function(_$rootScope_, $compile, $rootElement) {
<add> $rootScope = _$rootScope_;
<add> var container = $compile('<div><div ng-click="count = count + 1"></div>' +
<add> '<input id="input1" type="radio" ng-model="selection" value="radio1">' +
<add> '<label for="input1">Input1</label></div>')($rootScope);
<add> $rootElement.append(container);
<add> otherElement = container.children()[0];
<add> input = container.children()[1];
<add> label = container.children()[2];
<ide>
<del> time = 10;
<del> browserTrigger(element1, 'touchstart',{
<del> keys: [],
<del> x: 10,
<del> y: 10
<add> $rootScope.selection = 'initial';
<add>
<add> $rootScope.$digest();
<add> }));
<add>
<add>
<add> afterEach(function() {
<add> dealoc(label);
<add> dealoc(input);
<add> dealoc(otherElement);
<add> dealoc(container);
<ide> });
<ide>
<del> time = 50;
<del> browserTrigger(element1, 'touchend',{
<del> keys: [],
<del> x: 10,
<del> y: 10
<add>
<add> it('should not cancel input clicks with (0,0) coordinates', function() {
<add> touch(otherElement, 100, 100);
<add>
<add> time = 500;
<add> click(label, 10, 10);
<add> click(input, 0, 0);
<add>
<add> expect($rootScope.selection).toBe('radio1');
<ide> });
<ide>
<del> expect($rootScope.count).toBe(1);
<ide>
<del> time = 2700;
<del> browserTrigger(element1, 'click',{
<del> keys: [],
<del> x: 10,
<del> y: 10
<add> it('should not cancel input clicks with negative coordinates', function() {
<add> touch(otherElement, 100, 100);
<add>
<add> time = 500;
<add> click(label, 10, 10);
<add> click(input, -1, -1);
<add>
<add> expect($rootScope.selection).toBe('radio1');
<ide> });
<ide>
<del> expect($rootScope.count).toBe(2);
<del> }));
<add>
<add> it('should not cancel input clicks with positive coordinates identical to label click', function() {
<add> touch(otherElement, 100, 100);
<add>
<add> time = 500;
<add> click(label, 10, 10);
<add> click(input, 10, 10);
<add>
<add> expect($rootScope.selection).toBe('radio1');
<add> });
<add>
<add>
<add> it('should cancel input clicks with positive coordinates different than label click', function() {
<add> touch(otherElement, 100, 100);
<add>
<add> time = 500;
<add> click(label, 10, 10);
<add> click(input, 11, 11);
<add>
<add> expect($rootScope.selection).toBe('initial');
<add> });
<add> });
<ide> });
<ide>
<ide> | 2 |
PHP | PHP | fix open cursors | a08549cbb2861d9c0dbc950f18fdbc83c4813654 | <ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testWhereInArrayEmpty()
<ide> $query = new Query($this->connection);
<ide> $query->select(['id'])
<ide> ->from('articles')
<del> ->whereInList('id', [], ['allowEmpty' => true])
<del> ->execute();
<del> $sql = $query->sql();
<del>
<del> $result = $query->execute();
<del> $this->assertFalse($result->fetch('assoc'));
<add> ->whereInList('id', [], ['allowEmpty' => true]);
<ide>
<ide> $this->assertQuotedQuery(
<ide> 'SELECT <id> FROM <articles> WHERE 1=0',
<del> $sql,
<add> $query->sql(),
<ide> !$this->autoQuote
<ide> );
<add>
<add> $statement = $query->execute();
<add> $this->assertFalse($statement->fetch('assoc'));
<add> $statement->closeCursor();
<ide> }
<ide>
<ide> /**
<ide> public function testSelectOffset()
<ide> $query->select('id')->from('comments')
<ide> ->limit(1)
<ide> ->offset(1)
<del> ->execute();
<add> ->execute()
<add> ->closeCursor();
<ide>
<ide> $reflect = new ReflectionProperty($query, '_dirty');
<ide> $reflect->setAccessible(true); | 1 |
Text | Text | add content on strings | 60e278f1d7757f8167e412c0973434be86e980f6 | <ide><path>guide/english/python/data-structures/strings/index.md
<ide> Python allows `str` objects, or _strings_, to be expressed in a few different wa
<ide> Traceback (most recent call last):
<ide> File "<stdin>", line 1, in <module>
<ide> TypeError: 'str' object does not support item assignment
<add>
<add> Instead, you can convert the string into a list, modify the list element (string character) you wish to change, and then join the list elements back to a string, like so:
<add>
<add> >>> foo = "my string"
<add> >>> foo_list_form = list(foo)
<add> >>> foo_list_form[0] = "a"
<add> >>> foo = ' '.join(foo_list_form)
<add> >>> print(foo)
<add> ay string # The required output
<ide> * Indexable: You can access any character of `str` object by specifying its index. And as it supports slicing like in `list` and `tuple` objects.
<ide>
<ide> >>> foo = "my string"
<ide> Python allows `str` objects, or _strings_, to be expressed in a few different wa
<ide> >>> foo[::-1]
<ide> 'gnirts ym'
<ide>
<del> Instead, you can convert the string into a list, modify the list element (string character) you wish to change, and then join the list elements back to a string, like so:
<del>
<del> >>> foo = "my string"
<del> >>> foo_list_form = list(foo)
<del> >>> foo_list_form[0] = "a"
<del> >>> foo = ' '.join(foo_list_form)
<del> >>> print(foo)
<del> ay string # The required output
<ide>
<add>If we have a string `S`, we can access its length with the command `len(S)`.
<add>```python
<add>>>> S = 'Hero'
<add>>>> len(S)
<add>4
<add>```
<add>
<add>#### Accessing elements, Indexing and Slicing:
<add>Strings are zero-indexed. We can associate each element in a string with a number, the `1st` element indexed at `0`. So, a string of `N` characters would have `N` indices, from `0` to `N-1`.
<add>Indices help us to access elements of the string.
<add>```python
<add>>>> S = 'ABCDEFGH'
<add>>>> S[0]
<add>'A'
<add>>>> S[2]
<add>'C'
<add>>>> S[8]
<add>Traceback (most recent call last):
<add> File "<pyshell#9>", line 1, in <module>
<add> S[8]
<add>IndexError: string index out of range
<add>>>>
<add>>>> S[7]
<add>'H'
<add>```
<add>As we see above, we type `S[0]` to access the 1st element of the string, i.e., `'A'`. Also note that since the indices start at `0`, the last element in the string `ABCDEFGH` has the index `7` and not `8`, even though the string itself has length `8`. Hence, we see that `IndexError` message when we try to access `S[8]`.
<add>Another cool thing we can do with strings is slicing. Instead of accessing individual elements, we can access chunks of the string with slices. The syntax is `S[start:stop:step]` where `start` (default value `0`) refers to the index at which we want to begin slicing, `stop` (default value `len(S)`) is the index where we want to end slicing, and `step` (default value `1`) is the jump after each element. Let's look at this in action.
<add>```python
<add>>>> S = 'ABCDEFGH'
<add>>>> S[0:5:1]
<add>'ABCDE'
<add>>>> S[2:8]
<add>'CDEFGH'
<add>>>> S[1::2]
<add>'BDFH'
<add>>>> S[::-1]
<add>'HGFEDCBA'
<add>```
<add>Please note that the part of string that gets printed out goes up to `stop - 1` value and not `stop`. Hence, `S[0:5:1]` starts at `S[0]` and stops at `S[4]`.
<add>When we don't specify a value for a parameter, Python automatically takes the default value as stated above.
<add>See how making the `step` equal to `-1` just reverses the string. Cool, huh?
<add>Feel free to experiment with different combinations to get comfortable with slicing. It's going to be very useful.
<add>
<add>#### Concatenation and Repetition:
<add>```python
<add>>>> 2 + 3
<add>5
<add>>>> 'My' + ' ' + 'Hero' + ' ' + 'Academia'
<add>'My Hero Academia'
<add>>>>
<add>>>> 4 * 9
<add>36
<add>>>> 'Yo!' * 3
<add>'Yo!Yo!Yo!'
<add>```
<add>The `+` and `*` operators are said to be `overloaded` because they behave differently for different types of objects.
<add>Using the `+` operator on strings leads to `concatenation`, while the `*` operator results in `repetition`.
<add>
<ide> ## Reference:
<ide>
<ide> <a href='https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str' target='_blank' rel='nofollow'>Text Sequence Type _str_</a> | 1 |
Ruby | Ruby | fix syntax error, sorry about that | ad02ea74da758f5063b219a4a35df9431c4d8732 | <ide><path>Library/Homebrew/macos/xcode.rb
<ide> def installed?
<ide> end
<ide>
<ide> def latest_version?
<del> `/usr/bin/clang -v` =~ %r{tags/Apple/clang-(\d+).(\d+).(\d+)}
<del> $1 >= 421 and $3 >= 57
<add> `/usr/bin/clang -v 2>&1` =~ %r{tags/Apple/clang-(\d+)\.(\d+)\.(\d+)}
<add> $1.to_i >= 421 and $3.to_i >= 57
<ide> end
<ide>
<ide> def version | 1 |
Python | Python | remove dependency to simplejson | 739462d804baad9af7b5ac0461cbd335ce181047 | <ide><path>celery/views.py
<ide> from django.http import HttpResponse
<ide> from celery.task import is_done, delay_task
<ide> from celery.result import AsyncResult
<del>import simplejson
<add>from carrot.serialization import serialize as JSON_dump
<ide>
<ide>
<ide> def is_task_done(request, task_id):
<ide> """Returns task execute status in JSON format."""
<ide> response_data = {"task": {"id": task_id, "executed": is_done(task_id)}}
<del> return HttpResponse(simplejson.dumps(response_data))
<add> return HttpResponse(JSON_dump(response_data))
<ide>
<ide>
<ide> def task_status(request, task_id):
<ide> def task_status(request, task_id):
<ide> "status": async_result.status,
<ide> "result": async_result.result,
<ide> }}
<del> return HttpResponse(simplejson.dumps(response_data))
<add> return HttpResponse(JSON_dump(response_data))
<ide><path>setup.py
<ide> def run(self):
<ide> scripts=["bin/celeryd"],
<ide> zip_safe=False,
<ide> install_requires=[
<del> 'simplejson',
<ide> 'carrot>=0.4.1',
<ide> 'django',
<ide> ], | 2 |
PHP | PHP | improve description and fix phpcs error | fdffa438cb48d784bdba69b7da79728c3e224162 | <ide><path>src/Core/ContainerInterface.php
<ide> */
<ide> namespace Cake\Core;
<ide>
<del>use League\Container\DefinitionInterface;
<add>use League\Container\Definition\DefinitionInterface;
<ide> use Psr\Container\ContainerInterface as PsrInterface;
<ide>
<ide> /**
<ide> * The methods defined in this interface use the conventions provided
<ide> * by league/container as that is the library that CakePHP uses.
<ide> *
<del> * @experimental This interface is not final and can have additional
<add> * @experimental This interface is not final and can have additional
<ide> * methods and parameters added in future minor releases.
<ide> */
<ide> interface ContainerInterface extends PsrInterface
<ide> interface ContainerInterface extends PsrInterface
<ide> *
<ide> * @param string $id The class name or name of the service being registered.
<ide> * @param mixed $concrete Either the classname an interface or name resolves to.
<del> * Can also be a constructed object, or null. When null, the `$id` parameter will
<add> * Can also be a constructed object, Closure, or null. When null, the `$id` parameter will
<ide> * be used as the concrete class name.
<del> * @param boolean $shared Set to true to make a service shared.
<del> * @return \League\Container\DefinitionInterface
<add> * @param bool|null $shared Set to true to make a service shared.
<add> * @return \League\Container\Definition\DefinitionInterface
<ide> */
<ide> public function add(string $id, $concrete = null, bool $shared = null): DefinitionInterface;
<ide>
<ide> /**
<ide> * Add a service provider to the container
<ide> *
<del> * @param \League\Container\ServiceProviderInterface $provider The service provider to add.
<add> * @param \League\Container\ServiceProvider\ServiceProviderInterface $provider The service provider to add.
<ide> * @return $this
<ide> */
<ide> public function addServiceProvider($provider); | 1 |
Text | Text | fix some format errors | 71f1205269494430116e7a564ee76bfa0bfccc63 | <ide><path>docs/reference/run.md
<ide> Supported networks :
<ide> <td class="no-wrap"><strong>container</strong>:<name|id></td>
<ide> <td>
<ide> Use the network stack of another container, specified via
<del> its *name* or *id*.
<add> its <i>name</i> or <i>id</i>.
<ide> </td>
<ide> </tr>
<ide> <tr>
<ide> <td class="no-wrap"><strong>NETWORK</strong></td>
<ide> <td>
<del> Connects the container to a user created network (using `docker network create` command)
<add> Connects the container to a user created network (using <code>docker network create</code> command)
<ide> </td>
<ide> </tr>
<ide> </tbody>
<ide> but the volume for `/bar` will not. Volumes inherited via `--volumes-from` will
<ide> with the same logic -- if the original volume was specified with a name it will **not** be removed.
<ide>
<ide> ## Security configuration
<del> --security-opt="label=user:USER" : Set the label user for the container
<del> --security-opt="label=role:ROLE" : Set the label role for the container
<del> --security-opt="label=type:TYPE" : Set the label type for the container
<del> --security-opt="label=level:LEVEL" : Set the label level for the container
<del> --security-opt="label=disable" : Turn off label confinement for the container
<del> --security-opt="apparmor=PROFILE" : Set the apparmor profile to be applied to the container
<del> --security-opt="no-new-privileges" : Disable container processes from gaining new privileges
<del> --security-opt="seccomp=unconfined": Turn off seccomp confinement for the container
<del> --security-opt="seccomp=profile.json: White listed syscalls seccomp Json file to be used as a seccomp filter
<add> --security-opt="label=user:USER" : Set the label user for the container
<add> --security-opt="label=role:ROLE" : Set the label role for the container
<add> --security-opt="label=type:TYPE" : Set the label type for the container
<add> --security-opt="label=level:LEVEL" : Set the label level for the container
<add> --security-opt="label=disable" : Turn off label confinement for the container
<add> --security-opt="apparmor=PROFILE" : Set the apparmor profile to be applied to the container
<add> --security-opt="no-new-privileges" : Disable container processes from gaining new privileges
<add> --security-opt="seccomp=unconfined" : Turn off seccomp confinement for the container
<add> --security-opt="seccomp=profile.json": White listed syscalls seccomp Json file to be used as a seccomp filter
<ide>
<ide>
<ide> You can override the default labeling scheme for each container by specifying
<ide> We have four ways to set user memory usage:
<ide> <td class="no-wrap"><strong>memory=L<inf, memory-swap=2*L</strong></td>
<ide> <td>
<ide> (specify memory without memory-swap) The container is not allowed to
<del> use more than L bytes of memory, swap *plus* memory usage is double
<add> use more than L bytes of memory, swap <i>plus</i> memory usage is double
<ide> of that.
<ide> </td>
<ide> </tr>
<ide> We have four ways to set user memory usage:
<ide> </td>
<ide> <td>
<ide> (specify both memory and memory-swap) The container is not allowed to
<del> use more than L bytes of memory, swap *plus* memory usage is limited
<add> use more than L bytes of memory, swap <i>plus</i> memory usage is limited
<ide> by S.
<ide> </td>
<ide> </tr> | 1 |
Mixed | Python | remove weight tying in autoencoder | 94c930e99e8908d2188213672bed050b54ebdb5a | <ide><path>docs/sources/layers/core.md
<ide> model.add(TimeDistributedDense(5, 10)) # output shape: (nb_samples, nb_timesteps
<ide>
<ide> ## AutoEncoder
<ide> ```python
<del>keras.layers.core.AutoEncoder(encoder, decoder, output_reconstruction=True, tie_weights=False, weights=None):
<add>keras.layers.core.AutoEncoder(encoder, decoder, output_reconstruction=True, weights=None):
<ide> ```
<ide>
<ide> A customizable autoencoder model. If `output_reconstruction = True` then dim(input) = dim(output) else dim(output) = dim(hidden)
<ide> A customizable autoencoder model. If `output_reconstruction = True` then dim(inp
<ide>
<ide> - __output_reconstruction__: If this is False the when .predict() is called the output is the deepest hidden layer's activation. Otherwise the output of the final decoder layer is presented. Be sure your validation data confirms to this logic if you decide to use any.
<ide>
<del> - __tie_weights__: If True then the encoder bias is tied to the decoder bias. **Note**: This required the encoder layer corresponding to this decoder layer to be of the same time, eg: Dense:Dense
<del>
<ide> - __weights__: list of numpy arrays to set as initial weights. The list should have 1 element, of shape `(input_dim, output_dim)`.
<ide>
<ide> - __Example__:
<ide> encoder = containers.Sequential([Dense(32, 16), Dense(16, 8)])
<ide> decoder = containers.Sequential([Dense(8, 16), Dense(16, 32)])
<ide>
<ide> autoencoder = Sequential()
<del>autoencoder.add(AutoEncoder(encoder=encoder, decoder=decoder, output_reconstruction=False, tie_weights=True))
<add>autoencoder.add(AutoEncoder(encoder=encoder, decoder=decoder, output_reconstruction=False))
<ide> ```
<ide>
<ide>
<ide><path>keras/layers/core.py
<ide> class AutoEncoder(Layer):
<ide> If output_reconstruction then dim(input) = dim(output)
<ide> else dim(output) = dim(hidden)
<ide> '''
<del> def __init__(self, encoder, decoder, output_reconstruction=True, tie_weights=False, weights=None):
<add> def __init__(self, encoder, decoder, output_reconstruction=True, weights=None):
<ide>
<ide> super(AutoEncoder, self).__init__()
<ide>
<ide> self.output_reconstruction = output_reconstruction
<del> self.tie_weights = tie_weights
<ide> self.encoder = encoder
<ide> self.decoder = decoder
<ide>
<ide> def __init__(self, encoder, decoder, output_reconstruction=True, tie_weights=Fal
<ide> self.regularizers = []
<ide> self.constraints = []
<ide> for layer in [self.encoder, self.decoder]:
<del> self.params += layer.params
<del> if hasattr(layer, 'regularizers'):
<del> self.regularizers += layer.regularizers
<del> if hasattr(layer, 'constraints'):
<del> self.constraints += layer.constraints
<add> params, regularizers, constraints = layer.get_params()
<add> self.constraints += constraints
<add> for p, r in zip(params, regularizers):
<add> if p not in self.params:
<add> self.params.append(p)
<add> self.regularizers.append(r)
<ide>
<ide> if weights is not None:
<ide> self.set_weights(weights)
<ide> def get_output(self, train=False):
<ide> if not train and not self.output_reconstruction:
<ide> return self.encoder.get_output(train)
<ide>
<del> decoded = self.decoder.get_output(train)
<del>
<del> if self.tie_weights:
<del> encoder_params = self.encoder.get_weights()
<del> decoder_params = self.decoder.get_weights()
<del> for dec_param, enc_param in zip(decoder_params, encoder_params):
<del> if len(dec_param.shape) > 1:
<del> enc_param = dec_param.T
<del>
<del> return decoded
<add> return self.decoder.get_output(train)
<ide>
<ide> def get_config(self):
<ide> return {"name":self.__class__.__name__,
<ide> "encoder_config":self.encoder.get_config(),
<ide> "decoder_config":self.decoder.get_config(),
<del> "output_reconstruction":self.output_reconstruction,
<del> "tie_weights":self.tie_weights}
<add> "output_reconstruction":self.output_reconstruction}
<ide>
<ide>
<ide>
<ide><path>tests/manual/check_autoencoder.py
<ide> from __future__ import print_function
<ide> from keras.datasets import mnist
<ide> from keras.models import Sequential
<del>from keras.layers.core import DenoisingAutoEncoder, AutoEncoder, Dense, Activation, TimeDistributedDense, Flatten
<add>from keras.layers.core import AutoEncoder, Dense, Activation, TimeDistributedDense, Flatten
<ide> from keras.layers.recurrent import LSTM
<ide> from keras.layers.embeddings import Embedding
<ide> from keras.layers.core import Layer
<ide> def build_lstm_autoencoder(autoencoder, X_train, X_test):
<ide> autoencoder.add(TimeDistributedDense(input_dim, 16))
<ide> autoencoder.add(AutoEncoder(encoder=LSTM(16, 8, activation=activation, return_sequences=True),
<ide> decoder=LSTM(8, input_dim, activation=activation, return_sequences=True),
<del> output_reconstruction=False, tie_weights=True))
<add> output_reconstruction=False))
<ide> return autoencoder, X_train, X_test
<ide>
<ide> def build_deep_classical_autoencoder(autoencoder):
<ide> encoder = containers.Sequential([Dense(input_dim, hidden_dim, activation=activation), Dense(hidden_dim, hidden_dim/2, activation=activation)])
<ide> decoder = containers.Sequential([Dense(hidden_dim/2, hidden_dim, activation=activation), Dense(hidden_dim, input_dim, activation=activation)])
<del> autoencoder.add(AutoEncoder(encoder=encoder, decoder=decoder, output_reconstruction=False, tie_weights=True))
<del> return autoencoder
<del>
<del>def build_denoising_autoencoder(autoencoder):
<del> # You need another layer before a denoising autoencoder
<del> # This is similar to the dropout layers, etc..
<del> autoencoder.add(Dense(input_dim, input_dim))
<del> autoencoder.add(DenoisingAutoEncoder(encoder=Dense(input_dim, hidden_dim, activation=activation),
<del> decoder=Dense(hidden_dim, input_dim, activation=activation),
<del> output_reconstruction=False, tie_weights=True, corruption_level=0.3))
<del> return autoencoder
<del>
<del>def build_deep_denoising_autoencoder(autoencoder):
<del> encoder = containers.Sequential([Dense(input_dim, hidden_dim, activation=activation), Dense(hidden_dim, hidden_dim/2, activation=activation)])
<del> decoder = containers.Sequential([Dense(hidden_dim/2, hidden_dim, activation=activation), Dense(hidden_dim, input_dim, activation=activation)])
<del> autoencoder.add(Dense(input_dim, input_dim))
<del> autoencoder.add(DenoisingAutoEncoder(encoder=encoder, decoder=decoder, output_reconstruction=False, tie_weights=True))
<add> autoencoder.add(AutoEncoder(encoder=encoder, decoder=decoder, output_reconstruction=False))
<ide> return autoencoder
<ide>
<ide>
<ide>
<ide> # Try different things here: 'lstm' or 'classical' or 'denoising'
<ide> # or 'deep_denoising'
<ide>
<del>for autoencoder_type in ['classical', 'denoising', 'deep_denoising', 'lstm']:
<add>for autoencoder_type in ['classical', 'lstm']:
<ide> print(autoencoder_type)
<ide> print('-'*40)
<ide> # Build our autoencoder model
<ide> autoencoder = Sequential()
<ide> if autoencoder_type == 'lstm':
<ide> print("Training LSTM AutoEncoder")
<ide> autoencoder, X_train, X_test = build_lstm_autoencoder(autoencoder, X_train, X_test)
<del> elif autoencoder_type == 'denoising':
<del> print("Training Denoising AutoEncoder")
<del> autoencoder = build_denoising_autoencoder(autoencoder)
<del> elif autoencoder_type == 'deep_denoising':
<del> print ("Training Deep Denoising AutoEncoder")
<del> autoencoder = build_deep_denoising_autoencoder(autoencoder)
<ide> elif autoencoder_type == 'classical':
<ide> print("Training Classical AutoEncoder")
<ide> autoencoder = build_deep_classical_autoencoder(autoencoder) | 3 |
Javascript | Javascript | add a separate class for hotupdatechunk | 3677e25c3089a7bb5df5fa471d4b07c6668a9310 | <ide><path>lib/HotUpdateChunk.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>"use strict";
<add>
<add>const Chunk = require("./Chunk");
<add>
<add>class HotUpdateChunk extends Chunk {
<add> constructor() {
<add> super();
<add> this.removedModules = undefined;
<add> }
<add>}
<add>
<add>module.exports = HotUpdateChunk;
<ide><path>lib/HotUpdateChunkTemplate.js
<ide> "use strict";
<ide>
<ide> const Template = require("./Template");
<del>const Chunk = require("./Chunk");
<add>const HotUpdateChunk = require("./HotUpdateChunk");
<ide> const { Tapable, SyncWaterfallHook, SyncHook } = require("tapable");
<ide>
<ide> module.exports = class HotUpdateChunkTemplate extends Tapable {
<ide> module.exports = class HotUpdateChunkTemplate extends Tapable {
<ide> moduleTemplate,
<ide> dependencyTemplates
<ide> ) {
<del> const hotUpdateChunk = new Chunk();
<add> const hotUpdateChunk = new HotUpdateChunk();
<ide> hotUpdateChunk.id = id;
<ide> hotUpdateChunk.setModules(modules);
<ide> hotUpdateChunk.removedModules = removedModules; | 2 |
Ruby | Ruby | add full license | 895a78de2c5193e53a79cdf64be86c88bcb93c3c | <ide><path>ci/qunit-selenium-runner.rb
<ide> require "webdrivers"
<ide>
<ide> # This class based on https://github.com/smontanari/qunit-selenium, with a few tweaks to make it easier to read output.
<add># The license from https://github.com/smontanari/qunit-selenium is enclosed:
<add>#
<add># The MIT License (MIT)
<add>#
<ide> # Copyright (c) 2014 Silvio Montanari
<del># License: MIT
<add>#
<add># Permission is hereby granted, free of charge, to any person obtaining a copy
<add># of this software and associated documentation files (the "Software"), to deal
<add># in the Software without restriction, including without limitation the rights
<add># to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
<add># copies of the Software, and to permit persons to whom the Software is
<add># furnished to do so, subject to the following conditions:
<add>#
<add># The above copyright notice and this permission notice shall be included in all
<add># copies or substantial portions of the Software.
<add>#
<add># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<add># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<add># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
<add># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
<add># OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
<add># SOFTWARE.
<add>
<ide> class TestRun
<ide> TestResult = Struct.new(:tests, :assertions, :duration, :raw_output)
<ide> | 1 |
PHP | PHP | fix cs error | befb7ba36511623807da8922608dafbd9d5804a8 | <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> use Cake\Http\Response;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Http\Session;
<del>use Cake\Routing\Route\InflectedRoute;
<ide> use Cake\Routing\Router;
<add>use Cake\Routing\Route\InflectedRoute;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Security;
<ide> use TestApp\Controller\AuthTestController; | 1 |
Ruby | Ruby | use correct version in download | 417f27f40f112bdc228b9f2ab27fef8cea7c7d97 | <ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def bump_formula_pr
<ide> rsrc = Resource.new { @url = rsrc_url }
<ide> rsrc.download_strategy = CurlDownloadStrategy
<ide> rsrc.owner = Resource.new(formula.name)
<add> rsrc.version = forced_version if forced_version
<ide> rsrc_path = rsrc.fetch
<ide> if Utils.popen_read("/usr/bin/tar", "-tf", rsrc_path) =~ %r{/.*\.}
<ide> new_hash = rsrc_path.sha256 | 1 |
Ruby | Ruby | use gitconfig to remember last tag | 5b360f35c534a881e045fd51474e3982dad63c11 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def update_report
<ide> puts "Updated Homebrew from #{shorten_revision(initial_revision)} to #{shorten_revision(current_revision)}."
<ide> updated = true
<ide>
<del> new_repository_version = Utils.safe_popen_read("git", "tag", "--points-at", "HEAD").chomp.presence
<add> old_tag = if (HOMEBREW_REPOSITORY/".git/config").exist?
<add> Utils.popen_read(
<add> "git", "config", "--file=#{HOMEBREW_REPOSITORY}/.git/config", "--get", "homebrew.latesttag"
<add> ).chomp.presence
<add> end
<add>
<add> new_tag = Utils.popen_read(
<add> "git", "-C", HOMEBREW_REPOSITORY, "tag", "--list", "--sort=-version:refname"
<add> ).lines.first.chomp
<add>
<add> if new_tag != old_tag
<add> system "git", "config", "--file=#{HOMEBREW_REPOSITORY}/.git/config",
<add> "--replace-all", "homebrew.latesttag", new_tag
<add> new_repository_version = new_tag
<add> end
<ide> end
<ide>
<ide> Homebrew.failed = true if ENV["HOMEBREW_UPDATE_FAILED"] | 1 |
PHP | PHP | add update with join support for postgres | 7f19f76494995ec1566dbcaf228792a32aa0e3ff | <ide><path>lib/Cake/Database/Dialect/PostgresDialectTrait.php
<ide> protected function _selectQueryTranslator($query) {
<ide> return $query;
<ide> }
<ide>
<add>/**
<add> * Returns an update query that has been transformed for Postgres.
<add> *
<add> * Postgres requires joins to be defined in the FROM list instead of
<add> * as standard joins. This translator will erase joins and replace them with
<add> * an expression object in the FROM clause.
<add> *
<add> * @param Cake\Database\Query $query
<add> * @return Cake\Database\Query
<add> */
<add> protected function _updateQueryTranslator($query) {
<add> $joins = $query->clause('join');
<add> if ($joins) {
<add> $sql = '';
<add> foreach ($joins as $i => $join) {
<add> if ($i == 0) {
<add> $sql .= sprintf('%s %s', $join['table'], $join['alias']);
<add> if (isset($join['conditions']) && count($join['conditions'])) {
<add> $query->where($join['conditions']);
<add> }
<add> continue;
<add> }
<add> $sql .= sprintf(' %s JOIN %s %s', $join['type'], $join['table'], $join['alias']);
<add> if (isset($join['conditions']) && count($join['conditions'])) {
<add> $sql .= sprintf(' ON %s', $join['conditions']);
<add> } else {
<add> $sql .= ' ON 1 = 1';
<add> }
<add> }
<add> $expr = $query->newExpr()->add($sql);
<add> $query->join([], [], true);
<add> $query->from([$expr]);
<add> }
<add> return $query;
<add> }
<add>
<ide> /**
<ide> * Returns a function that will be used as a callback for a results decorator.
<ide> * this function is responsible for deleting the artificial column in results
<ide><path>lib/Cake/Database/Query.php
<ide> protected function _traverseDelete(callable $visitor) {
<ide> * @return void
<ide> */
<ide> protected function _traverseUpdate(callable $visitor) {
<del> $parts = ['update', 'join', 'set', 'where'];
<add> $parts = ['update', 'join', 'set', 'from', 'where'];
<ide> foreach ($parts as $name) {
<ide> call_user_func($visitor, $this->_parts[$name], $name);
<ide> }
<ide> public function join($tables = null, $types = [], $overwrite = false) {
<ide> if (!($t['conditions']) instanceof ExpressionInterface) {
<ide> $t['conditions'] = $this->newExpr()->add($t['conditions'], $types);
<ide> }
<del>
<ide> $joins[] = $t + ['type' => 'INNER', 'alias' => is_string($alias) ? $alias : null];
<ide> }
<ide>
<ide> public function join($tables = null, $types = [], $overwrite = false) {
<ide> protected function _buildJoinPart($parts) {
<ide> $joins = '';
<ide> foreach ($parts as $join) {
<add> if ($join instanceof ExpressionInterface) {
<add> $joins .= $join->sql();
<add> continue;
<add> }
<add>
<ide> $joins .= sprintf(' %s JOIN %s %s', $join['type'], $join['table'], $join['alias']);
<ide> if (isset($join['conditions']) && count($join['conditions'])) {
<ide> $joins .= sprintf(' ON %s', $join['conditions']);
<ide><path>lib/Cake/Test/TestCase/Database/Driver/PostgresTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Database\Connection;
<ide> use Cake\Database\Driver\Postgres;
<add>use Cake\Database\Query;
<ide> use \PDO;
<ide>
<ide> /**
<ide> public function testConnectionConfigCustom() {
<ide> $driver->connect();
<ide> }
<ide>
<add> public function testUpdateWithJoin() {
<add> $driver = $this->getMock('Cake\Database\driver\Postgres', ['_connect', 'connection']);
<add> $connection = new Connection(Configure::read('Datasource.test'));
<add> $connection->driver($driver);
<add>
<add> $query = new Query($connection);
<add>
<add> $query->update('articles')
<add> ->set('title', 'New title')
<add> ->join([
<add> 'table' => 'authors',
<add> 'alias' => 'a',
<add> 'conditions' => 'author_id = a.id'
<add> ])
<add> ->join('comments')
<add> ->where(['articles.id' => 1]);
<add> $result = $query->sql(true);
<add>
<add> $this->assertContains('UPDATE articles SET title = :', $result);
<add> $this->assertContains('FROM authors a INNER JOIN comments ON 1 = 1', $result);
<add> $this->assertContains('WHERE (articles.id = :', $result);
<add> $this->assertContains('AND author_id = a.id)', $result);
<add> }
<add>
<ide> } | 3 |
Text | Text | fix broken link | 963034d243d579b24e4053432691d2e0f059e6fc | <ide><path>docs/tutorials/fundamentals/part-3-state-reducers-actions.md
<ide> Writing immutable update logic by hand _is_ hard, and accidentally mutating stat
<ide>
<ide> :::tip
<ide>
<del>In real-world applications, you won't have to write these complex nested immutable updates by hand. In [Part 8](./part-8-modern-redux), you'll
<add>In real-world applications, you won't have to write these complex nested immutable updates by hand. In [Part 8](./part-8-modern-redux.md), you'll
<ide> learn how to use Redux Toolkit to simplify writing immutable update logic in reducers.
<ide>
<ide> ::: | 1 |
PHP | PHP | move additional code into the shared trait | 0eca8416955206022915076c5ec1ac456bf636c0 | <ide><path>src/I18n/DateFormatTrait.php
<ide> */
<ide> trait DateFormatTrait
<ide> {
<add> /**
<add> * The default locale to be used for displaying formatted date strings.
<add> *
<add> * @var string
<add> */
<add> public static $defaultLocale;
<add>
<add> /**
<add> * In-memory cache of date formatters
<add> *
<add> * @var array
<add> */
<add> protected static $_formatters = [];
<ide>
<ide> /**
<ide> * The format to use when when converting this object to json
<ide> protected function _formatObject($date, $format, $locale)
<ide> );
<ide> }
<ide>
<del> return static::$_formatters[$key]->format($date);
<add> return static::$_formatters[$key]->format($date->format('U'));
<ide> }
<ide>
<ide> /**
<ide> public static function parseDateTime($time, $format = null)
<ide> $time = $formatter->parse($time);
<ide> if ($time) {
<ide> $result = new static('@' . $time);
<del> $result->setTimezone(date_default_timezone_get());
<del> return $result;
<add> return $result->setTimezone(date_default_timezone_get());
<ide> }
<ide> return null;
<ide> }
<ide><path>src/I18n/Time.php
<ide> class Time extends Chronos implements JsonSerializable
<ide> * @see \Cake\I18n\Time::nice()
<ide> */
<ide> public static $niceFormat = [IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT];
<del>
<del> /**
<del> * The default locale to be used for displaying formatted date strings.
<del> *
<del> * @var string
<del> */
<del> public static $defaultLocale;
<del>
<ide> /**
<ide> * The format to use when formatting a time using `Cake\I18n\Time::timeAgoInWords()`
<ide> * and the difference is more than `Cake\I18n\Time::$wordEnd`
<ide> class Time extends Chronos implements JsonSerializable
<ide> */
<ide> public static $wordEnd = '+1 month';
<ide>
<del> /**
<del> * In-memory cache of date formatters
<del> *
<del> * @var array
<del> */
<del> protected static $_formatters = [];
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */ | 2 |
Javascript | Javascript | allow username submission after failure | 265e383705e16bade6570e1769103d35e3498f1c | <ide><path>client/src/components/settings/Username.js
<ide> class UsernameSettings extends Component {
<ide> {
<ide> formValue: newValue,
<ide> isFormPristine: username === newValue,
<del> characterValidation: this.validateFormInput(newValue)
<add> characterValidation: this.validateFormInput(newValue),
<add> submitClicked: false
<ide> },
<ide> () =>
<ide> this.state.isFormPristine || this.state.characterValidation.error | 1 |
Go | Go | remove uses of ioutils.tempdir | c4c53659f1022c227af8e4c07ad8cf3b70fd42d5 | <ide><path>integration-cli/docker_api_containers_test.go
<ide> import (
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/integration-cli/cli"
<ide> "github.com/docker/docker/integration-cli/cli/build"
<del> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/testutil/request"
<ide> "github.com/docker/docker/volume"
<ide> func (s *DockerAPISuite) TestContainersAPICreateMountsValidation(c *testing.T) {
<ide> }
<ide>
<ide> if testEnv.IsLocalDaemon() {
<del> tmpDir, err := ioutils.TempDir("", "test-mounts-api")
<add> tmpDir, err := os.MkdirTemp("", "test-mounts-api")
<ide> assert.NilError(c, err)
<ide> defer os.RemoveAll(tmpDir)
<ide> cases = append(cases, []testCase{
<ide> func (s *DockerAPISuite) TestContainersAPICreateMountsCreate(c *testing.T) {
<ide>
<ide> // for modes only supported on Linux
<ide> if DaemonIsLinux() {
<del> tmpDir3, err := ioutils.TempDir("", "test-mounts-api-3")
<add> tmpDir3, err := os.MkdirTemp("", "test-mounts-api-3")
<ide> assert.NilError(c, err)
<ide> defer os.RemoveAll(tmpDir3)
<ide> | 1 |
Mixed | Text | add docs update - part 1 | 7e702439eb4a82fe2ef45911fbb176e95d5f0bce | <ide><path>docs/api-guide/fields.md
<ide> Corresponds to `django.forms.fields.RegexField`
<ide>
<ide> A date representation.
<ide>
<del>Uses `DATE_INPUT_FORMATS` to validate date.
<del>
<ide> Optionally takes `format` as parameter to replace the matching pattern.
<ide>
<ide> Corresponds to `django.db.models.fields.DateField`
<ide>
<add>**Signature:** `DateField(input_formats=None, output_format=False)`
<add>
<add> - `input_formats` designates which input formats are supported. This will override the `DATE_INPUT_FORMATS`
<add>
<add> - `output_format` designates which output format will be used. This will override the `DATE_OUTPUT_FORMAT`
<add>
<ide> ## DateTimeField
<ide>
<ide> A date and time representation.
<ide>
<del>Uses `DATETIME_INPUT_FORMATS` to validate date_time.
<del>
<ide> Optionally takes `format` as parameter to replace the matching pattern.
<ide>
<ide> Corresponds to `django.db.models.fields.DateTimeField`
<ide> If you want to override this behavior, you'll need to declare the `DateTimeField
<ide> class Meta:
<ide> model = Comment
<ide>
<add>**Signature:** `DateTimeField(input_formats=None, output_format=False)`
<add>
<add> - `input_formats` designates which input formats are supported. This will override the `DATETIME_INPUT_FORMATS`
<add>
<add> - `output_format` designates which output format will be used. This will override the `DATETIME_OUTPUT_FORMAT`
<add>
<ide> ## TimeField
<ide>
<ide> A time representation.
<ide>
<del>Uses `TIME_INPUT_FORMATS` to validate time.
<del>
<ide> Optionally takes `format` as parameter to replace the matching pattern.
<ide>
<ide> Corresponds to `django.db.models.fields.TimeField`
<ide>
<add>**Signature:** `TimeField(input_formats=None, output_format=False)`
<add>
<add> - `input_formats` designates which input formats are supported. This will override the `TIME_INPUT_FORMATS`
<add>
<add> - `output_format` designates which output format will be used. This will override the `TIME_OUTPUT_FORMAT`
<add>
<ide> ## IntegerField
<ide>
<ide> An integer representation.
<ide><path>docs/api-guide/settings.md
<ide> The name of a parameter in the URL conf that may be used to provide a format suf
<ide>
<ide> Default: `'format'`
<ide>
<add>## DATE_INPUT_FORMATS
<add>
<add>Default:
<add>
<add> (
<add> '%Y-%m-%d', # '1984-07-31'
<add> )
<add>
<add>## DATE_OUTPUT_FORMAT
<add>
<add>## DATETIME_INPUT_FORMATS
<add>
<add>Default:
<add>
<add> (
<add> '%Y-%m-%d', # '1984-07-31'
<add> '%Y-%m-%d %H:%M', # '1984-07-31 04:31'
<add> '%Y-%m-%d %H:%M:%S', # '1984-07-31 04:31:59'
<add> '%Y-%m-%d %H:%M:%S.%f', # '1984-07-31 04:31:59.000200'
<add> )
<add>
<add>## DATETIME_OUTPUT_FORMAT
<add>
<add>## TIME_INPUT_FORMATS
<add>
<add>Default:
<add>
<add> (
<add> '%H:%M', # '04:31'
<add> '%H:%M:%S', # '04:31:59'
<add> '%H:%M:%S.%f', # '04:31:59.000200'
<add> )
<add>
<add>## TIME_OUTPUT_FORMAT
<add>
<ide> [cite]: http://www.python.org/dev/peps/pep-0020/
<ide><path>docs/topics/release-notes.md
<ide> You can determine your currently installed version using `pip freeze`:
<ide>
<ide> * Bugfix for serializer data being uncacheable with pickle protocol 0.
<ide> * Bugfixes for model field validation edge-cases.
<del>* Support `DATE_INPUT_FORMATS` for `DateField` validation
<del>* Support `DATETIME_INPUT_FORMATS` for `DateTimeField` validation
<del>* Support `TIME_INPUT_FORMATS` for `TimeField` validation
<add>* Support for custom input and output formats for `DateField`, `DateTimeField` and `TimeField`
<ide>
<ide> ### 2.2.1
<ide>
<ide><path>rest_framework/fields.py
<ide> class DateField(WritableField):
<ide> }
<ide> empty = None
<ide>
<del> def __init__(self, *args, **kwargs):
<del> self.input_formats = kwargs.pop('input_formats', api_settings.DATE_INPUT_FORMATS)
<del> self.output_format = kwargs.pop('output_format', api_settings.DATE_OUTPUT_FORMAT)
<add> def __init__(self, input_formats=None, output_format=None, *args, **kwargs):
<add> self.input_formats = input_formats or api_settings.DATE_INPUT_FORMATS
<add> self.output_format = output_format or api_settings.DATE_OUTPUT_FORMAT
<ide> super(DateField, self).__init__(*args, **kwargs)
<ide>
<ide> def from_native(self, value):
<ide> class DateTimeField(WritableField):
<ide> }
<ide> empty = None
<ide>
<del> def __init__(self, *args, **kwargs):
<del> self.input_formats = kwargs.pop('input_formats', api_settings.DATETIME_INPUT_FORMATS)
<del> self.output_format = kwargs.pop('output_format', api_settings.DATETIME_OUTPUT_FORMAT)
<add> def __init__(self, input_formats=None, output_format=None, *args, **kwargs):
<add> self.input_formats = input_formats or api_settings.DATETIME_INPUT_FORMATS
<add> self.output_format = output_format or api_settings.DATETIME_OUTPUT_FORMAT
<ide> super(DateTimeField, self).__init__(*args, **kwargs)
<ide>
<ide> def from_native(self, value):
<ide> class TimeField(WritableField):
<ide> }
<ide> empty = None
<ide>
<del> def __init__(self, *args, **kwargs):
<del> self.input_formats = kwargs.pop('input_formats', api_settings.TIME_INPUT_FORMATS)
<del> self.output_format = kwargs.pop('output_format', api_settings.TIME_OUTPUT_FORMAT)
<add> def __init__(self, input_formats=None, output_format=None, *args, **kwargs):
<add> self.input_formats = input_formats or api_settings.TIME_INPUT_FORMATS
<add> self.output_format = output_format or api_settings.TIME_OUTPUT_FORMAT
<ide> super(TimeField, self).__init__(*args, **kwargs)
<ide>
<ide> def from_native(self, value): | 4 |
Javascript | Javascript | alphabetize eslint rules | c221355c50f6ee4eafaf7f61e8a468acd061fdda | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> },
<ide> ],
<ide> rules: {
<del> // Possible Errors
<del> // http://eslint.org/docs/rules/#possible-errors
<add> // ESLint built-in rules
<add> // http://eslint.org/docs/rules
<add> 'accessor-pairs': 'error',
<add> 'array-callback-return': 'error',
<add> 'arrow-parens': ['error', 'always'],
<add> 'arrow-spacing': ['error', { before: true, after: true }],
<add> 'block-spacing': 'error',
<add> 'brace-style': ['error', '1tbs', { allowSingleLine: true }],
<add> 'comma-dangle': ['error', 'only-multiline'],
<add> 'comma-spacing': 'error',
<add> 'comma-style': 'error',
<add> 'computed-property-spacing': 'error',
<add> 'constructor-super': 'error',
<add> 'dot-location': ['error', 'property'],
<add> 'dot-notation': 'error',
<add> 'eol-last': 'error',
<add> eqeqeq: ['error', 'smart'],
<ide> 'for-direction': 'error',
<add> 'func-call-spacing': 'error',
<add> 'func-name-matching': 'error',
<add> 'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
<add> indent: ['error', 2, {
<add> ArrayExpression: 'first',
<add> CallExpression: { arguments: 'first' },
<add> FunctionDeclaration: { parameters: 'first' },
<add> FunctionExpression: { parameters: 'first' },
<add> MemberExpression: 'off',
<add> ObjectExpression: 'first',
<add> SwitchCase: 1,
<add> }],
<add> 'key-spacing': ['error', { mode: 'strict' }],
<add> 'keyword-spacing': 'error',
<add> 'linebreak-style': ['error', 'unix'],
<add> 'max-len': ['error', {
<add> code: 80,
<add> ignorePattern: '^// Flags:',
<add> ignoreRegExpLiterals: true,
<add> ignoreUrls: true,
<add> tabWidth: 2,
<add> }],
<add> 'new-parens': 'error',
<add> 'no-class-assign': 'error',
<add> 'no-confusing-arrow': 'error',
<add> 'no-const-assign': 'error',
<ide> 'no-control-regex': 'error',
<ide> 'no-debugger': 'error',
<add> 'no-delete-var': 'error',
<ide> 'no-dupe-args': 'error',
<add> 'no-dupe-class-members': 'error',
<ide> 'no-dupe-keys': 'error',
<ide> 'no-duplicate-case': 'error',
<ide> 'no-empty-character-class': 'error',
<ide> 'no-ex-assign': 'error',
<ide> 'no-extra-boolean-cast': 'error',
<ide> 'no-extra-parens': ['error', 'functions'],
<ide> 'no-extra-semi': 'error',
<add> 'no-fallthrough': 'error',
<ide> 'no-func-assign': 'error',
<add> 'no-global-assign': 'error',
<ide> 'no-invalid-regexp': 'error',
<ide> 'no-irregular-whitespace': 'error',
<del> 'no-obj-calls': 'error',
<del> 'no-template-curly-in-string': 'error',
<del> 'no-unexpected-multiline': 'error',
<del> 'no-unreachable': 'error',
<del> 'no-unsafe-negation': 'error',
<del> 'use-isnan': 'error',
<del> 'valid-typeof': 'error',
<del>
<del> // Best Practices
<del> // http://eslint.org/docs/rules/#best-practices
<del> 'accessor-pairs': 'error',
<del> 'array-callback-return': 'error',
<del> 'dot-location': ['error', 'property'],
<del> 'dot-notation': 'error',
<del> eqeqeq: ['error', 'smart'],
<del> 'no-fallthrough': 'error',
<del> 'no-global-assign': 'error',
<add> 'no-lonely-if': 'error',
<add> 'no-mixed-requires': 'error',
<add> 'no-mixed-spaces-and-tabs': 'error',
<ide> 'no-multi-spaces': ['error', { ignoreEOLComments: true }],
<add> 'no-multiple-empty-lines': ['error', { max: 2, maxEOF: 0, maxBOF: 0 }],
<add> 'no-new-require': 'error',
<add> 'no-new-symbol': 'error',
<add> 'no-obj-calls': 'error',
<ide> 'no-octal': 'error',
<add> 'no-path-concat': 'error',
<ide> 'no-proto': 'error',
<ide> 'no-redeclare': 'error',
<add> 'no-restricted-modules': ['error', 'sys'],
<ide> 'no-restricted-properties': [
<ide> 'error',
<ide> {
<ide> module.exports = {
<ide> message: '__defineSetter__ is deprecated.',
<ide> }
<ide> ],
<del> 'no-return-await': 'error',
<del> 'no-self-assign': 'error',
<del> 'no-self-compare': 'error',
<del> 'no-throw-literal': 'error',
<del> 'no-unused-labels': 'error',
<del> 'no-useless-call': 'error',
<del> 'no-useless-concat': 'error',
<del> 'no-useless-escape': 'error',
<del> 'no-useless-return': 'error',
<del> 'no-void': 'error',
<del> 'no-with': 'error',
<del>
<del> // Strict Mode
<del> // http://eslint.org/docs/rules/#strict-mode
<del> strict: ['error', 'global'],
<del>
<del> // Variables
<del> // http://eslint.org/docs/rules/#variables
<del> 'no-delete-var': 'error',
<del> 'no-undef': 'error',
<del> 'no-undef-init': 'error',
<del> 'no-unused-vars': ['error', { args: 'none' }],
<del> 'no-use-before-define': ['error', {
<del> classes: true,
<del> functions: false,
<del> variables: false,
<del> }],
<del>
<del> // Node.js and CommonJS
<del> // http://eslint.org/docs/rules/#nodejs-and-commonjs
<del> 'no-mixed-requires': 'error',
<del> 'no-new-require': 'error',
<del> 'no-path-concat': 'error',
<del> 'no-restricted-modules': ['error', 'sys'],
<del>
<del> // Stylistic Issues
<del> // http://eslint.org/docs/rules/#stylistic-issues'
<del> 'block-spacing': 'error',
<del> 'brace-style': ['error', '1tbs', { allowSingleLine: true }],
<del> 'comma-dangle': ['error', 'only-multiline'],
<del> 'comma-spacing': 'error',
<del> 'comma-style': 'error',
<del> 'computed-property-spacing': 'error',
<del> 'eol-last': 'error',
<del> 'func-call-spacing': 'error',
<del> 'func-name-matching': 'error',
<del> 'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
<del> indent: ['error', 2, {
<del> ArrayExpression: 'first',
<del> CallExpression: { arguments: 'first' },
<del> FunctionDeclaration: { parameters: 'first' },
<del> FunctionExpression: { parameters: 'first' },
<del> MemberExpression: 'off',
<del> ObjectExpression: 'first',
<del> SwitchCase: 1,
<del> }],
<del> 'key-spacing': ['error', { mode: 'strict' }],
<del> 'keyword-spacing': 'error',
<del> 'linebreak-style': ['error', 'unix'],
<del> 'max-len': ['error', {
<del> code: 80,
<del> ignorePattern: '^// Flags:',
<del> ignoreRegExpLiterals: true,
<del> ignoreUrls: true,
<del> tabWidth: 2,
<del> }],
<del> 'new-parens': 'error',
<del> 'no-lonely-if': 'error',
<del> 'no-mixed-spaces-and-tabs': 'error',
<del> 'no-multiple-empty-lines': ['error', { max: 2, maxEOF: 0, maxBOF: 0 }],
<ide> /* eslint-disable max-len, quotes */
<ide> 'no-restricted-syntax': [
<ide> 'error',
<ide> module.exports = {
<ide> }
<ide> ],
<ide> /* eslint-enable max-len, quotes */
<add> 'no-return-await': 'error',
<add> 'no-self-assign': 'error',
<add> 'no-self-compare': 'error',
<ide> 'no-tabs': 'error',
<add> 'no-template-curly-in-string': 'error',
<add> 'no-this-before-super': 'error',
<add> 'no-throw-literal': 'error',
<ide> 'no-trailing-spaces': 'error',
<add> 'no-undef': 'error',
<add> 'no-undef-init': 'error',
<add> 'no-unexpected-multiline': 'error',
<add> 'no-unreachable': 'error',
<ide> 'no-unsafe-finally': 'error',
<add> 'no-unsafe-negation': 'error',
<add> 'no-unused-labels': 'error',
<add> 'no-unused-vars': ['error', { args: 'none' }],
<add> 'no-use-before-define': ['error', {
<add> classes: true,
<add> functions: false,
<add> variables: false,
<add> }],
<add> 'no-useless-call': 'error',
<add> 'no-useless-concat': 'error',
<add> 'no-useless-escape': 'error',
<add> 'no-useless-return': 'error',
<add> 'no-void': 'error',
<ide> 'no-whitespace-before-property': 'error',
<add> 'no-with': 'error',
<ide> 'object-curly-spacing': ['error', 'always'],
<ide> 'one-var': ['error', { initialized: 'never' }],
<ide> 'one-var-declaration-per-line': 'error',
<ide> 'operator-linebreak': ['error', 'after'],
<add> 'prefer-const': ['error', { ignoreReadBeforeAssign: true }],
<ide> quotes: ['error', 'single', { avoidEscape: true }],
<add> 'rest-spread-spacing': 'error',
<ide> semi: 'error',
<ide> 'semi-spacing': 'error',
<ide> 'space-before-blocks': ['error', 'always'],
<ide> module.exports = {
<ide> 'space-in-parens': ['error', 'never'],
<ide> 'space-infix-ops': 'error',
<ide> 'space-unary-ops': 'error',
<del> 'unicode-bom': 'error',
<del>
<del> // ECMAScript 6
<del> // http://eslint.org/docs/rules/#ecmascript-6
<del> 'arrow-parens': ['error', 'always'],
<del> 'arrow-spacing': ['error', { before: true, after: true }],
<del> 'constructor-super': 'error',
<del> 'no-class-assign': 'error',
<del> 'no-confusing-arrow': 'error',
<del> 'no-const-assign': 'error',
<del> 'no-dupe-class-members': 'error',
<del> 'no-new-symbol': 'error',
<del> 'no-this-before-super': 'error',
<del> 'prefer-const': ['error', { ignoreReadBeforeAssign: true }],
<del> 'rest-spread-spacing': 'error',
<add> strict: ['error', 'global'],
<ide> 'symbol-description': 'error',
<ide> 'template-curly-spacing': 'error',
<add> 'unicode-bom': 'error',
<add> 'use-isnan': 'error',
<add> 'valid-typeof': 'error',
<ide>
<del> // Custom rules in from eslint-plugin-node-core
<add> // Custom rules from eslint-plugin-node-core
<ide> 'node-core/no-unescaped-regexp-dot': 'error',
<ide> },
<ide> globals: { | 1 |
Python | Python | use randomized name to get the failure status | 3f59e75cdf4a95829ac60b151135e03267e63a12 | <ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py
<ide> def execute(self, context) -> Optional[str]:
<ide> self.log.info("creating pod with labels %s and launcher %s", labels, launcher)
<ide> final_state, _, result = self.create_new_pod_for_operator(labels, launcher)
<ide> if final_state != State.SUCCESS:
<del> status = self.client.read_namespaced_pod(self.name, self.namespace)
<del> raise AirflowException(f'Pod returned a failure: {status}')
<add> status = self.client.read_namespaced_pod(self.pod.metadata.name, self.namespace)
<add> raise AirflowException(f'Pod {self.pod.metadata.name} returned a failure: {status}')
<ide> return result
<ide> except AirflowException as ex:
<ide> raise AirflowException(f'Pod Launching failed: {ex}')
<ide><path>tests/providers/cncf/kubernetes/operators/test_kubernetes_pod.py
<ide> def test_randomize_pod_name(self, mock_client, monitor_mock, start_mock):
<ide>
<ide> assert start_mock.call_args[0][0].metadata.name.startswith(name_base)
<ide> assert start_mock.call_args[0][0].metadata.name != name_base
<add>
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<add> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<add> def test_describes_pod_on_failure(self, mock_client, monitor_mock, start_mock):
<add> from airflow.utils.state import State
<add>
<add> name_base = 'test'
<add>
<add> k = KubernetesPodOperator(
<add> namespace='default',
<add> image="ubuntu:16.04",
<add> cmds=["bash", "-cx"],
<add> arguments=["echo 10"],
<add> labels={"foo": "bar"},
<add> name=name_base,
<add> task_id="task",
<add> in_cluster=False,
<add> do_xcom_push=False,
<add> cluster_context='default',
<add> )
<add> monitor_mock.return_value = (State.FAILED, None)
<add> failed_pod_status = 'read_pod_namespaced_result'
<add> read_namespaced_pod_mock = mock_client.return_value.read_namespaced_pod
<add> read_namespaced_pod_mock.return_value = failed_pod_status
<add>
<add> with self.assertRaises(AirflowException) as cm:
<add> context = self.create_context(k)
<add> k.execute(context=context)
<add>
<add> self.assertEqual(
<add> str(cm.exception),
<add> f"Pod Launching failed: Pod {k.pod.metadata.name} returned a failure: {failed_pod_status}",
<add> )
<add> assert mock_client.return_value.read_namespaced_pod.called
<add> self.assertEqual(read_namespaced_pod_mock.call_args[0][0], k.pod.metadata.name)
<add>
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.start_pod")
<add> @mock.patch("airflow.kubernetes.pod_launcher.PodLauncher.monitor_pod")
<add> @mock.patch("airflow.kubernetes.kube_client.get_kube_client")
<add> def test_no_need_to_describe_pod_on_success(self, mock_client, monitor_mock, start_mock):
<add> from airflow.utils.state import State
<add>
<add> name_base = 'test'
<add>
<add> k = KubernetesPodOperator(
<add> namespace='default',
<add> image="ubuntu:16.04",
<add> cmds=["bash", "-cx"],
<add> arguments=["echo 10"],
<add> labels={"foo": "bar"},
<add> name=name_base,
<add> task_id="task",
<add> in_cluster=False,
<add> do_xcom_push=False,
<add> cluster_context='default',
<add> )
<add> monitor_mock.return_value = (State.SUCCESS, None)
<add>
<add> context = self.create_context(k)
<add> k.execute(context=context)
<add>
<add> assert not mock_client.return_value.read_namespaced_pod.called | 2 |
Go | Go | allow hyphens in namespaces | 6c126d443b3ee3bbb6d0a437a1b5c51cbf9e47f2 | <ide><path>registry/registry.go
<ide> var (
<ide> ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")")
<ide> ErrDoesNotExist = errors.New("Image does not exist")
<ide> errLoginRequired = errors.New("Authentication is required.")
<del> validNamespace = regexp.MustCompile(`^([a-z0-9_]{4,30})$`)
<add> validNamespaceChars = regexp.MustCompile(`^([a-z0-9-_]*)$`)
<ide> validRepo = regexp.MustCompile(`^([a-z0-9-_.]+)$`)
<ide> )
<ide>
<ide> func validateRepositoryName(repositoryName string) error {
<ide> namespace = nameParts[0]
<ide> name = nameParts[1]
<ide> }
<del> if !validNamespace.MatchString(namespace) {
<del> return fmt.Errorf("Invalid namespace name (%s), only [a-z0-9_] are allowed, size between 4 and 30", namespace)
<add> if !validNamespaceChars.MatchString(namespace) {
<add> return fmt.Errorf("Invalid namespace name (%s). Only [a-z0-9-_] are allowed.", namespace)
<add> }
<add> if len(namespace) < 4 || len(namespace) > 30 {
<add> return fmt.Errorf("Invalid namespace name (%s). Cannot be fewer than 4 or more than 30 characters.", namespace)
<add> }
<add> if strings.HasPrefix(namespace, "-") || strings.HasSuffix(namespace, "-") {
<add> return fmt.Errorf("Invalid namespace name (%s). Cannot begin or end with a hyphen.", namespace)
<add> }
<add> if strings.Contains(namespace, "--") {
<add> return fmt.Errorf("Invalid namespace name (%s). Cannot contain consecutive hyphens.", namespace)
<ide> }
<ide> if !validRepo.MatchString(name) {
<ide> return fmt.Errorf("Invalid repository name (%s), only [a-z0-9-_.] are allowed", name)
<ide><path>registry/registry_test.go
<ide> func TestSearchRepositories(t *testing.T) {
<ide> }
<ide>
<ide> func TestValidRepositoryName(t *testing.T) {
<del> if err := validateRepositoryName("docker/docker"); err != nil {
<del> t.Fatal(err)
<del> }
<del> // Support 64-byte non-hexadecimal names (hexadecimal names are forbidden)
<del> if err := validateRepositoryName("thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev"); err != nil {
<del> t.Fatal(err)
<add> validRepositoryNames := []string{
<add> // Sanity check.
<add> "docker/docker",
<add>
<add> // Allow 64-character non-hexadecimal names (hexadecimal names are forbidden).
<add> "thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev",
<add>
<add> // Allow embedded hyphens.
<add> "docker-rules/docker",
<add>
<add> // Allow underscores everywhere (as opposed to hyphens).
<add> "____/____",
<ide> }
<del> if err := validateRepositoryName("docker/Docker"); err == nil {
<del> t.Log("Repository name should be invalid")
<del> t.Fail()
<add> for _, repositoryName := range validRepositoryNames {
<add> if err := validateRepositoryName(repositoryName); err != nil {
<add> t.Errorf("Repository name should be valid: %v. Error: %v", repositoryName, err)
<add> }
<ide> }
<del> if err := validateRepositoryName("docker///docker"); err == nil {
<del> t.Log("Repository name should be invalid")
<del> t.Fail()
<add>
<add> invalidRepositoryNames := []string{
<add> // Disallow capital letters.
<add> "docker/Docker",
<add>
<add> // Only allow one slash.
<add> "docker///docker",
<add>
<add> // Disallow 64-character hexadecimal.
<add> "1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a",
<add>
<add> // Disallow leading and trailing hyphens in namespace.
<add> "-docker/docker",
<add> "docker-/docker",
<add> "-docker-/docker",
<add>
<add> // Disallow consecutive hyphens.
<add> "dock--er/docker",
<add>
<add> // Namespace too short.
<add> "doc/docker",
<add>
<add> // No repository.
<add> "docker/",
<ide> }
<del> if err := validateRepositoryName("1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a"); err == nil {
<del> t.Log("Repository name should be invalid, 64-byte hexadecimal names forbidden")
<del> t.Fail()
<add> for _, repositoryName := range invalidRepositoryNames {
<add> if err := validateRepositoryName(repositoryName); err == nil {
<add> t.Errorf("Repository name should be invalid: %v", repositoryName)
<add> }
<ide> }
<ide> }
<ide> | 2 |
Text | Text | fix a typo | 2767f01be05e3714b250f8c2743b7f5e1b0833ac | <ide><path>guides/source/working_with_javascript.md
<ide> attributes, and attaches appropriate handlers.
<ide> ### form_for
<ide>
<ide> [`form_for`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for)
<del>is a helper that assists with writing `<form>`s. `form_for` takes a `:remote`
<add>is a helper that assists with writing forms. `form_for` takes a `:remote`
<ide> option. It works like this:
<ide>
<ide> ``` | 1 |
PHP | PHP | add explict ordering | 593e1819e2f98bb8116ef5d5490e8369109812cb | <ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testSelectGroup()
<ide> ->from('articles')
<ide> ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
<ide> ->group('author_id')
<add> ->order(['total' => 'desc'])
<ide> ->execute();
<ide> $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
<ide> $this->assertEquals($expected, $result->fetchAll('assoc'));
<ide> public function testSelectOrHaving()
<ide> ->from('articles')
<ide> ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
<ide> ->group('author_id')
<add> ->order(['total' => 'desc'])
<ide> ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
<ide> ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
<ide> ->execute();
<ide> public function testSqlCaseStatement()
<ide> 'integer'
<ide> );
<ide>
<del> //Postgres requires the case statement to be cast to a integer
<add> // Postgres requires the case statement to be cast to a integer
<ide> if ($this->connection->getDriver() instanceof \Cake\Database\Driver\Postgres) {
<ide> $publishedCase = $query->func()
<ide> ->cast([$publishedCase, 'integer' => 'literal']) | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.