content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
update the uri of devtools tutorial
8ac3fada4e282be0ade4bc4ba5065ffcea2165a3
<ide><path>docs/creating-a-theme.md <ide> _styleguide_, or use the shortcut `cmd-ctrl-shift-g`. <ide> [atom]: https://atom.io/ <ide> [package.json]: ./creating-a-package.html#package-json <ide> [less-tutorial]: https://speakerdeck.com/danmatthews/less-css <del>[devtools-tutorial]: https://developers.google.com/chrome-developer-tools/docs/elements <add>[devtools-tutorial]: https://developer.chrome.com/devtools/docs/dom-and-styles <ide> [ui-variables]: ./theme-variables.html <ide> [livereload]: https://github.com/atom/dev-live-reload <ide> [styleguide]: https://github.com/atom/styleguide
1
PHP
PHP
fix bug in database connection
b0b0fb6f762f360da2e89c0267bc9ee86fa65142
<ide><path>src/Illuminate/Database/Connection.php <ide> public function getName() <ide> */ <ide> public function getConfig($option) <ide> { <del> return array_get($config, $option); <add> return array_get($this->config, $option); <ide> } <ide> <ide> /**
1
Python
Python
fix issue with wrapper logic
37217e85b80c389208cd3396c2cdc4b89bd46bcf
<ide><path>scripts/flaskext_migrate.py <ide> def fix(ast): <ide> <ide> if __name__ == "__main__": <ide> input_file = sys.argv[1] <del> fix(input_file) <add> ast = read_source(input_file) <add> ast = fix_imports(ast) <add> write_source(ast, input_file)
1
Go
Go
remove unnecessary else branch in getpoolname()
553b50bd37ade60bfafe5d5cc10f984251741f44
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) oldMetadataFile() string { <ide> func (devices *DeviceSet) getPoolName() string { <ide> if devices.thinPoolDevice == "" { <ide> return devices.devicePrefix + "-pool" <del> } else { <del> return devices.thinPoolDevice <ide> } <add> return devices.thinPoolDevice <ide> } <ide> <ide> func (devices *DeviceSet) getPoolDevName() string {
1
Python
Python
fix header for assert_array_almost_equal
0259a4972a81295353407dfaf4ba5adcb34a42db
<ide><path>numpy/testing/utils.py <ide> def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True): <ide> from numpy.core import ndarray <ide> if isinstance(actual, ndarray) or isinstance(desired, ndarray): <ide> return assert_array_almost_equal(actual, desired, decimal, err_msg) <del> msg = build_err_msg([actual, desired], err_msg, verbose=verbose) <del> <add> msg = build_err_msg([actual, desired], err_msg, verbose=verbose, <add> header='Arrays are not almost equal') <ide> try: <ide> # If one of desired/actual is not finite, handle it specially here: <ide> # check that both are nan if any is a nan, and test for equality
1
Python
Python
assert fromfile ending earlier in pyx processing
4c877be5fc4075595e15b4a451f76e128376de00
<ide><path>tools/cythonize.py <ide> def process_tempita_pyx(fromfile, tofile): <ide> except ImportError: <ide> raise Exception('Building %s requires Tempita: ' <ide> 'pip install --user Tempita' % VENDOR) <add> assert fromfile.endswith('.pyx.in') <ide> with open(fromfile, "r") as f: <ide> tmpl = f.read() <ide> pyxcontent = tempita.sub(tmpl) <del> assert fromfile.endswith('.pyx.in') <ide> pyxfile = fromfile[:-len('.pyx.in')] + '.pyx' <ide> with open(pyxfile, "w") as f: <ide> f.write(pyxcontent)
1
Javascript
Javascript
fix "function statements" in strict mode builds
88ba7ebcc77e5ff0a38954d298b6478960d0702a
<ide><path>Libraries/polyfills/console.js <ide> INSPECTOR_LEVELS[LOG_LEVELS.error] = 'error'; <ide> // strip method printing to originalConsole. <ide> const INSPECTOR_FRAMES_TO_SKIP = __DEV__ ? 2 : 1; <ide> <del>if (global.nativeLoggingHook) { <del> function getNativeLogFunction(level) { <del> return function() { <del> let str; <del> if (arguments.length === 1 && typeof arguments[0] === 'string') { <del> str = arguments[0]; <del> } else { <del> str = Array.prototype.map <del> .call(arguments, function(arg) { <del> return inspect(arg, {depth: 10}); <del> }) <del> .join(', '); <del> } <del> <del> let logLevel = level; <del> if (str.slice(0, 9) === 'Warning: ' && logLevel >= LOG_LEVELS.error) { <del> // React warnings use console.error so that a stack trace is shown, <del> // but we don't (currently) want these to show a redbox <del> // (Note: Logic duplicated in ExceptionsManager.js.) <del> logLevel = LOG_LEVELS.warn; <del> } <del> if (global.__inspectorLog) { <del> global.__inspectorLog( <del> INSPECTOR_LEVELS[logLevel], <del> str, <del> [].slice.call(arguments), <del> INSPECTOR_FRAMES_TO_SKIP, <del> ); <del> } <del> global.nativeLoggingHook(str, logLevel); <del> }; <del> } <del> <del> function repeat(element, n) { <del> return Array.apply(null, Array(n)).map(function() { <del> return element; <del> }); <del> } <add>function getNativeLogFunction(level) { <add> return function() { <add> let str; <add> if (arguments.length === 1 && typeof arguments[0] === 'string') { <add> str = arguments[0]; <add> } else { <add> str = Array.prototype.map <add> .call(arguments, function(arg) { <add> return inspect(arg, {depth: 10}); <add> }) <add> .join(', '); <add> } <ide> <del> function consoleTablePolyfill(rows) { <del> // convert object -> array <del> if (!Array.isArray(rows)) { <del> var data = rows; <del> rows = []; <del> for (var key in data) { <del> if (data.hasOwnProperty(key)) { <del> var row = data[key]; <del> row[OBJECT_COLUMN_NAME] = key; <del> rows.push(row); <del> } <del> } <add> let logLevel = level; <add> if (str.slice(0, 9) === 'Warning: ' && logLevel >= LOG_LEVELS.error) { <add> // React warnings use console.error so that a stack trace is shown, <add> // but we don't (currently) want these to show a redbox <add> // (Note: Logic duplicated in ExceptionsManager.js.) <add> logLevel = LOG_LEVELS.warn; <ide> } <del> if (rows.length === 0) { <del> global.nativeLoggingHook('', LOG_LEVELS.info); <del> return; <add> if (global.__inspectorLog) { <add> global.__inspectorLog( <add> INSPECTOR_LEVELS[logLevel], <add> str, <add> [].slice.call(arguments), <add> INSPECTOR_FRAMES_TO_SKIP, <add> ); <ide> } <add> global.nativeLoggingHook(str, logLevel); <add> }; <add>} <ide> <del> var columns = Object.keys(rows[0]).sort(); <del> var stringRows = []; <del> var columnWidths = []; <del> <del> // Convert each cell to a string. Also <del> // figure out max cell width for each column <del> columns.forEach(function(k, i) { <del> columnWidths[i] = k.length; <del> for (var j = 0; j < rows.length; j++) { <del> var cellStr = (rows[j][k] || '?').toString(); <del> stringRows[j] = stringRows[j] || []; <del> stringRows[j][i] = cellStr; <del> columnWidths[i] = Math.max(columnWidths[i], cellStr.length); <del> } <del> }); <add>function repeat(element, n) { <add> return Array.apply(null, Array(n)).map(function() { <add> return element; <add> }); <add>} <ide> <del> // Join all elements in the row into a single string with | separators <del> // (appends extra spaces to each cell to make separators | aligned) <del> function joinRow(row, space) { <del> var cells = row.map(function(cell, i) { <del> var extraSpaces = repeat(' ', columnWidths[i] - cell.length).join(''); <del> return cell + extraSpaces; <del> }); <del> space = space || ' '; <del> return cells.join(space + '|' + space); <add>function consoleTablePolyfill(rows) { <add> // convert object -> array <add> if (!Array.isArray(rows)) { <add> var data = rows; <add> rows = []; <add> for (var key in data) { <add> if (data.hasOwnProperty(key)) { <add> var row = data[key]; <add> row[OBJECT_COLUMN_NAME] = key; <add> rows.push(row); <add> } <ide> } <add> } <add> if (rows.length === 0) { <add> global.nativeLoggingHook('', LOG_LEVELS.info); <add> return; <add> } <ide> <del> var separators = columnWidths.map(function(columnWidth) { <del> return repeat('-', columnWidth).join(''); <add> var columns = Object.keys(rows[0]).sort(); <add> var stringRows = []; <add> var columnWidths = []; <add> <add> // Convert each cell to a string. Also <add> // figure out max cell width for each column <add> columns.forEach(function(k, i) { <add> columnWidths[i] = k.length; <add> for (var j = 0; j < rows.length; j++) { <add> var cellStr = (rows[j][k] || '?').toString(); <add> stringRows[j] = stringRows[j] || []; <add> stringRows[j][i] = cellStr; <add> columnWidths[i] = Math.max(columnWidths[i], cellStr.length); <add> } <add> }); <add> <add> // Join all elements in the row into a single string with | separators <add> // (appends extra spaces to each cell to make separators | aligned) <add> function joinRow(row, space) { <add> var cells = row.map(function(cell, i) { <add> var extraSpaces = repeat(' ', columnWidths[i] - cell.length).join(''); <add> return cell + extraSpaces; <ide> }); <del> var separatorRow = joinRow(separators, '-'); <del> var header = joinRow(columns); <del> var table = [header, separatorRow]; <add> space = space || ' '; <add> return cells.join(space + '|' + space); <add> } <ide> <del> for (var i = 0; i < rows.length; i++) { <del> table.push(joinRow(stringRows[i])); <del> } <add> var separators = columnWidths.map(function(columnWidth) { <add> return repeat('-', columnWidth).join(''); <add> }); <add> var separatorRow = joinRow(separators, '-'); <add> var header = joinRow(columns); <add> var table = [header, separatorRow]; <ide> <del> // Notice extra empty line at the beginning. <del> // Native logging hook adds "RCTLog >" at the front of every <del> // logged string, which would shift the header and screw up <del> // the table <del> global.nativeLoggingHook('\n' + table.join('\n'), LOG_LEVELS.info); <add> for (var i = 0; i < rows.length; i++) { <add> table.push(joinRow(stringRows[i])); <ide> } <ide> <add> // Notice extra empty line at the beginning. <add> // Native logging hook adds "RCTLog >" at the front of every <add> // logged string, which would shift the header and screw up <add> // the table <add> global.nativeLoggingHook('\n' + table.join('\n'), LOG_LEVELS.info); <add>} <add> <add>if (global.nativeLoggingHook) { <ide> const originalConsole = global.console; <ide> global.console = { <ide> error: getNativeLogFunction(LOG_LEVELS.error),
1
Text
Text
fix minor typos in readme
0c47e4092b61793a83fed7ac9525e3b602935f21
<ide><path>README.md <ide> They are based on the official release schedule of Python and Kubernetes, nicely <ide> [Python Developer's Guide](https://devguide.python.org/#status-of-python-branches) and <ide> [Kubernetes version skew policy](https://kubernetes.io/docs/setup/release/version-skew-policy/). <ide> <del>1. We drop support for Python and Kubernetes versions when they reach EOL. Except for kubernetes, a <del> version stay supported by Airflow if two major cloud provider still provide support for it. We drop <add>1. We drop support for Python and Kubernetes versions when they reach EOL. Except for Kubernetes, a <add> version stays supported by Airflow if two major cloud providers still provide support for it. We drop <ide> support for those EOL versions in main right after EOL date, and it is effectively removed when we release <ide> the first new MINOR (Or MAJOR if there is no new MINOR version) of Airflow. For example, for Python 3.7 it <ide> means that we will drop support in main right after 27.06.2023, and the first MAJOR or MINOR version of
1
Javascript
Javascript
remove setmaxlisteners in test-crypto-random
f07f4207522075fb5b3062afac24a19ecbb83825
<ide><path>test/parallel/test-crypto-random.js <ide> const { inspect } = require('util'); <ide> const kMaxUint32 = Math.pow(2, 32) - 1; <ide> const kMaxPossibleLength = Math.min(kMaxLength, kMaxUint32); <ide> <del>// Bump, we register a lot of exit listeners <del>process.setMaxListeners(256); <del> <ide> common.expectWarning('DeprecationWarning', <ide> 'crypto.pseudoRandomBytes is deprecated.', 'DEP0115'); <ide>
1
Ruby
Ruby
add failing test for wrong database connection
a58543dbb1ea52f3cb0c98d054ffd7bc7a373765
<ide><path>railties/test/application/test_runner_test.rb <ide> def test_rake_passes_TESTOPTS_to_minitest <ide> end <ide> <ide> def test_running_with_ruby_gets_test_env_by_default <add> # Subshells inherit `ENV`, so we need to ensure `RAILS_ENV` is set to <add> # nil before we run the tests in the test app. <add> re, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], nil <add> <ide> file = create_test_for_env("test") <ide> results = Dir.chdir(app_path) { <ide> `ruby -Ilib:test #{file}`.each_line.map { |line| JSON.parse line } <ide> } <ide> assert_equal 1, results.length <ide> failures = results.first["failures"] <ide> flunk(failures.first) unless failures.empty? <add> <add> ensure <add> ENV["RAILS_ENV"] = re <ide> end <ide> <ide> def test_running_with_ruby_can_set_env_via_cmdline <add> # Subshells inherit `ENV`, so we need to ensure `RAILS_ENV` is set to <add> # nil before we run the tests in the test app. <add> re, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], nil <add> <ide> file = create_test_for_env("development") <ide> results = Dir.chdir(app_path) { <ide> `ruby -Ilib:test #{file} -e development`.each_line.map { |line| JSON.parse line } <ide> } <ide> assert_equal 1, results.length <ide> failures = results.first["failures"] <ide> flunk(failures.first) unless failures.empty? <add> <add> ensure <add> ENV["RAILS_ENV"] = re <ide> end <ide> <ide> def test_rake_passes_multiple_TESTOPTS_to_minitest <ide> def Minitest.plugin_json_reporter_init(opts) <ide> <ide> class EnvironmentTest < ActiveSupport::TestCase <ide> def test_environment <add> test_db = ActiveRecord::Base.configurations[#{env.dump}]["database"] <add> db_file = ActiveRecord::Base.connection_config[:database] <add> assert_match(test_db, db_file) <ide> assert_equal #{env.dump}, ENV["RAILS_ENV"] <ide> end <ide> end
1
Javascript
Javascript
fetch csrf cookie and set headers lazily
ffcf8294f1fc6f96b540ad38f7b4a5a8b350de9c
<ide><path>client/src/redux/cookieValues.js <ide> import cookies from 'browser-cookies'; <ide> <del>export const _csrf = typeof window !== 'undefined' && cookies.get('_csrf'); <ide> export const jwt = <ide> typeof window !== 'undefined' && cookies.get('jwt_access_token'); <ide><path>client/src/utils/ajax.js <ide> import { apiLocation } from '../../config/env.json'; <del>import { _csrf } from '../redux/cookieValues'; <ide> import axios from 'axios'; <ide> import Tokens from 'csrf'; <add>import cookies from 'browser-cookies'; <ide> <ide> const base = apiLocation; <ide> const tokens = new Tokens(); <ide> axios.defaults.withCredentials = true; <ide> <ide> // _csrf is passed to the client as a cookie. Tokens are sent back to the server <ide> // via headers: <del>if (_csrf) { <add>function setCSRFTokens() { <add> const _csrf = typeof window !== 'undefined' && cookies.get('_csrf'); <add> if (!_csrf) return; <ide> axios.defaults.headers.post['CSRF-Token'] = tokens.create(_csrf); <ide> axios.defaults.headers.put['CSRF-Token'] = tokens.create(_csrf); <ide> } <ide> function get(path) { <ide> } <ide> <ide> export function post(path, body) { <add> setCSRFTokens(); <ide> return axios.post(`${base}${path}`, body); <ide> } <ide> <ide> function put(path, body) { <add> setCSRFTokens(); <ide> return axios.put(`${base}${path}`, body); <ide> } <ide>
2
Mixed
Go
update flag usages and docs for max restart count
5ad4879d2a5ee5af95c8b8ab701a621c8b49609a
<ide><path>docs/sources/reference/commandline/cli.md <ide> removed before the image is removed. <ide> format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort <ide> (use 'docker port' to see the actual mapping) <ide> --privileged=false Give extended privileges to this container <del> --restart="" Restart policy to apply when a container exits (no, on-failure, always) <add> --restart="" Restart policy to apply when a container exits (no, on-failure[:max-retry], always) <ide> --rm=false Automatically remove the container when it exits (incompatible with -d) <ide> --sig-proxy=true Proxy received signals to the process (even in non-TTY mode). SIGCHLD, SIGSTOP, and SIGKILL are not proxied. <ide> -t, --tty=false Allocate a pseudo-TTY <ide> the container exits, Docker will restart it. <ide> This will run the `redis` container with a restart policy of ** on-failure ** and a <ide> maximum restart count of 10. If the `redis` container exits with a non-zero exit <ide> status more than 10 times in a row Docker will abort trying to restart the container. <add>Providing a maximum restart limit is only valid for the ** on-failure ** policy. <ide> <ide> ## save <ide> <ide><path>runconfig/parse.go <ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf <ide> flCpuShares = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)") <ide> flCpuset = cmd.String([]string{"-cpuset"}, "", "CPUs in which to allow execution (0-3, 0,1)") <ide> flNetMode = cmd.String([]string{"-net"}, "bridge", "Set the Network mode for the container\n'bridge': creates a new network stack for the container on the docker bridge\n'none': no networking for this container\n'container:<name|id>': reuses another container network stack\n'host': use the host network stack inside the container. Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.") <del> flRestartPolicy = cmd.String([]string{"-restart"}, "", "Restart policy to apply when a container exits (no, on-failure, always)") <add> flRestartPolicy = cmd.String([]string{"-restart"}, "", "Restart policy to apply when a container exits (no, on-failure[:max-retry], always)") <ide> // For documentation purpose <ide> _ = cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxy received signals to the process (even in non-TTY mode). SIGCHLD, SIGSTOP, and SIGKILL are not proxied.") <ide> _ = cmd.String([]string{"#name", "-name"}, "", "Assign a name to the container")
2
Text
Text
add v3.5.0-beta.4 to changelog
7c45f2066931bb779ced201797b5a8ff7eef0322
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.6.0-beta.1 (Unreleased) <add>### v3.5.0-beta.4 (October 1, 2018) <ide> <del>- [#17003](https://github.com/emberjs/ember.js/pull/17003) / [#17013](https://github.com/emberjs/ember.js/pull/17013) [BUGFIX] Fix rendering of empty content with `{{{...}}}` and `htmlSafe` <add>- [#17003](https://github.com/emberjs/ember.js/pull/17003) / [#17013](https://github.com/emberjs/ember.js/pull/17013) [BUGFIX] Fix rendering of empty content with `{{{...}}}` or `{{...}}` with `htmlSafe('')` <ide> <ide> ### v3.5.0-beta.3 (September 24, 2018) <ide>
1
Javascript
Javascript
upgrade requireensureplugin to es6
a589fa6d2b354b825a035171f6b9e8c1f3707635
<ide><path>lib/dependencies/RequireEnsurePlugin.js <ide> Author Tobias Koppers @sokra <ide> */ <ide> "use strict"; <del>var RequireEnsureItemDependency = require("./RequireEnsureItemDependency"); <del>var RequireEnsureDependency = require("./RequireEnsureDependency"); <del>var ConstDependency = require("./ConstDependency"); <ide> <del>var NullFactory = require("../NullFactory"); <add>const RequireEnsureItemDependency = require("./RequireEnsureItemDependency"); <add>const RequireEnsureDependency = require("./RequireEnsureDependency"); <add>const ConstDependency = require("./ConstDependency"); <ide> <del>var RequireEnsureDependenciesBlockParserPlugin = require("./RequireEnsureDependenciesBlockParserPlugin"); <add>const NullFactory = require("../NullFactory"); <add> <add>const RequireEnsureDependenciesBlockParserPlugin = require("./RequireEnsureDependenciesBlockParserPlugin"); <ide> <ide> const ParserHelpers = require("../ParserHelpers"); <ide> <del>function RequireEnsurePlugin() {} <del>module.exports = RequireEnsurePlugin; <add>class RequireEnsurePlugin { <ide> <del>RequireEnsurePlugin.prototype.apply = function(compiler) { <del> compiler.plugin("compilation", function(compilation, params) { <del> var normalModuleFactory = params.normalModuleFactory; <add> apply(compiler) { <add> compiler.plugin("compilation", (compilation, params) => { <add> const normalModuleFactory = params.normalModuleFactory; <ide> <del> compilation.dependencyFactories.set(RequireEnsureItemDependency, normalModuleFactory); <del> compilation.dependencyTemplates.set(RequireEnsureItemDependency, new RequireEnsureItemDependency.Template()); <add> compilation.dependencyFactories.set(RequireEnsureItemDependency, normalModuleFactory); <add> compilation.dependencyTemplates.set(RequireEnsureItemDependency, new RequireEnsureItemDependency.Template()); <ide> <del> compilation.dependencyFactories.set(RequireEnsureDependency, new NullFactory()); <del> compilation.dependencyTemplates.set(RequireEnsureDependency, new RequireEnsureDependency.Template()); <add> compilation.dependencyFactories.set(RequireEnsureDependency, new NullFactory()); <add> compilation.dependencyTemplates.set(RequireEnsureDependency, new RequireEnsureDependency.Template()); <ide> <del> params.normalModuleFactory.plugin("parser", function(parser, parserOptions) { <add> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { <ide> <del> if(typeof parserOptions.requireEnsure !== "undefined" && !parserOptions.requireEnsure) <del> return; <add> if(typeof parserOptions.requireEnsure !== "undefined" && !parserOptions.requireEnsure) <add> return; <ide> <del> parser.apply(new RequireEnsureDependenciesBlockParserPlugin()); <del> parser.plugin("evaluate typeof require.ensure", ParserHelpers.evaluateToString("function")); <del> parser.plugin("typeof require.ensure", function(expr) { <del> var dep = new ConstDependency("'function'", expr.range); <del> dep.loc = expr.loc; <del> this.state.current.addDependency(dep); <del> return true; <add> parser.apply(new RequireEnsureDependenciesBlockParserPlugin()); <add> parser.plugin("evaluate typeof require.ensure", ParserHelpers.evaluateToString("function")); <add> parser.plugin("typeof require.ensure", (expr) => { <add> const dep = new ConstDependency("'function'", expr.range); <add> dep.loc = expr.loc; <add> parser.state.current.addDependency(dep); <add> return true; <add> }); <ide> }); <ide> }); <del> }); <del>}; <add> } <add>} <add>module.exports = RequireEnsurePlugin;
1
PHP
PHP
update toresponse return type
8fd18a33e56e4d16dd176a0342109844606fdbcd
<ide><path>src/Illuminate/Contracts/Support/Responsable.php <ide> interface Responsable <ide> * Create an HTTP response that represents the object. <ide> * <ide> * @param \Illuminate\Http\Request $request <del> * @return \Illuminate\Http\Response <add> * @return \Symfony\Component\HttpFoundation\Response <ide> */ <ide> public function toResponse($request); <ide> }
1
Python
Python
fix tests for py2/3 compat
9923a6ce9013693ea1723e7895b3cab638d719fd
<ide><path>tests/test_serializer_bulk_update.py <ide> """ <ide> from __future__ import unicode_literals <ide> from django.test import TestCase <add>from django.utils import six <ide> from rest_framework import serializers <ide> <ide> <ide> def test_invalid_list_datatype(self): <ide> serializer = self.BookSerializer(data=data, many=True) <ide> self.assertEqual(serializer.is_valid(), False) <ide> <add> text_type_string = six.text_type.__name__ <add> message = 'Invalid data. Expected a dictionary, but got %s.' % text_type_string <ide> expected_errors = [ <del> {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']}, <del> {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']}, <del> {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']} <add> {'non_field_errors': [message]}, <add> {'non_field_errors': [message]}, <add> {'non_field_errors': [message]} <ide> ] <ide> <ide> self.assertEqual(serializer.errors, expected_errors)
1
Ruby
Ruby
use full path to sqlite database in tests
dd93a5f4598b420710fb4a9a2628abfd98799fb6
<ide><path>railties/test/application/initializers/frameworks_test.rb <ide> def from_bar_helper <ide> require "#{app_path}/config/environment" <ide> orig_database_url = ENV.delete("DATABASE_URL") <ide> orig_rails_env, Rails.env = Rails.env, 'development' <del> database_url_db_name = "db/database_url_db.sqlite3" <add> database_url_db_name = File.join(app_path, "db/database_url_db.sqlite3") <ide> ENV["DATABASE_URL"] = "sqlite3://:@localhost/#{database_url_db_name}" <ide> ActiveRecord::Base.establish_connection <ide> assert ActiveRecord::Base.connection <ide><path>railties/test/application/rake/dbs_test.rb <ide> def teardown <ide> end <ide> <ide> def database_url_db_name <del> "db/database_url_db.sqlite3" <add> File.join(app_path, "db/database_url_db.sqlite3") <ide> end <ide> <ide> def set_database_url <del> ENV['DATABASE_URL'] = "sqlite3://:@localhost/#{database_url_db_name}" <add> ENV['DATABASE_URL'] = File.join("sqlite3://:@localhost", database_url_db_name) <ide> # ensure it's using the DATABASE_URL <ide> FileUtils.rm_rf("#{app_path}/config/database.yml") <ide> end <ide> def db_migrate_and_status <ide> `rails generate model book title:string; <ide> bundle exec rake db:migrate` <ide> output = `bundle exec rake db:migrate:status` <del> assert_match(/database:\s+\S+#{expected[:database]}/, output) <add> assert_match(%r{database:\s+\S*#{Regexp.escape(expected[:database])}}, output) <ide> assert_match(/up\s+\d{14}\s+Create books/, output) <ide> end <ide> end
2
Python
Python
change psoftplus defaults to be nearer relu
2ada7d16cb90e6b8239a8d863c3294f03f372bbc
<ide><path>keras/layers/advanced_activations.py <ide> from ..layers.core import Layer <del>from ..utils.theano_utils import shared_zeros, shared_ones <add>from ..utils.theano_utils import shared_zeros, shared_ones, shared_scalars <ide> import theano.tensor as T <ide> <ide> class LeakyReLU(Layer): <ide> class Psoftplus(Layer): <ide> ''' <ide> def __init__(self, input_shape): <ide> super(Psoftplus,self).__init__() <del> self.alphas = shared_ones(input_shape) <del> self.betas = shared_ones(input_shape) <add> self.alphas = shared_scalars(input_shape, 0.2) <add> self.betas = shared_scalars(input_shape, 5.0) <ide> self.params = [self.alphas, self.betas] <ide> self.input_shape = input_shape <ide> <ide> def get_output(self, train): <ide> <ide> def get_config(self): <ide> return {"name":self.__class__.__name__, <del> "input_shape":self.input_shape} <ide>\ No newline at end of file <add> "input_shape":self.input_shape} <ide><path>keras/utils/theano_utils.py <ide> def shared_scalar(val=0., dtype=theano.config.floatX, name=None): <ide> def shared_ones(shape, dtype=theano.config.floatX, name=None): <ide> return sharedX(np.ones(shape), dtype=dtype, name=name) <ide> <add>def shared_scalars(shape, val, dtype=theano.config.floatX, name=None): <add> return sharedX(np.ones(shape)*val, dtype=dtype, name=name) <add> <ide> def alloc_zeros_matrix(*dims): <ide> return T.alloc(np.cast[theano.config.floatX](0.), *dims) <ide>
2
Python
Python
fix inputexample docstring
ea8eba35e2984882c3cd522ff669eb8060941a94
<ide><path>src/transformers/data/processors/utils.py <ide> class InputExample(object): <ide> Args: <ide> guid: Unique id for the example. <ide> text_a: string. The untokenized text of the first sequence. For single <del> sequence tasks, only this sequence must be specified. <add> sequence tasks, only this sequence must be specified. <ide> text_b: (Optional) string. The untokenized text of the second sequence. <del> Only must be specified for sequence pair tasks. <add> Only must be specified for sequence pair tasks. <ide> label: (Optional) string. The label of the example. This should be <del> specified for train and dev examples, but not for test examples. <add> specified for train and dev examples, but not for test examples. <ide> """ <ide> <ide> def __init__(self, guid, text_a, text_b=None, label=None):
1
Javascript
Javascript
use template literal for string concat
9cbfd5b580acfe4a5b0406bbf6221052afa4a01a
<ide><path>test/parallel/test-repl-persistent-history.js <ide> const replDisabled = '\nPersistent history support disabled. Set the ' + <ide> 'user-writable path to enable.\n'; <ide> const convertMsg = '\nConverted old JSON repl history to line-separated ' + <ide> 'history.\nThe new repl history file can be found at ' + <del> path.join(common.tmpDir, '.node_repl_history') + '.\n'; <add> `${path.join(common.tmpDir, '.node_repl_history')}.\n`; <ide> const homedirErr = '\nError: Could not get the home directory.\n' + <ide> 'REPL session history will not be persisted.\n'; <ide> const replFailedRead = '\nError: Could not open history file.\n' +
1
PHP
PHP
implement styled dumper based on symfony dumper
8d6bff9fc0d923201b95fe6349af4adc129a7a5a
<ide><path>src/Illuminate/Support/Debug/Dumper.php <add><?php namespace Illuminate\Support\Debug; <add> <add>use Symfony\Component\VarDumper\Cloner\VarCloner; <add>use Symfony\Component\VarDumper\Dumper\CliDumper; <add> <add>class Dumper { <add> <add> /** <add> * Var dump a value elegantly. <add> * <add> * @param mixed $value <add> * @return string <add> */ <add> public function dump($value) <add> { <add> $cloner = new VarCloner(); <add> $dumper = 'cli' === PHP_SAPI ? new CliDumper() : new HtmlDumper(); <add> $dumper->dump($cloner->cloneVar($value)); <add> } <add>} <ide><path>src/Illuminate/Support/Debug/HtmlDumper.php <add><?php namespace Illuminate\Support\Debug; <add> <add>use Symfony\Component\VarDumper\Dumper\HtmlDumper as SymfonyHtmlDumper; <add> <add>class HtmlDumper extends SymfonyHtmlDumper { <add> <add> /** <add> * Colour definitions for output. <add> * <add> * @var array <add> */ <add> protected $styles = array( <add> 'default' => 'background-color:#fff; color:#222; line-height:1.2em; font-weight:normal; font:12px Monaco, Consolas, monospace', <add> 'num' => 'color:#a71d5d', <add> 'const' => 'color:#795da3', <add> 'str' => 'color:#df5000', <add> 'cchr' => 'color:#222', <add> 'note' => 'color:#a71d5d', <add> 'ref' => 'color:#A0A0A0', <add> 'public' => 'color:#795da3', <add> 'protected' => 'color:#795da3', <add> 'private' => 'color:#795da3', <add> 'meta' => 'color:#B729D9', <add> 'key' => 'color:#df5000', <add> 'index' => 'color:#a71d5d', <add> ); <add> <add>} <ide><path>src/Illuminate/Support/helpers.php <ide> function data_get($target, $key, $default = null) <ide> */ <ide> function dd() <ide> { <del> array_map(function($x) { dump($x); }, func_get_args()); die; <add> array_map(function($x) { <add> $dumper = new \Illuminate\Support\Debug\Dumper; <add> $dumper->dump($x); <add> }, func_get_args()); die; <ide> } <ide> } <ide>
3
Python
Python
fix mypy error at maths
d009cea391414bfef17520ba6b64e4c2d97163ed
<ide><path>maths/greedy_coin_change.py <ide> """ <ide> <ide> <del>def find_minimum_change(denominations: list[int], value: int) -> list[int]: <add>def find_minimum_change(denominations: list[int], value: str) -> list[int]: <ide> """ <ide> Find the minimum change from the given denominations and value <ide> >>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745) <ide> def find_minimum_change(denominations: list[int], value: int) -> list[int]: <ide> if __name__ == "__main__": <ide> <ide> denominations = list() <del> value = 0 <add> value = "0" <ide> <ide> if ( <ide> input("Do you want to enter your denominations ? (yY/n): ").strip().lower() <ide><path>maths/triplet_sum.py <ide> def make_dataset() -> tuple[list[int], int]: <ide> dataset = make_dataset() <ide> <ide> <del>def triplet_sum1(arr: list[int], target: int) -> tuple[int, int, int]: <add>def triplet_sum1(arr: list[int], target: int) -> tuple[int, ...]: <ide> """ <ide> Returns a triplet in the array with sum equal to target, <ide> else (0, 0, 0). <ide><path>maths/two_sum.py <ide> def two_sum(nums: list[int], target: int) -> list[int]: <ide> >>> two_sum([3 * i for i in range(10)], 19) <ide> [] <ide> """ <del> chk_map = {} <add> chk_map: dict[int, int] = {} <ide> for index, val in enumerate(nums): <ide> compl = target - val <ide> if compl in chk_map:
3
Text
Text
clarify readable.unshift null/eof
273d38b1980fe308583c430eaeb837b8e6b3d204
<ide><path>doc/api/stream.md <ide> changes: <ide> * `encoding` {string} Encoding of string chunks. Must be a valid <ide> `Buffer` encoding, such as `'utf8'` or `'ascii'`. <ide> <del>Passing `chunk` as `null` signals the end of the stream (EOF), after which no <del>more data can be written. <add>Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the <add>same as `readable.push(null)`, after which no more data can be written. The EOF <add>signal is put at the end of the buffer and any buffered data will still be <add>flushed. <ide> <ide> The `readable.unshift()` method pushes a chunk of data back into the internal <ide> buffer. This is useful in certain situations where a stream is being consumed by
1
Javascript
Javascript
remove legacy_handlebars_tag flag
3d0fbece8afe03610db33ed07a864e18772933d3
<ide><path>packages/ember-handlebars/lib/loader.js <ide> require("ember-handlebars/ext"); <ide> Ember.Handlebars.bootstrap = function(ctx) { <ide> var selectors = 'script[type="text/x-handlebars"], script[type="text/x-raw-handlebars"]'; <ide> <del> if (Ember.ENV.LEGACY_HANDLEBARS_TAGS) { selectors += ', script[type="text/html"]'; } <del> <del> Ember.warn("Ember no longer parses text/html script tags by default. Set ENV.LEGACY_HANDLEBARS_TAGS = true to restore this functionality.", Ember.ENV.LEGACY_HANDLEBARS_TAGS || Ember.$('script[type="text/html"]').length === 0); <del> <ide> Ember.$(selectors, ctx) <ide> .each(function() { <ide> // Get a reference to the script tag <ide><path>packages/ember-handlebars/tests/loader_test.js <ide> test('template without data-element-id should still get an attribute', function( <ide> ok(id && /^ember\d+$/.test(id), "has standard Ember id"); <ide> }); <ide> <del>test('template with type text/html should work if LEGACY_HANDLEBARS_TAGS is true', function() { <del> Ember.ENV.LEGACY_HANDLEBARS_TAGS = true; <del> <del> try { <del> Ember.$('#qunit-fixture').html('<script type="text/html" data-template-name="funkyTemplate">Tobias Fünke</script>'); <del> <del> Ember.run(function() { <del> Ember.Handlebars.bootstrap(Ember.$('#qunit-fixture')); <del> }); <del> <del> ok(Ember.TEMPLATES['funkyTemplate'], 'template with name funkyTemplate available'); <del> } finally { <del> Ember.ENV.LEGACY_HANDLEBARS_TAGS = false; <del> } <del>}); <del> <ide> test('template with type text/x-raw-handlebars should be parsed', function() { <ide> Ember.$('#qunit-fixture').html('<script type="text/x-raw-handlebars" data-template-name="funkyTemplate">{{name}}</script>'); <ide>
2
Java
Java
remove ioexception from handshakehandler
13ce20b1ca14320dd3ddab516aff495753a2feae
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/DefaultHandshakeHandler.java <ide> public String[] getSupportedProtocols() { <ide> <ide> @Override <ide> public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws IOException, HandshakeFailureException { <add> WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException { <ide> <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Initiating handshake for " + request.getURI() + ", headers=" + request.getHeaders()); <ide> } <ide> <del> if (!HttpMethod.GET.equals(request.getMethod())) { <del> response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED); <del> response.getHeaders().setAllow(Collections.singleton(HttpMethod.GET)); <del> logger.debug("Only HTTP GET is allowed, current method is " + request.getMethod()); <del> return false; <del> } <del> if (!"WebSocket".equalsIgnoreCase(request.getHeaders().getUpgrade())) { <del> handleInvalidUpgradeHeader(request, response); <del> return false; <del> } <del> if (!request.getHeaders().getConnection().contains("Upgrade") && <del> !request.getHeaders().getConnection().contains("upgrade")) { <del> handleInvalidConnectHeader(request, response); <del> return false; <del> } <del> if (!isWebSocketVersionSupported(request)) { <del> handleWebSocketVersionNotSupported(request, response); <del> return false; <del> } <del> if (!isValidOrigin(request)) { <del> response.setStatusCode(HttpStatus.FORBIDDEN); <del> return false; <add> try { <add> if (!HttpMethod.GET.equals(request.getMethod())) { <add> response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED); <add> response.getHeaders().setAllow(Collections.singleton(HttpMethod.GET)); <add> logger.debug("Only HTTP GET is allowed, current method is " + request.getMethod()); <add> return false; <add> } <add> if (!"WebSocket".equalsIgnoreCase(request.getHeaders().getUpgrade())) { <add> handleInvalidUpgradeHeader(request, response); <add> return false; <add> } <add> if (!request.getHeaders().getConnection().contains("Upgrade") && <add> !request.getHeaders().getConnection().contains("upgrade")) { <add> handleInvalidConnectHeader(request, response); <add> return false; <add> } <add> if (!isWebSocketVersionSupported(request)) { <add> handleWebSocketVersionNotSupported(request, response); <add> return false; <add> } <add> if (!isValidOrigin(request)) { <add> response.setStatusCode(HttpStatus.FORBIDDEN); <add> return false; <add> } <add> String wsKey = request.getHeaders().getSecWebSocketKey(); <add> if (wsKey == null) { <add> logger.debug("Missing \"Sec-WebSocket-Key\" header"); <add> response.setStatusCode(HttpStatus.BAD_REQUEST); <add> return false; <add> } <ide> } <del> String wsKey = request.getHeaders().getSecWebSocketKey(); <del> if (wsKey == null) { <del> logger.debug("Missing \"Sec-WebSocket-Key\" header"); <del> response.setStatusCode(HttpStatus.BAD_REQUEST); <del> return false; <add> catch (IOException ex) { <add> throw new HandshakeFailureException( <add> "Response update failed during upgrade to WebSocket, uri=" + request.getURI(), ex); <ide> } <ide> <del> String selectedProtocol = selectProtocol(request.getHeaders().getSecWebSocketProtocol()); <del> // TODO: select extensions <add> String subProtocol = selectProtocol(request.getHeaders().getSecWebSocketProtocol()); <ide> <ide> if (logger.isDebugEnabled()) { <del> logger.debug("Upgrading request"); <add> logger.debug("Upgrading request, sub-protocol=" + subProtocol); <ide> } <ide> <del> this.requestUpgradeStrategy.upgrade(request, response, selectedProtocol, webSocketHandler, attributes); <add> this.requestUpgradeStrategy.upgrade(request, response, subProtocol, wsHandler, attributes); <ide> <ide> return true; <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/HandshakeFailureException.java <ide> @SuppressWarnings("serial") <ide> public class HandshakeFailureException extends NestedRuntimeException { <ide> <del> public HandshakeFailureException(String msg, Throwable cause) { <del> super(msg, cause); <add> <add> /** <add> * Constructor with message and root cause. <add> */ <add> public HandshakeFailureException(String message, Throwable cause) { <add> super(message, cause); <ide> } <ide> <del> public HandshakeFailureException(String msg) { <del> super(msg); <add> /** <add> * Constructor without a message. <add> */ <add> public HandshakeFailureException(String message) { <add> super(message); <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/HandshakeHandler.java <ide> <ide> package org.springframework.web.socket.server; <ide> <del>import java.io.IOException; <ide> import java.util.Map; <ide> <ide> import org.springframework.http.server.ServerHttpRequest; <ide> */ <ide> public interface HandshakeHandler { <ide> <add> <ide> /** <ide> * Initiate the handshake. <ide> * <ide> public interface HandshakeHandler { <ide> * response status, headers, and body will have been updated to reflect the <ide> * result of the negotiation <ide> * <del> * @throws IOException thrown when accessing or setting the response <del> * <ide> * @throws HandshakeFailureException thrown when handshake processing failed to <ide> * complete due to an internal, unrecoverable error, i.e. a server error as <del> * opposed to a failure to successfully negotiate the requirements of the <del> * handshake request. <add> * opposed to a failure to successfully negotiate the handshake. <ide> */ <ide> boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, <del> Map<String, Object> attributes) throws IOException, HandshakeFailureException; <add> Map<String, Object> attributes) throws HandshakeFailureException; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/RequestUpgradeStrategy.java <ide> <ide> package org.springframework.web.socket.server; <ide> <del>import java.io.IOException; <ide> import java.util.Map; <ide> <ide> import org.springframework.http.server.ServerHttpRequest; <ide> public interface RequestUpgradeStrategy { <ide> * handshake request. <ide> */ <ide> void upgrade(ServerHttpRequest request, ServerHttpResponse response, String acceptedProtocol, <del> WebSocketHandler wsHandler, Map<String, Object> attributes) throws IOException, HandshakeFailureException; <add> WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractStandardUpgradeStrategy.java <ide> <ide> package org.springframework.web.socket.server.support; <ide> <del>import java.io.IOException; <ide> import java.net.InetSocketAddress; <ide> import java.util.Map; <ide> <ide> import org.springframework.web.socket.server.RequestUpgradeStrategy; <ide> <ide> /** <del> * A {@link RequestUpgradeStrategy} for containers that support standard Java WebSocket. <add> * A base class for {@link RequestUpgradeStrategy} implementations that build on the <add> * standard WebSocket API for Java. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> public abstract class AbstractStandardUpgradeStrategy implements RequestUpgradeS <ide> <ide> @Override <ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response, String acceptedProtocol, <del> WebSocketHandler wsHandler, Map<String, Object> attributes) <del> throws IOException, HandshakeFailureException { <add> WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException { <ide> <ide> HttpHeaders headers = request.getHeaders(); <add> <ide> InetSocketAddress localAddr = request.getLocalAddress(); <ide> InetSocketAddress remoteAddr = request.getRemoteAddress(); <ide> <del> StandardWebSocketSession wsSession = new StandardWebSocketSession(headers, attributes, localAddr, remoteAddr); <del> StandardWebSocketHandlerAdapter endpoint = new StandardWebSocketHandlerAdapter(wsHandler, wsSession); <add> StandardWebSocketSession session = new StandardWebSocketSession(headers, attributes, localAddr, remoteAddr); <add> StandardWebSocketHandlerAdapter endpoint = new StandardWebSocketHandlerAdapter(wsHandler, session); <ide> <ide> upgradeInternal(request, response, acceptedProtocol, endpoint); <ide> } <ide> <ide> protected abstract void upgradeInternal(ServerHttpRequest request, ServerHttpResponse response, <del> String selectedProtocol, Endpoint endpoint) throws IOException, HandshakeFailureException; <add> String selectedProtocol, Endpoint endpoint) throws HandshakeFailureException; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/GlassFishRequestUpgradeStrategy.java <ide> public String[] getSupportedVersions() { <ide> <ide> @Override <ide> public void upgradeInternal(ServerHttpRequest request, ServerHttpResponse response, <del> String selectedProtocol, Endpoint endpoint) throws IOException, HandshakeFailureException { <add> String selectedProtocol, Endpoint endpoint) throws HandshakeFailureException { <ide> <ide> Assert.isTrue(request instanceof ServletServerHttpRequest); <ide> HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); <ide> public void upgradeInternal(ServerHttpRequest request, ServerHttpResponse respon <ide> webSocketEngine.register(webSocketApplication); <ide> } <ide> catch (DeploymentException ex) { <del> throw new HandshakeFailureException("Failed to deploy endpoint in GlassFish", ex); <add> throw new HandshakeFailureException("Failed to configure endpoint in GlassFish", ex); <ide> } <ide> <ide> try { <ide> performUpgrade(servletRequest, servletResponse, request.getHeaders(), webSocketApplication); <ide> } <add> catch (IOException ex) { <add> throw new HandshakeFailureException( <add> "Response update failed during upgrade to WebSocket, uri=" + request.getURI(), ex); <add> } <ide> finally { <ide> webSocketEngine.unregister(webSocketApplication); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/JettyRequestUpgradeStrategy.java <ide> * {@code org.eclipse.jetty.websocket.server.WebSocketHandler} class. <ide> * <ide> * @author Phillip Webb <add> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide> public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy { <ide> <del> // FIXME jetty has options, timeouts etc. Do we need a common abstraction <del> <del> // FIXME need a way for someone to plug their own RequestUpgradeStrategy or override <del> // Jetty settings <del> <del> // FIXME when to call factory.cleanup(); <del> <del> private static final String WEBSOCKET_LISTENER_ATTR_NAME = JettyRequestUpgradeStrategy.class.getName() <del> + ".HANDLER_PROVIDER"; <add> private static final String WS_HANDLER_ATTR_NAME = JettyRequestUpgradeStrategy.class.getName() + ".WS_LISTENER"; <ide> <ide> private WebSocketServerFactory factory; <ide> <ide> <add> /** <add> * Default constructor. <add> */ <ide> public JettyRequestUpgradeStrategy() { <ide> this.factory = new WebSocketServerFactory(); <ide> this.factory.setCreator(new WebSocketCreator() { <ide> @Override <ide> public Object createWebSocket(UpgradeRequest request, UpgradeResponse response) { <ide> Assert.isInstanceOf(ServletUpgradeRequest.class, request); <del> return ((ServletUpgradeRequest) request).getServletAttributes().get(WEBSOCKET_LISTENER_ATTR_NAME); <add> return ((ServletUpgradeRequest) request).getServletAttributes().get(WS_HANDLER_ATTR_NAME); <ide> } <ide> }); <ide> try { <ide> public String[] getSupportedVersions() { <ide> <ide> @Override <ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response, <del> String protocol, WebSocketHandler wsHandler, Map<String, Object> attrs) throws IOException { <add> String protocol, WebSocketHandler wsHandler, Map<String, Object> attrs) throws HandshakeFailureException { <ide> <ide> Assert.isInstanceOf(ServletServerHttpRequest.class, request); <ide> HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); <ide> <ide> Assert.isInstanceOf(ServletServerHttpResponse.class, response); <ide> HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse(); <ide> <del> if (!this.factory.isUpgradeRequest(servletRequest, servletResponse)) { <del> // should never happen <del> throw new HandshakeFailureException("Not a WebSocket request"); <del> } <del> <del> JettyWebSocketSession wsSession = new JettyWebSocketSession(request.getPrincipal(), attrs); <del> JettyWebSocketHandlerAdapter wsListener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession); <add> Assert.isTrue(this.factory.isUpgradeRequest(servletRequest, servletResponse), "Not a WebSocket handshake"); <ide> <del> servletRequest.setAttribute(WEBSOCKET_LISTENER_ATTR_NAME, wsListener); <add> JettyWebSocketSession session = new JettyWebSocketSession(request.getPrincipal(), attrs); <add> JettyWebSocketHandlerAdapter handlerAdapter = new JettyWebSocketHandlerAdapter(wsHandler, session); <ide> <del> if (!this.factory.acceptWebSocket(servletRequest, servletResponse)) { <del> // should not happen <del> throw new HandshakeFailureException("WebSocket request not accepted by Jetty"); <add> try { <add> servletRequest.setAttribute(WS_HANDLER_ATTR_NAME, handlerAdapter); <add> this.factory.acceptWebSocket(servletRequest, servletResponse); <add> } <add> catch (IOException ex) { <add> throw new HandshakeFailureException( <add> "Response update failed during upgrade to WebSocket, uri=" + request.getURI(), ex); <add> } <add> finally { <add> servletRequest.removeAttribute(WS_HANDLER_ATTR_NAME); <ide> } <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/TomcatRequestUpgradeStrategy.java <ide> <ide> package org.springframework.web.socket.server.support; <ide> <add>import java.io.IOException; <ide> import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.Map; <ide> <ide> import javax.servlet.ServletContext; <add>import javax.servlet.ServletException; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> import javax.websocket.Endpoint; <ide> public void upgradeInternal(ServerHttpRequest request, ServerHttpResponse respon <ide> try { <ide> getContainer(servletRequest).doUpgrade(servletRequest, servletResponse, endpointConfig, pathParams); <ide> } <del> catch (Exception ex) { <del> throw new HandshakeFailureException("Failed to upgrade HttpServletRequest", ex); <add> catch (ServletException ex) { <add> throw new HandshakeFailureException( <add> "Servlet request failed to upgrade to WebSocket, uri=" + request.getURI(), ex); <add> } <add> catch (IOException ex) { <add> throw new HandshakeFailureException( <add> "Response update failed during upgrade to WebSocket, uri=" + request.getURI(), ex); <ide> } <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/SockJsException.java <ide> public class SockJsException extends NestedRuntimeException { <ide> private final String sessionId; <ide> <ide> <add> public SockJsException(String message, Throwable cause) { <add> this(message, null, cause); <add> } <add> <ide> public SockJsException(String message, String sessionId, Throwable cause) { <ide> super(message, cause); <ide> this.sessionId = sessionId; <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/SockJsHttpRequestHandler.java <ide> protected WebSocketHandler decorateWebSocketHandler(WebSocketHandler handler) { <ide> public void handleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) <ide> throws ServletException, IOException { <ide> <del> ServerHttpRequest serverRequest = new ServletServerHttpRequest(servletRequest); <del> ServerHttpResponse serverResponse = new ServletServerHttpResponse(servletResponse); <add> ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); <add> ServerHttpResponse response = new ServletServerHttpResponse(servletResponse); <ide> <del> this.sockJsService.handleRequest(serverRequest, serverResponse, this.webSocketHandler); <add> try { <add> this.sockJsService.handleRequest(request, response, this.webSocketHandler); <add> } <add> catch (Throwable t) { <add> throw new SockJsException("Uncaught failure in SockJS request, uri=" + request.getURI(), t); <add> } <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/WebSocketTransportHandler.java <ide> <ide> package org.springframework.web.socket.sockjs.transport.handler; <ide> <del>import java.io.IOException; <ide> import java.util.Collections; <ide> import java.util.Map; <ide> <ide> import org.springframework.web.socket.CloseStatus; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketSession; <add>import org.springframework.web.socket.server.HandshakeFailureException; <ide> import org.springframework.web.socket.server.HandshakeHandler; <ide> import org.springframework.web.socket.sockjs.SockJsException; <ide> import org.springframework.web.socket.sockjs.SockJsTransportFailureException; <ide> import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession; <ide> <ide> /** <del> * A WebSocket {@link TransportHandler}. Uses {@link SockJsWebSocketHandler} and <add> * WebSocket-based {@link TransportHandler}. Uses {@link SockJsWebSocketHandler} and <ide> * {@link WebSocketServerSockJsSession} to add SockJS processing. <ide> * <ide> * <p>Also implements {@link HandshakeHandler} to support raw WebSocket communication at <ide> public void handleRequest(ServerHttpRequest request, ServerHttpResponse response <ide> <ide> @Override <ide> public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler handler, Map<String, Object> attributes) throws IOException { <add> WebSocketHandler handler, Map<String, Object> attributes) throws HandshakeFailureException { <ide> <ide> return this.handshakeHandler.doHandshake(request, response, handler, attributes); <ide> }
11
Text
Text
add function to "map manual"
84c27f7db109f266cc47509452a4a7641d7a54cc
<ide><path>client/src/pages/guide/english/cplusplus/map/index.md <ide> d => 40 <ide> ## Creating map object <ide> ` map<string, int> myMap; ` <ide> <add>## Get Size <add>Get size of map with size function <add>``` <add>map<int, int > myMap; <add>myMap[100] = 3 <add>count << "size of map is " << myMap.size() << '\n'; <add>``` <add> <add>Output: <add>``` <add>size of map is 1 <add>``` <add> <ide> ## Insertion <ide> Inserting data with insert member function. <ide> <ide> We can also insert data in std::map using operator [] i.e. <ide> <ide> `myMap["sun"] = 3;` <ide> <add>If "sun" is already mapped before, this action will override the value mapped to key. <add> <add>## Erase <add>Erasing data with erase function <add> <add>``` <add>map<int, int > myMap; <add>myMap[10] = 1000; <add>cout << "before erase, size of map is " << myMap.size() << '\n'; <add>myMap.erase(10); <add>cout << "after erase, size of map is " << myMap.size() << '\n'; <add>``` <add> <add>Output: <add>``` <add>before erase, size of map is 1 <add>after erase, size of map is 0 <add>``` <add> <add>## Accessing map value <add> <add>To access map values, simply call Map[key]. For example: <add>``` <add>map<string, int > M; <add>M["abc"] = 1; <add>M["def"] = 2; <add>cout << "value of abc is " << M["abc"] << '\n'; <add>cout << "value of def is " << M["def"] << '\n'; <add>``` <add> <add>Output: <add>``` <add>value of abc is 1 <add>value of def is 2 <add>``` <add> <ide> ## Accessing map elements <ide> <ide> To access map elements, you have to create iterator for it. Here is an example as stated before.
1
PHP
PHP
fix warning on empty data
d711364db4d7ecd5aeb0143d4e57acdd7ba28859
<ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> public function startup(EventInterface $event): void <ide> $this->ext = 'ajax'; <ide> } <ide> <del> if ( <del> !$request->is(['get', 'head', 'options']) <del> && $request->getParsedBody() === [] <del> && !empty($request->input()) <del> ) { <del> deprecationWarning( <del> 'Request\'s input data parsing feature has been removed from RequestHandler. ' <del> . 'Use the BodyParserMiddleware in your Application class instead.' <del> ); <add> if (!$request->is(['get', 'head', 'options']) && $request->getParsedBody() === []) { <add> $input = $request->input(); <add> if (!in_array($input, ['', '[]', '{}'], true)) { <add> deprecationWarning( <add> 'Request input data parsing feature has been removed from RequestHandler. ' <add> . 'Use the BodyParserMiddleware in your Application class instead.' <add> ); <add> } <ide> } <ide> } <ide> <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> use Cake\View\AjaxView; <ide> use Cake\View\JsonView; <ide> use Cake\View\XmlView; <add>use PHPUnit\Framework\Error\Deprecated; <ide> use TestApp\Controller\Component\RequestHandlerExtComponent; <ide> use TestApp\Controller\RequestHandlerTestController; <ide> use TestApp\View\AppView; <ide> public function testInitializeInputDataWarning() <ide> ]); <ide> $this->Controller->setRequest($request->withMethod('POST')); <ide> <del> $this->deprecated(function () { <del> $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller)); <del> }); <add> $this->expectException(Deprecated::class); <add> $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller)); <add> } <ide> <del> $this->assertEmpty($request->getData()); <add> /** <add> * Test that startup() throws deprecation warning if input data is available and request data is not populated. <add> * <add> * @return void <add> */ <add> public function testInitializeInputNoWarningEmptyJsonObject() <add> { <add> $request = new ServerRequest([ <add> 'input' => json_encode([]), <add> ]); <add> $this->Controller->setRequest($request->withMethod('POST')); <add> $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller)); <add> $this->assertSame([], $request->getParsedBody()); <ide> } <ide> <ide> /**
2
Python
Python
update the version string
990e640643e2beb4e6c13ac2e54298af97a2c334
<ide><path>libcloud/__init__.py <ide> <ide> __all__ = ["__version__", "enable_debug"] <ide> <del>__version__ = "0.5.0-dev" <add>__version__ = "0.5.0" <ide> <ide> def enable_debug(fo): <ide> """
1
Javascript
Javascript
convert throws to assertions in `registry`
3b22f49e857f959edc8b5bfeca5dbfff47b38b25
<ide><path>packages/container/lib/registry.js <ide> export default class Registry { <ide> */ <ide> register(fullName, factory, options = {}) { <ide> assert('fullName must be a proper full name', this.validateFullName(fullName)); <del> <del> if (factory === undefined) { <del> throw new TypeError(`Attempting to register an unknown factory: '${fullName}'`); <del> } <add> assert(`Attempting to register an unknown factory: '${fullName}'`, factory !== undefined); <ide> <ide> let normalizedName = this.normalize(fullName); <del> <del> if (this._resolveCache[normalizedName]) { <del> throw new Error(`Cannot re-register: '${fullName}', as it has already been resolved.`); <del> } <add> assert(`Cannot re-register: '${fullName}', as it has already been resolved.`, !this._resolveCache[normalizedName]); <ide> <ide> delete this._failCache[normalizedName]; <ide> this.registrations[normalizedName] = factory; <ide> export default class Registry { <ide> assert('fullName must be a proper full name', this.validateFullName(fullName)); <ide> <ide> let fullNameType = fullName.split(':')[0]; <del> if (fullNameType === type) { <del> throw new Error(`Cannot inject a '${fullName}' on other ${type}(s).`); <del> } <add> assert(`Cannot inject a '${fullName}' on other ${type}(s).`, fullNameType !== type); <ide> <ide> let injections = this._typeInjections[type] || <ide> (this._typeInjections[type] = []); <ide><path>packages/container/tests/registry_test.js <ide> QUnit.test('Throw exception when trying to inject `type:thing` on all type(s)', <ide> <ide> registry.register('controller:post', PostController); <ide> <del> throws(() => { <add> expectAssertion(() => { <ide> registry.typeInjection('controller', 'injected', 'controller:post'); <ide> }, /Cannot inject a 'controller:post' on other controller\(s\)\./); <ide> }); <ide> QUnit.test('cannot re-register a factory if it has been resolved', function() { <ide> registry.register('controller:apple', FirstApple); <ide> strictEqual(registry.resolve('controller:apple'), FirstApple); <ide> <del> throws(function() { <add> expectAssertion(function() { <ide> registry.register('controller:apple', SecondApple); <ide> }, /Cannot re-register: 'controller:apple', as it has already been resolved\./); <ide>
2
Javascript
Javascript
add rollbar keys
3c50f7651c3e4032def54abd983545d45f528cb3
<ide><path>client/gatsby-node.js <ide> exports.onCreateWebpackConfig = ({ plugins, actions }) => { <ide> process.env.HOME_PATH || 'http://localhost:3000' <ide> ), <ide> STRIPE_PUBLIC_KEY: JSON.stringify(process.env.STRIPE_PUBLIC_KEY || ''), <add> ROLLBAR_CLIENT_ID: JSON.stringify(process.env.ROLLBAR_CLIENT_ID || ''), <ide> ENVIRONMENT: JSON.stringify( <ide> process.env.FREECODECAMP_NODE_ENV || 'development' <ide> ),
1
Python
Python
remove outdated entries in f2py
76b5875855e09479efca5034790a4500b138afc2
<ide><path>numpy/f2py/rules.py <ide> * This file is auto-generated with f2py (version:#f2py_version#). <ide> * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition, <ide> * written by Pearu Peterson <pearu@cens.ioc.ee>. <del> * See http://cens.ioc.ee/projects/f2py2e/ <ide> * Generation date: """ + time.asctime(time.gmtime(generationtime)) + """ <del> * $R""" + """evision:$ <del> * $D""" + """ate:$ <ide> * Do not edit this file directly unless you know what you are doing!!! <ide> */ <ide>
1
Ruby
Ruby
fix license output
5cae3f409640c2afbb1f87eaf99e790aba735f35
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def bottle_formula(f, args:) <ide> "tap_git_revision" => tap_git_revision, <ide> "tap_git_remote" => tap_git_remote, <ide> "desc" => f.desc, <del> "license" => f.license, <add> "license" => SPDX.license_expression_to_string(f.license), <ide> "homepage" => f.homepage, <ide> }, <ide> "bottle" => {
1
PHP
PHP
fix docblock errors
a1ce05ed97f666a88a2f8c7b8e899524ce6e845c
<ide><path>src/Collection/Iterator/ReplaceIterator.php <ide> class ReplaceIterator extends Collection <ide> /** <ide> * A reference to the internal iterator this object is wrapping. <ide> * <del> * @var \Iterator <add> * @var \Traversable <ide> */ <ide> protected $_innerIterator; <ide> <ide><path>src/Collection/Iterator/StoppableIterator.php <ide> class StoppableIterator extends Collection <ide> /** <ide> * A reference to the internal iterator this object is wrapping. <ide> * <del> * @var \Iterator <add> * @var \Traversable <ide> */ <ide> protected $_innerIterator; <ide> <ide><path>src/Collection/Iterator/UnfoldIterator.php <ide> class UnfoldIterator extends IteratorIterator implements RecursiveIterator <ide> /** <ide> * A reference to the internal iterator this object is wrapping. <ide> * <del> * @var \Iterator <add> * @var \Traversable <ide> */ <ide> protected $_innerIterator; <ide>
3
PHP
PHP
improve exception logging
fc50df40808fb7939c6c1d26ce94bb477019d759
<ide><path>src/Error/ExceptionRenderer.php <ide> protected function _outputMessage(string $template): Response <ide> } <ide> <ide> return $this->_outputMessageSafe('error500'); <del> } catch (Throwable $e) { <del> return $this->_outputMessageSafe('error500'); <add> } catch (Throwable $outer) { <add> try { <add> return $this->_outputMessageSafe('error500'); <add> } catch (Throwable $inner) { <add> throw $outer; <add> } <ide> } <ide> } <ide>
1
Java
Java
fix compiler warnings
23bda9a5a74780dd2c56829caa23766e5ffbbb31
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/JsonPathAssertions.java <ide> public boolean equals(Object obj) { <ide> "to avoid being used in error instead of JsonPathAssertions#isEqualTo(String)."); <ide> } <ide> <add> @Override <add> public int hashCode() { <add> return super.hashCode(); <add> } <add> <ide> } <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/XpathAssertions.java <ide> public boolean equals(Object obj) { <ide> "to avoid being used in error instead of XPathAssertions#isEqualTo(String)."); <ide> } <ide> <add> @Override <add> public int hashCode() { <add> return super.hashCode(); <add> } <add> <ide> <ide> /** <ide> * Lets us be able to use lambda expressions that could throw checked exceptions, since
2
Python
Python
correct eos_token_id settings in generate
5ec368d79ecfa1467358f5b42da2cecbe23d6b0d
<ide><path>src/transformers/generation_utils.py <ide> def generate( <ide> <ide> pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id <ide> eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id <add> if eos_token_id is None and hasattr(self.config, "decoder"): <add> eos_token_id = self.config.decoder.eos_token_id <ide> <ide> output_scores = output_scores if output_scores is not None else self.config.output_scores <ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions <ide><path>tests/test_modeling_encoder_decoder.py <ide> def check_encoder_decoder_model_output_attentions( <ide> def check_encoder_decoder_model_generate(self, input_ids, config, decoder_config, **kwargs): <ide> encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) <ide> enc_dec_model = EncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) <add> <add> # Generate until max length <add> enc_dec_model.config.decoder.eos_token_id = None <ide> enc_dec_model.to(torch_device) <ide> <ide> # Bert does not have a bos token id, so use pad_token_id instead
2
Go
Go
fix invalid argument error on push
48ec176cd51da20e23564941da2d9906a7779d28
<ide><path>pkg/archive/archive.go <ide> func NewTempArchive(src Archive, dir string) (*TempArchive, error) { <ide> return nil, err <ide> } <ide> size := st.Size() <del> return &TempArchive{f, size, 0}, nil <add> return &TempArchive{File: f, Size: size}, nil <ide> } <ide> <ide> type TempArchive struct { <ide> *os.File <del> Size int64 // Pre-computed from Stat().Size() as a convenience <del> read int64 <add> Size int64 // Pre-computed from Stat().Size() as a convenience <add> read int64 <add> closed bool <add>} <add> <add>// Close closes the underlying file if it's still open, or does a no-op <add>// to allow callers to try to close the TempArchive multiple times safely. <add>func (archive *TempArchive) Close() error { <add> if archive.closed { <add> return nil <add> } <add> <add> archive.closed = true <add> <add> return archive.File.Close() <ide> } <ide> <ide> func (archive *TempArchive) Read(data []byte) (int, error) { <ide> n, err := archive.File.Read(data) <ide> archive.read += int64(n) <ide> if err != nil || archive.read == archive.Size { <del> archive.File.Close() <add> archive.Close() <ide> os.Remove(archive.File.Name()) <ide> } <ide> return n, err <ide><path>pkg/archive/archive_test.go <ide> import ( <ide> "os/exec" <ide> "path" <ide> "path/filepath" <add> "strings" <ide> "syscall" <ide> "testing" <ide> "time" <ide> func TestUntarInvalidSymlink(t *testing.T) { <ide> } <ide> } <ide> } <add> <add>func TestTempArchiveCloseMultipleTimes(t *testing.T) { <add> reader := ioutil.NopCloser(strings.NewReader("hello")) <add> tempArchive, err := NewTempArchive(reader, "") <add> buf := make([]byte, 10) <add> n, err := tempArchive.Read(buf) <add> if n != 5 { <add> t.Fatalf("Expected to read 5 bytes. Read %d instead", n) <add> } <add> for i := 0; i < 3; i++ { <add> if err = tempArchive.Close(); err != nil { <add> t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err) <add> } <add> } <add>}
2
Ruby
Ruby
fix closing tag [ci skip]
ad3f47dc2f27a74b43c29ae66820f15239c81f21
<ide><path>actionpack/lib/action_view/helpers/tag_helper.rb <ide> module TagHelper <ide> # thus accessed as <tt>dataset.userId</tt>. <ide> # <ide> # Values are encoded to JSON, with the exception of strings and symbols. <del> # This may come in handy when using jQuery's HTML5-aware <tt>.data()<tt> <add> # This may come in handy when using jQuery's HTML5-aware <tt>.data()</tt> <ide> # from 1.4.3. <ide> # <ide> # ==== Examples
1
Ruby
Ruby
move browser checking to its own class
f52e17f1c3b59f4301a84da5ed4f46a77363f29d
<ide><path>actionpack/lib/action_dispatch/system_test_case.rb <ide> require "capybara/minitest" <ide> require "action_controller" <ide> require "action_dispatch/system_testing/driver" <add>require "action_dispatch/system_testing/browser" <ide> require "action_dispatch/system_testing/server" <ide> require "action_dispatch/system_testing/test_helpers/screenshot_helper" <ide> require "action_dispatch/system_testing/test_helpers/setup_and_teardown" <ide><path>actionpack/lib/action_dispatch/system_testing/browser.rb <add># frozen_string_literal: true <add> <add>module ActionDispatch <add> module SystemTesting <add> class Browser # :nodoc: <add> attr_reader :name <add> <add> def initialize(name) <add> @name = name <add> end <add> <add> def type <add> case name <add> when :headless_chrome <add> :chrome <add> when :headless_firefox <add> :firefox <add> else <add> name <add> end <add> end <add> <add> def options <add> case name <add> when :headless_chrome <add> headless_chrome_browser_options <add> when :headless_firefox <add> headless_firefox_browser_options <add> end <add> end <add> <add> private <add> def headless_chrome_browser_options <add> options = Selenium::WebDriver::Chrome::Options.new <add> options.args << "--headless" <add> options.args << "--disable-gpu" <add> <add> options <add> end <add> <add> def headless_firefox_browser_options <add> options = Selenium::WebDriver::Firefox::Options.new <add> options.args << "-headless" <add> <add> options <add> end <add> end <add> end <add>end <ide><path>actionpack/lib/action_dispatch/system_testing/driver.rb <ide> module SystemTesting <ide> class Driver # :nodoc: <ide> def initialize(name, **options) <ide> @name = name <del> @browser = options[:using] <add> @browser = Browser.new(options[:using]) <ide> @screen_size = options[:screen_size] <ide> @options = options[:options] <ide> end <ide> def register <ide> end <ide> <ide> def browser_options <del> if @browser == :headless_chrome <del> browser_options = Selenium::WebDriver::Chrome::Options.new <del> browser_options.args << "--headless" <del> browser_options.args << "--disable-gpu" <del> <del> @options.merge(options: browser_options) <del> elsif @browser == :headless_firefox <del> browser_options = Selenium::WebDriver::Firefox::Options.new <del> browser_options.args << "-headless" <del> <del> @options.merge(options: browser_options) <del> else <del> @options <del> end <del> end <del> <del> def browser <del> if @browser == :headless_chrome <del> :chrome <del> elsif @browser == :headless_firefox <del> :firefox <del> else <del> @browser <del> end <add> @options.merge(options: @browser.options).compact <ide> end <ide> <ide> def register_selenium(app) <del> Capybara::Selenium::Driver.new(app, { browser: browser }.merge(browser_options)).tap do |driver| <add> Capybara::Selenium::Driver.new(app, { browser: @browser.type }.merge(browser_options)).tap do |driver| <ide> driver.browser.manage.window.size = Selenium::WebDriver::Dimension.new(*@screen_size) <ide> end <ide> end <ide><path>actionpack/test/dispatch/system_testing/driver_test.rb <ide> class DriverTest < ActiveSupport::TestCase <ide> test "initializing the driver with a browser" do <ide> driver = ActionDispatch::SystemTesting::Driver.new(:selenium, using: :chrome, screen_size: [1400, 1400], options: { url: "http://example.com/wd/hub" }) <ide> assert_equal :selenium, driver.instance_variable_get(:@name) <del> assert_equal :chrome, driver.instance_variable_get(:@browser) <add> assert_equal :chrome, driver.instance_variable_get(:@browser).name <add> assert_nil driver.instance_variable_get(:@browser).options <ide> assert_equal [1400, 1400], driver.instance_variable_get(:@screen_size) <ide> assert_equal ({ url: "http://example.com/wd/hub" }), driver.instance_variable_get(:@options) <ide> end <ide> <ide> test "initializing the driver with a headless chrome" do <ide> driver = ActionDispatch::SystemTesting::Driver.new(:selenium, using: :headless_chrome, screen_size: [1400, 1400], options: { url: "http://example.com/wd/hub" }) <ide> assert_equal :selenium, driver.instance_variable_get(:@name) <del> assert_equal :headless_chrome, driver.instance_variable_get(:@browser) <add> assert_equal :headless_chrome, driver.instance_variable_get(:@browser).name <ide> assert_equal [1400, 1400], driver.instance_variable_get(:@screen_size) <ide> assert_equal ({ url: "http://example.com/wd/hub" }), driver.instance_variable_get(:@options) <ide> end <ide> <ide> test "initializing the driver with a headless firefox" do <ide> driver = ActionDispatch::SystemTesting::Driver.new(:selenium, using: :headless_firefox, screen_size: [1400, 1400], options: { url: "http://example.com/wd/hub" }) <ide> assert_equal :selenium, driver.instance_variable_get(:@name) <del> assert_equal :headless_firefox, driver.instance_variable_get(:@browser) <add> assert_equal :headless_firefox, driver.instance_variable_get(:@browser).name <ide> assert_equal [1400, 1400], driver.instance_variable_get(:@screen_size) <ide> assert_equal ({ url: "http://example.com/wd/hub" }), driver.instance_variable_get(:@options) <ide> end
4
Javascript
Javascript
remove opt defaults, simplify load()
3e1542b48599d705f4038f7448f61f0907e549e0
<ide><path>packager/src/Bundler/index.js <ide> const ModuleTransport = require('../lib/ModuleTransport'); <ide> const imageSize = require('image-size'); <ide> const path = require('path'); <ide> const denodeify = require('denodeify'); <add>const defaults = require('../../defaults'); <ide> <ide> const { <ide> sep: pathSeparator, <ide> class Bundler { <ide> hasteImpl: opts.hasteImpl, <ide> minifyCode: this._transformer.minify, <ide> moduleFormat: opts.moduleFormat, <del> platforms: opts.platforms, <add> platforms: new Set(opts.platforms), <ide> polyfillModuleNames: opts.polyfillModuleNames, <ide> projectRoots: opts.projectRoots, <del> providesModuleNodeModules: opts.providesModuleNodeModules, <add> providesModuleNodeModules: <add> opts.providesModuleNodeModules || defaults.providesModuleNodeModules, <ide> reporter: opts.reporter, <ide> resetCache: opts.resetCache, <ide> transformCode: <ide><path>packager/src/Resolver/index.js <ide> type Options = { <ide> assetExts: Array<string>, <ide> blacklistRE?: RegExp, <ide> cache: Cache, <del> extraNodeModules?: {}, <add> extraNodeModules: ?{}, <ide> getTransformCacheKey: GetTransformCacheKey, <ide> globalTransformCache: ?GlobalTransformCache, <ide> hasteImpl?: HasteImpl, <ide> minifyCode: MinifyCode, <del> platforms: Array<string>, <add> platforms: Set<string>, <ide> polyfillModuleNames?: Array<string>, <ide> projectRoots: Array<string>, <del> providesModuleNodeModules?: Array<string>, <add> providesModuleNodeModules: Array<string>, <ide> reporter: Reporter, <ide> resetCache: boolean, <ide> transformCode: TransformCode, <del> watch?: boolean, <add> watch: boolean, <ide> }; <ide> <ide> class Resolver { <ide> class Resolver { <ide> } <ide> <ide> static async load(opts: Options): Promise<Resolver> { <del> const depGraph = await DependencyGraph.load({ <add> const depGraphOpts = Object.assign(Object.create(opts), { <ide> assetDependencies: ['react-native/Libraries/Image/AssetRegistry'], <del> assetExts: opts.assetExts, <del> cache: opts.cache, <del> extraNodeModules: opts.extraNodeModules, <ide> extensions: ['js', 'json'], <ide> forceNodeFilesystemAPI: false, <del> getTransformCacheKey: opts.getTransformCacheKey, <del> globalTransformCache: opts.globalTransformCache, <ide> ignoreFilePath(filepath) { <ide> return filepath.indexOf('__tests__') !== -1 || <ide> (opts.blacklistRE != null && opts.blacklistRE.test(filepath)); <ide> class Resolver { <ide> hasteImpl: opts.hasteImpl, <ide> resetCache: opts.resetCache, <ide> }, <del> platforms: new Set(opts.platforms), <ide> preferNativePlatform: true, <del> providesModuleNodeModules: <del> opts.providesModuleNodeModules || defaults.providesModuleNodeModules, <del> reporter: opts.reporter, <del> resetCache: opts.resetCache, <ide> roots: opts.projectRoots, <del> transformCode: opts.transformCode, <ide> useWatchman: true, <del> watch: opts.watch || false, <ide> }); <add> const depGraph = await DependencyGraph.load(depGraphOpts); <ide> return new Resolver(opts, depGraph); <ide> } <ide> <ide><path>packager/src/node-haste/index.js <ide> type Options = { <ide> assetExts: Array<string>, <ide> cache: Cache, <ide> extensions: Array<string>, <del> extraNodeModules: ?Object, <add> extraNodeModules: ?{}, <ide> forceNodeFilesystemAPI: boolean, <ide> getTransformCacheKey: GetTransformCacheKey, <ide> globalTransformCache: ?GlobalTransformCache, <ide> class DependencyGraph extends EventEmitter { <ide> initialModuleMap: ModuleMap, <ide> }) { <ide> super(); <del> this._opts = {...config.opts}; <add> this._opts = config.opts; <ide> this._haste = config.haste; <ide> this._hasteFS = config.initialHasteFS; <ide> this._moduleMap = config.initialModuleMap;
3
Javascript
Javascript
fix treatment of some values as non-empty"
0f39ef4ca11bf0c6c6891dec3fa0d2d3d16513cb
<ide><path>lib/url.js <ide> Object.defineProperty(Url.prototype, 'port', { <ide> return null; <ide> }, <ide> set: function(v) { <del> if (isConsideredEmpty(v)) { <add> if (v === null) { <ide> this._port = -1; <ide> if (this._host) <ide> this._host = null; <ide> Object.defineProperty(Url.prototype, 'path', { <ide> return (p == null && s) ? ('/' + s) : null; <ide> }, <ide> set: function(v) { <del> if (isConsideredEmpty(v)) { <add> if (v === null) { <ide> this._pathname = this._search = null; <ide> return; <ide> } <ide> Object.defineProperty(Url.prototype, 'protocol', { <ide> return proto; <ide> }, <ide> set: function(v) { <del> if (isConsideredEmpty(v)) { <add> if (v === null) { <ide> this._protocol = null; <ide> } else { <ide> var proto = '' + v; <ide> Object.defineProperty(Url.prototype, 'href', { <ide> var parsesQueryStrings = this._parsesQueryStrings; <ide> // Reset properties. <ide> Url.call(this); <del> if (!isConsideredEmpty(v)) <add> if (v !== null && v !== '') <ide> this.parse('' + v, parsesQueryStrings, false); <ide> }, <ide> enumerable: true, <ide> Object.defineProperty(Url.prototype, 'auth', { <ide> return this._auth; <ide> }, <ide> set: function(v) { <del> this._auth = isConsideredEmpty(v) ? null : '' + v; <add> this._auth = v === null ? null : '' + v; <ide> this._href = ''; <ide> }, <ide> enumerable: true, <ide> Object.defineProperty(Url.prototype, 'host', { <ide> return this._host; <ide> }, <ide> set: function(v) { <del> if (isConsideredEmpty(v)) { <add> if (v === null) { <ide> this._port = -1; <ide> this._hostname = this._host = null; <ide> } else { <ide> Object.defineProperty(Url.prototype, 'hostname', { <ide> return this._hostname; <ide> }, <ide> set: function(v) { <del> if (isConsideredEmpty(v)) { <add> if (v === null) { <ide> this._hostname = null; <ide> <ide> if (this._hasValidPort()) <ide> Object.defineProperty(Url.prototype, 'hash', { <ide> return this._hash; <ide> }, <ide> set: function(v) { <del> if (isConsideredEmpty(v) || v === '#') { <add> if (v === null) { <ide> this._hash = null; <ide> } else { <ide> var hash = '' + v; <ide> Object.defineProperty(Url.prototype, 'search', { <ide> return this._search; <ide> }, <ide> set: function(v) { <del> if (isConsideredEmpty(v) || v === '?') { <add> if (v === null) { <ide> this._search = this._query = null; <ide> } else { <ide> var search = escapeSearch('' + v); <ide> Object.defineProperty(Url.prototype, 'pathname', { <ide> return this._pathname; <ide> }, <ide> set: function(v) { <del> if (isConsideredEmpty(v)) { <add> if (v === null) { <ide> this._pathname = null; <ide> } else { <ide> var pathname = escapePathName('' + v).replace(/\\/g, '/'); <ide> Object.defineProperty(Url.prototype, 'pathname', { <ide> configurable: true <ide> }); <ide> <del>function isConsideredEmpty(value) { <del> return value === null || value === undefined || value === ''; <del>} <del> <ide> // Search `char1` (integer code for a character) in `string` <ide> // starting from `fromIndex` and ending at `string.length - 1` <ide> // or when a stop character is found. <ide><path>test/parallel/test-url-accessors.js <ide> const accessorTests = [{ <ide> }, { <ide> // Setting href to non-null non-string coerces to string <ide> url: 'google', <del> set: {href: 0}, <add> set: {href: undefined}, <ide> test: { <del> path: '0', <del> href: '0' <add> path: 'undefined', <add> href: 'undefined' <ide> } <ide> }, { <ide> // Setting port is reflected in host <ide> const accessorTests = [{ <ide> url: 'http://www.google.com', <ide> set: {search: ''}, <ide> test: { <del> search: null, <del> path: '/' <add> search: '?', <add> path: '/?' <ide> } <ide> }, { <ide> <ide> const accessorTests = [{ <ide> }, { <ide> <ide> // Empty hash is ok <del> url: 'http://www.google.com#hash', <add> url: 'http://www.google.com', <ide> set: {hash: ''}, <ide> test: { <del> hash: null, <del> href: 'http://www.google.com/' <add> hash: '#' <ide> } <ide> }, { <ide> <ide> const accessorTests = [{ <ide> url: 'http://www.google.com', <ide> set: {pathname: ''}, <ide> test: { <del> pathname: null, <del> href: 'http://www.google.com' <add> pathname: '/' <ide> } <ide> }, { <ide> // Null path is ok <ide> const accessorTests = [{ <ide> protocol: null <ide> } <ide> }, { <del> // Empty protocol is ok <add> // Empty protocol is invalid <ide> url: 'http://www.google.com/path', <ide> set: {protocol: ''}, <ide> test: { <del> protocol: null, <del> href: '//www.google.com/path' <add> protocol: 'http:' <ide> } <ide> }, { <ide> // Set query to an object <ide> const accessorTests = [{ <ide> url: 'http://www.google.com/path?key=value', <ide> set: {path: '?key2=value2'}, <ide> test: { <del> pathname: null, <add> pathname: '/', <ide> search: '?key2=value2', <del> href: 'http://www.google.com?key2=value2' <add> href: 'http://www.google.com/?key2=value2' <ide> } <ide> }, { <ide> // path is reflected in search and pathname 3 <ide> const accessorTests = [{ <ide> search: null, <ide> href: 'http://www.google.com' <ide> } <del>}, { <del> // setting hash to '' removes any hash <del> url: 'http://www.google.com/#hash', <del> set: {hash: ''}, <del> test: { <del> hash: null, <del> href: 'http://www.google.com/' <del> } <del>}, { <del> // setting hash to '#' removes any hash <del> url: 'http://www.google.com/#hash', <del> set: {hash: '#'}, <del> test: { <del> hash: null, <del> href: 'http://www.google.com/' <del> } <del>}, { <del> // setting search to '' removes any search <del> url: 'http://www.google.com/?search', <del> set: {search: ''}, <del> test: { <del> search: null, <del> href: 'http://www.google.com/' <del> } <del>}, { <del> // setting search to '?' removes any search <del> url: 'http://www.google.com/?search', <del> set: {search: '?'}, <del> test: { <del> search: null, <del> href: 'http://www.google.com/' <del> } <ide> } <ide> <ide> ];
2
Javascript
Javascript
normalize whitespace for transformed jsx code
60d7a02d44d8ce893e338f0ff6ae4812c9b5331a
<ide><path>vendor/fbtransform/transforms/react.js <ide> var renderXJSExpressionContainer = <ide> var renderXJSLiteral = require('./xjs').renderXJSLiteral; <ide> var quoteAttrName = require('./xjs').quoteAttrName; <ide> <add>var trimLeft = require('./xjs').trimLeft; <add> <ide> /** <ide> * Customized desugar processor. <ide> * <ide> function visitReactTag(traverse, object, path, state) { <ide> var nameObject = openingElement.name; <ide> var attributesObject = openingElement.attributes; <ide> <del> utils.catchup(openingElement.range[0], state); <add> utils.catchup(openingElement.range[0], state, trimLeft); <ide> <ide> if (nameObject.namespace) { <ide> throw new Error( <ide> function visitReactTag(traverse, object, path, state) { <ide> <ide> utils.move(nameObject.range[1], state); <ide> <add> var hasAttributes = attributesObject.length; <add> <ide> // if we don't have any attributes, pass in null <del> if (attributesObject.length === 0) { <add> if (hasAttributes) { <add> utils.append('{', state); <add> } else { <ide> utils.append('null', state); <ide> } <ide> <ide> // write attributes <ide> attributesObject.forEach(function(attr, index) { <del> utils.catchup(attr.range[0], state); <ide> if (attr.name.namespace) { <ide> throw new Error( <ide> 'Namespace attributes are not supported. ReactJSX is not XML.'); <ide> } <ide> var name = attr.name.name; <del> var isFirst = index === 0; <ide> var isLast = index === attributesObject.length - 1; <ide> <del> if (isFirst) { <del> utils.append('{', state); <del> } <del> <add> utils.catchup(attr.range[0], state, trimLeft); <ide> utils.append(quoteAttrName(name), state); <del> utils.append(':', state); <add> utils.append(': ', state); <ide> <ide> if (!attr.value) { <ide> state.g.buffer += 'true'; <ide> state.g.position = attr.name.range[1]; <ide> if (!isLast) { <del> utils.append(',', state); <add> utils.append(', ', state); <ide> } <ide> } else { <ide> utils.move(attr.name.range[1], state); <del> // Use catchupWhiteSpace to skip over the '=' in the attribute <del> utils.catchupWhiteSpace(attr.value.range[0], state); <add> // Use catchupNewlines to skip over the '=' in the attribute <add> utils.catchupNewlines(attr.value.range[0], state); <ide> if (JSX_ATTRIBUTE_TRANSFORMS.hasOwnProperty(attr.name.name)) { <ide> utils.append(JSX_ATTRIBUTE_TRANSFORMS[attr.name.name](attr), state); <ide> utils.move(attr.value.range[1], state); <ide> if (!isLast) { <del> utils.append(',', state); <add> utils.append(', ', state); <ide> } <ide> } else if (attr.value.type === Syntax.Literal) { <ide> renderXJSLiteral(attr.value, isLast, state); <ide> function visitReactTag(traverse, object, path, state) { <ide> } <ide> } <ide> <del> if (isLast) { <del> utils.append('}', state); <del> } <del> <del> utils.catchup(attr.range[1], state); <add> utils.catchup(attr.range[1], state, trimLeft); <ide> }); <ide> <ide> if (!openingElement.selfClosing) { <del> utils.catchup(openingElement.range[1] - 1, state); <add> utils.catchup(openingElement.range[1] - 1, state, trimLeft); <ide> utils.move(openingElement.range[1], state); <ide> } <ide> <add> if (hasAttributes) { <add> utils.append('}', state); <add> } <add> <ide> // filter out whitespace <ide> var childrenToRender = object.children.filter(function(child) { <ide> return !(child.type === Syntax.Literal <ide> function visitReactTag(traverse, object, path, state) { <ide> } <ide> <ide> childrenToRender.forEach(function(child, index) { <del> utils.catchup(child.range[0], state); <add> utils.catchup(child.range[0], state, trimLeft); <ide> <ide> var isLast = index >= lastRenderableIndex; <ide> <ide> function visitReactTag(traverse, object, path, state) { <ide> } else { <ide> traverse(child, path, state); <ide> if (!isLast) { <del> utils.append(',', state); <del> state.g.buffer = state.g.buffer.replace(/(\s*),$/, ',$1'); <add> utils.append(', ', state); <ide> } <ide> } <ide> <del> utils.catchup(child.range[1], state); <add> utils.catchup(child.range[1], state, trimLeft); <ide> }); <ide> } <ide> <ide> if (openingElement.selfClosing) { <ide> // everything up to /> <del> utils.catchup(openingElement.range[1] - 2, state); <add> utils.catchup(openingElement.range[1] - 2, state, trimLeft); <ide> utils.move(openingElement.range[1], state); <ide> } else { <ide> // everything up to </ sdflksjfd> <del> utils.catchup(object.closingElement.range[0], state); <add> utils.catchup(object.closingElement.range[0], state, trimLeft); <ide> utils.move(object.closingElement.range[1], state); <ide> } <ide> <ide><path>vendor/fbtransform/transforms/xjs.js <ide> function renderXJSLiteral(object, isLast, state, start, end) { <ide> trimmedLine = trimmedLine.replace(/[ ]+$/, ''); <ide> } <ide> <del> utils.append(line.match(/^[ \t]*/)[0], state); <add> if (!isFirstLine) { <add> utils.append(line.match(/^[ \t]*/)[0], state); <add> } <ide> <ide> if (trimmedLine || isLastNonEmptyLine) { <ide> utils.append( <ide> JSON.stringify(trimmedLine) + <del> (!isLastNonEmptyLine ? "+' '+" : ''), <add> (!isLastNonEmptyLine ? " + ' ' +" : ''), <ide> state); <ide> <ide> if (isLastNonEmptyLine) { <ide> if (end) { <ide> utils.append(end, state); <ide> } <ide> if (!isLast) { <del> utils.append(',', state); <add> utils.append(', ', state); <ide> } <ide> } <ide> <ide> // only restore tail whitespace if line had literals <del> if (trimmedLine) { <add> if (trimmedLine && !isLastLine) { <ide> utils.append(line.match(/[ \t]*$/)[0], state); <ide> } <ide> } <ide> function renderXJSExpressionContainer(traverse, object, isLast, path, state) { <ide> // Plus 1 to skip `{`. <ide> utils.move(object.range[0] + 1, state); <ide> traverse(object.expression, path, state); <add> <ide> if (!isLast && object.expression.type !== Syntax.XJSEmptyExpression) { <ide> // If we need to append a comma, make sure to do so after the expression. <del> utils.catchup(object.expression.range[1], state); <del> utils.append(',', state); <add> utils.catchup(object.expression.range[1], state, trimLeft); <add> utils.append(', ', state); <ide> } <ide> <ide> // Minus 1 to skip `}`. <del> utils.catchup(object.range[1] - 1, state); <add> utils.catchup(object.range[1] - 1, state, trimLeft); <ide> utils.move(object.range[1], state); <ide> return false; <ide> } <ide> function quoteAttrName(attr) { <ide> return attr; <ide> } <ide> <add>function trimLeft(value) { <add> return value.replace(/^[ ]+/, ''); <add>} <add> <ide> exports.knownTags = knownTags; <ide> exports.renderXJSExpressionContainer = renderXJSExpressionContainer; <ide> exports.renderXJSLiteral = renderXJSLiteral; <ide> exports.quoteAttrName = quoteAttrName; <add>exports.trimLeft = trimLeft;
2
Java
Java
fix memory leak in reactive multipart parser
60f47f44894ea405e9425a34f5a4a53c8ca1cacc
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java <ide> public void accept(FluxSink<Part> emitter) { <ide> catch (IOException ex) { <ide> listener.onError("Exception thrown providing input to the parser", ex); <ide> } <add> finally { <add> DataBufferUtils.release(buffer); <add> } <ide> }, (ex) -> { <ide> try { <ide> listener.onError("Request body input error", ex);
1
Javascript
Javascript
add myself as author
f1dd1daf22c8640de503b70fe5be0594200e9422
<ide><path>src/renderers/WebGLRenderer2.js <ide> * @author mrdoob / http://mrdoob.com/ <ide> * @author alteredq / http://alteredqualia.com/ <ide> * @author szimek / https://github.com/szimek/ <add> * @author gero3 / https://github.com/gero3/ <ide> */ <ide> <ide> THREE.WebGLRenderer2 = function ( parameters ) { <ide> THREE.WebGLRenderer2 = function ( parameters ) { <ide> <ide> }; <ide> <del>THREE.WebGLRenderer = THREE.WebGLRenderer2; <add>//THREE.WebGLRenderer = THREE.WebGLRenderer2;
1
Javascript
Javascript
support beta release versions
452d1cd66e8109fd5d19189207ac4be16ad827b5
<ide><path>compare-master-to-stable.js <ide> then(function (tags) { <ide> sort(semver.rcompare); <ide> }). <ide> then(function (tags) { <del> var major = tags[0].split('.')[0] + '.x'; <add> var major = tags[0].split('.')[0]; <ide> return tags. <ide> filter(function (ver) { <del> return semver.satisfies(ver, major); <add> return semver(ver).major == major; <ide> }); <ide> }). <ide> then(function (tags) {
1
Text
Text
add changes for 1.3.0-beta.13
1e4f5ccd3cc7be0beb10144d31501bf047ad8e9e
<ide><path>CHANGELOG.md <add>Reading git log since v1.3.0-beta.12 <add>Parsed 1 commits <add>Generating changelog to stdout ( undefined ) <add><a name="1.3.0-beta.13"></a> <add># 1.3.0-beta.13 idiosyncratic-numerification (2014-06-16) <add> <add> <add>## Bug Fixes <add> <add>- **jqLite:** change expando property to a more unique name <add> ([20c3c9e2](https://github.com/angular/angular.js/commit/20c3c9e25f6417773333727549ed2ca2d3505b44)) <add> <add> <add> <ide> <a name="1.3.0-beta.12"></a> <ide> # 1.3.0-beta.12 ephemeral-acceleration (2014-06-13) <ide>
1
Ruby
Ruby
check git available
31ddce85e7d37eac032e0dd80a6f45cd2ff1d4f8
<ide><path>Library/Homebrew/utils.rb <ide> def self.system(cmd, *args) <ide> end <ide> <ide> def self.git_origin <add> return unless Utils.git_available? <ide> HOMEBREW_REPOSITORY.cd { `git config --get remote.origin.url 2>/dev/null`.chuzzle } <ide> end <ide> <ide> def self.git_head <add> return unless Utils.git_available? <ide> HOMEBREW_REPOSITORY.cd { `git rev-parse --verify -q HEAD 2>/dev/null`.chuzzle } <ide> end <ide> <ide> def self.git_short_head <add> return unless Utils.git_available? <ide> HOMEBREW_REPOSITORY.cd { `git rev-parse --short=4 --verify -q HEAD 2>/dev/null`.chuzzle } <ide> end <ide> <ide> def self.git_last_commit <add> return unless Utils.git_available? <ide> HOMEBREW_REPOSITORY.cd { `git show -s --format="%cr" HEAD 2>/dev/null`.chuzzle } <ide> end <ide> <ide> def self.git_last_commit_date <add> return unless Utils.git_available? <ide> HOMEBREW_REPOSITORY.cd { `git show -s --format="%cd" --date=short HEAD 2>/dev/null`.chuzzle } <ide> end <ide> <ide> def self.homebrew_version_string <del> if Utils.git_available? && (pretty_revision = git_short_head) <add> if pretty_revision = git_short_head <ide> last_commit = git_last_commit_date <ide> "#{HOMEBREW_VERSION} (git revision #{pretty_revision}; last commit #{last_commit})" <ide> else
1
Javascript
Javascript
return object, not just code
e89c93f4f76bcd2030b30750a08dfec2cb2b3f02
<ide><path>jest/preprocessor_DO_NOT_USE.js <ide> babelRegisterOnly([]); <ide> <ide> const transformer = require('metro-react-native-babel-transformer'); <ide> module.exports = { <del> process(src /*: string */, file /*: string */) /*: string */ { <add> process(src /*: string */, file /*: string */) /*: {code: string, ...} */ { <ide> if (nodeFiles.test(file)) { <ide> // node specific transforms only <ide> return babelTransformSync(src, { <ide> filename: file, <ide> sourceType: 'script', <ide> ...nodeOptions, <ide> ast: false, <del> }).code; <add> }); <ide> } <ide> <ide> const {ast} = transformer.transform({ <ide> module.exports = { <ide> sourceMaps: true, <ide> }, <ide> src, <del> ).code; <add> ); <ide> }, <ide> <ide> getCacheKey: (createCacheKeyFunction([
1
Ruby
Ruby
call #name rather than relying on implicit #to_s
175336202475325a6a1b13372f93d7d44dd55385
<ide><path>Library/Homebrew/cmd/pull.rb <ide> def pull <ide> unless ARGV.include?('--bottle') <ide> changed_formulae.each do |f| <ide> next unless f.bottle <del> opoo "#{f} has a bottle: do you need to update it with --bottle?" <add> opoo "#{f.name} has a bottle: do you need to update it with --bottle?" <ide> end <ide> end <ide>
1
Javascript
Javascript
name anonymous functions in _http_incoming
239ff06126474ec1035a676b4cb3423bcb2c4165
<ide><path>lib/_http_incoming.js <ide> util.inherits(IncomingMessage, Stream.Readable); <ide> exports.IncomingMessage = IncomingMessage; <ide> <ide> <del>IncomingMessage.prototype.setTimeout = function(msecs, callback) { <add>IncomingMessage.prototype.setTimeout = function setTimeout(msecs, callback) { <ide> if (callback) <ide> this.on('timeout', callback); <ide> this.socket.setTimeout(msecs); <ide> return this; <ide> }; <ide> <ide> <del>IncomingMessage.prototype.read = function(n) { <add>IncomingMessage.prototype.read = function read(n) { <ide> if (!this._consuming) <ide> this._readableState.readingMore = false; <ide> this._consuming = true; <ide> IncomingMessage.prototype.read = function(n) { <ide> }; <ide> <ide> <del>IncomingMessage.prototype._read = function(n) { <add>IncomingMessage.prototype._read = function _read(n) { <ide> // We actually do almost nothing here, because the parserOnBody <ide> // function fills up our internal buffer directly. However, we <ide> // do need to unpause the underlying socket so that it flows. <ide> IncomingMessage.prototype._read = function(n) { <ide> // It's possible that the socket will be destroyed, and removed from <ide> // any messages, before ever calling this. In that case, just skip <ide> // it, since something else is destroying this connection anyway. <del>IncomingMessage.prototype.destroy = function(error) { <add>IncomingMessage.prototype.destroy = function destroy(error) { <ide> if (this.socket) <ide> this.socket.destroy(error); <ide> }; <ide> <ide> <del>IncomingMessage.prototype._addHeaderLines = function(headers, n) { <add>IncomingMessage.prototype._addHeaderLines = _addHeaderLines; <add>function _addHeaderLines(headers, n) { <ide> if (headers && headers.length) { <ide> var raw, dest; <ide> if (this.complete) { <ide> IncomingMessage.prototype._addHeaderLines = function(headers, n) { <ide> this._addHeaderLine(k, v, dest); <ide> } <ide> } <del>}; <add>} <ide> <ide> <ide> // Add the given (field, value) pair to the message <ide> IncomingMessage.prototype._addHeaderLines = function(headers, n) { <ide> // multiple values this way. If not, we declare the first instance the winner <ide> // and drop the second. Extended header fields (those beginning with 'x-') are <ide> // always joined. <del>IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { <add>IncomingMessage.prototype._addHeaderLine = _addHeaderLine; <add>function _addHeaderLine(field, value, dest) { <ide> field = field.toLowerCase(); <ide> switch (field) { <ide> // Array headers: <ide> IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { <ide> dest[field] = value; <ide> } <ide> } <del>}; <add>} <ide> <ide> <ide> // Call this instead of resume() if we want to just <ide> // dump all the data to /dev/null <del>IncomingMessage.prototype._dump = function() { <add>IncomingMessage.prototype._dump = function _dump() { <ide> if (!this._dumped) { <ide> this._dumped = true; <ide> this.resume();
1
PHP
PHP
fix failing tests
08cfa33602f796d2114861d5408635005cb4a5b1
<ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> public function beforeRender(EventInterface $event): void <ide> $response->checkNotModified($request) <ide> ) { <ide> $controller->setResponse($response); <del> <ide> $event->stopPropagation(); <add> <add> return; <ide> } <ide> $controller->setResponse($response); <ide> } <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testCheckNotModifiedByEtagStar(): void <ide> <ide> $event = new Event('Controller.beforeRender', $this->Controller); <ide> $requestHandler = new RequestHandlerComponent($this->Controller->components()); <del> $this->assertFalse($requestHandler->beforeRender($event)); <add> $this->assertNull($requestHandler->beforeRender($event)); <add> $this->assertTrue($event->isStopped()); <ide> $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode()); <ide> $this->assertEquals('', (string)$this->Controller->getResponse()->getBody()); <ide> $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-Type'), 'header should not be removed.'); <ide> public function testCheckNotModifiedByEtagExact(): void <ide> $event = new Event('Controller.beforeRender', $this->Controller); <ide> <ide> $requestHandler = new RequestHandlerComponent($this->Controller->components()); <del> $this->assertFalse($requestHandler->beforeRender($event)); <add> $this->assertNull($requestHandler->beforeRender($event)); <add> $this->assertTrue($event->isStopped()); <ide> $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode()); <ide> $this->assertEquals('', (string)$this->Controller->getResponse()->getBody()); <ide> $this->assertFalse($this->Controller->getResponse()->hasHeader('Content-Type')); <ide> public function testCheckNotModifiedByEtagAndTime(): void <ide> <ide> $event = new Event('Controller.beforeRender', $this->Controller); <ide> $requestHandler = new RequestHandlerComponent($this->Controller->components()); <del> $this->assertFalse($requestHandler->beforeRender($event)); <add> $this->assertNull($requestHandler->beforeRender($event)); <add> $this->assertTrue($event->isStopped()); <ide> <ide> $this->assertEquals(304, $this->Controller->getResponse()->getStatusCode()); <ide> $this->assertEquals('', (string)$this->Controller->getResponse()->getBody());
2
Javascript
Javascript
fix jslint error
5773438913ffff104ae1f4907e35f925299090d3
<ide><path>test/parallel/test-sync-io-option.js <ide> if (process.argv[2] === 'child') { <ide> // Prints 4 WARNINGS for --trace-sync-io. 1 for each sync call <ide> // inside readFileSync <ide> assert.equal(cntr1, 4); <del> } else if (execArgv[0] === ' ') <add> } else if (execArgv[0] === ' ') { <ide> assert.equal(cntr1, 0); <del> else <add> } else { <ide> throw new Error('UNREACHABLE'); <add> } <ide> <ide> if (flags.length > 0) <ide> setImmediate(runTest, flags);
1
PHP
PHP
remove another method i missed earlier
6047bb43bdb91883414e3b019586f09ffa5eea3f
<ide><path>src/Core/Plugin.php <ide> public static function configPath(string $name): string <ide> return $plugin->getConfigPath(); <ide> } <ide> <del> /** <del> * Loads the bootstrapping files for a plugin, or calls the initialization setup in the configuration <del> * <del> * @param string $name name of the plugin <del> * @return void <del> * @see \Cake\Core\Plugin::load() for examples of bootstrap configuration <del> * @deprecated 3.7 This method will be removed in 4.0.0. <del> */ <del> public static function bootstrap(string $name): void <del> { <del> deprecationWarning( <del> 'Plugin::bootstrap() is deprecated. ' . <del> 'This method will be removed in 4.0.0.' <del> ); <del> $plugin = static::getCollection()->get($name); <del> if (!$plugin->isEnabled('bootstrap')) { <del> return; <del> } <del> // Disable bootstrapping for this plugin as it will have <del> // been bootstrapped. <del> $plugin->disable('bootstrap'); <del> <del> static::_includeFile( <del> $plugin->getConfigPath() . 'bootstrap.php', <del> true <del> ); <del> } <del> <ide> /** <ide> * Returns true if the plugin $plugin is already loaded. <ide> *
1
Javascript
Javascript
fix global restore
d7f2ce3a9ab4920def12fc561a7c948255257429
<ide><path>index.js <ide> var document = require("jsdom").jsdom("<html><head></head><body></body></html>") <ide> <ide> // stash globals <ide> if ("window" in global) globals.window = global.window; <del>if ("document" in global) globals.document = global.document; <ide> global.window = window; <add>if ("document" in global) globals.document = global.document; <ide> global.document = document; <ide> <ide> // https://github.com/chad3814/CSSStyleDeclaration/issues/3 <ide> module.exports = require("./d3"); <ide> <ide> // restore globals <ide> if ("window" in globals) global.window = globals.window; <add>else delete global.window; <ide> if ("document" in globals) global.document = globals.document; <add>else delete global.document;
1
Ruby
Ruby
fix usage of undefined variable
fa3c55aa650e815ce548e1276845171def2847f4
<ide><path>Library/Homebrew/utils/analytics.rb <ide> def report_analytics_event(category, action, label=analytics_anonymous_prefix_an <ide> <ide> def report_analytics_exception(exception, options={}) <ide> if exception.is_a? BuildError <del> report_analytics_event("BuildError", e.formula.full_name) <add> report_analytics_event("BuildError", exception.formula.full_name) <ide> end <ide> <ide> fatal = options.fetch(:fatal, true) ? "1" : "0"
1
Text
Text
fix minor typo
bf957c6c5096da7887fc0e6df45f8a286cf83202
<ide><path>docs/docs/flux-overview.md <ide> case 'TODO_CREATE': <ide> break; <ide> ``` <ide> <del>The arguments for `waitFor()` are an array of dipatcher registry indexes, and a final callback to invoke after the callbacks at the given indexes have completed. Thus the store that is invoking `waitFor()` can depend on the state of another store to inform how it should update its own state. <add>The arguments for `waitFor()` are an array of dispatcher registry indexes, and a final callback to invoke after the callbacks at the given indexes have completed. Thus the store that is invoking `waitFor()` can depend on the state of another store to inform how it should update its own state. <ide> <ide> A problem arises if we create circular dependencies. If Store A waits for Store B, and B waits for A, then we'll have a very bad situation on our hands. We'll need a more robust dispatcher that flags these circular dependencies with console errors, and this is not easily accomplished with promises. Unfortunately, that's a bit beyond the scope of this documentation. In the future we hope to cover how to build a more robust dispatcher and how to initialize, update, and save the state of the application with persistent data, like a web service API.
1
Mixed
Python
deprecate .model in related routers/permissions
4d8c63abc996bcb44d7a68dd7a7234b0d9f148a0
<ide><path>docs/api-guide/permissions.md <ide> This permission is suitable if you want to your API to allow read permissions to <ide> <ide> ## DjangoModelPermissions <ide> <del>This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. When applied to a view that has a `.model` property, authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. <add>This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that has a `.queryset` property set. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. <ide> <ide> * `POST` requests require the user to have the `add` permission on the model. <ide> * `PUT` and `PATCH` requests require the user to have the `change` permission on the model. <ide> The default behaviour can also be overridden to support custom model permissions <ide> <ide> To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details. <ide> <add>#### Using with views that do not include a `queryset` attribute. <add> <add>If you're using this permission with a view that uses an overridden `get_queryset()` method there may not be a `queryset` attribute on the view. In this case we suggest also marking the view with a sential queryset, so that this class can determine the required permissions. For example: <add> <add> queryset = User.objects.none() # Required for DjangoModelPermissions <add> <ide> ## DjangoModelPermissionsOrAnonReadOnly <ide> <ide> Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API. <ide> Similar to `DjangoModelPermissions`, but also allows unauthenticated users to ha <ide> <ide> This permission class ties into Django's standard [object permissions framework][objectpermissions] that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as [django-guardian][guardian]. <ide> <del>When applied to a view that has a `.model` property, authorization will only be granted if the user *is authenticated* and has the *relevant per-object permissions* and *relevant model permissions* assigned. <add>As with `DjangoModelPermissions`, this permission must only be applied to views that have a `.queryset` property. Authorization will only be granted if the user *is authenticated* and has the *relevant per-object permissions* and *relevant model permissions* assigned. <ide> <ide> * `POST` requests require the user to have the `add` permission on the model instance. <ide> * `PUT` and `PATCH` requests require the user to have the `change` permission on the model instance. <ide><path>docs/api-guide/routers.md <ide> The example above would generate the following URL patterns: <ide> <ide> **Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part. <ide> <del>Typically you won't *need* to specify the `base-name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have any `.model` or `.queryset` attribute set. If you try to register that viewset you'll see an error like this: <add>Typically you won't *need* to specify the `base-name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this: <ide> <del> 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.model' or '.queryset' attribute. <add> 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. <ide> <ide> This means you'll need to explicitly set the `base_name` argument when registering the viewset, as it could not be automatically determined from the model name. <ide> <ide><path>rest_framework/permissions.py <ide> def get_required_permissions(self, method, model_cls): <ide> return [perm % kwargs for perm in self.perms_map[method]] <ide> <ide> def has_permission(self, request, view): <add> # Note that `.model` attribute on views is deprecated, although we <add> # enforce the deprecation on the view `get_serializer_class()` and <add> # `get_queryset()` methods, rather than here. <ide> model_cls = getattr(view, 'model', None) <ide> queryset = getattr(view, 'queryset', None) <ide> <ide><path>rest_framework/routers.py <ide> def get_default_base_name(self, viewset): <ide> If `base_name` is not specified, attempt to automatically determine <ide> it from the viewset. <ide> """ <add> # Note that `.model` attribute on views is deprecated, although we <add> # enforce the deprecation on the view `get_serializer_class()` and <add> # `get_queryset()` methods, rather than here. <ide> model_cls = getattr(viewset, 'model', None) <ide> queryset = getattr(viewset, 'queryset', None) <ide> if model_cls is None and queryset is not None: <ide> model_cls = queryset.model <ide> <ide> assert model_cls, '`base_name` argument not specified, and could ' \ <ide> 'not automatically determine the name from the viewset, as ' \ <del> 'it does not have a `.model` or `.queryset` attribute.' <add> 'it does not have a `.queryset` attribute.' <ide> <ide> return model_cls._meta.object_name.lower() <ide>
4
Go
Go
add support for base path in docker cli -h
47a7f770f42bc0fd9b0a594b72a8f20fb4b874d1
<ide><path>api/client/cli.go <ide> import ( <ide> "fmt" <ide> "io" <ide> "net/http" <add> "net/url" <ide> "reflect" <ide> "strings" <ide> "text/template" <ide> type DockerCli struct { <ide> proto string <ide> // addr holds the client address. <ide> addr string <add> // basePath holds the path to prepend to the requests <add> basePath string <ide> <ide> // configFile has the client configuration file <ide> configFile *cliconfig.ConfigFile <ide> func NewDockerCli(in io.ReadCloser, out, err io.Writer, keyFile string, proto, a <ide> isTerminalIn = false <ide> isTerminalOut = false <ide> scheme = "http" <add> basePath = "" <ide> ) <ide> <ide> if tlsConfig != nil { <ide> func NewDockerCli(in io.ReadCloser, out, err io.Writer, keyFile string, proto, a <ide> fmt.Fprintf(err, "WARNING: Error loading config file:%v\n", e) <ide> } <ide> <add> if proto == "tcp" { <add> // error is checked in pkg/parsers already <add> parsed, _ := url.Parse("tcp://" + addr) <add> addr = parsed.Host <add> basePath = parsed.Path <add> } <add> <ide> return &DockerCli{ <ide> proto: proto, <ide> addr: addr, <add> basePath: basePath, <ide> configFile: configFile, <ide> in: in, <ide> out: out, <ide><path>api/client/hijack.go <ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.Rea <ide> if err != nil { <ide> return err <ide> } <del> req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.Version, path), params) <add> req, err := http.NewRequest(method, fmt.Sprintf("%s/v%s%s", cli.basePath, api.Version, path), params) <ide> if err != nil { <ide> return err <ide> } <ide><path>api/client/utils.go <ide> func (cli *DockerCli) clientRequest(method, path string, in io.Reader, headers m <ide> if expectedPayload && in == nil { <ide> in = bytes.NewReader([]byte{}) <ide> } <del> req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.Version, path), in) <add> req, err := http.NewRequest(method, fmt.Sprintf("%s/v%s%s", cli.basePath, api.Version, path), in) <ide> if err != nil { <ide> return serverResp, err <ide> } <ide><path>pkg/parsers/parsers.go <ide> package parsers <ide> <ide> import ( <ide> "fmt" <add> "net/url" <ide> "runtime" <ide> "strconv" <ide> "strings" <ide> func ParseTCPAddr(addr string, defaultAddr string) (string, error) { <ide> return "", fmt.Errorf("Invalid proto, expected tcp: %s", addr) <ide> } <ide> <del> hostParts := strings.Split(addr, ":") <add> u, err := url.Parse("tcp://" + addr) <add> if err != nil { <add> return "", err <add> } <add> hostParts := strings.Split(u.Host, ":") <ide> if len(hostParts) != 2 { <ide> return "", fmt.Errorf("Invalid bind address format: %s", addr) <ide> } <ide> func ParseTCPAddr(addr string, defaultAddr string) (string, error) { <ide> if err != nil && p == 0 { <ide> return "", fmt.Errorf("Invalid bind address format: %s", addr) <ide> } <del> return fmt.Sprintf("tcp://%s:%d", host, p), nil <add> return fmt.Sprintf("tcp://%s:%d%s", host, p, u.Path), nil <ide> } <ide> <ide> // Get a repos name and returns the right reposName + tag|digest <ide><path>pkg/parsers/parsers_test.go <ide> func TestParseHost(t *testing.T) { <ide> "0.0.0.0": "Invalid bind address format: 0.0.0.0", <ide> "tcp://": "Invalid proto, expected tcp: ", <ide> "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d", <add> "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path", <ide> "udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1", <ide> "udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375", <ide> } <ide> valids := map[string]string{ <del> "0.0.0.1:5555": "tcp://0.0.0.1:5555", <del> ":6666": "tcp://127.0.0.1:6666", <del> "tcp://:7777": "tcp://127.0.0.1:7777", <del> "": "unix:///var/run/docker.sock", <add> "0.0.0.1:5555": "tcp://0.0.0.1:5555", <add> "0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path", <add> ":6666": "tcp://127.0.0.1:6666", <add> ":6666/path": "tcp://127.0.0.1:6666/path", <add> "tcp://:7777": "tcp://127.0.0.1:7777", <add> "tcp://:7777/path": "tcp://127.0.0.1:7777/path", <add> "": "unix:///var/run/docker.sock", <ide> "unix:///run/docker.sock": "unix:///run/docker.sock", <ide> "unix://": "unix:///var/run/docker.sock", <ide> "fd://": "fd://",
5
Javascript
Javascript
remove unused variables from tls tests
3d2356762296ee6bf8fc98a7d8e4d07cbac278d1
<ide><path>test/parallel/test-tls-0-dns-altname.js <ide> if (!common.hasCrypto) { <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <del>var net = require('net'); <ide> <ide> var common = require('../common'); <ide> <ide><path>test/parallel/test-tls-async-cb-after-socket-end.js <ide> <ide> var common = require('../common'); <ide> <del>var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <ide> var constants = require('constants'); <ide><path>test/parallel/test-tls-client-default-ciphers.js <ide> function test1() { <ide> }; <ide> <ide> try { <del> var s = tls.connect(common.PORT); <add> tls.connect(common.PORT); <ide> } catch (e) { <ide> assert(e instanceof Done); <ide> } <ide><path>test/parallel/test-tls-close-error.js <ide> if (!common.hasCrypto) { <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <del>var net = require('net'); <ide> <ide> var errorCount = 0; <ide> var closeCount = 0; <ide><path>test/parallel/test-tls-close-notify.js <ide> if (!common.hasCrypto) { <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <del>var net = require('net'); <ide> <ide> var ended = 0; <ide> <ide><path>test/parallel/test-tls-connect-secure-context.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> console.log('1..0 # Skipped: missing crypto'); <ide><path>test/parallel/test-tls-destroy-whilst-write.js <ide> 'use strict'; <del>var assert = require('assert'); <ide> var common = require('../common'); <ide> <ide> if (!common.hasCrypto) { <ide><path>test/parallel/test-tls-fast-writing.js <ide> var server = tls.createServer(options, onconnection); <ide> var gotChunk = false; <ide> var gotDrain = false; <ide> <del>var timer = setTimeout(function() { <add>setTimeout(function() { <ide> console.log('not ok - timed out'); <ide> process.exit(1); <ide> }, common.platformTimeout(500)); <ide><path>test/parallel/test-tls-handshake-error.js <ide> if (!common.hasCrypto) { <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <del>var net = require('net'); <ide> <ide> var errorCount = 0; <ide> var closeCount = 0; <ide><path>test/parallel/test-tls-handshake-nohang.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> console.log('1..0 # Skipped: missing crypto'); <ide><path>test/parallel/test-tls-invoke-queued.js <ide> if (!common.hasCrypto) { <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <del>var net = require('net'); <ide> <ide> <ide> var received = ''; <ide><path>test/parallel/test-tls-key-mismatch.js <ide> var options = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') <ide> }; <ide> <del>var cert = null; <del> <ide> assert.throws(function() { <ide> tls.createSecureContext(options); <ide> }); <ide><path>test/parallel/test-tls-legacy-onselect.js <ide> function filenamePEM(n) { <ide> return require('path').join(common.fixturesDir, 'keys', n + '.pem'); <ide> } <ide> <del>function loadPEM(n) { <del> return fs.readFileSync(filenamePEM(n)); <del>} <del> <ide> var server = net.Server(function(raw) { <ide> var pair = tls.createSecurePair(null, true, false, false); <ide> pair.on('error', function() {}); <ide><path>test/parallel/test-tls-max-send-fragment.js <ide> if (!common.hasCrypto) { <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <del>var net = require('net'); <ide> <ide> var common = require('../common'); <ide> <ide><path>test/parallel/test-tls-ocsp-callback.js <ide> function test(testOptions, cb) { <ide> var clientSecure = 0; <ide> var ocspCount = 0; <ide> var ocspResponse; <del> var session; <ide> <ide> if (testOptions.pfx) { <ide> delete options.key; <ide><path>test/parallel/test-tls-peer-certificate-encoding.js <ide> var tls = require('tls'); <ide> var fs = require('fs'); <ide> var util = require('util'); <ide> var join = require('path').join; <del>var spawn = require('child_process').spawn; <ide> <ide> var options = { <ide> key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-key.pem')), <ide><path>test/parallel/test-tls-peer-certificate-multi-keys.js <ide> var tls = require('tls'); <ide> var fs = require('fs'); <ide> var util = require('util'); <ide> var join = require('path').join; <del>var spawn = require('child_process').spawn; <ide> <ide> var options = { <ide> key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), <ide><path>test/parallel/test-tls-peer-certificate.js <ide> var tls = require('tls'); <ide> var fs = require('fs'); <ide> var util = require('util'); <ide> var join = require('path').join; <del>var spawn = require('child_process').spawn; <ide> <ide> var options = { <ide> key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-key.pem')), <ide><path>test/parallel/test-tls-request-timeout.js <ide> var server = tls.Server(options, function(socket) { <ide> }); <ide> <ide> server.listen(common.PORT, function() { <del> var socket = tls.connect({ <add> tls.connect({ <ide> port: common.PORT, <ide> rejectUnauthorized: false <ide> }); <ide><path>test/parallel/test-tls-socket-default-options.js <ide> if (!common.hasCrypto) { <ide> const tls = require('tls'); <ide> <ide> const fs = require('fs'); <del>const net = require('net'); <ide> <ide> const sent = 'hello world'; <ide> <ide><path>test/parallel/test-tls-ticket-cluster.js <ide> if (cluster.isMaster) { <ide> <ide> function fork() { <ide> var worker = cluster.fork(); <del> var workerReqCount = 0; <ide> worker.on('message', function(msg) { <ide> console.error('[master] got %j', msg); <ide> if (msg === 'reused') {
21
Javascript
Javascript
implement the `detach` method
1a05daf5dc67813528afdb88086766dc22b6c0df
<ide><path>src/jqLite.js <ide> * - [`contents()`](http://api.jquery.com/contents/) <ide> * - [`css()`](http://api.jquery.com/css/) <ide> * - [`data()`](http://api.jquery.com/data/) <add> * - [`detach()`](http://api.jquery.com/detach/) <ide> * - [`empty()`](http://api.jquery.com/empty/) <ide> * - [`eq()`](http://api.jquery.com/eq/) <ide> * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name <ide> function jqLiteEmpty(element) { <ide> } <ide> } <ide> <add>function jqLiteRemove(element, keepData) { <add> if (!keepData) jqLiteDealoc(element); <add> var parent = element.parentNode; <add> if (parent) parent.removeChild(element); <add>} <add> <ide> ////////////////////////////////////////// <ide> // Functions which are declared directly. <ide> ////////////////////////////////////////// <ide> forEach({ <ide> return jqLiteInheritedData(element, '$injector'); <ide> }, <ide> <del> removeAttr: function(element,name) { <add> removeAttr: function(element, name) { <ide> element.removeAttribute(name); <ide> }, <ide> <ide> forEach({ <ide> wrapNode.appendChild(element); <ide> }, <ide> <del> remove: function(element) { <del> jqLiteDealoc(element); <del> var parent = element.parentNode; <del> if (parent) parent.removeChild(element); <add> remove: jqLiteRemove, <add> <add> detach: function(element) { <add> jqLiteRemove(element, true); <ide> }, <ide> <ide> after: function(element, newElement) { <ide><path>test/jqLiteSpec.js <ide> describe('jqLite', function() { <ide> })); <ide> <ide> <add> it('should keep data if an element is removed via detach()', function() { <add> var root = jqLite('<div><span>abc</span></div>'), <add> span = root.find('span'), <add> data = span.data(); <add> <add> span.data('foo', 'bar'); <add> span.detach(); <add> <add> expect(data).toEqual({foo: 'bar'}); <add> <add> span.remove(); <add> }); <add> <add> <ide> it('should retrieve all data if called without params', function() { <ide> var element = jqLite(a); <ide> expect(element.data()).toEqual({}); <ide> describe('jqLite', function() { <ide> }); <ide> <ide> <add> describe('detach', function() { <add> it('should detach', function() { <add> var root = jqLite('<div><span>abc</span></div>'); <add> var span = root.find('span'); <add> expect(span.detach()).toEqual(span); <add> expect(root.html()).toEqual(''); <add> }); <add> }); <add> <add> <ide> describe('after', function() { <ide> it('should after', function() { <ide> var root = jqLite('<div><span></span></div>');
2
Ruby
Ruby
remove unnecessary path parameters
f7233b27f2683560fed58ee9accb95ad43b0a148
<ide><path>activerecord/lib/active_record/associations.rb <ide> module Associations # :nodoc: <ide> <ide> # These classes will be loaded when associations are created. <ide> # So there is no need to eager load them. <del> autoload :Association, 'active_record/associations/association' <del> autoload :SingularAssociation, 'active_record/associations/singular_association' <del> autoload :CollectionAssociation, 'active_record/associations/collection_association' <del> autoload :ForeignAssociation, 'active_record/associations/foreign_association' <del> autoload :CollectionProxy, 'active_record/associations/collection_proxy' <add> autoload :Association <add> autoload :SingularAssociation <add> autoload :CollectionAssociation <add> autoload :ForeignAssociation <add> autoload :CollectionProxy <ide> <del> autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association' <del> autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association' <del> autoload :HasManyAssociation, 'active_record/associations/has_many_association' <del> autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association' <del> autoload :HasOneAssociation, 'active_record/associations/has_one_association' <del> autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association' <del> autoload :ThroughAssociation, 'active_record/associations/through_association' <add> autoload :BelongsToAssociation <add> autoload :BelongsToPolymorphicAssociation <add> autoload :HasManyAssociation <add> autoload :HasManyThroughAssociation <add> autoload :HasOneAssociation <add> autoload :HasOneThroughAssociation <add> autoload :ThroughAssociation <ide> <ide> module Builder #:nodoc: <ide> autoload :Association, 'active_record/associations/builder/association' <ide> module Builder #:nodoc: <ide> end <ide> <ide> eager_autoload do <del> autoload :Preloader, 'active_record/associations/preloader' <del> autoload :JoinDependency, 'active_record/associations/join_dependency' <del> autoload :AssociationScope, 'active_record/associations/association_scope' <del> autoload :AliasTracker, 'active_record/associations/alias_tracker' <add> autoload :Preloader <add> autoload :JoinDependency <add> autoload :AssociationScope <add> autoload :AliasTracker <ide> end <ide> <ide> # Returns the association instance for the given name, instantiating it if it doesn't already exist
1
PHP
PHP
fix "@since" tag
a120ac6e0d83896b47e624986a9e0d0e8d96e6c6
<ide><path>tests/TestCase/Http/Middleware/SessionCsrfProtectionMiddlewareTest.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 3.5.0 <add> * @since 4.2.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> namespace Cake\Test\TestCase\Http\Middleware;
1
Javascript
Javascript
avoid recursion for nested plain objects
8c594a61c1d169689c5877181054598af9769ff4
<ide><path>lib/serialization/PlainObjectSerializer.js <ide> <ide> "use strict"; <ide> <add>const writeObject = (obj, write, values) => { <add> const keys = Object.keys(obj); <add> for (const key of keys) { <add> const value = obj[key]; <add> if ( <add> value !== null && <add> typeof value === "object" && <add> value.constructor && <add> value.constructor === Object <add> ) { <add> // nested object <add> write(true); <add> write(key); <add> writeObject(value, write, values); <add> write(false); <add> } else { <add> write(key); <add> values.push(value); <add> } <add> } <add>}; <add> <ide> class PlainObjectSerializer { <ide> serialize(obj, { write }) { <ide> if (Array.isArray(obj)) { <ide> class PlainObjectSerializer { <ide> write(item); <ide> } <ide> } else { <del> const keys = Object.keys(obj); <del> for (const key of keys) { <del> write(key); <del> } <add> const values = []; <add> writeObject(obj, write, values); <ide> write(null); <del> for (const key of keys) { <del> write(obj[key]); <add> for (const value of values) { <add> write(value); <ide> } <ide> } <ide> } <ide> class PlainObjectSerializer { <ide> } <ide> return array; <ide> } else { <del> const obj = {}; <ide> const keys = []; <add> let hasNested = key === true; <ide> while (key !== null) { <ide> keys.push(key); <ide> key = read(); <add> if (key === true) { <add> hasNested = true; <add> } <ide> } <del> for (const key of keys) { <del> obj[key] = read(); <add> let currentObj = {}; <add> const stack = hasNested && []; <add> for (let i = 0; i < keys.length; i++) { <add> const key = keys[i]; <add> if (key === true) { <add> // enter nested object <add> const objectKey = keys[++i]; <add> const newObj = {}; <add> currentObj[objectKey] = newObj; <add> stack.push(currentObj); <add> currentObj = newObj; <add> } else if (key === false) { <add> // leave nested object <add> currentObj = stack.pop(); <add> } else { <add> currentObj[key] = read(); <add> } <ide> } <del> return obj; <add> return currentObj; <ide> } <ide> } <ide> }
1
Python
Python
handle fortran compiler on open-solaris
bc3cfee0148369b1a58cc8b2490c0be5cc1feb18
<ide><path>numpy/distutils/command/scons.py <ide> def dist2sconsfc(compiler): <ide> return 'g77' <ide> elif compiler.compiler_type == 'gnu95': <ide> return 'gfortran' <add> elif compiler.compiler_type == 'sun': <add> return 'sunf77' <ide> else: <ide> # XXX: Just give up for now, and use generic fortran compiler <ide> return 'fortran'
1
Java
Java
fix failing tests
bbd3f902d0ed2c309623f62f760ef63c15282141
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageDeliveryException; <ide> import org.springframework.messaging.converter.MessageConversionException; <add>import org.springframework.messaging.converter.StringMessageConverter; <ide> import org.springframework.messaging.simp.stomp.StompSession.Receiptable; <ide> import org.springframework.messaging.simp.stomp.StompSession.Subscription; <ide> import org.springframework.messaging.support.MessageBuilder; <ide> public void setUp() throws Exception { <ide> this.sessionHandler = mock(StompSessionHandler.class); <ide> this.connectHeaders = new StompHeaders(); <ide> this.session = new DefaultStompSession(this.sessionHandler, this.connectHeaders); <add> this.session.setMessageConverter(new StringMessageConverter()); <ide> <ide> SettableListenableFuture<Void> future = new SettableListenableFuture<>(); <ide> future.set(null);
1
Python
Python
ensure path on read_json
070e026ed98f4c016ab9ff2c355b4bd9d7c807c1
<ide><path>spacy/util.py <ide> def read_json(location): <ide> location (Path): Path to JSON file. <ide> RETURNS (dict): Loaded JSON content. <ide> """ <add> location = ensure_path(location) <ide> with location.open('r', encoding='utf8') as f: <ide> return ujson.load(f) <ide>
1
Mixed
Javascript
remove unused err_socket_cannot_send error
331d63624007be4bf49d6d161bdef2b5e540affa
<ide><path>doc/api/errors.md <ide> value. <ide> While using [`dgram.createSocket()`][], the size of the receive or send `Buffer` <ide> could not be determined. <ide> <del><a id="ERR_SOCKET_CANNOT_SEND"></a> <del>### `ERR_SOCKET_CANNOT_SEND` <del> <del>Data could be sent on a socket. <del> <ide> <a id="ERR_SOCKET_CLOSED"></a> <ide> ### `ERR_SOCKET_CLOSED` <ide> <ide> removed: v10.0.0 <ide> <ide> The `repl` module was unable to parse data from the REPL history file. <ide> <add><a id="ERR_SOCKET_CANNOT_SEND"></a> <add>### `ERR_SOCKET_CANNOT_SEND` <add><!-- YAML <add>added: v9.0.0 <add>removed: REPLACEME <add>--> <add> <add>Data could be sent on a socket. <add> <ide> <a id="ERR_STDERR_CLOSE"></a> <ide> ### `ERR_STDERR_CLOSE` <ide> <!-- YAML <ide><path>lib/internal/errors.js <ide> E('ERR_SOCKET_BAD_TYPE', <ide> E('ERR_SOCKET_BUFFER_SIZE', <ide> 'Could not get or set buffer size', <ide> SystemError); <del>E('ERR_SOCKET_CANNOT_SEND', 'Unable to send data', Error); <ide> E('ERR_SOCKET_CLOSED', 'Socket is closed', Error); <ide> E('ERR_SOCKET_DGRAM_IS_CONNECTED', 'Already connected', Error); <ide> E('ERR_SOCKET_DGRAM_NOT_CONNECTED', 'Not connected', Error);
2
Javascript
Javascript
fix path for windows machines
0c2e45acc3b8d99d3176b8b82fbffe6bed67de68
<ide><path>gulpfile.js <ide> gulp.task('serve', function(cb) { <ide> script: paths.server, <ide> ext: '.js .json', <ide> ignore: paths.serverIgnore, <del> exec: './node_modules/.bin/babel-node', <add> exec: path.join(__dirname, 'node_modules/.bin/babel-node'), <ide> env: { <ide> 'NODE_ENV': 'development', <ide> 'DEBUG': process.env.DEBUG || 'freecc:*'
1
Javascript
Javascript
add sectionseparatorcomponent support
a141e63ee44dea0cf782e4a383410af3e50b19a2
<ide><path>Examples/UIExplorer/js/SectionListExample.js <ide> const { <ide> renderSmallSwitchOption, <ide> } = require('./ListExampleShared'); <ide> <del>const SectionHeaderComponent = ({section}) => <add>const SectionHeaderComponent = ({section}) => ( <ide> <View> <ide> <Text style={styles.headerText}>SECTION HEADER: {section.key}</Text> <ide> <SeparatorComponent /> <del> </View>; <add> </View> <add>); <add> <add>const SectionSeparatorComponent = () => ( <add> <View> <add> <SeparatorComponent /> <add> <Text style={styles.sectionSeparatorText}>SECTION SEPARATOR</Text> <add> <SeparatorComponent /> <add> </View> <add>); <ide> <ide> class SectionListExample extends React.PureComponent { <ide> static title = '<SectionList>'; <ide> class SectionListExample extends React.PureComponent { <ide> FooterComponent={FooterComponent} <ide> ItemComponent={this._renderItemComponent} <ide> SectionHeaderComponent={SectionHeaderComponent} <add> SectionSeparatorComponent={SectionSeparatorComponent} <ide> SeparatorComponent={SeparatorComponent} <ide> enableVirtualization={this.state.virtualized} <ide> onRefresh={() => alert('onRefresh: nothing to refresh :P')} <ide> onViewableItemsChanged={this._onViewableItemsChanged} <ide> refreshing={false} <del> shouldItemUpdate={(prev, next) => prev.item !== next.item} <ide> sections={[ <ide> {ItemComponent: StackedItemComponent, key: 's1', data: [ <ide> {title: 'Item In Header Section', text: 's1', key: '0'} <ide> const styles = StyleSheet.create({ <ide> searchRow: { <ide> paddingHorizontal: 10, <ide> }, <add> sectionSeparatorText: { <add> color: 'gray', <add> alignSelf: 'center', <add> padding: 4, <add> fontWeight: 'bold', <add> }, <ide> }); <ide> <ide> module.exports = SectionListExample; <ide><path>Libraries/Experimental/SectionList.js <ide> type SectionItem = any; <ide> <ide> type SectionBase = { <ide> // Must be provided directly on each section. <del> data: ?Array<SectionItem>, <add> data: Array<SectionItem>, <ide> key: string, <ide> <ide> // Optional props will override list-wide props just for this section. <ide> type OptionalProps<SectionT: SectionBase> = { <ide> * Rendered at the top of each section. In the future, a sticky option will be added. <ide> */ <ide> SectionHeaderComponent?: ?ReactClass<{section: SectionT}>, <add> /** <add> * Rendered at the bottom of every Section, except the very last one, in place of the normal <add> * SeparatorComponent. <add> */ <add> SectionSeparatorComponent?: ?ReactClass<*>, <ide> /** <ide> * Rendered at the bottom of every Item except the very last one in the last section. <ide> */ <ide> type OptionalProps<SectionT: SectionBase> = { <ide> * Set this true while waiting for new data from a refresh. <ide> */ <ide> refreshing?: boolean, <add> /** <add> * This is an optional optimization to minimize re-rendering items. <add> */ <add> shouldItemUpdate?: ( <add> prevProps: {item: Item, index: number}, <add> nextProps: {item: Item, index: number} <add> ) => boolean, <ide> }; <ide> <ide> type Props<SectionT> = RequiredProps<SectionT> & OptionalProps<SectionT>; <ide><path>Libraries/Experimental/VirtualizedSectionList.js <ide> type SectionItem = any; <ide> <ide> type Section = { <ide> // Must be provided directly on each section. <del> data: ?Array<SectionItem>, <add> data: Array<SectionItem>, <ide> key: string, <del> /** <del> * Stick whatever you want here, e.g. meta data for rendering section headers. <del> */ <del> extra?: any, <ide> <ide> // Optional props will override list-wide props just for this section. <ide> ItemComponent?: ?ReactClass<{item: SectionItem, index: number}>, <ide> type RequiredProps = { <ide> type OptionalProps = { <ide> ItemComponent?: ?ReactClass<{item: Item, index: number}>, <ide> SectionHeaderComponent?: ?ReactClass<{section: Section}>, <add> SectionSeparatorComponent?: ?ReactClass<*>, <ide> SeparatorComponent?: ?ReactClass<*>, <ide> /** <ide> * Warning: Virtualization can drastically improve memory consumption for long lists, but trashes <ide> class VirtualizedSectionList extends React.PureComponent { <ide> }; <ide> <ide> _keyExtractor = (item: Item, index: number) => { <del> const info = this._subExtractor(item, index); <add> const info = this._subExtractor(index); <ide> return info && info.key; <ide> }; <ide> <ide> _subExtractor( <del> item, <ide> index: number, <ide> ): ?{ <ide> section: Section, <ide> class VirtualizedSectionList extends React.PureComponent { <ide> <ide> _convertViewable = (viewable: Viewable): ?Viewable => { <ide> invariant(viewable.index != null, 'Received a broken Viewable'); <del> const info = this._subExtractor(viewable.item, viewable.index); <add> const info = this._subExtractor(viewable.index); <ide> if (!info) { <ide> return null; <ide> } <ide> class VirtualizedSectionList extends React.PureComponent { <ide> } <ide> <ide> _isItemSticky = (item, index) => { <del> const info = this._subExtractor(item, index); <add> const info = this._subExtractor(index); <ide> return info && info.index == null; <ide> }; <ide> <ide> _renderItem = ({item, index}: {item: Item, index: number}) => { <del> const info = this._subExtractor(item, index); <add> const info = this._subExtractor(index); <ide> if (!info) { <ide> return null; <ide> } else if (info.index == null) { <ide> return <this.props.SectionHeaderComponent section={info.section} />; <ide> } else { <ide> const ItemComponent = info.section.ItemComponent || this.props.ItemComponent; <ide> const SeparatorComponent = info.section.SeparatorComponent || this.props.SeparatorComponent; <add> const {SectionSeparatorComponent} = this.props; <add> const [shouldRenderSectionSeparator, shouldRenderItemSeparator] = <add> this._shouldRenderSeparators(index, info); <ide> return ( <ide> <View> <ide> <ItemComponent item={item} index={info.index} /> <del> {SeparatorComponent && index < this.state.childProps.getItemCount() - 1 <del> ? <SeparatorComponent /> <del> : null <del> } <add> {shouldRenderItemSeparator ? <SeparatorComponent /> : null} <add> {shouldRenderSectionSeparator ? <SectionSeparatorComponent /> : null} <ide> </View> <ide> ); <ide> } <ide> }; <ide> <add> _shouldRenderSeparators(index: number, info?: ?Object): [boolean, boolean] { <add> info = info || this._subExtractor(index); <add> if (!info) { <add> return [false, false]; <add> } <add> const SeparatorComponent = info.section.SeparatorComponent || this.props.SeparatorComponent; <add> const {SectionSeparatorComponent} = this.props; <add> const lastItemIndex = this.state.childProps.getItemCount() - 1; <add> let shouldRenderSectionSeparator = false; <add> if (SectionSeparatorComponent) { <add> shouldRenderSectionSeparator = <add> info.index === info.section.data.length - 1 && index < lastItemIndex; <add> } <add> const shouldRenderItemSeparator = SeparatorComponent && !shouldRenderSectionSeparator && <add> index < lastItemIndex; <add> return [shouldRenderSectionSeparator, shouldRenderItemSeparator]; <add> } <add> <add> _shouldItemUpdate = (prev, next) => { <add> const {shouldItemUpdate} = this.props; <add> if (!shouldItemUpdate || shouldItemUpdate(prev, next)) { <add> return true; <add> } <add> if (prev.index !== next.index) { <add> const [secSepPrev, itSepPrev] = this._shouldRenderSeparators(prev.index); <add> const [secSepNext, itSepNext] = this._shouldRenderSeparators(next.index); <add> if (secSepPrev !== secSepNext || itSepPrev !== itSepNext) { <add> return true; <add> } <add> } <add> } <add> <ide> _computeState(props: Props) { <ide> const itemCount = props.sections.reduce((v, section) => v + section.data.length + 1, 0); <ide> return { <ide> class VirtualizedSectionList extends React.PureComponent { <ide> keyExtractor: this._keyExtractor, <ide> onViewableItemsChanged: <ide> props.onViewableItemsChanged ? this._onViewableItemsChanged : undefined, <add> shouldItemUpdate: this._shouldItemUpdate, <ide> }, <ide> }; <ide> }
3
Javascript
Javascript
add support for image xobjs with imagemask
62afa95fe10cde938412911374c33afbf3d3a816
<ide><path>pdf.js <ide> var PartialEvaluator = (function() { <ide> args = [ objId, w, h ]; <ide> } else { <ide> // Needs to be rendered ourself. <del> var inline = false; <del> var imageObj = new PDFImage(xref, resources, image, inline); <add> <add> // Figure out if the image has an imageMask. <add> var imageMask = dict.get('ImageMask', 'IM') || false; <add> <add> // If there is no imageMask, create the PDFImage and a lot <add> // of image processing can be done here. <add> if (!imageMask) { <add> var inline = false; <add> var imageObj = new PDFImage(xref, resources, image, inline); <ide> <del> if (imageObj.imageMask) { <del> throw "Can't handle this in the web worker :/"; <add> if (imageObj.imageMask) { <add> throw "Can't handle this in the web worker :/"; <add> } <add> <add> var imgData = { <add> width: w, <add> height: h, <add> data: new Uint8Array(w * h * 4) <add> }; <add> var pixels = imgData.data; <add> imageObj.fillRgbaBuffer(pixels, imageObj.decode); <add> <add> fn = "paintReadyImageXObject"; <add> args = [ imgData ]; <add> } else /* imageMask == true */ { <add> // This depends on a tmpCanvas beeing filled with the <add> // current fillStyle, such that processing the pixel <add> // data can't be done here. Instead of creating a <add> // complete PDFImage, only read the information needed <add> // for later. <add> fn = "paintReadyImageMaskXObject"; <add> <add> var width = dict.get('Width', 'W'); <add> var height = dict.get('Height', 'H'); <add> var bitStrideLength = (width + 7) >> 3; <add> var imgArray = image.getBytes(bitStrideLength * height); <add> var decode = dict.get('Decode', 'D'); <add> var inverseDecode = !!imageObj.decode && imageObj.decode[0] > 0; <add> <add> args = [ imgArray, inverseDecode, width, height ]; <ide> } <del> <del> var imgData = { <del> width: w, <del> height: h, <del> data: new Uint8Array(w * h * 4) <del> }; <del> var pixels = imgData.data; <del> imageObj.fillRgbaBuffer(pixels, imageObj.decode); <del> <del> fn = "paintReadyImageXObject"; <del> args = [ imgData ]; <ide> } <ide> } else { <ide> error('Unhandled XObject subtype ' + type.name); <ide> var CanvasGraphics = (function() { <ide> this.restore(); <ide> }, <ide> <add> paintReadyImageMaskXObject: function(imgArray, inverseDecode, width, height) { <add> function applyStencilMask(buffer, inverseDecode) { <add> var imgArrayPos = 0; <add> var i, j, mask, buf; <add> // removing making non-masked pixels transparent <add> var bufferPos = 3; // alpha component offset <add> for (i = 0; i < height; i++) { <add> mask = 0; <add> for (j = 0; j < width; j++) { <add> if (!mask) { <add> buf = imgArray[imgArrayPos++]; <add> mask = 128; <add> } <add> if (!(buf & mask) == inverseDecode) { <add> buffer[bufferPos] = 0; <add> } <add> bufferPos += 4; <add> mask >>= 1; <add> } <add> } <add> } <add> <add> this.save(); <add> <add> var ctx = this.ctx; <add> var w = width, h = height; <add> <add> // scale the image to the unit square <add> ctx.scale(1 / w, -1 / h); <add> <add> var tmpCanvas = new this.ScratchCanvas(w, h); <add> var tmpCtx = tmpCanvas.getContext('2d'); <add> var fillColor = this.current.fillColor; <add> <add> tmpCtx.fillStyle = (fillColor && fillColor.type === 'Pattern') ? <add> fillColor.getPattern(tmpCtx) : fillColor; <add> tmpCtx.fillRect(0, 0, w, h); <add> <add> var imgData = tmpCtx.getImageData(0, 0, w, h); <add> var pixels = imgData.data; <add> <add> applyStencilMask(pixels, inverseDecode); <add> <add> tmpCtx.putImageData(imgData, 0, 0); <add> ctx.drawImage(tmpCanvas, 0, -h); <add> this.restore(); <add> }, <add> <ide> paintReadyImageXObject: function(imgData) { <ide> this.save(); <ide> <ide> var CanvasGraphics = (function() { <ide> // Copy over the imageData. <ide> var tmpImgDataPixels = tmpImgData.data; <ide> var len = tmpImgDataPixels.length; <add> <add> // TODO: There got to be a better way to copy an ImageData array <add> // then coping over all the bytes one by one :/ <ide> while (len--) <ide> tmpImgDataPixels[len] = imgData.data[len]; <ide> <ide> var PDFImage = (function() { <ide> } <ide> return buf; <ide> }, <del> applyStencilMask: function applyStencilMask(buffer, inverseDecode) { <del> var width = this.width, height = this.height; <del> var bitStrideLength = (width + 7) >> 3; <del> var imgArray = this.image.getBytes(bitStrideLength * height); <del> var imgArrayPos = 0; <del> var i, j, mask, buf; <del> // removing making non-masked pixels transparent <del> var bufferPos = 3; // alpha component offset <del> for (i = 0; i < height; i++) { <del> mask = 0; <del> for (j = 0; j < width; j++) { <del> if (!mask) { <del> buf = imgArray[imgArrayPos++]; <del> mask = 128; <del> } <del> if (!(buf & mask) == inverseDecode) { <del> buffer[bufferPos] = 0; <del> } <del> bufferPos += 4; <del> mask >>= 1; <del> } <del> } <del> }, <ide> fillRgbaBuffer: function fillRgbaBuffer(buffer, decodeMap) { <ide> var numComps = this.numComps; <ide> var width = this.width;
1
Text
Text
add a reference to the list of openssl flags
d3d4aceb96fced82710e1cdb3dfc7224f830df48
<ide><path>doc/api/crypto.md <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> <ide> ### Other OpenSSL constants <ide> <add>See the [list of SSL OP Flags][] for details. <add> <ide> <table> <ide> <tr> <ide> <th>Constant</th> <ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. <ide> [scrypt]: https://en.wikipedia.org/wiki/Scrypt <ide> [stream-writable-write]: stream.html#stream_writable_write_chunk_encoding_callback <ide> [stream]: stream.html <add>[list of SSL OP Flags]: wiki.openssl.org/index.php/List_of_SSL_OP_Flags#Table_of_Options
1
Python
Python
fix gpt2config parameters in gpt2modeltester
b518aaf193938247f698a7c4522afe42b025225a
<ide><path>tests/test_modeling_gpt2.py <ide> def get_config(self, gradient_checkpointing=False): <ide> n_embd=self.hidden_size, <ide> n_layer=self.num_hidden_layers, <ide> n_head=self.num_attention_heads, <del> intermediate_size=self.intermediate_size, <del> hidden_act=self.hidden_act, <del> hidden_dropout_prob=self.hidden_dropout_prob, <del> attention_probs_dropout_prob=self.attention_probs_dropout_prob, <add> n_inner=self.intermediate_size, <add> activation_function=self.hidden_act, <add> resid_pdrop=self.hidden_dropout_prob, <add> attn_pdrop=self.attention_probs_dropout_prob, <ide> n_positions=self.max_position_embeddings, <ide> n_ctx=self.max_position_embeddings, <ide> type_vocab_size=self.type_vocab_size,
1
Javascript
Javascript
add ios 12 textcontenttype options
644fc57fad4b163e96c3b3d6ec441c7b566d2d43
<ide><path>Libraries/Components/TextInput/TextInput.js <ide> type IOSProps = $ReadOnly<{| <ide> | 'telephoneNumber' <ide> | 'username' <ide> | 'password' <add> | 'newPassword' <add> | 'oneTimeCode' <ide> ), <ide> scrollEnabled?: ?boolean, <ide> |}>; <ide> const TextInput = createReactClass({ <ide> 'telephoneNumber', <ide> 'username', <ide> 'password', <add> 'newPassword', <add> 'oneTimeCode', <ide> ]), <ide> }, <ide> getDefaultProps(): Object {
1
Text
Text
add changelog entry for [ci skip]
2b2e04150680498f043720de34f82e6dc647c14a
<ide><path>activesupport/CHANGELOG.md <add>* Deprecate `capture` and `quietly`. <add> <add> These methods are not thread safe and may cause issues when used in threaded environments. <add> To avoid problems we are deprecating them. <add> <add> *Tom Meier* <add> <ide> * `DateTime#to_f` now preserves the fractional seconds instead of always <ide> rounding to `.0`. <ide>
1
Text
Text
add a readme
b905b41285e0919928ba18887ccc7504ff67b13d
<ide><path>neural_programmer/README.md <add>Implementation of the Neural Programmer model described in https://openreview.net/pdf?id=ry2YOrcge <add> <add>Download the data from http://www-nlp.stanford.edu/software/sempre/wikitable/ Change the data_dir FLAG to the location of the data <add> <add>Training: python neural_programmer.py <add> <add>The models are written to FLAGS.output_dir <add> <add>Testing: python neural_programmer.py --evaluator_job=True <add> <add>The models are loaded from FLAGS.output_dir. The evaluation is done on development data. <add> <add>Maintained by Arvind Neelakantan (arvind2505)
1
Text
Text
add common.wpt to test readme
3fffebbde3221323d45f72a22a936120fe43de58
<ide><path>test/README.md <ide> The realpath of the 'tmp' directory. <ide> * return [&lt;String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) <ide> <ide> Name of the temp directory used by tests. <add> <add>### WPT <add> <add>A port of parts of <add>[W3C testharness.js](https://github.com/w3c/testharness.js) for testing the <add>Node.js <add>[WHATWG URL API](https://nodejs.org/api/url.html#url_the_whatwg_url_api) <add>implementation with tests from <add>[W3C Web Platform Tests](https://github.com/w3c/web-platform-tests).
1
Java
Java
simplify use of headers for sockjsclient requests
b7bdd724b2eab6959eade7868cfb1ecf21aa118b
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/AbstractXhrTransport.java <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpStatus; <del>import org.springframework.http.MediaType; <ide> import org.springframework.http.ResponseEntity; <ide> import org.springframework.util.concurrent.ListenableFuture; <ide> import org.springframework.util.concurrent.SettableListenableFuture; <ide> public abstract class AbstractXhrTransport implements XhrTransport { <ide> <ide> private HttpHeaders requestHeaders = new HttpHeaders(); <ide> <del> private HttpHeaders xhrSendRequestHeaders = new HttpHeaders(); <del> <ide> <ide> @Override <ide> public List<TransportType> getTransportTypes() { <ide> public boolean isXhrStreamingDisabled() { <ide> /** <ide> * Configure headers to be added to every executed HTTP request. <ide> * @param requestHeaders the headers to add to requests <add> * @deprecated as of 4.2 in favor of {@link SockJsClient#setHttpHeaderNames}. <ide> */ <add> @Deprecated <ide> public void setRequestHeaders(HttpHeaders requestHeaders) { <ide> this.requestHeaders.clear(); <del> this.xhrSendRequestHeaders.clear(); <ide> if (requestHeaders != null) { <ide> this.requestHeaders.putAll(requestHeaders); <del> this.xhrSendRequestHeaders.putAll(requestHeaders); <del> this.xhrSendRequestHeaders.setContentType(MediaType.APPLICATION_JSON); <ide> } <ide> } <ide> <add> @Deprecated <ide> public HttpHeaders getRequestHeaders() { <ide> return this.requestHeaders; <ide> } <ide> <ide> <ide> // Transport methods <ide> <add> @SuppressWarnings("deprecation") <ide> @Override <ide> public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebSocketHandler handler) { <ide> SettableListenableFuture<WebSocketSession> connectFuture = new SettableListenableFuture<WebSocketSession>(); <ide> public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebS <ide> } <ide> <ide> HttpHeaders handshakeHeaders = new HttpHeaders(); <del> handshakeHeaders.putAll(request.getHandshakeHeaders()); <ide> handshakeHeaders.putAll(getRequestHeaders()); <add> handshakeHeaders.putAll(request.getHandshakeHeaders()); <ide> <ide> connectInternal(request, handler, receiveUrl, handshakeHeaders, session, connectFuture); <ide> return connectFuture; <ide> protected abstract void connectInternal(TransportRequest request, WebSocketHandl <ide> // InfoReceiver methods <ide> <ide> @Override <del> public String executeInfoRequest(URI infoUrl) { <add> @SuppressWarnings("deprecation") <add> public String executeInfoRequest(URI infoUrl, HttpHeaders headers) { <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Executing SockJS Info request, url=" + infoUrl); <ide> } <del> ResponseEntity<String> response = executeInfoRequestInternal(infoUrl); <add> HttpHeaders infoRequestHeaders = new HttpHeaders(); <add> infoRequestHeaders.putAll(getRequestHeaders()); <add> if (headers != null) { <add> infoRequestHeaders.putAll(headers); <add> } <add> ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders); <ide> if (response.getStatusCode() != HttpStatus.OK) { <ide> if (logger.isErrorEnabled()) { <ide> logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response); <ide> public String executeInfoRequest(URI infoUrl) { <ide> return response.getBody(); <ide> } <ide> <del> protected abstract ResponseEntity<String> executeInfoRequestInternal(URI infoUrl); <add> protected abstract ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers); <ide> <ide> // XhrTransport methods <ide> <ide> @Override <del> public void executeSendRequest(URI url, TextMessage message) { <add> public void executeSendRequest(URI url, HttpHeaders headers, TextMessage message) { <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Starting XHR send, url=" + url); <ide> } <del> ResponseEntity<String> response = executeSendRequestInternal(url, this.xhrSendRequestHeaders, message); <add> ResponseEntity<String> response = executeSendRequestInternal(url, headers, message); <ide> if (response.getStatusCode() != HttpStatus.NO_CONTENT) { <ide> if (logger.isErrorEnabled()) { <ide> logger.error("XHR send request (url=" + url + ") failed: " + response); <ide> public void executeSendRequest(URI url, TextMessage message) { <ide> } <ide> } <ide> <del> protected abstract ResponseEntity<String> executeSendRequestInternal(URI url, HttpHeaders headers, TextMessage message); <add> protected abstract ResponseEntity<String> executeSendRequestInternal(URI url, <add> HttpHeaders headers, TextMessage message); <ide> <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/DefaultTransportRequest.java <ide> class DefaultTransportRequest implements TransportRequest { <ide> <ide> private final HttpHeaders handshakeHeaders; <ide> <add> private final HttpHeaders httpRequestHeaders; <add> <ide> private final Transport transport; <ide> <ide> private final TransportType serverTransportType; <ide> class DefaultTransportRequest implements TransportRequest { <ide> private DefaultTransportRequest fallbackRequest; <ide> <ide> <del> public DefaultTransportRequest(SockJsUrlInfo sockJsUrlInfo, HttpHeaders handshakeHeaders, <add> public DefaultTransportRequest(SockJsUrlInfo sockJsUrlInfo, <add> HttpHeaders handshakeHeaders, HttpHeaders httpRequestHeaders, <ide> Transport transport, TransportType serverTransportType, SockJsMessageCodec codec) { <ide> <ide> Assert.notNull(sockJsUrlInfo, "'sockJsUrlInfo' is required"); <ide> public DefaultTransportRequest(SockJsUrlInfo sockJsUrlInfo, HttpHeaders handshak <ide> Assert.notNull(codec, "'codec' is required"); <ide> this.sockJsUrlInfo = sockJsUrlInfo; <ide> this.handshakeHeaders = (handshakeHeaders != null ? handshakeHeaders : new HttpHeaders()); <add> this.httpRequestHeaders = (httpRequestHeaders != null ? httpRequestHeaders : new HttpHeaders()); <ide> this.transport = transport; <ide> this.serverTransportType = serverTransportType; <ide> this.codec = codec; <ide> public HttpHeaders getHandshakeHeaders() { <ide> return this.handshakeHeaders; <ide> } <ide> <add> @Override <add> public HttpHeaders getHttpRequestHeaders() { <add> return this.httpRequestHeaders; <add> } <add> <ide> @Override <ide> public URI getTransportUrl() { <ide> return this.sockJsUrlInfo.getTransportUrl(this.serverTransportType); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/InfoReceiver.java <ide> <ide> import java.net.URI; <ide> <add>import org.springframework.http.HttpHeaders; <add> <ide> /** <ide> * A component that can execute the SockJS "Info" request that needs to be <ide> * performed before the SockJS session starts in order to check server endpoint <ide> public interface InfoReceiver { <ide> /** <ide> * Perform an HTTP request to the SockJS "Info" URL. <ide> * and return the resulting JSON response content, or raise an exception. <del> * <add> * <p>Note that as of 4.2 this method accepts a {@code headers} parameter. <ide> * @param infoUrl the URL to obtain SockJS server information from <add> * @param headers the headers to use for the request <ide> * @return the body of the response <ide> */ <del> String executeInfoRequest(URI infoUrl); <add> String executeInfoRequest(URI infoUrl, HttpHeaders headers); <ide> <ide> } <ide>\ No newline at end of file <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/JettyXhrTransport.java <ide> public boolean isRunning() { <ide> <ide> <ide> @Override <del> protected void connectInternal(TransportRequest request, WebSocketHandler handler, <add> protected void connectInternal(TransportRequest transportRequest, WebSocketHandler handler, <ide> URI url, HttpHeaders handshakeHeaders, XhrClientSockJsSession session, <ide> SettableListenableFuture<WebSocketSession> connectFuture) { <ide> <del> SockJsResponseListener listener = new SockJsResponseListener(url, getRequestHeaders(), session, connectFuture); <add> HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders(); <add> SockJsResponseListener listener = new SockJsResponseListener(url, httpHeaders, session, connectFuture); <ide> executeReceiveRequest(url, handshakeHeaders, listener); <ide> } <ide> <ide> private void executeReceiveRequest(URI url, HttpHeaders headers, SockJsResponseL <ide> } <ide> <ide> @Override <del> protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl) { <del> return executeRequest(infoUrl, HttpMethod.GET, getRequestHeaders(), null); <add> protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) { <add> return executeRequest(infoUrl, HttpMethod.GET, headers, null); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java <ide> public TaskExecutor getTaskExecutor() { <ide> <ide> <ide> @Override <del> protected void connectInternal(final TransportRequest request, final WebSocketHandler handler, <add> protected void connectInternal(final TransportRequest transportRequest, final WebSocketHandler handler, <ide> final URI receiveUrl, final HttpHeaders handshakeHeaders, final XhrClientSockJsSession session, <ide> final SettableListenableFuture<WebSocketSession> connectFuture) { <ide> <ide> getTaskExecutor().execute(new Runnable() { <ide> @Override <ide> public void run() { <add> HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders(); <ide> XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders); <del> XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(getRequestHeaders()); <add> XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders); <ide> XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session); <ide> while (true) { <ide> if (session.isDisconnected()) { <ide> public void run() { <ide> } <ide> <ide> @Override <del> public ResponseEntity<String> executeInfoRequestInternal(URI infoUrl) { <del> RequestCallback requestCallback = new XhrRequestCallback(getRequestHeaders()); <add> protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) { <add> RequestCallback requestCallback = new XhrRequestCallback(headers); <ide> return this.restTemplate.execute(infoUrl, HttpMethod.GET, requestCallback, textResponseExtractor); <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java <ide> public class SockJsClient implements WebSocketClient, Lifecycle { <ide> <ide> private final List<Transport> transports; <ide> <add> private String[] httpHeaderNames; <add> <ide> private InfoReceiver infoReceiver; <ide> <ide> private SockJsMessageCodec messageCodec; <ide> private static InfoReceiver initInfoReceiver(List<Transport> transports) { <ide> } <ide> <ide> <add> /** <add> * The names of HTTP headers that should be copied from the handshake headers <add> * of each call to {@link SockJsClient#doHandshake(WebSocketHandler, WebSocketHttpHeaders, URI)} <add> * and also used with other HTTP requests issued as part of that SockJS <add> * connection, e.g. the initial info request, XHR send or receive requests. <add> * <add> * <p>By default if this property is not set, all handshake headers are also <add> * used for other HTTP requests. Set it if you want only a subset of handshake <add> * headers (e.g. auth headers) to be used for other HTTP requests. <add> * <add> * @param httpHeaderNames HTTP header names <add> */ <add> public void setHttpHeaderNames(String... httpHeaderNames) { <add> this.httpHeaderNames = httpHeaderNames; <add> } <add> <add> /** <add> * The configured HTTP header names to be copied from the handshake <add> * headers and also included in other HTTP requests. <add> */ <add> public String[] getHttpHeaderNames() { <add> return this.httpHeaderNames; <add> } <add> <ide> /** <ide> * Configure the {@code InfoReceiver} to use to perform the SockJS "Info" <ide> * request before the SockJS session starts. <ide> public final ListenableFuture<WebSocketSession> doHandshake( <ide> SettableListenableFuture<WebSocketSession> connectFuture = new SettableListenableFuture<WebSocketSession>(); <ide> try { <ide> SockJsUrlInfo sockJsUrlInfo = new SockJsUrlInfo(url); <del> ServerInfo serverInfo = getServerInfo(sockJsUrlInfo); <add> ServerInfo serverInfo = getServerInfo(sockJsUrlInfo, getHttpRequestHeaders(headers)); <ide> createRequest(sockJsUrlInfo, headers, serverInfo).connect(handler, connectFuture); <ide> } <ide> catch (Throwable exception) { <ide> public final ListenableFuture<WebSocketSession> doHandshake( <ide> return connectFuture; <ide> } <ide> <del> private ServerInfo getServerInfo(SockJsUrlInfo sockJsUrlInfo) { <add> private HttpHeaders getHttpRequestHeaders(HttpHeaders webSocketHttpHeaders) { <add> if (getHttpHeaderNames() == null) { <add> return webSocketHttpHeaders; <add> } <add> else { <add> HttpHeaders httpHeaders = new HttpHeaders(); <add> for (String name : getHttpHeaderNames()) { <add> if (webSocketHttpHeaders.containsKey(name)) { <add> httpHeaders.put(name, webSocketHttpHeaders.get(name)); <add> } <add> } <add> return httpHeaders; <add> } <add> } <add> <add> private ServerInfo getServerInfo(SockJsUrlInfo sockJsUrlInfo, HttpHeaders headers) { <ide> URI infoUrl = sockJsUrlInfo.getInfoUrl(); <ide> ServerInfo info = this.serverInfoCache.get(infoUrl); <ide> if (info == null) { <ide> long start = System.currentTimeMillis(); <del> String response = this.infoReceiver.executeInfoRequest(infoUrl); <add> String response = this.infoReceiver.executeInfoRequest(infoUrl, headers); <ide> long infoRequestTime = System.currentTimeMillis() - start; <ide> info = new ServerInfo(response, infoRequestTime); <ide> this.serverInfoCache.put(infoUrl, info); <ide> private DefaultTransportRequest createRequest(SockJsUrlInfo urlInfo, HttpHeaders <ide> for (Transport transport : this.transports) { <ide> for (TransportType type : transport.getTransportTypes()) { <ide> if (serverInfo.isWebSocketEnabled() || !TransportType.WEBSOCKET.equals(type)) { <del> requests.add(new DefaultTransportRequest(urlInfo, headers, transport, type, getMessageCodec())); <add> requests.add(new DefaultTransportRequest(urlInfo, headers, getHttpRequestHeaders(headers), <add> transport, type, getMessageCodec())); <ide> } <ide> } <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/TransportRequest.java <ide> public interface TransportRequest { <ide> */ <ide> HttpHeaders getHandshakeHeaders(); <ide> <add> /** <add> * Return the headers to add to all other HTTP requests besides the handshake <add> * request such XHR receive and send requests. <add> * @since 4.2 <add> */ <add> HttpHeaders getHttpRequestHeaders(); <add> <ide> /** <ide> * Return the transport URL for the given transport. <ide> * For an {@link XhrTransport} this is the URL for receiving messages. <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/UndertowXhrTransport.java <ide> protected void connectInternal(TransportRequest request, WebSocketHandler handle <ide> HttpHeaders handshakeHeaders, XhrClientSockJsSession session, <ide> SettableListenableFuture<WebSocketSession> connectFuture) { <ide> <del> executeReceiveRequest(receiveUrl, handshakeHeaders, session, connectFuture); <add> executeReceiveRequest(request, receiveUrl, handshakeHeaders, session, connectFuture); <ide> } <ide> <del> private void executeReceiveRequest(final URI url, final HttpHeaders headers, <del> final XhrClientSockJsSession session, <add> private void executeReceiveRequest(final TransportRequest transportRequest, <add> final URI url, final HttpHeaders headers, final XhrClientSockJsSession session, <ide> final SettableListenableFuture<WebSocketSession> connectFuture) { <ide> <ide> if (logger.isTraceEnabled()) { <ide> public void completed(ClientConnection connection) { <ide> HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST); <ide> request.getRequestHeaders().add(headerName, url.getHost()); <ide> addHttpHeaders(request, headers); <del> connection.sendRequest(request, createReceiveCallback(url, <del> getRequestHeaders(), session, connectFuture)); <add> HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders(); <add> connection.sendRequest(request, createReceiveCallback(transportRequest, <add> url, httpHeaders, session, connectFuture)); <ide> } <ide> <ide> @Override <ide> private static void addHttpHeaders(ClientRequest request, HttpHeaders headers) { <ide> } <ide> } <ide> <del> private ClientCallback<ClientExchange> createReceiveCallback(final URI url, final HttpHeaders headers, <del> final XhrClientSockJsSession sockJsSession, <add> private ClientCallback<ClientExchange> createReceiveCallback(final TransportRequest transportRequest, <add> final URI url, final HttpHeaders headers, final XhrClientSockJsSession sockJsSession, <ide> final SettableListenableFuture<WebSocketSession> connectFuture) { <ide> <ide> return new ClientCallback<ClientExchange>() { <ide> public void completed(ClientExchange result) { <ide> onFailure(new HttpServerErrorException(status, "Unexpected XHR receive status")); <ide> } <ide> else { <del> SockJsResponseListener listener = new SockJsResponseListener(result.getConnection(), <del> url, headers, sockJsSession, connectFuture); <add> SockJsResponseListener listener = new SockJsResponseListener( <add> transportRequest, result.getConnection(), url, headers, <add> sockJsSession, connectFuture); <ide> listener.setup(result.getResponseChannel()); <ide> } <ide> if (logger.isTraceEnabled()) { <ide> private static HttpHeaders toHttpHeaders(HeaderMap headerMap) { <ide> } <ide> <ide> @Override <del> protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl) { <del> return executeRequest(infoUrl, Methods.GET, getRequestHeaders(), null); <add> protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) { <add> return executeRequest(infoUrl, Methods.GET, headers, null); <ide> } <ide> <ide> @Override <ide> private void onFailure(CountDownLatch latch, IOException ex) { <ide> <ide> private class SockJsResponseListener implements ChannelListener<StreamSourceChannel> { <ide> <add> private final TransportRequest request; <add> <ide> private final ClientConnection connection; <ide> <ide> private final URI url; <ide> private class SockJsResponseListener implements ChannelListener<StreamSourceChan <ide> <ide> private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); <ide> <del> public SockJsResponseListener(ClientConnection connection, URI url, <add> <add> public SockJsResponseListener(TransportRequest request, ClientConnection connection, URI url, <ide> HttpHeaders headers, XhrClientSockJsSession sockJsSession, <ide> SettableListenableFuture<WebSocketSession> connectFuture) { <ide> <add> this.request = request; <ide> this.connection = connection; <ide> this.url = url; <ide> this.headers = headers; <ide> public void onSuccess() { <ide> logger.trace("XHR receive request completed."); <ide> } <ide> IoUtils.safeClose(this.connection); <del> executeReceiveRequest(this.url, this.headers, this.session, this.connectFuture); <add> executeReceiveRequest(this.request, this.url, this.headers, this.session, this.connectFuture); <ide> } <ide> <ide> public void onFailure(Throwable failure) { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/XhrClientSockJsSession.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 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.net.URI; <ide> import java.util.List; <ide> <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.concurrent.SettableListenableFuture; <ide> import org.springframework.web.socket.CloseStatus; <ide> */ <ide> public class XhrClientSockJsSession extends AbstractClientSockJsSession { <ide> <del> private final URI sendUrl; <del> <ide> private final XhrTransport transport; <ide> <add> private HttpHeaders headers; <add> <add> private HttpHeaders sendHeaders; <add> <add> private final URI sendUrl; <add> <ide> private int textMessageSizeLimit = -1; <ide> <ide> private int binaryMessageSizeLimit = -1; <ide> public XhrClientSockJsSession(TransportRequest request, WebSocketHandler handler <ide> <ide> super(request, handler, connectFuture); <ide> Assert.notNull(transport, "'restTemplate' is required"); <del> this.sendUrl = request.getSockJsUrlInfo().getTransportUrl(TransportType.XHR_SEND); <ide> this.transport = transport; <add> this.headers = request.getHttpRequestHeaders(); <add> this.sendHeaders = new HttpHeaders(); <add> if (this.headers != null) { <add> this.sendHeaders.putAll(this.headers); <add> } <add> this.sendHeaders.setContentType(MediaType.APPLICATION_JSON); <add> this.sendUrl = request.getSockJsUrlInfo().getTransportUrl(TransportType.XHR_SEND); <ide> } <ide> <ide> <add> public HttpHeaders getHeaders() { <add> return this.headers; <add> } <add> <ide> @Override <ide> public InetSocketAddress getLocalAddress() { <ide> return null; <ide> public List<WebSocketExtension> getExtensions() { <ide> <ide> @Override <ide> protected void sendInternal(TextMessage message) { <del> this.transport.executeSendRequest(this.sendUrl, message); <add> this.transport.executeSendRequest(this.sendUrl, this.sendHeaders, message); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/XhrTransport.java <ide> <ide> import java.net.URI; <ide> <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.web.socket.TextMessage; <ide> <ide> /** <ide> * A SockJS {@link Transport} that uses HTTP requests to simulate a WebSocket <ide> * interaction. The {@code connect} method of the base {@code Transport} interface <ide> * is used to receive messages from the server while the <del> * {@link #executeSendRequest(java.net.URI, org.springframework.web.socket.TextMessage) <del> * executeSendRequest(URI, TextMessage)} method here is used to send messages. <add> * {@link #executeSendRequest} method here is used to send messages. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.1 <ide> public interface XhrTransport extends Transport, InfoReceiver { <ide> * An {@code XhrTransport} supports both the "xhr_streaming" and "xhr" SockJS <ide> * server transports. From a client perspective there is no implementation <ide> * difference. <del> * <ide> * <p>By default an {@code XhrTransport} will be used with "xhr_streaming" <ide> * first and then with "xhr", if the streaming fails to connect. In some <ide> * cases it may be useful to suppress streaming so that only "xhr" is used. <ide> public interface XhrTransport extends Transport, InfoReceiver { <ide> <ide> /** <ide> * Execute a request to send the message to the server. <add> * <p>Note that as of 4.2 this method accepts a {@code headers} parameter. <ide> * @param transportUrl the URL for sending messages. <ide> * @param message the message to send <ide> */ <del> void executeSendRequest(URI transportUrl, TextMessage message); <add> void executeSendRequest(URI transportUrl, HttpHeaders headers, TextMessage message); <ide> <ide> } <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/AbstractSockJsIntegrationTests.java <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.server.ServletServerHttpRequest; <ide> import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; <ide> import org.springframework.tests.Assume; <ide> import org.springframework.tests.TestGroup; <ide> public abstract class AbstractSockJsIntegrationTests { <ide> <ide> @BeforeClass <ide> public static void performanceTestGroupAssumption() throws Exception { <del> Assume.group(TestGroup.PERFORMANCE); <add>// Assume.group(TestGroup.PERFORMANCE); <ide> } <ide> <ide> <ide> protected void initSockJsClient(Transport... transports) { <ide> <ide> @Test <ide> public void echoWebSocket() throws Exception { <del> testEcho(100, createWebSocketTransport()); <add> testEcho(100, createWebSocketTransport(), null); <ide> } <ide> <ide> @Test <ide> public void echoXhrStreaming() throws Exception { <del> testEcho(100, createXhrTransport()); <add> testEcho(100, createXhrTransport(), null); <ide> } <ide> <ide> @Test <ide> public void echoXhr() throws Exception { <ide> AbstractXhrTransport xhrTransport = createXhrTransport(); <ide> xhrTransport.setXhrStreamingDisabled(true); <del> testEcho(100, xhrTransport); <add> testEcho(100, xhrTransport, null); <add> } <add> <add> // SPR-13254 <add> <add> @Test <add> public void echoXhrWithHeaders() throws Exception { <add> AbstractXhrTransport xhrTransport = createXhrTransport(); <add> xhrTransport.setXhrStreamingDisabled(true); <add> <add> WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); <add> headers.add("auth", "123"); <add> testEcho(10, xhrTransport, headers); <add> <add> for (Map.Entry<String, HttpHeaders> entry : this.testFilter.requests.entrySet()) { <add> HttpHeaders httpHeaders = entry.getValue(); <add> assertEquals("No auth header for: " + entry.getKey(), "123", httpHeaders.getFirst("auth")); <add> } <ide> } <ide> <ide> @Test <ide> public void fallbackAfterConnectTimeout() throws Exception { <ide> } <ide> <ide> <del> private void testEcho(int messageCount, Transport transport) throws Exception { <add> private void testEcho(int messageCount, Transport transport, WebSocketHttpHeaders headers) throws Exception { <ide> List<TextMessage> messages = new ArrayList<>(); <ide> for (int i = 0; i < messageCount; i++) { <ide> messages.add(new TextMessage("m" + i)); <ide> } <ide> TestClientHandler handler = new TestClientHandler(); <ide> initSockJsClient(transport); <del> WebSocketSession session = this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").get(); <add> URI url = new URI(this.baseUrl + "/echo"); <add> WebSocketSession session = this.sockJsClient.doHandshake(handler, headers, url).get(); <ide> for (TextMessage message : messages) { <ide> session.sendMessage(message); <ide> } <ide> public WebSocketSession awaitSession(long timeToWait) throws InterruptedExceptio <ide> <ide> private static class TestFilter implements Filter { <ide> <del> private final List<ServletRequest> requests = new ArrayList<>(); <add> private final Map<String, HttpHeaders> requests = new HashMap<>(); <ide> <ide> private final Map<String, Long> sleepDelayMap = new HashMap<>(); <ide> <ide> private static class TestFilter implements Filter { <ide> public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) <ide> throws IOException, ServletException { <ide> <del> this.requests.add(request); <add> HttpServletRequest httpRequest = (HttpServletRequest) request; <add> String uri = httpRequest.getRequestURI(); <add> HttpHeaders headers = new ServletServerHttpRequest(httpRequest).getHeaders(); <add> this.requests.put(uri, headers); <ide> <ide> for (String suffix : this.sleepDelayMap.keySet()) { <del> if (((HttpServletRequest) request).getRequestURI().endsWith(suffix)) { <add> if ((httpRequest).getRequestURI().endsWith(suffix)) { <ide> try { <ide> Thread.sleep(this.sleepDelayMap.get(suffix)); <ide> break; <ide> public void doFilter(ServletRequest request, ServletResponse response, FilterCha <ide> } <ide> } <ide> for (String suffix : this.sendErrorMap.keySet()) { <del> if (((HttpServletRequest) request).getRequestURI().endsWith(suffix)) { <add> if ((httpRequest).getRequestURI().endsWith(suffix)) { <ide> ((HttpServletResponse) response).sendError(this.sendErrorMap.get(suffix)); <ide> return; <ide> } <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/ClientSockJsSessionTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class ClientSockJsSessionTests { <ide> public void setup() throws Exception { <ide> SockJsUrlInfo urlInfo = new SockJsUrlInfo(new URI("http://example.com")); <ide> Transport transport = mock(Transport.class); <del> TransportRequest request = new DefaultTransportRequest(urlInfo, null, transport, TransportType.XHR, CODEC); <add> TransportRequest request = new DefaultTransportRequest(urlInfo, null, null, transport, TransportType.XHR, CODEC); <ide> this.handler = mock(WebSocketHandler.class); <ide> this.connectFuture = new SettableListenableFuture<>(); <ide> this.session = new TestClientSockJsSession(request, this.handler, this.connectFuture); <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/DefaultTransportRequestTests.java <ide> public void fallbackAfterTimeout() throws Exception { <ide> <ide> protected DefaultTransportRequest createTransportRequest(Transport transport, TransportType type) throws Exception { <ide> SockJsUrlInfo urlInfo = new SockJsUrlInfo(new URI("http://example.com")); <del> return new DefaultTransportRequest(urlInfo, new HttpHeaders(), transport, type, CODEC); <add> return new DefaultTransportRequest(urlInfo, new HttpHeaders(), new HttpHeaders(), transport, type, CODEC); <ide> } <ide> <ide> } <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransportTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 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> private ListenableFuture<WebSocketSession> connect(RestOperations restTemplate, <ide> SockJsUrlInfo urlInfo = new SockJsUrlInfo(new URI("http://example.com")); <ide> HttpHeaders headers = new HttpHeaders(); <ide> headers.add("h-foo", "h-bar"); <del> TransportRequest request = new DefaultTransportRequest(urlInfo, headers, transport, TransportType.XHR, CODEC); <add> TransportRequest request = new DefaultTransportRequest(urlInfo, headers, headers, <add> transport, TransportType.XHR, CODEC); <ide> <ide> return transport.connect(request, this.webSocketHandler); <ide> } <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/SockJsClientTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 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> <ide> package org.springframework.web.socket.sockjs.client; <ide> <add>import java.net.URI; <ide> import java.net.URISyntaxException; <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <add>import org.mockito.ArgumentCaptor; <ide> <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.util.concurrent.ListenableFutureCallback; <ide> import org.springframework.web.client.HttpServerErrorException; <ide> import org.springframework.web.socket.WebSocketHandler; <add>import org.springframework.web.socket.WebSocketHttpHeaders; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.socket.sockjs.client.TestTransport.XhrTestTransport; <ide> <del>import static org.junit.Assert.*; <del>import static org.mockito.BDDMockito.*; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertTrue; <add>import static org.mockito.BDDMockito.any; <add>import static org.mockito.BDDMockito.given; <add>import static org.mockito.BDDMockito.mock; <add>import static org.mockito.BDDMockito.times; <add>import static org.mockito.BDDMockito.verify; <add>import static org.mockito.BDDMockito.verifyNoMoreInteractions; <add>import static org.mockito.BDDMockito.when; <ide> <ide> /** <ide> * Unit tests for {@link org.springframework.web.socket.sockjs.client.SockJsClient}. <ide> public void connectXhrStreamingDisabled() throws Exception { <ide> assertTrue(this.xhrTransport.getRequest().getTransportUrl().toString().endsWith("xhr")); <ide> } <ide> <add> // SPR-13254 <add> <add> @Test <add> public void connectWithHandshakeHeaders() throws Exception { <add> ArgumentCaptor<HttpHeaders> headersCaptor = setupInfoRequest(false); <add> this.xhrTransport.setStreamingDisabled(true); <add> <add> WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); <add> headers.set("foo", "bar"); <add> headers.set("auth", "123"); <add> this.sockJsClient.doHandshake(handler, headers, new URI(URL)).addCallback(this.connectCallback); <add> <add> HttpHeaders httpHeaders = headersCaptor.getValue(); <add> assertEquals(2, httpHeaders.size()); <add> assertEquals("bar", httpHeaders.getFirst("foo")); <add> assertEquals("123", httpHeaders.getFirst("auth")); <add> <add> httpHeaders = this.xhrTransport.getRequest().getHttpRequestHeaders(); <add> assertEquals(2, httpHeaders.size()); <add> assertEquals("bar", httpHeaders.getFirst("foo")); <add> assertEquals("123", httpHeaders.getFirst("auth")); <add> } <add> <add> @Test <add> public void connectAndUseSubsetOfHandshakeHeadersForHttpRequests() throws Exception { <add> ArgumentCaptor<HttpHeaders> headersCaptor = setupInfoRequest(false); <add> this.xhrTransport.setStreamingDisabled(true); <add> <add> WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); <add> headers.set("foo", "bar"); <add> headers.set("auth", "123"); <add> this.sockJsClient.setHttpHeaderNames("auth"); <add> this.sockJsClient.doHandshake(handler, headers, new URI(URL)).addCallback(this.connectCallback); <add> <add> assertEquals(1, headersCaptor.getValue().size()); <add> assertEquals("123", headersCaptor.getValue().getFirst("auth")); <add> assertEquals(1, this.xhrTransport.getRequest().getHttpRequestHeaders().size()); <add> assertEquals("123", this.xhrTransport.getRequest().getHttpRequestHeaders().getFirst("auth")); <add> } <add> <ide> @Test <ide> public void connectSockJsInfo() throws Exception { <ide> setupInfoRequest(true); <ide> this.sockJsClient.doHandshake(handler, URL); <del> verify(this.infoReceiver, times(1)).executeInfoRequest(any()); <add> verify(this.infoReceiver, times(1)).executeInfoRequest(any(), any()); <ide> } <ide> <ide> @Test <ide> public void connectSockJsInfoCached() throws Exception { <ide> this.sockJsClient.doHandshake(handler, URL); <ide> this.sockJsClient.doHandshake(handler, URL); <ide> this.sockJsClient.doHandshake(handler, URL); <del> verify(this.infoReceiver, times(1)).executeInfoRequest(any()); <add> verify(this.infoReceiver, times(1)).executeInfoRequest(any(), any()); <ide> } <ide> <ide> @Test <ide> public void connectInfoRequestFailure() throws URISyntaxException { <ide> HttpServerErrorException exception = new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE); <del> given(this.infoReceiver.executeInfoRequest(any())).willThrow(exception); <add> given(this.infoReceiver.executeInfoRequest(any(), any())).willThrow(exception); <ide> this.sockJsClient.doHandshake(handler, URL).addCallback(this.connectCallback); <ide> verify(this.connectCallback).onFailure(exception); <ide> assertFalse(this.webSocketTransport.invoked()); <ide> assertFalse(this.xhrTransport.invoked()); <ide> } <ide> <del> private void setupInfoRequest(boolean webSocketEnabled) { <del> given(this.infoReceiver.executeInfoRequest(any())).willReturn("{\"entropy\":123," + <del> "\"origins\":[\"*:*\"],\"cookie_needed\":true,\"websocket\":" + webSocketEnabled + "}"); <add> private ArgumentCaptor<HttpHeaders> setupInfoRequest(boolean webSocketEnabled) { <add> ArgumentCaptor<HttpHeaders> headersCaptor = ArgumentCaptor.forClass(HttpHeaders.class); <add> when(this.infoReceiver.executeInfoRequest(any(), headersCaptor.capture())).thenReturn( <add> "{\"entropy\":123," + <add> "\"origins\":[\"*:*\"]," + <add> "\"cookie_needed\":true," + <add> "\"websocket\":" + webSocketEnabled + "}"); <add> return headersCaptor; <ide> } <ide> <ide> } <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/TestTransport.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 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> <ide> import java.net.URI; <ide> import java.util.Arrays; <add>import java.util.Collections; <ide> import java.util.List; <ide> <ide> import org.mockito.ArgumentCaptor; <add> <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.util.concurrent.ListenableFuture; <ide> import org.springframework.util.concurrent.ListenableFutureCallback; <ide> import org.springframework.web.socket.TextMessage; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.socket.sockjs.transport.TransportType; <ide> <del>import static org.mockito.Mockito.*; <add>import static org.mockito.Mockito.mock; <add>import static org.mockito.Mockito.verify; <ide> <ide> /** <ide> * Test SockJS Transport. <ide> public TestTransport(String name) { <ide> <ide> @Override <ide> public List<TransportType> getTransportTypes() { <del> return Arrays.asList(TransportType.WEBSOCKET); <add> return Collections.singletonList(TransportType.WEBSOCKET); <ide> } <ide> <ide> public TransportRequest getRequest() { <ide> static class XhrTestTransport extends TestTransport implements XhrTransport { <ide> @Override <ide> public List<TransportType> getTransportTypes() { <ide> return (isXhrStreamingDisabled() ? <del> Arrays.asList(TransportType.XHR) : <add> Collections.singletonList(TransportType.XHR) : <ide> Arrays.asList(TransportType.XHR_STREAMING, TransportType.XHR)); <ide> } <ide> <ide> public boolean isXhrStreamingDisabled() { <ide> } <ide> <ide> @Override <del> public void executeSendRequest(URI transportUrl, TextMessage message) { <add> public void executeSendRequest(URI transportUrl, HttpHeaders headers, TextMessage message) { <ide> } <ide> <ide> @Override <del> public String executeInfoRequest(URI infoUrl) { <add> public String executeInfoRequest(URI infoUrl, HttpHeaders headers) { <ide> return null; <ide> } <ide> } <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/XhrTransportTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class XhrTransportTests { <ide> public void infoResponse() throws Exception { <ide> TestXhrTransport transport = new TestXhrTransport(); <ide> transport.infoResponseToReturn = new ResponseEntity<>("body", HttpStatus.OK); <del> assertEquals("body", transport.executeInfoRequest(new URI("http://example.com/info"))); <add> assertEquals("body", transport.executeInfoRequest(new URI("http://example.com/info"), null)); <ide> } <ide> <ide> @Test(expected = HttpServerErrorException.class) <ide> public void infoResponseError() throws Exception { <ide> TestXhrTransport transport = new TestXhrTransport(); <ide> transport.infoResponseToReturn = new ResponseEntity<>("body", HttpStatus.BAD_REQUEST); <del> assertEquals("body", transport.executeInfoRequest(new URI("http://example.com/info"))); <add> assertEquals("body", transport.executeInfoRequest(new URI("http://example.com/info"), null)); <ide> } <ide> <ide> @Test <ide> public void sendMessage() throws Exception { <ide> HttpHeaders requestHeaders = new HttpHeaders(); <ide> requestHeaders.set("foo", "bar"); <add> requestHeaders.setContentType(MediaType.APPLICATION_JSON); <ide> TestXhrTransport transport = new TestXhrTransport(); <del> transport.setRequestHeaders(requestHeaders); <ide> transport.sendMessageResponseToReturn = new ResponseEntity<>(HttpStatus.NO_CONTENT); <ide> URI url = new URI("http://example.com"); <del> transport.executeSendRequest(url, new TextMessage("payload")); <add> transport.executeSendRequest(url, requestHeaders, new TextMessage("payload")); <ide> assertEquals(2, transport.actualSendRequestHeaders.size()); <ide> assertEquals("bar", transport.actualSendRequestHeaders.getFirst("foo")); <ide> assertEquals(MediaType.APPLICATION_JSON, transport.actualSendRequestHeaders.getContentType()); <ide> public void sendMessageError() throws Exception { <ide> TestXhrTransport transport = new TestXhrTransport(); <ide> transport.sendMessageResponseToReturn = new ResponseEntity<>(HttpStatus.BAD_REQUEST); <ide> URI url = new URI("http://example.com"); <del> transport.executeSendRequest(url, new TextMessage("payload")); <add> transport.executeSendRequest(url, null, new TextMessage("payload")); <ide> } <ide> <add> @SuppressWarnings("deprecation") <ide> @Test <ide> public void connect() throws Exception { <ide> HttpHeaders handshakeHeaders = new HttpHeaders(); <ide> public void connect() throws Exception { <ide> verify(request).addTimeoutTask(captor.capture()); <ide> verify(request).getTransportUrl(); <ide> verify(request).getHandshakeHeaders(); <add> verify(request).getHttpRequestHeaders(); <ide> verifyNoMoreInteractions(request); <ide> <ide> assertEquals(2, transport.actualHandshakeHeaders.size()); <ide> private static class TestXhrTransport extends AbstractXhrTransport { <ide> <ide> <ide> @Override <del> protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl) { <add> protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) { <ide> return this.infoResponseToReturn; <ide> } <ide>
17
Javascript
Javascript
improve test coverage for comparisons
c3bd65146e95968edf81b70f51823e0f44e701f2
<ide><path>test/parallel/test-assert-deep.js <ide> assertOnlyDeepEqual( <ide> new Map([[null, undefined]]), <ide> new Map([[undefined, null]]) <ide> ); <add> <ide> assertOnlyDeepEqual( <ide> new Set([null, '']), <ide> new Set([undefined, 0]) <ide> assertNotDeepOrStrict( <ide> new Set(['']), <ide> new Set(['0']) <ide> ); <add>assertOnlyDeepEqual( <add> new Map([[1, {}]]), <add> new Map([[true, {}]]) <add>); <ide> <ide> // GH-6416. Make sure circular refs don't throw. <ide> { <ide> assertOnlyDeepEqual([1, , , 3], [1, , , 3, , , ]); <ide> // Handle different error messages <ide> { <ide> const err1 = new Error('foo1'); <del> const err2 = new Error('foo2'); <del> const err3 = new TypeError('foo1'); <del> assertNotDeepOrStrict(err1, err2, assert.AssertionError); <del> assertNotDeepOrStrict(err1, err3, assert.AssertionError); <add> assertNotDeepOrStrict(err1, new Error('foo2'), assert.AssertionError); <add> assertNotDeepOrStrict(err1, new TypeError('foo1'), assert.AssertionError); <add> assertDeepAndStrictEqual(err1, new Error('foo1')); <ide> // TODO: evaluate if this should throw or not. The same applies for RegExp <ide> // Date and any object that has the same keys but not the same prototype. <del> assertOnlyDeepEqual(err1, {}, assert.AssertionError); <add> assertOnlyDeepEqual(err1, {}); <ide> } <ide> <ide> // Handle NaN
1
Go
Go
remove duplicate rootfstoapitype
4ceea53b5e6a86c39122e99f6ffbc1142d28a174
<ide><path>daemon/daemon_unix.go <ide> import ( <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/daemon/initlayer" <del> "github.com/docker/docker/image" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/containerfs" <ide> "github.com/docker/docker/pkg/idtools" <ide> func (daemon *Daemon) setDefaultIsolation() error { <ide> return nil <ide> } <ide> <del>func rootFSToAPIType(rootfs *image.RootFS) types.RootFS { <del> var layers []string <del> for _, l := range rootfs.DiffIDs { <del> layers = append(layers, l.String()) <del> } <del> return types.RootFS{ <del> Type: rootfs.Type, <del> Layers: layers, <del> } <del>} <del> <ide> // setupDaemonProcess sets various settings for the daemon's process <ide> func setupDaemonProcess(config *config.Config) error { <ide> // setup the daemons oom_score_adj <ide><path>daemon/daemon_windows.go <ide> import ( <ide> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/daemon/config" <del> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/containerfs" <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/idtools" <ide> func (daemon *Daemon) setDefaultIsolation() error { <ide> return nil <ide> } <ide> <del>func rootFSToAPIType(rootfs *image.RootFS) types.RootFS { <del> var layers []string <del> for _, l := range rootfs.DiffIDs { <del> layers = append(layers, l.String()) <del> } <del> return types.RootFS{ <del> Type: rootfs.Type, <del> Layers: layers, <del> } <del>} <del> <ide> func setupDaemonProcess(config *config.Config) error { <ide> return nil <ide> } <ide><path>daemon/image_inspect.go <ide> import ( <ide> <ide> "github.com/docker/distribution/reference" <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/pkg/errors" <ide> func (daemon *Daemon) LookupImage(name string) (*types.ImageInspect, error) { <ide> <ide> return imageInspect, nil <ide> } <add> <add>func rootFSToAPIType(rootfs *image.RootFS) types.RootFS { <add> var layers []string <add> for _, l := range rootfs.DiffIDs { <add> layers = append(layers, l.String()) <add> } <add> return types.RootFS{ <add> Type: rootfs.Type, <add> Layers: layers, <add> } <add>}
3
PHP
PHP
add docblock examples for attachments
8414d37e48d1e2eb839be28ec1a97632a46bc5ce
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> public function messageId($message = null) { <ide> } <ide> <ide> /** <del> * Attachments <add> * Add attachments to the email message <add> * <add> * Attachments can be defined in a few forms depending on how much control you need: <add> * <add> * Attach a single file: <add> * <add> * {{{ <add> * $email->attachments('path/to/file'); <add> * }}} <add> * <add> * Attach a file with a different filename: <add> * <add> * {{{ <add> * $email->attachments(array('custom_name.txt' => 'path/to/file.txt')); <add> * }}} <add> * <add> * Attach a file and specify additional properties: <add> * <add> * {{{ <add> * $email->attachments(array('custom_name.png' => array( <add> * 'file' => 'path/to/file', <add> * 'mimetype' => 'image/png', <add> * 'contentId' => 'abc123' <add> * )); <add> * }}} <add> * <add> * The `contentId` key allows you to specify an inline attachment. In your email text, you <add> * can use `<img src="cid:abc123" />` to display the image inline. <ide> * <ide> * @param mixed $attachments String with the filename or array with filenames <del> * @return mixed <add> * @return mixed Either the array of attachments when getting or $this when setting. <ide> * @throws SocketException <ide> */ <ide> public function attachments($attachments = null) {
1
Text
Text
add a link to some documentation about exec
7f1ea7129e7b87e60ea4b1e4449b0541f6f432c9
<ide><path>docs/sources/articles/dockerfile_best-practices.md <ide> beginning user will then be forced to learn about `ENTRYPOINT` and <ide> `--entrypoint`. <ide> <ide> In order to avoid a situation where commands are run without clear visibility <del>to the user, make sure your script ends with something like `exec "$@"`. After <del>the entrypoint completes, the script will transparently bootstrap the command <add>to the user, make sure your script ends with something like `exec "$@"` (see <add>[the exec builtin command](http://wiki.bash-hackers.org/commands/builtin/exec)). <add>After the entrypoint completes, the script will transparently bootstrap the command <ide> invoked by the user, making what has been run clear to the user (for example, <ide> `docker run -it mysql mysqld --some --flags` will transparently run <ide> `mysqld --some --flags` after `ENTRYPOINT` runs `initdb`).
1
Javascript
Javascript
handle case when regexp is false in context
9f21fed24791e0c1ba4a9e6249d3fc50d1168a35
<ide><path>lib/ContextModuleFactory.js <ide> ContextModuleFactory.prototype.create = function(context, dependency, callback) <ide> }; <ide> <ide> ContextModuleFactory.prototype.resolveDependencies = function resolveDependencies(fs, resource, recursive, regExp, callback) { <add> if(!regExp || !resource) <add> return callback(null, []); <ide> (function addDirectory(directory, callback) { <ide> fs.readdir(directory, function(err, files) { <ide> if(!files || files.length === 0) return callback(null, []);
1
Java
Java
reset mbean servers after jruby and jmx tests
0d73d199ec645f6d332d3283b72a531b26575cf6
<ide><path>spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java <ide> import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; <ide> import org.springframework.context.ConfigurableApplicationContext; <ide> import org.springframework.context.support.GenericApplicationContext; <add>import org.springframework.util.MBeanTestUtils; <ide> <ide> /** <ide> * <strong>Note:</strong> the JMX test suite requires the presence of the <ide> * <code>jmxremote_optional.jar</code> in your classpath. Thus, if you <ide> * run into the <em>"Unsupported protocol: jmxmp"</em> error, you will <ide> * need to download the <del> * <a href="http://www.oracle.com/technetwork/java/javase/tech/download-jsp-141676.html">JMX Remote API 1.0.1_04 Reference Implementation</a> <add> * <a href="http://www.oracle.com/technetwork/java/javase/tech/download-jsp-141676.html">JMX Remote API 1.0.1_04 Reference Implementation</a> <ide> * from Oracle and extract <code>jmxremote_optional.jar</code> into your <ide> * classpath, for example in the <code>lib/ext</code> folder of your JVM. <ide> * See also <a href="https://issuetracker.springsource.com/browse/EBR-349">EBR-349</a>. <del> * <add> * <ide> * @author Rob Harrop <ide> * @author Juergen Hoeller <ide> * @author Sam Brannen <ide> protected void tearDown() throws Exception { <ide> onTearDown(); <ide> } <ide> <del> private void releaseServer() { <add> private void releaseServer() throws Exception { <ide> MBeanServerFactory.releaseMBeanServer(getServer()); <add> MBeanTestUtils.resetMBeanServers(); <ide> } <ide> <ide> protected void onTearDown() throws Exception { <ide><path>spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java <ide> package org.springframework.jmx.support; <ide> <ide> import java.lang.management.ManagementFactory; <del>import java.lang.reflect.Field; <ide> import java.util.List; <ide> <ide> import javax.management.MBeanServer; <ide> import javax.management.MBeanServerFactory; <ide> <ide> import junit.framework.TestCase; <ide> <add>import org.springframework.util.MBeanTestUtils; <add> <ide> /** <ide> * @author Rob Harrop <ide> * @author Juergen Hoeller <ide> public class MBeanServerFactoryBeanTests extends TestCase { <ide> <ide> @Override <ide> protected void setUp() throws Exception { <del> resetPlatformManager(); <add> MBeanTestUtils.resetMBeanServers(); <ide> } <ide> <ide> @Override <ide> protected void tearDown() throws Exception { <del> resetPlatformManager(); <del> } <del> <del> /** <del> * Resets MBeanServerFactory and ManagementFactory to a known consistent state. <del> * This involves releasing all currently registered MBeanServers and resetting <del> * the platformMBeanServer to null. <del> */ <del> private void resetPlatformManager() throws Exception { <del> for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) { <del> MBeanServerFactory.releaseMBeanServer(server); <del> } <del> Field field = ManagementFactory.class.getDeclaredField("platformMBeanServer"); <del> field.setAccessible(true); <del> field.set(null, null); <add> MBeanTestUtils.resetMBeanServers(); <ide> } <ide> <ide> public void testGetObject() throws Exception { <ide><path>spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests.java <ide> <ide> package org.springframework.scripting.jruby; <ide> <del>import static org.junit.Assert.*; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertTrue; <ide> <add>import org.junit.After; <ide> import org.junit.Test; <ide> import org.springframework.aop.framework.Advised; <ide> import org.springframework.aop.support.AopUtils; <ide> import org.springframework.context.support.ClassPathXmlApplicationContext; <ide> import org.springframework.scripting.Messenger; <add>import org.springframework.util.MBeanTestUtils; <ide> <ide> import test.advice.CountingBeforeAdvice; <ide> <ide> * @author Chris Beams <ide> */ <ide> public final class AdvisedJRubyScriptFactoryTests { <del> <add> <ide> private static final Class<?> CLASS = AdvisedJRubyScriptFactoryTests.class; <ide> private static final String CLASSNAME = CLASS.getSimpleName(); <del> <add> <ide> private static final String FACTORYBEAN_CONTEXT = CLASSNAME + "-factoryBean.xml"; <ide> private static final String APC_CONTEXT = CLASSNAME + "-beanNameAutoProxyCreator.xml"; <ide> <add> @After <add> public void resetMBeanServers() throws Exception { <add> MBeanTestUtils.resetMBeanServers(); <add> } <add> <ide> @Test <ide> public void testAdviseWithProxyFactoryBean() { <ide> ClassPathXmlApplicationContext ctx = <ide> new ClassPathXmlApplicationContext(FACTORYBEAN_CONTEXT, CLASS); <add> try { <add> Messenger bean = (Messenger) ctx.getBean("messenger"); <add> assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean)); <add> assertTrue("Bean is not an Advised object", bean instanceof Advised); <ide> <del> Messenger bean = (Messenger) ctx.getBean("messenger"); <del> assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean)); <del> assertTrue("Bean is not an Advised object", bean instanceof Advised); <del> <del> CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice"); <del> assertEquals(0, advice.getCalls()); <del> bean.getMessage(); <del> assertEquals(1, advice.getCalls()); <add> CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice"); <add> assertEquals(0, advice.getCalls()); <add> bean.getMessage(); <add> assertEquals(1, advice.getCalls()); <add> } finally { <add> ctx.close(); <add> } <ide> } <ide> <ide> @Test <ide> public void testAdviseWithBeanNameAutoProxyCreator() { <ide> ClassPathXmlApplicationContext ctx = <ide> new ClassPathXmlApplicationContext(APC_CONTEXT, CLASS); <add> try { <add> Messenger bean = (Messenger) ctx.getBean("messenger"); <add> assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean)); <add> assertTrue("Bean is not an Advised object", bean instanceof Advised); <ide> <del> Messenger bean = (Messenger) ctx.getBean("messenger"); <del> assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean)); <del> assertTrue("Bean is not an Advised object", bean instanceof Advised); <del> <del> CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice"); <del> assertEquals(0, advice.getCalls()); <del> bean.getMessage(); <del> assertEquals(1, advice.getCalls()); <add> CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice"); <add> assertEquals(0, advice.getCalls()); <add> bean.getMessage(); <add> assertEquals(1, advice.getCalls()); <add> } finally { <add> ctx.close(); <add> } <ide> } <ide> <ide> } <ide><path>spring-context/src/test/java/org/springframework/util/MBeanTestUtils.java <add>/* <add> * Copyright 2002-2012 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.util; <add> <add>import java.lang.management.ManagementFactory; <add>import java.lang.reflect.Field; <add> <add>import javax.management.MBeanServer; <add>import javax.management.MBeanServerFactory; <add> <add>/** <add> * Utilities for MBean tests. <add> * <add> * @author Phillip Webb <add> */ <add>public class MBeanTestUtils { <add> <add> /** <add> * Resets MBeanServerFactory and ManagementFactory to a known consistent state. <add> * This involves releasing all currently registered MBeanServers and resetting <add> * the platformMBeanServer to null. <add> */ <add> public static void resetMBeanServers() throws Exception { <add> for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) { <add> MBeanServerFactory.releaseMBeanServer(server); <add> } <add> Field field = ManagementFactory.class.getDeclaredField("platformMBeanServer"); <add> field.setAccessible(true); <add> field.set(null, null); <add> } <add> <add>}
4
PHP
PHP
allow string for parameters
e44933af48548502f79d6b8049824205fa229b91
<ide><path>src/Illuminate/Routing/PendingResourceRegistration.php <ide> public function name($method, $name) <ide> /** <ide> * Override the route parameter names. <ide> * <del> * @param array $parameters <add> * @param array|string $parameters <ide> * @return \Illuminate\Routing\PendingResourceRegistration <ide> */ <del> public function parameters(array $parameters) <add> public function parameters($parameters) <ide> { <ide> $this->options['parameters'] = $parameters; <ide> <ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testResourceRoutingParameters() <ide> <ide> $router = $this->getRouter(); <ide> $router->resource('foos', 'FooController', ['parameters' => 'singular']); <del> $router->resource('foos.bars', 'FooController', ['parameters' => 'singular']); <add> $router->resource('foos.bars', 'FooController')->parameters('singular'); <ide> $routes = $router->getRoutes(); <ide> $routes = $routes->getRoutes(); <ide> <ide> public function testResourceRoutingParameters() <ide> $routes = $routes->getRoutes(); <ide> <ide> $this->assertEquals('foos/{foo}/bars/{bar}', $routes[3]->uri()); <add> <add> $router = $this->getRouter(); <add> $router->resource('foos.bars', 'FooController')->parameter('foos', 'foo')->parameter('bars', 'bar'); <add> $routes = $router->getRoutes(); <add> $routes = $routes->getRoutes(); <add> <add> $this->assertEquals('foos/{foo}/bars/{bar}', $routes[3]->uri()); <ide> } <ide> <ide> public function testResourceRouteNaming()
2
Text
Text
fix broken external link in security guide
d23fb68e3d4b8cc81e877266aefce95dac562699
<ide><path>guides/source/security.md <ide> In December 2006, 34,000 actual user names and passwords were stolen in a [MySpa <ide> <ide> INFO: _CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application._ <ide> <del>CSS Injection is explained best by the well-known [MySpace Samy worm](http://namb.la/popular/tech.html). This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, which created so much traffic that MySpace went offline. The following is a technical explanation of that worm. <add>CSS Injection is explained best by the well-known [MySpace Samy worm](https://samy.pl/popular/tech.html). This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, which created so much traffic that MySpace went offline. The following is a technical explanation of that worm. <ide> <ide> MySpace blocked many tags, but allowed CSS. So the worm's author put JavaScript into CSS like this: <ide>
1
Text
Text
update example output for node inspect
dcb052c12bf6e67184d0cb6a69daf39c25666cfe
<ide><path>docs/reference/commandline/node_inspect.md <ide> Example output: <ide> $ docker node inspect --pretty self <ide> ID: e216jshn25ckzbvmwlnh5jr3g <ide> Hostname: swarm-manager <add> Joined at: 2016-06-16 22:52:44.9910662 +0000 utc <ide> Status: <ide> State: Ready <ide> Availability: Active <ide><path>docs/swarm/manage-nodes.md <ide> pass the `--pretty` flag to print the results in human-readable format. For exam <ide> ```bash <ide> docker node inspect self --pretty <ide> <del>ID: ehkv3bcimagdese79dn78otj5 <del>Hostname: node-1 <add>ID: ehkv3bcimagdese79dn78otj5 <add>Hostname: node-1 <add>Joined at: 2016-06-16 22:52:44.9910662 +0000 utc <ide> Status: <del> State: Ready <del> Availability: Active <add> State: Ready <add> Availability: Active <ide> Manager Status: <del> Address: 172.17.0.2:2377 <del> Raft Status: Reachable <del> Leader: Yes <add> Address: 172.17.0.2:2377 <add> Raft Status: Reachable <add> Leader: Yes <ide> Platform: <del> Operating System: linux <del> Architecture: x86_64 <add> Operating System: linux <add> Architecture: x86_64 <ide> Resources: <del> CPUs: 2 <del> Memory: 1.954 GiB <add> CPUs: 2 <add> Memory: 1.954 GiB <ide> Plugins: <del> Network: overlay, host, bridge, overlay, null <del> Volume: local <del>Engine Version: 1.12.0-dev <add> Network: overlay, host, bridge, overlay, null <add> Volume: local <add>Engine Version: 1.12.0-dev <ide> ``` <ide> <ide> ## Update a node
2
Go
Go
relax dns search to accept empty domain
804b00cd7d1f084a872211e5043d255c454c8e51
<ide><path>docker/docker.go <ide> func main() { <ide> flSocketGroup = flag.String([]string{"G", "-group"}, "docker", "Group to assign the unix socket specified by -H when running in daemon mode\nuse '' (the empty string) to disable setting of a group") <ide> flEnableCors = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API") <ide> flDns = opts.NewListOpts(opts.ValidateIp4Address) <del> flDnsSearch = opts.NewListOpts(opts.ValidateDomain) <add> flDnsSearch = opts.NewListOpts(opts.ValidateDnsSearch) <ide> flEnableIptables = flag.Bool([]string{"#iptables", "-iptables"}, true, "Enable Docker's addition of iptables rules") <ide> flEnableIpForward = flag.Bool([]string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward") <ide> flDefaultIp = flag.String([]string{"#ip", "-ip"}, "0.0.0.0", "Default IP address to use when binding container ports") <ide><path>integration-cli/docker_cli_run_test.go <ide> package main <ide> <ide> import ( <ide> "fmt" <add> "io/ioutil" <ide> "os" <ide> "os/exec" <ide> "reflect" <ide> import ( <ide> "strings" <ide> "sync" <ide> "testing" <add> <add> "github.com/dotcloud/docker/pkg/networkfs/resolvconf" <ide> ) <ide> <ide> // "test123" should be printed by docker run <ide> func TestDisallowBindMountingRootToRoot(t *testing.T) { <ide> <ide> logDone("run - bind mount /:/ as volume should fail") <ide> } <add> <add>func TestDnsDefaultOptions(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf") <add> <add> actual, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err, actual) <add> } <add> <add> resolvConf, err := ioutil.ReadFile("/etc/resolv.conf") <add> if os.IsNotExist(err) { <add> t.Fatalf("/etc/resolv.conf does not exist") <add> } <add> <add> if actual != string(resolvConf) { <add> t.Fatalf("expected resolv.conf is not the same of actual") <add> } <add> <add> deleteAllContainers() <add> <add> logDone("run - dns default options") <add>} <add> <add>func TestDnsOptions(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf") <add> <add> out, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err, out) <add> } <add> <add> actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1) <add> if actual != "nameserver 127.0.0.1 search mydomain" { <add> t.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: '%s'", actual) <add> } <add> <add> cmd = exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf") <add> <add> out, _, err = runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err, out) <add> } <add> <add> actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1) <add> if actual != "nameserver 127.0.0.1" { <add> t.Fatalf("expected 'nameserver 127.0.0.1', but says: '%s'", actual) <add> } <add> <add> logDone("run - dns options") <add>} <add> <add>func TestDnsOptionsBasedOnHostResolvConf(t *testing.T) { <add> resolvConf, err := ioutil.ReadFile("/etc/resolv.conf") <add> if os.IsNotExist(err) { <add> t.Fatalf("/etc/resolv.conf does not exist") <add> } <add> <add> hostNamservers := resolvconf.GetNameservers(resolvConf) <add> hostSearch := resolvconf.GetSearchDomains(resolvConf) <add> <add> cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf") <add> <add> out, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err, out) <add> } <add> <add> if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" { <add> t.Fatalf("expected '127.0.0.1', but says: '%s'", string(actualNameservers[0])) <add> } <add> <add> actualSearch := resolvconf.GetSearchDomains([]byte(out)) <add> if len(actualSearch) != len(hostSearch) { <add> t.Fatalf("expected '%s' search domain(s), but it has: '%s'", len(hostSearch), len(actualSearch)) <add> } <add> for i := range actualSearch { <add> if actualSearch[i] != hostSearch[i] { <add> t.Fatalf("expected '%s' domain, but says: '%s'", actualSearch[i], hostSearch[i]) <add> } <add> } <add> <add> cmd = exec.Command(dockerBinary, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf") <add> <add> out, _, err = runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err, out) <add> } <add> <add> actualNameservers := resolvconf.GetNameservers([]byte(out)) <add> if len(actualNameservers) != len(hostNamservers) { <add> t.Fatalf("expected '%s' nameserver(s), but it has: '%s'", len(hostNamservers), len(actualNameservers)) <add> } <add> for i := range actualNameservers { <add> if actualNameservers[i] != hostNamservers[i] { <add> t.Fatalf("expected '%s' nameserver, but says: '%s'", actualNameservers[i], hostNamservers[i]) <add> } <add> } <add> <add> if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" { <add> t.Fatalf("expected 'mydomain', but says: '%s'", string(actualSearch[0])) <add> } <add> <add> deleteAllContainers() <add> <add> logDone("run - dns options based on host resolv.conf") <add>} <ide><path>opts/opts.go <ide> func ValidateIp4Address(val string) (string, error) { <ide> return "", fmt.Errorf("%s is not an ip4 address", val) <ide> } <ide> <del>func ValidateDomain(val string) (string, error) { <add>// Validates domain for resolvconf search configuration. <add>// A zero length domain is represented by . <add>func ValidateDnsSearch(val string) (string, error) { <add> if val = strings.Trim(val, " "); val == "." { <add> return val, nil <add> } <add> return validateDomain(val) <add>} <add> <add>func validateDomain(val string) (string, error) { <ide> alpha := regexp.MustCompile(`[a-zA-Z]`) <ide> if alpha.FindString(val) == "" { <ide> return "", fmt.Errorf("%s is not a valid domain", val) <ide><path>opts/opts_test.go <ide> func TestValidateIP4(t *testing.T) { <ide> <ide> } <ide> <del>func TestValidateDomain(t *testing.T) { <add>func TestValidateDnsSearch(t *testing.T) { <ide> valid := []string{ <add> `.`, <ide> `a`, <ide> `a.`, <ide> `1.foo`, <ide> func TestValidateDomain(t *testing.T) { <ide> <ide> invalid := []string{ <ide> ``, <del> `.`, <add> ` `, <add> ` `, <ide> `17`, <ide> `17.`, <ide> `.17`, <ide> func TestValidateDomain(t *testing.T) { <ide> } <ide> <ide> for _, domain := range valid { <del> if ret, err := ValidateDomain(domain); err != nil || ret == "" { <del> t.Fatalf("ValidateDomain(`"+domain+"`) got %s %s", ret, err) <add> if ret, err := ValidateDnsSearch(domain); err != nil || ret == "" { <add> t.Fatalf("ValidateDnsSearch(`"+domain+"`) got %s %s", ret, err) <ide> } <ide> } <ide> <ide> for _, domain := range invalid { <del> if ret, err := ValidateDomain(domain); err == nil || ret != "" { <del> t.Fatalf("ValidateDomain(`"+domain+"`) got %s %s", ret, err) <add> if ret, err := ValidateDnsSearch(domain); err == nil || ret != "" { <add> t.Fatalf("ValidateDnsSearch(`"+domain+"`) got %s %s", ret, err) <ide> } <ide> } <ide> } <ide><path>pkg/networkfs/resolvconf/resolvconf.go <ide> func Build(path string, dns, dnsSearch []string) error { <ide> } <ide> } <ide> if len(dnsSearch) > 0 { <del> if _, err := content.WriteString("search " + strings.Join(dnsSearch, " ") + "\n"); err != nil { <del> return err <add> if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." { <add> if _, err := content.WriteString("search " + searchString + "\n"); err != nil { <add> return err <add> } <ide> } <ide> } <ide> <ide><path>pkg/networkfs/resolvconf/resolvconf_test.go <ide> func TestBuild(t *testing.T) { <ide> t.Fatalf("Expected to find '%s' got '%s'", expected, content) <ide> } <ide> } <add> <add>func TestBuildWithZeroLengthDomainSearch(t *testing.T) { <add> file, err := ioutil.TempFile("", "") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.Remove(file.Name()) <add> <add> err = Build(file.Name(), []string{"ns1", "ns2", "ns3"}, []string{"."}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> content, err := ioutil.ReadFile(file.Name()) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if expected := "nameserver ns1\nnameserver ns2\nnameserver ns3\n"; !bytes.Contains(content, []byte(expected)) { <add> t.Fatalf("Expected to find '%s' got '%s'", expected, content) <add> } <add> if notExpected := "search ."; bytes.Contains(content, []byte(notExpected)) { <add> t.Fatalf("Expected to not find '%s' got '%s'", notExpected, content) <add> } <add>} <ide><path>runconfig/parse.go <ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf <ide> flPublish opts.ListOpts <ide> flExpose opts.ListOpts <ide> flDns opts.ListOpts <del> flDnsSearch = opts.NewListOpts(opts.ValidateDomain) <add> flDnsSearch = opts.NewListOpts(opts.ValidateDnsSearch) <ide> flVolumesFrom opts.ListOpts <ide> flLxcOpts opts.ListOpts <ide> flEnvFile opts.ListOpts
7
Javascript
Javascript
remove dependency on window.settimeout
021bdf3922b6525bd117e59fb4945b30a5a55341
<ide><path>src/Angular.js <ide> function bootstrap(element, modules) { <ide> }]); <ide> modules.unshift('ng'); <ide> var injector = createInjector(modules); <del> injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', <del> function(scope, element, compile, injector) { <add> injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animator', <add> function(scope, element, compile, injector, animator) { <ide> scope.$apply(function() { <ide> element.data('$injector', injector); <ide> compile(element)(scope); <ide> }); <add> animator.enabled(true); <ide> }] <ide> ); <ide> return injector; <ide><path>src/ng/animator.js <ide> var $AnimatorProvider = function() { <ide> this.$get = ['$animation', '$window', '$sniffer', '$rootElement', '$rootScope', <ide> function($animation, $window, $sniffer, $rootElement, $rootScope) { <ide> $rootElement.data(NG_ANIMATE_CONTROLLER, rootAnimateController); <del> var unregister = $rootScope.$watch(function() { <del> unregister(); <del> if (rootAnimateController.running) { <del> $window.setTimeout(function() { <del> rootAnimateController.running = false; <del> }, 0); <del> } <del> }); <ide> <ide> /** <ide> * @ngdoc function <ide><path>test/ng/animatorSpec.js <ide> describe("$animator", function() { <ide> }); <ide> }); <ide> <del> it("should disable and enable the animations", inject(function($animator, $rootScope, $window) { <del> expect($animator.enabled()).toBe(false); <add> it("should disable and enable the animations", function() { <add> var initialState = null; <add> var animator; <ide> <del> $rootScope.$digest(); <del> $window.setTimeout.expect(0).process(); <add> angular.bootstrap(body, [function() { <add> return function($animator) { <add> animator = $animator; <add> initialState = $animator.enabled(); <add> } <add> }]); <ide> <del> expect($animator.enabled()).toBe(true); <add> expect(initialState).toBe(false); <ide> <del> expect($animator.enabled(0)).toBe(false); <del> expect($animator.enabled()).toBe(false); <add> expect(animator.enabled()).toBe(true); <ide> <del> expect($animator.enabled(1)).toBe(true); <del> expect($animator.enabled()).toBe(true); <del> })); <add> expect(animator.enabled(0)).toBe(false); <add> expect(animator.enabled()).toBe(false); <add> <add> expect(animator.enabled(1)).toBe(true); <add> expect(animator.enabled()).toBe(true); <add> }); <ide> <ide> }); <ide> <ide> describe("$animator", function() { <ide> ngAnimate : '{enter: \'custom\'}' <ide> }); <ide> <del> $rootScope.$digest(); // re-enable the animations; <del> window.setTimeout.expect(0).process(); <del> <ide> expect(element.contents().length).toBe(0); <ide> animator.enter(child, element); <ide> window.setTimeout.expect(1).process(); <ide> describe("$animator", function() { <ide> ngAnimate : '{leave: \'custom\'}' <ide> }); <ide> <del> $rootScope.$digest(); // re-enable the animations; <del> window.setTimeout.expect(0).process(); <del> <ide> element.append(child); <ide> expect(element.contents().length).toBe(1); <ide> animator.leave(child, element);
3
Go
Go
remove redundant return nil
9788822421255a0516a0e3ce2ac32b1ec9d7d894
<ide><path>daemon/cluster/cluster.go <ide> func (c *Cluster) RemoveService(input string) error { <ide> return err <ide> } <ide> <del> if _, err := state.controlClient.RemoveService(ctx, &swarmapi.RemoveServiceRequest{ServiceID: service.ID}); err != nil { <del> return err <del> } <del> return nil <add> _, err = state.controlClient.RemoveService(ctx, &swarmapi.RemoveServiceRequest{ServiceID: service.ID}) <add> return err <ide> } <ide> <ide> // ServiceLogs collects service logs and writes them back to `config.OutStream` <ide> func (c *Cluster) RemoveNode(input string, force bool) error { <ide> return err <ide> } <ide> <del> if _, err := state.controlClient.RemoveNode(ctx, &swarmapi.RemoveNodeRequest{NodeID: node.ID, Force: force}); err != nil { <del> return err <del> } <del> return nil <add> _, err = state.controlClient.RemoveNode(ctx, &swarmapi.RemoveNodeRequest{NodeID: node.ID, Force: force}) <add> return err <ide> } <ide> <ide> // GetTasks returns a list of tasks matching the filter options. <ide> func (c *Cluster) RemoveNetwork(input string) error { <ide> return err <ide> } <ide> <del> if _, err := state.controlClient.RemoveNetwork(ctx, &swarmapi.RemoveNetworkRequest{NetworkID: network.ID}); err != nil { <del> return err <del> } <del> return nil <add> _, err = state.controlClient.RemoveNetwork(ctx, &swarmapi.RemoveNetworkRequest{NetworkID: network.ID}) <add> return err <ide> } <ide> <ide> func (c *Cluster) populateNetworkID(ctx context.Context, client swarmapi.ControlClient, s *types.ServiceSpec) error {
1
Javascript
Javascript
remove moz statements from requestanimationframe
7d09bd30f9fc2c265588323817b541fd26b9abe0
<ide><path>src/ngAnimate/animate.js <ide> angular.module('ngAnimate', ['ng']) <ide> */ <ide> .factory('$$animateReflow', ['$window', '$timeout', function($window, $timeout) { <ide> var requestAnimationFrame = $window.requestAnimationFrame || <del> $window.mozRequestAnimationFrame || <ide> $window.webkitRequestAnimationFrame || <ide> function(fn) { <ide> return $timeout(fn, 10, false); <ide> }; <ide> <ide> var cancelAnimationFrame = $window.cancelAnimationFrame || <del> $window.mozCancelAnimationFrame || <ide> $window.webkitCancelAnimationFrame || <ide> function(timer) { <ide> return $timeout.cancel(timer);
1
Java
Java
remove todos related to profile logging
150838bfc13a136ef0baf943e378a8ebb5f3549f
<ide><path>org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java <ide> /* <del> * Copyright 2002-2010 the original author or authors. <add> * Copyright 2002-2011 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected void doRegisterBeanDefinitions(Element root) { <ide> Assert.state(this.environment != null, "environment property must not be null"); <ide> String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); <ide> if (!this.environment.acceptsProfiles(specifiedProfiles)) { <del> // TODO SPR-7508: log that this bean is being rejected on profile mismatch <ide> return; <ide> } <ide> } <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotatedBeanDefinitionReader.java <ide> public void registerBean(Class<?> annotatedClass, String name, Class<? extends A <ide> <ide> if (ProfileHelper.isProfileAnnotationPresent(metadata)) { <ide> if (!this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata))) { <del> // TODO SPR-7508: log that this bean is being rejected on profile mismatch <ide> return; <ide> } <ide> } <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java <ide> protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOE <ide> if (!ProfileHelper.isProfileAnnotationPresent(metadata)) { <ide> return true; <ide> } <del> // TODO SPR-7508: log that this bean is being rejected on profile mismatch <ide> return this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata)); <ide> } <ide> } <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java <ide> /* <del> * Copyright 2002-2010 the original author or authors. <add> * Copyright 2002-2011 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected void processConfigurationClass(ConfigurationClass configClass) throws <ide> AnnotationMetadata metadata = configClass.getMetadata(); <ide> if (this.environment != null && ProfileHelper.isProfileAnnotationPresent(metadata)) { <ide> if (!this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata))) { <del> // TODO SPR-7508: log that this bean is being rejected on profile mismatch <ide> return; <ide> } <ide> } <ide><path>org.springframework.core/src/main/java/org/springframework/core/env/MutablePropertySources.java <ide> protected void assertLegalRelativeAddition(String relativePropertySourceName, Pr <ide> */ <ide> protected void removeIfPresent(PropertySource<?> propertySource) { <ide> if (this.propertySourceList.contains(propertySource)) { <del> // TODO SPR-7508: add logging <ide> this.propertySourceList.remove(propertySource); <ide> } <ide> }
5
Javascript
Javascript
fix the type of svggraphics
d72bbecee23c0bca0998b9dce64179c1a2691a62
<ide><path>src/display/svg.js <ide> import { <ide> import { DOMSVGFactory } from "./display_utils.js"; <ide> import { isNodeJS } from "../shared/is_node.js"; <ide> <add>/** @type {any} */ <ide> let SVGGraphics = function () { <ide> throw new Error("Not implemented: SVGGraphics"); <ide> };
1
Go
Go
update documents of `detect`
0bbd476ceb8da679f818df529cc917ec807a16af
<ide><path>builder/remotecontext/detect.go <ide> import ( <ide> const ClientSessionRemote = "client-session" <ide> <ide> // Detect returns a context and dockerfile from remote location or local <del>// archive. progressReader is only used if remoteURL is actually a URL <del>// (not empty, and not a Git endpoint). <add>// archive. <ide> func Detect(config backend.BuildConfig) (remote builder.Source, dockerfile *parser.Result, err error) { <ide> remoteURL := config.Options.RemoteContext <ide> dockerfilePath := config.Options.Dockerfile
1
PHP
PHP
add allteststest for skeleton app
0661d7832b2b12ba76a3dd407fc75d39c62028ca
<ide><path>lib/Cake/Console/Templates/skel/Test/Case/AllTestsTest.php <add><?php <add>/** <add> * AllTests file <add> * <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @package app.Test.Case <add> * @since CakePHP(tm) v 2.5 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add> <add>class AllTestsTest extends CakeTestSuite { <add> <add> public static function suite() { <add> $suite = new CakeTestSuite('All application tests'); <add> $suite->addTestDirectoryRecursive(TESTS . 'Case'); <add> return $suite; <add> } <add>} <ide>\ No newline at end of file
1
Ruby
Ruby
replace array#shuffle.first with array#sample
2b6bacd1927830e23bf99ed319a067c004ae92ac
<ide><path>actionpack/lib/action_dispatch/journey/gtg/transition_table.rb <ide> def visualizer(paths, title = 'FSM') <ide> erb = File.read File.join(viz_dir, 'index.html.erb') <ide> states = "function tt() { return #{to_json}; }" <ide> <del> fun_routes = paths.shuffle.first(3).map do |ast| <add> fun_routes = paths.sample(3).map do |ast| <ide> ast.map { |n| <ide> case n <ide> when Nodes::Symbol <ide> case n.left <ide> when ':id' then rand(100).to_s <del> when ':format' then %w{ xml json }.shuffle.first <add> when ':format' then %w{ xml json }.sample <ide> else <ide> 'omg' <ide> end
1
Ruby
Ruby
allow strings as update assignments
3e6ad6e5838d20c946d7a286cb34be12aae177ff
<ide><path>lib/arel/engines/sql/relations/writes.rb <ide> def to_sql(formatter = nil) <ide> protected <ide> <ide> def assignment_sql <del> assignments.collect do |attribute, value| <del> "#{engine.quote_column_name(attribute.name)} = #{attribute.format(value)}" <del> end.join(",\n") <add> if assignments.respond_to?(:collect) <add> assignments.collect do |attribute, value| <add> "#{engine.quote_column_name(attribute.name)} = #{attribute.format(value)}" <add> end.join(",\n") <add> else <add> assignments.value <add> end <ide> end <ide> end <ide> end
1
Java
Java
add option to always append 'must-revalidate'
68d4a70f8e7315d227b7727b087a65e64f4b0f9e
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.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 org.springframework.util.StringUtils; <ide> import org.springframework.web.HttpRequestMethodNotSupportedException; <ide> import org.springframework.web.HttpSessionRequiredException; <add>import org.springframework.web.context.request.WebRequest; <ide> import org.springframework.web.context.support.WebApplicationObjectSupport; <add>import org.springframework.web.servlet.mvc.LastModified; <ide> <ide> /** <ide> * Convenient superclass for any kind of web content generator, <ide> public abstract class WebContentGenerator extends WebApplicationObjectSupport { <ide> <ide> private int cacheSeconds = -1; <ide> <add> private boolean alwaysMustRevalidate = false; <add> <ide> <ide> /** <ide> * Create a new WebContentGenerator which supports <ide> public final boolean isUseCacheControlNoStore() { <ide> return this.useCacheControlNoStore; <ide> } <ide> <add> /** <add> * An option to add 'must-revalidate' to every Cache-Control header. This <add> * may be useful with annotated controller methods, which can <add> * programmatically do a lastModified calculation as described in <add> * {@link WebRequest#checkNotModified(long)}. Default is "false", <add> * effectively relying on whether the handler implements <add> * {@link LastModified} or not. <add> */ <add> public void setAlwaysMustRevalidate(boolean mustRevalidate) { <add> this.alwaysMustRevalidate = mustRevalidate; <add> } <add> <add> /** <add> * Return whether 'must-revaliate' is added to every Cache-Control header. <add> */ <add> public boolean isAlwaysMustRevalidate() { <add> return alwaysMustRevalidate; <add> } <add> <ide> /** <ide> * Cache content for the given number of seconds. Default is -1, <ide> * indicating no generation of cache-related headers. <ide> protected final void cacheForSeconds(HttpServletResponse response, int seconds, <ide> if (this.useCacheControlHeader) { <ide> // HTTP 1.1 header <ide> String headerValue = "max-age=" + seconds; <del> if (mustRevalidate) { <add> if (mustRevalidate || this.alwaysMustRevalidate) { <ide> headerValue += ", must-revalidate"; <ide> } <ide> response.setHeader(HEADER_CACHE_CONTROL, headerValue);
1
Javascript
Javascript
use memorize util instead of lazyrequire
faea05d195a0733ba6cbb34d3cf00fbaf5527818
<ide><path>lib/asset/AssetModulesPlugin.js <ide> <ide> "use strict"; <ide> <add>const memorize = require("../util/memorize"); <ide> const validateOptions = require("schema-utils"); <ide> const { compareModulesByIdentifier } = require("../util/comparators"); <ide> <ide> const { compareModulesByIdentifier } = require("../util/comparators"); <ide> /** @typedef {import("../Compiler")} Compiler */ <ide> /** @typedef {import("../Module")} Module */ <ide> <del>const lazyRequire = require("../util/lazyRequire")(require); <del>const generatorSchema = lazyRequire( <del> "../../schemas/plugins/AssetModulesPluginGenerator.json", <del> false <add>const getGeneratorSchema = memorize(() => <add> require("../../schemas/plugins/AssetModulesPluginGenerator.json") <ide> ); <del>const parserSchema = lazyRequire( <del> "../../schemas/plugins/AssetModulesPluginParser.json", <del> false <add>const getParserSchema = memorize(() => <add> require("../../schemas/plugins/AssetModulesPluginParser.json") <add>); <add>const getAssetGenerator = memorize(() => require("./AssetGenerator")); <add>const getAssetParser = memorize(() => require("./AssetParser")); <add>const getAssetSourceGenerator = memorize(() => <add> require("./AssetSourceGenerator") <ide> ); <del>/** @type {typeof import('./AssetGenerator')} */ <del>const AssetGenerator = lazyRequire("./AssetGenerator"); <del>/** @type {typeof import('./AssetParser')} */ <del>const AssetParser = lazyRequire("./AssetParser"); <del>/** @type {typeof import('./AssetSourceGenerator')} */ <del>const AssetSourceGenerator = lazyRequire("./AssetSourceGenerator"); <ide> <ide> const type = "asset"; <ide> const plugin = "AssetModulesPlugin"; <ide> class AssetModulesPlugin { <ide> normalModuleFactory.hooks.createParser <ide> .for("asset") <ide> .tap(plugin, parserOptions => { <del> validateOptions(parserSchema, parserOptions, { <add> validateOptions(getParserSchema(), parserOptions, { <ide> name: "Asset Modules Plugin", <ide> baseDataPath: "parser" <ide> }); <ide> class AssetModulesPlugin { <ide> }; <ide> } <ide> <add> const AssetParser = getAssetParser(); <add> <ide> return new AssetParser(dataUrlCondition); <ide> }); <ide> normalModuleFactory.hooks.createParser <ide> .for("asset/inline") <del> .tap(plugin, parserOptions => new AssetParser(true)); <add> .tap(plugin, parserOptions => { <add> const AssetParser = getAssetParser(); <add> <add> return new AssetParser(true); <add> }); <ide> normalModuleFactory.hooks.createParser <ide> .for("asset/resource") <del> .tap(plugin, parserOptions => new AssetParser(false)); <add> .tap(plugin, parserOptions => { <add> const AssetParser = getAssetParser(); <add> <add> return new AssetParser(false); <add> }); <ide> normalModuleFactory.hooks.createParser <ide> .for("asset/source") <del> .tap(plugin, parserOptions => new AssetParser(false)); <add> .tap(plugin, parserOptions => { <add> const AssetParser = getAssetParser(); <add> <add> return new AssetParser(false); <add> }); <ide> <ide> for (const type of ["asset", "asset/inline"]) { <ide> normalModuleFactory.hooks.createGenerator <ide> .for(type) <ide> // eslint-disable-next-line no-loop-func <ide> .tap(plugin, generatorOptions => { <del> validateOptions(generatorSchema, generatorOptions, { <add> validateOptions(getGeneratorSchema(), generatorOptions, { <ide> name: "Asset Modules Plugin", <ide> baseDataPath: "generator" <ide> }); <ide> class AssetModulesPlugin { <ide> }; <ide> } <ide> <add> const AssetGenerator = getAssetGenerator(); <add> <ide> return new AssetGenerator(compilation, dataUrl); <ide> }); <ide> } <ide> normalModuleFactory.hooks.createGenerator <ide> .for("asset/resource") <del> .tap(plugin, () => new AssetGenerator(compilation)); <add> .tap(plugin, () => { <add> const AssetGenerator = getAssetGenerator(); <add> <add> return new AssetGenerator(compilation); <add> }); <ide> normalModuleFactory.hooks.createGenerator <ide> .for("asset/source") <del> .tap(plugin, () => new AssetSourceGenerator()); <add> .tap(plugin, () => { <add> const AssetSourceGenerator = getAssetSourceGenerator(); <add> <add> return new AssetSourceGenerator(); <add> }); <ide> <ide> compilation.hooks.renderManifest.tap(plugin, (result, options) => { <ide> const { chunkGraph } = compilation; <ide><path>lib/json/JsonModulesPlugin.js <ide> <ide> "use strict"; <ide> <add>const memorize = require("../util/memorize"); <ide> const validateOptions = require("schema-utils"); <ide> const JsonGenerator = require("./JsonGenerator"); <ide> const JsonParser = require("./JsonParser"); <ide> <ide> /** @typedef {import("../Compiler")} Compiler */ <ide> <del>const lazyRequire = require("../util/lazyRequire")(require); <del>const parserSchema = lazyRequire( <del> "../../schemas/plugins/JsonModulesPluginParser.json", <del> false <add>const getParserSchema = memorize(() => <add> require("../../schemas/plugins/JsonModulesPluginParser.json") <ide> ); <ide> <ide> class JsonModulesPlugin { <ide> class JsonModulesPlugin { <ide> normalModuleFactory.hooks.createParser <ide> .for("json") <ide> .tap("JsonModulesPlugin", parserOptions => { <del> validateOptions(parserSchema, parserOptions, { <add> validateOptions(getParserSchema(), parserOptions, { <ide> name: "Json Modules Plugin", <ide> baseDataPath: "parser" <ide> }); <ide><path>lib/util/lazyRequire.js <del>/* <del> MIT License http://www.opensource.org/licenses/mit-license.php <del> Author Ivan Kopeykin @vankop <del>*/ <del> <del>"use strict"; <del> <del>/* Fork from https://github.com/sindresorhus/import-lazy */ <del> <del>const lazy = (importedModule, requireFn, moduleId) => <del> importedModule === undefined ? requireFn(moduleId) : importedModule; <del> <del>/** <del> * @template T <del> * @callback LazyRequire <del> * @param {string} moduleId path to module <del> * @param {boolean} [isFunction] flag for Proxy type, <del> * if true returns function, object otherwise. <del> * True by default since webpack modules are mostly functions or classes <del> * @returns {T} module export <del> */ <del> <del>/** <del> * @template T <del> * @param {Function} requireFn require function relative to parent module <del> * @returns {LazyRequire<T>} require function <del> */ <del>module.exports = requireFn => (moduleId, isFunction = true) => { <del> let importedModule; <del> <del> const handler = { <del> get: (target, property) => { <del> importedModule = lazy(importedModule, requireFn, moduleId); <del> return Reflect.get(importedModule, property); <del> }, <del> apply: (target, thisArgument, argumentsList) => { <del> importedModule = lazy(importedModule, requireFn, moduleId); <del> return Reflect.apply(importedModule, thisArgument, argumentsList); <del> }, <del> construct: (target, argumentsList) => { <del> importedModule = lazy(importedModule, requireFn, moduleId); <del> return Reflect.construct(importedModule, argumentsList); <del> } <del> }; <del> <del> return new Proxy(isFunction ? function() {} : {}, handler); <del>}; <ide><path>lib/wasm-async/AsyncWebAssemblyModulesPlugin.js <ide> "use strict"; <ide> <ide> const { SyncWaterfallHook } = require("tapable"); <add>const memorize = require("../util/memorize"); <ide> const Compilation = require("../Compilation"); <ide> const Generator = require("../Generator"); <ide> const { tryRunOrWebpackError } = require("../HookWebpackError"); <ide> const { compareModulesByIdentifier } = require("../util/comparators"); <ide> /** @typedef {import("../Template").RenderManifestEntry} RenderManifestEntry */ <ide> /** @typedef {import("../Template").RenderManifestOptions} RenderManifestOptions */ <ide> <del>const lazyRequire = require("../util/lazyRequire")(require); <del>/** @type {typeof import('./AsyncWebAssemblyGenerator')} */ <del>const AsyncWebAssemblyGenerator = lazyRequire("./AsyncWebAssemblyGenerator"); <del>/** @type {typeof import('./AsyncWebAssemblyJavascriptGenerator')} */ <del>const AsyncWebAssemblyJavascriptGenerator = lazyRequire( <del> "./AsyncWebAssemblyJavascriptGenerator" <add>const getAsyncWebAssemblyGenerator = memorize(() => <add> require("./AsyncWebAssemblyGenerator") <add>); <add>const getAsyncWebAssemblyJavascriptGenerator = memorize(() => <add> require("./AsyncWebAssemblyJavascriptGenerator") <add>); <add>const getAsyncWebAssemblyParser = memorize(() => <add> require("./AsyncWebAssemblyParser") <ide> ); <del>/** @type {typeof import('./AsyncWebAssemblyParser')} */ <del>const AsyncWebAssemblyParser = lazyRequire("./AsyncWebAssemblyParser"); <ide> <ide> /** <ide> * @typedef {Object} RenderContext <ide> class AsyncWebAssemblyModulesPlugin { <ide> <ide> normalModuleFactory.hooks.createParser <ide> .for("webassembly/async") <del> .tap( <del> "AsyncWebAssemblyModulesPlugin", <del> () => new AsyncWebAssemblyParser() <del> ); <add> .tap("AsyncWebAssemblyModulesPlugin", () => { <add> const AsyncWebAssemblyParser = getAsyncWebAssemblyParser(); <add> <add> return new AsyncWebAssemblyParser(); <add> }); <ide> normalModuleFactory.hooks.createGenerator <ide> .for("webassembly/async") <ide> .tap("AsyncWebAssemblyModulesPlugin", () => { <add> const AsyncWebAssemblyJavascriptGenerator = getAsyncWebAssemblyJavascriptGenerator(); <add> const AsyncWebAssemblyGenerator = getAsyncWebAssemblyGenerator(); <add> <ide> return Generator.byType({ <ide> javascript: new AsyncWebAssemblyJavascriptGenerator( <ide> compilation.outputOptions.webassemblyModuleFilename <ide><path>lib/wasm/WebAssemblyModulesPlugin.js <ide> "use strict"; <ide> <ide> const Generator = require("../Generator"); <add>const memorize = require("../util/memorize"); <ide> const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); <ide> const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); <ide> const { compareModulesByIdentifier } = require("../util/comparators"); <ide> const WebAssemblyInInitialChunkError = require("./WebAssemblyInInitialChunkError <ide> /** @typedef {import("../ModuleTemplate")} ModuleTemplate */ <ide> /** @typedef {import("../ModuleTemplate").RenderContext} RenderContext */ <ide> <del>const lazyRequire = require("../util/lazyRequire")(require); <del> <del>/** @type {typeof import('./WebAssemblyGenerator')} */ <del>const WebAssemblyGenerator = lazyRequire("./WebAssemblyGenerator"); <del>/** @type {typeof import('./WebAssemblyJavascriptGenerator')} */ <del>const WebAssemblyJavascriptGenerator = lazyRequire( <del> "./WebAssemblyJavascriptGenerator" <add>const getWebAssemblyGenerator = memorize(() => <add> require("./WebAssemblyGenerator") <add>); <add>const getWebAssemblyJavascriptGenerator = memorize(() => <add> require("./WebAssemblyJavascriptGenerator") <ide> ); <del>/** @type {typeof import('./WebAssemblyParser')} */ <del>const WebAssemblyParser = lazyRequire("./WebAssemblyParser"); <add>const getWebAssemblyParser = memorize(() => require("./WebAssemblyParser")); <ide> <ide> class WebAssemblyModulesPlugin { <ide> constructor(options) { <ide> class WebAssemblyModulesPlugin { <ide> <ide> normalModuleFactory.hooks.createParser <ide> .for("webassembly/sync") <del> .tap("WebAssemblyModulesPlugin", () => new WebAssemblyParser()); <add> .tap("WebAssemblyModulesPlugin", () => { <add> const WebAssemblyParser = getWebAssemblyParser(); <add> <add> return new WebAssemblyParser(); <add> }); <ide> <ide> normalModuleFactory.hooks.createGenerator <ide> .for("webassembly/sync") <ide> .tap("WebAssemblyModulesPlugin", () => { <add> const WebAssemblyJavascriptGenerator = getWebAssemblyJavascriptGenerator(); <add> const WebAssemblyGenerator = getWebAssemblyGenerator(); <add> <ide> return Generator.byType({ <ide> javascript: new WebAssemblyJavascriptGenerator(), <ide> webassembly: new WebAssemblyGenerator(this.options)
5
PHP
PHP
add support for "where value" subqueries
2227c446fcecb365346a08de203c1997de96a931
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function whereKeyNot($id) <ide> */ <ide> public function where($column, $operator = null, $value = null, $boolean = 'and') <ide> { <del> if ($column instanceof Closure) { <add> if ($column instanceof Closure && is_null($operator)) { <ide> $column($query = $this->model->newQueryWithoutRelationships()); <ide> <ide> $this->query->addNestedWhereQuery($query->getQuery(), $boolean); <ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function where($column, $operator = null, $value = null, $boolean = 'and' <ide> // If the columns is actually a Closure instance, we will assume the developer <ide> // wants to begin a nested where statement which is wrapped in parenthesis. <ide> // We'll add that Closure to the query then return back out immediately. <del> if ($column instanceof Closure) { <add> if ($column instanceof Closure && is_null($operator)) { <ide> return $this->whereNested($column, $boolean); <ide> } <ide> <add> // If the column is a Closure instance and there an operator set, we will <add> // assume the developer wants to run a subquery and then compare the <add> // results of the subquery with the value that was provided. <add> if ($column instanceof Closure && ! is_null($operator)) { <add> list($sub, $bindings) = $this->createSub($column); <add> <add> return $this->addBinding($bindings, 'where') <add> ->where(new Expression('('.$sub.')'), $operator, $value, $boolean); <add> } <add> <ide> // If the given operator is not found in the list of valid operators we will <ide> // assume that the developer is just short-cutting the '=' operators and <ide> // we will set the operators to '=' and set the values appropriately.
2
Go
Go
fix a race in cleaning up after journald followers
52c0f36f7b7aa794932fa41dfe50dc85f78e6146
<ide><path>daemon/logger/journald/read.go <ide> func (s *journald) followJournal(logWatcher *logger.LogWatcher, config logger.Re <ide> s.readers.mu.Lock() <ide> delete(s.readers.readers, logWatcher) <ide> s.readers.mu.Unlock() <add> C.sd_journal_close(j) <add> close(logWatcher.Msg) <ide> }() <ide> // Wait until we're told to stop. <ide> select { <ide> func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadCon <ide> var pipes [2]C.int <ide> cursor := "" <ide> <del> defer close(logWatcher.Msg) <ide> // Get a handle to the journal. <ide> rc := C.sd_journal_open(&j, C.int(0)) <ide> if rc != 0 { <ide> logWatcher.Err <- fmt.Errorf("error opening journal") <add> close(logWatcher.Msg) <ide> return <ide> } <del> defer C.sd_journal_close(j) <add> // If we end up following the log, we can set the journal context <add> // pointer and the channel pointer to nil so that we won't close them <add> // here, potentially while the goroutine that uses them is still <add> // running. Otherwise, close them when we return from this function. <add> following := false <add> defer func(pfollowing *bool) { <add> if !*pfollowing { <add> C.sd_journal_close(j) <add> close(logWatcher.Msg) <add> } <add> }(&following) <ide> // Remove limits on the size of data items that we'll retrieve. <ide> rc = C.sd_journal_set_data_threshold(j, C.size_t(0)) <ide> if rc != 0 { <ide> func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadCon <ide> logWatcher.Err <- fmt.Errorf("error opening journald close notification pipe") <ide> } else { <ide> s.followJournal(logWatcher, config, j, pipes, cursor) <add> // Let followJournal handle freeing the journal context <add> // object and closing the channel. <add> following = true <ide> } <ide> } <ide> return
1