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 minimal requirements | 820ee847ac141910d9eddab02dceb3ca93dfd84e | <ide><path>docs/Homebrew-on-Linux.md
<ide> If you're using an older distribution of Linux, installing your first package wi
<ide>
<ide> ## Linux/WSL Requirements
<ide>
<del>+ **GCC** 4.4 or newer
<add>+ **GCC** 4.7.0 or newer
<ide> + **Linux** 2.6.32 or newer
<del>+ **Glibc** 2.12 or newer
<add>+ **Glibc** 2.13 or newer
<ide> + **64-bit x86_64** CPU
<ide>
<ide> Paste at a terminal prompt: | 1 |
Ruby | Ruby | allow write access to /dev/random | 53a677aba6f28a148c9950cfde7f73fda5cdf81f | <ide><path>Library/Homebrew/sandbox.rb
<ide> class SandboxProfile
<ide> (literal "/dev/ptmx")
<ide> (literal "/dev/dtracehelper")
<ide> (literal "/dev/null")
<add> (literal "/dev/random")
<ide> (literal "/dev/zero")
<ide> (regex #"^/dev/fd/[0-9]+$")
<ide> (regex #"^/dev/ttys?[0-9]*$") | 1 |
Javascript | Javascript | add comment describing test-fs-mkdir | d8ef9811a726c84c4b6803436235642d87ec47ea | <ide><path>test/parallel/test-fs-mkdir.js
<ide> function nextdir() {
<ide> return `test${++dirc}`;
<ide> }
<ide>
<add>// mkdir creates directory using assigned path
<ide> {
<ide> const pathname = path.join(tmpdir.path, nextdir());
<ide>
<ide> function nextdir() {
<ide> }));
<ide> }
<ide>
<add>// mkdir creates directory with assigned mode value
<ide> {
<ide> const pathname = path.join(tmpdir.path, nextdir());
<ide>
<ide> function nextdir() {
<ide> }));
<ide> }
<ide>
<add>// mkdirSync successfully creates directory from given path
<ide> {
<ide> const pathname = path.join(tmpdir.path, nextdir());
<ide>
<ide> function nextdir() {
<ide> assert.strictEqual(exists, true);
<ide> }
<ide>
<add>// mkdirSync and mkdir require path to be a string, buffer or url.
<add>// Anything else generates an error.
<ide> [false, 1, {}, [], null, undefined].forEach((i) => {
<ide> common.expectsError(
<ide> () => fs.mkdir(i, common.mustNotCall()), | 1 |
Text | Text | update items to equal an array | 75857bec01d8a8ae56cf0e85f738ea02d42c639e | <ide><path>docs/upgrading/upgrading-your-package.md
<ide> class CommandPaletteView extends SelectListView
<ide> attach: ->
<ide> @storeFocusedElement()
<ide>
<del> items = # build items
<add> items = [] # TODO: build items
<ide> @setItems(items)
<ide>
<ide> atom.workspaceView.append(this) | 1 |
Ruby | Ruby | fix cellar output | 4eb7116c9cc0175a37e5c2fd2c1bc2b85bd799b0 | <ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def bottle_output bottle
<ide> puts "bottle do"
<ide> prefix = bottle.prefix.to_s
<ide> puts " prefix '#{prefix}'" if prefix != '/usr/local'
<del> cellar = bottle.cellar.to_s
<del> cellar = ":#{bottle.cellar}" if bottle.cellar.is_a? Symbol
<del> puts " cellar '#{cellar}'" if bottle.cellar.to_s != '/usr/local/Cellar'
<add> cellar = if bottle.cellar.is_a? Symbol
<add> ":#{bottle.cellar}"
<add> elsif bottle.cellar.to_s != '/usr/local/Cellar'
<add> "'bottle.cellar'"
<add> end
<add> puts " cellar #{cellar}" if cellar
<ide> puts " revision #{bottle.revision}" if bottle.revision > 0
<ide> Checksum::TYPES.each do |checksum_type|
<ide> checksum_os_versions = bottle.send checksum_type | 1 |
Ruby | Ruby | add constraints to resources in new routing dsl | e1a70faea675499d717cef7662262ceb03b23975 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def initialize(*args)
<ide>
<ide> def scope(*args)
<ide> options = args.extract_options!
<add> options = options.dup
<ide>
<ide> case args.first
<ide> when String
<ide> def name_for_action(action)
<ide> def id_segment
<ide> ":#{singular}_id"
<ide> end
<add>
<add> def constraints
<add> options[:constraints] || {}
<add> end
<add>
<add> def id_constraint?
<add> options[:id] && options[:id].is_a?(Regexp) || constraints[:id] && constraints[:id].is_a?(Regexp)
<add> end
<add>
<add> def id_constraint
<add> options[:id] || constraints[:id]
<add> end
<add>
<add> def collection_options
<add> (options || {}).dup.tap do |options|
<add> options.delete(:id)
<add> options[:constraints] = options[:constraints].dup if options[:constraints]
<add> options[:constraints].delete(:id) if options[:constraints].is_a?(Hash)
<add> end
<add> end
<add>
<add> def nested_options
<add> options = { :name_prefix => member_name }
<add> options["#{singular}_id".to_sym] = id_constraint if id_constraint?
<add> options
<add> end
<ide> end
<ide>
<ide> class SingletonResource < Resource #:nodoc:
<ide> def resource(*resources, &block)
<ide> yield if block_given?
<ide> end
<ide>
<del> get :show if resource.actions.include?(:show)
<del> post :create if resource.actions.include?(:create)
<del> put :update if resource.actions.include?(:update)
<del> delete :destroy if resource.actions.include?(:destroy)
<del> get :new, :as => resource.name if resource.actions.include?(:new)
<del> get :edit, :as => resource.name if resource.actions.include?(:edit)
<add> scope(resource.options) do
<add> get :show if resource.actions.include?(:show)
<add> post :create if resource.actions.include?(:create)
<add> put :update if resource.actions.include?(:update)
<add> delete :destroy if resource.actions.include?(:destroy)
<add> get :new, :as => resource.name if resource.actions.include?(:new)
<add> get :edit, :as => resource.name if resource.actions.include?(:edit)
<add> end
<ide> end
<ide> end
<ide>
<ide> def resources(*resources, &block)
<ide> yield if block_given?
<ide>
<ide> with_scope_level(:collection) do
<del> get :index if resource.actions.include?(:index)
<del> post :create if resource.actions.include?(:create)
<del> get :new, :as => resource.singular if resource.actions.include?(:new)
<add> scope(resource.collection_options) do
<add> get :index if resource.actions.include?(:index)
<add> post :create if resource.actions.include?(:create)
<add> get :new, :as => resource.singular if resource.actions.include?(:new)
<add> end
<ide> end
<ide>
<ide> with_scope_level(:member) do
<ide> scope(':id') do
<del> get :show if resource.actions.include?(:show)
<del> put :update if resource.actions.include?(:update)
<del> delete :destroy if resource.actions.include?(:destroy)
<del> get :edit, :as => resource.singular if resource.actions.include?(:edit)
<add> scope(resource.options) do
<add> get :show if resource.actions.include?(:show)
<add> put :update if resource.actions.include?(:update)
<add> delete :destroy if resource.actions.include?(:destroy)
<add> get :edit, :as => resource.singular if resource.actions.include?(:edit)
<add> end
<ide> end
<ide> end
<ide> end
<ide> def nested
<ide> end
<ide>
<ide> with_scope_level(:nested) do
<del> scope(parent_resource.id_segment, :name_prefix => parent_resource.member_name) do
<add> scope(parent_resource.id_segment, parent_resource.nested_options) do
<ide> yield
<ide> end
<ide> end
<ide><path>actionpack/test/dispatch/routing_test.rb
<ide> def self.matches?(request)
<ide> resources :descriptions
<ide> root :to => 'projects#index'
<ide> end
<add>
<add> resources :products, :constraints => { :id => /\d{4}/ } do
<add> resources :images
<add> end
<add>
<add> resource :dashboard, :constraints => { :ip => /192\.168\.1\.\d{1,3}/ }
<ide> end
<ide> end
<ide>
<ide> def test_default_params
<ide> end
<ide> end
<ide>
<add> def test_resource_constraints
<add> with_test_routes do
<add> assert_raise(ActionController::RoutingError) { get '/products/1' }
<add> get '/products'
<add> assert_equal 'products#index', @response.body
<add> get '/products/0001'
<add> assert_equal 'products#show', @response.body
<add>
<add> assert_raise(ActionController::RoutingError) { get '/products/1/images' }
<add> get '/products/0001/images'
<add> assert_equal 'images#index', @response.body
<add> get '/products/0001/images/1'
<add> assert_equal 'images#show', @response.body
<add>
<add> assert_raise(ActionController::RoutingError) { get '/dashboard', {}, {'REMOTE_ADDR' => '10.0.0.100'} }
<add> get '/dashboard', {}, {'REMOTE_ADDR' => '192.168.1.100'}
<add> assert_equal 'dashboards#show', @response.body
<add> end
<add> end
<add>
<ide> private
<ide> def with_test_routes
<ide> yield | 2 |
Ruby | Ruby | add exec and jar helpers | 73b3977ab4b516d20912fc50f36477dc59b6c28e | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def find_formula
<ide> end
<ide> end
<ide> end
<add>
<add> # Writes an exec script in this folder for each target pathname
<add> def write_exec_script *targets
<add> targets = [targets].flatten
<add> if targets.empty?
<add> opoo "tried to write exec sripts to #{self} for an empty list of targets"
<add> end
<add> targets.each do |target|
<add> target = Pathname.new(target) # allow pathnames or strings
<add> (self+target.basename()).write <<-EOS.undent
<add> #!/bin/bash
<add> exec "#{target}" "$@"
<add> EOS
<add> end
<add> end
<add>
<add> # Writes an exec script that invokes a java jar
<add> def write_jar_script target_jar, script_name, java_opts=""
<add> (self+script_name).write <<-EOS.undent
<add> #!/bin/bash
<add> exec java #{java_opts} -jar #{target_jar} "$@"
<add> EOS
<add> end
<add>
<ide> end
<ide>
<ide> # sets $n and $d so you can observe creation of stuff | 1 |
Mixed | Ruby | add option to mute multiple database yaml warning | 43d83e96c922af78129d1ee83b95866121d7cf81 | <ide><path>actionmailbox/test/dummy/config/environments/development.rb
<ide> # Highlight code that triggered database queries in logs.
<ide> config.active_record.verbose_query_logs = true
<ide>
<add> # Show a warning when Rails couldn't parse your database.yml
<add> # for multiple databases.
<add> config.active_record.suppress_multiple_database_warning = false
<add>
<ide> # Debug mode disables concatenation and preprocessing of assets.
<ide> # This option may cause significant delays in view rendering with a large
<ide> # number of complex assets.
<ide><path>actiontext/test/dummy/config/environments/development.rb
<ide> # Highlight code that triggered database queries in logs.
<ide> config.active_record.verbose_query_logs = true
<ide>
<add> # Show a warning when Rails couldn't parse your database.yml
<add> # for multiple databases.
<add> config.active_record.suppress_multiple_database_warning = false
<add>
<ide> # Debug mode disables concatenation and preprocessing of assets.
<ide> # This option may cause significant delays in view rendering with a large
<ide> # number of complex assets.
<ide><path>activerecord/CHANGELOG.md
<add>* Allow users to silence the "Rails couldn't infer whether you are using multiple databases..."
<add> message using `config.active_record.suppress_multiple_database_warning`.
<add>
<add> *Omri Gabay*
<add>
<ide> * Connections can be granularly switched for abstract classes when `connected_to` is called.
<ide>
<ide> This change allows `connected_to` to switch a `role` and/or `shard` for a single abstract class instead of all classes globally. Applications that want to use the new feature need to set `config.active_record.legacy_connection_handling` to `false` in their application configuration.
<ide><path>activerecord/lib/active_record/core.rb
<ide> def self.configurations
<ide> # potentially cause memory bloat.
<ide> mattr_accessor :warn_on_records_fetched_greater_than, instance_writer: false
<ide>
<add> ##
<add> # :singleton-method:
<add> # Show a warning when Rails couldn't parse your database.yml
<add> # for multiple databases.
<add> mattr_accessor :suppress_multiple_database_warning, instance_writer: false, default: false
<add>
<ide> mattr_accessor :maintain_test_schema, instance_accessor: false
<ide>
<ide> class_attribute :belongs_to_required_by_default, instance_accessor: false
<ide><path>activerecord/lib/active_record/tasks/database_tasks.rb
<ide> def setup_initial_database_yaml
<ide> begin
<ide> Rails.application.config.load_database_yaml
<ide> rescue
<del> $stderr.puts "Rails couldn't infer whether you are using multiple databases from your database.yml and can't generate the tasks for the non-primary databases. If you'd like to use this feature, please simplify your ERB."
<add> unless ActiveRecord::Base.suppress_multiple_database_warning
<add> $stderr.puts "Rails couldn't infer whether you are using multiple databases from your database.yml and can't generate the tasks for the non-primary databases. If you'd like to use this feature, please simplify your ERB."
<add> end
<ide>
<ide> {}
<ide> end
<ide><path>railties/test/application/configuration_test.rb
<ide> def index
<ide> assert_not ActiveRecord::Base.verbose_query_logs
<ide> end
<ide>
<add> test "config.active_record.suppress_multiple_database_warning is false by default in development" do
<add> app "development"
<add> assert_not ActiveRecord::Base.suppress_multiple_database_warning
<add> end
<add>
<ide> test "config.annotations wrapping SourceAnnotationExtractor::Annotation class" do
<ide> make_basic_app do |application|
<ide> application.config.annotations.register_extensions("coffee") do |tag|
<ide> class D < C
<ide> assert_equal({}, Rails.application.config.load_database_yaml)
<ide> end
<ide>
<add> test "setup_initial_database_yaml does not print a warning if config.active_record.suppress_multiple_database_warning is true" do
<add> app_file "config/database.yml", <<-YAML
<add> <%= Rails.env %>:
<add> username: bobby
<add> adapter: sqlite3
<add> database: 'dev_db'
<add> YAML
<add> add_to_config <<-RUBY
<add> config.active_record.suppress_multiple_database_warning = true
<add> RUBY
<add> app "development"
<add>
<add> assert_silent do
<add> ActiveRecord::Tasks::DatabaseTasks.setup_initial_database_yaml
<add> end
<add> end
<add>
<ide> test "raises with proper error message if no database configuration found" do
<ide> FileUtils.rm("#{app_path}/config/database.yml")
<ide> err = assert_raises RuntimeError do | 6 |
Javascript | Javascript | improve warning message for setstate-on-unmounted | 5855e9f2158b31d945f3fcc5bc582389dbecc88e | <ide><path>packages/react-dom/src/__tests__/ReactCompositeComponent-test.js
<ide> describe('ReactCompositeComponent', () => {
<ide> ReactDOM.unmountComponentAtNode(container);
<ide>
<ide> expect(() => instance.forceUpdate()).toWarnDev(
<del> 'Can only update a mounted or mounting component. This usually means ' +
<del> 'you called setState, replaceState, or forceUpdate on an unmounted ' +
<del> 'component. This is a no-op.\n\nPlease check the code for the ' +
<del> 'Component component.',
<add> "Warning: Can't call setState (or forceUpdate) on an unmounted " +
<add> 'component. This is a no-op, but it indicates a memory leak in your ' +
<add> 'application. To fix, cancel all subscriptions and asynchronous ' +
<add> 'tasks in the componentWillUnmount method.\n' +
<add> ' in Component (at **)',
<ide> );
<ide>
<ide> // No additional warning should be recorded
<ide> describe('ReactCompositeComponent', () => {
<ide> }
<ide> }
<ide>
<del> let instance = <Component />;
<del> expect(instance.setState).not.toBeDefined();
<del>
<del> instance = ReactDOM.render(instance, container);
<add> let instance;
<add> ReactDOM.render(
<add> <div>
<add> <span>
<add> <Component ref={c => (instance = c || instance)} />
<add> </span>
<add> </div>,
<add> container,
<add> );
<ide>
<ide> expect(renders).toBe(1);
<ide>
<ide> instance.setState({value: 1});
<ide>
<ide> expect(renders).toBe(2);
<ide>
<del> ReactDOM.unmountComponentAtNode(container);
<add> ReactDOM.render(<div />, container);
<ide>
<ide> expect(() => {
<ide> instance.setState({value: 2});
<ide> }).toWarnDev(
<del> 'Can only update a mounted or mounting component. This usually means ' +
<del> 'you called setState, replaceState, or forceUpdate on an unmounted ' +
<del> 'component. This is a no-op.\n\nPlease check the code for the ' +
<del> 'Component component.',
<add> "Warning: Can't call setState (or forceUpdate) on an unmounted " +
<add> 'component. This is a no-op, but it indicates a memory leak in your ' +
<add> 'application. To fix, cancel all subscriptions and asynchronous ' +
<add> 'tasks in the componentWillUnmount method.\n' +
<add> ' in Component (at **)\n' +
<add> ' in span',
<ide> );
<ide>
<ide> expect(renders).toBe(2);
<ide><path>packages/react-reconciler/src/ReactFiberScheduler.js
<ide> import type {HydrationContext} from './ReactFiberHydrationContext';
<ide> import type {ExpirationTime} from './ReactFiberExpirationTime';
<ide>
<ide> import ReactErrorUtils from 'shared/ReactErrorUtils';
<add>import {getStackAddendumByWorkInProgressFiber} from 'shared/ReactFiberComponentTreeHook';
<ide> import {ReactCurrentOwner} from 'shared/ReactGlobalSharedState';
<ide> import ReactStrictModeWarnings from './ReactStrictModeWarnings';
<ide> import {
<ide> if (__DEV__) {
<ide> const didWarnStateUpdateForUnmountedComponent = {};
<ide>
<ide> warnAboutUpdateOnUnmounted = function(fiber: Fiber) {
<add> // We show the whole stack but dedupe on the top component's name because
<add> // the problematic code almost always lies inside that component.
<ide> const componentName = getComponentName(fiber) || 'ReactClass';
<ide> if (didWarnStateUpdateForUnmountedComponent[componentName]) {
<ide> return;
<ide> }
<ide> warning(
<ide> false,
<del> 'Can only update a mounted or mounting ' +
<del> 'component. This usually means you called setState, replaceState, ' +
<del> 'or forceUpdate on an unmounted component. This is a no-op.\n\nPlease ' +
<del> 'check the code for the %s component.',
<del> componentName,
<add> "Can't call setState (or forceUpdate) on an unmounted component. This " +
<add> 'is a no-op, but it indicates a memory leak in your application. To ' +
<add> 'fix, cancel all subscriptions and asynchronous tasks in the ' +
<add> 'componentWillUnmount method.%s',
<add> getStackAddendumByWorkInProgressFiber(fiber),
<ide> );
<ide> didWarnStateUpdateForUnmountedComponent[componentName] = true;
<ide> }; | 2 |
Javascript | Javascript | name all constructors | 1ef4c94de20eaae4a1f010eb0660b693e1c71f51 | <ide><path>src/canvas.js
<ide> var TextRenderingMode = {
<ide> ADD_TO_PATH: 7
<ide> };
<ide>
<del>var CanvasExtraState = (function canvasExtraState() {
<del> function constructor(old) {
<add>var CanvasExtraState = (function CanvasExtraStateClosure() {
<add> function CanvasExtraState(old) {
<ide> // Are soft masks and alpha values shapes or opacities?
<ide> this.alphaIsShape = false;
<ide> this.fontSize = 0;
<ide> var CanvasExtraState = (function canvasExtraState() {
<ide> this.old = old;
<ide> }
<ide>
<del> constructor.prototype = {
<add> CanvasExtraState.prototype = {
<ide> clone: function canvasextra_clone() {
<ide> return Object.create(this);
<ide> },
<ide> var CanvasExtraState = (function canvasExtraState() {
<ide> this.y = y;
<ide> }
<ide> };
<del> return constructor;
<add> return CanvasExtraState;
<ide> })();
<ide>
<ide> function ScratchCanvas(width, height) {
<ide> function addContextCurrentTransform(ctx) {
<ide> }
<ide> }
<ide>
<del>var CanvasGraphics = (function canvasGraphics() {
<add>var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> // Defines the time the executeIRQueue is going to be executing
<ide> // before it stops and shedules a continue of execution.
<ide> var kExecutionTime = 50;
<ide>
<del> function constructor(canvasCtx, objs, textLayer) {
<add> function CanvasGraphics(canvasCtx, objs, textLayer) {
<ide> this.ctx = canvasCtx;
<ide> this.current = new CanvasExtraState();
<ide> this.stateStack = [];
<ide> var CanvasGraphics = (function canvasGraphics() {
<ide> var NORMAL_CLIP = {};
<ide> var EO_CLIP = {};
<ide>
<del> constructor.prototype = {
<add> CanvasGraphics.prototype = {
<ide> slowCommands: {
<ide> 'stroke': true,
<ide> 'closeStroke': true,
<ide> var CanvasGraphics = (function canvasGraphics() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return CanvasGraphics;
<ide> })();
<ide>
<ide> if (!isWorker) {
<ide><path>src/colorspace.js
<ide>
<ide> 'use strict';
<ide>
<del>var ColorSpace = (function colorSpaceColorSpace() {
<add>var ColorSpace = (function ColorSpaceClosure() {
<ide> // Constructor should define this.numComps, this.defaultColor, this.name
<del> function constructor() {
<add> function ColorSpace() {
<ide> error('should not call ColorSpace constructor');
<ide> }
<ide>
<del> constructor.prototype = {
<add> ColorSpace.prototype = {
<ide> // Input: array of size numComps representing color component values
<ide> // Output: array of rgb values, each value ranging from [0.1]
<ide> getRgb: function colorSpaceGetRgb(color) {
<ide> var ColorSpace = (function colorSpaceColorSpace() {
<ide> }
<ide> };
<ide>
<del> constructor.parse = function colorSpaceParse(cs, xref, res) {
<del> var IR = constructor.parseToIR(cs, xref, res);
<add> ColorSpace.parse = function colorSpaceParse(cs, xref, res) {
<add> var IR = ColorSpace.parseToIR(cs, xref, res);
<ide> if (IR instanceof AlternateCS)
<ide> return IR;
<ide>
<del> return constructor.fromIR(IR);
<add> return ColorSpace.fromIR(IR);
<ide> };
<ide>
<del> constructor.fromIR = function colorSpaceFromIR(IR) {
<add> ColorSpace.fromIR = function colorSpaceFromIR(IR) {
<ide> var name = isArray(IR) ? IR[0] : IR;
<ide>
<ide> switch (name) {
<ide> var ColorSpace = (function colorSpaceColorSpace() {
<ide> return null;
<ide> };
<ide>
<del> constructor.parseToIR = function colorSpaceParseToIR(cs, xref, res) {
<add> ColorSpace.parseToIR = function colorSpaceParseToIR(cs, xref, res) {
<ide> if (isName(cs)) {
<ide> var colorSpaces = xref.fetchIfRef(res.get('ColorSpace'));
<ide> if (isDict(colorSpaces)) {
<ide> var ColorSpace = (function colorSpaceColorSpace() {
<ide> return null;
<ide> };
<ide>
<del> return constructor;
<add> return ColorSpace;
<ide> })();
<ide>
<ide> /**
<ide> var ColorSpace = (function colorSpaceColorSpace() {
<ide> * Both color spaces use a tinting function to convert colors to a base color
<ide> * space.
<ide> */
<del>var AlternateCS = (function alternateCS() {
<del> function constructor(numComps, base, tintFn) {
<add>var AlternateCS = (function AlternateCSClosure() {
<add> function AlternateCS(numComps, base, tintFn) {
<ide> this.name = 'Alternate';
<ide> this.numComps = numComps;
<ide> this.defaultColor = [];
<ide> var AlternateCS = (function alternateCS() {
<ide> this.tintFn = tintFn;
<ide> }
<ide>
<del> constructor.prototype = {
<add> AlternateCS.prototype = {
<ide> getRgb: function altcs_getRgb(color) {
<ide> var tinted = this.tintFn(color);
<ide> return this.base.getRgb(tinted);
<ide> var AlternateCS = (function alternateCS() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return AlternateCS;
<ide> })();
<ide>
<del>var PatternCS = (function patternCS() {
<del> function constructor(baseCS) {
<add>var PatternCS = (function PatternCSClosure() {
<add> function PatternCS(baseCS) {
<ide> this.name = 'Pattern';
<ide> this.base = baseCS;
<ide> }
<del> constructor.prototype = {};
<add> PatternCS.prototype = {};
<ide>
<del> return constructor;
<add> return PatternCS;
<ide> })();
<ide>
<del>var IndexedCS = (function indexedCS() {
<del> function constructor(base, highVal, lookup) {
<add>var IndexedCS = (function IndexedCSClosure() {
<add> function IndexedCS(base, highVal, lookup) {
<ide> this.name = 'Indexed';
<ide> this.numComps = 1;
<ide> this.defaultColor = [0];
<ide> var IndexedCS = (function indexedCS() {
<ide> this.lookup = lookupArray;
<ide> }
<ide>
<del> constructor.prototype = {
<add> IndexedCS.prototype = {
<ide> getRgb: function indexcs_getRgb(color) {
<ide> var numComps = this.base.numComps;
<ide> var start = color[0] * numComps;
<ide> var IndexedCS = (function indexedCS() {
<ide> return base.getRgbBuffer(baseBuf, 8);
<ide> }
<ide> };
<del> return constructor;
<add> return IndexedCS;
<ide> })();
<ide>
<del>var DeviceGrayCS = (function deviceGrayCS() {
<del> function constructor() {
<add>var DeviceGrayCS = (function DeviceGrayCSClosure() {
<add> function DeviceGrayCS() {
<ide> this.name = 'DeviceGray';
<ide> this.numComps = 1;
<ide> this.defaultColor = [0];
<ide> }
<ide>
<del> constructor.prototype = {
<add> DeviceGrayCS.prototype = {
<ide> getRgb: function graycs_getRgb(color) {
<ide> var c = color[0];
<ide> return [c, c, c];
<ide> var DeviceGrayCS = (function deviceGrayCS() {
<ide> return rgbBuf;
<ide> }
<ide> };
<del> return constructor;
<add> return DeviceGrayCS;
<ide> })();
<ide>
<del>var DeviceRgbCS = (function deviceRgbCS() {
<del> function constructor() {
<add>var DeviceRgbCS = (function DeviceRgbCSClosure() {
<add> function DeviceRgbCS() {
<ide> this.name = 'DeviceRGB';
<ide> this.numComps = 3;
<ide> this.defaultColor = [0, 0, 0];
<ide> }
<del> constructor.prototype = {
<add> DeviceRgbCS.prototype = {
<ide> getRgb: function rgbcs_getRgb(color) {
<ide> return color;
<ide> },
<ide> var DeviceRgbCS = (function deviceRgbCS() {
<ide> return rgbBuf;
<ide> }
<ide> };
<del> return constructor;
<add> return DeviceRgbCS;
<ide> })();
<ide>
<del>var DeviceCmykCS = (function deviceCmykCS() {
<del> function constructor() {
<add>var DeviceCmykCS = (function DeviceCmykCSClosure() {
<add> function DeviceCmykCS() {
<ide> this.name = 'DeviceCMYK';
<ide> this.numComps = 4;
<ide> this.defaultColor = [0, 0, 0, 1];
<ide> }
<del> constructor.prototype = {
<add> DeviceCmykCS.prototype = {
<ide> getRgb: function cmykcs_getRgb(color) {
<ide> var c = color[0], m = color[1], y = color[2], k = color[3];
<ide> var c1 = 1 - c, m1 = 1 - m, y1 = 1 - y, k1 = 1 - k;
<ide> var DeviceCmykCS = (function deviceCmykCS() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return DeviceCmykCS;
<ide> })();
<ide>
<ide><path>src/core.js
<ide> function getPdf(arg, callback) {
<ide> }
<ide> globalScope.PDFJS.getPdf = getPdf;
<ide>
<del>var Page = (function pagePage() {
<del> function constructor(xref, pageNumber, pageDict, ref) {
<add>var Page = (function PageClosure() {
<add> function Page(xref, pageNumber, pageDict, ref) {
<ide> this.pageNumber = pageNumber;
<ide> this.pageDict = pageDict;
<ide> this.stats = {
<ide> var Page = (function pagePage() {
<ide> this.callback = null;
<ide> }
<ide>
<del> constructor.prototype = {
<add> Page.prototype = {
<ide> getPageProp: function pageGetPageProp(key) {
<ide> return this.xref.fetchIfRef(this.pageDict.get(key));
<ide> },
<ide> var Page = (function pagePage() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return Page;
<ide> })();
<ide>
<ide> /**
<ide> var Page = (function pagePage() {
<ide> * need for the `PDFDocModel` anymore and there is only one object on the
<ide> * main thread and not one entire copy on each worker instance.
<ide> */
<del>var PDFDocModel = (function pdfDoc() {
<del> function constructor(arg, callback) {
<add>var PDFDocModel = (function PDFDocModelClosure() {
<add> function PDFDocModel(arg, callback) {
<ide> if (isStream(arg))
<ide> init.call(this, arg);
<ide> else if (isArrayBuffer(arg))
<ide> var PDFDocModel = (function pdfDoc() {
<ide> return true; /* found */
<ide> }
<ide>
<del> constructor.prototype = {
<add> PDFDocModel.prototype = {
<ide> get linearization() {
<ide> var length = this.stream.length;
<ide> var linearization = false;
<ide> var PDFDocModel = (function pdfDoc() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return PDFDocModel;
<ide> })();
<ide>
<del>var PDFDoc = (function pdfDoc() {
<del> function constructor(arg, callback) {
<add>var PDFDoc = (function PDFDocClosure() {
<add> function PDFDoc(arg, callback) {
<ide> var stream = null;
<ide> var data = null;
<ide>
<ide> var PDFDoc = (function pdfDoc() {
<ide> }
<ide> }
<ide>
<del> constructor.prototype = {
<add> PDFDoc.prototype = {
<ide> setupFakeWorker: function() {
<ide> // If we don't use a worker, just post/sendMessage to the main thread.
<ide> var fakeWorker = {
<ide> var PDFDoc = (function pdfDoc() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return PDFDoc;
<ide> })();
<ide>
<ide> globalScope.PDFJS.PDFDoc = PDFDoc;
<ide><path>src/crypto.js
<ide>
<ide> 'use strict';
<ide>
<del>var ARCFourCipher = (function arcFourCipher() {
<del> function constructor(key) {
<add>var ARCFourCipher = (function ARCFourCipherClosure() {
<add> function ARCFourCipher(key) {
<ide> this.a = 0;
<ide> this.b = 0;
<ide> var s = new Uint8Array(256);
<ide> var ARCFourCipher = (function arcFourCipher() {
<ide> this.s = s;
<ide> }
<ide>
<del> constructor.prototype = {
<add> ARCFourCipher.prototype = {
<ide> encryptBlock: function arcFourCipherEncryptBlock(data) {
<ide> var i, n = data.length, tmp, tmp2;
<ide> var a = this.a, b = this.b, s = this.s;
<ide> var ARCFourCipher = (function arcFourCipher() {
<ide> return output;
<ide> }
<ide> };
<del> constructor.prototype.decryptBlock = constructor.prototype.encryptBlock;
<add> ARCFourCipher.prototype.decryptBlock = ARCFourCipher.prototype.encryptBlock;
<ide>
<del> return constructor;
<add> return ARCFourCipher;
<ide> })();
<ide>
<del>var calculateMD5 = (function calculateMD5() {
<add>var calculateMD5 = (function calculateMD5Closure() {
<ide> var r = new Uint8Array([
<ide> 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
<ide> 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
<ide> var calculateMD5 = (function calculateMD5() {
<ide> return hash;
<ide> })();
<ide>
<del>var NullCipher = (function nullCipher() {
<del> function constructor() {
<add>var NullCipher = (function NullCipherClosure() {
<add> function NullCipher() {
<ide> }
<ide>
<del> constructor.prototype = {
<add> NullCipher.prototype = {
<ide> decryptBlock: function nullCipherDecryptBlock(data) {
<ide> return data;
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return NullCipher;
<ide> })();
<ide>
<del>var AES128Cipher = (function aes128Cipher() {
<add>var AES128Cipher = (function AES128CipherClosure() {
<ide> var rcon = new Uint8Array([
<ide> 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
<ide> 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
<ide> var AES128Cipher = (function aes128Cipher() {
<ide> return state;
<ide> }
<ide>
<del> function constructor(key) {
<add> function AES128Cipher(key) {
<ide> this.key = expandKey128(key);
<ide> this.buffer = new Uint8Array(16);
<ide> this.bufferPosition = 0;
<ide> var AES128Cipher = (function aes128Cipher() {
<ide> return output;
<ide> }
<ide>
<del> constructor.prototype = {
<add> AES128Cipher.prototype = {
<ide> decryptBlock: function aes128CipherDecryptBlock(data) {
<ide> var i, sourceLength = data.length;
<ide> var buffer = this.buffer, bufferLength = this.bufferPosition;
<ide> var AES128Cipher = (function aes128Cipher() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return AES128Cipher;
<ide> })();
<ide>
<del>var CipherTransform = (function cipherTransform() {
<del> function constructor(stringCipherConstructor, streamCipherConstructor) {
<add>var CipherTransform = (function CipherTransformClosure() {
<add> function CipherTransform(stringCipherConstructor, streamCipherConstructor) {
<ide> this.stringCipherConstructor = stringCipherConstructor;
<ide> this.streamCipherConstructor = streamCipherConstructor;
<ide> }
<del> constructor.prototype = {
<add> CipherTransform.prototype = {
<ide> createStream: function cipherTransformCreateStream(stream) {
<ide> var cipher = new this.streamCipherConstructor();
<ide> return new DecryptStream(stream,
<ide> var CipherTransform = (function cipherTransform() {
<ide> return bytesToString(data);
<ide> }
<ide> };
<del> return constructor;
<add> return CipherTransform;
<ide> })();
<ide>
<del>var CipherTransformFactory = (function cipherTransformFactory() {
<add>var CipherTransformFactory = (function CipherTransformFactoryClosure() {
<ide> function prepareKeyData(fileId, password, ownerPassword, userPassword,
<ide> flags, revision, keyLength, encryptMetadata) {
<ide> var defaultPasswordBytes = new Uint8Array([
<ide> var CipherTransformFactory = (function cipherTransformFactory() {
<ide>
<ide> var identityName = new Name('Identity');
<ide>
<del> function constructor(dict, fileId, password) {
<add> function CipherTransformFactory(dict, fileId, password) {
<ide> var filter = dict.get('Filter');
<ide> if (!isName(filter) || filter.name != 'Standard')
<ide> error('unknown encryption method');
<ide> var CipherTransformFactory = (function cipherTransformFactory() {
<ide> return null;
<ide> }
<ide>
<del> constructor.prototype = {
<add> CipherTransformFactory.prototype = {
<ide> createCipherTransform: function buildCipherCreateCipherTransform(num,
<ide> gen) {
<ide> if (this.algorithm == 4) {
<ide> var CipherTransformFactory = (function cipherTransformFactory() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return CipherTransformFactory;
<ide> })();
<ide>
<ide><path>src/evaluator.js
<ide>
<ide> 'use strict';
<ide>
<del>var PartialEvaluator = (function partialEvaluator() {
<del> function constructor(xref, handler, uniquePrefix) {
<add>var PartialEvaluator = (function PartialEvaluatorClosure() {
<add> function PartialEvaluator(xref, handler, uniquePrefix) {
<ide> this.state = new EvalState();
<ide> this.stateStack = [];
<ide>
<ide> var PartialEvaluator = (function partialEvaluator() {
<ide> EX: 'endCompat'
<ide> };
<ide>
<del> constructor.prototype = {
<add> PartialEvaluator.prototype = {
<ide> getIRQueue: function partialEvaluatorGetIRQueue(stream, resources,
<ide> queue, dependency) {
<ide>
<ide> var PartialEvaluator = (function partialEvaluator() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return PartialEvaluator;
<ide> })();
<ide>
<del>var EvalState = (function evalState() {
<del> function constructor() {
<add>var EvalState = (function EvalStateClosure() {
<add> function EvalState() {
<ide> // Are soft masks and alpha values shapes or opacities?
<ide> this.alphaIsShape = false;
<ide> this.fontSize = 0;
<ide> var EvalState = (function evalState() {
<ide> this.fillColorSpace = null;
<ide> this.strokeColorSpace = null;
<ide> }
<del> constructor.prototype = {
<add> EvalState.prototype = {
<ide> };
<del> return constructor;
<add> return EvalState;
<ide> })();
<ide>
<ide><path>src/fonts.js
<ide> function isSpecialUnicode(unicode) {
<ide> * var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
<ide> * type1Font.bind();
<ide> */
<del>var Font = (function Font() {
<del> var constructor = function font_constructor(name, file, properties) {
<add>var Font = (function FontClosure() {
<add> function Font(name, file, properties) {
<ide> this.name = name;
<ide> this.coded = properties.coded;
<ide> this.charProcIRQueues = properties.charProcIRQueues;
<ide> var Font = (function Font() {
<ide> return nameTable;
<ide> }
<ide>
<del> constructor.prototype = {
<add> Font.prototype = {
<ide> name: null,
<ide> font: null,
<ide> mimetype: null,
<ide> var Font = (function Font() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return Font;
<ide> })();
<ide>
<ide> /*
<ide> CFF.prototype = {
<ide> }
<ide> };
<ide>
<del>var Type2CFF = (function type2CFF() {
<add>var Type2CFF = (function Type2CFFClosure() {
<ide> // TODO: replace parsing code with the Type2Parser in font_utils.js
<del> function constructor(file, properties) {
<add> function Type2CFF(file, properties) {
<ide> var bytes = file.getBytes();
<ide> this.bytes = bytes;
<ide> this.properties = properties;
<ide>
<ide> this.data = this.parse();
<ide> }
<ide>
<del> constructor.prototype = {
<add> Type2CFF.prototype = {
<ide> parse: function cff_parse() {
<ide> var header = this.parseHeader();
<ide> var properties = this.properties;
<ide> var Type2CFF = (function type2CFF() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return Type2CFF;
<ide> })();
<ide>
<ide><path>src/function.js
<ide>
<ide> 'use strict';
<ide>
<del>var PDFFunction = (function pdfFunction() {
<add>var PDFFunction = (function PDFFunctionClosure() {
<ide> var CONSTRUCT_SAMPLED = 0;
<ide> var CONSTRUCT_INTERPOLATED = 2;
<ide> var CONSTRUCT_STICHED = 3;
<ide><path>src/image.js
<ide>
<ide> 'use strict';
<ide>
<del>var PDFImage = (function pdfImage() {
<del> function constructor(xref, res, image, inline) {
<add>var PDFImage = (function PDFImageClosure() {
<add> function PDFImage(xref, res, image, inline) {
<ide> this.image = image;
<ide> if (image.getParams) {
<ide> // JPX/JPEG2000 streams directly contain bits per component
<ide> var PDFImage = (function pdfImage() {
<ide> }
<ide> }
<ide>
<del> constructor.prototype = {
<add> PDFImage.prototype = {
<ide> getComponents: function getComponents(buffer, decodeMap) {
<ide> var bpc = this.bpc;
<ide> if (bpc == 8)
<ide> var PDFImage = (function pdfImage() {
<ide> buffer[i] = comps[i];
<ide> }
<ide> };
<del> return constructor;
<add> return PDFImage;
<ide> })();
<ide>
<del>var JpegImageLoader = (function jpegImage() {
<add>var JpegImageLoader = (function JpegImageLoaderClosure() {
<ide> function JpegImageLoader(objId, imageData, objs) {
<ide> var src = 'data:image/jpeg;base64,' + window.btoa(imageData);
<ide>
<ide> var img = new Image();
<del> img.onload = (function jpegImageLoaderOnload() {
<add> img.onload = (function onloadClosure() {
<ide> this.loaded = true;
<ide>
<ide> objs.resolve(objId, this);
<ide><path>src/parser.js
<ide> function isEOF(v) {
<ide> return v == EOF;
<ide> }
<ide>
<del>var Parser = (function parserParser() {
<del> function constructor(lexer, allowStreams, xref) {
<add>var Parser = (function ParserClosure() {
<add> function Parser(lexer, allowStreams, xref) {
<ide> this.lexer = lexer;
<ide> this.allowStreams = allowStreams;
<ide> this.xref = xref;
<ide> this.inlineImg = 0;
<ide> this.refill();
<ide> }
<ide>
<del> constructor.prototype = {
<add> Parser.prototype = {
<ide> refill: function parserRefill() {
<ide> this.buf1 = this.lexer.getObj();
<ide> this.buf2 = this.lexer.getObj();
<ide> var Parser = (function parserParser() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return Parser;
<ide> })();
<ide>
<del>var Lexer = (function lexer() {
<del> function constructor(stream) {
<add>var Lexer = (function LexerClosure() {
<add> function Lexer(stream) {
<ide> this.stream = stream;
<ide> }
<ide>
<del> constructor.isSpace = function lexerIsSpace(ch) {
<add> Lexer.isSpace = function lexerIsSpace(ch) {
<ide> return ch == ' ' || ch == '\t' || ch == '\x0d' || ch == '\x0a';
<ide> };
<ide>
<ide> var Lexer = (function lexer() {
<ide> return -1;
<ide> }
<ide>
<del> constructor.prototype = {
<add> Lexer.prototype = {
<ide> getNumber: function lexerGetNumber(ch) {
<ide> var floating = false;
<ide> var str = ch;
<ide> var Lexer = (function lexer() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return Lexer;
<ide> })();
<ide>
<del>var Linearization = (function linearizationLinearization() {
<del> function constructor(stream) {
<add>var Linearization = (function LinearizationClosure() {
<add> function Linearization(stream) {
<ide> this.parser = new Parser(new Lexer(stream), false);
<ide> var obj1 = this.parser.getObj();
<ide> var obj2 = this.parser.getObj();
<ide> var Linearization = (function linearizationLinearization() {
<ide> }
<ide> }
<ide>
<del> constructor.prototype = {
<add> Linearization.prototype = {
<ide> getInt: function linearizationGetInt(name) {
<ide> var linDict = this.linDict;
<ide> var obj;
<ide> var Linearization = (function linearizationLinearization() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return Linearization;
<ide> })();
<ide>
<ide><path>src/pattern.js
<ide> var PatternType = {
<ide> RADIAL: 3
<ide> };
<ide>
<del>var Pattern = (function patternPattern() {
<add>var Pattern = (function PatternClosure() {
<ide> // Constructor should define this.getPattern
<del> function constructor() {
<add> function Pattern() {
<ide> error('should not call Pattern constructor');
<ide> }
<ide>
<del> constructor.prototype = {
<add> Pattern.prototype = {
<ide> // Input: current Canvas context
<ide> // Output: the appropriate fillStyle or strokeStyle
<ide> getPattern: function pattern_getStyle(ctx) {
<ide> error('Should not call Pattern.getStyle: ' + ctx);
<ide> }
<ide> };
<ide>
<del> constructor.shadingFromIR = function pattern_shadingFromIR(ctx, raw) {
<add> Pattern.shadingFromIR = function pattern_shadingFromIR(ctx, raw) {
<ide> return Shadings[raw[0]].fromIR(ctx, raw);
<ide> };
<ide>
<del> constructor.parseShading = function pattern_shading(shading, matrix, xref,
<add> Pattern.parseShading = function pattern_shading(shading, matrix, xref,
<ide> res, ctx) {
<ide>
<ide> var dict = isStream(shading) ? shading.dict : shading;
<ide> var Pattern = (function patternPattern() {
<ide> return new Shadings.Dummy();
<ide> }
<ide> };
<del> return constructor;
<add> return Pattern;
<ide> })();
<ide>
<ide> var Shadings = {};
<ide>
<ide> // Radial and axial shading have very similar implementations
<ide> // If needed, the implementations can be broken into two classes
<del>Shadings.RadialAxial = (function radialAxialShading() {
<del> function constructor(dict, matrix, xref, res, ctx) {
<add>Shadings.RadialAxial = (function RadialAxialClosure() {
<add> function RadialAxial(dict, matrix, xref, res, ctx) {
<ide> this.matrix = matrix;
<ide> this.coordsArr = dict.get('Coords');
<ide> this.shadingType = dict.get('ShadingType');
<ide> Shadings.RadialAxial = (function radialAxialShading() {
<ide> this.colorStops = colorStops;
<ide> }
<ide>
<del> constructor.fromIR = function radialAxialShadingGetIR(ctx, raw) {
<add> RadialAxial.fromIR = function radialAxialShadingGetIR(ctx, raw) {
<ide> var type = raw[1];
<ide> var colorStops = raw[2];
<ide> var p0 = raw[3];
<ide> Shadings.RadialAxial = (function radialAxialShading() {
<ide> return grad;
<ide> };
<ide>
<del> constructor.prototype = {
<add> RadialAxial.prototype = {
<ide> getIR: function radialAxialShadingGetIR() {
<ide> var coordsArr = this.coordsArr;
<ide> var type = this.shadingType;
<ide> Shadings.RadialAxial = (function radialAxialShading() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return RadialAxial;
<ide> })();
<ide>
<del>Shadings.Dummy = (function dummyShading() {
<del> function constructor() {
<add>Shadings.Dummy = (function DummyClosure() {
<add> function Dummy() {
<ide> this.type = 'Pattern';
<ide> }
<ide>
<del> constructor.fromIR = function dummyShadingFromIR() {
<add> Dummy.fromIR = function dummyShadingFromIR() {
<ide> return 'hotpink';
<ide> };
<ide>
<del> constructor.prototype = {
<add> Dummy.prototype = {
<ide> getIR: function dummyShadingGetIR() {
<ide> return ['Dummy'];
<ide> }
<ide> };
<del> return constructor;
<add> return Dummy;
<ide> })();
<ide>
<del>var TilingPattern = (function tilingPattern() {
<add>var TilingPattern = (function TilingPatternClosure() {
<ide> var PAINT_TYPE_COLORED = 1, PAINT_TYPE_UNCOLORED = 2;
<ide>
<ide> function TilingPattern(IR, color, ctx, objs) {
<ide><path>src/stream.js
<ide>
<ide> 'use strict';
<ide>
<del>var Stream = (function streamStream() {
<del> function constructor(arrayBuffer, start, length, dict) {
<add>var Stream = (function StreamClosure() {
<add> function Stream(arrayBuffer, start, length, dict) {
<ide> this.bytes = new Uint8Array(arrayBuffer);
<ide> this.start = start || 0;
<ide> this.pos = this.start;
<ide> var Stream = (function streamStream() {
<ide>
<ide> // required methods for a stream. if a particular stream does not
<ide> // implement these, an error should be thrown
<del> constructor.prototype = {
<add> Stream.prototype = {
<ide> get length() {
<ide> return this.end - this.start;
<ide> },
<ide> var Stream = (function streamStream() {
<ide> isStream: true
<ide> };
<ide>
<del> return constructor;
<add> return Stream;
<ide> })();
<ide>
<del>var StringStream = (function stringStream() {
<del> function constructor(str) {
<add>var StringStream = (function StringStreamClosure() {
<add> function StringStream(str) {
<ide> var length = str.length;
<ide> var bytes = new Uint8Array(length);
<ide> for (var n = 0; n < length; ++n)
<ide> bytes[n] = str.charCodeAt(n);
<ide> Stream.call(this, bytes);
<ide> }
<ide>
<del> constructor.prototype = Stream.prototype;
<add> StringStream.prototype = Stream.prototype;
<ide>
<del> return constructor;
<add> return StringStream;
<ide> })();
<ide>
<ide> // super class for the decoding streams
<del>var DecodeStream = (function decodeStream() {
<del> function constructor() {
<add>var DecodeStream = (function DecodeStreamClosure() {
<add> function DecodeStream() {
<ide> this.pos = 0;
<ide> this.bufferLength = 0;
<ide> this.eof = false;
<ide> this.buffer = null;
<ide> }
<ide>
<del> constructor.prototype = {
<add> DecodeStream.prototype = {
<ide> ensureBuffer: function decodestream_ensureBuffer(requested) {
<ide> var buffer = this.buffer;
<ide> var current = buffer ? buffer.byteLength : 0;
<ide> var DecodeStream = (function decodeStream() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return DecodeStream;
<ide> })();
<ide>
<del>var FakeStream = (function fakeStream() {
<del> function constructor(stream) {
<add>var FakeStream = (function FakeStreamClosure() {
<add> function FakeStream(stream) {
<ide> this.dict = stream.dict;
<ide> DecodeStream.call(this);
<ide> }
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<del> constructor.prototype.readBlock = function fakeStreamReadBlock() {
<add> FakeStream.prototype = Object.create(DecodeStream.prototype);
<add> FakeStream.prototype.readBlock = function fakeStreamReadBlock() {
<ide> var bufferLength = this.bufferLength;
<ide> bufferLength += 1024;
<ide> var buffer = this.ensureBuffer(bufferLength);
<ide> this.bufferLength = bufferLength;
<ide> };
<ide>
<del> constructor.prototype.getBytes = function fakeStreamGetBytes(length) {
<add> FakeStream.prototype.getBytes = function fakeStreamGetBytes(length) {
<ide> var end, pos = this.pos;
<ide>
<ide> if (length) {
<ide> var FakeStream = (function fakeStream() {
<ide> return this.buffer.subarray(pos, end);
<ide> };
<ide>
<del> return constructor;
<add> return FakeStream;
<ide> })();
<ide>
<del>var StreamsSequenceStream = (function streamSequenceStream() {
<del> function constructor(streams) {
<add>var StreamsSequenceStream = (function StreamsSequenceStreamClosure() {
<add> function StreamsSequenceStream(streams) {
<ide> this.streams = streams;
<ide> DecodeStream.call(this);
<ide> }
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype);
<add>
<add> StreamsSequenceStream.prototype.readBlock =
<add> function streamSequenceStreamReadBlock() {
<ide>
<del> constructor.prototype.readBlock = function streamSequenceStreamReadBlock() {
<ide> var streams = this.streams;
<ide> if (streams.length == 0) {
<ide> this.eof = true;
<ide> var StreamsSequenceStream = (function streamSequenceStream() {
<ide> this.bufferLength = newLength;
<ide> };
<ide>
<del> return constructor;
<add> return StreamsSequenceStream;
<ide> })();
<ide>
<del>var FlateStream = (function flateStream() {
<add>var FlateStream = (function FlateStreamClosure() {
<ide> var codeLenCodeMap = new Uint32Array([
<ide> 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
<ide> ]);
<ide> var FlateStream = (function flateStream() {
<ide> 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
<ide> ]), 5];
<ide>
<del> function constructor(stream) {
<add> function FlateStream(stream) {
<ide> var bytes = stream.getBytes();
<ide> var bytesPos = 0;
<ide>
<ide> var FlateStream = (function flateStream() {
<ide> DecodeStream.call(this);
<ide> }
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> FlateStream.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.getBits = function flateStreamGetBits(bits) {
<add> FlateStream.prototype.getBits = function flateStreamGetBits(bits) {
<ide> var codeSize = this.codeSize;
<ide> var codeBuf = this.codeBuf;
<ide> var bytes = this.bytes;
<ide> var FlateStream = (function flateStream() {
<ide> return b;
<ide> };
<ide>
<del> constructor.prototype.getCode = function flateStreamGetCode(table) {
<add> FlateStream.prototype.getCode = function flateStreamGetCode(table) {
<ide> var codes = table[0];
<ide> var maxLen = table[1];
<ide> var codeSize = this.codeSize;
<ide> var FlateStream = (function flateStream() {
<ide> return codeVal;
<ide> };
<ide>
<del> constructor.prototype.generateHuffmanTable =
<add> FlateStream.prototype.generateHuffmanTable =
<ide> function flateStreamGenerateHuffmanTable(lengths) {
<ide> var n = lengths.length;
<ide>
<ide> var FlateStream = (function flateStream() {
<ide> return [codes, maxLen];
<ide> };
<ide>
<del> constructor.prototype.readBlock = function flateStreamReadBlock() {
<add> FlateStream.prototype.readBlock = function flateStreamReadBlock() {
<ide> // read block header
<ide> var hdr = this.getBits(3);
<ide> if (hdr & 1)
<ide> var FlateStream = (function flateStream() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return FlateStream;
<ide> })();
<ide>
<del>var PredictorStream = (function predictorStream() {
<del> function constructor(stream, params) {
<add>var PredictorStream = (function PredictorStreamClosure() {
<add> function PredictorStream(stream, params) {
<ide> var predictor = this.predictor = params.get('Predictor') || 1;
<ide>
<ide> if (predictor <= 1)
<ide> var PredictorStream = (function predictorStream() {
<ide> return this;
<ide> }
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> PredictorStream.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.readBlockTiff =
<add> PredictorStream.prototype.readBlockTiff =
<ide> function predictorStreamReadBlockTiff() {
<ide> var rowBytes = this.rowBytes;
<ide>
<ide> var PredictorStream = (function predictorStream() {
<ide> this.bufferLength += rowBytes;
<ide> };
<ide>
<del> constructor.prototype.readBlockPng = function predictorStreamReadBlockPng() {
<add> PredictorStream.prototype.readBlockPng =
<add> function predictorStreamReadBlockPng() {
<add>
<ide> var rowBytes = this.rowBytes;
<ide> var pixBytes = this.pixBytes;
<ide>
<ide> var PredictorStream = (function predictorStream() {
<ide> this.bufferLength += rowBytes;
<ide> };
<ide>
<del> return constructor;
<add> return PredictorStream;
<ide> })();
<ide>
<ide> /**
<ide> var PredictorStream = (function predictorStream() {
<ide> * a library to decode these images and the stream behaves like all the other
<ide> * DecodeStreams.
<ide> */
<del>var JpegStream = (function jpegStream() {
<add>var JpegStream = (function JpegStreamClosure() {
<ide> function isAdobeImage(bytes) {
<ide> var maxBytesScanned = Math.max(bytes.length - 16, 1024);
<ide> // Looking for APP14, 'Adobe'
<ide> var JpegStream = (function jpegStream() {
<ide> return newBytes;
<ide> }
<ide>
<del> function constructor(bytes, dict, xref) {
<add> function JpegStream(bytes, dict, xref) {
<ide> // TODO: per poppler, some images may have 'junk' before that
<ide> // need to be removed
<ide> this.dict = dict;
<ide> var JpegStream = (function jpegStream() {
<ide> DecodeStream.call(this);
<ide> }
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> JpegStream.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.ensureBuffer = function jpegStreamEnsureBuffer(req) {
<add> JpegStream.prototype.ensureBuffer = function jpegStreamEnsureBuffer(req) {
<ide> if (this.bufferLength)
<ide> return;
<ide> var jpegImage = new JpegImage();
<ide> var JpegStream = (function jpegStream() {
<ide> this.buffer = data;
<ide> this.bufferLength = data.length;
<ide> };
<del> constructor.prototype.getIR = function jpegStreamGetIR() {
<add> JpegStream.prototype.getIR = function jpegStreamGetIR() {
<ide> return this.src;
<ide> };
<del> constructor.prototype.getChar = function jpegStreamGetChar() {
<add> JpegStream.prototype.getChar = function jpegStreamGetChar() {
<ide> error('internal error: getChar is not valid on JpegStream');
<ide> };
<ide>
<del> return constructor;
<add> return JpegStream;
<ide> })();
<ide>
<del>var DecryptStream = (function decryptStream() {
<del> function constructor(str, decrypt) {
<add>var DecryptStream = (function DecryptStreamClosure() {
<add> function DecryptStream(str, decrypt) {
<ide> this.str = str;
<ide> this.dict = str.dict;
<ide> this.decrypt = decrypt;
<ide> var DecryptStream = (function decryptStream() {
<ide>
<ide> var chunkSize = 512;
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> DecryptStream.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.readBlock = function decryptStreamReadBlock() {
<add> DecryptStream.prototype.readBlock = function decryptStreamReadBlock() {
<ide> var chunk = this.str.getBytes(chunkSize);
<ide> if (!chunk || chunk.length == 0) {
<ide> this.eof = true;
<ide> var DecryptStream = (function decryptStream() {
<ide> this.bufferLength = bufferLength;
<ide> };
<ide>
<del> return constructor;
<add> return DecryptStream;
<ide> })();
<ide>
<del>var Ascii85Stream = (function ascii85Stream() {
<del> function constructor(str) {
<add>var Ascii85Stream = (function Ascii85StreamClosure() {
<add> function Ascii85Stream(str) {
<ide> this.str = str;
<ide> this.dict = str.dict;
<ide> this.input = new Uint8Array(5);
<ide>
<ide> DecodeStream.call(this);
<ide> }
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> Ascii85Stream.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.readBlock = function ascii85StreamReadBlock() {
<add> Ascii85Stream.prototype.readBlock = function ascii85StreamReadBlock() {
<ide> var tildaCode = '~'.charCodeAt(0);
<ide> var zCode = 'z'.charCodeAt(0);
<ide> var str = this.str;
<ide> var Ascii85Stream = (function ascii85Stream() {
<ide> }
<ide> };
<ide>
<del> return constructor;
<add> return Ascii85Stream;
<ide> })();
<ide>
<del>var AsciiHexStream = (function asciiHexStream() {
<del> function constructor(str) {
<add>var AsciiHexStream = (function AsciiHexStreamClosure() {
<add> function AsciiHexStream(str) {
<ide> this.str = str;
<ide> this.dict = str.dict;
<ide>
<ide> var AsciiHexStream = (function asciiHexStream() {
<ide> 102: 15
<ide> };
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> AsciiHexStream.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.readBlock = function asciiHexStreamReadBlock() {
<add> AsciiHexStream.prototype.readBlock = function asciiHexStreamReadBlock() {
<ide> var gtCode = '>'.charCodeAt(0), bytes = this.str.getBytes(), c, n,
<ide> decodeLength, buffer, bufferLength, i, length;
<ide>
<ide> var AsciiHexStream = (function asciiHexStream() {
<ide> this.eof = true;
<ide> };
<ide>
<del> return constructor;
<add> return AsciiHexStream;
<ide> })();
<ide>
<del>var CCITTFaxStream = (function ccittFaxStream() {
<add>var CCITTFaxStream = (function CCITTFaxStreamClosure() {
<ide>
<ide> var ccittEOL = -2;
<ide> var twoDimPass = 0;
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> [2, 2], [2, 2], [2, 2], [2, 2]
<ide> ];
<ide>
<del> function constructor(str, params) {
<add> function CCITTFaxStream(str, params) {
<ide> this.str = str;
<ide> this.dict = str.dict;
<ide>
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> DecodeStream.call(this);
<ide> }
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.readBlock = function ccittFaxStreamReadBlock() {
<add> CCITTFaxStream.prototype.readBlock = function ccittFaxStreamReadBlock() {
<ide> while (!this.eof) {
<ide> var c = this.lookChar();
<ide> this.buf = EOF;
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> }
<ide> };
<ide>
<del> constructor.prototype.addPixels =
<add> CCITTFaxStream.prototype.addPixels =
<ide> function ccittFaxStreamAddPixels(a1, blackPixels) {
<ide> var codingLine = this.codingLine;
<ide> var codingPos = this.codingPos;
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> this.codingPos = codingPos;
<ide> };
<ide>
<del> constructor.prototype.addPixelsNeg =
<add> CCITTFaxStream.prototype.addPixelsNeg =
<ide> function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {
<ide> var codingLine = this.codingLine;
<ide> var codingPos = this.codingPos;
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> this.codingPos = codingPos;
<ide> };
<ide>
<del> constructor.prototype.lookChar = function ccittFaxStreamLookChar() {
<add> CCITTFaxStream.prototype.lookChar = function ccittFaxStreamLookChar() {
<ide> if (this.buf != EOF)
<ide> return this.buf;
<ide>
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> return [false, 0, false];
<ide> };
<ide>
<del> constructor.prototype.getTwoDimCode = function ccittFaxStreamGetTwoDimCode() {
<add> CCITTFaxStream.prototype.getTwoDimCode =
<add> function ccittFaxStreamGetTwoDimCode() {
<add>
<ide> var code = 0;
<ide> var p;
<ide> if (this.eoblock) {
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> return EOF;
<ide> };
<ide>
<del> constructor.prototype.getWhiteCode = function ccittFaxStreamGetWhiteCode() {
<add> CCITTFaxStream.prototype.getWhiteCode =
<add> function ccittFaxStreamGetWhiteCode() {
<add>
<ide> var code = 0;
<ide> var p;
<ide> var n;
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> return 1;
<ide> };
<ide>
<del> constructor.prototype.getBlackCode = function ccittFaxStreamGetBlackCode() {
<add> CCITTFaxStream.prototype.getBlackCode =
<add> function ccittFaxStreamGetBlackCode() {
<add>
<ide> var code, p;
<ide> if (this.eoblock) {
<ide> code = this.lookBits(13);
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> return 1;
<ide> };
<ide>
<del> constructor.prototype.lookBits = function ccittFaxStreamLookBits(n) {
<add> CCITTFaxStream.prototype.lookBits = function ccittFaxStreamLookBits(n) {
<ide> var c;
<ide> while (this.inputBits < n) {
<ide> if ((c = this.str.getByte()) == null) {
<ide> var CCITTFaxStream = (function ccittFaxStream() {
<ide> return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
<ide> };
<ide>
<del> constructor.prototype.eatBits = function ccittFaxStreamEatBits(n) {
<add> CCITTFaxStream.prototype.eatBits = function ccittFaxStreamEatBits(n) {
<ide> if ((this.inputBits -= n) < 0)
<ide> this.inputBits = 0;
<ide> };
<ide>
<del> return constructor;
<add> return CCITTFaxStream;
<ide> })();
<ide>
<del>var LZWStream = (function lzwStream() {
<del> function constructor(str, earlyChange) {
<add>var LZWStream = (function LZWStreamClosure() {
<add> function LZWStream(str, earlyChange) {
<ide> this.str = str;
<ide> this.dict = str.dict;
<ide> this.cachedData = 0;
<ide> var LZWStream = (function lzwStream() {
<ide> DecodeStream.call(this);
<ide> }
<ide>
<del> constructor.prototype = Object.create(DecodeStream.prototype);
<add> LZWStream.prototype = Object.create(DecodeStream.prototype);
<ide>
<del> constructor.prototype.readBits = function lzwStreamReadBits(n) {
<add> LZWStream.prototype.readBits = function lzwStreamReadBits(n) {
<ide> var bitsCached = this.bitsCached;
<ide> var cachedData = this.cachedData;
<ide> while (bitsCached < n) {
<ide> var LZWStream = (function lzwStream() {
<ide> return (cachedData >>> bitsCached) & ((1 << n) - 1);
<ide> };
<ide>
<del> constructor.prototype.readBlock = function lzwStreamReadBlock() {
<add> LZWStream.prototype.readBlock = function lzwStreamReadBlock() {
<ide> var blockSize = 512;
<ide> var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
<ide> var i, j, q;
<ide> var LZWStream = (function lzwStream() {
<ide> this.bufferLength = currentBufferLength;
<ide> };
<ide>
<del> return constructor;
<add> return LZWStream;
<ide> })();
<ide>
<ide><path>src/util.js
<ide> function stringToBytes(str) {
<ide>
<ide> var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
<ide>
<del>var Util = (function utilUtil() {
<del> function constructor() {}
<del> constructor.makeCssRgb = function makergb(r, g, b) {
<add>var Util = (function UtilClosure() {
<add> function Util() {}
<add> Util.makeCssRgb = function makergb(r, g, b) {
<ide> var ri = (255 * r) | 0, gi = (255 * g) | 0, bi = (255 * b) | 0;
<ide> return 'rgb(' + ri + ',' + gi + ',' + bi + ')';
<ide> };
<del> constructor.makeCssCmyk = function makecmyk(c, m, y, k) {
<add> Util.makeCssCmyk = function makecmyk(c, m, y, k) {
<ide> c = (new DeviceCmykCS()).getRgb([c, m, y, k]);
<ide> var ri = (255 * c[0]) | 0, gi = (255 * c[1]) | 0, bi = (255 * c[2]) | 0;
<ide> return 'rgb(' + ri + ',' + gi + ',' + bi + ')';
<ide> };
<del> constructor.applyTransform = function apply(p, m) {
<add> Util.applyTransform = function apply(p, m) {
<ide> var xt = p[0] * m[0] + p[1] * m[2] + m[4];
<ide> var yt = p[0] * m[1] + p[1] * m[3] + m[5];
<ide> return [xt, yt];
<ide> };
<ide>
<del> return constructor;
<add> return Util;
<ide> })();
<ide>
<ide> var PDFStringTranslateTable = [
<ide> function isPDFFunction(v) {
<ide> * can be set. If any of these happens twice or the data is required before
<ide> * it was set, an exception is throw.
<ide> */
<del>var Promise = (function promise() {
<add>var Promise = (function PromiseClosure() {
<ide> var EMPTY_PROMISE = {};
<ide>
<ide> /** | 12 |
PHP | PHP | add support for using iam roles for sqs queues | 2f4c14f5a4f58b1a6312074af53f07312653dee5 | <ide><path>src/Illuminate/Queue/Connectors/SqsConnector.php
<ide> class SqsConnector implements ConnectorInterface {
<ide> */
<ide> public function connect(array $config)
<ide> {
<del> $sqs = SqsClient::factory(array(
<add> $sqsConfig = array_only($config, array('key', 'secret', 'region', 'default_cache_config'));
<ide>
<del> 'key' => $config['key'], 'secret' => $config['secret'], 'region' => $config['region'],
<del>
<del> ));
<add> $sqs = SqsClient::factory($sqsConfig);
<ide>
<ide> return new SqsQueue($sqs, $config['queue']);
<ide> } | 1 |
Javascript | Javascript | fix amphtml href with nested amp page | 5a48272af004239fec5b765ccde336a73a888545 | <ide><path>packages/next/export/index.js
<ide> export default async function (dir, options, configuration) {
<ide> } else {
<ide> const ampPath = tryAmp(defaultPathMap, path)
<ide> if (ampPath !== path) {
<del> defaultPathMap[path].query = { hasAmp: true, ampPath }
<add> defaultPathMap[path].query = { hasAmp: true, ampPath: ampPath.replace(/(?<!^)\/index\.amp$/, '.amp') }
<ide> }
<ide> }
<ide> })
<ide><path>test/integration/export-default-map/test/index.test.js
<ide> /* global jasmine */
<ide> import fs from 'fs'
<ide> import { join } from 'path'
<add>import cheerio from 'cheerio'
<ide> import { promisify } from 'util'
<ide> import {
<ide> nextBuild,
<ide> nextExport
<ide> } from 'next-test-utils'
<ide>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<add>const readFile = promisify(fs.readFile)
<ide> const access = promisify(fs.access)
<ide> const appDir = join(__dirname, '../')
<ide> const outdir = join(appDir, 'out')
<ide> describe('Export with default map', () => {
<ide> })
<ide>
<ide> it('should export nested hybrid amp page correctly', async () => {
<del> expect.assertions(2)
<add> expect.assertions(3)
<ide> await expect(access(join(outdir, 'docs/index.html'))).resolves.toBe(undefined)
<ide> await expect(access(join(outdir, 'docs.amp/index.html'))).resolves.toBe(undefined)
<add>
<add> const html = await readFile(join(outdir, 'docs/index.html'))
<add> const $ = cheerio.load(html)
<add> expect($('link[rel=amphtml]').attr('href')).toBe('/docs.amp')
<ide> })
<ide>
<ide> it('should export nested hybrid amp page correctly with folder', async () => {
<del> expect.assertions(2)
<add> expect.assertions(3)
<ide> await expect(access(join(outdir, 'info/index.html'))).resolves.toBe(undefined)
<ide> await expect(access(join(outdir, 'info.amp/index.html'))).resolves.toBe(undefined)
<add>
<add> const html = await readFile(join(outdir, 'info/index.html'))
<add> const $ = cheerio.load(html)
<add> expect($('link[rel=amphtml]').attr('href')).toBe('/info.amp')
<ide> })
<ide> }) | 2 |
Python | Python | add a setup.py to the array_api submodule | d74a7d0b3297e10194bd3899a0d17a63610e49a1 | <ide><path>numpy/array_api/setup.py
<add>def configuration(parent_package='', top_path=None):
<add> from numpy.distutils.misc_util import Configuration
<add> config = Configuration('array_api', parent_package, top_path)
<add> config.add_subpackage('tests')
<add> return config
<add>
<add>
<add>if __name__ == '__main__':
<add> from numpy.distutils.core import setup
<add> setup(configuration=configuration) | 1 |
Ruby | Ruby | fix const reference in mach | 3703d60e573a152eea183c5ca030edd86167ad6f | <ide><path>Library/Homebrew/mach.rb
<ide> def universal?
<ide> end
<ide>
<ide> def ppc?
<del> (PPC_32BIT_ARCHS+PPC_64BIT_ARCHS).any? {|a| self.include? a}
<add> (Hardware::CPU::PPC_32BIT_ARCHS+Hardware::CPU::PPC_64BIT_ARCHS).any? {|a| self.include? a}
<ide> end
<ide>
<ide> def remove_ppc! | 1 |
Javascript | Javascript | fix hmr for dynamic entries (#652) | b8373b847dcf5d88ccfce27c7504331d63a9f6a5 | <ide><path>server/build/plugins/watch-pages-plugin.js
<ide> export default class WatchPagesPlugin {
<ide>
<ide> if (compiler.hasEntry(name)) return
<ide>
<del> const entries = [hotMiddlewareClientPath, f]
<add> const entries = [hotMiddlewareClientPath, f + '?entry']
<ide> compiler.addEntry(entries, name)
<ide> })
<ide>
<ide> export default class WatchPagesPlugin {
<ide> if (defaultPages.has(name)) {
<ide> compiler.addEntry([
<ide> hotMiddlewareClientPath,
<del> defaultPages.get(name)
<add> defaultPages.get(name) + '?entry'
<ide> ], name)
<ide> }
<ide> }) | 1 |
Javascript | Javascript | add some missing types in react-reconciler | cc8cb145f0bfebaeaddc4e7439efe5f3e14639ae | <ide><path>packages/react-reconciler/src/ReactFiber.new.js
<ide> export function createFiberFromSuspense(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_SUSPENSE_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromSuspenseList(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromOffscreen(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_OFFSCREEN_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromLegacyHidden(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(LegacyHiddenComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_LEGACY_HIDDEN_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromCache(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(CacheComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_CACHE_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromTracingMarker(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(TracingMarkerComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_TRACING_MARKER_TYPE;
<ide> fiber.lanes = lanes;
<ide><path>packages/react-reconciler/src/ReactFiber.old.js
<ide> export function createFiberFromSuspense(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_SUSPENSE_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromSuspenseList(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromOffscreen(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_OFFSCREEN_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromLegacyHidden(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(LegacyHiddenComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_LEGACY_HIDDEN_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromCache(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(CacheComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_CACHE_TYPE;
<ide> fiber.lanes = lanes;
<ide> export function createFiberFromTracingMarker(
<ide> mode: TypeOfMode,
<ide> lanes: Lanes,
<ide> key: null | string,
<del>) {
<add>): Fiber {
<ide> const fiber = createFiber(TracingMarkerComponent, pendingProps, key, mode);
<ide> fiber.elementType = REACT_TRACING_MARKER_TYPE;
<ide> fiber.lanes = lanes;
<ide><path>packages/react-reconciler/src/ReactFiberAct.new.js
<ide> export function isLegacyActEnvironment(fiber: Fiber): boolean {
<ide> return false;
<ide> }
<ide>
<del>export function isConcurrentActEnvironment() {
<add>export function isConcurrentActEnvironment(): void | boolean {
<ide> if (__DEV__) {
<ide> const isReactActEnvironmentGlobal =
<ide> // $FlowFixMe – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
<ide><path>packages/react-reconciler/src/ReactFiberAct.old.js
<ide> export function isLegacyActEnvironment(fiber: Fiber): boolean {
<ide> return false;
<ide> }
<ide>
<del>export function isConcurrentActEnvironment() {
<add>export function isConcurrentActEnvironment(): void | boolean {
<ide> if (__DEV__) {
<ide> const isReactActEnvironmentGlobal =
<ide> // $FlowFixMe – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global | 4 |
Java | Java | add bytebufencoder and bytebufdecoder | 3543e47841355680f00ba2c7dab525d7d9573f4b | <ide><path>spring-core/src/main/java/org/springframework/core/codec/ByteBufDecoder.java
<add>/*
<add> * Copyright 2002-2020 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.core.codec;
<add>
<add>import io.netty.buffer.ByteBuf;
<add>import io.netty.buffer.Unpooled;
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferUtils;
<add>import org.springframework.core.io.buffer.NettyDataBuffer;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.MimeType;
<add>import org.springframework.util.MimeTypeUtils;
<add>
<add>import java.util.Map;
<add>
<add>/**
<add> * Decoder for {@link ByteBuf ByteBufs}.
<add> *
<add> * @author Vladislav Kisel
<add> * @since 5.3
<add> */
<add>public class ByteBufDecoder extends AbstractDataBufferDecoder<ByteBuf> {
<add>
<add> public ByteBufDecoder() {
<add> super(MimeTypeUtils.ALL);
<add> }
<add>
<add>
<add> @Override
<add> public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType) {
<add> return (ByteBuf.class.isAssignableFrom(elementType.toClass()) &&
<add> super.canDecode(elementType, mimeType));
<add> }
<add>
<add> @Override
<add> public ByteBuf decode(DataBuffer dataBuffer, ResolvableType elementType,
<add> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> // Copies the dataBuffer if needed only
<add> ByteBuf byteBuf;
<add> if (dataBuffer instanceof NettyDataBuffer) {
<add> byteBuf = ((NettyDataBuffer) dataBuffer).getNativeBuffer();
<add> } else {
<add> byteBuf = Unpooled.wrappedBuffer(dataBuffer.asByteBuffer());
<add> DataBufferUtils.release(dataBuffer);
<add> }
<add>
<add> if (logger.isDebugEnabled()) {
<add> logger.debug(Hints.getLogPrefix(hints) + "Read " + byteBuf.readableBytes() + " bytes");
<add> }
<add> return byteBuf;
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/core/codec/ByteBufEncoder.java
<add>/*
<add> * Copyright 2002-2020 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.core.codec;
<add>
<add>import io.netty.buffer.ByteBuf;
<add>import org.reactivestreams.Publisher;
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferFactory;
<add>import org.springframework.core.io.buffer.NettyDataBufferFactory;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.MimeType;
<add>import org.springframework.util.MimeTypeUtils;
<add>import reactor.core.publisher.Flux;
<add>
<add>import java.util.Map;
<add>
<add>/**
<add> * Encoder for {@link ByteBuf ByteBufs}.
<add> *
<add> * @author Vladislav Kisel
<add> * @since 5.3
<add> */
<add>public class ByteBufEncoder extends AbstractEncoder<ByteBuf> {
<add>
<add> public ByteBufEncoder() {
<add> super(MimeTypeUtils.ALL);
<add> }
<add>
<add>
<add> @Override
<add> public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
<add> Class<?> clazz = elementType.toClass();
<add> return super.canEncode(elementType, mimeType) && ByteBuf.class.isAssignableFrom(clazz);
<add> }
<add>
<add> @Override
<add> public Flux<DataBuffer> encode(Publisher<? extends ByteBuf> inputStream,
<add> DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
<add> @Nullable Map<String, Object> hints) {
<add>
<add> return Flux.from(inputStream).map(byteBuffer ->
<add> encodeValue(byteBuffer, bufferFactory, elementType, mimeType, hints));
<add> }
<add>
<add> @Override
<add> public DataBuffer encodeValue(ByteBuf byteBuf, DataBufferFactory bufferFactory,
<add> ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add>
<add> DataBuffer dataBuffer;
<add> if (bufferFactory instanceof NettyDataBufferFactory) {
<add> dataBuffer = ((NettyDataBufferFactory) bufferFactory).wrap(byteBuf);
<add> } else {
<add> dataBuffer = bufferFactory.wrap(byteBuf.nioBuffer());
<add> }
<add>
<add> if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
<add> String logPrefix = Hints.getLogPrefix(hints);
<add> logger.debug(logPrefix + "Writing " + dataBuffer.readableByteCount() + " bytes");
<add> }
<add> return dataBuffer;
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/core/codec/ByteBufDecoderTests.java
<add>/*
<add> * Copyright 2002-2020 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.core.codec;
<add>
<add>import io.netty.buffer.ByteBuf;
<add>import io.netty.buffer.Unpooled;
<add>import org.junit.jupiter.api.Test;
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.testfixture.codec.AbstractDecoderTests;
<add>import org.springframework.util.MimeTypeUtils;
<add>import reactor.core.publisher.Flux;
<add>
<add>import java.nio.charset.StandardCharsets;
<add>import java.util.function.Consumer;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>
<add>/**
<add> * @author Vladislav Kisel
<add> */
<add>class ByteBufDecoderTests extends AbstractDecoderTests<ByteBufDecoder> {
<add>
<add> private final byte[] fooBytes = "foo".getBytes(StandardCharsets.UTF_8);
<add>
<add> private final byte[] barBytes = "bar".getBytes(StandardCharsets.UTF_8);
<add>
<add>
<add> ByteBufDecoderTests() {
<add> super(new ByteBufDecoder());
<add> }
<add>
<add> @Override
<add> @Test
<add> public void canDecode() {
<add> assertThat(this.decoder.canDecode(ResolvableType.forClass(ByteBuf.class),
<add> MimeTypeUtils.TEXT_PLAIN)).isTrue();
<add> assertThat(this.decoder.canDecode(ResolvableType.forClass(Integer.class),
<add> MimeTypeUtils.TEXT_PLAIN)).isFalse();
<add> assertThat(this.decoder.canDecode(ResolvableType.forClass(ByteBuf.class),
<add> MimeTypeUtils.APPLICATION_JSON)).isTrue();
<add> }
<add>
<add> @Override
<add> @Test
<add> public void decode() {
<add> Flux<DataBuffer> input = Flux.concat(
<add> dataBuffer(this.fooBytes),
<add> dataBuffer(this.barBytes));
<add>
<add> testDecodeAll(input, ByteBuf.class, step -> step
<add> .consumeNextWith(expectByteBuffer(Unpooled.copiedBuffer(this.fooBytes)))
<add> .consumeNextWith(expectByteBuffer(Unpooled.copiedBuffer(this.barBytes)))
<add> .verifyComplete());
<add> }
<add>
<add> @Override
<add> @Test
<add> public void decodeToMono() {
<add> Flux<DataBuffer> input = Flux.concat(
<add> dataBuffer(this.fooBytes),
<add> dataBuffer(this.barBytes));
<add>
<add> ByteBuf expected = Unpooled.buffer(this.fooBytes.length + this.barBytes.length)
<add> .writeBytes(this.fooBytes)
<add> .writeBytes(this.barBytes)
<add> .readerIndex(0);
<add>
<add> testDecodeToMonoAll(input, ByteBuf.class, step -> step
<add> .consumeNextWith(expectByteBuffer(expected))
<add> .verifyComplete());
<add> }
<add>
<add> private Consumer<ByteBuf> expectByteBuffer(ByteBuf expected) {
<add> return actual -> assertThat(actual).isEqualTo(expected);
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/core/codec/ByteBufEncoderTests.java
<add>/*
<add> * Copyright 2002-2020 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.core.codec;
<add>
<add>import io.netty.buffer.ByteBuf;
<add>import io.netty.buffer.Unpooled;
<add>import org.junit.jupiter.api.Test;
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.testfixture.codec.AbstractEncoderTests;
<add>import org.springframework.util.MimeTypeUtils;
<add>import reactor.core.publisher.Flux;
<add>
<add>import java.nio.charset.StandardCharsets;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>
<add>/**
<add> * @author Vladislav Kisel
<add> */
<add>class ByteBufEncoderTests extends AbstractEncoderTests<ByteBufEncoder> {
<add>
<add> private final byte[] fooBytes = "foo".getBytes(StandardCharsets.UTF_8);
<add>
<add> private final byte[] barBytes = "bar".getBytes(StandardCharsets.UTF_8);
<add>
<add> ByteBufEncoderTests() {
<add> super(new ByteBufEncoder());
<add> }
<add>
<add> @Override
<add> @Test
<add> public void canEncode() {
<add> assertThat(this.encoder.canEncode(ResolvableType.forClass(ByteBuf.class),
<add> MimeTypeUtils.TEXT_PLAIN)).isTrue();
<add> assertThat(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
<add> MimeTypeUtils.TEXT_PLAIN)).isFalse();
<add> assertThat(this.encoder.canEncode(ResolvableType.forClass(ByteBuf.class),
<add> MimeTypeUtils.APPLICATION_JSON)).isTrue();
<add>
<add> // SPR-15464
<add> assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse();
<add> }
<add>
<add> @Override
<add> @Test
<add> public void encode() {
<add> Flux<ByteBuf> input = Flux.just(this.fooBytes, this.barBytes).map(Unpooled::copiedBuffer);
<add>
<add> Unpooled.copiedBuffer(this.fooBytes, this.barBytes);
<add>
<add> testEncodeAll(input, ByteBuf.class, step -> step
<add> .consumeNextWith(expectBytes(this.fooBytes))
<add> .consumeNextWith(expectBytes(this.barBytes))
<add> .verifyComplete());
<add> }
<add>
<add>} | 4 |
Ruby | Ruby | move app initializers to sprockets railtie | 8f75c3abcde4f2ff64e855178027e1bd93976de9 | <ide><path>actionpack/lib/sprockets/railtie.rb
<ide> require "sprockets"
<ide>
<add># TODO: Move this to sprockets-rails
<add># If so, we can move the require to a Gemfile and remove assets.enabled
<ide> class Sprockets::Railtie < Rails::Railtie
<add> # Configure ActionController to use sprockets.
<ide> initializer "sprockets.set_configs", :after => "action_controller.set_configs" do |app|
<ide> ActiveSupport.on_load(:action_controller) do
<ide> self.use_sprockets = app.config.assets.enabled
<ide> end
<ide> end
<add>
<add> # We need to configure this after initialization to ensure we collect
<add> # paths from all engines. This hook is invoked exactly before routes
<add> # are compiled.
<add> config.after_initialize do |app|
<add> assets = app.config.assets
<add> next unless assets.enabled
<add>
<add> app.assets = asset_environment(app)
<add> app.routes.append do
<add> mount app.assets => assets.prefix
<add> end
<add>
<add> if config.action_controller.perform_caching
<add> app.assets = app.assets.index
<add> end
<add> end
<add>
<add> protected
<add>
<add> def asset_environment(app)
<add> assets = app.config.assets
<add> env = Sprockets::Environment.new(app.root.to_s)
<add> env.static_root = File.join(app.root.join("public"), assets.prefix)
<add> env.paths.concat assets.paths
<add> env.logger = Rails.logger
<add> env
<add> end
<ide> end
<ide>\ No newline at end of file
<ide><path>railties/lib/rails/application.rb
<ide> def config
<ide>
<ide> alias :build_middleware_stack :app
<ide>
<del> def build_asset_environment
<del> require 'sprockets'
<del> env = Sprockets::Environment.new(root.to_s)
<del> env.static_root = File.join(root.join("public"), config.assets.prefix)
<del> env.paths.concat config.assets.paths
<del> env.logger = Rails.logger
<del> @assets = env
<del> end
<del>
<ide> def default_middleware_stack
<ide> ActionDispatch::MiddlewareStack.new.tap do |middleware|
<ide> if rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache
<ide><path>railties/lib/rails/application/finisher.rb
<ide> module Finisher
<ide> end
<ide> end
<ide>
<del> initializer :add_sprockets_route do |app|
<del> assets = config.assets
<del> if assets.enabled
<del> build_asset_environment
<del> app.routes.append do
<del> mount app.assets => assets.prefix
<del> end
<del> end
<del> end
<del>
<del> initializer :index_sprockets_environment do |app|
<del> if config.assets.enabled && config.action_controller.perform_caching
<del> app.assets = app.assets.index
<del> end
<del> end
<del>
<ide> initializer :build_middleware_stack do
<ide> build_middleware_stack
<ide> end
<ide> module Finisher
<ide> end
<ide>
<ide> # Force routes to be loaded just at the end and add it to to_prepare callbacks
<add> # This needs to be after the finisher hook to ensure routes added in the hook
<add> # are still loaded.
<ide> initializer :set_routes_reloader do |app|
<ide> reloader = lambda { app.routes_reloader.execute_if_updated }
<ide> reloader.call | 3 |
Ruby | Ruby | remove unused variable | c3c4a8b9139a750fbf950190b67243724b91a212 | <ide><path>Library/Contributions/cmd/brew-readall.rb
<ide> require 'formula'
<ide> Formula.names.each do |n|
<ide> begin
<del> f = Formula.factory(n)
<add> Formula.factory(n)
<ide> rescue Exception => e
<ide> onoe "problem in #{Formula.path(n)}"
<ide> puts e | 1 |
Python | Python | fix state and try number for failed mapped tasks | a1fd82f2a5c9edc4817b04b4ccc257d6e394f886 | <ide><path>airflow/www/utils.py
<ide> def get_mapped_instances(task_instance, session):
<ide> TaskInstance.dag_id == task_instance.dag_id,
<ide> TaskInstance.run_id == task_instance.run_id,
<ide> TaskInstance.task_id == task_instance.task_id,
<del> TaskInstance.map_index >= 0,
<ide> )
<ide> .all()
<ide> )
<ide> def get_mapped_summary(parent_instance, task_instances):
<ide> max((ti.end_date for ti in task_instances if ti.end_date), default=None)
<ide> )
<ide>
<add> try_count = (
<add> parent_instance.prev_attempted_tries
<add> if parent_instance.prev_attempted_tries != 0
<add> else parent_instance.try_number
<add> )
<ide> return {
<ide> 'dag_id': parent_instance.dag_id,
<ide> 'task_id': parent_instance.task_id,
<ide> def get_mapped_summary(parent_instance, task_instances):
<ide> 'mapped_states': mapped_states,
<ide> 'operator': parent_instance.operator,
<ide> 'execution_date': datetime_to_string(parent_instance.execution_date),
<del> 'try_number': parent_instance.try_number,
<add> 'try_number': try_count,
<ide> }
<ide>
<ide>
<ide> def encode_ti(
<ide> if is_mapped:
<ide> return get_mapped_summary(task_instance, task_instances=get_mapped_instances(task_instance, session))
<ide>
<add> try_count = (
<add> task_instance.prev_attempted_tries
<add> if task_instance.prev_attempted_tries != 0
<add> else task_instance.try_number
<add> )
<ide> return {
<ide> 'task_id': task_instance.task_id,
<ide> 'dag_id': task_instance.dag_id,
<ide> def encode_ti(
<ide> 'end_date': datetime_to_string(task_instance.end_date),
<ide> 'operator': task_instance.operator,
<ide> 'execution_date': datetime_to_string(task_instance.execution_date),
<del> 'try_number': task_instance.try_number,
<add> 'try_number': try_count,
<ide> }
<ide>
<ide> | 1 |
Javascript | Javascript | fix statistics calculation for instanced geometry | c49ac0847bb1ade3b0efd931c6f97aca064ab889 | <ide><path>src/renderers/webgl/WebGLBufferRenderer.js
<ide> THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {
<ide>
<ide> if ( position instanceof THREE.InterleavedBufferAttribute ) {
<ide>
<del> extension.drawArraysInstancedANGLE( mode, 0, position.data.count, geometry.maxInstancedCount );
<add> var count = position.data.count;
<add>
<add> extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
<add>
<add> _infoRender.calls ++;
<add> _infoRender.vertices += count * geometry.maxInstancedCount;
<add> if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
<ide>
<ide> } else {
<ide>
<del> extension.drawArraysInstancedANGLE( mode, 0, position.count, geometry.maxInstancedCount );
<add> var count = position.count;
<add>
<add> extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
<add>
<add> _infoRender.calls ++;
<add> _infoRender.vertices += count * geometry.maxInstancedCount;
<add> if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
<ide>
<ide> }
<ide>
<ide><path>src/renderers/webgl/WebGLIndexedBufferRenderer.js
<ide> THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) {
<ide>
<ide> extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
<ide>
<add> _infoRender.calls ++;
<add> _infoRender.vertices += count * geometry.maxInstancedCount;
<add> if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
<ide> }
<ide>
<ide> this.setMode = setMode; | 2 |
Javascript | Javascript | verify the names parameter | 2508d2c12bb1a9319b84abc8e0b763d899471afa | <ide><path>src/fonts.js
<ide> var FontLoader = {
<ide> // The postMessage() hackery was added to work around chrome bug
<ide> // 82402.
<ide>
<add> // Validate the names parameter -- the values can used to construct HTML.
<add> if (!/^\w+$/.test(names.join(''))) {
<add> error('Invalid font name(s): ' + names.join());
<add> return; // Keep the return in case if error() did not throw.
<add> }
<add>
<ide> var div = document.createElement('div');
<ide> div.setAttribute('style',
<ide> 'visibility: hidden;' + | 1 |
Java | Java | fix checkstyle issue | 9a81d0276e4b94093b3c6a5a1d409d68a64204f7 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/InvocableHandlerMethod.java
<ide>
<ide> package org.springframework.web.reactive.result.method;
<ide>
<del>import static org.springframework.web.reactive.result.method.InvocableHandlerMethodKt.*;
<del>
<ide> import java.lang.reflect.InvocationTargetException;
<ide> import java.lang.reflect.Method;
<ide> import java.lang.reflect.ParameterizedType;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<add>import static org.springframework.web.reactive.result.method.InvocableHandlerMethodKt.invokeHandlerMethod;
<add>
<ide> /**
<ide> * Extension of {@link HandlerMethod} that invokes the underlying method with
<ide> * argument values resolved from the current HTTP request through a list of | 1 |
Mixed | Ruby | fix word case. `json` -> `json` | 3a32915bbcfea4e0d8acde257ab9254ff2392de6 | <ide><path>actionpack/CHANGELOG.md
<del>* Rescue `JSON::ParserError` in Cookies json deserializer to discards marshal dumps:
<add>* Rescue `JSON::ParserError` in Cookies JSON deserializer to discards marshal dumps:
<ide>
<ide> Without this change, if `action_dispatch.cookies_serializer` is set to `:json` and
<ide> the app tries to read a `:marshal` serialized cookie, it would error out which wouldn't
<ide><path>actionpack/test/dispatch/request/json_params_parsing_test.rb
<ide> def teardown
<ide> TestController.last_request_parameters = nil
<ide> end
<ide>
<del> test "parses json params for application json" do
<add> test "parses JSON params for application JSON" do
<ide> assert_parses(
<ide> { "person" => { "name" => "David" } },
<ide> "{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/json"
<ide> )
<ide> end
<ide>
<del> test "parses boolean and number json params for application json" do
<add> test "parses boolean and number JSON params for application JSON" do
<ide> assert_parses(
<ide> { "item" => { "enabled" => false, "count" => 10 } },
<ide> "{\"item\": {\"enabled\": false, \"count\": 10}}", "CONTENT_TYPE" => "application/json"
<ide> )
<ide> end
<ide>
<del> test "parses json params for application jsonrequest" do
<add> test "parses JSON params for application jsonrequest" do
<ide> assert_parses(
<ide> { "person" => { "name" => "David" } },
<ide> "{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/jsonrequest"
<ide> )
<ide> end
<ide>
<del> test "parses json params for application problem+json" do
<add> test "parses JSON params for application problem+json" do
<ide> assert_parses(
<ide> { "person" => { "name" => "David" } },
<ide> "{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/problem+json"
<ide> def teardown
<ide> UsersController.last_request_parameters = nil
<ide> end
<ide>
<del> test "parses json params for application json" do
<add> test "parses JSON params for application JSON" do
<ide> assert_parses(
<ide> { "user" => { "username" => "sikachu" }, "username" => "sikachu" },
<ide> "{\"username\": \"sikachu\"}", "CONTENT_TYPE" => "application/json"
<ide> )
<ide> end
<ide>
<del> test "parses json params for application jsonrequest" do
<add> test "parses JSON params for application jsonrequest" do
<ide> assert_parses(
<ide> { "user" => { "username" => "sikachu" }, "username" => "sikachu" },
<ide> "{\"username\": \"sikachu\"}", "CONTENT_TYPE" => "application/jsonrequest"
<ide> )
<ide> end
<ide>
<del> test "parses json params for application problem+json" do
<add> test "parses JSON params for application problem+json" do
<ide> assert_parses(
<ide> { "user" => { "username" => "sikachu" }, "username" => "sikachu" },
<ide> "{\"username\": \"sikachu\"}", "CONTENT_TYPE" => "application/problem+json"
<ide> )
<ide> end
<ide>
<del> test "parses json with non-object JSON content" do
<add> test "parses JSON with non-object JSON content" do
<ide> assert_parses(
<ide> { "user" => { "_json" => "string content" }, "_json" => "string content" },
<ide> "\"string content\"", "CONTENT_TYPE" => "application/json"
<ide> )
<ide> end
<ide>
<del> test "parses json params after custom json mime type registered" do
<add> test "parses JSON params after custom JSON mime type registered" do
<ide> Mime::Type.unregister :json
<ide> Mime::Type.register "application/json", :json, %w(application/vnd.rails+json)
<ide> assert_parses(
<ide> def teardown
<ide> Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest application/problem+json )
<ide> end
<ide>
<del> test "parses json params after custom json mime type registered with synonym" do
<add> test "parses JSON params after custom JSON mime type registered with synonym" do
<ide> Mime::Type.unregister :json
<ide> Mime::Type.register "application/json", :json, %w(application/vnd.rails+json)
<ide> assert_parses(
<ide><path>actionview/test/ujs/public/vendor/jquery-2.2.0.js
<ide> jQuery.extend( {
<ide> // Text to html (true = no transformation)
<ide> "text html": true,
<ide>
<del> // Evaluate text as a json expression
<add> // Evaluate text as a JSON expression
<ide> "text json": jQuery.parseJSON,
<ide>
<ide> // Parse text as xml
<ide> jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
<ide> s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
<ide> }
<ide>
<del> // Use data converter to retrieve json after script execution
<add> // Use data converter to retrieve JSON after script execution
<ide> s.converters[ "script json" ] = function() {
<ide> if ( !responseContainer ) {
<ide> jQuery.error( callbackName + " was not called" );
<ide> }
<ide> return responseContainer[ 0 ];
<ide> };
<ide>
<del> // Force json dataType
<add> // Force JSON dataType
<ide> s.dataTypes[ 0 ] = "json";
<ide>
<ide> // Install callback
<ide><path>activemodel/lib/active_model/errors.rb
<ide> def attribute_names
<ide>
<ide> # Returns a Hash that can be used as the JSON representation for this
<ide> # object. You can pass the <tt>:full_messages</tt> option. This determines
<del> # if the json object should contain full messages or not (false by default).
<add> # if the JSON object should contain full messages or not (false by default).
<ide> #
<ide> # person.errors.as_json # => {:name=>["cannot be nil"]}
<ide> # person.errors.as_json(full_messages: true) # => {:name=>["name cannot be nil"]}
<ide><path>activemodel/test/cases/serializers/json_serialization_test.rb
<ide> def setup
<ide> @contact.preferences = { "shows" => "anime" }
<ide> end
<ide>
<del> test "should not include root in json (class method)" do
<add> test "should not include root in JSON (class method)" do
<ide> json = @contact.to_json
<ide>
<ide> assert_no_match %r{^\{"contact":\{}, json
<ide> def setup
<ide> assert_match %r{"preferences":\{"shows":"anime"\}}, json
<ide> end
<ide>
<del> test "should include root in json if include_root_in_json is true" do
<add> test "should include root in JSON if include_root_in_json is true" do
<ide> original_include_root_in_json = Contact.include_root_in_json
<ide> Contact.include_root_in_json = true
<ide> json = @contact.to_json
<ide> def setup
<ide> Contact.include_root_in_json = original_include_root_in_json
<ide> end
<ide>
<del> test "should include root in json (option) even if the default is set to false" do
<add> test "should include root in JSON (option) even if the default is set to false" do
<ide> json = @contact.to_json(root: true)
<ide>
<ide> assert_match %r{^\{"contact":\{}, json
<ide> end
<ide>
<del> test "should not include root in json (option)" do
<add> test "should not include root in JSON (option)" do
<ide> json = @contact.to_json(root: false)
<ide>
<ide> assert_no_match %r{^\{"contact":\{}, json
<ide> end
<ide>
<del> test "should include custom root in json" do
<add> test "should include custom root in JSON" do
<ide> json = @contact.to_json(root: "json_contact")
<ide>
<ide> assert_match %r{^\{"json_contact":\{}, json
<ide> def @contact.as_json(options = {}); super(options.merge(only: [:name])); end
<ide> assert_no_match %r{"preferences":}, json
<ide> end
<ide>
<del> test "Class.model_name should be json encodable" do
<add> test "Class.model_name should be JSON encodable" do
<ide> assert_match %r{"Contact"}, Contact.model_name.to_json
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def supports_datetime_with_precision?
<ide> false
<ide> end
<ide>
<del> # Does this adapter support json data type?
<add> # Does this adapter support JSON data type?
<ide> def supports_json?
<ide> false
<ide> end
<ide><path>activerecord/test/cases/attribute_methods_test.rb
<ide> def topic.approved; false; end
<ide> assert_predicate topic, :user_defined_time?
<ide> end
<ide>
<del> test "user-defined json attribute predicate" do
<add> test "user-defined JSON attribute predicate" do
<ide> klass = Class.new(ActiveRecord::Base) do
<ide> self.table_name = Topic.table_name
<ide>
<ide><path>activesupport/lib/active_support/core_ext/object/json.rb
<ide> # frozen_string_literal: true
<ide>
<del># Hack to load json gem first so we can override its to_json.
<add># Hack to load JSON gem first so we can override its to_json.
<ide> require "json"
<ide> require "bigdecimal"
<ide> require "ipaddr"
<ide><path>activesupport/lib/active_support/json/decoding.rb
<ide> require "json"
<ide>
<ide> module ActiveSupport
<del> # Look for and parse json strings that look like ISO 8601 times.
<add> # Look for and parse JSON strings that look like ISO 8601 times.
<ide> mattr_accessor :parse_json_times
<ide>
<ide> module JSON
<ide><path>activesupport/test/core_ext/object/json_cherry_pick_test.rb
<ide>
<ide> require_relative "../../abstract_unit"
<ide>
<del># These test cases were added to test that cherry-picking the json extensions
<add># These test cases were added to test that cherry-picking the JSON extensions
<ide> # works correctly, primarily for dependencies problems reported in #16131. They
<ide> # need to be executed in isolation to reproduce the scenario correctly, because
<ide> # other test cases might have already loaded additional dependencies.
<ide><path>activesupport/test/core_ext/object/json_gem_encoding_test.rb
<ide> require "json"
<ide> require_relative "../../json/encoding_test_cases"
<ide>
<del># These test cases were added to test that we do not interfere with json gem's
<add># These test cases were added to test that we do not interfere with JSON gem's
<ide> # output when the AS encoder is loaded, primarily for problems reported in
<ide> # #20775. They need to be executed in isolation to reproduce the scenario
<ide> # correctly, because other test cases might have already loaded additional
<ide><path>activesupport/test/json/decoding_test.rb
<ide> def self.json_create(object)
<ide> %q({"a":"\n"}) => { "a" => "\n" },
<ide> %q({"a":"\u000a"}) => { "a" => "\n" },
<ide> %q({"a":"Line1\u000aLine2"}) => { "a" => "Line1\nLine2" },
<del> # prevent json unmarshalling
<add> # prevent JSON unmarshalling
<ide> '{"json_class":"TestJSONDecoding::Foo"}' => { "json_class" => "TestJSONDecoding::Foo" },
<del> # json "fragments" - these are invalid JSON, but ActionPack relies on this
<add> # JSON "fragments" - these are invalid JSON, but ActionPack relies on this
<ide> '"a string"' => "a string",
<ide> "1.1" => 1.1,
<ide> "1" => 1,
<ide> def self.json_create(object)
<ide> TESTS.each_with_index do |(json, expected), index|
<ide> fail_message = "JSON decoding failed for #{json}"
<ide>
<del> test "json decodes #{index}" do
<add> test "JSON decodes #{index}" do
<ide> with_tz_default "Eastern Time (US & Canada)" do
<ide> with_parse_json_times(true) do
<ide> silence_warnings do
<ide> def self.json_create(object)
<ide> end
<ide> end
<ide>
<del> test "json decodes time json with time parsing disabled" do
<add> test "JSON decodes time JSON with time parsing disabled" do
<ide> with_parse_json_times(false) do
<ide> expected = { "a" => "2007-01-01 01:12:34 Z" }
<ide> assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"}))
<ide><path>guides/source/4_1_release_notes.md
<ide> for detailed changes.
<ide> map to integers in the database, but can be queried by
<ide> name. ([Commit](https://github.com/rails/rails/commit/db41eb8a6ea88b854bf5cd11070ea4245e1639c5))
<ide>
<del>* Type cast json values on write, so that the value is consistent with reading
<add>* Type cast JSON values on write, so that the value is consistent with reading
<ide> from the database. ([Pull Request](https://github.com/rails/rails/pull/12643))
<ide>
<ide> * Type cast hstore values on write, so that the value is consistent
<ide><path>guides/source/i18n.md
<ide> The I18n API described in this guide is primarily intended for translating inter
<ide>
<ide> Several gems can help with this:
<ide>
<del>* [Mobility](https://github.com/shioyama/mobility): Provides support for storing translations in many formats, including translation tables, json columns (PostgreSQL), etc.
<add>* [Mobility](https://github.com/shioyama/mobility): Provides support for storing translations in many formats, including translation tables, JSON columns (PostgreSQL), etc.
<ide> * [Traco](https://github.com/barsoom/traco): Translatable columns stored in the model table itself
<ide>
<ide> Conclusion
<ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> start using the more precise `:plain`, `:html`, and `:body` options instead.
<ide> Using `render :text` may pose a security risk, as the content is sent as
<ide> `text/html`.
<ide>
<del>### PostgreSQL json and hstore datatypes
<add>### PostgreSQL JSON and hstore datatypes
<ide>
<ide> Rails 4.1 will map `json` and `hstore` columns to a string-keyed Ruby `Hash`.
<ide> In earlier versions, a `HashWithIndifferentAccess` was used. This means that
<ide><path>railties/test/application/middleware/cookies_test.rb
<ide> def read_raw_cookie
<ide> assert_equal "signed cookie", verifier_sha512.verify(last_response.body, purpose: "cookie.signed_cookie")
<ide> end
<ide>
<del> test "signed cookies with SHA512 digest and json serializer and rotated out SHA256 and SHA1 digests" do
<add> test "signed cookies with SHA512 digest and JSON serializer and rotated out SHA256 and SHA1 digests" do
<ide> app_file "config/routes.rb", <<-RUBY
<ide> Rails.application.routes.draw do
<ide> get ':controller(/:action)'
<ide><path>railties/test/application/middleware/session_test.rb
<ide> def read_cookie
<ide> assert_equal '"1"', last_response.body
<ide> end
<ide>
<del> test "session using encrypted cookie store with json serializer" do
<add> test "session using encrypted cookie store with JSON serializer" do
<ide> app_file "config/routes.rb", <<-RUBY
<ide> Rails.application.routes.draw do
<ide> get ':controller(/:action)' | 17 |
Javascript | Javascript | improve coverage for util.promisify | f86427eae844477b70c256e3c9cbd36970c4b5b0 | <ide><path>test/parallel/test-util-promisify.js
<ide> const stat = promisify(fs.stat);
<ide> })
<ide> ]);
<ide> }
<add>
<add>[undefined, null, true, 0, 'str', {}, [], Symbol()].forEach((input) => {
<add> common.expectsError(
<add> () => promisify(input),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "original" argument must be of type Function'
<add> });
<add>}); | 1 |
Java | Java | fix the race condition in bufferuntilsubscriber | f7a59afa822d14d20a200aacefee2eaf82845e12 | <ide><path>rxjava-core/src/test/java/rx/internal/operators/BufferUntilSubscriberTest.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<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>package rx.internal.operators;
<add>
<add>import org.junit.Assert;
<add>import org.junit.Test;
<add>import rx.Observable;
<add>import rx.functions.Action1;
<add>import rx.functions.Func1;
<add>import rx.schedulers.Schedulers;
<add>import rx.subjects.PublishSubject;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.CountDownLatch;
<add>import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<add>import java.util.concurrent.atomic.AtomicLong;
<add>
<add>public class BufferUntilSubscriberTest {
<add>
<add> @Test
<add> public void testIssue1677() throws InterruptedException {
<add> final AtomicLong counter = new AtomicLong();
<add> final Integer[] numbers = new Integer[5000];
<add> for (int i = 0; i < numbers.length; i++)
<add> numbers[i] = i + 1;
<add> final int NITERS = 250;
<add> final CountDownLatch latch = new CountDownLatch(NITERS);
<add> for (int iters = 0; iters < NITERS; iters++) {
<add> final CountDownLatch innerLatch = new CountDownLatch(1);
<add> final PublishSubject s = PublishSubject.create();
<add> final AtomicBoolean completed = new AtomicBoolean();
<add> Observable.from(numbers)
<add> .takeUntil(s)
<add> .window(50)
<add> .flatMap(new Func1<Observable<Integer>, Observable<Integer>>() {
<add> @Override
<add> public Observable<Integer> call(Observable<Integer> integerObservable) {
<add> return integerObservable
<add> .subscribeOn(Schedulers.computation())
<add> .map(new Func1<Integer, Integer>() {
<add> @Override
<add> public Integer call(Integer integer) {
<add> if (integer >= 5 && completed.compareAndSet(false, true)) {
<add> s.onCompleted();
<add> }
<add> // do some work
<add> Math.pow(Math.random(), Math.random());
<add> return integer * 2;
<add> }
<add> });
<add> }
<add> })
<add> .toList()
<add> .doOnNext(new Action1<List<Integer>>() {
<add> @Override
<add> public void call(List<Integer> integers) {
<add> counter.incrementAndGet();
<add> latch.countDown();
<add> innerLatch.countDown();
<add> }
<add> })
<add> .subscribe();
<add> if (!innerLatch.await(30, TimeUnit.SECONDS))
<add> Assert.fail("Failed inner latch wait, iteration " + iters);
<add> }
<add> if (!latch.await(30, TimeUnit.SECONDS))
<add> Assert.fail("Incomplete! Went through " + latch.getCount() + " iterations");
<add> else
<add> Assert.assertEquals(NITERS, counter.get());
<add> }
<add>}
<ide><path>src/main/java/rx/internal/operators/BufferUntilSubscriber.java
<ide> package rx.internal.operators;
<ide>
<ide> import java.util.concurrent.ConcurrentLinkedQueue;
<del>import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
<ide> import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
<ide>
<ide> import rx.Observer;
<ide> public static <T> BufferUntilSubscriber<T> create() {
<ide>
<ide> /** The common state. */
<ide> static final class State<T> {
<del> /** The first observer or the one which buffers until the first arrives. */
<del> volatile Observer<? super T> observerRef = new BufferedObserver<T>();
<del> /** Allow a single subscriber only. */
<del> volatile int first;
<add> volatile Observer<? super T> observerRef = null;
<ide> /** Field updater for observerRef. */
<ide> @SuppressWarnings("rawtypes")
<ide> static final AtomicReferenceFieldUpdater<State, Observer> OBSERVER_UPDATER
<ide> = AtomicReferenceFieldUpdater.newUpdater(State.class, Observer.class, "observerRef");
<del> /** Field updater for first. */
<del> @SuppressWarnings("rawtypes")
<del> static final AtomicIntegerFieldUpdater<State> FIRST_UPDATER
<del> = AtomicIntegerFieldUpdater.newUpdater(State.class, "first");
<del>
<del> boolean casFirst(int expected, int next) {
<del> return FIRST_UPDATER.compareAndSet(this, expected, next);
<del> }
<del> void setObserverRef(Observer<? super T> o) {
<del> observerRef = o;
<add>
<add> boolean casObserverRef(Observer<? super T> expected, Observer<? super T> next) {
<add> return OBSERVER_UPDATER.compareAndSet(this, expected, next);
<ide> }
<add>
<add> Object guard = new Object();
<add> /* protected by guard */
<add> boolean emitting = false;
<add>
<add> final ConcurrentLinkedQueue<Object> buffer = new ConcurrentLinkedQueue<Object>();
<add> final NotificationLite<T> nl = NotificationLite.instance();
<ide> }
<ide>
<ide> static final class OnSubscribeAction<T> implements OnSubscribe<T> {
<ide> public OnSubscribeAction(State<T> state) {
<ide>
<ide> @Override
<ide> public void call(final Subscriber<? super T> s) {
<del> if (state.casFirst(0, 1)) {
<del> final NotificationLite<T> nl = NotificationLite.instance();
<del> // drain queued notifications before subscription
<del> // we do this here before PassThruObserver so the consuming thread can do this before putting itself in the line of the producer
<del> BufferedObserver<? super T> buffered = (BufferedObserver<? super T>)state.observerRef;
<del> Object o;
<del> while ((o = buffered.buffer.poll()) != null) {
<del> nl.accept(s, o);
<del> }
<del> // register real observer for pass-thru ... and drain any further events received on first notification
<del> state.setObserverRef(new PassThruObserver<T>(s, buffered.buffer, state));
<add> if (state.casObserverRef(null, s)) {
<ide> s.add(Subscriptions.create(new Action0() {
<ide> @Override
<ide> public void call() {
<del> state.setObserverRef(Subscribers.empty());
<add> state.observerRef = Subscribers.empty();
<ide> }
<ide> }));
<add> boolean win = false;
<add> synchronized (state.guard) {
<add> if (!state.emitting) {
<add> state.emitting = true;
<add> win = true;
<add> }
<add> }
<add> if (win) {
<add> final NotificationLite<T> nl = NotificationLite.instance();
<add> while(true) {
<add> Object o;
<add> while ((o = state.buffer.poll()) != null) {
<add> nl.accept(state.observerRef, o);
<add> }
<add> synchronized (state.guard) {
<add> if (state.buffer.isEmpty()) {
<add> // Although the buffer is empty, there is still a chance
<add> // that further events may be put into the `buffer`.
<add> // `emit(Object v)` should handle it.
<add> state.emitting = false;
<add> break;
<add> }
<add> }
<add> }
<add> }
<ide> } else {
<ide> s.onError(new IllegalStateException("Only one subscriber allowed!"));
<ide> }
<ide> }
<ide>
<ide> }
<ide> final State<T> state;
<del>
<add>
<add> private boolean forward = false;
<add>
<ide> private BufferUntilSubscriber(State<T> state) {
<ide> super(new OnSubscribeAction<T>(state));
<ide> this.state = state;
<ide> }
<ide>
<del> @Override
<del> public void onCompleted() {
<del> state.observerRef.onCompleted();
<del> }
<del>
<del> @Override
<del> public void onError(Throwable e) {
<del> state.observerRef.onError(e);
<add> private void emit(Object v) {
<add> synchronized (state.guard) {
<add> state.buffer.add(v);
<add> if (state.observerRef != null && !state.emitting) {
<add> // Have an observer and nobody is emitting,
<add> // should drain the `buffer`
<add> forward = true;
<add> state.emitting = true;
<add> }
<add> }
<add> if (forward) {
<add> Object o;
<add> while ((o = state.buffer.poll()) != null) {
<add> state.nl.accept(state.observerRef, o);
<add> }
<add> // Because `emit(Object v)` will be called in sequence,
<add> // no event will be put into `buffer` after we drain it.
<add> }
<ide> }
<ide>
<ide> @Override
<del> public void onNext(T t) {
<del> state.observerRef.onNext(t);
<del> }
<del>
<del> /**
<del> * This is a temporary observer between buffering and the actual that gets into the line of notifications
<del> * from the producer and will drain the queue of any items received during the race of the initial drain and
<del> * switching this.
<del> *
<del> * It will then immediately swap itself out for the actual (after a single notification), but since this is
<del> * now being done on the same producer thread no further buffering will occur.
<del> */
<del> private static final class PassThruObserver<T> extends Subscriber<T> {
<del>
<del> private final Observer<? super T> actual;
<del> // this assumes single threaded synchronous notifications (the Rx contract for a single Observer)
<del> private final ConcurrentLinkedQueue<Object> buffer;
<del> private final State<T> state;
<del>
<del> PassThruObserver(Observer<? super T> actual, ConcurrentLinkedQueue<Object> buffer,
<del> State<T> state) {
<del> this.actual = actual;
<del> this.buffer = buffer;
<del> this.state = state;
<del> }
<del>
<del> @Override
<del> public void onCompleted() {
<del> drainIfNeededAndSwitchToActual();
<del> actual.onCompleted();
<add> public void onCompleted() {
<add> if (forward) {
<add> state.observerRef.onCompleted();
<ide> }
<del>
<del> @Override
<del> public void onError(Throwable e) {
<del> drainIfNeededAndSwitchToActual();
<del> actual.onError(e);
<add> else {
<add> emit(state.nl.completed());
<ide> }
<add> }
<ide>
<del> @Override
<del> public void onNext(T t) {
<del> drainIfNeededAndSwitchToActual();
<del> actual.onNext(t);
<add> @Override
<add> public void onError(Throwable e) {
<add> if (forward) {
<add> state.observerRef.onError(e);
<ide> }
<del>
<del> private void drainIfNeededAndSwitchToActual() {
<del> final NotificationLite<T> nl = NotificationLite.instance();
<del> Object o;
<del> while ((o = buffer.poll()) != null) {
<del> nl.accept(this, o);
<del> }
<del> // now we can safely change over to the actual and get rid of the pass-thru
<del> // but only if not unsubscribed
<del> state.setObserverRef(actual);
<add> else {
<add> emit(state.nl.error(e));
<ide> }
<del>
<ide> }
<ide>
<del> private static final class BufferedObserver<T> extends Subscriber<T> {
<del> private final ConcurrentLinkedQueue<Object> buffer = new ConcurrentLinkedQueue<Object>();
<del> private static final NotificationLite<Object> nl = NotificationLite.instance();
<del>
<del> @Override
<del> public void onCompleted() {
<del> buffer.add(nl.completed());
<del> }
<del>
<del> @Override
<del> public void onError(Throwable e) {
<del> buffer.add(nl.error(e));
<add> @Override
<add> public void onNext(T t) {
<add> if (forward) {
<add> state.observerRef.onNext(t);
<ide> }
<del>
<del> @Override
<del> public void onNext(T t) {
<del> buffer.add(nl.next(t));
<add> else {
<add> emit(state.nl.next(t));
<ide> }
<del>
<ide> }
<ide> } | 2 |
Go | Go | handle error for dockercmdindir | 1b34008532849467623039f78191e0f706fb34a5 | <ide><path>integration-cli/docker_cli_build_unix_test.go
<ide> func (s *DockerSuite) TestBuildResourceConstraintsAreUsed(c *check.C) {
<ide> `, map[string]string{})
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "--rm=false", "--memory=64m", "--memory-swap=-1", "--cpuset-cpus=0", "--cpuset-mems=0", "--cpu-shares=100", "--cpu-quota=8000", "--ulimit", "nofile=42", "-t", name, ".")
<add> _, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "--rm=false", "--memory=64m", "--memory-swap=-1", "--cpuset-cpus=0", "--cpuset-mems=0", "--cpu-shares=100", "--cpu-quota=8000", "--ulimit", "nofile=42", "-t", name, ".")
<add> if err != nil {
<add> c.Fatal(err)
<add> }
<ide>
<ide> out, _ := dockerCmd(c, "ps", "-lq")
<ide> cID := strings.TrimSpace(out) | 1 |
PHP | PHP | fix style error in tests | b1530ae9108c1a2c35094c6fc49a2c02605894c1 | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testCallbackArgumentTypes()
<ide> 'Model.beforeFind',
<ide> function (EventInterface $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) {
<ide> $this->assertInternalType('bool', $primary);
<del> $associationBeforeFindCount ++;
<add> $associationBeforeFindCount++;
<ide> }
<ide> );
<ide>
<ide> function (EventInterface $event, Query $query, ArrayObject $options, $primary) u
<ide> 'Model.beforeFind',
<ide> function (EventInterface $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) {
<ide> $this->assertInternalType('bool', $primary);
<del> $beforeFindCount ++;
<add> $beforeFindCount++;
<ide> }
<ide> );
<ide> $table->find()->contain('authors')->first();
<ide> function (EventInterface $event, Query $query, ArrayObject $options, $primary) u
<ide> 'Model.buildValidator',
<ide> $callback = function (EventInterface $event, Validator $validator, $name) use (&$buildValidatorCount) {
<ide> $this->assertInternalType('string', $name);
<del> $buildValidatorCount ++;
<add> $buildValidatorCount++;
<ide> }
<ide> );
<ide> $table->getValidator();
<ide> function (EventInterface $event, Query $query, ArrayObject $options, $primary) u
<ide> $eventManager->on(
<ide> 'Model.buildRules',
<ide> function (EventInterface $event, RulesChecker $rules) use (&$buildRulesCount) {
<del> $buildRulesCount ++;
<add> $buildRulesCount++;
<ide> }
<ide> );
<ide> $eventManager->on(
<ide> 'Model.beforeRules',
<ide> function (EventInterface $event, EntityInterface $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) {
<ide> $this->assertInternalType('string', $operation);
<del> $beforeRulesCount ++;
<add> $beforeRulesCount++;
<ide> }
<ide> );
<ide> $eventManager->on(
<ide> 'Model.afterRules',
<ide> function (EventInterface $event, EntityInterface $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) {
<ide> $this->assertInternalType('bool', $result);
<ide> $this->assertInternalType('string', $operation);
<del> $afterRulesCount ++;
<add> $afterRulesCount++;
<ide> }
<ide> );
<ide> $eventManager->on(
<ide> 'Model.beforeSave',
<ide> function (EventInterface $event, EntityInterface $entity, ArrayObject $options) use (&$beforeSaveCount) {
<del> $beforeSaveCount ++;
<add> $beforeSaveCount++;
<ide> }
<ide> );
<ide> $eventManager->on(
<ide> 'Model.afterSave',
<ide> $afterSaveCallback = function (EventInterface $event, EntityInterface $entity, ArrayObject $options) use (&$afterSaveCount) {
<del> $afterSaveCount ++;
<add> $afterSaveCount++;
<ide> }
<ide> );
<ide> $entity = new Entity(['title' => 'Title']);
<ide> function (EventInterface $event, EntityInterface $entity, ArrayObject $options)
<ide> $eventManager->on(
<ide> 'Model.beforeDelete',
<ide> function (EventInterface $event, EntityInterface $entity, ArrayObject $options) use (&$beforeDeleteCount) {
<del> $beforeDeleteCount ++;
<add> $beforeDeleteCount++;
<ide> }
<ide> );
<ide> $eventManager->on(
<ide> 'Model.afterDelete',
<ide> function (EventInterface $event, EntityInterface $entity, ArrayObject $options) use (&$afterDeleteCount) {
<del> $afterDeleteCount ++;
<add> $afterDeleteCount++;
<ide> }
<ide> );
<ide> $this->assertTrue($table->delete($entity, ['checkRules' => false])); | 1 |
Ruby | Ruby | move parameters to the top on logging | a8e25a518ae8df1682c84affa3b986ca3627da12 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> class Base < Metal
<ide> include ActionController::Compatibility
<ide>
<ide> include ActionController::Cookies
<add> include ActionController::FilterParameterLogging
<ide> include ActionController::Flash
<ide> include ActionController::Verification
<ide> include ActionController::RequestForgeryProtection
<ide> class Base < Metal
<ide> # Add instrumentations hooks at the bottom, to ensure they instrument
<ide> # all the methods properly.
<ide> include ActionController::Instrumentation
<del> include ActionController::FilterParameterLogging
<ide>
<ide> # TODO: Extract into its own module
<ide> # This should be moved together with other normalizing behavior
<ide><path>actionpack/lib/action_controller/metal/filter_parameter_logging.rb
<ide> def filter_parameter_logging(*filter_words, &block)
<ide>
<ide> protected
<ide>
<del> def append_info_to_payload(payload)
<del> super
<del> payload[:params] = filter_parameters(request.params)
<del> end
<del>
<ide> def filter_parameters(params)
<ide> params.dup.except!(*INTERNAL_PARAMS)
<ide> end
<ide><path>actionpack/lib/action_controller/metal/instrumentation.rb
<ide> module ActionController
<ide> module Instrumentation
<ide> extend ActiveSupport::Concern
<ide>
<del> included do
<del> include AbstractController::Logger
<del> end
<add> include AbstractController::Logger
<add> include ActionController::FilterParameterLogging
<ide>
<ide> attr_internal :view_runtime
<ide>
<ide> def process_action(action, *args)
<del> ActiveSupport::Notifications.instrument("action_controller.process_action") do |payload|
<add> raw_payload = {
<add> :controller => self.class.name,
<add> :action => self.action_name,
<add> :params => filter_parameters(params),
<add> :formats => request.formats.map(&:to_sym)
<add> }
<add>
<add> ActiveSupport::Notifications.instrument("action_controller.start_processing", raw_payload.dup)
<add>
<add> ActiveSupport::Notifications.instrument("action_controller.process_action", raw_payload) do |payload|
<ide> result = super
<del> payload[:controller] = self.class.name
<del> payload[:action] = self.action_name
<del> payload[:status] = response.status
<add> payload[:status] = response.status
<ide> append_info_to_payload(payload)
<ide> result
<ide> end
<ide><path>actionpack/lib/action_controller/railties/subscriber.rb
<ide> module ActionController
<ide> module Railties
<ide> class Subscriber < Rails::Subscriber
<del> def process_action(event)
<add> def start_processing(event)
<ide> payload = event.payload
<add> info " Processing by #{payload[:controller]}##{payload[:action]} as #{payload[:formats].first.to_s.upcase}"
<ide> info " Parameters: #{payload[:params].inspect}" unless payload[:params].blank?
<add> end
<ide>
<add> def process_action(event)
<add> payload = event.payload
<ide> additions = ActionController::Base.log_process_action(payload)
<ide>
<ide> message = "Completed in %.0fms" % event.duration
<ide> message << " (#{additions.join(" | ")})" unless additions.blank?
<del> message << " by #{payload[:controller]}##{payload[:action]} [#{payload[:status]}]"
<add> message << " with #{payload[:status]}"
<ide>
<ide> info(message)
<ide> end
<ide><path>actionpack/test/activerecord/controller_runtime_test.rb
<ide> def test_log_with_active_record
<ide> get :show
<ide> wait
<ide>
<del> assert_equal 1, @logger.logged(:info).size
<del> assert_match /\(Views: [\d\.]+ms | ActiveRecord: [\d\.]+ms\)/, @logger.logged(:info)[0]
<add> assert_equal 2, @logger.logged(:info).size
<add> assert_match /\(Views: [\d\.]+ms | ActiveRecord: [\d\.]+ms\)/, @logger.logged(:info)[1]
<ide> end
<ide>
<ide> class SyncSubscriberTest < ActionController::TestCase
<ide><path>actionpack/test/controller/subscriber_test.rb
<ide> def set_logger(logger)
<ide> ActionController::Base.logger = logger
<ide> end
<ide>
<add> def test_start_processing
<add> get :show
<add> wait
<add> assert_equal 2, logs.size
<add> assert_equal "Processing by Another::SubscribersController#show as HTML", logs.first
<add> end
<add>
<ide> def test_process_action
<ide> get :show
<ide> wait
<del> assert_equal 1, logs.size
<del> assert_match /Completed/, logs.first
<del> assert_match /\[200\]/, logs.first
<del> assert_match /Another::SubscribersController#show/, logs.first
<add> assert_equal 2, logs.size
<add> assert_match /Completed/, logs.last
<add> assert_match /with 200/, logs.last
<ide> end
<ide>
<ide> def test_process_action_without_parameters
<ide> def test_process_action_with_parameters
<ide> get :show, :id => '10'
<ide> wait
<ide>
<del> assert_equal 2, logs.size
<del> assert_equal 'Parameters: {"id"=>"10"}', logs[0]
<add> assert_equal 3, logs.size
<add> assert_equal 'Parameters: {"id"=>"10"}', logs[1]
<ide> end
<ide>
<ide> def test_process_action_with_view_runtime
<ide> get :show
<ide> wait
<del> assert_match /\(Views: [\d\.]+ms\)/, logs[0]
<add> assert_match /\(Views: [\d\.]+ms\)/, logs[1]
<ide> end
<ide>
<ide> def test_process_action_with_filter_parameters
<ide> def test_process_action_with_filter_parameters
<ide> get :show, :lifo => 'Pratik', :amount => '420', :step => '1'
<ide> wait
<ide>
<del> params = logs[0]
<add> params = logs[1]
<ide> assert_match /"amount"=>"\[FILTERED\]"/, params
<ide> assert_match /"lifo"=>"\[FILTERED\]"/, params
<ide> assert_match /"step"=>"1"/, params
<ide> def test_redirect_to
<ide> get :redirector
<ide> wait
<ide>
<del> assert_equal 2, logs.size
<del> assert_equal "Redirected to http://foo.bar/", logs[0]
<add> assert_equal 3, logs.size
<add> assert_equal "Redirected to http://foo.bar/", logs[1]
<ide> end
<ide>
<ide> def test_send_data
<ide> get :data_sender
<ide> wait
<ide>
<del> assert_equal 2, logs.size
<del> assert_match /Sent data omg\.txt/, logs[0]
<add> assert_equal 3, logs.size
<add> assert_match /Sent data omg\.txt/, logs[1]
<ide> end
<ide>
<ide> def test_send_file
<ide> get :file_sender
<ide> wait
<ide>
<del> assert_equal 2, logs.size
<del> assert_match /Sent file/, logs[0]
<del> assert_match /test\/fixtures\/company\.rb/, logs[0]
<add> assert_equal 3, logs.size
<add> assert_match /Sent file/, logs[1]
<add> assert_match /test\/fixtures\/company\.rb/, logs[1]
<ide> end
<ide>
<ide> def test_send_xfile
<ide> get :xfile_sender
<ide> wait
<ide>
<del> assert_equal 2, logs.size
<del> assert_match /Sent X\-Sendfile header/, logs[0]
<del> assert_match /test\/fixtures\/company\.rb/, logs[0]
<add> assert_equal 3, logs.size
<add> assert_match /Sent X\-Sendfile header/, logs[1]
<add> assert_match /test\/fixtures\/company\.rb/, logs[1]
<ide> end
<ide>
<ide> def test_with_fragment_cache
<ide> ActionController::Base.perform_caching = true
<ide> get :with_fragment_cache
<ide> wait
<ide>
<del> assert_equal 3, logs.size
<del> assert_match /Exist fragment\? views\/foo/, logs[0]
<del> assert_match /Write fragment views\/foo/, logs[1]
<add> assert_equal 4, logs.size
<add> assert_match /Exist fragment\? views\/foo/, logs[1]
<add> assert_match /Write fragment views\/foo/, logs[2]
<ide> ensure
<ide> ActionController::Base.perform_caching = true
<ide> end
<ide> def test_with_page_cache
<ide> get :with_page_cache
<ide> wait
<ide>
<del> assert_equal 2, logs.size
<del> assert_match /Write page/, logs[0]
<del> assert_match /\/index\.html/, logs[0]
<add> assert_equal 3, logs.size
<add> assert_match /Write page/, logs[1]
<add> assert_match /\/index\.html/, logs[1]
<ide> ensure
<ide> ActionController::Base.perform_caching = true
<ide> end | 6 |
Text | Text | fix the <details> in train.md. fix bert repo link | e12386ba46bf02a6668320c7f68dc136cbf9ee8c | <ide><path>official/nlp/docs/train.md
<ide> export PYTHONPATH=$PYTHONPATH:/path/to/models
<ide> pip3 install --user -r official/requirements.txt
<ide> ```
<ide>
<add>### Fine-tuning SQuAD with a pre-trained BERT checkpoint
<add>
<add>This example fine-tunes a pre-trained BERT checkpoint on the
<add>Stanford Question Answering Dataset (SQuAD) using TPUs.
<add>The [SQuAD website](https://rajpurkar.github.io/SQuAD-explorer/) contains
<add>detailed information about the SQuAD datasets and evaluation. After downloading
<add>the SQuAD datasets and the [pre-trained BERT checkpoints](https://github.com/tensorflow/models/blob/master/official/nlp/docs/pretrained_models.md),
<add>you can run the following command to prepare the `tf_record` files:
<add>
<add>```shell
<add>export SQUAD_DIR=~/squad
<add>export BERT_DIR=~/uncased_L-12_H-768_A-12
<add>export OUTPUT_DATA_DIR=gs://some_bucket/datasets
<add>
<add>python3 create_finetuning_data.py \
<add> --squad_data_file=${SQUAD_DIR}/train-v1.1.json \
<add> --vocab_file=${BERT_DIR}/vocab.txt \
<add> --train_data_output_path=${OUTPUT_DATA_DIR}/train.tf_record \
<add> --meta_data_file_path=${OUTPUT_DATA_DIR}/squad_meta_data \
<add> --fine_tuning_task_type=squad --max_seq_length=384
<add>```
<add>
<add>Note: To create fine-tuning data with SQuAD 2.0, you need to add flag `--version_2_with_negative=True`.
<add>
<add>Then, you can start the training and evaluation jobs:
<add>
<add>```shell
<add>export SQUAD_DIR=~/squad
<add>export INPUT_DATA_DIR=gs://some_bucket/datasets
<add>export OUTPUT_DIR=gs://some_bucket/my_output_dir
<add>
<add># See the following link for more pre-trained checkpoints:
<add># https://github.com/tensorflow/models/blob/master/official/nlp/docs/pretrained_models.md
<add>export BERT_DIR=~/uncased_L-12_H-768_A-12
<add>
<add># Override the configurations by FLAGS. Alternatively, you can directly edit
<add># `configs/experiments/squad_v1.1.yaml` to specify corresponding fields.
<add># Also note that the training data is the pre-processed tf_record file, while
<add># the validation file is the raw json file.
<add>export PARAMS=task.train_data.input_path=$INPUT_DATA_DIR/train.tf_record
<add>export PARAMS=$PARAMS,task.validation_data.input_path=$SQUAD_DIR/dev-v1.1.json
<add>export PARAMS=$PARAMS,task.validation_data.vocab_file=$BERT_DIR/vocab.txt
<add>export PARAMS=$PARAMS,task.init_checkpoint=$BERT_DIR/bert_model.ckpt
<add>export PARAMS=$PARAMS,runtime.distribution_strategy=tpu
<add>
<add>python3 train.py \
<add> --experiment=bert/squad \
<add> --mode=train_and_eval \
<add> --model_dir=$OUTPUT_DIR \
<add> --config_file=configs/models/bert_en_uncased_base.yaml \
<add> --config_file=configs/experiments/squad_v1.1.yaml \
<add> --tpu=${TPU_NAME} \
<add> --params_override=$PARAMS
<add>
<add>```
<add>
<ide> ### Fine-tuning Sentence Classification with BERT from TF-Hub
<ide>
<ide> <details>
<ide> models in `$OUTPUT_DIR`.
<ide>
<ide> </details>
<ide>
<del>### Fine-tuning SQuAD with a pre-trained BERT checkpoint
<del>
<del><details>
<del>
<del>This example fine-tunes a pre-trained BERT checkpoint on the
<del>Stanford Question Answering Dataset (SQuAD) using TPUs.
<del>The [SQuAD website](https://rajpurkar.github.io/SQuAD-explorer/) contains
<del>detailed information about the SQuAD datasets and evaluation. After downloading
<del>the SQuAD datasets and the [pre-trained BERT checkpoints](https://github.com/tensorflow/models/blob/master/official/nlp/docs/pretrained_models.md),
<del>you can run the following command to prepare the `tf_record` files:
<del>
<del>```shell
<del>export SQUAD_DIR=~/squad
<del>export BERT_DIR=~/uncased_L-12_H-768_A-12
<del>export OUTPUT_DATA_DIR=gs://some_bucket/datasets
<del>
<del>python3 create_finetuning_data.py \
<del> --squad_data_file=${SQUAD_DIR}/train-v1.1.json \
<del> --vocab_file=${BERT_DIR}/vocab.txt \
<del> --train_data_output_path=${OUTPUT_DATA_DIR}/train.tf_record \
<del> --meta_data_file_path=${OUTPUT_DATA_DIR}/squad_meta_data \
<del> --fine_tuning_task_type=squad --max_seq_length=384
<del>```
<del>
<del>Note: To create fine-tuning data with SQuAD 2.0, you need to add flag `--version_2_with_negative=True`.
<del>
<del>Then, you can start the training and evaluation jobs:
<del>
<del>```shell
<del>export SQUAD_DIR=~/squad
<del>export INPUT_DATA_DIR=gs://some_bucket/datasets
<del>export OUTPUT_DIR=gs://some_bucket/my_output_dir
<del>
<del># See the following link for more pre-trained checkpoints:
<del># https://github.com/tensorflow/models/blob/master/official/nlp/docs/pretrained_models.md
<del>export BERT_DIR=~/uncased_L-12_H-768_A-12
<del>
<del># Override the configurations by FLAGS. Alternatively, you can directly edit
<del># `configs/experiments/squad_v1.1.yaml` to specify corresponding fields.
<del># Also note that the training data is the pre-processed tf_record file, while
<del># the validation file is the raw json file.
<del>export PARAMS=task.train_data.input_path=$INPUT_DATA_DIR/train.tf_record
<del>export PARAMS=$PARAMS,task.validation_data.input_path=$SQUAD_DIR/dev-v1.1.json
<del>export PARAMS=$PARAMS,task.validation_data.vocab_file=$BERT_DIR/vocab.txt
<del>export PARAMS=$PARAMS,task.init_checkpoint=$BERT_DIR/bert_model.ckpt
<del>export PARAMS=$PARAMS,runtime.distribution_strategy=tpu
<del>
<del>python3 train.py \
<del> --experiment=bert/squad \
<del> --mode=train_and_eval \
<del> --model_dir=$OUTPUT_DIR \
<del> --config_file=configs/models/bert_en_uncased_base.yaml \
<del> --config_file=configs/experiments/squad_v1.1.yaml \
<del> --tpu=${TPU_NAME} \
<del> --params_override=$PARAMS
<del>
<del>```
<del>
<ide> ### Pre-train a BERT from scratch
<ide>
<del></details>
<del>
<ide> This example pre-trains a BERT model with Wikipedia and Books datasets used by
<ide> the original BERT paper.
<del>The [BERT repo](https://github.com/tensorflow/models/blob/master/official/nlp/data/create_pretraining_data.py)
<add>The [BERT repo](https://github.com/google-research/bert)
<ide> contains detailed information about the Wikipedia dump and
<ide> [BookCorpus](https://yknzhu.wixsite.com/mbweb). Of course, the pre-training
<ide> recipe is generic and you can apply the same recipe to your own corpus.
<ide>
<add><details>
<add>
<ide> Please use the script
<ide> [`create_pretraining_data.py`](https://github.com/tensorflow/models/blob/master/official/nlp/data/create_pretraining_data.py)
<ide> which is essentially branched from [BERT research repo](https://github.com/google-research/bert)
<ide> python models/official/nlp/data/create_pretraining_data.py \
<ide>
<ide> Then, you can update the yaml configuration file, e.g.
<ide> `configs/experiments/wiki_books_pretrain.yaml` to specify your data paths and
<del>update masking-related hyper parameters to match with your specification for
<add>update masking-related hyper parameters to match with your specification for
<ide> the pretraining data. When your data have multiple shards, you can
<ide> use `*` to include multiple files.
<ide>
<ide> model:
<ide>
<ide> to match the hidden dimensions.
<ide>
<add></details>
<add>
<ide> Then, you can start the training and evaluation jobs, which runs the
<ide> [`bert/pretraining`](https://github.com/tensorflow/models/blob/master/official/nlp/configs/pretraining_experiments.py#L51)
<ide> experiment: | 1 |
Python | Python | ignore colon with slash when split app_import_path | c38499bbf26cfa9683e30c52139a94dc5a50dcc4 | <ide><path>flask/cli.py
<ide> def load_app(self):
<ide> app = call_factory(self, self.create_app)
<ide> else:
<ide> if self.app_import_path:
<del> path, name = (self.app_import_path.split(':', 1) + [None])[:2]
<add> path, name = (re.split(r':(?![\\/])', self.app_import_path, 1) + [None])[:2]
<ide> import_name = prepare_import(path)
<ide> app = locate_app(self, import_name, name)
<ide> else:
<ide><path>tests/test_cli.py
<ide> def exit(self): return
<ide> def test_scriptinfo(test_apps, monkeypatch):
<ide> """Test of ScriptInfo."""
<ide> obj = ScriptInfo(app_import_path="cliapp.app:testapp")
<del> assert obj.load_app().name == "testapp"
<del> assert obj.load_app().name == "testapp"
<add> app = obj.load_app()
<add> assert app.name == "testapp"
<add> assert obj.load_app() is app
<add>
<add> # import app with module's absolute path
<add> cli_app_path = os.path.abspath(os.path.join(
<add> os.path.dirname(__file__), 'test_apps', 'cliapp', 'app.py'))
<add> obj = ScriptInfo(app_import_path=cli_app_path)
<add> app = obj.load_app()
<add> assert app.name == 'testapp'
<add> assert obj.load_app() is app
<add> obj = ScriptInfo(app_import_path=cli_app_path + ':testapp')
<add> app = obj.load_app()
<add> assert app.name == 'testapp'
<add> assert obj.load_app() is app
<ide>
<ide> def create_app(info):
<ide> return Flask("createapp")
<ide>
<ide> obj = ScriptInfo(create_app=create_app)
<ide> app = obj.load_app()
<ide> assert app.name == "createapp"
<del> assert obj.load_app() == app
<add> assert obj.load_app() is app
<ide>
<ide> obj = ScriptInfo()
<ide> pytest.raises(NoAppException, obj.load_app) | 2 |
PHP | PHP | remove unused private method | 7ae798c938b0a530af82b5bdb607230d3da4f7ca | <ide><path>src/Illuminate/Redis/Connections/PhpRedisConnection.php
<ide> public function disconnect()
<ide> $this->client->close();
<ide> }
<ide>
<del> /**
<del> * Apply a prefix to the given key if necessary.
<del> *
<del> * @param string $key
<del> * @return string
<del> */
<del> private function applyPrefix($key)
<del> {
<del> $prefix = (string) $this->client->getOption(Redis::OPT_PREFIX);
<del>
<del> return $prefix.$key;
<del> }
<del>
<ide> /**
<ide> * Pass other method calls down to the underlying client.
<ide> * | 1 |
Javascript | Javascript | fix sea3d blending material | 602f38034351fef9de6159ecce5005129b25a129 | <ide><path>examples/js/loaders/sea3d/SEA3DLoader.js
<ide> THREE.SEA3D.prototype.readContainer3D = function( sea ) {
<ide>
<ide> THREE.SEA3D.prototype.readSprite = function( sea ) {
<ide>
<del> var material;
<add> var mat;
<ide>
<ide> if ( sea.material ) {
<ide>
<ide> if ( ! sea.material.tag.sprite ) {
<ide>
<del> material = sea.material.tag.sprite = new THREE.SpriteMaterial();
<add> mat = sea.material.tag.sprite = new THREE.SpriteMaterial();
<ide>
<del> this.setBlending( material, sea.blendMode );
<add> this.setBlending( mat, sea.blendMode );
<ide>
<del> material.map = sea.material.tag.map;
<del> material.map.flipY = true;
<add> mat.map = sea.material.tag.map;
<add> mat.map.flipY = true;
<ide>
<del> material.color.set( sea.material.tag.color );
<del> material.opacity = sea.material.tag.opacity;
<del> material.blending = sea.material.tag.blending;
<del> material.fog = sea.material.receiveFog;
<add> mat.color.set( sea.material.tag.color );
<add> mat.opacity = sea.material.tag.opacity;
<add> mat.blending = sea.material.tag.blending;
<add> mat.fog = sea.material.receiveFog;
<ide>
<ide> }
<del> else material = sea.material.tag.sprite;
<add> else mat = sea.material.tag.sprite;
<ide>
<ide> }
<ide>
<del> var sprite = new THREE.Sprite( material );
<add> var sprite = new THREE.Sprite( mat );
<ide> sprite.name = sea.name;
<ide>
<ide> this.domain.sprites = this.sprites = this.sprites || [];
<ide> THREE.SEA3D.prototype.createMaterial = function( sea ) {
<ide>
<ide> };
<ide>
<del>THREE.SEA3D.prototype.setBlending = function( material, blendMode ) {
<add>THREE.SEA3D.prototype.setBlending = function( mat, blendMode ) {
<ide>
<ide> if ( blendMode == "normal" ) return;
<ide> | 1 |
PHP | PHP | fix nested errors generation for missing layout | 03700d873b81cfe6dd2a7f7f40fd5e2dcad720f6 | <ide><path>src/Error/ExceptionRenderer.php
<ide> use Cake\Http\ServerRequestFactory;
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Inflector;
<add>use Cake\View\Exception\MissingLayoutException;
<ide> use Cake\View\Exception\MissingTemplateException;
<ide> use Exception;
<ide> use PDOException;
<ide> protected function _outputMessage(string $template)
<ide> return $this->_shutdown();
<ide> } catch (MissingTemplateException $e) {
<ide> $attributes = $e->getAttributes();
<del> if (isset($attributes['file']) && strpos($attributes['file'], 'error500') !== false) {
<add> if (
<add> $e instanceof MissingLayoutException ||
<add> (isset($attributes['file']) && strpos($attributes['file'], 'error500') !== false)
<add> ) {
<ide> return $this->_outputMessageSafe('error500');
<ide> }
<ide>
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> function (EventInterface $event) {
<ide> $this->assertEquals('Error', $controller->viewBuilder()->getTemplatePath());
<ide> }
<ide>
<add> /**
<add> * Test that missing layout don't cause other fatal errors.
<add> *
<add> * @return void
<add> */
<add> public function testMissingLayoutRenderSafe()
<add> {
<add> $this->called = false;
<add> $exception = new NotFoundException();
<add> $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
<add>
<add> $controller = new Controller();
<add> $controller->getEventManager()->on(
<add> 'Controller.beforeRender',
<add> function (EventInterface $event) {
<add> $this->called = true;
<add> $event->getSubject()->viewBuilder()->setTemplatePath('Error');
<add> $event->getSubject()->viewBuilder()->setLayout('does-not-exist');
<add> }
<add> );
<add> $controller->setRequest(new ServerRequest());
<add> $ExceptionRenderer->setController($controller);
<add>
<add> $response = $ExceptionRenderer->render();
<add> $this->assertEquals('text/html', $response->getType());
<add> $this->assertContains('Not Found', (string)$response->getBody());
<add> $this->assertTrue($this->called, 'Listener added was not triggered.');
<add> $this->assertEquals('', $controller->viewBuilder()->getLayoutPath());
<add> $this->assertEquals('Error', $controller->viewBuilder()->getTemplatePath());
<add> }
<add>
<ide> /**
<ide> * Test that missing plugin disables Controller::$plugin if the two are the same plugin.
<ide> * | 2 |
Text | Text | remove redundant section from dev/readme.md toc | 0d76b59c686c6db821d47826e32baba3bbf09f40 | <ide><path>dev/README.md
<ide> **Table of contents**
<ide>
<ide> - [Development Tools](#development-tools)
<del> - [Airflow Pull Request Tool](#airflow-pull-request-tool)
<ide> - [Airflow release signing tool](#airflow-release-signing-tool)
<ide> - [Verifying the release candidate by PMCs (legal)](#verifying-the-release-candidate-by-pmcs-legal)
<ide> - [PMC voting](#pmc-voting) | 1 |
PHP | PHP | add dontseejson() to crawlertrait | 812bbd7525166b2fecbb10f66b7eaaae7e4ea378 | <ide><path>src/Illuminate/Foundation/Testing/CrawlerTrait.php
<ide> public function seeJsonEquals(array $data)
<ide> * Assert that the response contains JSON.
<ide> *
<ide> * @param array|null $data
<add> * @param bool $negate
<ide> * @return $this
<ide> */
<del> public function seeJson(array $data = null)
<add> public function seeJson(array $data = null, $negate = false)
<ide> {
<ide> if (is_null($data)) {
<ide> $this->assertJson(
<ide> public function seeJson(array $data = null)
<ide> return $this;
<ide> }
<ide>
<del> return $this->seeJsonContains($data);
<add> return $this->seeJsonContains($data, $negate);
<add> }
<add>
<add> /**
<add> * Assert that the response doesn't contain JSON.
<add> *
<add> * @param array|null $data
<add> * @return $this
<add> */
<add> public function dontSeeJson(array $data = null)
<add> {
<add> return $this->seeJson($data, true);
<ide> }
<ide>
<ide> /**
<ide> * Assert that the response contains the given JSON.
<ide> *
<ide> * @param array $data
<add> * @param bool $negate
<ide> * @return $this
<ide> */
<del> protected function seeJsonContains(array $data)
<add> protected function seeJsonContains(array $data, $negate = false)
<ide> {
<add> $method = $negate ? 'assertFalse' : 'assertTrue';
<add>
<ide> $actual = json_encode(array_sort_recursive(
<ide> json_decode($this->response->getContent(), true)
<ide> ));
<ide>
<ide> foreach (array_sort_recursive($data) as $key => $value) {
<ide> $expected = $this->formatToExpectedJson($key, $value);
<ide>
<del> $this->assertTrue(
<add> $this->{$method}(
<ide> Str::contains($actual, $expected),
<del> "Unable to find JSON fragment [{$expected}] within [{$actual}]."
<add> ($negate ? 'Found' : 'Unable to find')." JSON fragment [{$expected}] within [{$actual}]."
<ide> );
<ide> }
<ide> | 1 |
Javascript | Javascript | use a default offset | d5495e859c3aceab7f8a823e27950e715b746a35 | <ide><path>lib/internal/buffer.js
<ide> const float64Array = new Float64Array(1);
<ide> const uInt8Float64Array = new Uint8Array(float64Array.buffer);
<ide>
<ide> // Check endianness.
<del>float32Array[0] = -1;
<add>float32Array[0] = -1; // 0xBF800000
<add>// Either it is [0, 0, 128, 191] or [191, 128, 0, 0]. It is not possible to
<add>// check this with `os.endianness()` because that is determined at compile time.
<ide> const bigEndian = uInt8Float32Array[3] === 0;
<ide>
<ide> function checkBounds(buf, offset, byteLength) {
<ide> function readUIntLE(offset, byteLength) {
<ide> return this.readUInt32LE(offset);
<ide> if (byteLength === 2)
<ide> return this.readUInt16LE(offset);
<del> if (byteLength === 1)
<add> if (byteLength === 1 || byteLength === undefined)
<ide> return this.readUInt8(offset);
<ide>
<ide> boundsError(byteLength, 6, 'byteLength');
<ide> }
<ide>
<del>function readUInt48LE(buf, offset) {
<add>function readUInt48LE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 5];
<ide> function readUInt48LE(buf, offset) {
<ide> (buf[++offset] + last * 2 ** 8) * 2 ** 32;
<ide> }
<ide>
<del>function readUInt40LE(buf, offset) {
<add>function readUInt40LE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 4];
<ide> function readUInt40LE(buf, offset) {
<ide> last * 2 ** 32;
<ide> }
<ide>
<del>function readUInt32LE(offset) {
<add>function readUInt32LE(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 3];
<ide> function readUInt32LE(offset) {
<ide> last * 2 ** 24;
<ide> }
<ide>
<del>function readUInt24LE(buf, offset) {
<add>function readUInt24LE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 2];
<ide> function readUInt24LE(buf, offset) {
<ide> return first + buf[++offset] * 2 ** 8 + last * 2 ** 16;
<ide> }
<ide>
<del>function readUInt16LE(offset) {
<add>function readUInt16LE(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 1];
<ide> function readUInt16LE(offset) {
<ide> return first + last * 2 ** 8;
<ide> }
<ide>
<del>function readUInt8(offset) {
<add>function readUInt8(offset = 0) {
<ide> checkNumberType(offset);
<ide> const val = this[offset];
<ide> if (val === undefined)
<ide> function readUIntBE(offset, byteLength) {
<ide> return this.readUInt32BE(offset);
<ide> if (byteLength === 2)
<ide> return this.readUInt16BE(offset);
<del> if (byteLength === 1)
<add> if (byteLength === 1 || byteLength === undefined)
<ide> return this.readUInt8(offset);
<ide>
<ide> boundsError(byteLength, 6, 'byteLength');
<ide> }
<ide>
<del>function readUInt48BE(buf, offset) {
<add>function readUInt48BE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 5];
<ide> function readUInt48BE(buf, offset) {
<ide> last;
<ide> }
<ide>
<del>function readUInt40BE(buf, offset) {
<add>function readUInt40BE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 4];
<ide> function readUInt40BE(buf, offset) {
<ide> last;
<ide> }
<ide>
<del>function readUInt32BE(offset) {
<add>function readUInt32BE(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 3];
<ide> function readUInt32BE(offset) {
<ide> last;
<ide> }
<ide>
<del>function readUInt24BE(buf, offset) {
<add>function readUInt24BE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 2];
<ide> function readUInt24BE(buf, offset) {
<ide> return first * 2 ** 16 + buf[++offset] * 2 ** 8 + last;
<ide> }
<ide>
<del>function readUInt16BE(offset) {
<add>function readUInt16BE(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 1];
<ide> function readIntLE(offset, byteLength) {
<ide> return this.readInt32LE(offset);
<ide> if (byteLength === 2)
<ide> return this.readInt16LE(offset);
<del> if (byteLength === 1)
<add> if (byteLength === 1 || byteLength === undefined)
<ide> return this.readInt8(offset);
<ide>
<ide> boundsError(byteLength, 6, 'byteLength');
<ide> }
<ide>
<del>function readInt48LE(buf, offset) {
<add>function readInt48LE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 5];
<ide> function readInt48LE(buf, offset) {
<ide> buf[++offset] * 2 ** 24;
<ide> }
<ide>
<del>function readInt40LE(buf, offset) {
<add>function readInt40LE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 4];
<ide> function readInt40LE(buf, offset) {
<ide> buf[++offset] * 2 ** 24;
<ide> }
<ide>
<del>function readInt32LE(offset) {
<add>function readInt32LE(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 3];
<ide> function readInt32LE(offset) {
<ide> (last << 24); // Overflow
<ide> }
<ide>
<del>function readInt24LE(buf, offset) {
<add>function readInt24LE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 2];
<ide> function readInt24LE(buf, offset) {
<ide> return val | (val & 2 ** 23) * 0x1fe;
<ide> }
<ide>
<del>function readInt16LE(offset) {
<add>function readInt16LE(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 1];
<ide> function readInt16LE(offset) {
<ide> return val | (val & 2 ** 15) * 0x1fffe;
<ide> }
<ide>
<del>function readInt8(offset) {
<add>function readInt8(offset = 0) {
<ide> checkNumberType(offset);
<ide> const val = this[offset];
<ide> if (val === undefined)
<ide> function readIntBE(offset, byteLength) {
<ide> return this.readInt32BE(offset);
<ide> if (byteLength === 2)
<ide> return this.readInt16BE(offset);
<del> if (byteLength === 1)
<add> if (byteLength === 1 || byteLength === undefined)
<ide> return this.readInt8(offset);
<ide>
<ide> boundsError(byteLength, 6, 'byteLength');
<ide> }
<ide>
<del>function readInt48BE(buf, offset) {
<add>function readInt48BE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 5];
<ide> function readInt48BE(buf, offset) {
<ide> last;
<ide> }
<ide>
<del>function readInt40BE(buf, offset) {
<add>function readInt40BE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 4];
<ide> function readInt40BE(buf, offset) {
<ide> last;
<ide> }
<ide>
<del>function readInt32BE(offset) {
<add>function readInt32BE(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 3];
<ide> function readInt32BE(offset) {
<ide> last;
<ide> }
<ide>
<del>function readInt24BE(buf, offset) {
<add>function readInt24BE(buf, offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = buf[offset];
<ide> const last = buf[offset + 2];
<ide> function readInt24BE(buf, offset) {
<ide> return val | (val & 2 ** 23) * 0x1fe;
<ide> }
<ide>
<del>function readInt16BE(offset) {
<add>function readInt16BE(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 1];
<ide> function readInt16BE(offset) {
<ide> }
<ide>
<ide> // Read floats
<del>function readFloatBackwards(offset) {
<add>function readFloatBackwards(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 3];
<ide> function readFloatBackwards(offset) {
<ide> return float32Array[0];
<ide> }
<ide>
<del>function readFloatForwards(offset) {
<add>function readFloatForwards(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 3];
<ide> function readFloatForwards(offset) {
<ide> return float32Array[0];
<ide> }
<ide>
<del>function readDoubleBackwards(offset) {
<add>function readDoubleBackwards(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 7];
<ide> function readDoubleBackwards(offset) {
<ide> return float64Array[0];
<ide> }
<ide>
<del>function readDoubleForwards(offset) {
<add>function readDoubleForwards(offset = 0) {
<ide> checkNumberType(offset);
<ide> const first = this[offset];
<ide> const last = this[offset + 7];
<ide> function readDoubleForwards(offset) {
<ide> }
<ide>
<ide> // Write integers.
<del>function writeUIntLE(value, offset, byteLength) {
<add>function writeUIntLE(value, offset = 0, byteLength) {
<ide> if (byteLength === 6)
<ide> return writeU_Int48LE(this, value, offset, 0, 0xffffffffffff);
<ide> if (byteLength === 5)
<ide> function writeUIntLE(value, offset, byteLength) {
<ide> return writeU_Int32LE(this, value, offset, 0, 0xffffffff);
<ide> if (byteLength === 2)
<ide> return writeU_Int16LE(this, value, offset, 0, 0xffff);
<del> if (byteLength === 1)
<add> if (byteLength === 1 || byteLength === undefined)
<ide> return writeU_Int8(this, value, offset, 0, 0xff);
<ide>
<ide> boundsError(byteLength, 6, 'byteLength');
<ide> function writeU_Int32LE(buf, value, offset, min, max) {
<ide> return offset;
<ide> }
<ide>
<del>function writeUInt32LE(value, offset) {
<add>function writeUInt32LE(value, offset = 0) {
<ide> return writeU_Int32LE(this, value, offset, 0, 0xffffffff);
<ide> }
<ide>
<ide> function writeU_Int16LE(buf, value, offset, min, max) {
<ide> return offset;
<ide> }
<ide>
<del>function writeUInt16LE(value, offset) {
<add>function writeUInt16LE(value, offset = 0) {
<ide> return writeU_Int16LE(this, value, offset, 0, 0xffff);
<ide> }
<ide>
<ide> function writeU_Int8(buf, value, offset, min, max) {
<ide> return offset + 1;
<ide> }
<ide>
<del>function writeUInt8(value, offset) {
<add>function writeUInt8(value, offset = 0) {
<ide> return writeU_Int8(this, value, offset, 0, 0xff);
<ide> }
<ide>
<del>function writeUIntBE(value, offset, byteLength) {
<add>function writeUIntBE(value, offset = 0, byteLength) {
<ide> if (byteLength === 6)
<ide> return writeU_Int48BE(this, value, offset, 0, 0xffffffffffffff);
<ide> if (byteLength === 5)
<ide> function writeUIntBE(value, offset, byteLength) {
<ide> return writeU_Int32BE(this, value, offset, 0, 0xffffffff);
<ide> if (byteLength === 2)
<ide> return writeU_Int16BE(this, value, offset, 0, 0xffff);
<del> if (byteLength === 1)
<add> if (byteLength === 1 || byteLength === undefined)
<ide> return writeU_Int8(this, value, offset, 0, 0xff);
<ide>
<ide> boundsError(byteLength, 6, 'byteLength');
<ide> function writeU_Int32BE(buf, value, offset, min, max) {
<ide> return offset + 4;
<ide> }
<ide>
<del>function writeUInt32BE(value, offset) {
<add>function writeUInt32BE(value, offset = 0) {
<ide> return writeU_Int32BE(this, value, offset, 0, 0xffffffff);
<ide> }
<ide>
<ide> function writeU_Int16BE(buf, value, offset, min, max) {
<ide> return offset;
<ide> }
<ide>
<del>function writeUInt16BE(value, offset) {
<add>function writeUInt16BE(value, offset = 0) {
<ide> return writeU_Int16BE(this, value, offset, 0, 0xffffffff);
<ide> }
<ide>
<del>function writeIntLE(value, offset, byteLength) {
<add>function writeIntLE(value, offset = 0, byteLength) {
<ide> if (byteLength === 6)
<ide> return writeU_Int48LE(this, value, offset, -0x800000000000, 0x7fffffffffff);
<ide> if (byteLength === 5)
<ide> function writeIntLE(value, offset, byteLength) {
<ide> return writeU_Int32LE(this, value, offset, -0x80000000, 0x7fffffff);
<ide> if (byteLength === 2)
<ide> return writeU_Int16LE(this, value, offset, -0x8000, 0x7fff);
<del> if (byteLength === 1)
<add> if (byteLength === 1 || byteLength === undefined)
<ide> return writeU_Int8(this, value, offset, -0x80, 0x7f);
<ide>
<ide> boundsError(byteLength, 6, 'byteLength');
<ide> }
<ide>
<del>function writeInt32LE(value, offset) {
<add>function writeInt32LE(value, offset = 0) {
<ide> return writeU_Int32LE(this, value, offset, -0x80000000, 0x7fffffff);
<ide> }
<ide>
<del>function writeInt16LE(value, offset) {
<add>function writeInt16LE(value, offset = 0) {
<ide> return writeU_Int16LE(this, value, offset, -0x8000, 0x7fff);
<ide> }
<ide>
<del>function writeInt8(value, offset) {
<add>function writeInt8(value, offset = 0) {
<ide> return writeU_Int8(this, value, offset, -0x80, 0x7f);
<ide> }
<ide>
<del>function writeIntBE(value, offset, byteLength) {
<add>function writeIntBE(value, offset = 0, byteLength) {
<ide> if (byteLength === 6)
<ide> return writeU_Int48BE(this, value, offset, -0x800000000000, 0x7fffffffffff);
<ide> if (byteLength === 5)
<ide> function writeIntBE(value, offset, byteLength) {
<ide> return writeU_Int32BE(this, value, offset, -0x80000000, 0x7fffffff);
<ide> if (byteLength === 2)
<ide> return writeU_Int16BE(this, value, offset, -0x8000, 0x7fff);
<del> if (byteLength === 1)
<add> if (byteLength === 1 || byteLength === undefined)
<ide> return writeU_Int8(this, value, offset, -0x80, 0x7f);
<ide>
<ide> boundsError(byteLength, 6, 'byteLength');
<ide> }
<ide>
<del>function writeInt32BE(value, offset) {
<add>function writeInt32BE(value, offset = 0) {
<ide> return writeU_Int32BE(this, value, offset, -0x80000000, 0x7fffffff);
<ide> }
<ide>
<del>function writeInt16BE(value, offset) {
<add>function writeInt16BE(value, offset = 0) {
<ide> return writeU_Int16BE(this, value, offset, -0x8000, 0x7fff);
<ide> }
<ide>
<ide> // Write floats.
<del>function writeDoubleForwards(val, offset) {
<add>function writeDoubleForwards(val, offset = 0) {
<ide> val = +val;
<ide> checkBounds(this, offset, 7);
<ide>
<ide> function writeDoubleForwards(val, offset) {
<ide> return offset;
<ide> }
<ide>
<del>function writeDoubleBackwards(val, offset) {
<add>function writeDoubleBackwards(val, offset = 0) {
<ide> val = +val;
<ide> checkBounds(this, offset, 7);
<ide>
<ide> function writeDoubleBackwards(val, offset) {
<ide> return offset;
<ide> }
<ide>
<del>function writeFloatForwards(val, offset) {
<add>function writeFloatForwards(val, offset = 0) {
<ide> val = +val;
<ide> checkBounds(this, offset, 3);
<ide>
<ide> function writeFloatForwards(val, offset) {
<ide> return offset;
<ide> }
<ide>
<del>function writeFloatBackwards(val, offset) {
<add>function writeFloatBackwards(val, offset = 0) {
<ide> val = +val;
<ide> checkBounds(this, offset, 3);
<ide>
<ide><path>test/parallel/test-buffer-readdouble.js
<ide> assert.strictEqual(buffer.readDoubleBE(0), 3.04814e-319);
<ide> assert.strictEqual(buffer.readDoubleLE(0), -Infinity);
<ide>
<ide> ['readDoubleLE', 'readDoubleBE'].forEach((fn) => {
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((off) => {
<add>
<add> // Verify that default offset works fine.
<add> buffer[fn](undefined);
<add> buffer[fn]();
<add>
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((off) => {
<ide> assert.throws(
<ide> () => buffer[fn](off),
<ide> { code: 'ERR_INVALID_ARG_TYPE' }
<ide><path>test/parallel/test-buffer-readfloat.js
<ide> assert.strictEqual(buffer.readFloatBE(0), 4.627507918739843e-41);
<ide> assert.strictEqual(buffer.readFloatLE(0), -Infinity);
<ide>
<ide> ['readFloatLE', 'readFloatBE'].forEach((fn) => {
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((off) => {
<add>
<add> // Verify that default offset works fine.
<add> buffer[fn](undefined);
<add> buffer[fn]();
<add>
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((off) => {
<ide> assert.throws(
<ide> () => buffer[fn](off),
<ide> { code: 'ERR_INVALID_ARG_TYPE' }
<ide><path>test/parallel/test-buffer-readint.js
<ide> const assert = require('assert');
<ide> const buffer = Buffer.alloc(4);
<ide>
<ide> ['Int8', 'Int16BE', 'Int16LE', 'Int32BE', 'Int32LE'].forEach((fn) => {
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((o) => {
<add>
<add> // Verify that default offset works fine.
<add> buffer[`read${fn}`](undefined);
<add> buffer[`read${fn}`]();
<add>
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((o) => {
<ide> assert.throws(
<ide> () => buffer[`read${fn}`](o),
<ide> {
<ide> const assert = require('assert');
<ide>
<ide> // Check byteLength.
<ide> ['readIntBE', 'readIntLE'].forEach((fn) => {
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((len) => {
<add>
<add> // Verify that default offset & byteLength works fine.
<add> buffer[fn](undefined, undefined);
<add> buffer[fn](undefined);
<add> buffer[fn]();
<add>
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((len) => {
<ide> assert.throws(
<ide> () => buffer[fn](0, len),
<ide> { code: 'ERR_INVALID_ARG_TYPE' });
<ide> const assert = require('assert');
<ide> // Test 1 to 6 bytes.
<ide> for (let i = 1; i < 6; i++) {
<ide> ['readIntBE', 'readIntLE'].forEach((fn) => {
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((o) => {
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((o) => {
<ide> assert.throws(
<ide> () => buffer[fn](o, i),
<ide> {
<ide><path>test/parallel/test-buffer-writedouble.js
<ide> assert.ok(Number.isNaN(buffer.readDoubleLE(8)));
<ide> const small = Buffer.allocUnsafe(1);
<ide>
<ide> ['writeDoubleLE', 'writeDoubleBE'].forEach((fn) => {
<add>
<add> // Verify that default offset works fine.
<add> buffer[fn](23, undefined);
<add> buffer[fn](23);
<add>
<ide> assert.throws(
<ide> () => small[fn](11.11, 0),
<ide> {
<ide> assert.ok(Number.isNaN(buffer.readDoubleLE(8)));
<ide> message: 'Attempt to write outside buffer bounds'
<ide> });
<ide>
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((off) => {
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((off) => {
<ide> assert.throws(
<ide> () => small[fn](23, off),
<ide> { code: 'ERR_INVALID_ARG_TYPE' });
<ide><path>test/parallel/test-buffer-writefloat.js
<ide> assert.ok(Number.isNaN(buffer.readFloatLE(4)));
<ide> const small = Buffer.allocUnsafe(1);
<ide>
<ide> ['writeFloatLE', 'writeFloatBE'].forEach((fn) => {
<add>
<add> // Verify that default offset works fine.
<add> buffer[fn](23, undefined);
<add> buffer[fn](23);
<add>
<ide> assert.throws(
<ide> () => small[fn](11.11, 0),
<ide> {
<ide> assert.ok(Number.isNaN(buffer.readFloatLE(4)));
<ide> message: 'Attempt to write outside buffer bounds'
<ide> });
<ide>
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((off) => {
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((off) => {
<ide> assert.throws(
<ide> () => small[fn](23, off),
<ide> { code: 'ERR_INVALID_ARG_TYPE' }
<ide><path>test/parallel/test-buffer-writeint.js
<ide> const errorOutOfBounds = common.expectsError({
<ide> buffer.writeInt8(-0x80 - 1, 0);
<ide> }, errorOutOfBounds);
<ide>
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((off) => {
<add> // Verify that default offset works fine.
<add> buffer.writeInt8(23, undefined);
<add> buffer.writeInt8(23);
<add>
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((off) => {
<ide> assert.throws(
<ide> () => buffer.writeInt8(23, off),
<ide> { code: 'ERR_INVALID_ARG_TYPE' });
<ide> const errorOutOfBounds = common.expectsError({
<ide> assert.ok(buffer.equals(new Uint8Array([ 0xff, 0x7f, 0x00, 0x80 ])));
<ide>
<ide> ['writeInt16BE', 'writeInt16LE'].forEach((fn) => {
<add>
<add> // Verify that default offset works fine.
<add> buffer[fn](23, undefined);
<add> buffer[fn](23);
<add>
<ide> assert.throws(() => {
<ide> buffer[fn](0x7fff + 1, 0);
<ide> }, errorOutOfBounds);
<ide> assert.throws(() => {
<ide> buffer[fn](-0x8000 - 1, 0);
<ide> }, errorOutOfBounds);
<ide>
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((off) => {
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((off) => {
<ide> assert.throws(
<ide> () => buffer[fn](23, off),
<ide> { code: 'ERR_INVALID_ARG_TYPE' });
<ide> const errorOutOfBounds = common.expectsError({
<ide> ])));
<ide>
<ide> ['writeInt32BE', 'writeInt32LE'].forEach((fn) => {
<add>
<add> // Verify that default offset works fine.
<add> buffer[fn](23, undefined);
<add> buffer[fn](23);
<add>
<ide> assert.throws(() => {
<ide> buffer[fn](0x7fffffff + 1, 0);
<ide> }, errorOutOfBounds);
<ide> assert.throws(() => {
<ide> buffer[fn](-0x80000000 - 1, 0);
<ide> }, errorOutOfBounds);
<ide>
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((off) => {
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((off) => {
<ide> assert.throws(
<ide> () => buffer[fn](23, off),
<ide> { code: 'ERR_INVALID_ARG_TYPE' });
<ide> const errorOutOfBounds = common.expectsError({
<ide>
<ide> // Check byteLength.
<ide> ['writeIntBE', 'writeIntLE'].forEach((fn) => {
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((o) => {
<add>
<add> // Verify that default offset & byteLength works fine.
<add> data[fn](undefined, undefined);
<add> data[fn](undefined);
<add> data[fn]();
<add>
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((bl) => {
<ide> assert.throws(
<del> () => data[fn](23, 0, o),
<add> () => data[fn](23, 0, bl),
<ide> { code: 'ERR_INVALID_ARG_TYPE' });
<ide> });
<ide>
<ide> const errorOutOfBounds = common.expectsError({
<ide> });
<ide> });
<ide>
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((o) => {
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((o) => {
<ide> assert.throws(
<ide> () => data[fn](min, o, i),
<ide> {
<ide><path>test/parallel/test-buffer-writeuint.js
<ide> const assert = require('assert');
<ide> { // OOB
<ide> const data = Buffer.alloc(8);
<ide> ['UInt8', 'UInt16BE', 'UInt16LE', 'UInt32BE', 'UInt32LE'].forEach((fn) => {
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((o) => {
<add>
<add> // Verify that default offset works fine.
<add> data[`write${fn}`](23, undefined);
<add> data[`write${fn}`](23);
<add>
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((o) => {
<ide> assert.throws(
<ide> () => data[`write${fn}`](23, o),
<ide> { code: 'ERR_INVALID_ARG_TYPE' });
<ide> const assert = require('assert');
<ide>
<ide> // Check byteLength.
<ide> ['writeUIntBE', 'writeUIntLE'].forEach((fn) => {
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((o) => {
<add>
<add> // Verify that default offset & byteLength works fine.
<add> data[fn](undefined, undefined);
<add> data[fn](undefined);
<add> data[fn]();
<add>
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((bl) => {
<ide> assert.throws(
<del> () => data[fn](23, 0, o),
<add> () => data[fn](23, 0, bl),
<ide> { code: 'ERR_INVALID_ARG_TYPE' });
<ide> });
<ide>
<ide> const assert = require('assert');
<ide> `It must be >= 0 and <= ${val - 1}. Received ${val}`
<ide> });
<ide>
<del> ['', '0', null, undefined, {}, [], () => {}, true, false].forEach((o) => {
<add> ['', '0', null, {}, [], () => {}, true, false].forEach((o) => {
<ide> assert.throws(
<ide> () => data[fn](23, o, i),
<ide> { | 8 |
PHP | PHP | prefer an early return | 1ca85ae11919520859cde39375d50690614633a1 | <ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php
<ide> protected function seeCookie($cookieName, $value = null, $encrypted = true)
<ide>
<ide> $this->assertTrue($exist, "Cookie [{$cookieName}] not present on response.");
<ide>
<del> if ($exist && ! is_null($value)) {
<del> $cookieValue = $cookie->getValue();
<add> if (! $exist || is_null($value)) {
<add> return $this;
<add> }
<ide>
<del> $actual = $encrypted
<del> ? $this->app['encrypter']->decrypt($cookieValue) : $cookieValue;
<add> $cookieValue = $cookie->getValue();
<ide>
<del> $this->assertEquals(
<del> $actual, $value,
<del> "Cookie [{$cookieName}] was found, but value [{$actual}] does not match [{$value}]."
<del> );
<del> }
<add> $actual = $encrypted
<add> ? $this->app['encrypter']->decrypt($cookieValue) : $cookieValue;
<ide>
<del> return $this;
<add> return $this->assertEquals(
<add> $actual, $value,
<add> "Cookie [{$cookieName}] was found, but value [{$actual}] does not match [{$value}]."
<add> );
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | fix json serialization in lambda layer | e37df7ca853431f0579d66307ba3f7e4d7cdd20b | <ide><path>keras/layers/core.py
<ide> def get_config(self):
<ide>
<ide> if isinstance(self._output_shape, python_types.LambdaType):
<ide> if py3:
<del> output_shape = marshal.dumps(self._output_shape.__code__)
<add> output_shape = marshal.dumps(self._output_shape.__code__).decode('raw_unicode_escape')
<ide> else:
<del> output_shape = marshal.dumps(self._output_shape.func_code)
<add> output_shape = marshal.dumps(self._output_shape.func_code).decode('raw_unicode_escape')
<ide> output_shape_type = 'lambda'
<ide> elif callable(self._output_shape):
<ide> output_shape = self._output_shape.__name__
<ide> def from_config(cls, config):
<ide> if output_shape_type == 'function':
<ide> output_shape = globals()[config['output_shape']]
<ide> elif output_shape_type == 'lambda':
<del> output_shape = marshal.loads(config['output_shape'])
<add> output_shape = marshal.loads(config['output_shape'].encode('raw_unicode_escape'))
<ide> output_shape = python_types.FunctionType(output_shape, globals())
<ide> else:
<ide> output_shape = config['output_shape'] | 1 |
Go | Go | use pkg/errors in more places | 26d0bac8955903bc3a845358d159b2ec2f7c253f | <ide><path>api/server/server.go
<ide> func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
<ide> }
<ide>
<ide> if err := handlerFunc(ctx, w, r, vars); err != nil {
<del> logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
<add> logrus.Errorf("Handler for %s %s returned error: %+v", r.Method, r.URL.Path, err)
<ide> httputils.MakeErrorHandler(err)(w, r)
<ide> }
<ide> }
<ide><path>plugin/manager.go
<ide> func (pm *Manager) save(p *v2.Plugin) error {
<ide> return errors.Wrap(err, "failed to marshal plugin json")
<ide> }
<ide> if err := ioutils.AtomicWriteFile(filepath.Join(pm.config.Root, p.GetID(), configFileName), pluginJSON, 0600); err != nil {
<del> return err
<add> return errors.Wrap(err, "failed to write atomically plugin json")
<ide> }
<ide> return nil
<ide> }
<ide><path>plugin/manager_linux.go
<ide> func (pm *Manager) enable(p *v2.Plugin, c *controller, force bool) error {
<ide>
<ide> if p.PropagatedMount != "" {
<ide> if err := mount.MakeRShared(p.PropagatedMount); err != nil {
<del> return err
<add> return errors.WithStack(err)
<ide> }
<ide> }
<ide>
<ide> if err := initlayer.Setup(filepath.Join(pm.config.Root, p.PluginObj.ID, rootFSFileName), 0, 0); err != nil {
<del> return err
<add> return errors.WithStack(err)
<ide> }
<ide>
<ide> if err := pm.containerdClient.Create(p.GetID(), "", "", specs.Spec(*spec), attachToLog(p.GetID())); err != nil {
<ide> func (pm *Manager) enable(p *v2.Plugin, c *controller, force bool) error {
<ide> logrus.Warnf("Could not unmount %s: %v", p.PropagatedMount, err)
<ide> }
<ide> }
<del> return err
<add> return errors.WithStack(err)
<ide> }
<ide>
<ide> return pm.pluginPostStart(p, c)
<ide> func (pm *Manager) pluginPostStart(p *v2.Plugin, c *controller) error {
<ide> if err != nil {
<ide> c.restart = false
<ide> shutdownPlugin(p, c, pm.containerdClient)
<del> return err
<add> return errors.WithStack(err)
<ide> }
<ide>
<ide> p.SetPClient(client)
<ide><path>plugin/v2/plugin_linux.go
<ide> package v2
<ide>
<ide> import (
<del> "errors"
<ide> "os"
<ide> "path/filepath"
<ide> "strings"
<ide> import (
<ide> "github.com/docker/docker/oci"
<ide> "github.com/docker/docker/pkg/system"
<ide> specs "github.com/opencontainers/runtime-spec/specs-go"
<add> "github.com/pkg/errors"
<ide> )
<ide>
<ide> // InitSpec creates an OCI spec from the plugin's config.
<ide> func (p *Plugin) InitSpec(execRoot string) (*specs.Spec, error) {
<ide>
<ide> execRoot = filepath.Join(execRoot, p.PluginObj.ID)
<ide> if err := os.MkdirAll(execRoot, 0700); err != nil {
<del> return nil, err
<add> return nil, errors.WithStack(err)
<ide> }
<ide>
<ide> mounts := append(p.PluginObj.Config.Mounts, types.PluginMount{
<ide> func (p *Plugin) InitSpec(execRoot string) (*specs.Spec, error) {
<ide> path := *dev.Path
<ide> d, dPermissions, err := oci.DevicesFromPath(path, path, "rwm")
<ide> if err != nil {
<del> return nil, err
<add> return nil, errors.WithStack(err)
<ide> }
<ide> s.Linux.Devices = append(s.Linux.Devices, d...)
<ide> s.Linux.Resources.Devices = append(s.Linux.Resources.Devices, dPermissions...) | 4 |
Javascript | Javascript | pass kind to recursive calls to flush | fa27c5634b4e0bd1699eca526d415147fe334107 | <ide><path>lib/zlib.js
<ide> Zlib.prototype.flush = function(kind, callback) {
<ide> } else if (ws.needDrain) {
<ide> var self = this;
<ide> this.once('drain', function() {
<del> self.flush(callback);
<add> self.flush(kind, callback);
<ide> });
<ide> } else {
<ide> this._flushFlag = kind; | 1 |
Python | Python | update conversion script | 2f1c745cded91b2f6cfed5b502ea5cbd7d6b9ac7 | <ide><path>transformers/convert_xlm_roberta_original_pytorch_checkpoint_to_pytorch.py
<ide> def convert_roberta_checkpoint_to_pytorch(roberta_checkpoint_path, pytorch_dump_
<ide> roberta = FairseqRobertaModel.from_pretrained(roberta_checkpoint_path, bpe = 'sentencepiece')
<ide> roberta.eval() # disable dropout
<ide> config = BertConfig(
<del> vocab_size_or_config_json_file=250002,
<add> vocab_size=250002,
<ide> hidden_size=roberta.args.encoder_embed_dim,
<ide> num_hidden_layers=roberta.args.encoder_layers,
<ide> num_attention_heads=roberta.args.encoder_attention_heads, | 1 |
Python | Python | add doctests for sorting algorithms | 390feb0b23b4845a7ddfec7afd703aa053d1b224 | <ide><path>sorts/pancake_sort.py
<del>"""Pancake Sort Algorithm."""
<del># Only can reverse array from 0 to i
<del>
<add>"""
<add>This is a pure python implementation of the pancake sort algorithm
<add>For doctests run following command:
<add>python3 -m doctest -v pancake_sort.py
<add>or
<add>python -m doctest -v pancake_sort.py
<add>For manual testing run:
<add>python pancake_sort.py
<add>"""
<ide>
<ide> def pancake_sort(arr):
<del> """Sort Array with Pancake Sort."""
<add> """Sort Array with Pancake Sort.
<add> :param arr: Collection containing comparable items
<add> :return: Collection ordered in ascending order of items
<add> Examples:
<add> >>> pancake_sort([0, 5, 3, 2, 2])
<add> [0, 2, 2, 3, 5]
<add> >>> pancake_sort([])
<add> []
<add> >>> pancake_sort([-2, -5, -45])
<add> [-45, -5, -2]
<add> """
<ide> cur = len(arr)
<ide> while cur > 1:
<ide> # Find the maximum number in arr
<ide> def pancake_sort(arr):
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> print(pancake_sort([0, 10, 15, 3, 2, 9, 14, 13]))
<add> user_input = input('Enter numbers separated by a comma:\n').strip()
<add> unsorted = [int(item) for item in user_input.split(',')]
<add> print(pancake_sort(unsorted))
<ide><path>sorts/pigeon_sort.py
<ide> '''
<ide> This is an implementation of Pigeon Hole Sort.
<add> For doctests run following command:
<add>
<add> python3 -m doctest -v pigeon_sort.py
<add> or
<add> python -m doctest -v pigeon_sort.py
<add>
<add> For manual testing run:
<add> python pigeon_sort.py
<ide> '''
<ide> def pigeon_sort(array):
<add> """
<add> Implementation of pigeon hole sort algorithm
<add> :param array: Collection of comparable items
<add> :return: Collection sorted in ascending order
<add> >>> pigeon_sort([0, 5, 3, 2, 2])
<add> [0, 2, 2, 3, 5]
<add> >>> pigeon_sort([])
<add> []
<add> >>> pigeon_sort([-2, -5, -45])
<add> [-45, -5, -2]
<add> """
<add> if(len(array) == 0):
<add> return array
<add>
<ide> # Manually finds the minimum and maximum of the array.
<ide> min = array[0]
<ide> max = array[0]
<ide> def pigeon_sort(array):
<ide> if __name__ == '__main__':
<ide> user_input = input('Enter numbers separated by comma:\n')
<ide> unsorted = [int(x) for x in user_input.split(',')]
<del> sorted = pigeon_sort(unsorted)
<del>
<del> print(sorted)
<add> print(pigeon_sort(unsorted)) | 2 |
Ruby | Ruby | add ast cache to the find_by method | 77b18d7ef47f4dd6bf39853ac83cc19a3593406f | <ide><path>activerecord/lib/active_record/core.rb
<ide> def self.disable_implicit_join_references=(value)
<ide> end
<ide>
<ide> class_attribute :default_connection_handler, instance_writer: false
<add> class_attribute :find_by_statement_cache
<ide>
<ide> def self.connection_handler
<ide> ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler
<ide> def self.connection_handler=(handler)
<ide> end
<ide>
<ide> module ClassMethods
<add> def initialize_find_by_cache
<add> self.find_by_statement_cache = {}.extend(Mutex_m)
<add> end
<add>
<add> def inherited(child_class)
<add> child_class.initialize_find_by_cache
<add> super
<add> end
<add>
<add> def find_by(*args)
<add> return super if current_scope || args.length > 1 || reflect_on_all_aggregations.any?
<add>
<add> hash = args.first
<add>
<add> return super if hash.values.any? { |v| v.nil? || Array === v }
<add>
<add> key = hash.keys
<add>
<add> klass = self
<add> s = find_by_statement_cache[key] || find_by_statement_cache.synchronize {
<add> find_by_statement_cache[key] ||= StatementCache.new { |params|
<add> wheres = key.each_with_object({}) { |param,o|
<add> o[param] = params[param]
<add> }
<add> klass.where(wheres).limit(1)
<add> }
<add> }
<add> begin
<add> s.execute(hash).first
<add> rescue TypeError => e
<add> raise ActiveRecord::StatementInvalid.new(e.message, e)
<add> end
<add> end
<add>
<ide> def initialize_generated_modules
<ide> super
<ide> | 1 |
Ruby | Ruby | check git available | 8d5c445daa7520c75f7b3c2a132eda2ec86e0727 | <ide><path>Library/Homebrew/utils.rb
<ide> def self.git_last_commit_date
<ide> end
<ide>
<ide> def self.homebrew_version_string
<del> pretty_revision = git_short_head
<del> if pretty_revision
<add> if Utils.git_available? && (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 | fix typo in lib/util.js | 8d3c46daa8a4a9a06a7753f594690edc4a8fe401 | <ide><path>lib/util.js
<ide> exports.pump = function(readStream, writeStream, callback) {
<ide> *
<ide> * The Function.prototype.inherits from lang.js rewritten as a standalone
<ide> * function (not on Function.prototype). NOTE: If this file is to be loaded
<del> * during bootstrapping this function needs to be revritten using some native
<add> * during bootstrapping this function needs to be rewritten using some native
<ide> * functions as prototype setup using normal JavaScript does not work as
<ide> * expected during bootstrapping (see mirror.js in r114903).
<ide> * | 1 |
Javascript | Javascript | add userefresh hook to react-debug-tools | 27659559ebfd6b7119bfc0ff02ecb851c135020c | <ide><path>packages/react-debug-tools/src/ReactDebugHooks.js
<ide> function getPrimitiveStackCache(): Map<string, Array<any>> {
<ide> Dispatcher.useState(null);
<ide> Dispatcher.useReducer((s, a) => s, null);
<ide> Dispatcher.useRef(null);
<add> if (typeof Dispatcher.useCacheRefresh === 'function') {
<add> // This type check is for Flow only.
<add> Dispatcher.useCacheRefresh();
<add> }
<ide> Dispatcher.useLayoutEffect(() => {});
<ide> Dispatcher.useEffect(() => {});
<ide> Dispatcher.useImperativeHandle(undefined, () => null);
<ide> function useRef<T>(initialValue: T): {|current: T|} {
<ide> return ref;
<ide> }
<ide>
<add>function useCacheRefresh(): () => void {
<add> const hook = nextHook();
<add> hookLog.push({
<add> primitive: 'CacheRefresh',
<add> stackError: new Error(),
<add> value: hook !== null ? hook.memoizedState : function refresh() {},
<add> });
<add> return () => {};
<add>}
<add>
<ide> function useLayoutEffect(
<ide> create: () => (() => void) | void,
<ide> inputs: Array<mixed> | void | null,
<ide> function useOpaqueIdentifier(): OpaqueIDType | void {
<ide> const Dispatcher: DispatcherType = {
<ide> getCacheForType,
<ide> readContext,
<add> useCacheRefresh,
<ide> useCallback,
<ide> useContext,
<ide> useEffect, | 1 |
Python | Python | add deberta to model_for_pretraining_mapping | a01ea31b5c605ea812777330ed1de8e805dca9ea | <ide><path>src/transformers/models/auto/modeling_auto.py
<ide> (MPNetConfig, MPNetForMaskedLM),
<ide> (TapasConfig, TapasForMaskedLM),
<ide> (IBertConfig, IBertForMaskedLM),
<add> (DebertaConfig, DebertaForMaskedLM),
<add> (DebertaV2Config, DebertaV2ForMaskedLM),
<ide> ]
<ide> )
<ide> | 1 |
PHP | PHP | fix backwards compatibility for typehints | 113c5684716f117650f75bd3f996931c3d7460f2 | <ide><path>src/ORM/Table.php
<ide> public function implementedEvents()
<ide> return $events;
<ide> }
<ide>
<add> /**
<add> * {@inheritDoc}
<add> *
<add> * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
<add> * @return \Cake\ORM\RulesChecker
<add> */
<add> public function buildRules(RulesChecker $rules)
<add> {
<add> return $rules;
<add> }
<add>
<ide> /**
<ide> * Returns an array that can be used to describe the internal state of this
<ide> * object. | 1 |
Javascript | Javascript | update broken url in comments | 39a1ec8b9e407a942f434037470418db17a748b9 | <ide><path>examples/js/curves/CurveExtras.js
<ide> * http://en.wikipedia.org/wiki/Viviani%27s_curve
<ide> * http://mathdl.maa.org/images/upload_library/23/stemkoski/knots/page4.html
<ide> * http://www.mi.sanu.ac.rs/vismath/taylorapril2011/Taylor.pdf
<del> * http://prideout.net/blog/?p=44
<add> * https://prideout.net/blog/old/blog/index.html@p=44.html
<ide> */
<ide>
<ide> THREE.Curves = ( function () {
<ide><path>examples/jsm/curves/CurveExtras.js
<ide> * http://en.wikipedia.org/wiki/Viviani%27s_curve
<ide> * http://mathdl.maa.org/images/upload_library/23/stemkoski/knots/page4.html
<ide> * http://www.mi.sanu.ac.rs/vismath/taylorapril2011/Taylor.pdf
<del> * http://prideout.net/blog/?p=44
<add> * https://prideout.net/blog/old/blog/index.html@p=44.html
<ide> */
<ide>
<ide> import {
<ide><path>src/geometries/ParametricGeometry.js
<ide> * @author Mugen87 / https://github.com/Mugen87
<ide> *
<ide> * Parametric Surfaces Geometry
<del> * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
<add> * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
<ide> */
<ide>
<ide> import { Geometry } from '../core/Geometry.js'; | 3 |
Text | Text | fix typo in doc | fbc1bc6921b3d809cfe33a9cda116bfa239e212a | <ide><path>docs/recipes/reducers/UpdatingNormalizedData.md
<ide> As mentioned in [Normalizing State Shape](./NormalizingStateShape.md), the Norma
<ide>
<ide> ### Simple Merging
<ide>
<del>One approach is to merge the contents of the action in to the existing state. In this case, we need to do a deep recursive merge, not just a shallow copy. The Lodash `merge` function can handle this for us:
<add>One approach is to merge the contents of the action into the existing state. In this case, we need to do a deep recursive merge, not just a shallow copy. The Lodash `merge` function can handle this for us:
<ide>
<ide> ```js
<ide> import merge from "lodash/merge"; | 1 |
Javascript | Javascript | fix localedata months on greek | 555c00d010f22e059028cbf6eddd8a24c9182969 | <ide><path>src/locale/el.js
<ide> export default moment.defineLocale('el', {
<ide> months : function (momentToFormat, format) {
<ide> if (!momentToFormat) {
<ide> return this._monthsNominativeEl;
<del> } else if (/D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
<add> } else if (typeof format === 'string' && /D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
<ide> return this._monthsGenitiveEl[momentToFormat.month()];
<ide> } else {
<ide> return this._monthsNominativeEl[momentToFormat.month()];
<ide><path>src/test/locale/el.js
<ide> test('weeks year starting sunday format', function (assert) {
<ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2η', 'Jan 15 2012 should be week 2');
<ide> });
<ide>
<add>test('localeData months calls', function (assert) {
<add> var jan = moment('2012-01-01');
<add> assert.equal(moment.localeData().months(jan), 'Ιανουάριος', 'should return the nominative month name');
<add> assert.equal(moment.localeData().months(jan, 'D MMMM'), 'Ιανουαρίου', 'should return the genitive month name');
<add>}); | 2 |
Python | Python | remove one file | cadde4ee2bd6ecb25252dfa61c58f140838053d9 | <ide><path>official/projects/longformer/transform_longformer_tokenized_into_tfrecord.py
<del># Copyright 2021 The TensorFlow Authors. All Rights Reserved.
<del>#
<del># Licensed under the Apache License, Version 2.0 (the "License");
<del># you may not use this file except in compliance with the License.
<del># You may obtain a copy of the License at
<del>#
<del># http://www.apache.org/licenses/LICENSE-2.0
<del>#
<del># Unless required by applicable law or agreed to in writing, software
<del># distributed under the License is distributed on an "AS IS" BASIS,
<del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del># See the License for the specific language governing permissions and
<del># limitations under the License.
<del>
<del>"""BERT library to process data for classification task."""
<del>
<del>import collections
<del>import csv
<del>import importlib
<del>import json
<del>import os
<del>
<del>from absl import logging
<del>import tensorflow as tf
<del>import tensorflow_datasets as tfds
<del>
<del>from official.nlp.bert import tokenization
<del>
<del>
<del>class InputExample(object):
<del> """A single training/test example for simple seq regression/classification."""
<del>
<del> def __init__(self,
<del> guid,
<del> text_a,
<del> text_b=None,
<del> label=None,
<del> weight=None,
<del> example_id=None):
<del> """Constructs a InputExample.
<del>
<del> Args:
<del> guid: Unique id for the example.
<del> text_a: string. The untokenized text of the first sequence. For single
<del> sequence tasks, only this sequence must be specified.
<del> text_b: (Optional) string. The untokenized text of the second sequence.
<del> Only must be specified for sequence pair tasks.
<del> label: (Optional) string for classification, float for regression. The
<del> label of the example. This should be specified for train and dev
<del> examples, but not for test examples.
<del> weight: (Optional) float. The weight of the example to be used during
<del> training.
<del> example_id: (Optional) int. The int identification number of example in
<del> the corpus.
<del> """
<del> self.guid = guid
<del> self.text_a = text_a
<del> self.text_b = text_b
<del> self.label = label
<del> self.weight = weight
<del> self.example_id = example_id
<del>
<del>
<del>class InputFeatures(object):
<del> """A single set of features of data."""
<del>
<del> def __init__(self,
<del> input_ids,
<del> input_mask,
<del> segment_ids,
<del> label_id,
<del> is_real_example=True,
<del> weight=None,
<del> example_id=None):
<del> self.input_ids = input_ids
<del> self.input_mask = input_mask
<del> self.segment_ids = segment_ids
<del> self.label_id = label_id
<del> self.is_real_example = is_real_example
<del> self.weight = weight
<del> self.example_id = example_id
<del>
<del>
<del>class DataProcessor(object):
<del> """Base class for converters for seq regression/classification datasets."""
<del>
<del> def __init__(self, process_text_fn=tokenization.convert_to_unicode):
<del> self.process_text_fn = process_text_fn
<del> self.is_regression = False
<del> self.label_type = None
<del>
<del> def get_train_examples(self, data_dir):
<del> """Gets a collection of `InputExample`s for the train set."""
<del> raise NotImplementedError()
<del>
<del> def get_dev_examples(self, data_dir):
<del> """Gets a collection of `InputExample`s for the dev set."""
<del> raise NotImplementedError()
<del>
<del> def get_test_examples(self, data_dir):
<del> """Gets a collection of `InputExample`s for prediction."""
<del> raise NotImplementedError()
<del>
<del> def get_labels(self):
<del> """Gets the list of labels for this data set."""
<del> raise NotImplementedError()
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """Gets the string identifier of the processor."""
<del> raise NotImplementedError()
<del>
<del> @classmethod
<del> def _read_tsv(cls, input_file, quotechar=None):
<del> """Reads a tab separated value file."""
<del> with tf.io.gfile.GFile(input_file, "r") as f:
<del> reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
<del> lines = []
<del> for line in reader:
<del> lines.append(line)
<del> return lines
<del>
<del> @classmethod
<del> def _read_jsonl(cls, input_file):
<del> """Reads a json line file."""
<del> with tf.io.gfile.GFile(input_file, "r") as f:
<del> lines = []
<del> for json_str in f:
<del> lines.append(json.loads(json_str))
<del> return lines
<del>
<del> def featurize_example(self, *kargs, **kwargs):
<del> """Converts a single `InputExample` into a single `InputFeatures`."""
<del> return convert_single_example(*kargs, **kwargs)
<del>
<del>
<del>class DefaultGLUEDataProcessor(DataProcessor):
<del> """Processor for the SuperGLUE dataset."""
<del>
<del> def get_train_examples(self, data_dir):
<del> """See base class."""
<del> return self._create_examples_tfds("train")
<del>
<del> def get_dev_examples(self, data_dir):
<del> """See base class."""
<del> return self._create_examples_tfds("validation")
<del>
<del> def get_test_examples(self, data_dir):
<del> """See base class."""
<del> return self._create_examples_tfds("test")
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> raise NotImplementedError()
<del>
<del>
<del>class AxProcessor(DataProcessor):
<del> """Processor for the AX dataset (GLUE diagnostics dataset)."""
<del>
<del> def get_train_examples(self, data_dir):
<del> """See base class."""
<del> train_mnli_dataset = tfds.load(
<del> "glue/mnli", split="train", try_gcs=True).as_numpy_iterator()
<del> return self._create_examples_tfds(train_mnli_dataset, "train")
<del>
<del> def get_dev_examples(self, data_dir):
<del> """See base class."""
<del> val_mnli_dataset = tfds.load(
<del> "glue/mnli", split="validation_matched",
<del> try_gcs=True).as_numpy_iterator()
<del> return self._create_examples_tfds(val_mnli_dataset, "validation")
<del>
<del> def get_test_examples(self, data_dir):
<del> """See base class."""
<del> test_ax_dataset = tfds.load(
<del> "glue/ax", split="test", try_gcs=True).as_numpy_iterator()
<del> return self._create_examples_tfds(test_ax_dataset, "test")
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["contradiction", "entailment", "neutral"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "AX"
<del>
<del> def _create_examples_tfds(self, dataset, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "contradiction"
<del> text_a = self.process_text_fn(example["hypothesis"])
<del> text_b = self.process_text_fn(example["premise"])
<del> if set_type != "test":
<del> label = self.get_labels()[example["label"]]
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label,
<del> weight=None))
<del> return examples
<del>
<del>
<del>class ColaProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the CoLA data set (GLUE version)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["0", "1"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "COLA"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/cola", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "0"
<del> text_a = self.process_text_fn(example["sentence"])
<del> if set_type != "test":
<del> label = str(example["label"])
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=None, label=label, weight=None))
<del> return examples
<del>
<del>
<del>class ImdbProcessor(DataProcessor):
<del> """Processor for the IMDb dataset."""
<del>
<del> def get_labels(self):
<del> return ["neg", "pos"]
<del>
<del> def get_train_examples(self, data_dir):
<del> return self._create_examples(os.path.join(data_dir, "train"))
<del>
<del> def get_dev_examples(self, data_dir):
<del> return self._create_examples(os.path.join(data_dir, "test"))
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "IMDB"
<del>
<del> def _create_examples(self, data_dir):
<del> """Creates examples."""
<del> examples = []
<del> for label in ["neg", "pos"]:
<del> cur_dir = os.path.join(data_dir, label)
<del> for filename in tf.io.gfile.listdir(cur_dir):
<del> if not filename.endswith("txt"):
<del> continue
<del>
<del> if len(examples) % 1000 == 0:
<del> logging.info("Loading dev example %d", len(examples))
<del>
<del> path = os.path.join(cur_dir, filename)
<del> with tf.io.gfile.GFile(path, "r") as f:
<del> text = f.read().strip().replace("<br />", " ")
<del> examples.append(
<del> InputExample(
<del> guid="unused_id", text_a=text, text_b=None, label=label))
<del> return examples
<del>
<del>
<del>class MnliProcessor(DataProcessor):
<del> """Processor for the MultiNLI data set (GLUE version)."""
<del>
<del> def __init__(self,
<del> mnli_type="matched",
<del> process_text_fn=tokenization.convert_to_unicode):
<del> super(MnliProcessor, self).__init__(process_text_fn)
<del> self.dataset = tfds.load("glue/mnli", try_gcs=True)
<del> if mnli_type not in ("matched", "mismatched"):
<del> raise ValueError("Invalid `mnli_type`: %s" % mnli_type)
<del> self.mnli_type = mnli_type
<del>
<del> def get_train_examples(self, data_dir):
<del> """See base class."""
<del> return self._create_examples_tfds("train")
<del>
<del> def get_dev_examples(self, data_dir):
<del> """See base class."""
<del> if self.mnli_type == "matched":
<del> return self._create_examples_tfds("validation_matched")
<del> else:
<del> return self._create_examples_tfds("validation_mismatched")
<del>
<del> def get_test_examples(self, data_dir):
<del> """See base class."""
<del> if self.mnli_type == "matched":
<del> return self._create_examples_tfds("test_matched")
<del> else:
<del> return self._create_examples_tfds("test_mismatched")
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["contradiction", "entailment", "neutral"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "MNLI"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/mnli", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "contradiction"
<del> text_a = self.process_text_fn(example["hypothesis"])
<del> text_b = self.process_text_fn(example["premise"])
<del> if set_type != "test":
<del> label = self.get_labels()[example["label"]]
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label,
<del> weight=None))
<del> return examples
<del>
<del>
<del>class MrpcProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the MRPC data set (GLUE version)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["0", "1"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "MRPC"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/mrpc", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "0"
<del> text_a = self.process_text_fn(example["sentence1"])
<del> text_b = self.process_text_fn(example["sentence2"])
<del> if set_type != "test":
<del> label = str(example["label"])
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label,
<del> weight=None))
<del> return examples
<del>
<del>
<del>class PawsxProcessor(DataProcessor):
<del> """Processor for the PAWS-X data set."""
<del> supported_languages = ["de", "en", "es", "fr", "ja", "ko", "zh"]
<del>
<del> def __init__(self,
<del> language="en",
<del> process_text_fn=tokenization.convert_to_unicode):
<del> super(PawsxProcessor, self).__init__(process_text_fn)
<del> if language == "all":
<del> self.languages = PawsxProcessor.supported_languages
<del> elif language not in PawsxProcessor.supported_languages:
<del> raise ValueError("language %s is not supported for PAWS-X task." %
<del> language)
<del> else:
<del> self.languages = [language]
<del>
<del> def get_train_examples(self, data_dir):
<del> """See base class."""
<del> lines = []
<del> for language in self.languages:
<del> if language == "en":
<del> train_tsv = "train.tsv"
<del> else:
<del> train_tsv = "translated_train.tsv"
<del> # Skips the header.
<del> lines.extend(
<del> self._read_tsv(os.path.join(data_dir, language, train_tsv))[1:])
<del>
<del> examples = []
<del> for i, line in enumerate(lines):
<del> guid = "train-%d" % i
<del> text_a = self.process_text_fn(line[1])
<del> text_b = self.process_text_fn(line[2])
<del> label = self.process_text_fn(line[3])
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del> def get_dev_examples(self, data_dir):
<del> """See base class."""
<del> lines = []
<del> for lang in PawsxProcessor.supported_languages:
<del> lines.extend(
<del> self._read_tsv(os.path.join(data_dir, lang, "dev_2k.tsv"))[1:])
<del>
<del> examples = []
<del> for i, line in enumerate(lines):
<del> guid = "dev-%d" % i
<del> text_a = self.process_text_fn(line[1])
<del> text_b = self.process_text_fn(line[2])
<del> label = self.process_text_fn(line[3])
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del> def get_test_examples(self, data_dir):
<del> """See base class."""
<del> examples_by_lang = {k: [] for k in self.supported_languages}
<del> for lang in self.supported_languages:
<del> lines = self._read_tsv(os.path.join(data_dir, lang, "test_2k.tsv"))[1:]
<del> for i, line in enumerate(lines):
<del> guid = "test-%d" % i
<del> text_a = self.process_text_fn(line[1])
<del> text_b = self.process_text_fn(line[2])
<del> label = self.process_text_fn(line[3])
<del> examples_by_lang[lang].append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples_by_lang
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["0", "1"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "XTREME-PAWS-X"
<del>
<del>
<del>class QnliProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the QNLI data set (GLUE version)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["entailment", "not_entailment"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "QNLI"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/qnli", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "entailment"
<del> text_a = self.process_text_fn(example["question"])
<del> text_b = self.process_text_fn(example["sentence"])
<del> if set_type != "test":
<del> label = self.get_labels()[example["label"]]
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label,
<del> weight=None))
<del> return examples
<del>
<del>
<del>class QqpProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the QQP data set (GLUE version)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["0", "1"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "QQP"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/qqp", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "0"
<del> text_a = self.process_text_fn(example["question1"])
<del> text_b = self.process_text_fn(example["question2"])
<del> if set_type != "test":
<del> label = str(example["label"])
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label,
<del> weight=None))
<del> return examples
<del>
<del>
<del>class RteProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the RTE data set (GLUE version)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> # All datasets are converted to 2-class split, where for 3-class datasets we
<del> # collapse neutral and contradiction into not_entailment.
<del> return ["entailment", "not_entailment"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "RTE"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/rte", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "entailment"
<del> text_a = self.process_text_fn(example["sentence1"])
<del> text_b = self.process_text_fn(example["sentence2"])
<del> if set_type != "test":
<del> label = self.get_labels()[example["label"]]
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label,
<del> weight=None))
<del> return examples
<del>
<del>
<del>class SstProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the SST-2 data set (GLUE version)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["0", "1"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "SST-2"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/sst2", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "0"
<del> text_a = self.process_text_fn(example["sentence"])
<del> if set_type != "test":
<del> label = str(example["label"])
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=None, label=label, weight=None))
<del> return examples
<del>
<del>
<del>class StsBProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the STS-B data set (GLUE version)."""
<del>
<del> def __init__(self, process_text_fn=tokenization.convert_to_unicode):
<del> super(StsBProcessor, self).__init__(process_text_fn=process_text_fn)
<del> self.is_regression = True
<del> self.label_type = float
<del> self._labels = None
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/stsb", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = 0.0
<del> text_a = self.process_text_fn(example["sentence1"])
<del> text_b = self.process_text_fn(example["sentence2"])
<del> if set_type != "test":
<del> label = self.label_type(example["label"])
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label,
<del> weight=None))
<del> return examples
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return self._labels
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "STS-B"
<del>
<del>
<del>class TfdsProcessor(DataProcessor):
<del> """Processor for generic text classification and regression TFDS data set.
<del>
<del> The TFDS parameters are expected to be provided in the tfds_params string, in
<del> a comma-separated list of parameter assignments.
<del> Examples:
<del> tfds_params="dataset=scicite,text_key=string"
<del> tfds_params="dataset=imdb_reviews,test_split=,dev_split=test"
<del> tfds_params="dataset=glue/cola,text_key=sentence"
<del> tfds_params="dataset=glue/sst2,text_key=sentence"
<del> tfds_params="dataset=glue/qnli,text_key=question,text_b_key=sentence"
<del> tfds_params="dataset=glue/mrpc,text_key=sentence1,text_b_key=sentence2"
<del> tfds_params="dataset=glue/stsb,text_key=sentence1,text_b_key=sentence2,"
<del> "is_regression=true,label_type=float"
<del> tfds_params="dataset=snli,text_key=premise,text_b_key=hypothesis,"
<del> "skip_label=-1"
<del> Possible parameters (please refer to the documentation of Tensorflow Datasets
<del> (TFDS) for the meaning of individual parameters):
<del> dataset: Required dataset name (potentially with subset and version number).
<del> data_dir: Optional TFDS source root directory.
<del> module_import: Optional Dataset module to import.
<del> train_split: Name of the train split (defaults to `train`).
<del> dev_split: Name of the dev split (defaults to `validation`).
<del> test_split: Name of the test split (defaults to `test`).
<del> text_key: Key of the text_a feature (defaults to `text`).
<del> text_b_key: Key of the second text feature if available.
<del> label_key: Key of the label feature (defaults to `label`).
<del> test_text_key: Key of the text feature to use in test set.
<del> test_text_b_key: Key of the second text feature to use in test set.
<del> test_label: String to be used as the label for all test examples.
<del> label_type: Type of the label key (defaults to `int`).
<del> weight_key: Key of the float sample weight (is not used if not provided).
<del> is_regression: Whether the task is a regression problem (defaults to False).
<del> skip_label: Skip examples with given label (defaults to None).
<del> """
<del>
<del> def __init__(self,
<del> tfds_params,
<del> process_text_fn=tokenization.convert_to_unicode):
<del> super(TfdsProcessor, self).__init__(process_text_fn)
<del> self._process_tfds_params_str(tfds_params)
<del> if self.module_import:
<del> importlib.import_module(self.module_import)
<del>
<del> self.dataset, info = tfds.load(
<del> self.dataset_name, data_dir=self.data_dir, with_info=True)
<del> if self.is_regression:
<del> self._labels = None
<del> else:
<del> self._labels = list(range(info.features[self.label_key].num_classes))
<del>
<del> def _process_tfds_params_str(self, params_str):
<del> """Extracts TFDS parameters from a comma-separated assignements string."""
<del> dtype_map = {"int": int, "float": float}
<del> cast_str_to_bool = lambda s: s.lower() not in ["false", "0"]
<del>
<del> tuples = [x.split("=") for x in params_str.split(",")]
<del> d = {k.strip(): v.strip() for k, v in tuples}
<del> self.dataset_name = d["dataset"] # Required.
<del> self.data_dir = d.get("data_dir", None)
<del> self.module_import = d.get("module_import", None)
<del> self.train_split = d.get("train_split", "train")
<del> self.dev_split = d.get("dev_split", "validation")
<del> self.test_split = d.get("test_split", "test")
<del> self.text_key = d.get("text_key", "text")
<del> self.text_b_key = d.get("text_b_key", None)
<del> self.label_key = d.get("label_key", "label")
<del> self.test_text_key = d.get("test_text_key", self.text_key)
<del> self.test_text_b_key = d.get("test_text_b_key", self.text_b_key)
<del> self.test_label = d.get("test_label", "test_example")
<del> self.label_type = dtype_map[d.get("label_type", "int")]
<del> self.is_regression = cast_str_to_bool(d.get("is_regression", "False"))
<del> self.weight_key = d.get("weight_key", None)
<del> self.skip_label = d.get("skip_label", None)
<del> if self.skip_label is not None:
<del> self.skip_label = self.label_type(self.skip_label)
<del>
<del> def get_train_examples(self, data_dir):
<del> assert data_dir is None
<del> return self._create_examples(self.train_split, "train")
<del>
<del> def get_dev_examples(self, data_dir):
<del> assert data_dir is None
<del> return self._create_examples(self.dev_split, "dev")
<del>
<del> def get_test_examples(self, data_dir):
<del> assert data_dir is None
<del> return self._create_examples(self.test_split, "test")
<del>
<del> def get_labels(self):
<del> return self._labels
<del>
<del> def get_processor_name(self):
<del> return "TFDS_" + self.dataset_name
<del>
<del> def _create_examples(self, split_name, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> if split_name not in self.dataset:
<del> raise ValueError("Split {} not available.".format(split_name))
<del> dataset = self.dataset[split_name].as_numpy_iterator()
<del> examples = []
<del> text_b, weight = None, None
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> if set_type == "test":
<del> text_a = self.process_text_fn(example[self.test_text_key])
<del> if self.test_text_b_key:
<del> text_b = self.process_text_fn(example[self.test_text_b_key])
<del> label = self.test_label
<del> else:
<del> text_a = self.process_text_fn(example[self.text_key])
<del> if self.text_b_key:
<del> text_b = self.process_text_fn(example[self.text_b_key])
<del> label = self.label_type(example[self.label_key])
<del> if self.skip_label is not None and label == self.skip_label:
<del> continue
<del> if self.weight_key:
<del> weight = float(example[self.weight_key])
<del> examples.append(
<del> InputExample(
<del> guid=guid,
<del> text_a=text_a,
<del> text_b=text_b,
<del> label=label,
<del> weight=weight))
<del> return examples
<del>
<del>
<del>class WnliProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the WNLI data set (GLUE version)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["0", "1"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "WNLI"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "glue/wnli", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for i, example in enumerate(dataset):
<del> guid = "%s-%s" % (set_type, i)
<del> label = "0"
<del> text_a = self.process_text_fn(example["sentence1"])
<del> text_b = self.process_text_fn(example["sentence2"])
<del> if set_type != "test":
<del> label = str(example["label"])
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label,
<del> weight=None))
<del> return examples
<del>
<del>
<del>class XnliProcessor(DataProcessor):
<del> """Processor for the XNLI data set."""
<del> supported_languages = [
<del> "ar", "bg", "de", "el", "en", "es", "fr", "hi", "ru", "sw", "th", "tr",
<del> "ur", "vi", "zh"
<del> ]
<del>
<del> def __init__(self,
<del> language="en",
<del> process_text_fn=tokenization.convert_to_unicode):
<del> super(XnliProcessor, self).__init__(process_text_fn)
<del> if language == "all":
<del> self.languages = XnliProcessor.supported_languages
<del> elif language not in XnliProcessor.supported_languages:
<del> raise ValueError("language %s is not supported for XNLI task." % language)
<del> else:
<del> self.languages = [language]
<del>
<del> def get_train_examples(self, data_dir):
<del> """See base class."""
<del> lines = []
<del> for language in self.languages:
<del> # Skips the header.
<del> lines.extend(
<del> self._read_tsv(
<del> os.path.join(data_dir, "multinli",
<del> "multinli.train.%s.tsv" % language))[1:])
<del>
<del> examples = []
<del> for i, line in enumerate(lines):
<del> guid = "train-%d" % i
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = self.process_text_fn(line[2])
<del> if label == self.process_text_fn("contradictory"):
<del> label = self.process_text_fn("contradiction")
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del> def get_dev_examples(self, data_dir):
<del> """See base class."""
<del> lines = self._read_tsv(os.path.join(data_dir, "xnli.dev.tsv"))
<del> examples = []
<del> for i, line in enumerate(lines):
<del> if i == 0:
<del> continue
<del> guid = "dev-%d" % i
<del> text_a = self.process_text_fn(line[6])
<del> text_b = self.process_text_fn(line[7])
<del> label = self.process_text_fn(line[1])
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del> def get_test_examples(self, data_dir):
<del> """See base class."""
<del> lines = self._read_tsv(os.path.join(data_dir, "xnli.test.tsv"))
<del> examples_by_lang = {k: [] for k in XnliProcessor.supported_languages}
<del> for i, line in enumerate(lines):
<del> if i == 0:
<del> continue
<del> guid = "test-%d" % i
<del> language = self.process_text_fn(line[0])
<del> text_a = self.process_text_fn(line[6])
<del> text_b = self.process_text_fn(line[7])
<del> label = self.process_text_fn(line[1])
<del> examples_by_lang[language].append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples_by_lang
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["contradiction", "entailment", "neutral"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "XNLI"
<del>
<del>
<del>class XtremePawsxProcessor(DataProcessor):
<del> """Processor for the XTREME PAWS-X data set."""
<del> supported_languages = ["de", "en", "es", "fr", "ja", "ko", "zh"]
<del>
<del> def __init__(self,
<del> process_text_fn=tokenization.convert_to_unicode,
<del> translated_data_dir=None,
<del> only_use_en_dev=True):
<del> """See base class.
<del>
<del> Args:
<del> process_text_fn: See base class.
<del> translated_data_dir: If specified, will also include translated data in
<del> the training and testing data.
<del> only_use_en_dev: If True, only use english dev data. Otherwise, use dev
<del> data from all languages.
<del> """
<del> super(XtremePawsxProcessor, self).__init__(process_text_fn)
<del> self.translated_data_dir = translated_data_dir
<del> self.only_use_en_dev = only_use_en_dev
<del>
<del> def get_train_examples(self, data_dir):
<del> """See base class."""
<del> examples = []
<del> if self.translated_data_dir is None:
<del> lines = self._read_tsv(os.path.join(data_dir, "train-en.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = "train-%d" % i
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = self.process_text_fn(line[2])
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> else:
<del> for lang in self.supported_languages:
<del> lines = self._read_tsv(
<del> os.path.join(self.translated_data_dir, "translate-train",
<del> f"en-{lang}-translated.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = f"train-{lang}-{i}"
<del> text_a = self.process_text_fn(line[2])
<del> text_b = self.process_text_fn(line[3])
<del> label = self.process_text_fn(line[4])
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del> def get_dev_examples(self, data_dir):
<del> """See base class."""
<del> examples = []
<del> if self.only_use_en_dev:
<del> lines = self._read_tsv(os.path.join(data_dir, "dev-en.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = "dev-%d" % i
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = self.process_text_fn(line[2])
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> else:
<del> for lang in self.supported_languages:
<del> lines = self._read_tsv(os.path.join(data_dir, f"dev-{lang}.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = f"dev-{lang}-{i}"
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = self.process_text_fn(line[2])
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del> def get_test_examples(self, data_dir):
<del> """See base class."""
<del> examples_by_lang = {}
<del> for lang in self.supported_languages:
<del> examples_by_lang[lang] = []
<del> lines = self._read_tsv(os.path.join(data_dir, f"test-{lang}.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = f"test-{lang}-{i}"
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = "0"
<del> examples_by_lang[lang].append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> if self.translated_data_dir is not None:
<del> for lang in self.supported_languages:
<del> if lang == "en":
<del> continue
<del> examples_by_lang[f"{lang}-en"] = []
<del> lines = self._read_tsv(
<del> os.path.join(self.translated_data_dir, "translate-test",
<del> f"test-{lang}-en-translated.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = f"test-{lang}-en-{i}"
<del> text_a = self.process_text_fn(line[2])
<del> text_b = self.process_text_fn(line[3])
<del> label = "0"
<del> examples_by_lang[f"{lang}-en"].append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples_by_lang
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["0", "1"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "XTREME-PAWS-X"
<del>
<del>
<del>class XtremeXnliProcessor(DataProcessor):
<del> """Processor for the XTREME XNLI data set."""
<del> supported_languages = [
<del> "ar", "bg", "de", "el", "en", "es", "fr", "hi", "ru", "sw", "th", "tr",
<del> "ur", "vi", "zh"
<del> ]
<del>
<del> def __init__(self,
<del> process_text_fn=tokenization.convert_to_unicode,
<del> translated_data_dir=None,
<del> only_use_en_dev=True):
<del> """See base class.
<del>
<del> Args:
<del> process_text_fn: See base class.
<del> translated_data_dir: If specified, will also include translated data in
<del> the training data.
<del> only_use_en_dev: If True, only use english dev data. Otherwise, use dev
<del> data from all languages.
<del> """
<del> super(XtremeXnliProcessor, self).__init__(process_text_fn)
<del> self.translated_data_dir = translated_data_dir
<del> self.only_use_en_dev = only_use_en_dev
<del>
<del> def get_train_examples(self, data_dir):
<del> """See base class."""
<del> lines = self._read_tsv(os.path.join(data_dir, "train-en.tsv"))
<del>
<del> examples = []
<del> if self.translated_data_dir is None:
<del> for i, line in enumerate(lines):
<del> guid = "train-%d" % i
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = self.process_text_fn(line[2])
<del> if label == self.process_text_fn("contradictory"):
<del> label = self.process_text_fn("contradiction")
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> else:
<del> for lang in self.supported_languages:
<del> lines = self._read_tsv(
<del> os.path.join(self.translated_data_dir, "translate-train",
<del> f"en-{lang}-translated.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = f"train-{lang}-{i}"
<del> text_a = self.process_text_fn(line[2])
<del> text_b = self.process_text_fn(line[3])
<del> label = self.process_text_fn(line[4])
<del> if label == self.process_text_fn("contradictory"):
<del> label = self.process_text_fn("contradiction")
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del> def get_dev_examples(self, data_dir):
<del> """See base class."""
<del> examples = []
<del> if self.only_use_en_dev:
<del> lines = self._read_tsv(os.path.join(data_dir, "dev-en.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = "dev-%d" % i
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = self.process_text_fn(line[2])
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> else:
<del> for lang in self.supported_languages:
<del> lines = self._read_tsv(os.path.join(data_dir, f"dev-{lang}.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = f"dev-{lang}-{i}"
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = self.process_text_fn(line[2])
<del> if label == self.process_text_fn("contradictory"):
<del> label = self.process_text_fn("contradiction")
<del> examples.append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del> def get_test_examples(self, data_dir):
<del> """See base class."""
<del> examples_by_lang = {}
<del> for lang in self.supported_languages:
<del> examples_by_lang[lang] = []
<del> lines = self._read_tsv(os.path.join(data_dir, f"test-{lang}.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = f"test-{lang}-{i}"
<del> text_a = self.process_text_fn(line[0])
<del> text_b = self.process_text_fn(line[1])
<del> label = "contradiction"
<del> examples_by_lang[lang].append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> if self.translated_data_dir is not None:
<del> for lang in self.supported_languages:
<del> if lang == "en":
<del> continue
<del> examples_by_lang[f"{lang}-en"] = []
<del> lines = self._read_tsv(
<del> os.path.join(self.translated_data_dir, "translate-test",
<del> f"test-{lang}-en-translated.tsv"))
<del> for i, line in enumerate(lines):
<del> guid = f"test-{lang}-en-{i}"
<del> text_a = self.process_text_fn(line[2])
<del> text_b = self.process_text_fn(line[3])
<del> label = "contradiction"
<del> examples_by_lang[f"{lang}-en"].append(
<del> InputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples_by_lang
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["contradiction", "entailment", "neutral"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "XTREME-XNLI"
<del>
<del>
<del>def convert_single_example(ex_index, example, label_list, max_seq_length,
<del> tokenizer):
<del> """Converts a single `InputExample` into a single `InputFeatures`."""
<del> label_map = {}
<del> if label_list:
<del> for (i, label) in enumerate(label_list):
<del> label_map[label] = i
<del>
<del> tokens_a = tokenizer.tokenize(example.text_a)
<del> tokens_b = None
<del> if example.text_b:
<del> tokens_b = tokenizer.tokenize(example.text_b)
<del>
<del> if tokens_b:
<del> # Modifies `tokens_a` and `tokens_b` in place so that the total
<del> # length is less than the specified length.
<del> # Account for [CLS], [SEP], [SEP] with "- 3"
<del> _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
<del> else:
<del> # Account for [CLS] and [SEP] with "- 2"
<del> if len(tokens_a) > max_seq_length - 2:
<del> tokens_a = tokens_a[0:(max_seq_length - 2)]
<del>
<del> seg_id_a = 0
<del> seg_id_b = 1
<del> seg_id_cls = 0
<del> seg_id_pad = 0
<del>
<del> # The convention in BERT is:
<del> # (a) For sequence pairs:
<del> # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
<del> # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
<del> # (b) For single sequences:
<del> # tokens: [CLS] the dog is hairy . [SEP]
<del> # type_ids: 0 0 0 0 0 0 0
<del> #
<del> # Where "type_ids" are used to indicate whether this is the first
<del> # sequence or the second sequence. The embedding vectors for `type=0` and
<del> # `type=1` were learned during pre-training and are added to the wordpiece
<del> # embedding vector (and position vector). This is not *strictly* necessary
<del> # since the [SEP] token unambiguously separates the sequences, but it makes
<del> # it easier for the model to learn the concept of sequences.
<del> #
<del> # For classification tasks, the first vector (corresponding to [CLS]) is
<del> # used as the "sentence vector". Note that this only makes sense because
<del> # the entire model is fine-tuned.
<del> tokens = []
<del> segment_ids = []
<del> tokens.append("[CLS]")
<del> segment_ids.append(seg_id_cls)
<del> for token in tokens_a:
<del> tokens.append(token)
<del> segment_ids.append(seg_id_a)
<del> tokens.append("[SEP]")
<del> segment_ids.append(seg_id_a)
<del>
<del> if tokens_b:
<del> for token in tokens_b:
<del> tokens.append(token)
<del> segment_ids.append(seg_id_b)
<del> tokens.append("[SEP]")
<del> segment_ids.append(seg_id_b)
<del>
<del> input_ids = tokenizer.convert_tokens_to_ids(tokens)
<del>
<del> # The mask has 1 for real tokens and 0 for padding tokens. Only real
<del> # tokens are attended to.
<del> input_mask = [1] * len(input_ids)
<del>
<del> # Zero-pad up to the sequence length.
<del> while len(input_ids) < max_seq_length:
<del> input_ids.append(0)
<del> input_mask.append(0)
<del> segment_ids.append(seg_id_pad)
<del>
<del> assert len(input_ids) == max_seq_length
<del> assert len(input_mask) == max_seq_length
<del> assert len(segment_ids) == max_seq_length
<del>
<del> label_id = label_map[example.label] if label_map else example.label
<del> if ex_index < 5:
<del> logging.info("*** Example ***")
<del> logging.info("guid: %s", (example.guid))
<del> logging.info("tokens: %s",
<del> " ".join([tokenization.printable_text(x) for x in tokens]))
<del> logging.info("input_ids: %s", " ".join([str(x) for x in input_ids]))
<del> logging.info("input_mask: %s", " ".join([str(x) for x in input_mask]))
<del> logging.info("segment_ids: %s", " ".join([str(x) for x in segment_ids]))
<del> logging.info("label: %s (id = %s)", example.label, str(label_id))
<del> logging.info("weight: %s", example.weight)
<del> logging.info("example_id: %s", example.example_id)
<del>
<del> feature = InputFeatures(
<del> input_ids=input_ids,
<del> input_mask=input_mask,
<del> segment_ids=segment_ids,
<del> label_id=label_id,
<del> is_real_example=True,
<del> weight=example.weight,
<del> example_id=example.example_id)
<del>
<del> return feature
<del>
<del>
<del>class AXgProcessor(DataProcessor):
<del> """Processor for the AXg dataset (SuperGLUE diagnostics dataset)."""
<del>
<del> def get_test_examples(self, data_dir):
<del> """See base class."""
<del> return self._create_examples(
<del> self._read_jsonl(os.path.join(data_dir, "AX-g.jsonl")), "test")
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["entailment", "not_entailment"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "AXg"
<del>
<del> def _create_examples(self, lines, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> examples = []
<del> for line in lines:
<del> guid = "%s-%s" % (set_type, self.process_text_fn(str(line["idx"])))
<del> text_a = self.process_text_fn(line["premise"])
<del> text_b = self.process_text_fn(line["hypothesis"])
<del> label = self.process_text_fn(line["label"])
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del>
<del>class BoolQProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the BoolQ dataset (SuperGLUE diagnostics dataset)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["True", "False"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "BoolQ"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "super_glue/boolq", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for example in dataset:
<del> guid = "%s-%s" % (set_type, self.process_text_fn(str(example["idx"])))
<del> text_a = self.process_text_fn(example["question"])
<del> text_b = self.process_text_fn(example["passage"])
<del> label = "False"
<del> if set_type != "test":
<del> label = self.get_labels()[example["label"]]
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del>
<del>class CBProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the CB dataset (SuperGLUE diagnostics dataset)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> return ["entailment", "neutral", "contradiction"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "CB"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> dataset = tfds.load(
<del> "super_glue/cb", split=set_type, try_gcs=True).as_numpy_iterator()
<del> examples = []
<del> for example in dataset:
<del> guid = "%s-%s" % (set_type, self.process_text_fn(str(example["idx"])))
<del> text_a = self.process_text_fn(example["premise"])
<del> text_b = self.process_text_fn(example["hypothesis"])
<del> label = "entailment"
<del> if set_type != "test":
<del> label = self.get_labels()[example["label"]]
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del>
<del>class SuperGLUERTEProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the RTE dataset (SuperGLUE version)."""
<del>
<del> def get_labels(self):
<del> """See base class."""
<del> # All datasets are converted to 2-class split, where for 3-class datasets we
<del> # collapse neutral and contradiction into not_entailment.
<del> return ["entailment", "not_entailment"]
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "RTESuperGLUE"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> examples = []
<del> dataset = tfds.load(
<del> "super_glue/rte", split=set_type, try_gcs=True).as_numpy_iterator()
<del> for example in dataset:
<del> guid = "%s-%s" % (set_type, self.process_text_fn(str(example["idx"])))
<del> text_a = self.process_text_fn(example["premise"])
<del> text_b = self.process_text_fn(example["hypothesis"])
<del> label = "entailment"
<del> if set_type != "test":
<del> label = self.get_labels()[example["label"]]
<del> examples.append(
<del> InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
<del> return examples
<del>
<del>
<del>class WiCInputExample(InputExample):
<del> """Processor for the WiC dataset (SuperGLUE version)."""
<del>
<del> def __init__(self,
<del> guid,
<del> text_a,
<del> text_b=None,
<del> label=None,
<del> word=None,
<del> weight=None,
<del> example_id=None):
<del> """A single training/test example for simple seq regression/classification."""
<del> super(WiCInputExample, self).__init__(guid, text_a, text_b, label, weight,
<del> example_id)
<del> self.word = word
<del>
<del>
<del>class WiCProcessor(DefaultGLUEDataProcessor):
<del> """Processor for the RTE dataset (SuperGLUE version)."""
<del>
<del> def get_labels(self):
<del> """Not used."""
<del> return []
<del>
<del> @staticmethod
<del> def get_processor_name():
<del> """See base class."""
<del> return "RTESuperGLUE"
<del>
<del> def _create_examples_tfds(self, set_type):
<del> """Creates examples for the training/dev/test sets."""
<del> examples = []
<del> dataset = tfds.load(
<del> "super_glue/wic", split=set_type, try_gcs=True).as_numpy_iterator()
<del> for example in dataset:
<del> guid = "%s-%s" % (set_type, self.process_text_fn(str(example["idx"])))
<del> text_a = self.process_text_fn(example["sentence1"])
<del> text_b = self.process_text_fn(example["sentence2"])
<del> word = self.process_text_fn(example["word"])
<del> label = 0
<del> if set_type != "test":
<del> label = example["label"]
<del> examples.append(
<del> WiCInputExample(
<del> guid=guid, text_a=text_a, text_b=text_b, word=word, label=label))
<del> return examples
<del>
<del> def featurize_example(self, ex_index, example, label_list, max_seq_length,
<del> tokenizer):
<del> """Here we concate sentence1, sentence2, word together with [SEP] tokens."""
<del> del label_list
<del> tokens_a = tokenizer.tokenize(example.text_a)
<del> tokens_b = tokenizer.tokenize(example.text_b)
<del> tokens_word = tokenizer.tokenize(example.word)
<del>
<del> # Modifies `tokens_a` and `tokens_b` in place so that the total
<del> # length is less than the specified length.
<del> # Account for [CLS], [SEP], [SEP], [SEP] with "- 4"
<del> # Here we only pop out the first two sentence tokens.
<del> _truncate_seq_pair(tokens_a, tokens_b,
<del> max_seq_length - 4 - len(tokens_word))
<del>
<del> seg_id_a = 0
<del> seg_id_b = 1
<del> seg_id_c = 2
<del> seg_id_cls = 0
<del> seg_id_pad = 0
<del>
<del> tokens = []
<del> segment_ids = []
<del> tokens.append("[CLS]")
<del> segment_ids.append(seg_id_cls)
<del> for token in tokens_a:
<del> tokens.append(token)
<del> segment_ids.append(seg_id_a)
<del> tokens.append("[SEP]")
<del> segment_ids.append(seg_id_a)
<del>
<del> for token in tokens_b:
<del> tokens.append(token)
<del> segment_ids.append(seg_id_b)
<del>
<del> tokens.append("[SEP]")
<del> segment_ids.append(seg_id_b)
<del>
<del> for token in tokens_word:
<del> tokens.append(token)
<del> segment_ids.append(seg_id_c)
<del>
<del> tokens.append("[SEP]")
<del> segment_ids.append(seg_id_c)
<del>
<del> input_ids = tokenizer.convert_tokens_to_ids(tokens)
<del>
<del> # The mask has 1 for real tokens and 0 for padding tokens. Only real
<del> # tokens are attended to.
<del> input_mask = [1] * len(input_ids)
<del>
<del> # Zero-pad up to the sequence length.
<del> while len(input_ids) < max_seq_length:
<del> input_ids.append(0)
<del> input_mask.append(0)
<del> segment_ids.append(seg_id_pad)
<del>
<del> assert len(input_ids) == max_seq_length
<del> assert len(input_mask) == max_seq_length
<del> assert len(segment_ids) == max_seq_length
<del>
<del> label_id = example.label
<del> if ex_index < 5:
<del> logging.info("*** Example ***")
<del> logging.info("guid: %s", (example.guid))
<del> logging.info("tokens: %s",
<del> " ".join([tokenization.printable_text(x) for x in tokens]))
<del> logging.info("input_ids: %s", " ".join([str(x) for x in input_ids]))
<del> logging.info("input_mask: %s", " ".join([str(x) for x in input_mask]))
<del> logging.info("segment_ids: %s", " ".join([str(x) for x in segment_ids]))
<del> logging.info("label: %s (id = %s)", example.label, str(label_id))
<del> logging.info("weight: %s", example.weight)
<del> logging.info("example_id: %s", example.example_id)
<del>
<del> feature = InputFeatures(
<del> input_ids=input_ids,
<del> input_mask=input_mask,
<del> segment_ids=segment_ids,
<del> label_id=label_id,
<del> is_real_example=True,
<del> weight=example.weight,
<del> example_id=example.example_id)
<del>
<del> return feature
<del>
<del>
<del>def file_based_convert_examples_to_features(examples,
<del> label_list,
<del> max_seq_length,
<del> tokenizer,
<del> output_file,
<del> label_type=None,
<del> featurize_fn=None):
<del> """Convert a set of `InputExample`s to a TFRecord file."""
<del>
<del> tf.io.gfile.makedirs(os.path.dirname(output_file))
<del> writer = tf.io.TFRecordWriter(output_file)
<del>
<del> for ex_index, example in enumerate(examples):
<del> if ex_index % 10000 == 0:
<del> logging.info("Writing example %d of %d", ex_index, len(examples))
<del>
<del> if featurize_fn:
<del> feature = featurize_fn(ex_index, example, label_list, max_seq_length,
<del> tokenizer)
<del> else:
<del> feature = convert_single_example(ex_index, example, label_list,
<del> max_seq_length, tokenizer)
<del>
<del> def create_int_feature(values):
<del> f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
<del> return f
<del>
<del> def create_float_feature(values):
<del> f = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
<del> return f
<del>
<del> features = collections.OrderedDict()
<del> features["input_ids"] = create_int_feature(feature.input_ids)
<del> features["input_mask"] = create_int_feature(feature.input_mask)
<del> features["segment_ids"] = create_int_feature(feature.segment_ids)
<del> if label_type is not None and label_type == float:
<del> features["label_ids"] = create_float_feature([feature.label_id])
<del> elif feature.label_id is not None:
<del> features["label_ids"] = create_int_feature([feature.label_id])
<del> features["is_real_example"] = create_int_feature(
<del> [int(feature.is_real_example)])
<del> if feature.weight is not None:
<del> features["weight"] = create_float_feature([feature.weight])
<del> if feature.example_id is not None:
<del> features["example_id"] = create_int_feature([feature.example_id])
<del> else:
<del> features["example_id"] = create_int_feature([ex_index])
<del>
<del> tf_example = tf.train.Example(features=tf.train.Features(feature=features))
<del> writer.write(tf_example.SerializeToString())
<del> writer.close()
<del>
<del>
<del>def _truncate_seq_pair(tokens_a, tokens_b, max_length):
<del> """Truncates a sequence pair in place to the maximum length."""
<del>
<del> # This is a simple heuristic which will always truncate the longer sequence
<del> # one token at a time. This makes more sense than truncating an equal percent
<del> # of tokens from each, since if one sequence is very short then each token
<del> # that's truncated likely contains more information than a longer sequence.
<del> while True:
<del> total_length = len(tokens_a) + len(tokens_b)
<del> if total_length <= max_length:
<del> break
<del> if len(tokens_a) > len(tokens_b):
<del> tokens_a.pop()
<del> else:
<del> tokens_b.pop()
<del>
<del>
<del>def generate_tf_record_from_data_file(processor,
<del> data_dir,
<del> tokenizer,
<del> train_data_output_path=None,
<del> eval_data_output_path=None,
<del> test_data_output_path=None,
<del> max_seq_length=128):
<del> """Generates and saves training data into a tf record file.
<del>
<del> Args:
<del> processor: Input processor object to be used for generating data. Subclass
<del> of `DataProcessor`.
<del> data_dir: Directory that contains train/eval/test data to process.
<del> tokenizer: The tokenizer to be applied on the data.
<del> train_data_output_path: Output to which processed tf record for training
<del> will be saved.
<del> eval_data_output_path: Output to which processed tf record for evaluation
<del> will be saved.
<del> test_data_output_path: Output to which processed tf record for testing
<del> will be saved. Must be a pattern template with {} if processor has
<del> language specific test data.
<del> max_seq_length: Maximum sequence length of the to be generated
<del> training/eval data.
<del>
<del> Returns:
<del> A dictionary containing input meta data.
<del> """
<del> assert train_data_output_path or eval_data_output_path
<del>
<del> label_list = processor.get_labels()
<del> label_type = getattr(processor, "label_type", None)
<del> is_regression = getattr(processor, "is_regression", False)
<del> has_sample_weights = getattr(processor, "weight_key", False)
<del>
<del> num_training_data = 0
<del> if train_data_output_path:
<del> train_input_data_examples = processor.get_train_examples(data_dir)
<del> file_based_convert_examples_to_features(train_input_data_examples,
<del> label_list, max_seq_length,
<del> tokenizer, train_data_output_path,
<del> label_type,
<del> processor.featurize_example)
<del> num_training_data = len(train_input_data_examples)
<del>
<del> if eval_data_output_path:
<del> eval_input_data_examples = processor.get_dev_examples(data_dir)
<del> file_based_convert_examples_to_features(eval_input_data_examples,
<del> label_list, max_seq_length,
<del> tokenizer, eval_data_output_path,
<del> label_type,
<del> processor.featurize_example)
<del>
<del> meta_data = {
<del> "processor_type": processor.get_processor_name(),
<del> "train_data_size": num_training_data,
<del> "max_seq_length": max_seq_length,
<del> }
<del>
<del> if test_data_output_path:
<del> test_input_data_examples = processor.get_test_examples(data_dir)
<del> if isinstance(test_input_data_examples, dict):
<del> for language, examples in test_input_data_examples.items():
<del> file_based_convert_examples_to_features(
<del> examples, label_list, max_seq_length, tokenizer,
<del> test_data_output_path.format(language), label_type,
<del> processor.featurize_example)
<del> meta_data["test_{}_data_size".format(language)] = len(examples)
<del> else:
<del> file_based_convert_examples_to_features(test_input_data_examples,
<del> label_list, max_seq_length,
<del> tokenizer, test_data_output_path,
<del> label_type,
<del> processor.featurize_example)
<del> meta_data["test_data_size"] = len(test_input_data_examples)
<del>
<del> if is_regression:
<del> meta_data["task_type"] = "bert_regression"
<del> meta_data["label_type"] = {int: "int", float: "float"}[label_type]
<del> else:
<del> meta_data["task_type"] = "bert_classification"
<del> meta_data["num_labels"] = len(processor.get_labels())
<del> if has_sample_weights:
<del> meta_data["has_sample_weights"] = True
<del>
<del> if eval_data_output_path:
<del> meta_data["eval_data_size"] = len(eval_input_data_examples)
<del>
<del> return meta_data | 1 |
Javascript | Javascript | fix alert screen crash in android in rntester app | f898bb65fac3f26944cbe1c47b87c63b2cd10e03 | <ide><path>RNTester/js/examples/Alert/AlertExample.js
<ide> const {
<ide> View,
<ide> } = require('react-native');
<ide>
<del>const RNTesterBlock = require('../../components/RNTesterBlock');
<del>
<ide> // corporate ipsum > lorem ipsum
<ide> const alertMessage =
<ide> 'Credibly reintermediate next-generation potentialities after goal-oriented ' +
<ide> class SimpleAlertExampleBlock extends React.Component<Props> {
<ide> }
<ide> }
<ide>
<del>class AlertExample extends React.Component {
<del> static title = 'Alert';
<del>
<del> static description =
<del> 'Alerts display a concise and informative message ' +
<del> 'and prompt the user to make a decision.';
<del>
<del> render() {
<del> return (
<del> <RNTesterBlock title={'Alert'}>
<del> <SimpleAlertExampleBlock />
<del> </RNTesterBlock>
<del> );
<del> }
<del>}
<del>
<ide> const styles = StyleSheet.create({
<ide> wrapper: {
<ide> borderRadius: 5,
<ide> const styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>module.exports = {
<del> AlertExample,
<del> SimpleAlertExampleBlock,
<del>};
<add>exports.title = 'Alert';
<add>exports.description =
<add> 'Alerts display a concise and informative message ' +
<add> 'and prompt the user to make a decision.';
<add>exports.examples = [
<add> {
<add> title: 'Alerts',
<add> render(): React.Node {
<add> return <SimpleAlertExampleBlock />;
<add> },
<add> },
<add>];
<add>
<add>exports.SimpleAlertExampleBlock = SimpleAlertExampleBlock;
<ide><path>RNTester/js/utils/RNTesterList.android.js
<ide> const APIExamples: Array<RNTesterExample> = [
<ide> },
<ide> {
<ide> key: 'AlertExample',
<del> module: require('../examples/Alert/AlertExample').AlertExample,
<add> module: require('../examples/Alert/AlertExample'),
<ide> },
<ide> {
<ide> key: 'AnimatedExample', | 2 |
Ruby | Ruby | remove delegate methods that are not used | a11882ce405878d61e7edb8e7553980605e167c9 | <ide><path>activerecord/lib/active_record/associations/join_dependency/join_association.rb
<ide> class JoinAssociation < JoinPart # :nodoc:
<ide>
<ide> attr_accessor :tables
<ide>
<del> delegate :options, :through_reflection, :source_reflection, :chain, :to => :reflection
<add> delegate :chain, :to => :reflection
<ide>
<ide> def initialize(reflection, index, join_type)
<ide> super(reflection.klass) | 1 |
Ruby | Ruby | show minitest options in test runner help | 47308ff32a869f493ca85f7c5a58a082c084f391 | <ide><path>railties/lib/minitest/rails_plugin.rb
<ide> require "active_support/core_ext/module/attribute_accessors"
<ide> require "rails/test_unit/reporter"
<add>require "rails/test_unit/runner"
<ide>
<ide> module Minitest
<ide> class SuppressedSummaryReporter < SummaryReporter
<ide> def aggregated_results(*)
<ide> end
<ide>
<ide> def self.plugin_rails_options(opts, options)
<add> Rails::TestUnit::Runner.attach_before_load_options(opts)
<add>
<ide> opts.on("-b", "--backtrace", "Show the complete backtrace") do
<ide> options[:full_backtrace] = true
<ide> end
<ide><path>railties/lib/rails/commands/test/test_command.rb
<ide> require_relative "../../command"
<ide> require_relative "../../test_unit/runner"
<add>require_relative "../../test_unit/reporter"
<ide>
<ide> module Rails
<ide> module Command
<ide> class TestCommand < Base # :nodoc:
<ide> no_commands do
<ide> def help
<del> require "optparse"
<del> require "minitest/rails_plugin"
<add> say "Usage: #{Rails::TestUnitReporter.executable} [options] [files or directories]"
<add> say ""
<add> say "You can run a single test by appending a line number to a filename:"
<add> say ""
<add> say " #{Rails::TestUnitReporter.executable} test/models/user_test.rb:27"
<add> say ""
<add> say "You can run multiple files and directories at the same time:"
<add> say ""
<add> say " #{Rails::TestUnitReporter.executable} test/controllers test/integration/login_test.rb"
<add> say ""
<add> say "By default test failures and errors are reported inline during a run."
<add> say ""
<ide>
<del> opts = OptionParser.new
<del> opts.banner = "Usage: #{Rails::TestUnitReporter.executable} [options] [files or directories]"
<del> opts.separator ""
<del> opts.separator "You can run a single test by appending a line number to a filename:"
<del> opts.separator ""
<del> opts.separator " #{Rails::TestUnitReporter.executable} test/models/user_test.rb:27"
<del> opts.separator ""
<del> opts.separator "You can run multiple files and directories at the same time:"
<del> opts.separator ""
<del> opts.separator " #{Rails::TestUnitReporter.executable} test/controllers test/integration/login_test.rb"
<del> opts.separator ""
<del> opts.separator "By default test failures and errors are reported inline during a run."
<del> opts.separator ""
<del>
<del> opts.separator "Rails options:"
<del> Rails::TestUnit::Runner.options(opts)
<del> Minitest.plugin_rails_options(opts, {})
<del>
<del> say opts
<add> Minitest.run(%w(--help))
<ide> end
<ide> end
<ide>
<ide><path>railties/lib/rails/test_unit/runner.rb
<ide> class Runner
<ide> mattr_reader :filters, default: []
<ide>
<ide> class << self
<del> def options(opts)
<add> def attach_before_load_options(opts)
<ide> opts.on("--warnings", "-w", "Run with Ruby warnings enabled") {}
<ide> opts.on("--environment", "-e", "Run tests in the ENV environment") {}
<ide> end | 3 |
Ruby | Ruby | add html-scanner to the new base set of autoloads | 7dd094329eee01cf9d18e4141226357eb8f75c76 | <ide><path>actionpack/lib/action_controller/new_base.rb
<ide> module ActionController
<ide> require 'action_controller/routing'
<ide> end
<ide>
<add>autoload :HTML, 'action_controller/vendor/html-scanner'
<add>
<ide> require 'action_dispatch'
<ide> require 'action_view' | 1 |
Javascript | Javascript | avoid .tolowercase() call in buffer#write() | 4ddd6406ce1c474e1a54a5aa9b56f7554902fd10 | <ide><path>lib/buffer.js
<ide> Buffer.prototype.write = function(string, offset, length, encoding) {
<ide> if (length === undefined || length > remaining)
<ide> length = remaining;
<ide>
<del> encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
<del>
<ide> if (string.length > 0 && (length < 0 || offset < 0))
<ide> throw new RangeError('attempt to write outside buffer bounds');
<ide>
<del> var ret;
<del> switch (encoding) {
<del> case 'hex':
<del> ret = this.hexWrite(string, offset, length);
<del> break;
<add> if (!encoding)
<add> encoding = 'utf8';
<ide>
<del> case 'utf8':
<del> case 'utf-8':
<del> ret = this.utf8Write(string, offset, length);
<del> break;
<add> var loweredCase = false;
<add> for (;;) {
<add> switch (encoding) {
<add> case 'hex':
<add> return this.hexWrite(string, offset, length);
<ide>
<del> case 'ascii':
<del> ret = this.asciiWrite(string, offset, length);
<del> break;
<add> case 'utf8':
<add> case 'utf-8':
<add> return this.utf8Write(string, offset, length);
<ide>
<del> case 'binary':
<del> ret = this.binaryWrite(string, offset, length);
<del> break;
<add> case 'ascii':
<add> return this.asciiWrite(string, offset, length);
<ide>
<del> case 'base64':
<del> // Warning: maxLength not taken into account in base64Write
<del> ret = this.base64Write(string, offset, length);
<del> break;
<add> case 'binary':
<add> return this.binaryWrite(string, offset, length);
<ide>
<del> case 'ucs2':
<del> case 'ucs-2':
<del> case 'utf16le':
<del> case 'utf-16le':
<del> ret = this.ucs2Write(string, offset, length);
<del> break;
<add> case 'base64':
<add> // Warning: maxLength not taken into account in base64Write
<add> return this.base64Write(string, offset, length);
<ide>
<del> default:
<del> throw new TypeError('Unknown encoding: ' + encoding);
<del> }
<add> case 'ucs2':
<add> case 'ucs-2':
<add> case 'utf16le':
<add> case 'utf-16le':
<add> return this.ucs2Write(string, offset, length);
<ide>
<del> return ret;
<add> default:
<add> if (loweredCase)
<add> throw new TypeError('Unknown encoding: ' + encoding);
<add> encoding = ('' + encoding).toLowerCase();
<add> loweredCase = true;
<add> }
<add> }
<ide> };
<ide>
<ide> | 1 |
Ruby | Ruby | remove duplicate method | a7e8fe4d6e3f18eb3431e9fc95b42542ae2946fb | <ide><path>test/controllers/ingresses/sendgrid/inbound_emails_controller_test.rb
<ide> class ActionMailbox::Ingresses::Sendgrid::InboundEmailsControllerTest < ActionDi
<ide> end
<ide> end
<ide> end
<del>
<del> private
<del> def credentials
<del> ActionController::HttpAuthentication::Basic.encode_credentials "actionmailbox", ENV["RAILS_INBOUND_EMAIL_PASSWORD"]
<del> end
<ide> end | 1 |
PHP | PHP | remove unused use statements | 02d3a0d583eef4bcec3b1150bb072b722a6c689a | <ide><path>src/Illuminate/Foundation/Console/ChannelMakeCommand.php
<ide> namespace Illuminate\Foundation\Console;
<ide>
<ide> use Illuminate\Console\GeneratorCommand;
<del>use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> class ChannelMakeCommand extends GeneratorCommand
<ide> { | 1 |
PHP | PHP | add test for | 3ad0c5d850a7685952d437e1c432db44edce0073 | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testYear()
<ide> $this->assertContains('Published on', $result);
<ide> }
<ide>
<add> /**
<add> * Test minYear being prior to the unix epoch
<add> *
<add> * @return void
<add> */
<add> public function testInputDatetimePreEpoch()
<add> {
<add> $start = date('Y') - 80;
<add> $end = date('Y') - 18;
<add> $result = $this->Form->input('birth_year', [
<add> 'type' => 'date',
<add> 'label' => 'Birth Year',
<add> 'minYear' => $start,
<add> 'maxYear' => $end,
<add> 'month' => false,
<add> 'day' => false,
<add> ]);
<add> $this->assertContains('value="' . $start . '">' . $start, $result);
<add> $this->assertContains('value="' . $end . '" selected="selected">' . $end, $result);
<add> $this->assertNotContains('value="00">00', $result);
<add> }
<add>
<ide> /**
<ide> * testYearAutoExpandRange method
<ide> * | 1 |
Java | Java | add support for http options in spring mvc test | a56d8f28fe3c434d04d92ec6cd7ff60848cf8a2e | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java
<ide> public abstract class MockMvcBuilderSupport {
<ide>
<ide> protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
<ide> WebApplicationContext webAppContext, RequestBuilder defaultRequestBuilder,
<del> List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers) {
<add> List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers, Boolean dispatchOptions) {
<ide>
<ide> ServletContext servletContext = webAppContext.getServletContext();
<ide>
<ide> TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
<add> dispatcherServlet.setDispatchOptionsRequest(dispatchOptions);
<ide> try {
<ide> dispatcherServlet.init(servletConfig);
<ide> }
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java
<ide> public static MockHttpServletRequestBuilder delete(String urlTemplate, Object...
<ide> return new MockHttpServletRequestBuilder(HttpMethod.DELETE, urlTemplate, urlVariables);
<ide> }
<ide>
<add> /**
<add> * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request.
<add> *
<add> * @param urlTemplate a URL template; the resulting URL will be encoded
<add> * @param urlVariables zero or more URL variables
<add> */
<add> public static MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables) {
<add> return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, urlTemplate, urlVariables);
<add> }
<add>
<add>
<ide> /**
<ide> * Create a {@link MockHttpServletRequestBuilder} for a request with the given HTTP method.
<ide> *
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java
<ide> import org.springframework.test.web.servlet.ResultMatcher;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.context.WebApplicationContext;
<add>import org.springframework.web.servlet.DispatcherServlet;
<ide>
<ide> /**
<ide> * An concrete implementation of {@link MockMvcBuilder} with methods for
<ide> private final List<ResultMatcher> globalResultMatchers = new ArrayList<ResultMatcher>();
<ide>
<ide> private final List<ResultHandler> globalResultHandlers = new ArrayList<ResultHandler>();
<add>
<add> private Boolean dispatchOptions = Boolean.FALSE;
<ide>
<ide>
<ide> /**
<ide> public final <T extends Self> T alwaysDo(ResultHandler resultHandler) {
<ide> this.globalResultHandlers.add(resultHandler);
<ide> return (T) this;
<ide> }
<add>
<add> /**
<add> * Should the {@link DispatcherServlet} dispatch OPTIONS request to controllers.
<add> * @param dispatchOptions
<add> * @see {@link DispatcherServlet#setDispatchOptionsRequest(boolean)}
<add> */
<add> @SuppressWarnings("unchecked")
<add> public final <T extends Self> T dispatchOptions(boolean dispatchOptions) {
<add> this.dispatchOptions = dispatchOptions;
<add> return (T) this;
<add> }
<ide>
<ide> /**
<ide> * Build a {@link MockMvc} instance.
<ide> public final MockMvc build() {
<ide> Filter[] filterArray = this.filters.toArray(new Filter[this.filters.size()]);
<ide>
<ide> return super.createMockMvc(filterArray, mockServletConfig, this.webAppContext,
<del> this.defaultRequestBuilder, this.globalResultMatchers, this.globalResultHandlers);
<add> this.defaultRequestBuilder, this.globalResultMatchers, this.globalResultHandlers,this.dispatchOptions);
<ide> }
<ide>
<ide> /**
<ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java
<add>/*
<add> * Copyright 2002-2013 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>package org.springframework.test.web.servlet;
<add>
<add>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
<add>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
<add>import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
<add>
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import org.junit.Assert;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>import org.springframework.stereotype.Controller;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<add>import org.springframework.test.context.web.WebAppConfiguration;
<add>import org.springframework.web.bind.annotation.RequestMapping;
<add>import org.springframework.web.bind.annotation.RequestMethod;
<add>import org.springframework.web.bind.annotation.ResponseBody;
<add>import org.springframework.web.context.WebApplicationContext;
<add>import org.springframework.web.servlet.config.annotation.EnableWebMvc;
<add>import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
<add>
<add>/**
<add> * Tests for SPR-10093 (support for OPTIONS requests).
<add> * @author Arnaud Cogoluègnes
<add> */
<add>@RunWith(SpringJUnit4ClassRunner.class)
<add>@WebAppConfiguration
<add>@ContextConfiguration
<add>public class Spr10093Tests {
<add>
<add> @Autowired
<add> private WebApplicationContext wac;
<add>
<add> private MockMvc mockMvc;
<add>
<add> @Before
<add> public void setup() {
<add> this.mockMvc = webAppContextSetup(this.wac).dispatchOptions(true).build();
<add> }
<add>
<add> @Test
<add> public void test() throws Exception {
<add> MyController controller = this.wac.getBean(MyController.class);
<add> int initialCount = controller.counter.get();
<add> this.mockMvc.perform(options("/myUrl")).andExpect(status().isOk());
<add>
<add> Assert.assertEquals(initialCount+1,controller.counter.get());
<add> }
<add>
<add>
<add> @Configuration
<add> @EnableWebMvc
<add> static class WebConfig extends WebMvcConfigurerAdapter {
<add>
<add> @Bean
<add> public MyController myController() {
<add> return new MyController();
<add> }
<add> }
<add>
<add> @Controller
<add> private static class MyController {
<add>
<add> private AtomicInteger counter = new AtomicInteger(0);
<add>
<add> @RequestMapping(value="/myUrl",method=RequestMethod.OPTIONS)
<add> @ResponseBody
<add> public void handle() {
<add> counter.incrementAndGet();
<add> }
<add> }
<add>
<add>
<add>} | 4 |
Javascript | Javascript | improve labels for times that round to 0.0ms | 60511aadc065d49d0b83578c8983b4447de45abb | <ide><path>src/devtools/views/Profiler/FlamegraphChartBuilder.js
<ide> // @flow
<ide>
<del>import { calculateSelfDuration } from './utils';
<add>import { calculateSelfDuration, fineTune } from './utils';
<ide>
<ide> import type { CommitDetailsFrontend, CommitTreeFrontend } from './types';
<ide>
<ide> export function getChartData({
<ide>
<ide> let label = `${name}${maybeKey}`;
<ide> if (didRender) {
<del> label += ` (${selfDuration.toFixed(1)}ms of ${actualDuration.toFixed(
<del> 1
<add> label += ` (${fineTune(selfDuration.toFixed(1))}ms of ${fineTune(
<add> actualDuration.toFixed(1)
<ide> )}ms)`;
<ide> }
<ide>
<ide><path>src/devtools/views/Profiler/RankedChartBuilder.js
<ide> // @flow
<ide>
<del>import { calculateSelfDuration } from './utils';
<add>import { calculateSelfDuration, fineTune } from './utils';
<ide>
<ide> import type { CommitDetailsFrontend, CommitTreeFrontend } from './types';
<ide>
<ide> export function getChartData({
<ide> if (node.parentID === 0) {
<ide> return;
<ide> }
<del>
<ide> const selfDuration = calculateSelfDuration(id, commitTree, commitDetails);
<ide> maxSelfDuration = Math.max(maxSelfDuration, selfDuration);
<ide>
<ide> const name = node.displayName || 'Unknown';
<ide> const maybeKey = node.key !== null ? ` key="${node.key}"` : '';
<del> const label = `${name}${maybeKey} (${selfDuration.toFixed(1)}ms)`;
<add> const label = `${name}${maybeKey} (${fineTune(selfDuration.toFixed(1))}ms)`;
<ide> chartNodes.push({
<ide> id,
<ide> label,
<ide><path>src/devtools/views/Profiler/SidebarSelectedFiberInfo.js
<ide>
<ide> import React, { Fragment, useContext } from 'react';
<ide> import { ProfilerContext } from './ProfilerContext';
<del>import { formatDuration, formatTime } from './utils';
<add>import { formatDuration, formatTime, fineTune } from './utils';
<ide> import { StoreContext } from '../context';
<ide> import Button from '../Button';
<ide> import ButtonIcon from '../ButtonIcon';
<ide> export default function SidebarSelectedFiberInfo(_: Props) {
<ide> }
<ide> onClick={() => selectCommitIndex(commitIndex)}
<ide> >
<del> {formatTime(time)}s for {formatDuration(duration)}ms
<add> {fineTune(formatTime(time))}s for {fineTune(formatDuration(duration))}ms
<ide> </button>
<ide> );
<ide> }
<ide><path>src/devtools/views/Profiler/utils.js
<ide> export const scale = (
<ide> maxValue - minValue === 0
<ide> ? fallbackValue
<ide> : ((value - minValue) / (maxValue - minValue)) * (maxRange - minRange);
<add>
<add>export const fineTune = (duration: number | string): string => {
<add> if (Number(duration) === 0) {
<add> return '<0.1';
<add> }
<add> return `${duration}`;
<add>}; | 4 |
Javascript | Javascript | remove stream pending code | a65296db2c544df91e0f6c8cbc8ff79691f870fe | <ide><path>lib/internal/quic/core.js
<ide> class QuicSession extends EventEmitter {
<ide> silentClose: false,
<ide> statelessReset: false,
<ide> stats: undefined,
<del> pendingStreams: new Set(),
<ide> streams: new Map(),
<ide> verifyErrorReason: undefined,
<ide> verifyErrorCode: undefined,
<ide> class QuicSession extends EventEmitter {
<ide> return;
<ide> state.destroyed = true;
<ide>
<del> // Destroy any pending streams immediately. These
<del> // are streams that have been created but have not
<del> // yet been assigned an internal handle.
<del> for (const stream of state.pendingStreams)
<del> stream.destroy(error);
<del>
<ide> // Destroy any remaining streams immediately.
<ide> for (const stream of state.streams.values())
<ide> stream.destroy(error);
<ide> function streamOnResume() {
<ide> }
<ide>
<ide> function streamOnPause() {
<del> if (!this.destroyed /* && !this.pending */)
<add> if (!this.destroyed)
<ide> this[kHandle].readStop();
<ide> }
<ide>
<ide> class QuicStream extends Duplex {
<ide> if (this.destroyed || state.closed)
<ide> return;
<ide>
<del> if (this.pending)
<del> return this.once('ready', () => this[kClose](family, code));
<del>
<ide> state.closed = true;
<ide>
<ide> state.aborted = this.readable || this.writable;
<ide> class QuicStream extends Duplex {
<ide> // TODO(@jasnell): Implement this later
<ide> }
<ide>
<del> get pending() {
<del> // The id is set in the kSetHandle function
<del> return this[kInternalState].id === undefined;
<del> }
<del>
<ide> get aborted() {
<ide> return this[kInternalState].aborted;
<ide> }
<ide> class QuicStream extends Duplex {
<ide> if (this.destroyed)
<ide> return; // TODO(addaleax): Can this happen?
<ide>
<del> // The stream should be corked while still pending
<del> // but just in case uncork
<del> // was called early, defer the actual write until the
<del> // ready event is emitted.
<del> if (this.pending) {
<del> return this.once('ready', () => {
<del> this[kWriteGeneric](writev, data, encoding, cb);
<del> });
<del> }
<del>
<ide> this[kUpdateTimer]();
<ide> const req = (writev) ?
<ide> writevGeneric(this, data, cb) :
<ide> class QuicStream extends Duplex {
<ide> // coming so that a fin stream packet can be
<ide> // sent.
<ide> _final(cb) {
<del> // The QuicStream should be corked while pending
<del> // so this shouldn't be called, but just in case
<del> // the stream was prematurely uncorked, defer the
<del> // operation until the ready event is emitted.
<del> if (this.pending)
<del> return this.once('ready', () => this._final(cb));
<del>
<ide> const handle = this[kHandle];
<ide> if (handle === undefined) {
<ide> cb();
<ide> class QuicStream extends Duplex {
<ide> }
<ide>
<ide> _read(nread) {
<del> if (this.pending)
<del> return this.once('ready', () => this._read(nread));
<del>
<ide> if (this.destroyed) { // TODO(addaleax): Can this happen?
<ide> this.push(null);
<ide> return;
<ide> class QuicStream extends Duplex {
<ide> else if (typeof fd !== 'number')
<ide> throw new ERR_INVALID_ARG_TYPE('fd', ['number', 'FileHandle'], fd);
<ide>
<del> if (this.pending) {
<del> return this.once('ready', () => {
<del> this.sendFD(fd, { offset, length }, ownsFd);
<del> });
<del> }
<del>
<ide> this[kUpdateTimer]();
<ide> this.ownsFd = ownsFd;
<ide>
<ide><path>test/parallel/test-quic-client-server.js
<ide> client.on('close', common.mustCall(onSocketClose.bind(client)));
<ide> assert(!stream.unidirectional);
<ide> assert(stream.clientInitiated);
<ide> assert(!stream.serverInitiated);
<del> assert(!stream.pending);
<ide>
<ide> const file = fs.createReadStream(__filename);
<ide> let data = ''; | 2 |
Go | Go | add tcp support for gelf log driver | e17f3511144b37855d56a009d7e7622029242d2d | <ide><path>daemon/logger/gelf/gelf.go
<ide> func New(info logger.Info) (logger.Logger, error) {
<ide> return nil, err
<ide> }
<ide>
<del> if address.Scheme == "tcp" {
<del> return nil, fmt.Errorf("gelf: TCP not yet implemented")
<del> }
<del>
<ide> // collect extra data for GELF message
<ide> hostname, err := info.Hostname()
<ide> if err != nil {
<ide> func New(info logger.Info) (logger.Logger, error) {
<ide> return nil, err
<ide> }
<ide>
<del> // create new gelfWriter
<del> gelfWriter, err := gelf.NewUDPWriter(address.String())
<add> var gelfWriter gelf.Writer
<add> if address.Scheme == "udp" {
<add> gelfWriter, err = newGELFUDPWriter(address.Host, info)
<add> if err != nil {
<add> return nil, err
<add> }
<add> } else if address.Scheme == "tcp" {
<add> gelfWriter, err = newGELFTCPWriter(address.Host, info)
<add> if err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<add> return &gelfLogger{
<add> writer: gelfWriter,
<add> info: info,
<add> hostname: hostname,
<add> rawExtra: rawExtra,
<add> }, nil
<add>}
<add>
<add>// create new TCP gelfWriter
<add>func newGELFTCPWriter(address string, info logger.Info) (gelf.Writer, error) {
<add> gelfWriter, err := gelf.NewTCPWriter(address)
<ide> if err != nil {
<del> return nil, fmt.Errorf("gelf: cannot connect to GELF endpoint: %s %v", address.String(), err)
<add> return nil, fmt.Errorf("gelf: cannot connect to GELF endpoint: %s %v", address, err)
<add> }
<add>
<add> if v, ok := info.Config["gelf-tcp-max-reconnect"]; ok {
<add> i, err := strconv.Atoi(v)
<add> if err != nil || i < 0 {
<add> return nil, fmt.Errorf("gelf-tcp-max-reconnect must be a positive integer")
<add> }
<add> gelfWriter.MaxReconnect = i
<add> }
<add>
<add> if v, ok := info.Config["gelf-tcp-reconnect-delay"]; ok {
<add> i, err := strconv.Atoi(v)
<add> if err != nil || i < 0 {
<add> return nil, fmt.Errorf("gelf-tcp-reconnect-delay must be a positive integer")
<add> }
<add> gelfWriter.ReconnectDelay = time.Duration(i)
<add> }
<add>
<add> return gelfWriter, nil
<add>}
<add>
<add>// create new UDP gelfWriter
<add>func newGELFUDPWriter(address string, info logger.Info) (gelf.Writer, error) {
<add> gelfWriter, err := gelf.NewUDPWriter(address)
<add> if err != nil {
<add> return nil, fmt.Errorf("gelf: cannot connect to GELF endpoint: %s %v", address, err)
<ide> }
<ide>
<ide> if v, ok := info.Config["gelf-compression-type"]; ok {
<ide> func New(info logger.Info) (logger.Logger, error) {
<ide> gelfWriter.CompressionLevel = val
<ide> }
<ide>
<del> return &gelfLogger{
<del> writer: gelfWriter,
<del> info: info,
<del> hostname: hostname,
<del> rawExtra: rawExtra,
<del> }, nil
<add> return gelfWriter, nil
<ide> }
<ide>
<ide> func (s *gelfLogger) Log(msg *logger.Message) error {
<ide><path>daemon/logger/gelf/gelf_test.go
<ide> package gelf
<ide>
<ide> import (
<add> "net"
<ide> "testing"
<add>
<add> "github.com/docker/docker/daemon/logger"
<ide> )
<ide>
<del>//Validate parseAddress
<add>// Validate parseAddress
<ide> func TestParseAddress(t *testing.T) {
<ide> url, err := parseAddress("udp://127.0.0.1:12201")
<ide> if err != nil {
<ide> func TestParseAddress(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>//Validate UDP options
<del>func TestUDPValidateLogOpt(t *testing.T) {
<del> err := ValidateLogOpt(map[string]string{
<del> "gelf-address": "udp://127.0.0.1:12201",
<del> "tag": "testtag",
<del> "labels": "testlabel",
<del> "env": "testenv",
<del> "env-regex": "testenv-regex",
<del> "gelf-compression-level": "9",
<del> "gelf-compression-type": "gzip",
<del> })
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> err = ValidateLogOpt(map[string]string{
<del> "gelf-address": "udp://127.0.0.1:12201",
<del> "gelf-compression-level": "ultra",
<del> "gelf-compression-type": "zlib",
<del> })
<del> if err == nil {
<del> t.Fatal("Expected compression level error")
<del> }
<del>
<del> err = ValidateLogOpt(map[string]string{
<del> "gelf-address": "udp://127.0.0.1:12201",
<del> "gelf-compression-type": "rar",
<del> })
<del> if err == nil {
<del> t.Fatal("Expected compression type error")
<del> }
<del>
<del> err = ValidateLogOpt(map[string]string{
<del> "invalid": "invalid",
<del> })
<del> if err == nil {
<del> t.Fatal("Expected unknown option error")
<del> }
<del>
<del> err = ValidateLogOpt(map[string]string{})
<del> if err == nil {
<del> t.Fatal("Expected required parameter error")
<del> }
<del>}
<del>
<del>//Validate TCP options
<add>// Validate TCP options
<ide> func TestTCPValidateLogOpt(t *testing.T) {
<ide> err := ValidateLogOpt(map[string]string{
<ide> "gelf-address": "tcp://127.0.0.1:12201",
<ide> func TestTCPValidateLogOpt(t *testing.T) {
<ide> t.Fatal("Expected TCP reconnect to be invalid for UDP")
<ide> }
<ide> }
<add>
<add>// Validate UDP options
<add>func TestUDPValidateLogOpt(t *testing.T) {
<add> err := ValidateLogOpt(map[string]string{
<add> "gelf-address": "udp://127.0.0.1:12201",
<add> "tag": "testtag",
<add> "labels": "testlabel",
<add> "env": "testenv",
<add> "env-regex": "testenv-regex",
<add> "gelf-compression-level": "9",
<add> "gelf-compression-type": "gzip",
<add> })
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> err = ValidateLogOpt(map[string]string{
<add> "gelf-address": "udp://127.0.0.1:12201",
<add> "gelf-compression-level": "ultra",
<add> "gelf-compression-type": "zlib",
<add> })
<add> if err == nil {
<add> t.Fatal("Expected compression level error")
<add> }
<add>
<add> err = ValidateLogOpt(map[string]string{
<add> "gelf-address": "udp://127.0.0.1:12201",
<add> "gelf-compression-type": "rar",
<add> })
<add> if err == nil {
<add> t.Fatal("Expected compression type error")
<add> }
<add>
<add> err = ValidateLogOpt(map[string]string{
<add> "invalid": "invalid",
<add> })
<add> if err == nil {
<add> t.Fatal("Expected unknown option error")
<add> }
<add>
<add> err = ValidateLogOpt(map[string]string{})
<add> if err == nil {
<add> t.Fatal("Expected required parameter error")
<add> }
<add>}
<add>
<add>// Validate newGELFTCPWriter
<add>func TestNewGELFTCPWriter(t *testing.T) {
<add> address := "127.0.0.1:0"
<add> tcpAddr, err := net.ResolveTCPAddr("tcp", address)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> listener, err := net.ListenTCP("tcp", tcpAddr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> url := "tcp://" + listener.Addr().String()
<add> info := logger.Info{
<add> Config: map[string]string{
<add> "gelf-address": url,
<add> "gelf-tcp-max-reconnect": "0",
<add> "gelf-tcp-reconnect-delay": "0",
<add> "tag": "{{.ID}}",
<add> },
<add> ContainerID: "12345678901234567890",
<add> }
<add>
<add> writer, err := newGELFTCPWriter(listener.Addr().String(), info)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> err = writer.Close()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> err = listener.Close()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>}
<add>
<add>// Validate newGELFUDPWriter
<add>func TestNewGELFUDPWriter(t *testing.T) {
<add> address := "127.0.0.1:0"
<add> info := logger.Info{
<add> Config: map[string]string{
<add> "gelf-address": "udp://127.0.0.1:0",
<add> "gelf-compression-level": "5",
<add> "gelf-compression-type": "gzip",
<add> },
<add> }
<add>
<add> writer, err := newGELFUDPWriter(address, info)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> writer.Close()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>}
<add>
<add>// Validate New for TCP
<add>func TestNewTCP(t *testing.T) {
<add> address := "127.0.0.1:0"
<add> tcpAddr, err := net.ResolveTCPAddr("tcp", address)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> listener, err := net.ListenTCP("tcp", tcpAddr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> url := "tcp://" + listener.Addr().String()
<add> info := logger.Info{
<add> Config: map[string]string{
<add> "gelf-address": url,
<add> "gelf-tcp-max-reconnect": "0",
<add> "gelf-tcp-reconnect-delay": "0",
<add> },
<add> ContainerID: "12345678901234567890",
<add> }
<add>
<add> logger, err := New(info)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> err = logger.Close()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> err = listener.Close()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>}
<add>
<add>// Validate New for UDP
<add>func TestNewUDP(t *testing.T) {
<add> info := logger.Info{
<add> Config: map[string]string{
<add> "gelf-address": "udp://127.0.0.1:0",
<add> "gelf-compression-level": "5",
<add> "gelf-compression-type": "gzip",
<add> },
<add> ContainerID: "12345678901234567890",
<add> }
<add>
<add> logger, err := New(info)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> err = logger.Close()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>} | 2 |
PHP | PHP | rmove useless use in commands | fef787ba94e20c0942274e68fa10ed84f91c8a2e | <ide><path>src/Illuminate/Database/Console/Migrations/StatusCommand.php
<ide> <?php namespace Illuminate\Database\Console\Migrations;
<ide>
<ide> use Illuminate\Database\Migrations\Migrator;
<del>use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> class StatusCommand extends BaseCommand {
<ide>
<ide><path>src/Illuminate/Foundation/Console/RouteCacheCommand.php
<ide> use Illuminate\Console\Command;
<ide> use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\Routing\RouteCollection;
<del>use Symfony\Component\Console\Input\InputOption;
<del>use Symfony\Component\Console\Input\InputArgument;
<ide>
<ide> class RouteCacheCommand extends Command {
<ide>
<ide><path>src/Illuminate/Foundation/Console/RouteClearCommand.php
<ide> <?php namespace Illuminate\Foundation\Console;
<ide>
<del>use Illuminate\Routing\Router;
<ide> use Illuminate\Console\Command;
<ide> use Illuminate\Filesystem\Filesystem;
<del>use Symfony\Component\Console\Input\InputOption;
<del>use Symfony\Component\Console\Input\InputArgument;
<ide>
<ide> class RouteClearCommand extends Command {
<ide> | 3 |
Python | Python | fix lint issues | c4f1c98572e756d378e56e118124901d49b1032c | <ide><path>rest_framework/fields.py
<ide> import re
<ide> import uuid
<ide>
<del>import django
<ide> from django.conf import settings
<ide> from django.core.exceptions import ValidationError as DjangoValidationError
<ide> from django.core.exceptions import ObjectDoesNotExist
<ide> from django.core.validators import RegexValidator, ip_address_validators
<del>from django.forms import (
<del> ImageField as DjangoImageField, FilePathField as DjangoFilePathField
<del>)
<add>from django.forms import ImageField as DjangoImageField
<ide> from django.utils import six, timezone
<ide> from django.utils.dateparse import parse_date, parse_datetime, parse_time
<ide> from django.utils.encoding import is_protected_type, smart_text | 1 |
Ruby | Ruby | allow context type when set body mail | c4639b77378675f16c28660f43a23f2805ee6392 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def collect_responses(headers)
<ide> yield(collector)
<ide> collector.responses
<ide> elsif headers[:body]
<del> [{
<del> body: headers.delete(:body),
<del> content_type: self.class.default[:content_type] || "text/plain"
<del> }]
<add> collect_responses_from_text(headers)
<ide> else
<ide> collect_responses_from_templates(headers)
<ide> end
<ide> end
<ide>
<add> def collect_responses_from_text(headers)
<add> [{
<add> body: headers.delete(:body),
<add> content_type: headers[:content_type] || self.class.default[:content_type] || "text/plain"
<add> }]
<add> end
<add>
<ide> def collect_responses_from_templates(headers)
<ide> templates_path = headers[:template_path] || self.class.mailer_name
<ide> templates_name = headers[:template_name] || action_name
<ide><path>actionmailer/test/base_test.rb
<ide> class BaseTest < ActiveSupport::TestCase
<ide> assert_equal("multipart/mixed", email.mime_type)
<ide> end
<ide>
<add> test "set mime type to text/html when attachment is inclued and body is set" do
<add> email = BaseMailer.attachment_with_content(body: "Hello there", content_type: "text/html")
<add> assert_equal("text/html", email.mime_type)
<add> end
<add>
<ide> test "adds the rendered template as part" do
<ide> email = BaseMailer.attachment_with_content
<ide> assert_equal(2, email.parts.length) | 2 |
Javascript | Javascript | add platformconfig to native animations and nodes | 4a227ce2ab3f8c181150461ab28b831979093db0 | <ide><path>Libraries/Animated/AnimatedEvent.js
<ide> const invariant = require('invariant');
<ide>
<ide> const {shouldUseNativeDriver} = require('./NativeAnimatedHelper');
<ide>
<add>import type {PlatformConfig} from './AnimatedPlatformConfig';
<add>
<ide> export type Mapping =
<ide> | {[key: string]: Mapping, ...}
<ide> | AnimatedValue
<ide> | AnimatedValueXY;
<ide> export type EventConfig = {
<ide> listener?: ?Function,
<ide> useNativeDriver: boolean,
<add> platformConfig?: PlatformConfig,
<ide> };
<ide>
<ide> function attachNativeEvent(
<ide> viewRef: any,
<ide> eventName: string,
<ide> argMapping: $ReadOnlyArray<?Mapping>,
<add> platformConfig: ?PlatformConfig,
<ide> ): {detach: () => void} {
<ide> // Find animated values in `argMapping` and create an array representing their
<ide> // key path inside the `nativeEvent` object. Ex.: ['contentOffset', 'x'].
<ide> const eventMappings = [];
<ide>
<ide> const traverse = (value, path) => {
<ide> if (value instanceof AnimatedValue) {
<del> value.__makeNative();
<add> value.__makeNative(platformConfig);
<ide>
<ide> eventMappings.push({
<ide> nativeEventPath: path,
<ide> class AnimatedEvent {
<ide> _listeners: Array<Function> = [];
<ide> _attachedEvent: ?{detach: () => void, ...};
<ide> __isNative: boolean;
<add> __platformConfig: ?PlatformConfig;
<ide>
<ide> constructor(argMapping: $ReadOnlyArray<?Mapping>, config: EventConfig) {
<ide> this._argMapping = argMapping;
<ide> class AnimatedEvent {
<ide> }
<ide> this._attachedEvent = null;
<ide> this.__isNative = shouldUseNativeDriver(config);
<add> this.__platformConfig = config.platformConfig;
<ide> }
<ide>
<ide> __addListener(callback: Function): void {
<ide> class AnimatedEvent {
<ide> viewRef,
<ide> eventName,
<ide> this._argMapping,
<add> this.__platformConfig,
<ide> );
<ide> }
<ide>
<ide><path>Libraries/Animated/AnimatedPlatformConfig.js
<add>/**
<add> * Copyright (c) Meta Platforms, Inc. and affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>export type PlatformConfig = {};
<ide><path>Libraries/Animated/animations/Animation.js
<ide> 'use strict';
<ide>
<ide> const NativeAnimatedHelper = require('../NativeAnimatedHelper');
<del>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide> import type AnimatedValue from '../nodes/AnimatedValue';
<ide>
<ide> export type EndResult = {finished: boolean, ...};
<ide> export type EndCallback = (result: EndResult) => void;
<ide> export type AnimationConfig = {
<ide> isInteraction?: boolean,
<ide> useNativeDriver: boolean,
<add> platformConfig?: PlatformConfig,
<ide> onComplete?: ?EndCallback,
<ide> iterations?: number,
<ide> };
<ide> class Animation {
<ide> startNativeAnimationWaitId,
<ide> );
<ide> try {
<del> animatedValue.__makeNative();
<add> const config = this.__getNativeAnimationConfig();
<add> animatedValue.__makeNative(config.platformConfig);
<ide> this.__nativeId = NativeAnimatedHelper.generateNewAnimationId();
<ide> NativeAnimatedHelper.API.startAnimatingNode(
<ide> this.__nativeId,
<ide> animatedValue.__getNativeTag(),
<del> this.__getNativeAnimationConfig(),
<add> config,
<ide> // $FlowFixMe[method-unbinding] added when improving typing for this parameters
<ide> this.__debouncedOnEnd.bind(this),
<ide> );
<ide><path>Libraries/Animated/animations/DecayAnimation.js
<ide> const Animation = require('./Animation');
<ide>
<ide> const {shouldUseNativeDriver} = require('../NativeAnimatedHelper');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide> import type AnimatedValue from '../nodes/AnimatedValue';
<ide> import type {AnimationConfig, EndCallback} from './Animation';
<ide>
<ide> class DecayAnimation extends Animation {
<ide> _onUpdate: (value: number) => void;
<ide> _animationFrame: any;
<ide> _useNativeDriver: boolean;
<add> _platformConfig: ?PlatformConfig;
<ide>
<ide> constructor(config: DecayAnimationConfigSingle) {
<ide> super();
<ide> this._deceleration = config.deceleration ?? 0.998;
<ide> this._velocity = config.velocity;
<ide> this._useNativeDriver = shouldUseNativeDriver(config);
<add> this._platformConfig = config.platformConfig;
<ide> this.__isInteraction = config.isInteraction ?? !this._useNativeDriver;
<ide> this.__iterations = config.iterations ?? 1;
<ide> }
<ide>
<ide> __getNativeAnimationConfig(): {|
<ide> deceleration: number,
<ide> iterations: number,
<add> platformConfig: ?PlatformConfig,
<ide> type: $TEMPORARY$string<'decay'>,
<ide> velocity: number,
<ide> |} {
<ide> class DecayAnimation extends Animation {
<ide> deceleration: this._deceleration,
<ide> velocity: this._velocity,
<ide> iterations: this.__iterations,
<add> platformConfig: this._platformConfig,
<ide> };
<ide> }
<ide>
<ide><path>Libraries/Animated/animations/SpringAnimation.js
<ide> const invariant = require('invariant');
<ide>
<ide> const {shouldUseNativeDriver} = require('../NativeAnimatedHelper');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide> import type {AnimationConfig, EndCallback} from './Animation';
<ide>
<ide> export type SpringAnimationConfig = {
<ide> class SpringAnimation extends Animation {
<ide> _onUpdate: (value: number) => void;
<ide> _animationFrame: any;
<ide> _useNativeDriver: boolean;
<add> _platformConfig: ?PlatformConfig;
<ide>
<ide> constructor(config: SpringAnimationConfigSingle) {
<ide> super();
<ide> class SpringAnimation extends Animation {
<ide> this._toValue = config.toValue;
<ide> this._delay = config.delay ?? 0;
<ide> this._useNativeDriver = shouldUseNativeDriver(config);
<add> this._platformConfig = config.platformConfig;
<ide> this.__isInteraction = config.isInteraction ?? !this._useNativeDriver;
<ide> this.__iterations = config.iterations ?? 1;
<ide>
<ide> class SpringAnimation extends Animation {
<ide> initialVelocity: number,
<ide> iterations: number,
<ide> mass: number,
<add> platformConfig: ?PlatformConfig,
<ide> overshootClamping: boolean,
<ide> restDisplacementThreshold: number,
<ide> restSpeedThreshold: number,
<ide> class SpringAnimation extends Animation {
<ide> initialVelocity: this._initialVelocity ?? this._lastVelocity,
<ide> toValue: this._toValue,
<ide> iterations: this.__iterations,
<add> platformConfig: this._platformConfig,
<ide> };
<ide> }
<ide>
<ide><path>Libraries/Animated/animations/TimingAnimation.js
<ide> const Animation = require('./Animation');
<ide>
<ide> const {shouldUseNativeDriver} = require('../NativeAnimatedHelper');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide> import type {AnimationConfig, EndCallback} from './Animation';
<ide>
<ide> export type TimingAnimationConfig = {
<ide> class TimingAnimation extends Animation {
<ide> _animationFrame: any;
<ide> _timeout: any;
<ide> _useNativeDriver: boolean;
<add> _platformConfig: ?PlatformConfig;
<ide>
<ide> constructor(config: TimingAnimationConfigSingle) {
<ide> super();
<ide> class TimingAnimation extends Animation {
<ide> this._delay = config.delay ?? 0;
<ide> this.__iterations = config.iterations ?? 1;
<ide> this._useNativeDriver = shouldUseNativeDriver(config);
<add> this._platformConfig = config.platformConfig;
<ide> this.__isInteraction = config.isInteraction ?? !this._useNativeDriver;
<ide> }
<ide>
<ide> class TimingAnimation extends Animation {
<ide> frames,
<ide> toValue: this._toValue,
<ide> iterations: this.__iterations,
<add> platformConfig: this._platformConfig,
<ide> };
<ide> }
<ide>
<ide><path>Libraries/Animated/nodes/AnimatedAddition.js
<ide> const AnimatedNode = require('./AnimatedNode');
<ide> const AnimatedValue = require('./AnimatedValue');
<ide> const AnimatedWithChildren = require('./AnimatedWithChildren');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide> import type {InterpolationConfigType} from './AnimatedInterpolation';
<ide>
<ide> class AnimatedAddition extends AnimatedWithChildren {
<ide> class AnimatedAddition extends AnimatedWithChildren {
<ide> this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
<ide> }
<ide>
<del> __makeNative() {
<del> this._a.__makeNative();
<del> this._b.__makeNative();
<del> super.__makeNative();
<add> __makeNative(platformConfig: ?PlatformConfig) {
<add> this._a.__makeNative(platformConfig);
<add> this._b.__makeNative(platformConfig);
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getValue(): number {
<ide><path>Libraries/Animated/nodes/AnimatedDiffClamp.js
<ide> const AnimatedNode = require('./AnimatedNode');
<ide> const AnimatedWithChildren = require('./AnimatedWithChildren');
<ide>
<ide> import type {InterpolationConfigType} from './AnimatedInterpolation';
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide>
<ide> class AnimatedDiffClamp extends AnimatedWithChildren {
<ide> _a: AnimatedNode;
<ide> class AnimatedDiffClamp extends AnimatedWithChildren {
<ide> this._value = this._lastValue = this._a.__getValue();
<ide> }
<ide>
<del> __makeNative() {
<del> this._a.__makeNative();
<del> super.__makeNative();
<add> __makeNative(platformConfig: ?PlatformConfig) {
<add> this._a.__makeNative(platformConfig);
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> interpolate(config: InterpolationConfigType): AnimatedInterpolation {
<ide><path>Libraries/Animated/nodes/AnimatedDivision.js
<ide> const AnimatedValue = require('./AnimatedValue');
<ide> const AnimatedWithChildren = require('./AnimatedWithChildren');
<ide>
<ide> import type {InterpolationConfigType} from './AnimatedInterpolation';
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide>
<ide> class AnimatedDivision extends AnimatedWithChildren {
<ide> _a: AnimatedNode;
<ide> class AnimatedDivision extends AnimatedWithChildren {
<ide> this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
<ide> }
<ide>
<del> __makeNative() {
<del> this._a.__makeNative();
<del> this._b.__makeNative();
<del> super.__makeNative();
<add> __makeNative(platformConfig: ?PlatformConfig) {
<add> this._a.__makeNative(platformConfig);
<add> this._b.__makeNative(platformConfig);
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getValue(): number {
<ide><path>Libraries/Animated/nodes/AnimatedInterpolation.js
<ide> const NativeAnimatedHelper = require('../NativeAnimatedHelper');
<ide> const invariant = require('invariant');
<ide> const normalizeColor = require('../../StyleSheet/normalizeColor');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<add>
<ide> type ExtrapolateType = 'extend' | 'identity' | 'clamp';
<ide>
<ide> export type InterpolationConfigType = {
<ide> class AnimatedInterpolation extends AnimatedWithChildren {
<ide> this._interpolation = createInterpolation(config);
<ide> }
<ide>
<del> __makeNative() {
<del> this._parent.__makeNative();
<del> super.__makeNative();
<add> __makeNative(platformConfig: ?PlatformConfig) {
<add> this._parent.__makeNative(platformConfig);
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getValue(): number | string {
<ide><path>Libraries/Animated/nodes/AnimatedModulo.js
<ide> const AnimatedNode = require('./AnimatedNode');
<ide> const AnimatedWithChildren = require('./AnimatedWithChildren');
<ide>
<ide> import type {InterpolationConfigType} from './AnimatedInterpolation';
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide>
<ide> class AnimatedModulo extends AnimatedWithChildren {
<ide> _a: AnimatedNode;
<ide> class AnimatedModulo extends AnimatedWithChildren {
<ide> this._modulus = modulus;
<ide> }
<ide>
<del> __makeNative() {
<del> this._a.__makeNative();
<del> super.__makeNative();
<add> __makeNative(platformConfig: ?PlatformConfig) {
<add> this._a.__makeNative(platformConfig);
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getValue(): number {
<ide><path>Libraries/Animated/nodes/AnimatedMultiplication.js
<ide> const AnimatedValue = require('./AnimatedValue');
<ide> const AnimatedWithChildren = require('./AnimatedWithChildren');
<ide>
<ide> import type {InterpolationConfigType} from './AnimatedInterpolation';
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide>
<ide> class AnimatedMultiplication extends AnimatedWithChildren {
<ide> _a: AnimatedNode;
<ide> class AnimatedMultiplication extends AnimatedWithChildren {
<ide> this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
<ide> }
<ide>
<del> __makeNative() {
<del> this._a.__makeNative();
<del> this._b.__makeNative();
<del> super.__makeNative();
<add> __makeNative(platformConfig: ?PlatformConfig) {
<add> this._a.__makeNative(platformConfig);
<add> this._b.__makeNative(platformConfig);
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getValue(): number {
<ide><path>Libraries/Animated/nodes/AnimatedNode.js
<ide> const NativeAnimatedHelper = require('../NativeAnimatedHelper');
<ide> const NativeAnimatedAPI = NativeAnimatedHelper.API;
<ide> const invariant = require('invariant');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<add>
<ide> type ValueListenerCallback = (state: {value: number, ...}) => mixed;
<ide>
<ide> let _uniqueId = 1;
<ide> let _uniqueId = 1;
<ide> // support them yet
<ide> class AnimatedNode {
<ide> _listeners: {[key: string]: ValueListenerCallback, ...};
<add> _platformConfig: ?PlatformConfig;
<ide> __nativeAnimatedValueListener: ?any;
<ide> __attach(): void {}
<ide> __detach(): void {
<ide> class AnimatedNode {
<ide> this._listeners = {};
<ide> }
<ide>
<del> __makeNative() {
<add> __makeNative(platformConfig: ?PlatformConfig) {
<ide> if (!this.__isNative) {
<ide> throw new Error('This node cannot be made a "native" animated node');
<ide> }
<ide>
<add> this._platformConfig = platformConfig;
<ide> if (this.hasListeners()) {
<ide> this._startListeningToNativeValueUpdates();
<ide> }
<ide> class AnimatedNode {
<ide>
<ide> if (this.__nativeTag == null) {
<ide> this.__nativeTag = nativeTag;
<del> NativeAnimatedHelper.API.createAnimatedNode(
<del> nativeTag,
<del> this.__getNativeConfig(),
<del> );
<add> const config = this.__getNativeConfig();
<add> if (this._platformConfig) {
<add> config.platformConfig = this._platformConfig;
<add> }
<add> NativeAnimatedHelper.API.createAnimatedNode(nativeTag, config);
<ide> this.__shouldUpdateListenersForNewNativeTag = true;
<ide> }
<ide>
<ide> class AnimatedNode {
<ide> toJSON(): any {
<ide> return this.__getValue();
<ide> }
<add>
<add> __getPlatformConfig(): ?PlatformConfig {
<add> return this._platformConfig;
<add> }
<add> __setPlatformConfig(platformConfig: ?PlatformConfig) {
<add> this._platformConfig = platformConfig;
<add> }
<ide> }
<ide>
<ide> module.exports = AnimatedNode;
<ide><path>Libraries/Animated/nodes/AnimatedProps.js
<ide> const ReactNative = require('../../Renderer/shims/ReactNative');
<ide>
<ide> const invariant = require('invariant');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<add>
<ide> class AnimatedProps extends AnimatedNode {
<ide> _props: Object;
<ide> _animatedView: any;
<ide> class AnimatedProps extends AnimatedNode {
<ide> this._callback();
<ide> }
<ide>
<del> __makeNative(): void {
<add> __makeNative(platformConfig: ?PlatformConfig): void {
<ide> if (!this.__isNative) {
<ide> this.__isNative = true;
<ide> for (const key in this._props) {
<ide> const value = this._props[key];
<ide> if (value instanceof AnimatedNode) {
<del> value.__makeNative();
<add> value.__makeNative(platformConfig);
<ide> }
<ide> }
<add>
<add> // Since this does not call the super.__makeNative, we need to store the
<add> // supplied platformConfig here, before calling __connectAnimatedView
<add> // where it will be needed to traverse the graph of attached values.
<add> super.__setPlatformConfig(platformConfig);
<add>
<ide> if (this._animatedView) {
<ide> this.__connectAnimatedView();
<ide> }
<ide> class AnimatedProps extends AnimatedNode {
<ide> for (const propKey in this._props) {
<ide> const value = this._props[propKey];
<ide> if (value instanceof AnimatedNode) {
<del> value.__makeNative();
<add> value.__makeNative(this.__getPlatformConfig());
<ide> propsConfig[propKey] = value.__getNativeTag();
<ide> }
<ide> }
<ide><path>Libraries/Animated/nodes/AnimatedStyle.js
<ide> const NativeAnimatedHelper = require('../NativeAnimatedHelper');
<ide>
<ide> const flattenStyle = require('../../StyleSheet/flattenStyle');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<add>
<ide> class AnimatedStyle extends AnimatedWithChildren {
<ide> _style: Object;
<ide>
<ide> class AnimatedStyle extends AnimatedWithChildren {
<ide> super.__detach();
<ide> }
<ide>
<del> __makeNative() {
<add> __makeNative(platformConfig: ?PlatformConfig) {
<ide> for (const key in this._style) {
<ide> const value = this._style[key];
<ide> if (value instanceof AnimatedNode) {
<del> value.__makeNative();
<add> value.__makeNative(platformConfig);
<ide> }
<ide> }
<del> super.__makeNative();
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getNativeConfig(): Object {
<ide> const styleConfig = {};
<ide> for (const styleKey in this._style) {
<ide> if (this._style[styleKey] instanceof AnimatedNode) {
<ide> const style = this._style[styleKey];
<del> style.__makeNative();
<add> style.__makeNative(this.__getPlatformConfig());
<ide> styleConfig[styleKey] = style.__getNativeTag();
<ide> }
<ide> // Non-animated styles are set using `setNativeProps`, no need
<ide><path>Libraries/Animated/nodes/AnimatedSubtraction.js
<ide> const AnimatedValue = require('./AnimatedValue');
<ide> const AnimatedWithChildren = require('./AnimatedWithChildren');
<ide>
<ide> import type {InterpolationConfigType} from './AnimatedInterpolation';
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide>
<ide> class AnimatedSubtraction extends AnimatedWithChildren {
<ide> _a: AnimatedNode;
<ide> class AnimatedSubtraction extends AnimatedWithChildren {
<ide> this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
<ide> }
<ide>
<del> __makeNative() {
<del> this._a.__makeNative();
<del> this._b.__makeNative();
<del> super.__makeNative();
<add> __makeNative(platformConfig: ?PlatformConfig) {
<add> this._a.__makeNative(platformConfig);
<add> this._b.__makeNative(platformConfig);
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getValue(): number {
<ide><path>Libraries/Animated/nodes/AnimatedTracking.js
<ide> const {
<ide> shouldUseNativeDriver,
<ide> } = require('../NativeAnimatedHelper');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide> import type {EndCallback} from '../animations/Animation';
<ide>
<ide> class AnimatedTracking extends AnimatedNode {
<ide> class AnimatedTracking extends AnimatedNode {
<ide> this.__attach();
<ide> }
<ide>
<del> __makeNative() {
<add> __makeNative(platformConfig: ?PlatformConfig) {
<ide> this.__isNative = true;
<del> this._parent.__makeNative();
<del> super.__makeNative();
<del> this._value.__makeNative();
<add> this._parent.__makeNative(platformConfig);
<add> super.__makeNative(platformConfig);
<add> this._value.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getValue(): Object {
<ide> class AnimatedTracking extends AnimatedNode {
<ide> // if we don't do this `update` method will get called. At that point it
<ide> // may be too late as it would mean the JS driver has already started
<ide> // updating node values
<del> this.__makeNative();
<add> let {platformConfig} = this._animationConfig;
<add> this.__makeNative(platformConfig);
<ide> }
<ide> }
<ide>
<ide><path>Libraries/Animated/nodes/AnimatedTransform.js
<ide> const AnimatedNode = require('./AnimatedNode');
<ide> const AnimatedWithChildren = require('./AnimatedWithChildren');
<ide> const NativeAnimatedHelper = require('../NativeAnimatedHelper');
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<add>
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> _transforms: $ReadOnlyArray<Object>;
<ide>
<ide> class AnimatedTransform extends AnimatedWithChildren {
<ide> this._transforms = transforms;
<ide> }
<ide>
<del> __makeNative() {
<add> __makeNative(platformConfig: ?PlatformConfig) {
<ide> this._transforms.forEach(transform => {
<ide> for (const key in transform) {
<ide> const value = transform[key];
<ide> if (value instanceof AnimatedNode) {
<del> value.__makeNative();
<add> value.__makeNative(platformConfig);
<ide> }
<ide> }
<ide> });
<del> super.__makeNative();
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __getValue(): $ReadOnlyArray<Object> {
<ide><path>Libraries/Animated/nodes/AnimatedWithChildren.js
<ide>
<ide> 'use strict';
<ide>
<add>import type {PlatformConfig} from '../AnimatedPlatformConfig';
<ide> const AnimatedNode = require('./AnimatedNode');
<ide> const NativeAnimatedHelper = require('../NativeAnimatedHelper');
<ide>
<ide> class AnimatedWithChildren extends AnimatedNode {
<ide> this._children = [];
<ide> }
<ide>
<del> __makeNative() {
<add> __makeNative(platformConfig: ?PlatformConfig) {
<ide> if (!this.__isNative) {
<ide> this.__isNative = true;
<ide> for (const child of this._children) {
<del> child.__makeNative();
<add> child.__makeNative(platformConfig);
<ide> NativeAnimatedHelper.API.connectAnimatedNodes(
<ide> this.__getNativeTag(),
<ide> child.__getNativeTag(),
<ide> );
<ide> }
<ide> }
<del> super.__makeNative();
<add> super.__makeNative(platformConfig);
<ide> }
<ide>
<ide> __addChild(child: AnimatedNode): void {
<ide> class AnimatedWithChildren extends AnimatedNode {
<ide> this._children.push(child);
<ide> if (this.__isNative) {
<ide> // Only accept "native" animated nodes as children
<del> child.__makeNative();
<add> child.__makeNative(this.__getPlatformConfig());
<ide> NativeAnimatedHelper.API.connectAnimatedNodes(
<ide> this.__getNativeTag(),
<ide> child.__getNativeTag(), | 19 |
Java | Java | add more @nullable parameters based on null usage | 1f28825f9da63a13aaf8940aadedcf81358dc506 | <ide><path>spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java
<ide> public void setWrappedInstance(Object object) {
<ide> * @param nestedPath the nested path of the object
<ide> * @param rootObject the root object at the top of the path
<ide> */
<del> public void setWrappedInstance(Object object, String nestedPath, Object rootObject) {
<add> public void setWrappedInstance(Object object, String nestedPath, @Nullable Object rootObject) {
<ide> this.wrappedObject = ObjectUtils.unwrapOptional(object);
<ide> Assert.notNull(this.wrappedObject, "Target object must not be null");
<ide> this.nestedPath = (nestedPath != null ? nestedPath : "");
<ide> public boolean isWritableProperty(String propertyName) {
<ide> return false;
<ide> }
<ide>
<del> private Object convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<?> requiredType,
<add> private Object convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue, Object newValue, Class<?> requiredType,
<ide> TypeDescriptor td) throws TypeMismatchException {
<ide> try {
<ide> return this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue, newValue, requiredType, td);
<ide> private Object convertIfNecessary(String propertyName, Object oldValue, Object n
<ide> }
<ide> }
<ide>
<del> protected Object convertForProperty(String propertyName, Object oldValue, Object newValue, TypeDescriptor td)
<add> protected Object convertForProperty(String propertyName, @Nullable Object oldValue, Object newValue, TypeDescriptor td)
<ide> throws TypeMismatchException {
<ide>
<ide> return convertIfNecessary(propertyName, oldValue, newValue, td.getType(), td);
<ide> private PropertyValue createDefaultPropertyValue(PropertyTokenHolder tokens) {
<ide> return new PropertyValue(tokens.canonicalName, defaultValue);
<ide> }
<ide>
<del> private Object newValue(Class<?> type, TypeDescriptor desc, String name) {
<add> private Object newValue(Class<?> type, @Nullable TypeDescriptor desc, String name) {
<ide> try {
<ide> if (type.isArray()) {
<ide> Class<?> componentType = type.getComponentType();
<ide><path>spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
<ide> public static void copyProperties(Object source, Object target, String... ignore
<ide> * @throws BeansException if the copying failed
<ide> * @see BeanWrapper
<ide> */
<del> private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)
<add> private static void copyProperties(Object source, Object target, @Nullable Class<?> editable, String... ignoreProperties)
<ide> throws BeansException {
<ide>
<ide> Assert.notNull(source, "Source must not be null");
<ide><path>spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.convert.Property;
<ide> import org.springframework.core.convert.TypeDescriptor;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public void setBeanInstance(Object object) {
<ide> }
<ide>
<ide> @Override
<del> public void setWrappedInstance(Object object, String nestedPath, Object rootObject) {
<add> public void setWrappedInstance(Object object, String nestedPath, @Nullable Object rootObject) {
<ide> super.setWrappedInstance(object, nestedPath, rootObject);
<ide> setIntrospectionClass(getWrappedClass());
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java
<ide> public SimplePropertyDescriptor(PropertyDescriptor original) throws Introspectio
<ide> PropertyDescriptorUtils.copyNonMethodProperties(original, this);
<ide> }
<ide>
<del> public SimplePropertyDescriptor(String propertyName, Method readMethod, Method writeMethod) throws IntrospectionException {
<add> public SimplePropertyDescriptor(String propertyName, @Nullable Method readMethod, Method writeMethod) throws IntrospectionException {
<ide> super(propertyName, null, null);
<ide> this.readMethod = readMethod;
<ide> this.writeMethod = writeMethod;
<ide> public SimpleIndexedPropertyDescriptor(IndexedPropertyDescriptor original) throw
<ide> PropertyDescriptorUtils.copyNonMethodProperties(original, this);
<ide> }
<ide>
<del> public SimpleIndexedPropertyDescriptor(String propertyName, Method readMethod, Method writeMethod,
<del> Method indexedReadMethod, Method indexedWriteMethod) throws IntrospectionException {
<add> public SimpleIndexedPropertyDescriptor(String propertyName, @Nullable Method readMethod, @Nullable Method writeMethod,
<add> @Nullable Method indexedReadMethod, Method indexedWriteMethod) throws IntrospectionException {
<ide>
<ide> super(propertyName, null, null, null, null);
<ide> this.readMethod = readMethod;
<ide><path>spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
<ide> public <T> T convertIfNecessary(
<ide> * @throws IllegalArgumentException if type conversion failed
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> public <T> T convertIfNecessary(String propertyName, @Nullable Object oldValue, Object newValue,
<add> public <T> T convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue, Object newValue,
<ide> @Nullable Class<T> requiredType, TypeDescriptor typeDescriptor) throws IllegalArgumentException {
<ide>
<ide> // Custom editor for this type?
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java
<ide> Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String be
<ide> * @see #resolveDependency(DependencyDescriptor, String, Set, TypeConverter)
<ide> */
<ide> @Nullable
<del> Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName) throws BeansException;
<add> Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException;
<ide>
<ide> /**
<ide> * Resolve the specified dependency against the beans defined in this factory.
<ide> Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String be
<ide> */
<ide> @Nullable
<ide> Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,
<del> Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException;
<add> @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException;
<ide>
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java
<ide> public class BeanExpressionContext {
<ide> private final Scope scope;
<ide>
<ide>
<del> public BeanExpressionContext(ConfigurableBeanFactory beanFactory, Scope scope) {
<add> public BeanExpressionContext(ConfigurableBeanFactory beanFactory, @Nullable Scope scope) {
<ide> Assert.notNull(beanFactory, "BeanFactory must not be null");
<ide> this.beanFactory = beanFactory;
<ide> this.scope = scope;
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java
<ide> public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single
<ide> * then removed once the BeanFactory completes its bootstrap phase.
<ide> * @since 2.5
<ide> */
<del> void setTempClassLoader(ClassLoader tempClassLoader);
<add> void setTempClassLoader(@Nullable ClassLoader tempClassLoader);
<ide>
<ide> /**
<ide> * Return the temporary ClassLoader to use for type matching purposes,
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/ConstructorArgumentValues.java
<ide> public ValueHolder getGenericArgumentValue(Class<?> requiredType, String require
<ide> * @return the ValueHolder for the argument, or {@code null} if none found
<ide> */
<ide> @Nullable
<del> public ValueHolder getGenericArgumentValue(@Nullable Class<?> requiredType, @Nullable String requiredName, Set<ValueHolder> usedValueHolders) {
<add> public ValueHolder getGenericArgumentValue(@Nullable Class<?> requiredType, @Nullable String requiredName, @Nullable Set<ValueHolder> usedValueHolders) {
<ide> for (ValueHolder valueHolder : this.genericArgumentValues) {
<ide> if (usedValueHolders != null && usedValueHolders.contains(valueHolder)) {
<ide> continue;
<ide> public ValueHolder getArgumentValue(int index, Class<?> requiredType, String req
<ide> * @return the ValueHolder for the argument, or {@code null} if none set
<ide> */
<ide> @Nullable
<del> public ValueHolder getArgumentValue(int index, @Nullable Class<?> requiredType, @Nullable String requiredName, Set<ValueHolder> usedValueHolders) {
<add> public ValueHolder getArgumentValue(int index, @Nullable Class<?> requiredType, @Nullable String requiredName, @Nullable Set<ValueHolder> usedValueHolders) {
<ide> Assert.isTrue(index >= 0, "Index must not be negative");
<ide> ValueHolder valueHolder = getIndexedArgumentValue(index, requiredType, requiredName);
<ide> if (valueHolder == null) {
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/TypedStringValue.java
<ide> public class TypedStringValue implements BeanMetadataElement {
<ide> * Create a new {@link TypedStringValue} for the given String value.
<ide> * @param value the String value
<ide> */
<del> public TypedStringValue(String value) {
<add> public TypedStringValue(@Nullable String value) {
<ide> setValue(value);
<ide> }
<ide>
<ide> public TypedStringValue(String value) {
<ide> * @param value the String value
<ide> * @param targetType the type to convert to
<ide> */
<del> public TypedStringValue(String value, Class<?> targetType) {
<add> public TypedStringValue(@Nullable String value, Class<?> targetType) {
<ide> setValue(value);
<ide> setTargetType(targetType);
<ide> }
<ide> public TypedStringValue(String value, Class<?> targetType) {
<ide> * @param value the String value
<ide> * @param targetTypeName the type to convert to
<ide> */
<del> public TypedStringValue(String value, String targetTypeName) {
<add> public TypedStringValue(@Nullable String value, String targetTypeName) {
<ide> setValue(value);
<ide> setTargetTypeName(targetTypeName);
<ide> }
<ide> public TypedStringValue(String value, String targetTypeName) {
<ide> * for example in BeanFactoryPostProcessors.
<ide> * @see PropertyPlaceholderConfigurer
<ide> */
<del> public void setValue(String value) {
<add> public void setValue(@Nullable String value) {
<ide> this.value = value;
<ide> }
<ide>
<ide> /**
<ide> * Return the String value.
<ide> */
<add> @Nullable
<ide> public String getValue() {
<ide> return this.value;
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/YamlProcessor.java
<ide>
<ide> import org.springframework.core.CollectionFactory;
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> protected final Map<String, Object> getFlattenedMap(Map<String, Object> source)
<ide> return result;
<ide> }
<ide>
<del> private void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, String path) {
<add> private void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, @Nullable String path) {
<ide> for (Entry<String, Object> entry : source.entrySet()) {
<ide> String key = entry.getKey();
<ide> if (StringUtils.hasText(path)) {
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java
<ide> public Problem(String message, Location location, ParseState parseState) {
<ide> * @param parseState the {@link ParseState} at the time of the error
<ide> * @param location the location within a bean configuration source that triggered the error
<ide> */
<del> public Problem(String message, Location location, ParseState parseState, @Nullable Throwable rootCause) {
<add> public Problem(String message, Location location, @Nullable ParseState parseState, @Nullable Throwable rootCause) {
<ide> Assert.notNull(message, "Message must not be null");
<ide> Assert.notNull(location, "Location must not be null");
<ide> this.message = message;
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/parsing/ReaderContext.java
<ide> package org.springframework.beans.factory.parsing;
<ide>
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * Context that gets passed along a bean definition reading process,
<ide> public void fatal(String message, Object source, Throwable ex) {
<ide> fatal(message, source, null, ex);
<ide> }
<ide>
<del> public void fatal(String message, Object source, ParseState parseState) {
<add> public void fatal(String message, Object source, @Nullable ParseState parseState) {
<ide> fatal(message, source, parseState, null);
<ide> }
<ide>
<del> public void fatal(String message, Object source, ParseState parseState, Throwable cause) {
<add> public void fatal(String message, Object source, @Nullable ParseState parseState, @Nullable Throwable cause) {
<ide> Location location = new Location(getResource(), source);
<ide> this.problemReporter.fatal(new Problem(message, location, parseState, cause));
<ide> }
<ide> public void error(String message, Object source) {
<ide> error(message, source, null, null);
<ide> }
<ide>
<del> public void error(String message, Object source, Throwable ex) {
<add> public void error(String message, Object source, @Nullable Throwable ex) {
<ide> error(message, source, null, ex);
<ide> }
<ide>
<del> public void error(String message, Object source, ParseState parseState) {
<add> public void error(String message, Object source, @Nullable ParseState parseState) {
<ide> error(message, source, parseState, null);
<ide> }
<ide>
<del> public void error(String message, Object source, ParseState parseState, Throwable cause) {
<add> public void error(String message, Object source, @Nullable ParseState parseState, @Nullable Throwable cause) {
<ide> Location location = new Location(getResource(), source);
<ide> this.problemReporter.error(new Problem(message, location, parseState, cause));
<ide> }
<ide> public void warning(String message, Object source) {
<ide> warning(message, source, null, null);
<ide> }
<ide>
<del> public void warning(String message, Object source, Throwable ex) {
<add> public void warning(String message, Object source, @Nullable Throwable ex) {
<ide> warning(message, source, null, ex);
<ide> }
<ide>
<del> public void warning(String message, Object source, ParseState parseState) {
<add> public void warning(String message, Object source, @Nullable ParseState parseState) {
<ide> warning(message, source, parseState, null);
<ide> }
<ide>
<del> public void warning(String message, Object source, ParseState parseState, Throwable cause) {
<add> public void warning(String message, Object source, @Nullable ParseState parseState, @Nullable Throwable cause) {
<ide> Location location = new Location(getResource(), source);
<ide> this.problemReporter.warning(new Problem(message, location, parseState, cause));
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
<ide> public Object configureBean(Object existingBean, String beanName) throws BeansEx
<ide> }
<ide>
<ide> @Override
<del> public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName) throws BeansException {
<add> public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException {
<ide> return resolveDependency(descriptor, requestingBeanName, null, null);
<ide> }
<ide>
<ide> public void destroyBean(Object existingBean) {
<ide> * @see #doCreateBean
<ide> */
<ide> @Override
<del> protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
<add> protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Creating instance of bean '" + beanName + "'");
<ide> }
<ide> protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass,
<ide> * @see #autowireConstructor
<ide> * @see #instantiateBean
<ide> */
<del> protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
<add> protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
<ide> // Make sure bean class is actually resolved at this point.
<ide> Class<?> beanClass = resolveBeanClass(mbd, beanName);
<ide>
<ide> protected BeanWrapper instantiateUsingFactoryMethod(
<ide> * @return a BeanWrapper for the new instance
<ide> */
<ide> protected BeanWrapper autowireConstructor(
<del> String beanName, RootBeanDefinition mbd, Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
<add> String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
<ide>
<ide> return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
<ide> public <T> T getBean(String name, Class<T> requiredType, Object... args) throws
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide> protected <T> T doGetBean(
<del> final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
<add> final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly)
<ide> throws BeansException {
<ide>
<ide> final String beanName = transformedBeanName(name);
<ide> public ClassLoader getBeanClassLoader() {
<ide> }
<ide>
<ide> @Override
<del> public void setTempClassLoader(ClassLoader tempClassLoader) {
<add> public void setTempClassLoader(@Nullable ClassLoader tempClassLoader) {
<ide> this.tempClassLoader = tempClassLoader;
<ide> }
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java
<ide>
<ide> import org.springframework.beans.factory.config.BeanDefinitionCustomizer;
<ide> import org.springframework.beans.factory.config.RuntimeBeanReference;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ObjectUtils;
<ide>
<ide> /**
<ide> public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName) {
<ide> * @param beanClassName the class name for the bean that the definition is being created for
<ide> * @param factoryMethodName the name of the method to use to construct the bean instance
<ide> */
<del> public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName, String factoryMethodName) {
<add> public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName, @Nullable String factoryMethodName) {
<ide> BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
<ide> builder.beanDefinition = new RootBeanDefinition();
<ide> builder.beanDefinition.setBeanClassName(beanClassName);
<ide> public static BeanDefinitionBuilder rootBeanDefinition(Class<?> beanClass) {
<ide> * @param beanClass the {@code Class} of the bean that the definition is being created for
<ide> * @param factoryMethodName the name of the method to use to construct the bean instance
<ide> */
<del> public static BeanDefinitionBuilder rootBeanDefinition(Class<?> beanClass, String factoryMethodName) {
<add> public static BeanDefinitionBuilder rootBeanDefinition(Class<?> beanClass, @Nullable String factoryMethodName) {
<ide> BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
<ide> builder.beanDefinition = new RootBeanDefinition();
<ide> builder.beanDefinition.setBeanClass(beanClass);
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java
<ide> protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String be
<ide>
<ide> @Override
<ide> protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner,
<del> Constructor<?> ctor, Object... args) {
<add> @Nullable Constructor<?> ctor, Object... args) {
<ide>
<ide> // Must generate CGLIB subclass...
<ide> return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java
<ide> protected Constructor<?> getUserDeclaredConstructor(Constructor<?> constructor)
<ide> * Template method for resolving the specified argument which is supposed to be autowired.
<ide> */
<ide> protected Object resolveAutowiredArgument(
<del> MethodParameter param, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) {
<add> MethodParameter param, String beanName, @Nullable Set<String> autowiredBeanNames, TypeConverter typeConverter) {
<ide>
<ide> if (InjectionPoint.class.isAssignableFrom(param.getParameterType())) {
<ide> InjectionPoint injectionPoint = currentInjectionPoint.get();
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
<ide> else if (candidateNames.length > 1) {
<ide>
<ide> @Override
<ide> public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,
<del> Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
<add> @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
<ide>
<ide> descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
<ide> if (Optional.class == descriptor.getDependencyType()) {
<ide> else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
<ide>
<ide> @Nullable
<ide> public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
<del> Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
<add> @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
<ide>
<ide> InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
<ide> try {
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java
<ide> protected boolean isDependent(String beanName, String dependentBeanName) {
<ide> return isDependent(beanName, dependentBeanName, null);
<ide> }
<ide>
<del> private boolean isDependent(String beanName, String dependentBeanName, Set<String> alreadySeen) {
<add> private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
<ide> if (alreadySeen != null && alreadySeen.contains(beanName)) {
<ide> return false;
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java
<ide> public RootBeanDefinition(@Nullable Class<?> beanClass, int autowireMode, boolea
<ide> * @param cargs the constructor argument values to apply
<ide> * @param pvs the property values to apply
<ide> */
<del> public RootBeanDefinition(@Nullable Class<?> beanClass, ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
<add> public RootBeanDefinition(@Nullable Class<?> beanClass, ConstructorArgumentValues cargs, @Nullable MutablePropertyValues pvs) {
<ide> super(cargs, pvs);
<ide> setBeanClass(beanClass);
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java
<ide> public Object run() {
<ide> * Instantiation should use the given constructor and parameters.
<ide> */
<ide> protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner,
<del> Constructor<?> ctor, Object... args) {
<add> @Nullable Constructor<?> ctor, Object... args) {
<ide>
<ide> throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java
<ide> public void initDefaults(Element root) {
<ide> * @see #populateDefaults(DocumentDefaultsDefinition, DocumentDefaultsDefinition, org.w3c.dom.Element)
<ide> * @see #getDefaults()
<ide> */
<del> public void initDefaults(Element root, BeanDefinitionParserDelegate parent) {
<add> public void initDefaults(Element root, @Nullable BeanDefinitionParserDelegate parent) {
<ide> populateDefaults(this.defaults, (parent != null ? parent.defaults : null), root);
<ide> this.readerContext.fireDefaultsRegistered(this.defaults);
<ide> }
<ide> public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
<ide> * {@link org.springframework.beans.factory.parsing.ProblemReporter}.
<ide> */
<ide> @Nullable
<del> public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
<add> public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
<ide> String id = ele.getAttribute(ID_ATTRIBUTE);
<ide> String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
<ide>
<ide> public void parseQualifierElement(Element ele, AbstractBeanDefinition bd) {
<ide> * Also used for constructor arguments, "propertyName" being null in this case.
<ide> */
<ide> @Nullable
<del> public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
<add> public Object parsePropertyValue(Element ele, BeanDefinition bd, @Nullable String propertyName) {
<ide> String elementName = (propertyName != null) ?
<ide> "<property> element for property '" + propertyName + "'" :
<ide> "<constructor-arg> element";
<ide> else if (subElement != null) {
<ide> }
<ide> }
<ide>
<del> public Object parsePropertySubElement(Element ele, BeanDefinition bd) {
<add> public Object parsePropertySubElement(Element ele, @Nullable BeanDefinition bd) {
<ide> return parsePropertySubElement(ele, bd, null);
<ide> }
<ide>
<ide> public Object parsePropertySubElement(Element ele, BeanDefinition bd) {
<ide> * {@code <value>} tag that might be created
<ide> */
<ide> @Nullable
<del> public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultValueType) {
<add> public Object parsePropertySubElement(Element ele, BeanDefinition bd, @Nullable String defaultValueType) {
<ide> if (!isDefaultNamespace(ele)) {
<ide> return parseNestedCustomElement(ele, bd);
<ide> }
<ide> public BeanDefinition parseCustomElement(Element ele) {
<ide> }
<ide>
<ide> @Nullable
<del> public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
<add> public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
<ide> String namespaceUri = getNamespaceURI(ele);
<ide> NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
<ide> if (handler == null) {
<ide> public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDe
<ide> }
<ide>
<ide> public BeanDefinitionHolder decorateBeanDefinitionIfRequired(
<del> Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) {
<add> Element ele, BeanDefinitionHolder definitionHolder, @Nullable BeanDefinition containingBd) {
<ide>
<ide> BeanDefinitionHolder finalDefinition = definitionHolder;
<ide>
<ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/JavaMailSenderImpl.java
<ide> public void testConnection() throws MessagingException {
<ide> * @throws org.springframework.mail.MailSendException
<ide> * in case of failure when sending a message
<ide> */
<del> protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
<add> protected void doSend(MimeMessage[] mimeMessages, @Nullable Object[] originalMessages) throws MailException {
<ide> Map<Object, Exception> failedMessages = new LinkedHashMap<>();
<ide> Transport transport = null;
<ide>
<ide><path>spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java
<ide> protected void createMimeMultiparts(MimeMessage mimeMessage, int multipartMode)
<ide> * will be added to (can be the same as the root multipart object, or an element
<ide> * nested underneath the root multipart element)
<ide> */
<del> protected final void setMimeMultiparts(@Nullable MimeMultipart root, MimeMultipart main) {
<add> protected final void setMimeMultiparts(@Nullable MimeMultipart root, @Nullable MimeMultipart main) {
<ide> this.rootMimeMultipart = root;
<ide> this.mimeMultipart = main;
<ide> }
<ide><path>spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerAccessor.java
<ide>
<ide> import org.springframework.context.ResourceLoaderAware;
<ide> import org.springframework.core.io.ResourceLoader;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.transaction.PlatformTransactionManager;
<ide> import org.springframework.transaction.TransactionException;
<ide> import org.springframework.transaction.TransactionStatus;
<ide> public void setTransactionManager(PlatformTransactionManager transactionManager)
<ide> }
<ide>
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> this.resourceLoader = resourceLoader;
<ide> }
<ide>
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
<ide> private void performCacheEvict(CacheOperationContext context, CacheEvictOperatio
<ide> }
<ide> }
<ide>
<del> private void logInvalidating(CacheOperationContext context, CacheEvictOperation operation, Object key) {
<add> private void logInvalidating(CacheOperationContext context, CacheEvictOperation operation, @Nullable Object key) {
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Invalidating " + (key != null ? "cache key [" + key + "]" : "entire cache") +
<ide> " for operation " + operation + " on method " + context.metadata.method);
<ide><path>spring-context/src/main/java/org/springframework/context/MessageSource.java
<ide> public interface MessageSource {
<ide> * otherwise the default message passed as a parameter
<ide> * @see java.text.MessageFormat
<ide> */
<del> String getMessage(String code, @Nullable Object[] args, String defaultMessage, Locale locale);
<add> String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);
<ide>
<ide> /**
<ide> * Try to resolve the message. Treat as an error if the message can't be found.
<ide><path>spring-context/src/main/java/org/springframework/context/ResourceLoaderAware.java
<ide>
<ide> import org.springframework.beans.factory.Aware;
<ide> import org.springframework.core.io.ResourceLoader;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * Interface to be implemented by any object that wishes to be notified of
<ide> public interface ResourceLoaderAware extends Aware {
<ide> * @see org.springframework.core.io.support.ResourcePatternResolver
<ide> * @see org.springframework.core.io.support.ResourcePatternUtils#getResourcePatternResolver
<ide> */
<del> void setResourceLoader(ResourceLoader resourceLoader);
<add> void setResourceLoader(@Nullable ResourceLoader resourceLoader);
<ide>
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/AnnotatedBeanDefinitionReader.java
<ide> public void registerBean(Class<?> annotatedClass, String name, Class<? extends A
<ide> * factory's {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
<ide> * @since 5.0
<ide> */
<del> <T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, String name,
<add> <T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
<ide> @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
<ide>
<ide> AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigApplicationContext.java
<ide> public <T> void registerBean(@Nullable String beanName, Class<T> annotatedClass,
<ide> }
<ide>
<ide> @Override
<del> public <T> void registerBean(@Nullable String beanName, @Nullable Class<T> beanClass, Supplier<T> supplier,
<add> public <T> void registerBean(@Nullable String beanName, @Nullable Class<T> beanClass, @Nullable Supplier<T> supplier,
<ide> BeanDefinitionCustomizer... customizers) {
<ide>
<ide> this.reader.doRegisterBean(beanClass, supplier, beanName, null, customizers);
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java
<ide> protected BeanDefinitionRegistry getRegistry() {
<ide> * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver
<ide> */
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
<ide> this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
<ide> this.componentsIndex = CandidateComponentsIndexLoader.loadIndex(this.resourcePatternResolver.getClassLoader());
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java
<ide> public void setEnvironment(Environment environment) {
<ide> }
<ide>
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> Assert.notNull(resourceLoader, "ResourceLoader must not be null");
<ide> this.resourceLoader = resourceLoader;
<ide> if (!this.setMetadataReaderFactoryCalled) {
<ide><path>spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java
<ide> protected Collection<ApplicationListener<?>> getApplicationListeners(
<ide> * @return the pre-filtered list of application listeners for the given event and source type
<ide> */
<ide> private Collection<ApplicationListener<?>> retrieveApplicationListeners(
<del> ResolvableType eventType, Class<?> sourceType, ListenerRetriever retriever) {
<add> ResolvableType eventType, Class<?> sourceType, @Nullable ListenerRetriever retriever) {
<ide>
<ide> LinkedList<ApplicationListener<?>> allListeners = new LinkedList<>();
<ide> Set<ApplicationListener<?>> listeners;
<ide><path>spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java
<ide> public void publishEvent(Object event) {
<ide> * @param eventType the resolved event type, if known
<ide> * @since 4.2
<ide> */
<del> protected void publishEvent(Object event, ResolvableType eventType) {
<add> protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
<ide> Assert.notNull(event, "Event must not be null");
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Publishing event in " + getDisplayName() + ": " + event);
<ide> protected BeanFactory getInternalParentBeanFactory() {
<ide> //---------------------------------------------------------------------
<ide>
<ide> @Override
<del> public String getMessage(String code, @Nullable Object args[], String defaultMessage, Locale locale) {
<add> public String getMessage(String code, @Nullable Object args[], @Nullable String defaultMessage, Locale locale) {
<ide> return getMessageSource().getMessage(code, args, defaultMessage, locale);
<ide> }
<ide>
<ide><path>spring-context/src/main/java/org/springframework/context/support/AbstractMessageSource.java
<ide> protected boolean isUseCodeAsDefaultMessage() {
<ide>
<ide>
<ide> @Override
<del> public final String getMessage(String code, @Nullable Object[] args, String defaultMessage, Locale locale) {
<add> public final String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale) {
<ide> String msg = getMessageInternal(code, args, locale);
<ide> if (msg != null) {
<ide> return msg;
<ide><path>spring-context/src/main/java/org/springframework/context/support/DelegatingMessageSource.java
<ide> public MessageSource getParentMessageSource() {
<ide>
<ide>
<ide> @Override
<del> public String getMessage(String code, @Nullable Object[] args, String defaultMessage, Locale locale) {
<add> public String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale) {
<ide> if (this.parentMessageSource != null) {
<ide> return this.parentMessageSource.getMessage(code, args, defaultMessage, locale);
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/context/support/GenericApplicationContext.java
<ide> public final <T> void registerBean(Class<T> beanClass, Supplier<T> supplier, Bea
<ide> * factory's {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
<ide> * @since 5.0
<ide> */
<del> public <T> void registerBean(@Nullable String beanName, @Nullable Class<T> beanClass, Supplier<T> supplier,
<add> public <T> void registerBean(@Nullable String beanName, @Nullable Class<T> beanClass, @Nullable Supplier<T> supplier,
<ide> BeanDefinitionCustomizer... customizers) {
<ide>
<ide> Assert.isTrue(beanName != null || beanClass != null, "Either bean name or bean class must be specified");
<ide><path>spring-context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java
<ide> public void setPropertiesPersister(PropertiesPersister propertiesPersister) {
<ide> * @see org.springframework.context.ResourceLoaderAware
<ide> */
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
<ide> }
<ide>
<ide><path>spring-context/src/main/java/org/springframework/instrument/classloading/WeavingTransformer.java
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<add>import org.springframework.lang.Nullable;
<add>
<ide> /**
<ide> * ClassFileTransformer-based weaver, allowing for a list of transformers to be
<ide> * applied on a class byte array. Normally used inside class loaders.
<ide> public byte[] transformIfNecessary(String className, byte[] bytes) {
<ide> * @param pd protection domain to be used (can be null)
<ide> * @return (possibly transformed) class byte definition
<ide> */
<del> public byte[] transformIfNecessary(String className, String internalName, byte[] bytes, ProtectionDomain pd) {
<add> public byte[] transformIfNecessary(String className, String internalName, byte[] bytes, @Nullable ProtectionDomain pd) {
<ide> byte[] result = bytes;
<ide> for (ClassFileTransformer cft : this.transformers) {
<ide> try {
<ide><path>spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java
<ide> private ObjectName registerLazyInit(String beanName, String beanKey) throws JMEx
<ide> * @throws javax.management.MalformedObjectNameException
<ide> * if the retrieved {@code ObjectName} is malformed
<ide> */
<del> protected ObjectName getObjectName(Object bean, String beanKey) throws MalformedObjectNameException {
<add> protected ObjectName getObjectName(Object bean, @Nullable String beanKey) throws MalformedObjectNameException {
<ide> if (bean instanceof SelfNaming) {
<ide> return ((SelfNaming) bean).getObjectName();
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/jndi/JndiLocatorDelegate.java
<ide> import javax.naming.NamingException;
<ide>
<ide> import org.springframework.core.SpringProperties;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * {@link JndiLocatorSupport} subclass with public lookup methods,
<ide> public Object lookup(String jndiName) throws NamingException {
<ide> }
<ide>
<ide> @Override
<del> public <T> T lookup(String jndiName, Class<T> requiredType) throws NamingException {
<add> public <T> T lookup(String jndiName, @Nullable Class<T> requiredType) throws NamingException {
<ide> return super.lookup(jndiName, requiredType);
<ide> }
<ide>
<ide><path>spring-context/src/main/java/org/springframework/jndi/JndiLocatorSupport.java
<ide>
<ide> import javax.naming.NamingException;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> protected Object lookup(String jndiName) throws NamingException {
<ide> * @throws NamingException if the JNDI lookup failed
<ide> * @see #setResourceRef
<ide> */
<del> protected <T> T lookup(String jndiName, Class<T> requiredType) throws NamingException {
<add> protected <T> T lookup(String jndiName, @Nullable Class<T> requiredType) throws NamingException {
<ide> Assert.notNull(jndiName, "'jndiName' must not be null");
<ide> String convertedName = convertJndiName(jndiName);
<ide> T jndiObject;
<ide><path>spring-context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java
<ide> public String[] getAliases(String name) {
<ide>
<ide>
<ide> @SuppressWarnings("unchecked")
<del> private <T> T doGetSingleton(String name, Class<T> requiredType) throws NamingException {
<add> private <T> T doGetSingleton(String name, @Nullable Class<T> requiredType) throws NamingException {
<ide> synchronized (this.singletonObjects) {
<ide> if (this.singletonObjects.containsKey(name)) {
<ide> Object jndiObject = this.singletonObjects.get(name);
<ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncResult.java
<ide> import java.util.concurrent.Future;
<ide> import java.util.concurrent.TimeUnit;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.concurrent.FailureCallback;
<ide> import org.springframework.util.concurrent.ListenableFuture;
<ide> import org.springframework.util.concurrent.ListenableFutureCallback;
<ide> * Create a new AsyncResult holder.
<ide> * @param value the value to pass through
<ide> */
<del> public AsyncResult(V value) {
<add> public AsyncResult(@Nullable V value) {
<ide> this(value, null);
<ide> }
<ide>
<ide> /**
<ide> * Create a new AsyncResult holder.
<ide> * @param value the value to pass through
<ide> */
<del> private AsyncResult(V value, ExecutionException ex) {
<add> private AsyncResult(@Nullable V value, @Nullable ExecutionException ex) {
<ide> this.value = value;
<ide> this.executionException = ex;
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutor.java
<ide> import org.springframework.core.task.AsyncListenableTaskExecutor;
<ide> import org.springframework.core.task.TaskDecorator;
<ide> import org.springframework.core.task.support.TaskExecutorAdapter;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.scheduling.SchedulingAwareRunnable;
<ide> import org.springframework.scheduling.SchedulingTaskExecutor;
<ide> import org.springframework.util.ClassUtils;
<ide> public ConcurrentTaskExecutor(Executor concurrentExecutor) {
<ide> * <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedExecutorService}
<ide> * in order to expose {@link javax.enterprise.concurrent.ManagedTask} adapters for it.
<ide> */
<del> public final void setConcurrentExecutor(Executor concurrentExecutor) {
<add> public final void setConcurrentExecutor(@Nullable Executor concurrentExecutor) {
<ide> if (concurrentExecutor != null) {
<ide> this.concurrentExecutor = concurrentExecutor;
<ide> if (managedExecutorServiceClass != null && managedExecutorServiceClass.isInstance(concurrentExecutor)) {
<ide><path>spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java
<ide> public static Object createBshObject(String scriptSource, @Nullable Class<?>...
<ide> * @return the scripted Java object
<ide> * @throws EvalError in case of BeanShell parsing failure
<ide> */
<del> public static Object createBshObject(String scriptSource, @Nullable Class<?>[] scriptInterfaces, ClassLoader classLoader)
<add> public static Object createBshObject(String scriptSource, @Nullable Class<?>[] scriptInterfaces, @Nullable ClassLoader classLoader)
<ide> throws EvalError {
<ide>
<ide> Object result = evaluateBshScript(scriptSource, scriptInterfaces, classLoader);
<ide><path>spring-context/src/main/java/org/springframework/scripting/support/ScriptFactoryPostProcessor.java
<ide> public void setBeanFactory(BeanFactory beanFactory) {
<ide> }
<ide>
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> this.resourceLoader = resourceLoader;
<ide> }
<ide>
<ide><path>spring-context/src/main/java/org/springframework/validation/AbstractBindingResult.java
<ide> public String getObjectName() {
<ide>
<ide>
<ide> @Override
<del> public void reject(String errorCode, @Nullable Object[] errorArgs, String defaultMessage) {
<add> public void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
<ide> addError(new ObjectError(getObjectName(), resolveMessageCodes(errorCode), errorArgs, defaultMessage));
<ide> }
<ide>
<ide><path>spring-context/src/main/java/org/springframework/validation/BindException.java
<ide> public void reject(String errorCode, String defaultMessage) {
<ide> }
<ide>
<ide> @Override
<del> public void reject(String errorCode, @Nullable Object[] errorArgs, String defaultMessage) {
<add> public void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
<ide> this.bindingResult.reject(errorCode, errorArgs, defaultMessage);
<ide> }
<ide>
<ide><path>spring-context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java
<ide> public String[] resolveMessageCodes(String errorCode, String objectName, String
<ide> return StringUtils.toStringArray(codeList);
<ide> }
<ide>
<del> private void addCodes(Collection<String> codeList, String errorCode, String objectName, Iterable<String> fields) {
<add> private void addCodes(Collection<String> codeList, String errorCode, @Nullable String objectName, Iterable<String> fields) {
<ide> for (String field : fields) {
<ide> addCode(codeList, errorCode, objectName, field);
<ide> }
<ide> }
<ide>
<del> private void addCode(Collection<String> codeList, String errorCode, String objectName, String field) {
<add> private void addCode(Collection<String> codeList, String errorCode, @Nullable String objectName, @Nullable String field) {
<ide> codeList.add(postProcessMessageCode(this.formatter.format(errorCode, objectName, field)));
<ide> }
<ide>
<ide><path>spring-context/src/main/java/org/springframework/validation/Errors.java
<ide> public interface Errors {
<ide> * (can be {@code null})
<ide> * @param defaultMessage fallback default message
<ide> */
<del> void reject(String errorCode, @Nullable Object[] errorArgs, String defaultMessage);
<add> void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage);
<ide>
<ide> /**
<ide> * Register a field error for the specified field of the current object
<ide><path>spring-context/src/main/java/org/springframework/validation/ValidationUtils.java
<ide> public static void rejectIfEmpty(Errors errors, String field, @Nullable String e
<ide> * @param defaultMessage fallback default message
<ide> */
<ide> public static void rejectIfEmpty(
<del> Errors errors, String field, String errorCode, @Nullable Object[] errorArgs, String defaultMessage) {
<add> Errors errors, String field, String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
<ide>
<ide> Assert.notNull(errors, "Errors object must not be null");
<ide> Object value = errors.getFieldValue(field);
<ide> public static void rejectIfEmptyOrWhitespace(
<ide> * @param defaultMessage fallback default message
<ide> */
<ide> public static void rejectIfEmptyOrWhitespace(
<del> Errors errors, String field, String errorCode, @Nullable Object[] errorArgs, String defaultMessage) {
<add> Errors errors, String field, String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
<ide>
<ide> Assert.notNull(errors, "Errors object must not be null");
<ide> Object value = errors.getFieldValue(field);
<ide><path>spring-core/src/main/java/org/springframework/core/OrderComparator.java
<ide> public int compare(Object o1, Object o2) {
<ide> return doCompare(o1, o2, null);
<ide> }
<ide>
<del> private int doCompare(Object o1, Object o2, OrderSourceProvider sourceProvider) {
<add> private int doCompare(Object o1, Object o2, @Nullable OrderSourceProvider sourceProvider) {
<ide> boolean p1 = (o1 instanceof PriorityOrdered);
<ide> boolean p2 = (o2 instanceof PriorityOrdered);
<ide> if (p1 && !p2) {
<ide><path>spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java
<ide> public ReactiveAdapter getAdapter(Class<?> reactiveType) {
<ide> * (i.e. to adapt from; may be {@code null} if the reactive type is specified)
<ide> */
<ide> @Nullable
<del> public ReactiveAdapter getAdapter(@Nullable Class<?> reactiveType, Object source) {
<add> public ReactiveAdapter getAdapter(@Nullable Class<?> reactiveType, @Nullable Object source) {
<ide>
<ide> Object sourceToUse = (source instanceof Optional ? ((Optional<?>) source).orElse(null) : source);
<ide> Class<?> clazz = (sourceToUse != null ? sourceToUse.getClass() : reactiveType);
<ide><path>spring-core/src/main/java/org/springframework/core/ReactiveTypeDescriptor.java
<ide>
<ide> import java.util.function.Supplier;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public class ReactiveTypeDescriptor {
<ide> /**
<ide> * Private constructor. See static factory methods.
<ide> */
<del> private ReactiveTypeDescriptor(Class<?> reactiveType, Supplier<?> emptySupplier,
<add> private ReactiveTypeDescriptor(Class<?> reactiveType, @Nullable Supplier<?> emptySupplier,
<ide> boolean multiValue, boolean canBeEmpty, boolean noValue) {
<ide>
<ide> Assert.notNull(reactiveType, "'reactiveType' must not be null");
<ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java
<ide> private ResolvableType(Type type, TypeProvider typeProvider, VariableResolver va
<ide> * with upfront resolution and a pre-calculated hash.
<ide> * @since 4.2
<ide> */
<del> private ResolvableType(Type type, TypeProvider typeProvider, VariableResolver variableResolver, Integer hash) {
<add> private ResolvableType(@Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver, Integer hash) {
<ide> this.type = type;
<ide> this.typeProvider = typeProvider;
<ide> this.variableResolver = variableResolver;
<ide> private ResolvableType(Type type, TypeProvider typeProvider, VariableResolver va
<ide> * with upfront resolution but lazily calculated hash.
<ide> */
<ide> private ResolvableType(
<del> Type type, TypeProvider typeProvider, VariableResolver variableResolver, ResolvableType componentType) {
<add> Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver, ResolvableType componentType) {
<ide>
<ide> this.type = type;
<ide> this.typeProvider = typeProvider;
<ide> public boolean isAssignableFrom(ResolvableType other) {
<ide> return isAssignableFrom(other, null);
<ide> }
<ide>
<del> private boolean isAssignableFrom(ResolvableType other, Map<Type, Type> matchedBefore) {
<add> private boolean isAssignableFrom(ResolvableType other, @Nullable Map<Type, Type> matchedBefore) {
<ide> Assert.notNull(other, "ResolvableType must not be null");
<ide>
<ide> // If we cannot resolve types, we are not assignable
<ide> public Class<?>[] resolveGenerics() {
<ide> * @see #getGenerics()
<ide> * @see #resolve()
<ide> */
<del> public Class<?>[] resolveGenerics(Class<?> fallback) {
<add> public Class<?>[] resolveGenerics(@Nullable Class<?> fallback) {
<ide> ResolvableType[] generics = getGenerics();
<ide> Class<?>[] resolvedGenerics = new Class<?>[generics.length];
<ide> for (int i = 0; i < generics.length; i++) {
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java
<ide> public static boolean hasMetaAnnotationTypes(AnnotatedElement element, String an
<ide> return hasMetaAnnotationTypes(element, null, annotationName);
<ide> }
<ide>
<del> private static boolean hasMetaAnnotationTypes(AnnotatedElement element, Class<? extends Annotation> annotationType,
<del> String annotationName) {
<add> private static boolean hasMetaAnnotationTypes(AnnotatedElement element, @Nullable Class<? extends Annotation> annotationType,
<add> @Nullable String annotationName) {
<ide>
<ide> return Boolean.TRUE.equals(
<ide> searchWithGetSemantics(element, annotationType, annotationName, new SimpleAnnotationProcessor<Boolean>() {
<ide> public static <A extends Annotation> Set<A> findMergedRepeatableAnnotations(Anno
<ide> * @return the result of the processor, potentially {@code null}
<ide> */
<ide> @Nullable
<del> private static <T> T searchWithGetSemantics(AnnotatedElement element, Class<? extends Annotation> annotationType,
<del> String annotationName, Processor<T> processor) {
<add> private static <T> T searchWithGetSemantics(AnnotatedElement element, @Nullable Class<? extends Annotation> annotationType,
<add> @Nullable String annotationName, Processor<T> processor) {
<ide>
<ide> return searchWithGetSemantics(element, annotationType, annotationName, null, processor);
<ide> }
<ide> private static <T> T searchWithGetSemantics(AnnotatedElement element, Class<? ex
<ide> */
<ide> @Nullable
<ide> private static <T> T searchWithGetSemantics(AnnotatedElement element, Class<? extends Annotation> annotationType,
<del> String annotationName, @Nullable Class<? extends Annotation> containerType, Processor<T> processor) {
<add> @Nullable String annotationName, @Nullable Class<? extends Annotation> containerType, Processor<T> processor) {
<ide>
<ide> try {
<ide> return searchWithGetSemantics(element, annotationType, annotationName, containerType, processor,
<ide> private static <T> T searchWithGetSemantics(AnnotatedElement element, Class<? ex
<ide> * @return the result of the processor, potentially {@code null}
<ide> */
<ide> @Nullable
<del> private static <T> T searchWithGetSemantics(AnnotatedElement element, Class<? extends Annotation> annotationType,
<del> String annotationName, @Nullable Class<? extends Annotation> containerType, Processor<T> processor,
<add> private static <T> T searchWithGetSemantics(AnnotatedElement element, @Nullable Class<? extends Annotation> annotationType,
<add> @Nullable String annotationName, @Nullable Class<? extends Annotation> containerType, Processor<T> processor,
<ide> Set<AnnotatedElement> visited, int metaDepth) {
<ide>
<ide> Assert.notNull(element, "AnnotatedElement must not be null");
<ide> else if (currentAnnotationType == containerType) {
<ide> * @since 4.2
<ide> */
<ide> @Nullable
<del> private static <T> T searchWithFindSemantics(AnnotatedElement element, Class<? extends Annotation> annotationType,
<del> String annotationName, Processor<T> processor) {
<add> private static <T> T searchWithFindSemantics(AnnotatedElement element, @Nullable Class<? extends Annotation> annotationType,
<add> @Nullable String annotationName, Processor<T> processor) {
<ide>
<ide> return searchWithFindSemantics(element, annotationType, annotationName, null, processor);
<ide> }
<ide> private static <T> T searchWithFindSemantics(AnnotatedElement element, Class<? e
<ide> */
<ide> @Nullable
<ide> private static <T> T searchWithFindSemantics(AnnotatedElement element, Class<? extends Annotation> annotationType,
<del> String annotationName, @Nullable Class<? extends Annotation> containerType, Processor<T> processor) {
<add> @Nullable String annotationName, @Nullable Class<? extends Annotation> containerType, Processor<T> processor) {
<ide>
<ide> if (containerType != null && !processor.aggregates()) {
<ide> throw new IllegalArgumentException(
<ide><path>spring-core/src/main/java/org/springframework/core/codec/ByteArrayDecoder.java
<ide> public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType
<ide> }
<ide>
<ide> @Override
<del> public Flux<byte[]> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> public Flux<byte[]> decode(Publisher<DataBuffer> inputStream,@Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> return Flux.from(inputStream).map((dataBuffer) -> {
<ide><path>spring-core/src/main/java/org/springframework/core/codec/ByteBufferDecoder.java
<ide> public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType
<ide> }
<ide>
<ide> @Override
<del> public Flux<ByteBuffer> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> public Flux<ByteBuffer> decode(Publisher<DataBuffer> inputStream, @Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> return Flux.from(inputStream).map((dataBuffer) -> {
<ide><path>spring-core/src/main/java/org/springframework/core/codec/DataBufferDecoder.java
<ide> public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType
<ide> }
<ide>
<ide> @Override
<del> public Flux<DataBuffer> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> public Flux<DataBuffer> decode(Publisher<DataBuffer> inputStream, @Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide> return Flux.from(inputStream);
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/codec/Decoder.java
<ide> * @param hints additional information about how to do encode
<ide> * @return the output stream with decoded elements
<ide> */
<del> Flux<T> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> Flux<T> decode(Publisher<DataBuffer> inputStream, @Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints);
<ide>
<ide> /**
<ide><path>spring-core/src/main/java/org/springframework/core/codec/ResourceDecoder.java
<ide> public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType
<ide> }
<ide>
<ide> @Override
<del> public Flux<Resource> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> public Flux<Resource> decode(Publisher<DataBuffer> inputStream, @Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> return Flux.from(decodeToMono(inputStream, elementType, mimeType, hints));
<ide><path>spring-core/src/main/java/org/springframework/core/codec/StringDecoder.java
<ide> public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType
<ide> }
<ide>
<ide> @Override
<del> public Flux<String> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> public Flux<String> decode(Publisher<DataBuffer> inputStream, @Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> Flux<DataBuffer> inputFlux = Flux.from(inputStream);
<ide><path>spring-core/src/main/java/org/springframework/core/convert/ConversionFailedException.java
<ide>
<ide> package org.springframework.core.convert;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ObjectUtils;
<ide>
<ide> /**
<ide> public class ConversionFailedException extends ConversionException {
<ide> * @param value the value we tried to convert
<ide> * @param cause the cause of the conversion failure
<ide> */
<del> public ConversionFailedException(TypeDescriptor sourceType, TypeDescriptor targetType, Object value, Throwable cause) {
<add> public ConversionFailedException(TypeDescriptor sourceType, TypeDescriptor targetType, @Nullable Object value, Throwable cause) {
<ide> super("Failed to convert from type [" + sourceType + "] to type [" + targetType +
<ide> "] for value '" + ObjectUtils.nullSafeToString(value) + "'", cause);
<ide> this.sourceType = sourceType;
<ide><path>spring-core/src/main/java/org/springframework/core/convert/Property.java
<ide> public final class Property {
<ide> private Annotation[] annotations;
<ide>
<ide>
<del> public Property(Class<?> objectType, Method readMethod, Method writeMethod) {
<add> public Property(Class<?> objectType, @Nullable Method readMethod, @Nullable Method writeMethod) {
<ide> this(objectType, readMethod, writeMethod, null);
<ide> }
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java
<ide> public TypeDescriptor(Property property) {
<ide> * @param annotations the type annotations
<ide> * @since 4.0
<ide> */
<del> protected TypeDescriptor(ResolvableType resolvableType, @Nullable Class<?> type, Annotation[] annotations) {
<add> protected TypeDescriptor(ResolvableType resolvableType, @Nullable Class<?> type, @Nullable Annotation[] annotations) {
<ide> this.resolvableType = resolvableType;
<ide> this.type = (type != null ? type : resolvableType.resolve(Object.class));
<ide> this.annotatedElement = new AnnotatedElementAdapter(annotations);
<ide><path>spring-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java
<ide> public String toString() {
<ide> * @return the converted null object
<ide> */
<ide> @Nullable
<del> protected Object convertNullSource(TypeDescriptor sourceType, TypeDescriptor targetType) {
<add> protected Object convertNullSource(@Nullable TypeDescriptor sourceType, TypeDescriptor targetType) {
<ide> if (targetType.getObjectType() == Optional.class) {
<ide> return Optional.empty();
<ide> }
<ide> private Object handleConverterNotFound(Object source, TypeDescriptor sourceType,
<ide> throw new ConverterNotFoundException(sourceType, targetType);
<ide> }
<ide>
<del> private Object handleResult(TypeDescriptor sourceType, TypeDescriptor targetType, Object result) {
<add> private Object handleResult(@Nullable TypeDescriptor sourceType, TypeDescriptor targetType, Object result) {
<ide> if (result == null) {
<ide> assertNotPrimitiveTargetType(sourceType, targetType);
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/io/VfsUtils.java
<ide> import java.net.URI;
<ide> import java.net.URL;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ReflectionUtils;
<ide>
<ide> /**
<ide> public abstract class VfsUtils {
<ide> }
<ide> }
<ide>
<del> protected static Object invokeVfsMethod(Method method, Object target, Object... args) throws IOException {
<add> protected static Object invokeVfsMethod(Method method, @Nullable Object target, Object... args) throws IOException {
<ide> try {
<ide> return method.invoke(target, args);
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java
<ide> import org.springframework.core.env.PropertiesPropertySource;
<ide> import org.springframework.core.io.DefaultResourceLoader;
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> public ResourcePropertySource(String location) throws IOException {
<ide> this(new DefaultResourceLoader().getResource(location));
<ide> }
<ide>
<del> private ResourcePropertySource(String name, String resourceName, Map<String, Object> source) {
<add> private ResourcePropertySource(String name, @Nullable String resourceName, Map<String, Object> source) {
<ide> super(name, source);
<ide> this.resourceName = resourceName;
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/util/AntPathMatcher.java
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide>
<add>import org.springframework.lang.Nullable;
<add>
<ide> /**
<ide> * {@link PathMatcher} implementation for Ant-style path patterns.
<ide> *
<ide> public boolean matchStart(String pattern, String path) {
<ide> * as far as the given base path goes is sufficient)
<ide> * @return {@code true} if the supplied {@code path} matched, {@code false} if it didn't
<ide> */
<del> protected boolean doMatch(String pattern, String path, boolean fullMatch, Map<String, String> uriTemplateVariables) {
<add> protected boolean doMatch(String pattern, String path, boolean fullMatch, @Nullable Map<String, String> uriTemplateVariables) {
<ide> if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) {
<ide> return false;
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/util/CollectionUtils.java
<ide> public MultiValueMapAdapter(Map<K, List<V>> map) {
<ide> }
<ide>
<ide> @Override
<del> public void add(K key, V value) {
<add> public void add(K key, @Nullable V value) {
<ide> List<V> values = this.map.computeIfAbsent(key, k -> new LinkedList<>());
<ide> values.add(value);
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<add>import org.springframework.lang.Nullable;
<add>
<ide> /**
<ide> * Simple implementation of {@link MultiValueMap} that wraps a {@link LinkedHashMap},
<ide> * storing multiple values in a {@link LinkedList}.
<ide> public LinkedMultiValueMap(Map<K, List<V>> otherMap) {
<ide> // MultiValueMap implementation
<ide>
<ide> @Override
<del> public void add(K key, V value) {
<add> public void add(K key, @Nullable V value) {
<ide> List<V> values = this.targetMap.computeIfAbsent(key, k -> new LinkedList<>());
<ide> values.add(value);
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/util/MultiValueMap.java
<ide> * @param key the key
<ide> * @param value the value to be added
<ide> */
<del> void add(K key, V value);
<add> void add(K key, @Nullable V value);
<ide>
<ide> /**
<ide> * Add all the values of the given list to the current list of values for the given key.
<ide><path>spring-core/src/main/java/org/springframework/util/ReflectionUtils.java
<ide> public static Object invokeMethod(Method method, @Nullable Object target, @Nulla
<ide> * @see #invokeJdbcMethod(java.lang.reflect.Method, Object, Object[])
<ide> */
<ide> @Nullable
<del> public static Object invokeJdbcMethod(Method method, Object target) throws SQLException {
<add> public static Object invokeJdbcMethod(Method method, @Nullable Object target) throws SQLException {
<ide> return invokeJdbcMethod(method, target, new Object[0]);
<ide> }
<ide>
<ide> public static void doWithMethods(Class<?> clazz, MethodCallback mc) {
<ide> * @param mf the filter that determines the methods to apply the callback to
<ide> * @throws IllegalStateException if introspection fails
<ide> */
<del> public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) {
<add> public static void doWithMethods(Class<?> clazz, MethodCallback mc, @Nullable MethodFilter mf) {
<ide> // Keep backing up the inheritance hierarchy.
<ide> Method[] methods = getDeclaredMethods(clazz);
<ide> for (Method method : methods) {
<ide> public static void doWithFields(Class<?> clazz, FieldCallback fc) {
<ide> * @param ff the filter that determines the fields to apply the callback to
<ide> * @throws IllegalStateException if introspection fails
<ide> */
<del> public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) {
<add> public static void doWithFields(Class<?> clazz, FieldCallback fc, @Nullable FieldFilter ff) {
<ide> // Keep backing up the inheritance hierarchy.
<ide> Class<?> targetClass = clazz;
<ide> do {
<ide><path>spring-core/src/main/java/org/springframework/util/StringUtils.java
<ide> public static Properties splitArrayElementsIntoProperties(String[] array, String
<ide> */
<ide> @Nullable
<ide> public static Properties splitArrayElementsIntoProperties(
<del> String[] array, String delimiter, String charsToDelete) {
<add> String[] array, String delimiter, @Nullable String charsToDelete) {
<ide>
<ide> if (ObjectUtils.isEmpty(array)) {
<ide> return null;
<ide> public static String[] delimitedListToStringArray(String str, String delimiter)
<ide> * @return an array of the tokens in the list
<ide> * @see #tokenizeToStringArray
<ide> */
<del> public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {
<add> public static String[] delimitedListToStringArray(String str, String delimiter, @Nullable String charsToDelete) {
<ide> if (str == null) {
<ide> return new String[0];
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/util/concurrent/ListenableFutureTask.java
<ide> import java.util.concurrent.ExecutionException;
<ide> import java.util.concurrent.FutureTask;
<ide>
<add>import org.springframework.lang.Nullable;
<add>
<ide> /**
<ide> * Extension of {@link FutureTask} that implements {@link ListenableFuture}.
<ide> *
<ide> public ListenableFutureTask(Callable<T> callable) {
<ide> * @param runnable the runnable task
<ide> * @param result the result to return on successful completion
<ide> */
<del> public ListenableFutureTask(Runnable runnable, T result) {
<add> public ListenableFutureTask(Runnable runnable, @Nullable T result) {
<ide> super(runnable, result);
<ide> }
<ide>
<ide><path>spring-core/src/main/java/org/springframework/util/concurrent/SettableListenableFuture.java
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.TimeoutException;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public Object call() throws Exception {
<ide> * @param value the value that will be set
<ide> * @return {@code true} if the value was successfully set, else {@code false}
<ide> */
<del> public boolean set(T value) {
<add> public boolean set(@Nullable T value) {
<ide> return this.settableTask.setResultValue(value);
<ide> }
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/TypedValue.java
<ide> package org.springframework.expression;
<ide>
<ide> import org.springframework.core.convert.TypeDescriptor;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ObjectUtils;
<ide>
<ide> /**
<ide> public class TypedValue {
<ide> * is inferred from the object, so no generic declarations are preserved.
<ide> * @param value the object value
<ide> */
<del> public TypedValue(Object value) {
<add> public TypedValue(@Nullable Object value) {
<ide> this.value = value;
<ide> this.typeDescriptor = null; // initialized when/if requested
<ide> }
<ide> public TypedValue(Object value) {
<ide> * @param value the object value
<ide> * @param typeDescriptor a type descriptor describing the type of the value
<ide> */
<del> public TypedValue(Object value, TypeDescriptor typeDescriptor) {
<add> public TypedValue(@Nullable Object value, @Nullable TypeDescriptor typeDescriptor) {
<ide> this.value = value;
<ide> this.typeDescriptor = typeDescriptor;
<ide> }
<ide>
<ide>
<add> @Nullable
<ide> public Object getValue() {
<ide> return this.value;
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/common/ExpressionUtils.java
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.TypeConverter;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ClassUtils;
<ide>
<ide> /**
<ide> public abstract class ExpressionUtils {
<ide> * of the value to the specified type is not supported
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> public static <T> T convertTypedValue(EvaluationContext context, TypedValue typedValue, Class<T> targetType) {
<add> public static <T> T convertTypedValue(@Nullable EvaluationContext context, TypedValue typedValue, Class<T> targetType) {
<ide> Object value = typedValue.getValue();
<ide> if (targetType == null) {
<ide> return (T) value;
<ide><path>spring-expression/src/main/java/org/springframework/expression/common/TemplateAwareExpressionParser.java
<ide> import org.springframework.expression.ExpressionParser;
<ide> import org.springframework.expression.ParseException;
<ide> import org.springframework.expression.ParserContext;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * An expression parser that understands templates. It can be subclassed by expression
<ide> private int skipToCorrectEndSuffix(String suffix, String expressionString, int a
<ide> * @return an evaluator for the parsed expression
<ide> * @throws ParseException an exception occurred during parsing
<ide> */
<del> protected abstract Expression doParseExpression(String expressionString, ParserContext context)
<add> protected abstract Expression doParseExpression(String expressionString, @Nullable ParserContext context)
<ide> throws ParseException;
<ide>
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/CompiledExpression.java
<ide>
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.EvaluationException;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * Base superclass for compiled expressions. Each generated compiled expression class
<ide> public abstract class CompiledExpression {
<ide> * Subclasses of CompiledExpression generated by SpelCompiler will provide an
<ide> * implementation of this method.
<ide> */
<del> public abstract Object getValue(Object target, EvaluationContext context) throws EvaluationException;
<add> public abstract Object getValue(Object target, @Nullable EvaluationContext context) throws EvaluationException;
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ExpressionState.java
<ide> public Object lookupLocalVariable(String name) {
<ide> return null;
<ide> }
<ide>
<del> public TypedValue operate(Operation op, Object left, Object right) throws EvaluationException {
<add> public TypedValue operate(Operation op, Object left, @Nullable Object right) throws EvaluationException {
<ide> OperatorOverloader overloader = this.relatedContext.getOperatorOverloader();
<ide> if (overloader.overridesOperation(op, left, right)) {
<ide> Object returnValue = overloader.operate(op, left, right);
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/SpelParserConfiguration.java
<ide> package org.springframework.expression.spel;
<ide>
<ide> import org.springframework.core.SpringProperties;
<add>import org.springframework.lang.Nullable;
<ide>
<ide>
<ide> /**
<ide> public SpelParserConfiguration() {
<ide> * @param compilerMode the compiler mode for the parser
<ide> * @param compilerClassLoader the ClassLoader to use as the basis for expression compilation
<ide> */
<del> public SpelParserConfiguration(SpelCompilerMode compilerMode, ClassLoader compilerClassLoader) {
<add> public SpelParserConfiguration(@Nullable SpelCompilerMode compilerMode, ClassLoader compilerClassLoader) {
<ide> this(compilerMode, compilerClassLoader, false, false, Integer.MAX_VALUE);
<ide> }
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/FormatHelper.java
<ide> import java.util.List;
<ide>
<ide> import org.springframework.core.convert.TypeDescriptor;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ClassUtils;
<ide>
<ide> /**
<ide> public static String formatMethodForMessage(String name, List<TypeDescriptor> ar
<ide> * @return a formatted String suitable for message inclusion
<ide> * @see ClassUtils#getQualifiedName(Class)
<ide> */
<del> public static String formatClassNameForMessage(Class<?> clazz) {
<add> public static String formatClassNameForMessage(@Nullable Class<?> clazz) {
<ide> return (clazz != null ? ClassUtils.getQualifiedName(clazz) : "null");
<ide> }
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java
<ide> public InternalSpelExpressionParser(SpelParserConfiguration configuration) {
<ide>
<ide>
<ide> @Override
<del> protected SpelExpression doParseExpression(String expressionString, ParserContext context) throws ParseException {
<add> protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context) throws ParseException {
<ide> try {
<ide> this.expressionString = expressionString;
<ide> Tokenizer tokenizer = new Tokenizer(expressionString);
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelExpressionParser.java
<ide> import org.springframework.expression.ParserContext;
<ide> import org.springframework.expression.common.TemplateAwareExpressionParser;
<ide> import org.springframework.expression.spel.SpelParserConfiguration;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public SpelExpression parseRaw(String expressionString) throws ParseException {
<ide> }
<ide>
<ide> @Override
<del> protected SpelExpression doParseExpression(String expressionString, ParserContext context) throws ParseException {
<add> protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context) throws ParseException {
<ide> return new InternalSpelExpressionParser(this.configuration).doParseExpression(expressionString, context);
<ide> }
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/StandardEvaluationContext.java
<ide> import org.springframework.expression.TypeConverter;
<ide> import org.springframework.expression.TypeLocator;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public void setRootObject(Object rootObject, TypeDescriptor typeDescriptor) {
<ide> this.rootObject = new TypedValue(rootObject, typeDescriptor);
<ide> }
<ide>
<del> public void setRootObject(Object rootObject) {
<add> public void setRootObject(@Nullable Object rootObject) {
<ide> this.rootObject = (rootObject != null ? new TypedValue(rootObject) : TypedValue.NULL);
<ide> }
<ide>
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/config/SortedResourcesFactoryBean.java
<ide> import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
<ide> import org.springframework.core.io.support.ResourcePatternResolver;
<ide> import org.springframework.core.io.support.ResourcePatternUtils;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * {@link FactoryBean} implementation that takes a list of location Strings
<ide> public SortedResourcesFactoryBean(ResourceLoader resourceLoader, List<String> lo
<ide>
<ide>
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
<ide> }
<ide>
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
<ide> public <T> T execute(String sql, PreparedStatementCallback<T> action) throws Dat
<ide> * @throws DataAccessException if there is any problem
<ide> */
<ide> public <T> T query(
<del> PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor<T> rse)
<add> PreparedStatementCreator psc, @Nullable final PreparedStatementSetter pss, final ResultSetExtractor<T> rse)
<ide> throws DataAccessException {
<ide>
<ide> Assert.notNull(rse, "ResultSetExtractor must not be null");
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java
<ide> public static void setParameterValue(PreparedStatement ps, int paramIndex, int s
<ide> * @see SqlTypeValue
<ide> */
<ide> private static void setParameterValueInternal(PreparedStatement ps, int paramIndex, int sqlType,
<del> String typeName, Integer scale, Object inValue) throws SQLException {
<add> @Nullable String typeName, @Nullable Integer scale, Object inValue) throws SQLException {
<ide>
<ide> String typeNameToUse = typeName;
<ide> int sqlTypeToUse = sqlType;
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java
<ide> import org.springframework.jdbc.core.SqlRowSetResultSetExtractor;
<ide> import org.springframework.jdbc.support.KeyHolder;
<ide> import org.springframework.jdbc.support.rowset.SqlRowSet;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public int update(String sql, SqlParameterSource paramSource, KeyHolder generate
<ide>
<ide> @Override
<ide> public int update(
<del> String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
<add> String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, @Nullable String[] keyColumnNames)
<ide> throws DataAccessException {
<ide>
<ide> ParsedSql parsedSql = getParsedSql(sql);
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterUtils.java
<ide> private static int skipCommentsAndQuotes(char[] statement, int position) {
<ide> * @return the SQL statement with substituted parameters
<ide> * @see #parseSqlStatement
<ide> */
<del> public static String substituteNamedParameters(ParsedSql parsedSql, SqlParameterSource paramSource) {
<add> public static String substituteNamedParameters(ParsedSql parsedSql, @Nullable SqlParameterSource paramSource) {
<ide> String originalSql = parsedSql.getOriginalSql();
<ide> StringBuilder actualSql = new StringBuilder();
<ide> List<String> paramNames = parsedSql.getParameterNames();
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java
<ide> import javax.sql.DataSource;
<ide>
<ide> import org.springframework.beans.factory.InitializingBean;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.transaction.CannotCreateTransactionException;
<ide> import org.springframework.transaction.TransactionDefinition;
<ide> import org.springframework.transaction.TransactionSystemException;
<ide> private static class DataSourceTransactionObject extends JdbcTransactionObjectSu
<ide>
<ide> private boolean mustRestoreAutoCommit;
<ide>
<del> public void setConnectionHolder(ConnectionHolder connectionHolder, boolean newConnectionHolder) {
<add> public void setConnectionHolder(@Nullable ConnectionHolder connectionHolder, boolean newConnectionHolder) {
<ide> super.setConnectionHolder(connectionHolder);
<ide> this.newConnectionHolder = newConnectionHolder;
<ide> }
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/JdbcTransactionObjectSupport.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.transaction.CannotCreateTransactionException;
<ide> import org.springframework.transaction.NestedTransactionNotSupportedException;
<ide> import org.springframework.transaction.SavepointManager;
<ide> public abstract class JdbcTransactionObjectSupport implements SavepointManager,
<ide> private boolean savepointAllowed = false;
<ide>
<ide>
<del> public void setConnectionHolder(ConnectionHolder connectionHolder) {
<add> public void setConnectionHolder(@Nullable ConnectionHolder connectionHolder) {
<ide> this.connectionHolder = connectionHolder;
<ide> }
<ide>
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptUtils.java
<ide>
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.support.EncodedResource;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> public static void splitSqlScript(String script, String separator, List<String>
<ide> * @param statements the list that will contain the individual statements
<ide> * @throws ScriptException if an error occurred while splitting the SQL script
<ide> */
<del> public static void splitSqlScript(EncodedResource resource, String script, String separator, String commentPrefix,
<add> public static void splitSqlScript(@Nullable EncodedResource resource, String script, String separator, String commentPrefix,
<ide> String blockCommentStartDelimiter, String blockCommentEndDelimiter, List<String> statements)
<ide> throws ScriptException {
<ide>
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/object/SqlQuery.java
<ide> public int getRowsExpected() {
<ide> * @return a List of objects, one per row of the ResultSet. Normally all these
<ide> * will be of the same class, although it is possible to use different types.
<ide> */
<del> public List<T> execute(Object[] params, Map<?, ?> context) throws DataAccessException {
<add> public List<T> execute(Object[] params, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> validateParameters(params);
<ide> RowMapper<T> rowMapper = newRowMapper(params, context);
<ide> return getJdbcTemplate().query(newPreparedStatementCreator(params), rowMapper);
<ide> public List<T> execute() throws DataAccessException {
<ide> * @param p1 single int parameter
<ide> * @param context the contextual information for object creation
<ide> */
<del> public List<T> execute(int p1, Map<?, ?> context) throws DataAccessException {
<add> public List<T> execute(int p1, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> return execute(new Object[] {p1}, context);
<ide> }
<ide>
<ide> public List<T> execute(int p1) throws DataAccessException {
<ide> * @param p2 second int parameter
<ide> * @param context the contextual information for object creation
<ide> */
<del> public List<T> execute(int p1, int p2, Map<?, ?> context) throws DataAccessException {
<add> public List<T> execute(int p1, int p2, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> return execute(new Object[] {p1, p2}, context);
<ide> }
<ide>
<ide> public List<T> execute(int p1, int p2) throws DataAccessException {
<ide> * @param p1 single long parameter
<ide> * @param context the contextual information for object creation
<ide> */
<del> public List<T> execute(long p1, Map<?, ?> context) throws DataAccessException {
<add> public List<T> execute(long p1, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> return execute(new Object[] {p1}, context);
<ide> }
<ide>
<ide> public List<T> execute(long p1) throws DataAccessException {
<ide> * @param p1 single String parameter
<ide> * @param context the contextual information for object creation
<ide> */
<del> public List<T> execute(String p1, Map<?, ?> context) throws DataAccessException {
<add> public List<T> execute(String p1, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> return execute(new Object[] {p1}, context);
<ide> }
<ide>
<ide> public List<T> execute(String p1) throws DataAccessException {
<ide> * @return a List of objects, one per row of the ResultSet. Normally all these
<ide> * will be of the same class, although it is possible to use different types.
<ide> */
<del> public List<T> executeByNamedParam(Map<String, ?> paramMap, Map<?, ?> context) throws DataAccessException {
<add> public List<T> executeByNamedParam(Map<String, ?> paramMap, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> validateNamedParameters(paramMap);
<ide> ParsedSql parsedSql = getParsedSql();
<ide> MapSqlParameterSource paramSource = new MapSqlParameterSource(paramMap);
<ide> public List<T> executeByNamedParam(Map<String, ?> paramMap) throws DataAccessExc
<ide> * @see org.springframework.dao.support.DataAccessUtils#singleResult
<ide> */
<ide> @Nullable
<del> public T findObject(Object[] params, Map<?, ?> context) throws DataAccessException {
<add> public T findObject(Object[] params, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> List<T> results = execute(params, context);
<ide> return DataAccessUtils.singleResult(results);
<ide> }
<ide> public T findObject(Object... params) throws DataAccessException {
<ide> * Convenient method to find a single object given a single int parameter
<ide> * and a context.
<ide> */
<del> public T findObject(int p1, Map<?, ?> context) throws DataAccessException {
<add> public T findObject(int p1, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> return findObject(new Object[] {p1}, context);
<ide> }
<ide>
<ide> public T findObject(int p1) throws DataAccessException {
<ide> * Convenient method to find a single object given two int parameters
<ide> * and a context.
<ide> */
<del> public T findObject(int p1, int p2, Map<?, ?> context) throws DataAccessException {
<add> public T findObject(int p1, int p2, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> return findObject(new Object[] {p1, p2}, context);
<ide> }
<ide>
<ide> public T findObject(int p1, int p2) throws DataAccessException {
<ide> * Convenient method to find a single object given a single long parameter
<ide> * and a context.
<ide> */
<del> public T findObject(long p1, Map<?, ?> context) throws DataAccessException {
<add> public T findObject(long p1, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> return findObject(new Object[] {p1}, context);
<ide> }
<ide>
<ide> public T findObject(long p1) throws DataAccessException {
<ide> * Convenient method to find a single object given a single String parameter
<ide> * and a context.
<ide> */
<del> public T findObject(String p1, Map<?, ?> context) throws DataAccessException {
<add> public T findObject(String p1, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> return findObject(new Object[] {p1}, context);
<ide> }
<ide>
<ide> public T findObject(String p1) throws DataAccessException {
<ide> * @return a List of objects, one per row of the ResultSet. Normally all these
<ide> * will be of the same class, although it is possible to use different types.
<ide> */
<del> public T findObjectByNamedParam(Map<String, ?> paramMap, Map<?, ?> context) throws DataAccessException {
<add> public T findObjectByNamedParam(Map<String, ?> paramMap, @Nullable Map<?, ?> context) throws DataAccessException {
<ide> List<T> results = executeByNamedParam(paramMap, context);
<ide> return DataAccessUtils.singleResult(results);
<ide> }
<ide><path>spring-jms/src/main/java/org/springframework/jms/connection/CachingConnectionFactory.java
<ide> private MessageProducer getCachedProducer(Destination dest) throws JMSException
<ide> }
<ide>
<ide> private MessageConsumer getCachedConsumer(
<del> Destination dest, String selector, Boolean noLocal, String subscription, boolean durable) throws JMSException {
<add> Destination dest, String selector, @Nullable Boolean noLocal, @Nullable String subscription, boolean durable) throws JMSException {
<ide>
<ide> ConsumerCacheKey cacheKey = new ConsumerCacheKey(dest, selector, noLocal, subscription, durable);
<ide> MessageConsumer consumer = this.cachedConsumers.get(cacheKey);
<ide><path>spring-jms/src/main/java/org/springframework/jms/connection/JmsResourceHolder.java
<ide> public final void addSession(Session session) {
<ide> addSession(session, null);
<ide> }
<ide>
<del> public final void addSession(Session session, Connection connection) {
<add> public final void addSession(Session session, @Nullable Connection connection) {
<ide> Assert.isTrue(!this.frozen, "Cannot add Session because JmsResourceHolder is frozen");
<ide> Assert.notNull(session, "Session must not be null");
<ide> if (!this.sessions.contains(session)) {
<ide> public Session getSession(Class<? extends Session> sessionType) {
<ide> return getSession(sessionType, null);
<ide> }
<ide>
<del> public Session getSession(Class<? extends Session> sessionType, Connection connection) {
<add> public Session getSession(Class<? extends Session> sessionType, @Nullable Connection connection) {
<ide> List<Session> sessions = this.sessions;
<ide> if (connection != null) {
<ide> sessions = this.sessionsPerConnection.get(connection);
<ide><path>spring-jms/src/main/java/org/springframework/jms/connection/JmsTransactionManager.java
<ide> import javax.jms.TransactionRolledBackException;
<ide>
<ide> import org.springframework.beans.factory.InitializingBean;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.transaction.CannotCreateTransactionException;
<ide> import org.springframework.transaction.InvalidIsolationLevelException;
<ide> import org.springframework.transaction.TransactionDefinition;
<ide> private static class JmsTransactionObject implements SmartTransactionObject {
<ide>
<ide> private JmsResourceHolder resourceHolder;
<ide>
<del> public void setResourceHolder(JmsResourceHolder resourceHolder) {
<add> public void setResourceHolder(@Nullable JmsResourceHolder resourceHolder) {
<ide> this.resourceHolder = resourceHolder;
<ide> }
<ide>
<ide><path>spring-jms/src/main/java/org/springframework/jms/core/JmsMessageOperations.java
<ide> void convertAndSend(String destinationName, Object payload, MessagePostProcessor
<ide> * @param headers headers for the message to send
<ide> * @param postProcessor the post processor to apply to the message
<ide> */
<del> void convertAndSend(String destinationName, Object payload, Map<String,
<del> Object> headers, MessagePostProcessor postProcessor) throws MessagingException;
<add> void convertAndSend(String destinationName, Object payload, @Nullable Map<String,
<add> Object> headers, @Nullable MessagePostProcessor postProcessor) throws MessagingException;
<ide>
<ide> /**
<ide> * Receive a message from the given destination.
<ide> void convertAndSend(String destinationName, Object payload, Map<String,
<ide> * could not be received, for example due to a timeout
<ide> */
<ide> @Nullable
<del> <T> T convertSendAndReceive(String destinationName, Object request, Map<String, Object> headers, Class<T> targetClass)
<add> <T> T convertSendAndReceive(String destinationName, Object request, @Nullable Map<String, Object> headers, Class<T> targetClass)
<ide> throws MessagingException;
<ide>
<ide> /**
<ide><path>spring-jms/src/main/java/org/springframework/jms/core/JmsMessagingTemplate.java
<ide> import org.springframework.jms.support.converter.MessageConverter;
<ide> import org.springframework.jms.support.converter.MessagingMessageConverter;
<ide> import org.springframework.jms.support.converter.SimpleMessageConverter;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessagingException;
<ide> import org.springframework.messaging.converter.MessageConversionException;
<ide> public void convertAndSend(Object payload) throws MessagingException {
<ide> }
<ide>
<ide> @Override
<del> public void convertAndSend(Object payload, MessagePostProcessor postProcessor) throws MessagingException {
<add> public void convertAndSend(Object payload, @Nullable MessagePostProcessor postProcessor) throws MessagingException {
<ide> Destination defaultDestination = getDefaultDestination();
<ide> if (defaultDestination != null) {
<ide> convertAndSend(defaultDestination, payload, postProcessor);
<ide> public void convertAndSend(String destinationName, Object payload, MessagePostPr
<ide> }
<ide>
<ide> @Override
<del> public void convertAndSend(String destinationName, Object payload, Map<String, Object> headers,
<del> MessagePostProcessor postProcessor) throws MessagingException {
<add> public void convertAndSend(String destinationName, Object payload, @Nullable Map<String, Object> headers,
<add> @Nullable MessagePostProcessor postProcessor) throws MessagingException {
<ide>
<ide> Message<?> message = doConvert(payload, headers, postProcessor);
<ide> send(destinationName, message);
<ide> public <T> T convertSendAndReceive(Object request, Class<T> targetClass) {
<ide>
<ide> @Override
<ide> public <T> T convertSendAndReceive(String destinationName, Object request,
<del> Map<String, Object> headers, Class<T> targetClass) throws MessagingException {
<add> @Nullable Map<String, Object> headers, Class<T> targetClass) throws MessagingException {
<ide>
<ide> return convertSendAndReceive(destinationName, request, headers, targetClass, null);
<ide> }
<ide>
<ide> @Override
<del> public <T> T convertSendAndReceive(Object request, Class<T> targetClass, MessagePostProcessor postProcessor) {
<add> public <T> T convertSendAndReceive(Object request, Class<T> targetClass, @Nullable MessagePostProcessor postProcessor) {
<ide> Destination defaultDestination = getDefaultDestination();
<ide> if (defaultDestination != null) {
<ide> return convertSendAndReceive(defaultDestination, request, targetClass, postProcessor);
<ide> public <T> T convertSendAndReceive(String destinationName, Object request, Class
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> @Override
<del> public <T> T convertSendAndReceive(String destinationName, Object request, Map<String, Object> headers,
<del> Class<T> targetClass, MessagePostProcessor postProcessor) {
<add> public <T> T convertSendAndReceive(String destinationName, Object request, @Nullable Map<String, Object> headers,
<add> Class<T> targetClass, @Nullable MessagePostProcessor postProcessor) {
<ide>
<ide> Message<?> requestMessage = doConvert(request, headers, postProcessor);
<ide> Message<?> replyMessage = sendAndReceive(destinationName, requestMessage);
<ide><path>spring-jms/src/main/java/org/springframework/jms/core/JmsTemplate.java
<ide> public Message receiveSelected(String messageSelector) throws JmsException {
<ide> }
<ide>
<ide> @Override
<del> public Message receiveSelected(final Destination destination, final String messageSelector) throws JmsException {
<add> public Message receiveSelected(final Destination destination, @Nullable final String messageSelector) throws JmsException {
<ide> return execute(new SessionCallback<Message>() {
<ide> @Override
<ide> public Message doInJms(Session session) throws JMSException {
<ide> public Message doInJms(Session session) throws JMSException {
<ide> }
<ide>
<ide> @Override
<del> public Message receiveSelected(final String destinationName, final String messageSelector) throws JmsException {
<add> public Message receiveSelected(final String destinationName, @Nullable final String messageSelector) throws JmsException {
<ide> return execute(new SessionCallback<Message>() {
<ide> @Override
<ide> public Message doInJms(Session session) throws JMSException {
<ide> public <T> T browseSelected(String messageSelector, BrowserCallback<T> action) t
<ide> }
<ide>
<ide> @Override
<del> public <T> T browseSelected(final Queue queue, final String messageSelector, final BrowserCallback<T> action)
<add> public <T> T browseSelected(final Queue queue, @Nullable final String messageSelector, final BrowserCallback<T> action)
<ide> throws JmsException {
<ide>
<ide> Assert.notNull(action, "Callback object must not be null");
<ide> public T doInJms(Session session) throws JMSException {
<ide> }
<ide>
<ide> @Override
<del> public <T> T browseSelected(final String queueName, final String messageSelector, final BrowserCallback<T> action)
<add> public <T> T browseSelected(final String queueName, @Nullable final String messageSelector, final BrowserCallback<T> action)
<ide> throws JmsException {
<ide>
<ide> Assert.notNull(action, "Callback object must not be null");
<ide><path>spring-jms/src/main/java/org/springframework/jms/listener/SessionAwareMessageListener.java
<ide> import javax.jms.Message;
<ide> import javax.jms.Session;
<ide>
<add>import org.springframework.lang.Nullable;
<add>
<ide> /**
<ide> * Variant of the standard JMS {@link javax.jms.MessageListener} interface,
<ide> * offering not only the received Message but also the underlying
<ide> * @param session the underlying JMS Session (never {@code null})
<ide> * @throws JMSException if thrown by JMS methods
<ide> */
<del> void onMessage(M message, Session session) throws JMSException;
<add> void onMessage(M message, @Nullable Session session) throws JMSException;
<ide>
<ide> }
<ide><path>spring-jms/src/main/java/org/springframework/jms/listener/adapter/MessageListenerAdapter.java
<ide> import org.springframework.jms.listener.SubscriptionNameProvider;
<ide> import org.springframework.jms.support.converter.MessageConverter;
<ide> import org.springframework.jms.support.converter.SimpleMessageConverter;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MethodInvoker;
<ide> import org.springframework.util.ObjectUtils;
<ide> protected String getDefaultListenerMethod() {
<ide> */
<ide> @Override
<ide> @SuppressWarnings("unchecked")
<del> public void onMessage(Message message, Session session) throws JMSException {
<add> public void onMessage(Message message, @Nullable Session session) throws JMSException {
<ide> // Check whether the delegate is a MessageListener impl itself.
<ide> // In that case, the adapter will simply act as a pass-through.
<ide> Object delegate = getDelegate();
<ide><path>spring-jms/src/main/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapter.java
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.jms.support.JmsHeaderMapper;
<ide> import org.springframework.jms.support.converter.MessageConversionException;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessagingException;
<ide> import org.springframework.messaging.core.AbstractMessageSendingTemplate;
<ide> public void setHandlerMethod(InvocableHandlerMethod handlerMethod) {
<ide>
<ide>
<ide> @Override
<del> public void onMessage(javax.jms.Message jmsMessage, Session session) throws JMSException {
<add> public void onMessage(javax.jms.Message jmsMessage, @Nullable Session session) throws JMSException {
<ide> Message<?> message = toMessagingMessage(jmsMessage);
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Processing [" + message + "]");
<ide><path>spring-jms/src/main/java/org/springframework/jms/remoting/JmsInvokerServiceExporter.java
<ide> public void afterPropertiesSet() {
<ide>
<ide>
<ide> @Override
<del> public void onMessage(Message requestMessage, Session session) throws JMSException {
<add> public void onMessage(Message requestMessage, @Nullable Session session) throws JMSException {
<ide> RemoteInvocation invocation = readRemoteInvocation(requestMessage);
<ide> if (invocation != null) {
<ide> RemoteInvocationResult result = invokeAndCreateResult(invocation, this.proxy);
<ide><path>spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java
<ide> import org.springframework.context.support.GenericApplicationContext;
<ide> import org.springframework.core.task.TaskExecutor;
<ide> import org.springframework.jms.StubQueue;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ErrorHandler;
<ide>
<ide> import static org.junit.Assert.*;
<ide> public void testCorrectSessionExposedForSessionAwareMessageListenerInvocation()
<ide> this.container.setDestinationName(DESTINATION_NAME);
<ide> this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
<ide> @Override
<del> public void onMessage(Message message, Session sess) {
<add> public void onMessage(Message message, @Nullable Session sess) {
<ide> try {
<ide> // Check correct Session passed into SessionAwareMessageListener.
<ide> assertSame(sess, session);
<ide> public void testRegisteredExceptionListenerIsInvokedOnException() throws Excepti
<ide> this.container.setDestinationName(DESTINATION_NAME);
<ide> this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
<ide> @Override
<del> public void onMessage(Message message, Session session) throws JMSException {
<add> public void onMessage(Message message, @Nullable Session session) throws JMSException {
<ide> throw theException;
<ide> }
<ide> });
<ide> public void testRegisteredErrorHandlerIsInvokedOnException() throws Exception {
<ide> this.container.setDestinationName(DESTINATION_NAME);
<ide> this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
<ide> @Override
<del> public void onMessage(Message message, Session session) throws JMSException {
<add> public void onMessage(Message message, @Nullable Session session) throws JMSException {
<ide> throw theException;
<ide> }
<ide> });
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java
<ide> public class MessageHeaders implements Map<String, Object>, Serializable {
<ide> * {@link #TIMESTAMP} headers will also be added, overriding any existing values.
<ide> * @param headers a map with headers to add
<ide> */
<del> public MessageHeaders(Map<String, Object> headers) {
<add> public MessageHeaders(@Nullable Map<String, Object> headers) {
<ide> this(headers, null, null);
<ide> }
<ide>
<ide> public MessageHeaders(Map<String, Object> headers) {
<ide> * @param id the {@link #ID} header value
<ide> * @param timestamp the {@link #TIMESTAMP} header value
<ide> */
<del> protected MessageHeaders(Map<String, Object> headers, UUID id, Long timestamp) {
<add> protected MessageHeaders(@Nullable Map<String, Object> headers, UUID id, Long timestamp) {
<ide> this.headers = (headers != null ? new HashMap<>(headers) : new HashMap<String, Object>());
<ide>
<ide> if (id == null) {
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/AbstractDestinationResolvingMessagingTemplate.java
<ide>
<ide> import java.util.Map;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.util.Assert;
<ide>
<ide> public <T> void convertAndSend(String destinationName, T payload, MessagePostPro
<ide> }
<ide>
<ide> @Override
<del> public <T> void convertAndSend(String destinationName, T payload, Map<String, Object> headers, MessagePostProcessor postProcessor) {
<add> public <T> void convertAndSend(String destinationName, T payload, @Nullable Map<String, Object> headers, @Nullable MessagePostProcessor postProcessor) {
<ide> D destination = resolveDestination(destinationName);
<ide> super.convertAndSend(destination, payload, headers, postProcessor);
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/AbstractMessageSendingTemplate.java
<ide> public void convertAndSend(D destination, Object payload, Map<String, Object> he
<ide> }
<ide>
<ide> @Override
<del> public void convertAndSend(Object payload, MessagePostProcessor postProcessor) throws MessagingException {
<add> public void convertAndSend(Object payload, @Nullable MessagePostProcessor postProcessor) throws MessagingException {
<ide> convertAndSend(getRequiredDefaultDestination(), payload, postProcessor);
<ide> }
<ide>
<ide> public void convertAndSend(D destination, Object payload, MessagePostProcessor p
<ide> }
<ide>
<ide> @Override
<del> public void convertAndSend(D destination, Object payload, Map<String, Object> headers,
<del> MessagePostProcessor postProcessor) throws MessagingException {
<add> public void convertAndSend(D destination, Object payload, @Nullable Map<String, Object> headers,
<add> @Nullable MessagePostProcessor postProcessor) throws MessagingException {
<ide>
<ide> Message<?> message = doConvert(payload, headers, postProcessor);
<ide> send(destination, message);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/AbstractMessagingTemplate.java
<ide>
<ide> import java.util.Map;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide>
<ide> /**
<ide> public <T> T convertSendAndReceive(D destination, Object request, Class<T> targe
<ide> }
<ide>
<ide> @Override
<del> public <T> T convertSendAndReceive(D destination, Object request, Map<String, Object> headers, Class<T> targetClass) {
<add> public <T> T convertSendAndReceive(D destination, Object request, @Nullable Map<String, Object> headers, Class<T> targetClass) {
<ide> return convertSendAndReceive(destination, request, headers, targetClass, null);
<ide> }
<ide>
<ide> @Override
<del> public <T> T convertSendAndReceive(Object request, Class<T> targetClass, MessagePostProcessor postProcessor) {
<add> public <T> T convertSendAndReceive(Object request, Class<T> targetClass, @Nullable MessagePostProcessor postProcessor) {
<ide> return convertSendAndReceive(getRequiredDefaultDestination(), request, targetClass, postProcessor);
<ide> }
<ide>
<ide> public <T> T convertSendAndReceive(D destination, Object request, Class<T> targe
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> @Override
<del> public <T> T convertSendAndReceive(D destination, Object request, Map<String, Object> headers,
<del> Class<T> targetClass, MessagePostProcessor postProcessor) {
<add> public <T> T convertSendAndReceive(D destination, Object request, @Nullable Map<String, Object> headers,
<add> Class<T> targetClass, @Nullable MessagePostProcessor postProcessor) {
<ide>
<ide> Message<?> requestMessage = doConvert(request, headers, postProcessor);
<ide> Message<?> replyMessage = sendAndReceive(destination, requestMessage);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/DestinationResolvingMessageSendingOperations.java
<ide>
<ide> import java.util.Map;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessagingException;
<ide>
<ide> <T> void convertAndSend(String destinationName, T payload, MessagePostProcessor
<ide> * @param headers headers for the message to send
<ide> * @param postProcessor the post processor to apply to the message
<ide> */
<del> <T> void convertAndSend(String destinationName, T payload, Map<String, Object> headers,
<del> MessagePostProcessor postProcessor) throws MessagingException;
<add> <T> void convertAndSend(String destinationName, T payload, @Nullable Map<String, Object> headers,
<add> @Nullable MessagePostProcessor postProcessor) throws MessagingException;
<ide>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/MessageRequestReplyOperations.java
<ide> * could not be received, for example due to a timeout
<ide> */
<ide> @Nullable
<del> <T> T convertSendAndReceive(D destination, Object request, Map<String, Object> headers, Class<T> targetClass)
<add> <T> T convertSendAndReceive(D destination, Object request, @Nullable Map<String, Object> headers, Class<T> targetClass)
<ide> throws MessagingException;
<ide>
<ide> /**
<ide> <T> T convertSendAndReceive(D destination, Object request, Map<String, Object> h
<ide> * could not be received, for example due to a timeout
<ide> */
<ide> @Nullable
<del> <T> T convertSendAndReceive(Object request, Class<T> targetClass, MessagePostProcessor requestPostProcessor)
<add> <T> T convertSendAndReceive(Object request, Class<T> targetClass, @Nullable MessagePostProcessor requestPostProcessor)
<ide> throws MessagingException;
<ide>
<ide> /**
<ide> <T> T convertSendAndReceive(D destination, Object request, Class<T> targetClass,
<ide> * could not be received, for example due to a timeout
<ide> */
<ide> @Nullable
<del> <T> T convertSendAndReceive(D destination, Object request, Map<String, Object> headers,
<del> Class<T> targetClass, MessagePostProcessor requestPostProcessor) throws MessagingException;
<add> <T> T convertSendAndReceive(D destination, Object request, @Nullable Map<String, Object> headers,
<add> Class<T> targetClass, @Nullable MessagePostProcessor requestPostProcessor) throws MessagingException;
<ide>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/MessageSendingOperations.java
<ide>
<ide> import java.util.Map;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessagingException;
<ide>
<ide> * @param payload the Object to use as payload
<ide> * @param postProcessor the post processor to apply to the message
<ide> */
<del> void convertAndSend(Object payload, MessagePostProcessor postProcessor) throws MessagingException;
<add> void convertAndSend(Object payload, @Nullable MessagePostProcessor postProcessor) throws MessagingException;
<ide>
<ide> /**
<ide> * Convert the given Object to serialized form, possibly using a
<ide> * @param headers headers for the message to send
<ide> * @param postProcessor the post processor to apply to the message
<ide> */
<del> void convertAndSend(D destination, Object payload, Map<String, Object> headers, MessagePostProcessor postProcessor)
<add> void convertAndSend(D destination, Object payload, @Nullable Map<String, Object> headers, @Nullable MessagePostProcessor postProcessor)
<ide> throws MessagingException;
<ide>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageHeaderAccessor.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.support.IdTimestampMessageHeaderInitializer;
<ide> import org.springframework.messaging.support.MessageHeaderAccessor;
<ide> public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
<ide> * A constructor for creating new message headers.
<ide> * This constructor is protected. See factory methods in this and sub-classes.
<ide> */
<del> protected SimpMessageHeaderAccessor(SimpMessageType messageType, Map<String, List<String>> externalSourceHeaders) {
<add> protected SimpMessageHeaderAccessor(SimpMessageType messageType, @Nullable Map<String, List<String>> externalSourceHeaders) {
<ide> super(externalSourceHeaders);
<ide> Assert.notNull(messageType, "MessageType must not be null");
<ide> setHeader(MESSAGE_TYPE_HEADER, messageType);
<ide> public String getShortLogMessage(Object payload) {
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> @Override
<del> public String getDetailedLogMessage(Object payload) {
<add> public String getDetailedLogMessage(@Nullable Object payload) {
<ide> if (getMessageType() == null) {
<ide> return super.getDetailedLogMessage(payload);
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageSendingOperations.java
<ide> void convertAndSendToUser(String user, String destination, @Nullable Object payl
<ide> * @param headers the message headers
<ide> * @param postProcessor a postProcessor to post-process or modify the created message
<ide> */
<del> void convertAndSendToUser(String user, String destination, Object payload, Map<String, Object> headers,
<del> MessagePostProcessor postProcessor) throws MessagingException;
<add> void convertAndSendToUser(String user, String destination, Object payload, @Nullable Map<String, Object> headers,
<add> @Nullable MessagePostProcessor postProcessor) throws MessagingException;
<ide>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompSession.java
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.core.ResolvableType;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageDeliveryException;
<ide> import org.springframework.messaging.converter.MessageConversionException;
<ide> private StompHeaderAccessor createHeaderAccessor(StompCommand command) {
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<del> private Message<byte[]> createMessage(StompHeaderAccessor accessor, Object payload) {
<add> private Message<byte[]> createMessage(StompHeaderAccessor accessor, @Nullable Object payload) {
<ide> accessor.updateSimpMessageHeadersFromStompHeaders();
<ide> Message<byte[]> message;
<ide> if (payload == null) {
<ide> public void unsubscribe() {
<ide> }
<ide>
<ide> @Override
<del> public void unsubscribe(StompHeaders stompHeaders) {
<add> public void unsubscribe(@Nullable StompHeaders stompHeaders) {
<ide> String id = this.headers.getId();
<ide> DefaultStompSession.this.subscriptions.remove(id);
<ide> DefaultStompSession.this.unsubscribe(id, stompHeaders);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClient.java
<ide>
<ide> package org.springframework.messaging.simp.stomp;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.tcp.TcpOperations;
<ide> import org.springframework.messaging.tcp.reactor.ReactorNettyTcpClient;
<ide> import org.springframework.util.Assert;
<ide> public ListenableFuture<StompSession> connect(StompSessionHandler handler) {
<ide> * @param handler the handler for the STOMP session
<ide> * @return ListenableFuture for access to the session when ready for use
<ide> */
<del> public ListenableFuture<StompSession> connect(StompHeaders connectHeaders, StompSessionHandler handler) {
<add> public ListenableFuture<StompSession> connect(@Nullable StompHeaders connectHeaders, StompSessionHandler handler) {
<ide> ConnectionHandlingStompSession session = createSession(connectHeaders, handler);
<ide> this.tcpClient.connect(session);
<ide> return session.getSessionFuture();
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageChannel;
<ide> import org.springframework.messaging.MessageDeliveryException;
<ide> public void afterConnectFailure(Throwable ex) {
<ide> * Invoked when any TCP connectivity issue is detected, i.e. failure to establish
<ide> * the TCP connection, failure to send a message, missed heartbeat, etc.
<ide> */
<del> protected void handleTcpConnectionFailure(String error, Throwable ex) {
<add> protected void handleTcpConnectionFailure(String error, @Nullable Throwable ex) {
<ide> if (logger.isErrorEnabled()) {
<ide> logger.error("TCP connection failure in session " + this.sessionId + ": " + error, ex);
<ide> }
<ide> protected void handleInboundMessage(Message<?> message) {
<ide> }
<ide>
<ide> @Override
<del> protected void handleTcpConnectionFailure(String errorMessage, Throwable ex) {
<add> protected void handleTcpConnectionFailure(String errorMessage, @Nullable Throwable ex) {
<ide> super.handleTcpConnectionFailure(errorMessage, ex);
<ide> publishBrokerUnavailableEvent();
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompDecoder.java
<ide> public List<Message<byte[]>> decode(ByteBuffer byteBuffer) {
<ide> * @return the decoded messages, or an empty list if none
<ide> * @throws StompConversionException raised in case of decoding issues
<ide> */
<del> public List<Message<byte[]>> decode(ByteBuffer byteBuffer, MultiValueMap<String, String> partialMessageHeaders) {
<add> public List<Message<byte[]>> decode(ByteBuffer byteBuffer, @Nullable MultiValueMap<String, String> partialMessageHeaders) {
<ide> List<Message<byte[]>> messages = new ArrayList<>();
<ide> while (byteBuffer.hasRemaining()) {
<ide> Message<byte[]> message = decodeMessage(byteBuffer, partialMessageHeaders);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaderAccessor.java
<ide> public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
<ide> /**
<ide> * A constructor for creating message headers from a parsed STOMP frame.
<ide> */
<del> StompHeaderAccessor(StompCommand command, Map<String, List<String>> externalSourceHeaders) {
<add> StompHeaderAccessor(StompCommand command, @Nullable Map<String, List<String>> externalSourceHeaders) {
<ide> super(command.getMessageType(), externalSourceHeaders);
<ide> setHeader(COMMAND_HEADER, command);
<ide> updateSimpMessageHeadersFromStompHeaders();
<ide> else if (StompCommand.DISCONNECT.equals(getCommand())) {
<ide> }
<ide>
<ide> @Override
<del> public String getDetailedLogMessage(Object payload) {
<add> public String getDetailedLogMessage(@Nullable Object payload) {
<ide> if (isHeartbeat()) {
<ide> return "heart-beat in session " + getSessionId();
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaders.java
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MimeType;
<ide> public String getFirst(String headerName) {
<ide> * @see #set(String, String)
<ide> */
<ide> @Override
<del> public void add(String headerName, String headerValue) {
<add> public void add(String headerName, @Nullable String headerValue) {
<ide> List<String> headerValues = headers.computeIfAbsent(headerName, k -> new LinkedList<>());
<ide> headerValues.add(headerValue);
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompSession.java
<ide> interface Subscription extends Receiptable {
<ide> * to send to the server.
<ide> * <p><strong>Note:</strong> There is no need to set the subscription id.
<ide> */
<del> void unsubscribe(StompHeaders stompHeaders);
<add> void unsubscribe(@Nullable StompHeaders stompHeaders);
<ide> }
<ide>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/AbstractMessageChannel.java
<ide> public void applyPostSend(Message<?> message, MessageChannel channel, boolean se
<ide> }
<ide> }
<ide>
<del> public void triggerAfterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
<add> public void triggerAfterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {
<ide> for (int i = this.sendInterceptorIndex; i >= 0; i--) {
<ide> ChannelInterceptor interceptor = interceptors.get(i);
<ide> try {
<ide> public Message<?> applyPostReceive(Message<?> message, MessageChannel channel) {
<ide> return message;
<ide> }
<ide>
<del> public void triggerAfterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
<add> public void triggerAfterReceiveCompletion(@Nullable Message<?> message, MessageChannel channel, @Nullable Exception ex) {
<ide> for (int i = this.receiveInterceptorIndex; i >= 0; i--) {
<ide> ChannelInterceptor interceptor = interceptors.get(i);
<ide> try {
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/ExecutorSubscribableChannel.java
<ide> private Message<?> applyBeforeHandle(Message<?> message) {
<ide> return message;
<ide> }
<ide>
<del> private void triggerAfterMessageHandled(Message<?> message, Exception ex) {
<add> private void triggerAfterMessageHandled(Message<?> message, @Nullable Exception ex) {
<ide> for (int i = this.interceptorIndex; i >= 0; i--) {
<ide> ExecutorChannelInterceptor interceptor = executorInterceptors.get(i);
<ide> try {
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java
<ide> public String getShortLogMessage(Object payload) {
<ide> * @param payload the payload that corresponds to the headers.
<ide> * @return the message
<ide> */
<del> public String getDetailedLogMessage(Object payload) {
<add> public String getDetailedLogMessage(@Nullable Object payload) {
<ide> return "headers=" + this.headers.toString() + getDetailedPayloadLogMessage(payload);
<ide> }
<ide>
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/ConfigurableJtaPlatform.java
<ide> import org.hibernate.TransactionException;
<ide> import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.transaction.jta.UserTransactionAdapter;
<ide> import org.springframework.util.Assert;
<ide>
<ide> class ConfigurableJtaPlatform implements JtaPlatform {
<ide> * @param ut the JTA UserTransaction reference (optional)
<ide> * @param tsr the JTA 1.1 TransactionSynchronizationRegistry (optional)
<ide> */
<del> public ConfigurableJtaPlatform(TransactionManager tm, UserTransaction ut, TransactionSynchronizationRegistry tsr) {
<add> public ConfigurableJtaPlatform(TransactionManager tm, @Nullable UserTransaction ut, @Nullable TransactionSynchronizationRegistry tsr) {
<ide> Assert.notNull(tm, "TransactionManager reference must not be null");
<ide> this.transactionManager = tm;
<ide> this.userTransaction = (ut != null ? ut : new UserTransactionAdapter(tm));
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/HibernateTemplate.java
<ide> public <T> T get(Class<T> entityClass, Serializable id) throws DataAccessExcepti
<ide> }
<ide>
<ide> @Override
<del> public <T> T get(final Class<T> entityClass, final Serializable id, final LockMode lockMode)
<add> public <T> T get(final Class<T> entityClass, final Serializable id, @Nullable final LockMode lockMode)
<ide> throws DataAccessException {
<ide>
<ide> return executeWithNativeSession(new HibernateCallback<T>() {
<ide> public Object get(String entityName, Serializable id) throws DataAccessException
<ide> }
<ide>
<ide> @Override
<del> public Object get(final String entityName, final Serializable id, final LockMode lockMode)
<add> public Object get(final String entityName, final Serializable id, @Nullable final LockMode lockMode)
<ide> throws DataAccessException {
<ide>
<ide> return executeWithNativeSession(new HibernateCallback<Object>() {
<ide> public <T> T load(Class<T> entityClass, Serializable id) throws DataAccessExcept
<ide> }
<ide>
<ide> @Override
<del> public <T> T load(final Class<T> entityClass, final Serializable id, final LockMode lockMode)
<add> public <T> T load(final Class<T> entityClass, final Serializable id, @Nullable final LockMode lockMode)
<ide> throws DataAccessException {
<ide>
<ide> return executeWithNativeSession(new HibernateCallback<T>() {
<ide> public Object load(String entityName, Serializable id) throws DataAccessExceptio
<ide> }
<ide>
<ide> @Override
<del> public Object load(final String entityName, final Serializable id, final LockMode lockMode)
<add> public Object load(final String entityName, final Serializable id, @Nullable final LockMode lockMode)
<ide> throws DataAccessException {
<ide>
<ide> return executeWithNativeSession(new HibernateCallback<Object>() {
<ide> public void refresh(final Object entity) throws DataAccessException {
<ide> }
<ide>
<ide> @Override
<del> public void refresh(final Object entity, final LockMode lockMode) throws DataAccessException {
<add> public void refresh(final Object entity, @Nullable final LockMode lockMode) throws DataAccessException {
<ide> executeWithNativeSession(new HibernateCallback<Object>() {
<ide> @Override
<ide> public Object doInHibernate(Session session) throws HibernateException {
<ide> public void update(Object entity) throws DataAccessException {
<ide> }
<ide>
<ide> @Override
<del> public void update(final Object entity, final LockMode lockMode) throws DataAccessException {
<add> public void update(final Object entity, @Nullable final LockMode lockMode) throws DataAccessException {
<ide> executeWithNativeSession(new HibernateCallback<Object>() {
<ide> @Override
<ide> public Object doInHibernate(Session session) throws HibernateException {
<ide> public void update(String entityName, Object entity) throws DataAccessException
<ide> }
<ide>
<ide> @Override
<del> public void update(final String entityName, final Object entity, final LockMode lockMode)
<add> public void update(final String entityName, final Object entity, @Nullable final LockMode lockMode)
<ide> throws DataAccessException {
<ide>
<ide> executeWithNativeSession(new HibernateCallback<Object>() {
<ide> public void delete(Object entity) throws DataAccessException {
<ide> }
<ide>
<ide> @Override
<del> public void delete(final Object entity, final LockMode lockMode) throws DataAccessException {
<add> public void delete(final Object entity, @Nullable final LockMode lockMode) throws DataAccessException {
<ide> executeWithNativeSession(new HibernateCallback<Object>() {
<ide> @Override
<ide> public Object doInHibernate(Session session) throws HibernateException {
<ide> public void delete(String entityName, Object entity) throws DataAccessException
<ide> }
<ide>
<ide> @Override
<del> public void delete(final String entityName, final Object entity, final LockMode lockMode)
<add> public void delete(final String entityName, final Object entity, @Nullable final LockMode lockMode)
<ide> throws DataAccessException {
<ide>
<ide> executeWithNativeSession(new HibernateCallback<Object>() {
<ide> public <T> List<T> findByExample(T exampleEntity, int firstResult, int maxResult
<ide> @Override
<ide> @SuppressWarnings("deprecation")
<ide> public <T> List<T> findByExample(
<del> final String entityName, final T exampleEntity, final int firstResult, final int maxResults)
<add> @Nullable final String entityName, final T exampleEntity, final int firstResult, final int maxResults)
<ide> throws DataAccessException {
<ide>
<ide> Assert.notNull(exampleEntity, "Example entity must not be null");
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/HibernateTransactionManager.java
<ide> public void setExistingSession(Session session) {
<ide> this.newSession = false;
<ide> }
<ide>
<del> public void setSessionHolder(SessionHolder sessionHolder) {
<add> public void setSessionHolder(@Nullable SessionHolder sessionHolder) {
<ide> this.sessionHolder = sessionHolder;
<ide> this.newSessionHolder = false;
<ide> this.newSession = false;
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate5/LocalSessionFactoryBean.java
<ide> import org.springframework.core.io.support.ResourcePatternUtils;
<ide> import org.springframework.core.task.AsyncTaskExecutor;
<ide> import org.springframework.core.type.filter.TypeFilter;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public MetadataSources getMetadataSources() {
<ide> * @param resourceLoader the ResourceLoader to use (never {@code null})
<ide> */
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
<ide> }
<ide>
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/ExtendedEntityManagerCreator.java
<ide> private static EntityManager createProxy(EntityManager rawEntityManager,
<ide> */
<ide> private static EntityManager createProxy(
<ide> EntityManager rawEm, @Nullable Class<? extends EntityManager> emIfc, @Nullable ClassLoader cl,
<del> PersistenceExceptionTranslator exceptionTranslator, @Nullable Boolean jta,
<add> @Nullable PersistenceExceptionTranslator exceptionTranslator, @Nullable Boolean jta,
<ide> boolean containerManaged, boolean synchronizedWithTransaction) {
<ide>
<ide> Assert.notNull(rawEm, "EntityManager must not be null");
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/JpaTransactionManager.java
<ide> private class JpaTransactionObject extends JdbcTransactionObjectSupport {
<ide> private Object transactionData;
<ide>
<ide> public void setEntityManagerHolder(
<del> EntityManagerHolder entityManagerHolder, boolean newEntityManagerHolder) {
<add> @Nullable EntityManagerHolder entityManagerHolder, boolean newEntityManagerHolder) {
<ide> this.entityManagerHolder = entityManagerHolder;
<ide> this.newEntityManagerHolder = newEntityManagerHolder;
<ide> }
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.java
<ide> import org.springframework.core.io.ResourceLoader;
<ide> import org.springframework.instrument.classloading.LoadTimeWeaver;
<ide> import org.springframework.jdbc.datasource.lookup.SingleDataSourceLookup;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager;
<ide> import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
<ide> import org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor;
<ide> public void setLoadTimeWeaver(LoadTimeWeaver loadTimeWeaver) {
<ide> }
<ide>
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> this.internalPersistenceUnitManager.setResourceLoader(resourceLoader);
<ide> }
<ide>
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/persistenceunit/DefaultPersistenceUnitManager.java
<ide> public LoadTimeWeaver getLoadTimeWeaver() {
<ide> }
<ide>
<ide> @Override
<del> public void setResourceLoader(ResourceLoader resourceLoader) {
<add> public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
<ide> this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
<ide> this.componentsIndex = CandidateComponentsIndexLoader.loadIndex(resourceLoader.getClassLoader());
<ide> }
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java
<ide> public boolean requiresDestruction(Object bean) {
<ide> }
<ide>
<ide>
<del> private InjectionMetadata findPersistenceMetadata(String beanName, final Class<?> clazz, PropertyValues pvs) {
<add> private InjectionMetadata findPersistenceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) {
<ide> // Fall back to class name as cache key, for backwards compatibility with custom callers.
<ide> String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
<ide> // Quick check on the concurrent map first, with minimal locking.
<ide> private class PersistenceElement extends InjectionMetadata.InjectedElement {
<ide>
<ide> private Properties properties;
<ide>
<del> public PersistenceElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) {
<add> public PersistenceElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
<ide> super(member, pd);
<ide> PersistenceContext pc = ae.getAnnotation(PersistenceContext.class);
<ide> PersistenceUnit pu = ae.getAnnotation(PersistenceUnit.class);
<ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.java
<ide> private static class SessionTransactionData {
<ide> private final Integer previousIsolationLevel;
<ide>
<ide> public SessionTransactionData(
<del> Session session, FlushMode previousFlushMode, Connection preparedCon, Integer previousIsolationLevel) {
<add> Session session, FlushMode previousFlushMode, @Nullable Connection preparedCon, @Nullable Integer previousIsolationLevel) {
<ide> this.session = session;
<ide> this.previousFlushMode = previousFlushMode;
<ide> this.preparedCon = preparedCon;
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java
<ide> public void marshal(Object graph, Result result) throws XmlMappingException {
<ide> }
<ide>
<ide> @Override
<del> public void marshal(Object graph, Result result, MimeContainer mimeContainer) throws XmlMappingException {
<add> public void marshal(Object graph, Result result, @Nullable MimeContainer mimeContainer) throws XmlMappingException {
<ide> try {
<ide> Marshaller marshaller = createMarshaller();
<ide> if (this.mtomEnabled && mimeContainer != null) {
<ide> public Object unmarshal(Source source) throws XmlMappingException {
<ide> }
<ide>
<ide> @Override
<del> public Object unmarshal(Source source, MimeContainer mimeContainer) throws XmlMappingException {
<add> public Object unmarshal(Source source, @Nullable MimeContainer mimeContainer) throws XmlMappingException {
<ide> source = processSource(source);
<ide>
<ide> try {
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/mime/MimeMarshaller.java
<ide> import java.io.IOException;
<ide> import javax.xml.transform.Result;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.oxm.Marshaller;
<ide> import org.springframework.oxm.XmlMappingException;
<ide>
<ide> public interface MimeMarshaller extends Marshaller {
<ide> * @throws XmlMappingException if the given object cannot be marshalled to the result
<ide> * @throws IOException if an I/O exception occurs
<ide> */
<del> void marshal(Object graph, Result result, MimeContainer mimeContainer) throws XmlMappingException, IOException;
<add> void marshal(Object graph, Result result, @Nullable MimeContainer mimeContainer) throws XmlMappingException, IOException;
<ide>
<ide> }
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/mime/MimeUnmarshaller.java
<ide> import java.io.IOException;
<ide> import javax.xml.transform.Source;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.oxm.Unmarshaller;
<ide> import org.springframework.oxm.XmlMappingException;
<ide>
<ide> public interface MimeUnmarshaller extends Unmarshaller {
<ide> * @throws XmlMappingException if the given source cannot be mapped to an object
<ide> * @throws IOException if an I/O Exception occurs
<ide> */
<del> Object unmarshal(Source source, MimeContainer mimeContainer) throws XmlMappingException, IOException;
<add> Object unmarshal(Source source, @Nullable MimeContainer mimeContainer) throws XmlMappingException, IOException;
<ide>
<ide> }
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java
<ide> public void marshalOutputStream(Object graph, OutputStream outputStream) throws
<ide> marshalOutputStream(graph, outputStream, null);
<ide> }
<ide>
<del> public void marshalOutputStream(Object graph, OutputStream outputStream, DataHolder dataHolder)
<add> public void marshalOutputStream(Object graph, OutputStream outputStream, @Nullable DataHolder dataHolder)
<ide> throws XmlMappingException, IOException {
<ide>
<ide> if (this.streamDriver != null) {
<ide> public void marshalWriter(Object graph, Writer writer) throws XmlMappingExceptio
<ide> marshalWriter(graph, writer, null);
<ide> }
<ide>
<del> public void marshalWriter(Object graph, Writer writer, DataHolder dataHolder)
<add> public void marshalWriter(Object graph, Writer writer, @Nullable DataHolder dataHolder)
<ide> throws XmlMappingException, IOException {
<ide>
<ide> if (this.streamDriver != null) {
<ide> public void marshalWriter(Object graph, Writer writer, DataHolder dataHolder)
<ide> * Marshals the given graph to the given XStream HierarchicalStreamWriter.
<ide> * Converts exceptions using {@link #convertXStreamException}.
<ide> */
<del> private void doMarshal(Object graph, HierarchicalStreamWriter streamWriter, DataHolder dataHolder) {
<add> private void doMarshal(Object graph, HierarchicalStreamWriter streamWriter, @Nullable DataHolder dataHolder) {
<ide> try {
<ide> getXStream().marshal(graph, streamWriter, dataHolder);
<ide> }
<ide> public Object unmarshalInputStream(InputStream inputStream) throws XmlMappingExc
<ide> return unmarshalInputStream(inputStream, null);
<ide> }
<ide>
<del> public Object unmarshalInputStream(InputStream inputStream, DataHolder dataHolder) throws XmlMappingException, IOException {
<add> public Object unmarshalInputStream(InputStream inputStream, @Nullable DataHolder dataHolder) throws XmlMappingException, IOException {
<ide> if (this.streamDriver != null) {
<ide> return doUnmarshal(this.streamDriver.createReader(inputStream), dataHolder);
<ide> }
<ide> public Object unmarshalReader(Reader reader) throws XmlMappingException, IOExcep
<ide> return unmarshalReader(reader, null);
<ide> }
<ide>
<del> public Object unmarshalReader(Reader reader, DataHolder dataHolder) throws XmlMappingException, IOException {
<add> public Object unmarshalReader(Reader reader, @Nullable DataHolder dataHolder) throws XmlMappingException, IOException {
<ide> return doUnmarshal(getDefaultDriver().createReader(reader), dataHolder);
<ide> }
<ide>
<ide> /**
<ide> * Unmarshals the given graph to the given XStream HierarchicalStreamWriter.
<ide> * Converts exceptions using {@link #convertXStreamException}.
<ide> */
<del> private Object doUnmarshal(HierarchicalStreamReader streamReader, DataHolder dataHolder) {
<add> private Object doUnmarshal(HierarchicalStreamReader streamReader, @Nullable DataHolder dataHolder) {
<ide> try {
<ide> return getXStream().unmarshal(streamReader, null, dataHolder);
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/mock/web/MockAsyncContext.java
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<ide> import org.springframework.beans.BeanUtils;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.util.WebUtils;
<ide>
<ide> public void dispatch(String path) {
<ide> }
<ide>
<ide> @Override
<del> public void dispatch(ServletContext context, String path) {
<add> public void dispatch(@Nullable ServletContext context, String path) {
<ide> this.dispatchedPath = path;
<ide> for (Runnable r : this.dispatchHandlers) {
<ide> r.run();
<ide><path>spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java
<ide> public AsyncContext startAsync() {
<ide> }
<ide>
<ide> @Override
<del> public AsyncContext startAsync(ServletRequest request, ServletResponse response) {
<add> public AsyncContext startAsync(ServletRequest request, @Nullable ServletResponse response) {
<ide> Assert.state(this.asyncSupported, "Async not supported");
<ide> this.asyncStarted = true;
<ide> this.asyncContext = new MockAsyncContext(request, response);
<ide> public String getMethod() {
<ide> return this.method;
<ide> }
<ide>
<del> public void setPathInfo(String pathInfo) {
<add> public void setPathInfo(@Nullable String pathInfo) {
<ide> this.pathInfo = pathInfo;
<ide> }
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/setup/StubWebApplicationContext.java
<ide> public boolean containsLocalBean(String name) {
<ide> //---------------------------------------------------------------------
<ide>
<ide> @Override
<del> public String getMessage(String code, @Nullable Object args[], String defaultMessage, Locale locale) {
<add> public String getMessage(String code, @Nullable Object args[], @Nullable String defaultMessage, Locale locale) {
<ide> return this.messageSource.getMessage(code, args, defaultMessage, locale);
<ide> }
<ide>
<ide> public <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws Bea
<ide> }
<ide>
<ide> @Override
<del> public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName) {
<add> public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) {
<ide> throw new UnsupportedOperationException("Dependency resolution not supported");
<ide> }
<ide>
<ide> @Override
<ide> public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,
<del> Set<String> autowiredBeanNames, TypeConverter typeConverter) {
<add> @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) {
<ide> throw new UnsupportedOperationException("Dependency resolution not supported");
<ide> }
<ide>
<ide><path>spring-tx/src/main/java/org/springframework/jca/cci/connection/CciLocalTransactionManager.java
<ide> import javax.resource.spi.LocalTransactionException;
<ide>
<ide> import org.springframework.beans.factory.InitializingBean;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.transaction.CannotCreateTransactionException;
<ide> import org.springframework.transaction.TransactionDefinition;
<ide> import org.springframework.transaction.TransactionException;
<ide> private static class CciLocalTransactionObject {
<ide>
<ide> private ConnectionHolder connectionHolder;
<ide>
<del> public void setConnectionHolder(ConnectionHolder connectionHolder) {
<add> public void setConnectionHolder(@Nullable ConnectionHolder connectionHolder) {
<ide> this.connectionHolder = connectionHolder;
<ide> }
<ide>
<ide><path>spring-tx/src/main/java/org/springframework/jca/cci/core/CciTemplate.java
<ide> public <T> T execute(InteractionSpec spec, RecordCreator inputCreator, RecordExt
<ide> */
<ide> protected <T> T doExecute(
<ide> final InteractionSpec spec, final Record inputRecord, @Nullable final Record outputRecord,
<del> final RecordExtractor<T> outputExtractor) throws DataAccessException {
<add> @Nullable final RecordExtractor<T> outputExtractor) throws DataAccessException {
<ide>
<ide> return execute(new InteractionCallback<T>() {
<ide> @Override
<ide><path>spring-tx/src/main/java/org/springframework/jca/endpoint/AbstractMessageEndpointFactory.java
<ide> void initXAResource(XAResource xaResource) {
<ide> * sibling {@link #afterDelivery()} explicitly, as part of its own processing.
<ide> */
<ide> @Override
<del> public void beforeDelivery(Method method) throws ResourceException {
<add> public void beforeDelivery(@Nullable Method method) throws ResourceException {
<ide> this.beforeDeliveryCalled = true;
<ide> try {
<ide> this.transactionDelegate.beginTransaction();
<ide><path>spring-tx/src/main/java/org/springframework/jca/work/SimpleTaskWorkManager.java
<ide> import org.springframework.core.task.TaskExecutor;
<ide> import org.springframework.core.task.TaskRejectedException;
<ide> import org.springframework.core.task.TaskTimeoutException;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public void doWork(Work work) throws WorkException {
<ide> }
<ide>
<ide> @Override
<del> public void doWork(Work work, long startTimeout, ExecutionContext executionContext, WorkListener workListener)
<add> public void doWork(Work work, long startTimeout, @Nullable ExecutionContext executionContext, @Nullable WorkListener workListener)
<ide> throws WorkException {
<ide>
<ide> Assert.state(this.syncTaskExecutor != null, "No 'syncTaskExecutor' set");
<ide> public long startWork(Work work) throws WorkException {
<ide> }
<ide>
<ide> @Override
<del> public long startWork(Work work, long startTimeout, ExecutionContext executionContext, WorkListener workListener)
<add> public long startWork(Work work, long startTimeout, @Nullable ExecutionContext executionContext, @Nullable WorkListener workListener)
<ide> throws WorkException {
<ide>
<ide> Assert.state(this.asyncTaskExecutor != null, "No 'asyncTaskExecutor' set");
<ide> public void scheduleWork(Work work) throws WorkException {
<ide> }
<ide>
<ide> @Override
<del> public void scheduleWork(Work work, long startTimeout, ExecutionContext executionContext, WorkListener workListener)
<add> public void scheduleWork(Work work, long startTimeout, @Nullable ExecutionContext executionContext, @Nullable WorkListener workListener)
<ide> throws WorkException {
<ide>
<ide> Assert.state(this.asyncTaskExecutor != null, "No 'asyncTaskExecutor' set");
<ide><path>spring-tx/src/main/java/org/springframework/transaction/support/AbstractPlatformTransactionManager.java
<ide> private TransactionStatus handleExistingTransaction(
<ide> * @see #prepareTransactionStatus
<ide> */
<ide> protected final DefaultTransactionStatus prepareTransactionStatus(
<del> TransactionDefinition definition, Object transaction, boolean newTransaction,
<del> boolean newSynchronization, boolean debug, Object suspendedResources) {
<add> TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction,
<add> boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) {
<ide>
<ide> DefaultTransactionStatus status = newTransactionStatus(
<ide> definition, transaction, newTransaction, newSynchronization, debug, suspendedResources);
<ide> protected final DefaultTransactionStatus prepareTransactionStatus(
<ide> */
<ide> protected DefaultTransactionStatus newTransactionStatus(
<ide> TransactionDefinition definition, Object transaction, boolean newTransaction,
<del> boolean newSynchronization, boolean debug, Object suspendedResources) {
<add> boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) {
<ide>
<ide> boolean actualNewSynchronization = newSynchronization &&
<ide> !TransactionSynchronizationManager.isSynchronizationActive();
<ide> else if (transaction != null) {
<ide> * @see #doResume
<ide> * @see #suspend
<ide> */
<del> protected final void resume(Object transaction, @Nullable SuspendedResourcesHolder resourcesHolder)
<add> protected final void resume(@Nullable Object transaction, @Nullable SuspendedResourcesHolder resourcesHolder)
<ide> throws TransactionException {
<ide>
<ide> if (resourcesHolder != null) {
<ide><path>spring-tx/src/main/java/org/springframework/transaction/support/AbstractTransactionStatus.java
<ide> public boolean isCompleted() {
<ide> * Set a savepoint for this transaction. Useful for PROPAGATION_NESTED.
<ide> * @see org.springframework.transaction.TransactionDefinition#PROPAGATION_NESTED
<ide> */
<del> protected void setSavepoint(Object savepoint) {
<add> protected void setSavepoint(@Nullable Object savepoint) {
<ide> this.savepoint = savepoint;
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/ContentDisposition.java
<ide> public class ContentDisposition {
<ide> /**
<ide> * Private constructor. See static factory methods in this class.
<ide> */
<del> private ContentDisposition(String type, String name, String filename, Charset charset, Long size) {
<add> private ContentDisposition(@Nullable String type, @Nullable String name, @Nullable String filename, @Nullable Charset charset, @Nullable Long size) {
<ide> this.type = type;
<ide> this.name = name;
<ide> this.filename = filename;
<ide><path>spring-web/src/main/java/org/springframework/http/HttpHeaders.java
<ide> public String getFirst(String headerName) {
<ide> * @see #set(String, String)
<ide> */
<ide> @Override
<del> public void add(String headerName, String headerValue) {
<add> public void add(String headerName, @Nullable String headerValue) {
<ide> List<String> headerValues = this.headers.computeIfAbsent(headerName, k -> new LinkedList<>());
<ide> headerValues.add(headerValue);
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/HttpRange.java
<ide> import org.springframework.core.io.InputStreamResource;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.support.ResourceRegion;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.ObjectUtils;
<ide> private static class ByteRange extends HttpRange {
<ide>
<ide> private final Long lastPos;
<ide>
<del> public ByteRange(long firstPos, Long lastPos) {
<add> public ByteRange(long firstPos, @Nullable Long lastPos) {
<ide> assertPositions(firstPos, lastPos);
<ide> this.firstPos = firstPos;
<ide> this.lastPos = lastPos;
<ide><path>spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java
<ide> public List<MediaType> getWritableMediaTypes() {
<ide>
<ide>
<ide> @Override
<del> public boolean canWrite(ResolvableType elementType, MediaType mediaType) {
<add> public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) {
<ide> return this.encoder.canEncode(elementType, mediaType);
<ide> }
<ide>
<ide> private boolean isStreamingMediaType(MediaType contentType) {
<ide> // Server side only...
<ide>
<ide> @Override
<del> public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType actualType,
<add> public Mono<Void> write(Publisher<? extends T> inputStream, @Nullable ResolvableType actualType,
<ide> ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request,
<ide> ServerHttpResponse response, Map<String, Object> hints) {
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/FormHttpMessageWriter.java
<ide> public Charset getDefaultCharset() {
<ide>
<ide>
<ide> @Override
<del> public boolean canWrite(ResolvableType elementType, MediaType mediaType) {
<add> public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) {
<ide> return MULTIVALUE_TYPE.isAssignableFrom(elementType) &&
<ide> (mediaType == null || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(mediaType));
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/codec/HttpMessageWriter.java
<ide> * @param mediaType the media type for the write, possibly {@code null}
<ide> * @return {@code true} if writable, {@code false} otherwise
<ide> */
<del> boolean canWrite(ResolvableType elementType, MediaType mediaType);
<add> boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType);
<ide>
<ide> /**
<ide> * Write an given stream of object to the output message.
<ide> Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType elementType,
<ide> * @param response the current response
<ide> * @return a {@link Mono} that indicates completion of writing or error
<ide> */
<del> default Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType actualType,
<add> default Mono<Void> write(Publisher<? extends T> inputStream, @Nullable ResolvableType actualType,
<ide> ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request,
<ide> ServerHttpResponse response, Map<String, Object> hints) {
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ResourceHttpMessageWriter.java
<ide> public ResourceHttpMessageWriter(int bufferSize) {
<ide>
<ide>
<ide> @Override
<del> public boolean canWrite(ResolvableType elementType, MediaType mediaType) {
<add> public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) {
<ide> return this.encoder.canEncode(elementType, mediaType);
<ide> }
<ide>
<ide> private static OptionalLong lengthOf(Resource resource) {
<ide> return OptionalLong.empty();
<ide> }
<ide>
<del> private static Optional<Mono<Void>> zeroCopy(Resource resource, ResourceRegion region,
<add> private static Optional<Mono<Void>> zeroCopy(Resource resource, @Nullable ResourceRegion region,
<ide> ReactiveHttpOutputMessage message) {
<ide>
<ide> if (message instanceof ZeroCopyHttpOutputMessage) {
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerSentEventHttpMessageWriter.java
<ide> public List<MediaType> getWritableMediaTypes() {
<ide>
<ide>
<ide> @Override
<del> public boolean canWrite(ResolvableType elementType, MediaType mediaType) {
<add> public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) {
<ide> return (mediaType == null || MediaType.TEXT_EVENT_STREAM.includes(mediaType) ||
<ide> ServerSentEvent.class.isAssignableFrom(elementType.resolve(Object.class)));
<ide> }
<ide> private Mono<DataBuffer> encodeText(CharSequence text, DataBufferFactory bufferF
<ide> }
<ide>
<ide> @Override
<del> public Mono<Void> write(Publisher<?> input, ResolvableType actualType, ResolvableType elementType,
<add> public Mono<Void> write(Publisher<?> input, @Nullable ResolvableType actualType, ResolvableType elementType,
<ide> @Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response,
<ide> Map<String, Object> hints) {
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2CodecSupport.java
<ide> import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ResolvableType;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MimeType;
<ide> import org.springframework.util.ObjectUtils;
<ide> protected boolean supportsMimeType(MimeType mimeType) {
<ide> return (mimeType == null || this.mimeTypes.stream().anyMatch(m -> m.isCompatibleWith(mimeType)));
<ide> }
<ide>
<del> protected JavaType getJavaType(Type type, Class<?> contextClass) {
<add> protected JavaType getJavaType(Type type, @Nullable Class<?> contextClass) {
<ide> TypeFactory typeFactory = this.objectMapper.getTypeFactory();
<ide> return typeFactory.constructType(GenericTypeResolver.resolveType(type, contextClass));
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2JsonDecoder.java
<ide> public List<MimeType> getDecodableMimeTypes() {
<ide> }
<ide>
<ide> @Override
<del> public Flux<Object> decode(Publisher<DataBuffer> input, ResolvableType elementType,
<add> public Flux<Object> decode(Publisher<DataBuffer> input, @Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> return decodeInternal(this.fluxDecoder, input, elementType, mimeType, hints);
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/JsonObjectDecoder.java
<ide> public JsonObjectDecoder(int maxObjectLength,
<ide> }
<ide>
<ide> @Override
<del> public Flux<DataBuffer> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> public Flux<DataBuffer> decode(Publisher<DataBuffer> inputStream, @Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> return Flux.from(inputStream)
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriter.java
<ide> public List<MediaType> getWritableMediaTypes() {
<ide> }
<ide>
<ide> @Override
<del> public boolean canWrite(ResolvableType elementType, MediaType mediaType) {
<add> public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) {
<ide> return MultiValueMap.class.isAssignableFrom(elementType.getRawClass()) &&
<ide> (mediaType == null || MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType));
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/codec/xml/Jaxb2XmlDecoder.java
<ide> public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType
<ide> }
<ide>
<ide> @Override
<del> public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> public Flux<Object> decode(Publisher<DataBuffer> inputStream, @Nullable ResolvableType elementType,
<ide> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<ide>
<ide> Class<?> outputClass = elementType.getRawClass();
<ide><path>spring-web/src/main/java/org/springframework/http/converter/AbstractGenericHttpMessageConverter.java
<ide> public boolean canRead(Type type, @Nullable Class<?> contextClass, @Nullable Med
<ide> }
<ide>
<ide> @Override
<del> public boolean canWrite(@Nullable Type type, Class<?> clazz, @Nullable MediaType mediaType) {
<add> public boolean canWrite(@Nullable Type type, @Nullable Class<?> clazz, @Nullable MediaType mediaType) {
<ide> return canWrite(clazz, mediaType);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java
<ide> protected boolean canWrite(@Nullable MediaType mediaType) {
<ide> * Future implementations might add some default behavior, however.
<ide> */
<ide> @Override
<del> public final T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException {
<add> public final T read(@Nullable Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException {
<ide> return readInternal(clazz, inputMessage);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java
<ide> public List<MediaType> getSupportedMediaTypes() {
<ide> }
<ide>
<ide> @Override
<del> public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage)
<add> public BufferedImage read(@Nullable Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage)
<ide> throws IOException, HttpMessageNotReadableException {
<ide>
<ide> ImageInputStream imageInputStream = null;
<ide><path>spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java
<ide> public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
<ide> }
<ide>
<ide> @Override
<del> public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz,
<add> public MultiValueMap<String, String> read(@Nullable Class<? extends MultiValueMap<String, ?>> clazz,
<ide> HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
<ide>
<ide> MediaType contentType = inputMessage.getHeaders().getContentType();
<ide><path>spring-web/src/main/java/org/springframework/http/converter/GenericHttpMessageConverter.java
<ide> T read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage
<ide> * @return {@code true} if writable; {@code false} otherwise
<ide> * @since 4.2
<ide> */
<del> boolean canWrite(@Nullable Type type, Class<?> clazz, @Nullable MediaType mediaType);
<add> boolean canWrite(@Nullable Type type, @Nullable Class<?> clazz, @Nullable MediaType mediaType);
<ide>
<ide> /**
<ide> * Write an given object to the given output message.
<ide><path>spring-web/src/main/java/org/springframework/http/converter/HttpMessageConverter.java
<ide> * @throws IOException in case of I/O errors
<ide> * @throws HttpMessageNotReadableException in case of conversion errors
<ide> */
<del> T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
<add> T read(@Nullable Class<? extends T> clazz, HttpInputMessage inputMessage)
<ide> throws IOException, HttpMessageNotReadableException;
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/http/converter/ResourceRegionHttpMessageConverter.java
<ide> public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
<ide> }
<ide>
<ide> @Override
<del> public boolean canWrite(@Nullable Type type, Class<?> clazz, @Nullable MediaType mediaType) {
<add> public boolean canWrite(@Nullable Type type, @Nullable Class<?> clazz, @Nullable MediaType mediaType) {
<ide> if (!(type instanceof ParameterizedType)) {
<ide> return ResourceRegion.class.isAssignableFrom((Class<?>) type);
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverter.java
<ide> static class ProtobufJavaUtilSupport implements ProtobufFormatSupport {
<ide>
<ide> private final JsonFormat.Printer printer;
<ide>
<del> public ProtobufJavaUtilSupport(JsonFormat.Parser parser, JsonFormat.Printer printer) {
<add> public ProtobufJavaUtilSupport(@Nullable JsonFormat.Parser parser, @Nullable JsonFormat.Printer printer) {
<ide> this.parser = (parser != null ? parser : JsonFormat.parser());
<ide> this.printer = (printer != null ? printer : JsonFormat.printer());
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java
<ide> public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
<ide> * does not convert collections to XML.
<ide> */
<ide> @Override
<del> public boolean canWrite(@Nullable Type type, Class<?> clazz, @Nullable MediaType mediaType) {
<add> public boolean canWrite(@Nullable Type type, @Nullable Class<?> clazz, @Nullable MediaType mediaType) {
<ide> return false;
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/accept/AbstractMappingContentNegotiationStrategy.java
<ide> public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest)
<ide> * an already extracted key.
<ide> * @since 3.2.16
<ide> */
<del> public List<MediaType> resolveMediaTypeKey(NativeWebRequest webRequest, String key)
<add> public List<MediaType> resolveMediaTypeKey(@Nullable NativeWebRequest webRequest, String key)
<ide> throws HttpMediaTypeNotAcceptableException {
<ide>
<ide> if (StringUtils.hasText(key)) {
<ide><path>spring-web/src/main/java/org/springframework/web/bind/EscapedErrors.java
<ide> public void reject(String errorCode, String defaultMessage) {
<ide> }
<ide>
<ide> @Override
<del> public void reject(String errorCode, @Nullable Object[] errorArgs, String defaultMessage) {
<add> public void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
<ide> this.source.reject(errorCode, errorArgs, defaultMessage);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/bind/support/DefaultDataBinderFactory.java
<ide> public DefaultDataBinderFactory(@Nullable WebBindingInitializer initializer) {
<ide> @Override
<ide> @SuppressWarnings("deprecation")
<ide> public final WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target,
<del> String objectName) throws Exception {
<add> @Nullable String objectName) throws Exception {
<ide>
<ide> WebDataBinder dataBinder = createBinderInstance(target, objectName, webRequest);
<ide> if (this.initializer != null) {
<ide><path>spring-web/src/main/java/org/springframework/web/bind/support/WebDataBinderFactory.java
<ide> public interface WebDataBinderFactory {
<ide> * @return the created {@link WebDataBinder} instance, never null
<ide> * @throws Exception raised if the creation and initialization of the data binder fails
<ide> */
<del> WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target, String objectName) throws Exception;
<add> WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target, @Nullable String objectName) throws Exception;
<ide>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/bind/support/WebExchangeBindException.java
<ide> public void reject(String errorCode, String defaultMessage) {
<ide> }
<ide>
<ide> @Override
<del> public void reject(String errorCode, @Nullable Object[] errorArgs, String defaultMessage) {
<add> public void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage) {
<ide> this.bindingResult.reject(errorCode, errorArgs, defaultMessage);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/client/RestOperations.java
<ide> <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedType
<ide> * @return an arbitrary object, as returned by the {@link ResponseExtractor}
<ide> */
<ide> @Nullable
<del> <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
<del> ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException;
<add> <T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
<add> @Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException;
<ide>
<ide> /**
<ide> * Execute the HTTP method to the given URI template, preparing the request with the
<ide> <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
<ide> * @return an arbitrary object, as returned by the {@link ResponseExtractor}
<ide> */
<ide> @Nullable
<del> <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
<del> ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException;
<add> <T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
<add> @Nullable ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException;
<ide>
<ide> /**
<ide> * Execute the HTTP method to the given URL, preparing the request with the
<ide> <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
<ide> * @return an arbitrary object, as returned by the {@link ResponseExtractor}
<ide> */
<ide> @Nullable
<del> <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback,
<del> ResponseExtractor<T> responseExtractor) throws RestClientException;
<add> <T> T execute(URI url, HttpMethod method, @Nullable RequestCallback requestCallback,
<add> @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException;
<ide>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java
<ide> import javax.faces.context.ExternalContext;
<ide> import javax.faces.context.FacesContext;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> public boolean checkNotModified(long lastModifiedTimestamp) {
<ide> }
<ide>
<ide> @Override
<del> public boolean checkNotModified(String eTag) {
<add> public boolean checkNotModified(@Nullable String eTag) {
<ide> return false;
<ide> }
<ide>
<ide> @Override
<del> public boolean checkNotModified(String etag, long lastModifiedTimestamp) {
<add> public boolean checkNotModified(@Nullable String etag, long lastModifiedTimestamp) {
<ide> return false;
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java
<ide>
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide> public boolean checkNotModified(String etag) {
<ide> }
<ide>
<ide> @Override
<del> public boolean checkNotModified(String etag, long lastModifiedTimestamp) {
<add> public boolean checkNotModified(@Nullable String etag, long lastModifiedTimestamp) {
<ide> HttpServletResponse response = getResponse();
<ide> if (this.notModified || HttpStatus.OK.value() != response.getStatus()) {
<ide> return this.notModified;
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/WebRequest.java
<ide> public interface WebRequest extends RequestAttributes {
<ide> * @return true if the request does not require further processing.
<ide> * @since 4.2
<ide> */
<del> boolean checkNotModified(String etag, long lastModifiedTimestamp);
<add> boolean checkNotModified(@Nullable String etag, long lastModifiedTimestamp);
<ide>
<ide> /**
<ide> * Get a short description of this request,
<ide><path>spring-web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java
<ide> public static void registerWebApplicationScopes(ConfigurableListableBeanFactory
<ide> * @param beanFactory the BeanFactory to configure
<ide> * @param sc the ServletContext that we're running within
<ide> */
<del> public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, ServletContext sc) {
<add> public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, @Nullable ServletContext sc) {
<ide> beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
<ide> beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
<ide> if (sc != null) {
<ide> public static void registerEnvironmentBeans(ConfigurableListableBeanFactory bf,
<ide> * @param servletConfig the ServletConfig of the containing Portlet
<ide> */
<ide> public static void registerEnvironmentBeans(
<del> ConfigurableListableBeanFactory bf, ServletContext servletContext, ServletConfig servletConfig) {
<add> ConfigurableListableBeanFactory bf, ServletContext servletContext, @Nullable ServletConfig servletConfig) {
<ide>
<ide> if (servletContext != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) {
<ide> bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, servletContext);
<ide><path>spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java
<ide> public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDisc
<ide> * @exception Exception raised if no suitable argument resolver can be found,
<ide> * or if the method raised an exception
<ide> */
<del> public Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer,
<add> public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
<ide> Object... providedArgs) throws Exception {
<ide>
<ide> Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
<ide><path>spring-web/src/main/java/org/springframework/web/server/ServerWebExchange.java
<ide> import org.springframework.http.codec.multipart.Part;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<ide> /**
<ide> public interface ServerWebExchange {
<ide> * determined for the underlying resource
<ide> * @return true if the request does not require further processing.
<ide> */
<del> boolean checkNotModified(String etag, Instant lastModified);
<add> boolean checkNotModified(@Nullable String etag, Instant lastModified);
<ide>
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/server/ServerWebExchangeDecorator.java
<ide> import org.springframework.http.codec.multipart.Part;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MultiValueMap;
<ide>
<ide> public boolean checkNotModified(String etag) {
<ide> }
<ide>
<ide> @Override
<del> public boolean checkNotModified(String etag, Instant lastModified) {
<add> public boolean checkNotModified(@Nullable String etag, Instant lastModified) {
<ide> return getDelegate().checkNotModified(etag, lastModified);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/DefaultServerWebExchange.java
<ide> import org.springframework.http.codec.multipart.Part;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> public boolean checkNotModified(String etag) {
<ide> }
<ide>
<ide> @Override
<del> public boolean checkNotModified(String etag, Instant lastModified) {
<add> public boolean checkNotModified(@Nullable String etag, Instant lastModified) {
<ide> HttpStatus status = getResponse().getStatusCode();
<ide> if (this.notModified || (status != null && !HttpStatus.OK.equals(status))) {
<ide> return this.notModified;
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java
<ide> public static UriComponentsBuilder newInstance() {
<ide> * @param path the path to initialize with
<ide> * @return the new {@code UriComponentsBuilder}
<ide> */
<del> public static UriComponentsBuilder fromPath(String path) {
<add> public static UriComponentsBuilder fromPath(@Nullable String path) {
<ide> UriComponentsBuilder builder = new UriComponentsBuilder();
<ide> builder.path(path);
<ide> return builder;
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java
<ide> public static class PathRemainingMatchInfo {
<ide>
<ide> private final Map<String, String> matchingVariables;
<ide>
<del> PathRemainingMatchInfo(String pathRemaining) {
<add> PathRemainingMatchInfo(@Nullable String pathRemaining) {
<ide> this(pathRemaining, Collections.emptyMap());
<ide> }
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/BindingContext.java
<ide> public Model getModel() {
<ide> * @param name the name of the target object
<ide> * @return the created data binder
<ide> */
<del> public WebExchangeDataBinder createDataBinder(ServerWebExchange exchange, Object target, String name) {
<add> public WebExchangeDataBinder createDataBinder(ServerWebExchange exchange, @Nullable Object target, String name) {
<ide> WebExchangeDataBinder dataBinder = new WebExchangeDataBinder(target, name);
<ide> if (this.initializer != null) {
<ide> this.initializer.initBinder(dataBinder);
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/AppCacheManifestTransformer.java
<ide> import reactor.core.publisher.SynchronousSink;
<ide>
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.DigestUtils;
<ide> import org.springframework.util.FileCopyUtils;
<ide> import org.springframework.util.StringUtils;
<ide> private static class LineOutput {
<ide> private final Resource resource;
<ide>
<ide>
<del> public LineOutput(String line, Resource resource) {
<add> public LineOutput(String line, @Nullable Resource resource) {
<ide> this.line = line;
<ide> this.resource = resource;
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/DefaultResourceResolverChain.java
<ide> public DefaultResourceResolverChain(List<? extends ResourceResolver> resolvers)
<ide>
<ide>
<ide> @Override
<del> public Mono<Resource> resolveResource(ServerWebExchange exchange, String requestPath,
<add> public Mono<Resource> resolveResource(@Nullable ServerWebExchange exchange, String requestPath,
<ide> List<? extends Resource> locations) {
<ide>
<ide> ResourceResolver resolver = getNext();
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceResolverChain.java
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> public interface ResourceResolverChain {
<ide> * @param locations the locations to search in when looking up resources
<ide> * @return the resolved resource or an empty {@code Mono} if unresolved
<ide> */
<del> Mono<Resource> resolveResource(ServerWebExchange exchange, String requestPath,
<add> Mono<Resource> resolveResource(@Nullable ServerWebExchange exchange, String requestPath,
<ide> List<? extends Resource> locations);
<ide>
<ide> /**
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ControllerMethodResolver.java
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> import org.springframework.http.codec.HttpMessageReader;
<ide> import org.springframework.http.codec.ServerCodecConfigurer;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.web.bind.annotation.InitBinder;
<ide> private static class ArgumentResolverRegistrar {
<ide>
<ide>
<ide> private ArgumentResolverRegistrar(ArgumentResolverConfigurer resolvers,
<del> ServerCodecConfigurer codecs, boolean modelAttribute) {
<add> @Nullable ServerCodecConfigurer codecs, boolean modelAttribute) {
<ide>
<ide> this.customResolvers = resolvers.getCustomResolvers();
<ide> this.messageReaders = codecs != null ? codecs.getReaders() : null;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/HttpEntityArgumentResolver.java
<ide> import org.springframework.http.RequestEntity;
<ide> import org.springframework.http.codec.HttpMessageReader;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.web.reactive.BindingContext;
<ide> import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> public Mono<Object> resolveArgument(
<ide> .defaultIfEmpty(createEntity(null, entityType, exchange.getRequest()));
<ide> }
<ide>
<del> private Object createEntity(Object body, Class<?> entityType, ServerHttpRequest request) {
<add> private Object createEntity(@Nullable Object body, Class<?> entityType, ServerHttpRequest request) {
<ide> return RequestEntity.class.equals(entityType) ?
<ide> new RequestEntity<>(body, request.getHeaders(), request.getMethod(), request.getURI()) :
<ide> new HttpEntity<>(body, request.getHeaders());
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java
<ide> protected LocaleContext buildLocaleContext(HttpServletRequest request) {
<ide> */
<ide> @Nullable
<ide> protected ServletRequestAttributes buildRequestAttributes(
<del> HttpServletRequest request, HttpServletResponse response, RequestAttributes previousAttributes) {
<add> HttpServletRequest request, HttpServletResponse response, @Nullable RequestAttributes previousAttributes) {
<ide>
<ide> if (previousAttributes == null || previousAttributes instanceof ServletRequestAttributes) {
<ide> return new ServletRequestAttributes(request, response);
<ide> private void initContextHolders(
<ide> }
<ide>
<ide> private void resetContextHolders(HttpServletRequest request,
<del> LocaleContext prevLocaleContext, RequestAttributes previousAttributes) {
<add> @Nullable LocaleContext prevLocaleContext, @Nullable RequestAttributes previousAttributes) {
<ide>
<ide> LocaleContextHolder.setLocaleContext(prevLocaleContext, this.threadContextInheritable);
<ide> RequestContextHolder.setRequestAttributes(previousAttributes, this.threadContextInheritable);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.java
<ide> void applyPostHandle(HttpServletRequest request, HttpServletResponse response, M
<ide> * Will just invoke afterCompletion for all interceptors whose preHandle invocation
<ide> * has successfully completed and returned true.
<ide> */
<del> void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex)
<add> void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex)
<ide> throws Exception {
<ide>
<ide> HandlerInterceptor[] interceptors = getInterceptors();
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/MvcNamespaceUtils.java
<ide> public static void registerDefaultComponents(ParserContext parserContext, Object
<ide> * under that well-known name, unless already registered.
<ide> * @return a RuntimeBeanReference to this {@link UrlPathHelper} instance
<ide> */
<del> public static RuntimeBeanReference registerUrlPathHelper(RuntimeBeanReference urlPathHelperRef, ParserContext parserContext, Object source) {
<add> public static RuntimeBeanReference registerUrlPathHelper(@Nullable RuntimeBeanReference urlPathHelperRef, ParserContext parserContext, Object source) {
<ide> if (urlPathHelperRef != null) {
<ide> if (parserContext.getRegistry().isAlias(URL_PATH_HELPER_BEAN_NAME)) {
<ide> parserContext.getRegistry().removeAlias(URL_PATH_HELPER_BEAN_NAME);
<ide> else if (!parserContext.getRegistry().isAlias(URL_PATH_HELPER_BEAN_NAME)
<ide> * under that well-known name, unless already registered.
<ide> * @return a RuntimeBeanReference to this {@link PathMatcher} instance
<ide> */
<del> public static RuntimeBeanReference registerPathMatcher(RuntimeBeanReference pathMatcherRef, ParserContext parserContext, Object source) {
<add> public static RuntimeBeanReference registerPathMatcher(@Nullable RuntimeBeanReference pathMatcherRef, ParserContext parserContext, Object source) {
<ide> if (pathMatcherRef != null) {
<ide> if (parserContext.getRegistry().isAlias(PATH_MATCHER_BEAN_NAME)) {
<ide> parserContext.getRegistry().removeAlias(PATH_MATCHER_BEAN_NAME);
<ide> private static void registerSimpleControllerHandlerAdapter(ParserContext parserC
<ide> * if a non-null CORS configuration is provided.
<ide> * @return a RuntimeBeanReference to this {@code Map<String, CorsConfiguration>} instance
<ide> */
<del> public static RuntimeBeanReference registerCorsConfigurations(Map<String, CorsConfiguration> corsConfigurations, ParserContext parserContext, Object source) {
<add> public static RuntimeBeanReference registerCorsConfigurations(@Nullable Map<String, CorsConfiguration> corsConfigurations, ParserContext parserContext, Object source) {
<ide> if (!parserContext.getRegistry().containsBeanDefinition(CORS_CONFIGURATION_BEAN_NAME)) {
<ide> RootBeanDefinition corsConfigurationsDef = new RootBeanDefinition(LinkedHashMap.class);
<ide> corsConfigurationsDef.setSource(source);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java
<ide> public void enable() {
<ide> * This is useful when the default Servlet cannot be auto-detected, for example when it has been manually configured.
<ide> * @see DefaultServletHttpRequestHandler
<ide> */
<del> public void enable(String defaultServletName) {
<add> public void enable(@Nullable String defaultServletName) {
<ide> handler = new DefaultServletHttpRequestHandler();
<ide> handler.setDefaultServletName(defaultServletName);
<ide> handler.setServletContext(servletContext);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java
<ide> import org.springframework.http.converter.HttpMessageNotWritableException;
<ide> import org.springframework.http.server.ServletServerHttpRequest;
<ide> import org.springframework.http.server.ServletServerHttpResponse;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.HttpMediaTypeNotAcceptableException;
<ide> protected List<MediaType> getProducibleMediaTypes(HttpServletRequest request, Cl
<ide> * @since 4.2
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> protected List<MediaType> getProducibleMediaTypes(HttpServletRequest request, Class<?> valueClass, Type declaredType) {
<add> protected List<MediaType> getProducibleMediaTypes(HttpServletRequest request, Class<?> valueClass, @Nullable Type declaredType) {
<ide> Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
<ide> if (!CollectionUtils.isEmpty(mediaTypes)) {
<ide> return new ArrayList<>(mediaTypes);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java
<ide> public static UriComponentsBuilder fromController(Class<?> controllerType) {
<ide> * @param controllerType the controller to build a URI for
<ide> * @return a UriComponentsBuilder instance (never {@code null})
<ide> */
<del> public static UriComponentsBuilder fromController(UriComponentsBuilder builder,
<add> public static UriComponentsBuilder fromController(@Nullable UriComponentsBuilder builder,
<ide> Class<?> controllerType) {
<ide>
<ide> builder = getBaseUrlToUse(builder);
<ide> public static MethodArgumentBuilder fromMappingName(String mappingName) {
<ide> * if there is no unique match
<ide> * @since 4.2
<ide> */
<del> public static MethodArgumentBuilder fromMappingName(UriComponentsBuilder builder, String name) {
<add> public static MethodArgumentBuilder fromMappingName(@Nullable UriComponentsBuilder builder, String name) {
<ide> RequestMappingInfoHandlerMapping handlerMapping = getRequestMappingInfoHandlerMapping();
<ide> List<HandlerMethod> handlerMethods = handlerMapping.getHandlerMethodsForMappingName(name);
<ide> if (handlerMethods == null) {
<ide> public static UriComponentsBuilder fromMethod(UriComponentsBuilder baseUrl,
<ide> (controllerType != null ? controllerType : method.getDeclaringClass()), method, args);
<ide> }
<ide>
<del> private static UriComponentsBuilder fromMethodInternal(UriComponentsBuilder baseUrl,
<add> private static UriComponentsBuilder fromMethodInternal(@Nullable UriComponentsBuilder baseUrl,
<ide> Class<?> controllerType, Method method, Object... args) {
<ide>
<ide> baseUrl = getBaseUrlToUse(baseUrl);
<ide> public UriComponentsBuilder withMethod(Class<?> controllerType, Method method, O
<ide> }
<ide>
<ide> @Override
<del> public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) {
<add> public Object intercept(Object obj, Method method, Object[] args, @Nullable MethodProxy proxy) {
<ide> if (getControllerMethod.equals(method)) {
<ide> return this.controllerMethod;
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitter.java
<ide> public void send(Object object) throws IOException {
<ide> * @throws IOException raised when an I/O error occurs
<ide> * @throws java.lang.IllegalStateException wraps any other errors
<ide> */
<del> public synchronized void send(Object object, MediaType mediaType) throws IOException {
<add> public synchronized void send(Object object, @Nullable MediaType mediaType) throws IOException {
<ide> Assert.state(!this.complete, "ResponseBodyEmitter is already set complete");
<ide> sendInternal(object, mediaType);
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java
<ide> else if (ex instanceof AsyncRequestTimeoutException) {
<ide> * @param status the response status
<ide> * @param request the current request
<ide> */
<del> protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body,
<add> protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body,
<ide> HttpHeaders headers, HttpStatus status, WebRequest request) {
<ide>
<ide> if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.server.ServerHttpResponse;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> public void send(Object object) throws IOException {
<ide> * @throws IOException raised when an I/O error occurs
<ide> */
<ide> @Override
<del> public void send(Object object, MediaType mediaType) throws IOException {
<add> public void send(Object object, @Nullable MediaType mediaType) throws IOException {
<ide> if (object != null) {
<ide> send(event().data(object, mediaType));
<ide> }
<ide> public interface SseEventBuilder {
<ide> /**
<ide> * Add an SSE "data" line.
<ide> */
<del> SseEventBuilder data(Object object, MediaType mediaType);
<add> SseEventBuilder data(Object object, @Nullable MediaType mediaType);
<ide>
<ide> /**
<ide> * Return one or more Object-MediaType pairs to write via
<ide> public SseEventBuilder data(Object object) {
<ide> }
<ide>
<ide> @Override
<del> public SseEventBuilder data(Object object, MediaType mediaType) {
<add> public SseEventBuilder data(Object object, @Nullable MediaType mediaType) {
<ide> append("data:");
<ide> saveAppendedText();
<ide> this.dataToSend.add(new DataWithMediaType(object, mediaType));
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/AppCacheManifestTransformer.java
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.DigestUtils;
<ide> import org.springframework.util.FileCopyUtils;
<ide> import org.springframework.util.StringUtils;
<ide> private static class LineOutput {
<ide> private final Resource resource;
<ide>
<ide>
<del> public LineOutput(String line, Resource resource) {
<add> public LineOutput(String line, @Nullable Resource resource) {
<ide> this.line = line;
<ide> this.resource = resource;
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/DefaultResourceResolverChain.java
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> public DefaultResourceResolverChain(List<? extends ResourceResolver> resolvers)
<ide>
<ide>
<ide> @Override
<del> public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations) {
<add> public Resource resolveResource(@Nullable HttpServletRequest request, String requestPath, List<? extends Resource> locations) {
<ide> ResourceResolver resolver = getNext();
<ide> if (resolver == null) {
<ide> return null;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceResolverChain.java
<ide> public interface ResourceResolverChain {
<ide> * @return the resolved resource or {@code null} if unresolved
<ide> */
<ide> @Nullable
<del> Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations);
<add> Resource resolveResource(@Nullable HttpServletRequest request, String requestPath, List<? extends Resource> locations);
<ide>
<ide> /**
<ide> * Resolve the externally facing <em>public</em> URL path for clients to use
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java
<ide> protected RequestContext() {
<ide> * @see org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_ATTRIBUTE
<ide> * @see org.springframework.web.servlet.DispatcherServlet#THEME_RESOLVER_ATTRIBUTE
<ide> */
<del> protected void initContext(HttpServletRequest request, HttpServletResponse response, @Nullable ServletContext servletContext,
<add> protected void initContext(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable ServletContext servletContext,
<ide> @Nullable Map<String, Object> model) {
<ide>
<ide> this.request = request;
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractView.java
<ide> public String getBeanName() {
<ide> * <p>May be ignored by subclasses if the view itself is assumed
<ide> * to set the content type, e.g. in case of JSPs.
<ide> */
<del> public void setContentType(String contentType) {
<add> public void setContentType(@Nullable String contentType) {
<ide> this.contentType = contentType;
<ide> }
<ide>
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java
<ide> public void setRenderFunction(String functionName) {
<ide> * @since 4.2.1
<ide> */
<ide> @Override
<del> public void setContentType(String contentType) {
<add> public void setContentType(@Nullable String contentType) {
<ide> super.setContentType(contentType);
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketHttpHeaders.java
<ide> import java.util.Set;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<ide>
<ide> /**
<ide> public String getFirst(String headerName) {
<ide> * @see #set(String, String)
<ide> */
<ide> @Override
<del> public void add(String headerName, String headerValue) {
<add> public void add(String headerName, @Nullable String headerValue) {
<ide> this.headers.add(headerName, headerValue);
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/AbstractWebSocketClient.java
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.concurrent.ListenableFuture;
<ide> import org.springframework.web.socket.WebSocketExtension;
<ide> public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocket
<ide>
<ide> @Override
<ide> public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler,
<del> WebSocketHttpHeaders headers, URI uri) {
<add> @Nullable WebSocketHttpHeaders headers, URI uri) {
<ide>
<ide> Assert.notNull(webSocketHandler, "WebSocketHandler must not be null");
<ide> assertUri(uri);
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/WebSocketClient.java
<ide>
<ide> import java.net.URI;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.concurrent.ListenableFuture;
<ide> import org.springframework.web.socket.WebSocketHandler;
<ide> import org.springframework.web.socket.WebSocketHttpHeaders;
<ide> ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler
<ide> String uriTemplate, Object... uriVariables);
<ide>
<ide> ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler,
<del> WebSocketHttpHeaders headers, URI uri);
<add> @Nullable WebSocketHttpHeaders headers, URI uri);
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketStompClient.java
<ide>
<ide> import org.springframework.context.Lifecycle;
<ide> import org.springframework.context.SmartLifecycle;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.simp.stomp.BufferingStompDecoder;
<ide> import org.springframework.messaging.simp.stomp.ConnectionHandlingStompSession;
<ide> public ListenableFuture<StompSession> connect(String url, StompSessionHandler ha
<ide> * @param uriVariables URI variables to expand into the URL
<ide> * @return ListenableFuture for access to the session when ready for use
<ide> */
<del> public ListenableFuture<StompSession> connect(String url, WebSocketHttpHeaders handshakeHeaders,
<add> public ListenableFuture<StompSession> connect(String url, @Nullable WebSocketHttpHeaders handshakeHeaders,
<ide> StompSessionHandler handler, Object... uriVariables) {
<ide>
<ide> return connect(url, handshakeHeaders, null, handler, uriVariables);
<ide> public ListenableFuture<StompSession> connect(String url, WebSocketHttpHeaders h
<ide> * @return ListenableFuture for access to the session when ready for use
<ide> */
<ide> public ListenableFuture<StompSession> connect(String url, WebSocketHttpHeaders handshakeHeaders,
<del> StompHeaders connectHeaders, StompSessionHandler handler, Object... uriVariables) {
<add> @Nullable StompHeaders connectHeaders, StompSessionHandler handler, Object... uriVariables) {
<ide>
<ide> Assert.notNull(url, "'url' must not be null");
<ide> URI uri = UriComponentsBuilder.fromUriString(url).buildAndExpand(uriVariables).encode().toUri();
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/SockJsException.java
<ide> package org.springframework.web.socket.sockjs;
<ide>
<ide> import org.springframework.core.NestedRuntimeException;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * Base class for exceptions raised while processing SockJS HTTP requests.
<ide> public SockJsException(String message, Throwable cause) {
<ide> * @param sessionId the SockJS session id
<ide> * @param cause the root cause
<ide> */
<del> public SockJsException(String message, String sessionId, Throwable cause) {
<add> public SockJsException(String message, @Nullable String sessionId, @Nullable Throwable cause) {
<ide> super(message, cause);
<ide> this.sessionId = sessionId;
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/AbstractClientSockJsSession.java
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.concurrent.SettableListenableFuture;
<ide> import org.springframework.web.socket.CloseStatus;
<ide> public void handleTransportError(Throwable error) {
<ide> }
<ide> }
<ide>
<del> public void afterTransportClosed(CloseStatus closeStatus) {
<add> public void afterTransportClosed(@Nullable CloseStatus closeStatus) {
<ide> this.closeStatus = (this.closeStatus != null ? this.closeStatus : closeStatus);
<ide> Assert.state(this.closeStatus != null, "CloseStatus not available");
<ide> if (logger.isDebugEnabled()) {
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/DefaultTransportRequest.java
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.scheduling.TaskScheduler;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.concurrent.ListenableFutureCallback;
<ide> public void run() {
<ide> handleFailure(null, true);
<ide> }
<ide>
<del> private void handleFailure(Throwable ex, boolean isTimeoutFailure) {
<add> private void handleFailure(@Nullable Throwable ex, boolean isTimeoutFailure) {
<ide> if (this.handled.compareAndSet(false, true)) {
<ide> if (isTimeoutFailure) {
<ide> String message = "Connect timed out for " + DefaultTransportRequest.this;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/JettyXhrTransport.java
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.ResponseEntity;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.concurrent.SettableListenableFuture;
<ide> import org.springframework.web.client.HttpServerErrorException;
<ide> public ResponseEntity<String> executeSendRequestInternal(URI url, HttpHeaders he
<ide> return executeRequest(url, HttpMethod.POST, headers, message.getPayload());
<ide> }
<ide>
<del> protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, String body) {
<add> protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, @Nullable String body) {
<ide> Request httpRequest = this.httpClient.newRequest(url).method(method);
<ide> addHttpHeaders(httpRequest, headers);
<ide> if (body != null) {
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java
<ide> public ListenableFuture<WebSocketSession> doHandshake(
<ide>
<ide> @Override
<ide> public final ListenableFuture<WebSocketSession> doHandshake(
<del> WebSocketHandler handler, WebSocketHttpHeaders headers, URI url) {
<add> WebSocketHandler handler, @Nullable WebSocketHttpHeaders headers, URI url) {
<ide>
<ide> Assert.notNull(handler, "WebSocketHandler is required");
<ide> Assert.notNull(url, "URL is required");
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/DefaultSockJsService.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.scheduling.TaskScheduler;
<ide> import org.springframework.web.context.ServletContextAware;
<ide> import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
<ide> public DefaultSockJsService(TaskScheduler scheduler, Collection<TransportHandler
<ide> }
<ide>
<ide>
<del> private static Set<TransportHandler> getDefaultTransportHandlers(Collection<TransportHandler> overrides) {
<add> private static Set<TransportHandler> getDefaultTransportHandlers(@Nullable Collection<TransportHandler> overrides) {
<ide> Set<TransportHandler> result = new LinkedHashSet<>(8);
<ide> result.add(new XhrPollingTransportHandler());
<ide> result.add(new XhrReceivingTransportHandler()); | 219 |
Go | Go | use same args on restart | 2ed512c7faea938b0b07e69187b8a132e2ecb66a | <ide><path>integration-cli/check_test.go
<ide> func (s *DockerSwarmSuite) AddDaemon(c *check.C, joinSwarm, manager bool) *daemo
<ide> d.StartAndSwarmInit(c)
<ide> }
<ide> } else {
<del> d.StartWithBusybox(c, "--iptables=false", "--swarm-default-advertise-addr=lo")
<add> d.StartNode(c)
<ide> }
<ide>
<ide> s.portIndex++
<ide><path>integration-cli/docker_api_swarm_node_test.go
<ide> func (s *DockerSwarmSuite) TestAPISwarmNodeRemove(c *check.C) {
<ide> c.Assert(len(nodes), checker.Equals, 2, check.Commentf("nodes: %#v", nodes))
<ide>
<ide> // Restart the node that was removed
<del> d2.Restart(c)
<add> d2.RestartNode(c)
<ide>
<ide> // Give some time for the node to rejoin
<ide> time.Sleep(1 * time.Second)
<ide><path>integration-cli/docker_api_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestAPISwarmInit(c *check.C) {
<ide> d1.Stop(c)
<ide> d2.Stop(c)
<ide>
<del> d1.Start(c)
<del> d2.Start(c)
<add> d1.StartNode(c)
<add> d2.StartNode(c)
<ide>
<ide> info = d1.SwarmInfo(c)
<ide> c.Assert(info.ControlAvailable, checker.True)
<ide> func (s *DockerSwarmSuite) TestAPISwarmLeaderElection(c *check.C) {
<ide> stableleader := leader
<ide>
<ide> // add the d1, the initial leader, back
<del> d1.Start(c)
<add> d1.StartNode(c)
<ide>
<ide> // wait for possible election
<ide> c.Logf("Waiting for possible election...")
<ide> func (s *DockerSwarmSuite) TestAPISwarmRaftQuorum(c *check.C) {
<ide> return err.Error(), nil
<ide> }, checker.Contains, "Make sure more than half of the managers are online.")
<ide>
<del> d2.Start(c)
<add> d2.StartNode(c)
<ide>
<ide> // make sure there is a leader
<ide> waitAndAssert(c, defaultReconciliationTimeout, d1.CheckLeader, checker.IsNil)
<ide> func (s *DockerSwarmSuite) TestAPISwarmRestoreOnPendingJoin(c *check.C) {
<ide>
<ide> waitAndAssert(c, defaultReconciliationTimeout, d.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStatePending)
<ide>
<del> d.Stop(c)
<del> d.Start(c)
<add> d.RestartNode(c)
<ide>
<ide> info := d.SwarmInfo(c)
<ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive)
<ide> func (s *DockerSwarmSuite) TestAPISwarmManagerRestore(c *check.C) {
<ide> id := d1.CreateService(c, simpleTestService, setInstances(instances))
<ide>
<ide> d1.GetService(c, id)
<del> d1.Stop(c)
<del> d1.Start(c)
<add> d1.RestartNode(c)
<ide> d1.GetService(c, id)
<ide>
<ide> d2 := s.AddDaemon(c, true, true)
<ide> d2.GetService(c, id)
<del> d2.Stop(c)
<del> d2.Start(c)
<add> d2.RestartNode(c)
<ide> d2.GetService(c, id)
<ide>
<ide> d3 := s.AddDaemon(c, true, true)
<ide> d3.GetService(c, id)
<del> d3.Stop(c)
<del> d3.Start(c)
<add> d3.RestartNode(c)
<ide> d3.GetService(c, id)
<ide>
<ide> d3.Kill()
<ide> time.Sleep(1 * time.Second) // time to handle signal
<del> d3.Start(c)
<add> d3.StartNode(c)
<ide> d3.GetService(c, id)
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmIncompatibleDaemon(c *check.C) {
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(string(content), checker.Contains, "--live-restore daemon configuration is incompatible with swarm mode")
<ide> // restart for teardown
<del> d.Start(c)
<add> d.StartNode(c)
<ide> }
<ide>
<ide> func (s *DockerSwarmSuite) TestSwarmServiceTemplatingHostname(c *check.C) {
<ide> func (s *DockerSwarmSuite) TestSwarmContainerAutoStart(c *check.C) {
<ide> c.Assert(err, checker.IsNil, check.Commentf("%s", out))
<ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
<ide>
<del> d.Restart(c)
<add> d.RestartNode(c)
<ide>
<ide> out, err = d.Cmd("ps", "-q")
<ide> c.Assert(err, checker.IsNil, check.Commentf("%s", out))
<ide> func checkSwarmLockedToUnlocked(c *check.C, d *daemon.Daemon) {
<ide> // Wait for the PEM file to become unencrypted
<ide> waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, false)
<ide>
<del> d.Restart(c)
<add> d.RestartNode(c)
<ide> c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
<ide> }
<ide>
<ide> func checkSwarmUnlockedToLocked(c *check.C, d *daemon.Daemon) {
<ide> // Wait for the PEM file to become encrypted
<ide> waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, true)
<ide>
<del> d.Restart(c)
<add> d.RestartNode(c)
<ide> c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
<ide> }
<ide>
<ide> func (s *DockerSwarmSuite) TestSwarmInitLocked(c *check.C) {
<ide> c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
<ide>
<ide> // It starts off locked
<del> d.Restart(c)
<add> d.RestartNode(c)
<ide> c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
<ide>
<ide> cmd := d.Command("swarm", "unlock")
<ide> func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *check.C) {
<ide> c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
<ide>
<ide> // It starts off locked
<del> d.Restart(c, "--swarm-default-advertise-addr=lo")
<add> d.RestartNode(c)
<ide>
<ide> info := d.SwarmInfo(c)
<ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateLocked)
<ide> func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) {
<ide> d3 := s.AddDaemon(c, true, true)
<ide>
<ide> // they start off unlocked
<del> d2.Restart(c)
<add> d2.RestartNode(c)
<ide> c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
<ide>
<ide> // stop this one so it does not get autolock info
<ide> func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) {
<ide> }
<ide>
<ide> // d2 never got the cluster update, so it is still set to unlocked
<del> d2.Start(c)
<add> d2.StartNode(c)
<ide> c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
<ide>
<ide> // d2 is now set to lock
<ide> func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) {
<ide>
<ide> // managers who join now are never set to locked in the first place
<ide> d4 := s.AddDaemon(c, true, true)
<del> d4.Restart(c)
<add> d4.RestartNode(c)
<ide> c.Assert(getNodeStatus(c, d4), checker.Equals, swarm.LocalNodeStateActive)
<ide> }
<ide>
<ide> func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) {
<ide>
<ide> // joined workers start off unlocked
<ide> d2 := s.AddDaemon(c, true, false)
<del> d2.Restart(c)
<add> d2.RestartNode(c)
<ide> c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
<ide>
<ide> // promote worker
<ide> func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) {
<ide> }, checker.Equals, "swarm-worker")
<ide>
<ide> // by now, it should *never* be locked on restart
<del> d3.Restart(c)
<add> d3.RestartNode(c)
<ide> c.Assert(getNodeStatus(c, d3), checker.Equals, swarm.LocalNodeStateActive)
<ide> }
<ide>
<ide> func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) {
<ide> c.Assert(newUnlockKey, checker.Not(checker.Equals), "")
<ide> c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey)
<ide>
<del> d.Restart(c)
<add> d.RestartNode(c)
<ide> c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
<ide>
<ide> outs, _ = d.Cmd("node", "ls")
<ide> func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) {
<ide>
<ide> time.Sleep(3 * time.Second)
<ide>
<del> d.Restart(c)
<add> d.RestartNode(c)
<ide>
<ide> cmd = d.Command("swarm", "unlock")
<ide> cmd.Stdin = bytes.NewBufferString(unlockKey)
<ide> func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) {
<ide> c.Assert(newUnlockKey, checker.Not(checker.Equals), "")
<ide> c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey)
<ide>
<del> d2.Restart(c)
<del> d3.Restart(c)
<add> d2.RestartNode(c)
<add> d3.RestartNode(c)
<ide>
<ide> for _, d := range []*daemon.Daemon{d2, d3} {
<ide> c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
<ide> func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) {
<ide>
<ide> time.Sleep(3 * time.Second)
<ide>
<del> d.Restart(c)
<add> d.RestartNode(c)
<ide>
<ide> cmd = d.Command("swarm", "unlock")
<ide> cmd.Stdin = bytes.NewBufferString(unlockKey)
<ide><path>internal/test/daemon/swarm.go
<ide> const (
<ide> defaultSwarmListenAddr = "0.0.0.0"
<ide> )
<ide>
<del>// StartAndSwarmInit starts the daemon (with busybox) and init the swarm
<del>func (d *Daemon) StartAndSwarmInit(t testingT) {
<add>var (
<add> startArgs = []string{"--iptables=false", "--swarm-default-advertise-addr=lo"}
<add>)
<add>
<add>// StartNode starts daemon to be used as a swarm node
<add>func (d *Daemon) StartNode(t testingT) {
<ide> if ht, ok := t.(test.HelperT); ok {
<ide> ht.Helper()
<ide> }
<ide> // avoid networking conflicts
<del> args := []string{"--iptables=false", "--swarm-default-advertise-addr=lo"}
<del> d.StartWithBusybox(t, args...)
<del>
<del> d.SwarmInit(t, swarm.InitRequest{})
<add> d.StartWithBusybox(t, startArgs...)
<ide> }
<ide>
<del>// StartAndSwarmJoin starts the daemon (with busybox) and join the specified swarm as worker or manager
<del>func (d *Daemon) StartAndSwarmJoin(t testingT, leader *Daemon, manager bool) {
<add>// RestartNode restarts a daemon to be used as a swarm node
<add>func (d *Daemon) RestartNode(t testingT) {
<ide> if ht, ok := t.(test.HelperT); ok {
<ide> ht.Helper()
<ide> }
<ide> // avoid networking conflicts
<del> args := []string{"--iptables=false", "--swarm-default-advertise-addr=lo"}
<del> d.StartWithBusybox(t, args...)
<add> d.Stop(t)
<add> d.StartWithBusybox(t, startArgs...)
<add>}
<add>
<add>// StartAndSwarmInit starts the daemon (with busybox) and init the swarm
<add>func (d *Daemon) StartAndSwarmInit(t testingT) {
<add> d.StartNode(t)
<add> d.SwarmInit(t, swarm.InitRequest{})
<add>}
<add>
<add>// StartAndSwarmJoin starts the daemon (with busybox) and join the specified swarm as worker or manager
<add>func (d *Daemon) StartAndSwarmJoin(t testingT, leader *Daemon, manager bool) {
<add> d.StartNode(t)
<ide>
<ide> tokens := leader.JoinTokens(t)
<ide> token := tokens.Worker | 5 |
Text | Text | use present tense in events.md | c4b3b2341383369ccbd0fa68e51266f580e9a5fd | <ide><path>doc/api/events.md
<ide> can be used.
<ide>
<ide> When the `EventEmitter` object emits an event, all of the functions attached
<ide> to that specific event are called _synchronously_. Any values returned by the
<del>called listeners are _ignored_ and will be discarded.
<add>called listeners are _ignored_ and discarded.
<ide>
<ide> The following example shows a simple `EventEmitter` instance with a single
<ide> listener. The `eventEmitter.on()` method is used to register listeners, while
<ide> myEmitter.emit('event', 'a', 'b');
<ide> ## Handling events only once
<ide>
<ide> When a listener is registered using the `eventEmitter.on()` method, that
<del>listener will be invoked _every time_ the named event is emitted.
<add>listener is invoked _every time_ the named event is emitted.
<ide>
<ide> ```js
<ide> const myEmitter = new MyEmitter();
<ide> added: v0.1.26
<ide> The `EventEmitter` instance will emit its own `'newListener'` event *before*
<ide> a listener is added to its internal array of listeners.
<ide>
<del>Listeners registered for the `'newListener'` event will be passed the event
<add>Listeners registered for the `'newListener'` event are passed the event
<ide> name and a reference to the listener being added.
<ide>
<ide> The fact that the event is triggered before adding the listener has a subtle
<ide> but important side effect: any *additional* listeners registered to the same
<del>`name` *within* the `'newListener'` callback will be inserted *before* the
<add>`name` *within* the `'newListener'` callback are inserted *before* the
<ide> listener that is in the process of being added.
<ide>
<ide> ```js
<ide> event. This limit can be changed for individual `EventEmitter` instances
<ide> using the [`emitter.setMaxListeners(n)`][] method. To change the default
<ide> for *all* `EventEmitter` instances, the `EventEmitter.defaultMaxListeners`
<ide> property can be used. If this value is not a positive number, a `TypeError`
<del>will be thrown.
<add>is thrown.
<ide>
<ide> Take caution when setting the `EventEmitter.defaultMaxListeners` because the
<ide> change affects *all* `EventEmitter` instances, including those created before
<ide> added: v6.0.0
<ide> * Returns: {Array}
<ide>
<ide> Returns an array listing the events for which the emitter has registered
<del>listeners. The values in the array will be strings or `Symbol`s.
<add>listeners. The values in the array are strings or `Symbol`s.
<ide>
<ide> ```js
<ide> const EventEmitter = require('events');
<ide> listener array. If any single listener has been added multiple times to the
<ide> listener array for the specified `eventName`, then `removeListener()` must be
<ide> called multiple times to remove each instance.
<ide>
<del>Once an event has been emitted, all listeners attached to it at the
<del>time of emitting will be called in order. This implies that any
<add>Once an event is emitted, all listeners attached to it at the
<add>time of emitting are called in order. This implies that any
<ide> `removeListener()` or `removeAllListeners()` calls *after* emitting and
<ide> *before* the last listener finishes execution will not remove them from
<del>`emit()` in progress. Subsequent events will behave as expected.
<add>`emit()` in progress. Subsequent events behave as expected.
<ide>
<ide> ```js
<ide> const myEmitter = new MyEmitter();
<ide> There are two key differences between the Node.js `EventTarget` and the
<ide> event.
<ide> 2. In the Node.js `EventTarget`, if an event listener is an async function
<ide> or returns a `Promise`, and the returned `Promise` rejects, the rejection
<del> will be automatically captured and handled the same way as a listener that
<add> is automatically captured and handled the same way as a listener that
<ide> throws synchronously (see [`EventTarget` error handling][] for details).
<ide>
<ide> ### `NodeEventTarget` vs. `EventEmitter`
<ide> certain situations. A `NodeEventTarget` is *not* an instance of `EventEmitter`
<ide> and cannot be used in place of an `EventEmitter` in most cases.
<ide>
<ide> 1. Unlike `EventEmitter`, any given `listener` can be registered at most once
<del> per event `type`. Attempts to register a `listener` multiple times will be
<add> per event `type`. Attempts to register a `listener` multiple times are
<ide> ignored.
<ide> 2. The `NodeEventTarget` does not emulate the full `EventEmitter` API.
<ide> Specifically the `prependListener()`, `prependOnceListener()`,
<ide> and cannot be used in place of an `EventEmitter` in most cases.
<ide> Event listeners registered for an event `type` may either be JavaScript
<ide> functions or objects with a `handleEvent` property whose value is a function.
<ide>
<del>In either case, the handler function will be invoked with the `event` argument
<add>In either case, the handler function is invoked with the `event` argument
<ide> passed to the `eventTarget.dispatchEvent()` function.
<ide>
<ide> Async functions may be used as event listeners. If an async handler function
<del>rejects, the rejection will be captured and will be handled as described in
<add>rejects, the rejection is captured and handled as described in
<ide> [`EventTarget` error handling][].
<ide>
<del>An error thrown by one handler function will not prevent the other handlers
<add>An error thrown by one handler function does not prevent the other handlers
<ide> from being invoked.
<ide>
<del>The return value of a handler function will be ignored.
<add>The return value of a handler function is ignored.
<ide>
<ide> Handlers are always invoked in the order they were added.
<ide>
<ide> target.addEventListener('foo', handler4, { once: true });
<ide> ### `EventTarget` error handling
<ide>
<ide> When a registered event listener throws (or returns a Promise that rejects),
<del>by default the error will be forwarded to the `process.on('error')` event
<add>by default the error is forwarded to the `process.on('error')` event
<ide> on `process.nextTick()`. Throwing within an event listener will *not* stop
<ide> the other registered handlers from being invoked.
<ide>
<ide> added: v14.5.0
<ide>
<ide> * Type: {boolean}
<ide>
<del>Will be `true` if `cancelable` is `true` and `event.preventDefault()` has been
<add>Is `true` if `cancelable` is `true` and `event.preventDefault()` has been
<ide> called.
<ide>
<ide> #### `event.eventPhase`
<ide> added: v14.5.0
<ide> * `type` {string}
<ide> * `listener` {Function|EventListener}
<ide> * `options` {Object}
<del> * `once` {boolean} When `true`, the listener will be automatically removed
<add> * `once` {boolean} When `true`, the listener is automatically removed
<ide> when it is first invoked. **Default:** `false`.
<ide> * `passive` {boolean} When `true`, serves as a hint that the listener will
<ide> not call the `Event` object's `preventDefault()` method.
<ide> **Default:** `false`.
<ide> * `capture` {boolean} Not directly used by Node.js. Added for API
<ide> completeness. **Default:** `false`.
<ide>
<del>Adds a new handler for the `type` event. Any given `listener` will be added
<add>Adds a new handler for the `type` event. Any given `listener` is added
<ide> only once per `type` and per `capture` option value.
<ide>
<del>If the `once` option is `true`, the `listener` will be removed after the
<add>If the `once` option is `true`, the `listener` is removed after the
<ide> next time a `type` event is dispatched.
<ide>
<ide> The `capture` option is not used by Node.js in any functional way other than
<ide> Dispatches the `event` to the list of handlers for `event.type`. The `event`
<ide> may be an `Event` object or any object with a `type` property whose value is
<ide> a `string`.
<ide>
<del>The registered event listeners will be synchronously invoked in the order they
<add>The registered event listeners is synchronously invoked in the order they
<ide> were registered.
<ide>
<ide> #### `eventTarget.removeEventListener(type, listener)` | 1 |
Javascript | Javascript | add todo item | ab144f4843c2c7630564f26cfbdd69d01d8fbd00 | <ide><path>lib/tls.js
<ide> Server.prototype.setOptions = function(options) {
<ide> // s.end("hello world\n");
<ide> // });
<ide> //
<add>//
<add>// TODO: make port, host part of options!
<ide> exports.connect = function(port /* host, options, cb */) {
<ide> // parse args
<ide> var host, options = {}, cb; | 1 |
Javascript | Javascript | add assert.notdeepequal() tests | 294e3008ad65d92fc6ad9d97f043093054e079ad | <ide><path>test/parallel/test-assert.js
<ide> assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)),
<ide> a.AssertionError,
<ide> 'deepEqual(new Date(), new Date(2000, 3, 14))');
<ide>
<add>assert.throws(makeBlock(
<add> a.notDeepEqual,
<add> new Date(2000, 3, 14),
<add> new Date(2000, 3, 14)),
<add> a.AssertionError,
<add> 'notDeepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'
<add>);
<add>
<add>assert.doesNotThrow(makeBlock(
<add> a.notDeepEqual,
<add> new Date(),
<add> new Date(2000, 3, 14)),
<add> 'notDeepEqual(new Date(), new Date(2000, 3, 14))'
<add>);
<add>
<ide> // 7.3
<ide> assert.doesNotThrow(makeBlock(a.deepEqual, /a/, /a/));
<ide> assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g)); | 1 |
PHP | PHP | wrap long lines | e2461397b9463d46438b49878608620d24cafea7 | <ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> public function load($test)
<ide> try {
<ide> $fixture->dropConstraints($db);
<ide> } catch (PDOException $e) {
<del> $msg = sprintf('Unable to drop constraints for fixture "%s" in "%s" test case: ' . "\n" . '%s', get_class($fixture), get_class($test), $e->getMessage());
<add> $msg = sprintf(
<add> 'Unable to drop constraints for fixture "%s" in "%s" test case: ' . "\n" . '%s',
<add> get_class($fixture),
<add> get_class($test),
<add> $e->getMessage()
<add> );
<ide> throw new Exception($msg);
<ide> }
<ide> }
<ide> public function load($test)
<ide> try {
<ide> $fixture->createConstraints($db);
<ide> } catch (PDOException $e) {
<del> $msg = sprintf('Unable to create constraints for fixture "%s" in "%s" test case: ' . "\n" . '%s', get_class($fixture), get_class($test), $e->getMessage());
<add> $msg = sprintf(
<add> 'Unable to create constraints for fixture "%s" in "%s" test case: ' . "\n" . '%s',
<add> get_class($fixture),
<add> get_class($test),
<add> $e->getMessage()
<add> );
<ide> throw new Exception($msg);
<ide> }
<ide> }
<ide> public function load($test)
<ide> try {
<ide> $fixture->insert($db);
<ide> } catch (PDOException $e) {
<del> $msg = sprintf('Unable to insert fixture "%s" in "%s" test case: ' . "\n" . '%s', get_class($fixture), get_class($test), $e->getMessage());
<add> $msg = sprintf(
<add> 'Unable to insert fixture "%s" in "%s" test case: ' . "\n" . '%s',
<add> get_class($fixture),
<add> get_class($test),
<add> $e->getMessage()
<add> );
<ide> throw new Exception($msg);
<ide> }
<ide> }
<ide> };
<ide> $this->_runOperation($fixtures, $insert);
<ide> } catch (PDOException $e) {
<del> $msg = sprintf('Unable to insert fixtures for "%s" test case. %s', get_class($test), $e->getMessage());
<add> $msg = sprintf(
<add> 'Unable to insert fixtures for "%s" test case. %s',
<add> get_class($test),
<add> $e->getMessage()
<add> );
<ide> throw new Exception($msg);
<ide> }
<ide> } | 1 |
Ruby | Ruby | allow proc defaults with the attributes api | a6e3cdae0ce1d05a6b9f7dff4499f6be3fbf63c2 | <ide><path>activerecord/lib/active_record/attribute/user_provided_default.rb
<add>require 'active_record/attribute'
<add>
<add>module ActiveRecord
<add> class Attribute # :nodoc:
<add> class UserProvidedDefault < FromUser
<add> def initialize(name, value, type)
<add> super(name, value, type)
<add> end
<add>
<add> def type_cast(value)
<add> if value.is_a?(Proc)
<add> super(value.call)
<add> else
<add> super
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>activerecord/lib/active_record/attributes.rb
<add>require 'active_record/attribute/user_provided_default'
<add>
<ide> module ActiveRecord
<ide> # See ActiveRecord::Attributes::ClassMethods for documentation
<ide> module Attributes
<ide> def define_default_attribute(name, value, type, from_user:)
<ide> if value == NO_DEFAULT_PROVIDED
<ide> default_attribute = _default_attributes[name].with_type(type)
<ide> elsif from_user
<del> default_attribute = Attribute.from_user(name, value, type)
<add> default_attribute = Attribute::UserProvidedDefault.new(
<add> name,
<add> value,
<add> type,
<add> )
<ide> else
<ide> default_attribute = Attribute.from_database(name, value, type)
<ide> end
<ide><path>activerecord/test/cases/attributes_test.rb
<ide> def deserialize(*)
<ide> assert_equal "from user", model.wibble
<ide> end
<ide>
<add> test "procs for default values" do
<add> klass = Class.new(OverloadedType) do
<add> @@counter = 0
<add> attribute :counter, :integer, default: -> { @@counter += 1 }
<add> end
<add>
<add> assert_equal 1, klass.new.counter
<add> assert_equal 2, klass.new.counter
<add> end
<add>
<ide> if current_adapter?(:PostgreSQLAdapter)
<ide> test "arrays types can be specified" do
<ide> klass = Class.new(OverloadedType) do | 3 |
Ruby | Ruby | fix user name in doc [ci skip] | 4675a15a38f6373f417710ff949f1434c66cf43a | <ide><path>activerecord/lib/active_record/relation.rb
<ide> def new(*args, &block)
<ide> # ==== Examples
<ide> #
<ide> # users = User.where(name: 'Oscar')
<del> # users.create # => #<User id: 3, name: "oscar", ...>
<add> # users.create # => #<User id: 3, name: "Oscar", ...>
<ide> #
<ide> # users.create(name: 'fxn')
<ide> # users.create # => #<User id: 4, name: "fxn", ...> | 1 |
Ruby | Ruby | add test cases for optimistic locking | 7b1ee9f54c5906b49b60b300212e17e0290e8ee5 | <ide><path>activerecord/test/cases/locking_test.rb
<ide> def test_lock_new_when_explicitly_passing_nil
<ide> assert_equal 0, p1.lock_version
<ide> end
<ide>
<add> def test_lock_new_when_explicitly_passing_value
<add> p1 = Person.new(first_name: "Douglas Adams", lock_version: 42)
<add> p1.save!
<add> assert_equal 42, p1.lock_version
<add> end
<add>
<ide> def test_touch_existing_lock
<ide> p1 = Person.find(1)
<ide> assert_equal 0, p1.lock_version
<ide> def test_touch_stale_object
<ide> end
<ide> end
<ide>
<add> def test_explicit_update_lock_column_raise_error
<add> person = Person.find(1)
<add>
<add> assert_raises(ActiveRecord::StaleObjectError) do
<add> person.first_name = "Douglas Adams"
<add> person.lock_version = 42
<add>
<add> assert person.lock_version_changed?
<add>
<add> person.save
<add> end
<add> end
<add>
<ide> def test_lock_column_name_existing
<ide> t1 = LegacyThing.find(1)
<ide> t2 = LegacyThing.find(1) | 1 |
Java | Java | expose surfaceid as part reactrootview | f0b6f8441b68263722e5c771d3dfc8ad0dd76896 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
<ide> public void setShouldLogContentAppeared(boolean shouldLogContentAppeared) {
<ide> mShouldLogContentAppeared = shouldLogContentAppeared;
<ide> }
<ide>
<add> @Nullable
<add> @Override
<add> public String getSurfaceID() {
<add> Bundle appProperties = getAppProperties();
<add> return appProperties != null ? appProperties.getString("surfaceID") : null;
<add> }
<add>
<ide> private void updateRootLayoutSpecs(final int widthMeasureSpec, final int heightMeasureSpec) {
<ide> if (mReactInstanceManager == null) {
<ide> FLog.w(
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> public FabricUIManager(
<ide> public <T extends View> int addRootView(
<ide> final T rootView, final WritableMap initialProps, final @Nullable String initialUITemplate) {
<ide> final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag();
<add> ReactRoot reactRootView = (ReactRoot) rootView;
<add>
<ide> // TODO T31905686: Combine with startSurface below
<ide> ThemedReactContext reactContext =
<del> new ThemedReactContext(mReactApplicationContext, rootView.getContext());
<add> new ThemedReactContext(
<add> mReactApplicationContext, rootView.getContext(), reactRootView.getSurfaceID());
<ide> mMountingManager.addRootView(rootTag, rootView);
<add> String moduleName = reactRootView.getJSModuleName();
<ide> mReactContextForRootTag.put(rootTag, reactContext);
<del> String moduleName = ((ReactRoot) rootView).getJSModuleName();
<ide> if (ENABLE_FABRIC_LOGS) {
<ide> FLog.d(TAG, "Starting surface for module: %s and reactTag: %d", moduleName, rootTag);
<ide> }
<ide> public <T extends View> int startSurface(
<ide> int heightMeasureSpec) {
<ide> final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag();
<ide> ThemedReactContext reactContext =
<del> new ThemedReactContext(mReactApplicationContext, rootView.getContext());
<add> new ThemedReactContext(mReactApplicationContext, rootView.getContext(), moduleName);
<ide> if (ENABLE_FABRIC_LOGS) {
<ide> FLog.d(TAG, "Starting surface for module: %s and reactTag: %d", moduleName, rootTag);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java
<ide> public interface ReactRoot {
<ide>
<ide> /** Sets a flag that determines whether to log that content appeared on next view added. */
<ide> void setShouldLogContentAppeared(boolean shouldLogContentAppeared);
<add>
<add> /**
<add> * @return a {@link String} that represents the root js application that is being rendered with
<add> * this {@link ReactRoot}
<add> * @deprecated We recommend to not use this method as it is will be replaced in the near future.
<add> */
<add> @Deprecated
<add> @Nullable
<add> String getSurfaceID();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java
<ide> public <T extends View> int addRootView(
<ide> final int tag = ReactRootViewTagGenerator.getNextRootViewTag();
<ide> final ReactApplicationContext reactApplicationContext = getReactApplicationContext();
<ide> final ThemedReactContext themedRootContext =
<del> new ThemedReactContext(reactApplicationContext, rootView.getContext());
<add> new ThemedReactContext(
<add> reactApplicationContext, rootView.getContext(), ((ReactRoot) rootView).getSurfaceID());
<ide>
<ide> mUIImplementation.registerRootView(rootView, tag, themedRootContext);
<ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); | 4 |
Python | Python | remove unused import | 68a9f9a9221e1c7e0c90ef80fcd469da742613c0 | <ide><path>libcloud/compute/drivers/dreamhost.py
<ide>
<ide> import copy
<ide>
<del>from libcloud.pricing import get_pricing
<ide> from libcloud.common.base import ConnectionKey, Response
<ide> from libcloud.common.types import InvalidCredsError
<ide> from libcloud.compute.base import Node, NodeDriver, NodeSize | 1 |
Python | Python | fix bug in eig with complex solutions | af40b197e5af26afe09ebc1b9392993fa8a62270 | <ide><path>numpy/linalg/linalg.py
<ide> def eig(a):
<ide> v = vr
<ide> else:
<ide> w = wr+1j*wi
<del> v = array(vr,Complex)
<add> v = array(vr, w.dtype)
<ide> ind = nonzero(
<ide> equal(
<ide> equal(wi,0.0) # true for real e-vals | 1 |
PHP | PHP | allow int value | e472489a2f231fe264c11699a056eb2204ea594e | <ide><path>src/Illuminate/Validation/Rules/DatabaseRule.php
<ide> public function resolveTableName($table)
<ide> * Set a "where" constraint on the query.
<ide> *
<ide> * @param \Closure|string $column
<del> * @param array|string|null $value
<add> * @param array|string|int|null $value
<ide> * @return $this
<ide> */
<ide> public function where($column, $value = null) | 1 |
Javascript | Javascript | use tmpdir instead of fixturesdir | b11e2565744acaf714451f49fbdf5ec16cfdc061 | <ide><path>test/parallel/test-regress-GH-3739.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>const path = require('path');
<add>
<add>var dir = path.resolve(common.tmpDir);
<add>
<add>// Make sure that the tmp directory is clean
<add>common.refreshTmpDir();
<add>
<add>// Make a long path.
<add>for (var i = 0; i < 50; i++) {
<add> dir = dir + '/1234567890';
<add> try {
<add> fs.mkdirSync(dir, '0777');
<add> } catch (e) {
<add> if (e.code !== 'EEXIST') {
<add> throw e;
<add> }
<add> }
<add>}
<add>
<add>// Test if file exists synchronously
<add>assert(common.fileExists(dir), 'Directory is not accessible');
<add>
<add>// Test if file exists asynchronously
<add>fs.access(dir, function(err) {
<add> assert(!err, 'Directory is not accessible');
<add>});
<ide><path>test/sequential/test-regress-GH-3739.js
<del>'use strict';
<del>var common = require('../common'),
<del> assert = require('assert'),
<del> fs = require('fs'),
<del> path = require('path');
<del>
<del>var dir = path.resolve(common.fixturesDir),
<del> dirs = [];
<del>
<del>// Make a long path.
<del>for (var i = 0; i < 50; i++) {
<del> dir = dir + '/123456790';
<del> try {
<del> fs.mkdirSync(dir, '0777');
<del> } catch (e) {
<del> if (e.code == 'EEXIST') {
<del> // Ignore;
<del> } else {
<del> cleanup();
<del> throw e;
<del> }
<del> }
<del> dirs.push(dir);
<del>}
<del>
<del>// Test existsSync
<del>var r = common.fileExists(dir);
<del>if (r !== true) {
<del> cleanup();
<del> throw new Error('fs.accessSync returned false');
<del>}
<del>
<del>// Text exists
<del>fs.access(dir, function(err) {
<del> cleanup();
<del> if (err) {
<del> throw new Error('fs.access reported false');
<del> }
<del>});
<del>
<del>// Remove all created directories
<del>function cleanup() {
<del> for (var i = dirs.length - 1; i >= 0; i--) {
<del> fs.rmdirSync(dirs[i]);
<del> }
<del>} | 2 |
Go | Go | fix some typos | 3f02d91ef85499e0cf2fd106817d3cbeb77e3a38 | <ide><path>daemon/list.go
<ide> type listContext struct {
<ide>
<ide> // beforeFilter is a filter to ignore containers that appear before the one given
<ide> beforeFilter *container.Snapshot
<del> // sinceFilter is a filter to stop the filtering when the iterator arrive to the given container
<add> // sinceFilter is a filter to stop the filtering when the iterator arrives to the given container
<ide> sinceFilter *container.Snapshot
<ide>
<del> // taskFilter tells if we should filter based on wether a container is part of a task
<add> // taskFilter tells if we should filter based on whether a container is part of a task
<ide> taskFilter bool
<del> // isTask tells us if the we should filter container that are a task (true) or not (false)
<add> // isTask tells us if we should filter container that is a task (true) or not (false)
<ide> isTask bool
<ide>
<ide> // publish is a list of published ports to filter with | 1 |
PHP | PHP | remove unnecessary leftovers from new test case | 16216c0f97e5fee2d6c7be03c09a7f00d1b1b173 | <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide> public function testReplaceLinkWithConditions()
<ide> $connection = ConnectionManager::get('test');
<ide> $joint = $this->getMock(
<ide> '\Cake\ORM\Table',
<del> ['delete', 'find'],
<add> ['find'],
<ide> [['alias' => 'ArticlesTags', 'connection' => $connection]]
<ide> );
<ide> $config = [
<ide> public function testReplaceLinkWithConditions()
<ide> ];
<ide> $assoc = $this->getMock(
<ide> '\Cake\ORM\Association\BelongsToMany',
<del> ['_collectJointEntities', '_saveTarget'],
<add> ['_collectJointEntities'],
<ide> ['tags', $config]
<ide> );
<ide> $assoc->junction();
<ide>
<del> $this->article
<del> ->association('ArticlesTags')
<del> ->conditions(['foo' => 1]);
<del>
<ide> $query1 = $this->getMock(
<ide> '\Cake\ORM\Query',
<ide> ['where', 'andWhere', 'addDefaultTypes', 'contain'],
<ide> [$connection, $joint]
<ide> );
<ide> $query1->expects($this->at(0))
<ide> ->method('where')
<del> ->with(['foo' => 1])
<ide> ->will($this->returnSelf());
<ide> $query1->expects($this->at(1))
<ide> ->method('where')
<del> ->with(['article_id' => 1])
<ide> ->will($this->returnSelf());
<ide> $query1->expects($this->at(2))
<ide> ->method('contain')
<ide> public function testReplaceLinkWithConditions()
<ide> ->method('andWhere')
<ide> ->with($config['conditions'])
<ide> ->will($this->returnSelf());
<del>
<del> $existing = [
<del> new Entity(['article_id' => 1, 'tag_id' => 2]),
<del> new Entity(['article_id' => 1, 'tag_id' => 4]),
<del> new Entity(['article_id' => 1, 'tag_id' => 5]),
<del> new Entity(['article_id' => 1, 'tag_id' => 6])
<del> ];
<del> $query1->setResult(new \ArrayIterator($existing));
<add> $query1->setResult(new \ArrayIterator([]));
<ide>
<ide> $joint->expects($this->at(0))->method('find')
<ide> ->with('all')
<ide> ->will($this->returnValue($query1));
<ide>
<del> $opts = ['markNew' => false];
<del> $tags = [
<del> new Entity(['id' => 2], $opts),
<del> new Entity(['id' => 3], $opts),
<del> new Entity(['id' => 6])
<del> ];
<del> $entity = new Entity(['id' => 1, 'test' => $tags], $opts);
<add> $entity = new Entity(['id' => 1, 'test' => []]);
<ide>
<del> $jointEntities = [
<del> new Entity(['article_id' => 1, 'tag_id' => 2])
<del> ];
<ide> $assoc->expects($this->once())->method('_collectJointEntities')
<del> ->with($entity, $tags)
<del> ->will($this->returnValue($jointEntities));
<del>
<del> $joint->expects($this->at(1))
<del> ->method('delete')
<del> ->with($existing[1]);
<del> $joint->expects($this->at(2))
<del> ->method('delete')
<del> ->with($existing[2]);
<del>
<del> $options = ['foo' => 'bar'];
<del> $assoc->expects($this->once())
<del> ->method('_saveTarget')
<del> ->with($entity, [1 => $tags[1], 2 => $tags[2]], $options + ['associated' => false])
<del> ->will($this->returnCallback(function ($entity, $inserts) use ($tags) {
<del> $this->assertSame([1 => $tags[1], 2 => $tags[2]], $inserts);
<del> $entity->tags = $inserts;
<del> return true;
<del> }));
<add> ->with($entity, [])
<add> ->will($this->returnValue([]));
<ide>
<del> $assoc->replaceLinks($entity, $tags, $options + ['associated' => false]);
<del> $this->assertSame($tags, $entity->tags);
<del> $this->assertFalse($entity->dirty('tags'));
<add> $assoc->replaceLinks($entity, [], ['associated' => false]);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | add script to do conllu training | 24fb2c246fa263db893e4c7c959ce404dbf824aa | <ide><path>examples/training/conllu.py
<add>'''Train for CONLL 2017 UD treebank evaluation. Takes .conllu files, writes
<add>.conllu format for development data, allowing the official scorer to be used.
<add>'''
<add>from __future__ import unicode_literals
<add>import plac
<add>import tqdm
<add>import re
<add>import spacy
<add>import spacy.util
<add>from spacy.gold import GoldParse, minibatch
<add>from spacy.syntax.nonproj import projectivize
<add>from collections import Counter
<add>from timeit import default_timer as timer
<add>
<add>from spacy._align import align
<add>
<add>def prevent_bad_sentences(doc):
<add> '''This is an example pipeline component for fixing sentence segmentation
<add> mistakes. The component sets is_sent_start to False, which means the
<add> parser will be prevented from making a sentence boundary there. The
<add> rules here aren't necessarily a good idea.'''
<add> for token in doc[1:]:
<add> if token.nbor(-1).text == ',':
<add> token.is_sent_start = False
<add> elif not token.nbor(-1).whitespace_:
<add> token.is_sent_start = False
<add> elif not token.nbor(-1).is_punct:
<add> token.is_sent_start = False
<add> return doc
<add>
<add>
<add>def load_model(lang):
<add> '''This shows how to adjust the tokenization rules, to special-case
<add> for ways the CoNLLU tokenization differs. We need to get the tokenizer
<add> accuracy high on the various treebanks in order to do well. If we don't
<add> align on a content word, all dependencies to and from that word will
<add> be marked as incorrect.
<add> '''
<add> English = spacy.util.get_lang_class(lang)
<add> English.Defaults.infixes += ('(?<=[^-\d])[+\-\*^](?=[^-\d])',)
<add> English.Defaults.infixes += ('(?<=[^-])[+\-\*^](?=[^-\d])',)
<add> English.Defaults.infixes += ('(?<=[^-\d])[+\-\*^](?=[^-])',)
<add> English.Defaults.token_match = re.compile(r'=+').match
<add> nlp = English()
<add> nlp.tokenizer.add_special_case('***', [{'ORTH': '***'}])
<add> nlp.tokenizer.add_special_case("):", [{'ORTH': ")"}, {"ORTH": ":"}])
<add> nlp.tokenizer.add_special_case("and/or", [{'ORTH': "and"}, {"ORTH": "/"}, {"ORTH": "or"}])
<add> nlp.tokenizer.add_special_case("non-Microsoft", [{'ORTH': "non-Microsoft"}])
<add> nlp.tokenizer.add_special_case("mis-matches", [{'ORTH': "mis-matches"}])
<add> nlp.tokenizer.add_special_case("X.", [{'ORTH': "X"}, {"ORTH": "."}])
<add> nlp.tokenizer.add_special_case("b/c", [{'ORTH': "b/c"}])
<add> return nlp
<add>
<add>
<add>def get_token_acc(docs, golds):
<add> '''Quick function to evaluate tokenization accuracy.'''
<add> miss = 0
<add> hit = 0
<add> for doc, gold in zip(docs, golds):
<add> for i in range(len(doc)):
<add> token = doc[i]
<add> align = gold.words[i]
<add> if align == None:
<add> miss += 1
<add> else:
<add> hit += 1
<add> return miss, hit
<add>
<add>
<add>def golds_to_gold_tuples(docs, golds):
<add> '''Get out the annoying 'tuples' format used by begin_training, given the
<add> GoldParse objects.'''
<add> tuples = []
<add> for doc, gold in zip(docs, golds):
<add> text = doc.text
<add> ids, words, tags, heads, labels, iob = zip(*gold.orig_annot)
<add> sents = [((ids, words, tags, heads, labels, iob), [])]
<add> tuples.append((text, sents))
<add> return tuples
<add>
<add>
<add>def split_text(text):
<add> paragraphs = text.split('\n\n')
<add> paragraphs = [par.strip().replace('\n', ' ') for par in paragraphs]
<add> return paragraphs
<add>
<add>
<add>def read_conllu(file_):
<add> docs = []
<add> doc = []
<add> sent = []
<add> for line in file_:
<add> if line.startswith('# newdoc'):
<add> if doc:
<add> docs.append(doc)
<add> doc = []
<add> elif line.startswith('#'):
<add> continue
<add> elif not line.strip():
<add> if sent:
<add> doc.append(sent)
<add> sent = []
<add> else:
<add> sent.append(line.strip().split())
<add> if sent:
<add> doc.append(sent)
<add> if doc:
<add> docs.append(doc)
<add> return docs
<add>
<add>
<add>def get_docs(nlp, text):
<add> paragraphs = split_text(text)
<add> docs = [nlp.make_doc(par) for par in paragraphs]
<add> return docs
<add>
<add>
<add>def get_golds(docs, conllu):
<add> # sd is spacy doc; cd is conllu doc
<add> # cs is conllu sent, ct is conllu token
<add> golds = []
<add> for sd, cd in zip(docs, conllu):
<add> words = []
<add> tags = []
<add> heads = []
<add> deps = []
<add> for cs in cd:
<add> for id_, word, lemma, pos, tag, morph, head, dep, _1, _2 in cs:
<add> if '.' in id_:
<add> continue
<add> i = len(words)
<add> id_ = int(id_)-1
<add> head = int(head)-1 if head != '0' else id_
<add> head_dist = head - id_
<add> words.append(word)
<add> tags.append(tag)
<add> heads.append(i+head_dist)
<add> deps.append('ROOT' if dep == 'root' else dep)
<add> heads, deps = projectivize(heads, deps)
<add> entities = ['-'] * len(words)
<add> gold = GoldParse(sd, words=words, tags=tags, heads=heads, deps=deps,
<add> entities=entities)
<add> golds.append(gold)
<add> return golds
<add>
<add>def parse_dev_data(nlp, text_loc, conllu_loc):
<add> with open(text_loc) as file_:
<add> docs = get_docs(nlp, file_.read())
<add> with open(conllu_loc) as file_:
<add> conllu_dev = read_conllu(file_)
<add> golds = list(get_golds(docs, conllu_dev))
<add> scorer = nlp.evaluate(zip(docs, golds))
<add> return docs, scorer
<add>
<add>
<add>def print_progress(itn, losses, scores):
<add> scores = {}
<add> for col in ['dep_loss', 'tag_loss', 'uas', 'tags_acc', 'token_acc',
<add> 'ents_p', 'ents_r', 'ents_f', 'cpu_wps', 'gpu_wps']:
<add> scores[col] = 0.0
<add> scores['dep_loss'] = losses.get('parser', 0.0)
<add> scores['ner_loss'] = losses.get('ner', 0.0)
<add> scores['tag_loss'] = losses.get('tagger', 0.0)
<add> scores.update(scorer.scores)
<add> tpl = '\t'.join((
<add> '{:d}',
<add> '{dep_loss:.3f}',
<add> '{ner_loss:.3f}',
<add> '{uas:.3f}',
<add> '{ents_p:.3f}',
<add> '{ents_r:.3f}',
<add> '{ents_f:.3f}',
<add> '{tags_acc:.3f}',
<add> '{token_acc:.3f}',
<add> ))
<add> print(tpl.format(itn, **scores))
<add>
<add>def print_conllu(docs, file_):
<add> for i, doc in enumerate(docs):
<add> file_.write("# newdoc id = {i}\n".format(i=i))
<add> for j, sent in enumerate(doc.sents):
<add> file_.write("# sent_id = {i}.{j}\n".format(i=i, j=j))
<add> file_.write("# text = {text}\n".format(text=sent.text))
<add> for k, t in enumerate(sent):
<add> if t.head.i == t.i:
<add> head = 0
<add> else:
<add> head = k + (t.head.i - t.i) + 1
<add> fields = [str(k+1), t.text, t.lemma_, t.pos_, t.tag_, '_', str(head), t.dep_, '_', '_']
<add> file_.write('\t'.join(fields) + '\n')
<add> file_.write('\n')
<add>
<add>
<add>def main(spacy_model, conllu_train_loc, text_train_loc, conllu_dev_loc, text_dev_loc,
<add> output_loc):
<add> with open(conllu_train_loc) as file_:
<add> conllu_train = read_conllu(file_)
<add> nlp = load_model(spacy_model)
<add> print("Get docs")
<add> with open(text_train_loc) as file_:
<add> docs = get_docs(nlp, file_.read())
<add> golds = list(get_golds(docs, conllu_train))
<add> print("Create parser")
<add> nlp.add_pipe(nlp.create_pipe('parser'))
<add> nlp.add_pipe(nlp.create_pipe('tagger'))
<add> for gold in golds:
<add> for tag in gold.tags:
<add> if tag is not None:
<add> nlp.tagger.add_label(tag)
<add> optimizer = nlp.begin_training(lambda: golds_to_gold_tuples(docs, golds))
<add> n_train_words = sum(len(doc) for doc in docs)
<add> print(n_train_words)
<add> print("Begin training")
<add> for i in range(10):
<add> with open(text_train_loc) as file_:
<add> docs = get_docs(nlp, file_.read())
<add> docs = docs[:len(golds)]
<add> with tqdm.tqdm(total=n_train_words, leave=False) as pbar:
<add> losses = {}
<add> for batch in minibatch(list(zip(docs, golds)), size=1):
<add> if not batch:
<add> continue
<add> batch_docs, batch_gold = zip(*batch)
<add>
<add> nlp.update(batch_docs, batch_gold, sgd=optimizer,
<add> drop=0.2, losses=losses)
<add> pbar.update(sum(len(doc) for doc in batch_docs))
<add>
<add> with nlp.use_params(optimizer.averages):
<add> dev_docs, scorer = parse_dev_data(nlp, text_dev_loc, conllu_dev_loc)
<add> print_progress(i, losses, scorer.scores)
<add> with open(output_loc, 'w') as file_:
<add> print_conllu(dev_docs, file_)
<add>
<add>if __name__ == '__main__':
<add> plac.call(main) | 1 |
Text | Text | add readme to pkg | 652c2c2a80cd119ffb8017c25e741ddad9399236 | <ide><path>pkg/README.md
<add>pkg/ is a collection of utility packages used by the Docker project without being specific to its internals.
<add>
<add>Utility packages are kept separate from the docker core codebase to keep it as small and concise as possible.
<add>If some utilities grow larger and their APIs stabilize, they may be moved to their own repository under the
<add>Docker organization, to facilitate re-use by other projects. However that is not the priority.
<add>
<add>The directory `pkg` is named after the same directory in the camlistore project. Since Brad is a core
<add>Go maintainer, we thought it made sense to copy his methods for organizing Go code :) Thanks Brad!
<add>
<add>Because utility packages are small and neatly separated from the rest of the codebase, they are a good
<add>place to start for aspiring maintainers and contributors. Get in touch if you want to help maintain them! | 1 |
Javascript | Javascript | fix code styling to pass tests | 33356f65ba78ceb277f2375cccaf78b72d0414e7 | <ide><path>lib/Stats.js
<ide> Stats.jsonToString = function jsonToString(obj, useColors) {
<ide> }
<ide> };
<ide> return obj;
<del> }, { normal: function (str) { buf.push(str); } });
<add> }, {
<add> normal: function(str) {
<add> buf.push(str);
<add> }
<add> });
<ide>
<ide> function coloredTime(time) {
<ide> var times = [800, 400, 200, 100]; | 1 |
Python | Python | use smallest integer for tri ranges | dab5e3e2e23cd00a338fd221b3bd7751c6edd893 | <ide><path>numpy/lib/twodim_base.py
<ide>
<ide> from numpy.core.numeric import (
<ide> asanyarray, subtract, arange, zeros, greater_equal, multiply, ones,
<del> asarray, where, dtype as np_dtype, less
<add> asarray, where, dtype as np_dtype, less, int8, int16, int32, int64
<ide> )
<add>from numpy.core import iinfo
<ide>
<ide>
<add>i1 = iinfo(int8)
<add>i2 = iinfo(int16)
<add>i4 = iinfo(int32)
<add>def _min_int(low, high):
<add> """ get small int that fits the range """
<add> if high <= i1.max and low >= i1.min:
<add> return int8
<add> if high <= i2.max and low >= i2.min:
<add> return int16
<add> if high <= i4.max and low >= i4.min:
<add> return int32
<add> return int64
<add>
<ide>
<ide> def fliplr(m):
<ide> """
<ide> def tri(N, M=None, k=0, dtype=float):
<ide> if M is None:
<ide> M = N
<ide>
<del> m = greater_equal.outer(arange(N), arange(-k, M-k))
<add> m = greater_equal.outer(arange(N, dtype=_min_int(0, N)),
<add> arange(-k, M-k, dtype=_min_int(-k, M - k)))
<ide>
<ide> # Avoid making a copy if the requested type is already bool
<ide> if np_dtype(dtype) != np_dtype(bool): | 1 |
PHP | PHP | add missing type hints | ed142d8c89de98f32f8a2ec437c139ef88c47f3c | <ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> protected function _filterResults(&$results, Model $Model, $filtered = array())
<ide> * @return mixed
<ide> * @throws CakeException when results cannot be created.
<ide> */
<del> public function queryAssociation(Model $Model, &$LinkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
<add> public function queryAssociation(Model $Model, Model $LinkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
<ide> if (isset($stack['_joined'])) {
<ide> $joined = $stack['_joined'];
<ide> unset($stack['_joined']);
<ide> public function queryAssociation(Model $Model, &$LinkModel, $type, $association,
<ide> if ($type !== 'hasAndBelongsToMany') {
<ide> $q = $this->insertQueryData($query, $row, $association, $Model, $stack);
<ide>
<del>
<ide> $fetch = null;
<ide> if ($q !== false) {
<ide> $joinedData = array();
<ide> public function buildAssociationQuery(Model $Model, $queryData) {
<ide> * @return mixed
<ide> * True. when $external is false and association $type is 'hasOne' or 'belongsTo'.
<ide> */
<del> public function generateAssociationQuery(Model $Model, $LinkModel, $type, $association, $assocData, &$queryData, $external) {
<add> public function generateAssociationQuery(Model $Model, Model $LinkModel, $type, $association, $assocData, &$queryData, $external) {
<ide> $assocData = $this->_scrubQueryData($assocData);
<ide>
<ide> if ($external && !empty($assocData['finderQuery'])) {
<ide> public function buildJoinStatement($join) {
<ide> */
<ide> public function buildStatement($query, $model) {
<ide> $query = array_merge($this->_queryDefaults, $query);
<add>
<ide> if (!empty($query['joins'])) {
<ide> $count = count($query['joins']);
<ide> for ($i = 0; $i < $count; $i++) {
<ide> public function buildStatement($query, $model) {
<ide> }
<ide> }
<ide> }
<add>
<ide> return $this->renderStatement('select', array(
<ide> 'conditions' => $this->conditions($query['conditions'], true, true, $model),
<ide> 'fields' => implode(', ', $query['fields']), | 1 |
Java | Java | avoid deprecated mockito methods | ac774cdcef7b25878f075d7e3514c373880eacac | <ide><path>spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java
<ide> public void importSelectors() {
<ide> context.refresh();
<ide> context.getBean(Config.class);
<ide> InOrder ordered = inOrder(beanFactory);
<del> ordered.verify(beanFactory).registerBeanDefinition(eq("a"), (BeanDefinition) anyObject());
<del> ordered.verify(beanFactory).registerBeanDefinition(eq("b"), (BeanDefinition) anyObject());
<del> ordered.verify(beanFactory).registerBeanDefinition(eq("d"), (BeanDefinition) anyObject());
<del> ordered.verify(beanFactory).registerBeanDefinition(eq("c"), (BeanDefinition) anyObject());
<add> ordered.verify(beanFactory).registerBeanDefinition(eq("a"), any());
<add> ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any());
<add> ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any());
<add> ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java
<ide> public void resolveTypeWithCustomVariableResolver() throws Exception {
<ide> VariableResolver variableResolver = mock(VariableResolver.class);
<ide> given(variableResolver.getSource()).willReturn(this);
<ide> ResolvableType longType = ResolvableType.forClass(Long.class);
<del> given(variableResolver.resolveVariable((TypeVariable<?>) anyObject())).willReturn(longType);
<add> given(variableResolver.resolveVariable(any())).willReturn(longType);
<ide>
<ide> ResolvableType variable = ResolvableType.forType(
<ide> Fields.class.getField("typeVariableType").getGenericType(), variableResolver);
<ide><path>spring-jms/src/test/java/org/springframework/jms/core/JmsMessagingTemplateTests.java
<ide> public void sendAndReceive() {
<ide> Destination destination = new Destination() {};
<ide> Message<String> request = createTextMessage();
<ide> javax.jms.Message replyJmsMessage = createJmsTextMessage();
<del> given(jmsTemplate.sendAndReceive(eq(destination), anyObject())).willReturn(replyJmsMessage);
<add> given(jmsTemplate.sendAndReceive(eq(destination), any())).willReturn(replyJmsMessage);
<ide>
<ide> Message<?> actual = messagingTemplate.sendAndReceive(destination, request);
<del> verify(jmsTemplate, times(1)).sendAndReceive(eq(destination), anyObject());
<add> verify(jmsTemplate, times(1)).sendAndReceive(eq(destination), any());
<ide> assertTextMessage(actual);
<ide> }
<ide>
<ide> @Test
<ide> public void sendAndReceiveName() {
<ide> Message<String> request = createTextMessage();
<ide> javax.jms.Message replyJmsMessage = createJmsTextMessage();
<del> given(jmsTemplate.sendAndReceive(eq("myQueue"), anyObject())).willReturn(replyJmsMessage);
<add> given(jmsTemplate.sendAndReceive(eq("myQueue"), any())).willReturn(replyJmsMessage);
<ide>
<ide> Message<?> actual = messagingTemplate.sendAndReceive("myQueue", request);
<del> verify(jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), anyObject());
<add> verify(jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), any());
<ide> assertTextMessage(actual);
<ide> }
<ide>
<ide> public void sendAndReceiveDefaultDestination() {
<ide> messagingTemplate.setDefaultDestination(destination);
<ide> Message<String> request = createTextMessage();
<ide> javax.jms.Message replyJmsMessage = createJmsTextMessage();
<del> given(jmsTemplate.sendAndReceive(eq(destination), anyObject())).willReturn(replyJmsMessage);
<add> given(jmsTemplate.sendAndReceive(eq(destination), any())).willReturn(replyJmsMessage);
<ide>
<ide> Message<?> actual = messagingTemplate.sendAndReceive(request);
<del> verify(jmsTemplate, times(1)).sendAndReceive(eq(destination), anyObject());
<add> verify(jmsTemplate, times(1)).sendAndReceive(eq(destination), any());
<ide> assertTextMessage(actual);
<ide> }
<ide>
<ide> public void sendAndReceiveDefaultDestinationName() {
<ide> messagingTemplate.setDefaultDestinationName("myQueue");
<ide> Message<String> request = createTextMessage();
<ide> javax.jms.Message replyJmsMessage = createJmsTextMessage();
<del> given(jmsTemplate.sendAndReceive(eq("myQueue"), anyObject())).willReturn(replyJmsMessage);
<add> given(jmsTemplate.sendAndReceive(eq("myQueue"), any())).willReturn(replyJmsMessage);
<ide>
<ide> Message<?> actual = messagingTemplate.sendAndReceive(request);
<del> verify(jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), anyObject());
<add> verify(jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), any());
<ide> assertTextMessage(actual);
<ide> }
<ide>
<ide> public void sendAndReceiveNoDefaultSet() {
<ide> public void convertSendAndReceivePayload() throws JMSException {
<ide> Destination destination = new Destination() {};
<ide> javax.jms.Message replyJmsMessage = createJmsTextMessage("My reply");
<del> given(jmsTemplate.sendAndReceive(eq(destination), anyObject())).willReturn(replyJmsMessage);
<add> given(jmsTemplate.sendAndReceive(eq(destination), any())).willReturn(replyJmsMessage);
<ide>
<ide> String reply = messagingTemplate.convertSendAndReceive(destination, "my Payload", String.class);
<del> verify(jmsTemplate, times(1)).sendAndReceive(eq(destination), anyObject());
<add> verify(jmsTemplate, times(1)).sendAndReceive(eq(destination), any());
<ide> assertEquals("My reply", reply);
<ide> }
<ide>
<ide> @Test
<ide> public void convertSendAndReceivePayloadName() throws JMSException {
<ide> javax.jms.Message replyJmsMessage = createJmsTextMessage("My reply");
<del> given(jmsTemplate.sendAndReceive(eq("myQueue"), anyObject())).willReturn(replyJmsMessage);
<add> given(jmsTemplate.sendAndReceive(eq("myQueue"), any())).willReturn(replyJmsMessage);
<ide>
<ide> String reply = messagingTemplate.convertSendAndReceive("myQueue", "my Payload", String.class);
<del> verify(jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), anyObject());
<add> verify(jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), any());
<ide> assertEquals("My reply", reply);
<ide> }
<ide>
<ide> public void convertSendAndReceiveDefaultDestination() throws JMSException {
<ide> Destination destination = new Destination() {};
<ide> messagingTemplate.setDefaultDestination(destination);
<ide> javax.jms.Message replyJmsMessage = createJmsTextMessage("My reply");
<del> given(jmsTemplate.sendAndReceive(eq(destination), anyObject())).willReturn(replyJmsMessage);
<add> given(jmsTemplate.sendAndReceive(eq(destination), any())).willReturn(replyJmsMessage);
<ide>
<ide> String reply = messagingTemplate.convertSendAndReceive("my Payload", String.class);
<del> verify(jmsTemplate, times(1)).sendAndReceive(eq(destination), anyObject());
<add> verify(jmsTemplate, times(1)).sendAndReceive(eq(destination), any());
<ide> assertEquals("My reply", reply);
<ide> }
<ide>
<ide> @Test
<ide> public void convertSendAndReceiveDefaultDestinationName() throws JMSException {
<ide> messagingTemplate.setDefaultDestinationName("myQueue");
<ide> javax.jms.Message replyJmsMessage = createJmsTextMessage("My reply");
<del> given(jmsTemplate.sendAndReceive(eq("myQueue"), anyObject())).willReturn(replyJmsMessage);
<add> given(jmsTemplate.sendAndReceive(eq("myQueue"), any())).willReturn(replyJmsMessage);
<ide>
<ide> String reply = messagingTemplate.convertSendAndReceive("my Payload", String.class);
<del> verify(jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), anyObject());
<add> verify(jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), any());
<ide> assertEquals("My reply", reply);
<ide> }
<ide>
<ide> public void convertMessageConversionExceptionOnSend() throws JMSException {
<ide> Message<String> message = createTextMessage();
<ide> MessageConverter messageConverter = mock(MessageConverter.class);
<ide> willThrow(org.springframework.jms.support.converter.MessageConversionException.class)
<del> .given(messageConverter).toMessage(eq(message), anyObject());
<add> .given(messageConverter).toMessage(eq(message), any());
<ide> messagingTemplate.setJmsMessageConverter(messageConverter);
<ide> invokeMessageCreator("myQueue");
<ide>
<ide> public void convertMessageNotReadableException() throws JMSException {
<ide> @Test
<ide> public void convertDestinationResolutionExceptionOnSend() {
<ide> Destination destination = new Destination() {};
<del> willThrow(DestinationResolutionException.class).given(jmsTemplate).send(eq(destination), anyObject());
<add> willThrow(DestinationResolutionException.class).given(jmsTemplate).send(eq(destination), any());
<ide>
<ide> thrown.expect(org.springframework.messaging.core.DestinationResolutionException.class);
<ide> messagingTemplate.send(destination, createTextMessage());
<ide> public void convertDestinationResolutionExceptionOnReceive() {
<ide> public void convertMessageFormatException() throws JMSException {
<ide> Message<String> message = createTextMessage();
<ide> MessageConverter messageConverter = mock(MessageConverter.class);
<del> willThrow(MessageFormatException.class).given(messageConverter).toMessage(eq(message), anyObject());
<add> willThrow(MessageFormatException.class).given(messageConverter).toMessage(eq(message), any());
<ide> messagingTemplate.setJmsMessageConverter(messageConverter);
<ide> invokeMessageCreator("myQueue");
<ide>
<ide> public void convertMessageFormatException() throws JMSException {
<ide> public void convertMessageNotWritableException() throws JMSException {
<ide> Message<String> message = createTextMessage();
<ide> MessageConverter messageConverter = mock(MessageConverter.class);
<del> willThrow(MessageNotWriteableException.class).given(messageConverter).toMessage(eq(message), anyObject());
<add> willThrow(MessageNotWriteableException.class).given(messageConverter).toMessage(eq(message), any());
<ide> messagingTemplate.setJmsMessageConverter(messageConverter);
<ide> invokeMessageCreator("myQueue");
<ide>
<ide> public void convertMessageNotWritableException() throws JMSException {
<ide>
<ide> @Test
<ide> public void convertInvalidDestinationExceptionOnSendAndReceiveWithName() {
<del> willThrow(InvalidDestinationException.class).given(jmsTemplate).sendAndReceive(eq("unknownQueue"), anyObject());
<add> willThrow(InvalidDestinationException.class).given(jmsTemplate).sendAndReceive(eq("unknownQueue"), any());
<ide>
<ide> thrown.expect(org.springframework.messaging.core.DestinationResolutionException.class);
<ide> messagingTemplate.sendAndReceive("unknownQueue", createTextMessage());
<ide> public void convertInvalidDestinationExceptionOnSendAndReceiveWithName() {
<ide> @Test
<ide> public void convertInvalidDestinationExceptionOnSendAndReceive() {
<ide> Destination destination = new Destination() {};
<del> willThrow(InvalidDestinationException.class).given(jmsTemplate).sendAndReceive(eq(destination), anyObject());
<add> willThrow(InvalidDestinationException.class).given(jmsTemplate).sendAndReceive(eq(destination), any());
<ide>
<ide> thrown.expect(org.springframework.messaging.core.DestinationResolutionException.class);
<ide> messagingTemplate.sendAndReceive(destination, createTextMessage());
<ide> public Object answer(InvocationOnMock invocation) throws Throwable {
<ide> messageCreator.createMessage(null);
<ide> return null;
<ide> }
<del> }).given(jmsTemplate).send(eq("myQueue"), anyObject());
<add> }).given(jmsTemplate).send(eq("myQueue"), any());
<ide> }
<ide>
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java
<ide> public void receiptNotReceived() throws Exception {
<ide> receiptable.addReceiptLostTask(() -> notReceived.set(true));
<ide>
<ide> ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
<del> verify(taskScheduler).schedule(taskCaptor.capture(), notNull(Date.class));
<add> verify(taskScheduler).schedule(taskCaptor.capture(), (Date) notNull());
<ide> Runnable scheduledTask = taskCaptor.getValue();
<ide> assertNotNull(scheduledTask);
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverterTests.java
<ide> public void setUp() {
<ide>
<ide> @Test
<ide> public void extensionRegistryInitialized() {
<del> verify(this.registryInitializer, times(1)).initializeExtensionRegistry(anyObject());
<add> verify(this.registryInitializer, times(1)).initializeExtensionRegistry(any());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java
<ide> public void resolveArgumentFromModel() throws Exception {
<ide> public void resovleArgumentViaDefaultConstructor() throws Exception {
<ide> WebDataBinder dataBinder = new WebRequestDataBinder(null);
<ide> WebDataBinderFactory factory = mock(WebDataBinderFactory.class);
<del> given(factory.createBinder(anyObject(), notNull(), eq("attrName"))).willReturn(dataBinder);
<add> given(factory.createBinder(any(), notNull(), eq("attrName"))).willReturn(dataBinder);
<ide>
<ide> this.processor.resolveArgument(this.paramNamedValidModelAttr, this.container, this.request, factory);
<del> verify(factory).createBinder(anyObject(), notNull(), eq("attrName"));
<add> verify(factory).createBinder(any(), notNull(), eq("attrName"));
<ide> }
<ide>
<ide> @Test
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/WebSocketStompClientTests.java
<ide> */
<ide> public class WebSocketStompClientTests {
<ide>
<del> private TestWebSocketStompClient stompClient;
<del>
<ide> @Mock
<ide> private TaskScheduler taskScheduler;
<ide>
<ide> @Mock
<ide> private ConnectionHandlingStompSession stompSession;
<ide>
<add> @Mock
<add> private WebSocketSession webSocketSession;
<add>
<add>
<add> private TestWebSocketStompClient stompClient;
<add>
<ide> private ArgumentCaptor<WebSocketHandler> webSocketHandlerCaptor;
<ide>
<ide> private SettableListenableFuture<WebSocketSession> handshakeFuture;
<ide>
<del> @Mock
<del> private WebSocketSession webSocketSession;
<del>
<ide>
<ide> @Before
<ide> public void setUp() throws Exception {
<ide> public void webSocketHandshakeFailure() throws Exception {
<ide> @SuppressWarnings("unchecked")
<ide> public void webSocketConnectionEstablished() throws Exception {
<ide> connect().afterConnectionEstablished(this.webSocketSession);
<del> verify(this.stompSession).afterConnected(isNotNull(TcpConnection.class));
<add> verify(this.stompSession).afterConnected(notNull());
<ide> }
<ide>
<ide> @Test
<ide> public void webSocketConnectionClosed() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<add> @SuppressWarnings({"unchecked", "rawtypes"})
<ide> public void handleWebSocketMessage() throws Exception {
<ide> String text = "SEND\na:alpha\n\nMessage payload\0";
<ide> connect().handleMessage(this.webSocketSession, new TextMessage(text));
<ide> public void handleWebSocketMessage() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<add> @SuppressWarnings({"unchecked", "rawtypes"})
<ide> public void handleWebSocketMessageSplitAcrossTwoMessage() throws Exception {
<ide> WebSocketHandler webSocketHandler = connect();
<ide>
<ide> public void handleWebSocketMessageSplitAcrossTwoMessage() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> @SuppressWarnings({ "unchecked", "rawtypes" })
<add> @SuppressWarnings({"unchecked", "rawtypes"})
<ide> public void handleWebSocketMessageBinary() throws Exception {
<ide> String text = "SEND\na:alpha\n\nMessage payload\0";
<ide> connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(StandardCharsets.UTF_8)));
<ide> public void heartbeatDefaultValueSetWithoutScheduler() throws Exception {
<ide> fail("Expected IllegalStateException");
<ide> }
<ide> catch (IllegalStateException ex) {
<del> // Ignore
<add> // ignore
<ide> }
<ide> }
<ide>
<ide> public void writeInactivityBeforeDelayHasElapsed() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> @SuppressWarnings({"rawtypes", "unchecked"})
<ide> public void cancelInactivityTasks() throws Exception {
<ide> TcpConnection<byte[]> tcpConnection = getTcpConnection();
<ide> | 7 |
PHP | PHP | fix failing test | 6e0cf0dab7a41c1dfcc29471f73b8eb376e1456c | <ide><path>lib/Cake/Test/Case/Console/Command/CommandListShellTest.php
<ide> public function testMain() {
<ide> $expected = "/\[.*TestPluginTwo.*\] example, welcome/";
<ide> $this->assertRegExp($expected, $output);
<ide>
<del> $expected = "/\[.*CORE.*\] acl, api, bake, command_list, console, i18n, schema, test, testsuite, upgrade/";
<add> $expected = "/\[.*CORE.*\] acl, api, bake, command_list, console, i18n, schema, server, test, testsuite, upgrade/";
<ide> $this->assertRegExp($expected, $output);
<ide>
<ide> $expected = "/\[.*app.*\] sample/"; | 1 |
Ruby | Ruby | add explicit option for disabling sandbox | 307ca85e0e110d9c84179aa50957693bdeaf5dec | <ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def sandbox?
<ide> include?("--sandbox") || !ENV["HOMEBREW_SANDBOX"].nil?
<ide> end
<ide>
<add> def no_sandbox?
<add> include?("--no-sandbox") || !ENV["HOMEBREW_NO_SANDBOX"].nil?
<add> end
<add>
<ide> def ignore_deps?
<ide> include? "--ignore-dependencies"
<ide> end | 1 |
Python | Python | fix lint errors | 0fbc71fc4681356f76f21ee998ff18ed2b0aafd2 | <ide><path>official/recommendation/data_test.py
<ide>
<ide> from collections import defaultdict
<ide> import hashlib
<del>import mock
<ide> import os
<ide>
<add>import mock
<ide> import numpy as np
<ide> import scipy.stats
<ide> import tensorflow as tf
<ide> def test_preprocessing(self):
<ide> for match_mlperf in [True, False]:
<ide> cache_path = os.path.join(self.temp_data_dir, "test_cache.pickle")
<ide> data, valid_cache = data_preprocessing._filter_index_sort(
<del> self.rating_file, cache_path=cache_path,
<del> match_mlperf=match_mlperf)
<add> self.rating_file, cache_path=cache_path)
<ide>
<ide> assert len(data[rconst.USER_MAP]) == NUM_USERS
<ide> assert len(data[rconst.ITEM_MAP]) == NUM_ITEMS | 1 |
Javascript | Javascript | require ipc when needed | 934c0720d882387e801a95f5f276731cab75ee92 | <ide><path>static/index.js
<ide> window.onload = function() {
<del> var ipc = require('ipc');
<ide> try {
<ide> // Skip "?loadSettings=".
<ide> var loadSettings = JSON.parse(decodeURIComponent(location.search.substr(14)));
<ide> window.onload = function() {
<ide> ModuleCache.add(loadSettings.resourcePath);
<ide>
<ide> require(loadSettings.bootstrapScript);
<del> ipc.sendChannel('window-command', 'window:loaded')
<add> require('ipc').sendChannel('window-command', 'window:loaded')
<ide> }
<ide> catch (error) {
<ide> var currentWindow = require('remote').getCurrentWindow(); | 1 |
Ruby | Ruby | secure formulae loading | c5536e1e08a13352cf241a2c3f7b2aa75a8e31d6 | <ide><path>Library/Homebrew/descriptions.rb
<ide> require "formula"
<add>require "formula_versions"
<ide> require "csv"
<ide>
<ide> class Descriptions
<ide> def self.update_cache(report)
<ide> # cache. Save the updated cache to disk, unless explicitly told not to.
<ide> def self.cache_formulae(formula_names, options = { :save => true })
<ide> if self.cache
<del> formula_names.each { |name| @cache[name] = Formula[name].desc }
<add> formula_names.each do |name|
<add> begin
<add> desc = Formulary.factory(name).desc
<add> rescue FormulaUnavailableError, *FormulaVersions::IGNORED_EXCEPTIONS
<add> end
<add> @cache[name] = desc
<add> end
<ide> self.save_cache if options[:save]
<ide> end
<ide> end | 1 |
Mixed | Ruby | add ability to prevent writes to a database | f39d72d5267baed1000932831cda98503d1e1047 | <ide><path>activerecord/CHANGELOG.md
<add>* Add the ability to prevent writes to a database for the duration of a block.
<add>
<add> Allows the application to prevent writes to a database. This can be useful when
<add> you're building out multiple databases and want to make sure you're not sending
<add> writes when you want a read.
<add>
<add> If `while_preventing_writes` is called and the query is considered a write
<add> query the database will raise an exception regardless of whether the database
<add> user is able to write.
<add>
<add> This is not meant to be a catch-all for write queries but rather a way to enforce
<add> read-only queries without opening a second connection. One purpose of this is to
<add> catch accidental writes, not all writes.
<add>
<add> *Eileen M. Uchitelle*
<add>
<ide> * Allow aliased attributes to be used in `#update_columns` and `#update`.
<ide>
<ide> *Gannon McGibbon*
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
<ide> def query(sql, name = nil) # :nodoc:
<ide> exec_query(sql, name).rows
<ide> end
<ide>
<add> # Determines whether the SQL statement is a write query.
<add> def write_query?(sql)
<add> raise NotImplementedError
<add> end
<add>
<ide> # Executes the SQL statement in the context of this connection and returns
<ide> # the raw result from the connection adapter.
<ide> # Note: depending on your database connector, the result returned by this
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> class AbstractAdapter
<ide>
<ide> SIMPLE_INT = /\A\d+\z/
<ide>
<del> attr_accessor :visitor, :pool
<add> attr_accessor :visitor, :pool, :prevent_writes
<ide> attr_reader :schema_cache, :owner, :logger, :prepared_statements, :lock
<ide> alias :in_use? :owner
<ide>
<ide> def self.type_cast_config_to_boolean(config)
<ide> end
<ide> end
<ide>
<add> def self.build_read_query_regexp(*parts) # :nodoc:
<add> lambda do |*parts|
<add> parts = parts.map { |part| /\A\s*#{part}/i }
<add> Regexp.union(*parts)
<add> end
<add> end
<add>
<ide> def initialize(connection, logger = nil, config = {}) # :nodoc:
<ide> super()
<ide>
<ide> def replica?
<ide> @config[:replica] || false
<ide> end
<ide>
<add> # Determines whether writes are currently being prevents.
<add> #
<add> # Returns true if the connection is a replica, or if +prevent_writes+
<add> # is set to true.
<add> def preventing_writes?
<add> replica? || prevent_writes
<add> end
<add>
<add> # Prevent writing to the database regardless of role.
<add> #
<add> # In some cases you may want to prevent writes to the database
<add> # even if you are on a database that can write. `while_preventing_writes`
<add> # will prevent writes to the database for the duration of the block.
<add> def while_preventing_writes
<add> original = self.prevent_writes
<add> self.prevent_writes = true
<add> yield
<add> ensure
<add> self.prevent_writes = original
<add> end
<add>
<ide> def migrations_paths # :nodoc:
<ide> @config[:migrations_paths] || Migrator.migrations_paths
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb
<ide> def query(sql, name = nil) # :nodoc:
<ide> execute(sql, name).to_a
<ide> end
<ide>
<add> READ_QUERY = ActiveRecord::ConnectionAdapters::AbstractAdapter.build_read_query_regexp.call(:begin, :select, :set, :show, :release, :savepoint) # :nodoc:
<add>
<add> def write_query?(sql) # :nodoc:
<add> !READ_QUERY.match?(sql)
<add> end
<add>
<ide> # Executes the SQL statement in the context of this connection.
<ide> def execute(sql, name = nil)
<add> if preventing_writes? && write_query?(sql)
<add> raise ActiveRecord::StatementInvalid, "Write query attempted while in readonly mode: #{sql}"
<add> end
<add>
<ide> # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been
<ide> # made since we established the connection
<ide> @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
<ide> def query(sql, name = nil) #:nodoc:
<ide> end
<ide> end
<ide>
<add> READ_QUERY = ActiveRecord::ConnectionAdapters::AbstractAdapter.build_read_query_regexp.call(:select, :show, :set) # :nodoc:
<add>
<add> def write_query?(sql) # :nodoc:
<add> !READ_QUERY.match?(sql)
<add> end
<add>
<ide> # Executes an SQL statement, returning a PG::Result object on success
<ide> # or raising a PG::Error exception otherwise.
<ide> # Note: the PG::Result object is manually memory managed; if you don't
<ide> # need it specifically, you may want consider the <tt>exec_query</tt> wrapper.
<ide> def execute(sql, name = nil)
<add> if preventing_writes? && write_query?(sql)
<add> raise ActiveRecord::StatementInvalid, "Write query attempted while in readonly mode: #{sql}"
<add> end
<add>
<ide> materialize_transactions
<ide>
<ide> log(sql, name) do
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def disable_referential_integrity # :nodoc:
<ide> # DATABASE STATEMENTS ======================================
<ide> #++
<ide>
<add> READ_QUERY = ActiveRecord::ConnectionAdapters::AbstractAdapter.build_read_query_regexp.call(:select) # :nodoc:
<add>
<add> def write_query?(sql) # :nodoc:
<add> !READ_QUERY.match?(sql)
<add> end
<add>
<ide> def explain(arel, binds = [])
<ide> sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}"
<ide> SQLite3::ExplainPrettyPrinter.new.pp(exec_query(sql, "EXPLAIN", []))
<ide> def last_inserted_id(result)
<ide> end
<ide>
<ide> def execute(sql, name = nil) #:nodoc:
<add> if preventing_writes? && write_query?(sql)
<add> raise ActiveRecord::StatementInvalid, "Write query attempted while in readonly mode: #{sql}"
<add> end
<add>
<ide> materialize_transactions
<ide>
<ide> log(sql, name) do
<ide><path>activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb
<ide> def test_errors_for_bigint_fks_on_integer_pk_table
<ide> @conn.exec_query("ALTER TABLE engines DROP COLUMN old_car_id")
<ide> end
<ide>
<add> def test_errors_when_an_insert_query_is_called_while_preventing_writes
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @conn.while_preventing_writes do
<add> @conn.insert("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')")
<add> end
<add> end
<add> end
<add>
<add> def test_errors_when_an_update_query_is_called_while_preventing_writes
<add> @conn.insert("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')")
<add>
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @conn.while_preventing_writes do
<add> @conn.update("UPDATE `engines` SET `engines`.`car_id` = '9989' WHERE `engines`.`car_id` = '138853948594'")
<add> end
<add> end
<add> end
<add>
<add> def test_errors_when_a_delete_query_is_called_while_preventing_writes
<add> @conn.execute("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')")
<add>
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @conn.while_preventing_writes do
<add> @conn.execute("DELETE FROM `engines` where `engines`.`car_id` = '138853948594'")
<add> end
<add> end
<add> end
<add>
<add> def test_errors_when_a_replace_query_is_called_while_preventing_writes
<add> @conn.execute("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')")
<add>
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @conn.while_preventing_writes do
<add> @conn.execute("REPLACE INTO `engines` SET `engines`.`car_id` = '249823948'")
<add> end
<add> end
<add> end
<add>
<add> def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes
<add> @conn.execute("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')")
<add>
<add> @conn.while_preventing_writes do
<add> assert_equal 1, @conn.execute("SELECT `engines`.* FROM `engines` WHERE `engines`.`car_id` = '138853948594'").entries.count
<add> end
<add> end
<add>
<add> def test_doesnt_error_when_a_show_query_is_called_while_preventing_writes
<add> @conn.while_preventing_writes do
<add> assert_equal 2, @conn.execute("SHOW FULL FIELDS FROM `engines`").entries.count
<add> end
<add> end
<add>
<add> def test_doesnt_error_when_a_set_query_is_called_while_preventing_writes
<add> @conn.while_preventing_writes do
<add> assert_nil @conn.execute("SET NAMES utf8")
<add> end
<add> end
<add>
<ide> private
<ide>
<ide> def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block)
<ide><path>activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
<ide> def test_unparsed_defaults_are_at_least_set_when_saving
<ide> end
<ide> end
<ide>
<add> def test_errors_when_an_insert_query_is_called_while_preventing_writes
<add> with_example_table do
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @connection.while_preventing_writes do
<add> @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_errors_when_an_update_query_is_called_while_preventing_writes
<add> with_example_table do
<add> @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add>
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @connection.while_preventing_writes do
<add> @connection.execute("UPDATE ex SET data = '9989' WHERE data = '138853948594'")
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_errors_when_a_delete_query_is_called_while_preventing_writes
<add> with_example_table do
<add> @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add>
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @connection.while_preventing_writes do
<add> @connection.execute("DELETE FROM ex where data = '138853948594'")
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes
<add> with_example_table do
<add> @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add>
<add> @connection.while_preventing_writes do
<add> assert_equal 1, @connection.execute("SELECT * FROM ex WHERE data = '138853948594'").entries.count
<add> end
<add> end
<add> end
<add>
<add> def test_doesnt_error_when_a_show_query_is_called_while_preventing_writes
<add> @connection.while_preventing_writes do
<add> assert_equal 1, @connection.execute("SHOW TIME ZONE").entries.count
<add> end
<add> end
<add>
<add> def test_doesnt_error_when_a_set_query_is_called_while_preventing_writes
<add> @connection.while_preventing_writes do
<add> assert_equal [], @connection.execute("SET standard_conforming_strings = on").entries
<add> end
<add> end
<add>
<ide> private
<ide>
<ide> def with_example_table(definition = "id serial primary key, number integer, data character varying(255)", &block)
<ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
<ide> def test_writes_are_not_permitted_to_readonly_databases
<ide> end
<ide> end
<ide>
<add> def test_errors_when_an_insert_query_is_called_while_preventing_writes
<add> with_example_table "id int, data string" do
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @conn.while_preventing_writes do
<add> @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_errors_when_an_update_query_is_called_while_preventing_writes
<add> with_example_table "id int, data string" do
<add> @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add>
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @conn.while_preventing_writes do
<add> @conn.execute("UPDATE ex SET data = '9989' WHERE data = '138853948594'")
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_errors_when_a_delete_query_is_called_while_preventing_writes
<add> with_example_table "id int, data string" do
<add> @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add>
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @conn.while_preventing_writes do
<add> @conn.execute("DELETE FROM ex where data = '138853948594'")
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_errors_when_a_replace_query_is_called_while_preventing_writes
<add> with_example_table "id int, data string" do
<add> @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add>
<add> assert_raises(ActiveRecord::StatementInvalid) do
<add> @conn.while_preventing_writes do
<add> @conn.execute("REPLACE INTO ex (data) VALUES ('249823948')")
<add> end
<add> end
<add> end
<add> end
<add>
<add> def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes
<add> with_example_table "id int, data string" do
<add> @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')")
<add>
<add> @conn.while_preventing_writes do
<add> assert_equal 1, @conn.execute("SELECT data from ex WHERE data = '138853948594'").count
<add> end
<add> end
<add> end
<add>
<ide> private
<ide>
<ide> def assert_logged(logs)
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_protected_environments_are_stored_as_an_array_of_string
<ide> ensure
<ide> ActiveRecord::Base.protected_environments = previous_protected_environments
<ide> end
<add>
<add> test "creating a record raises if preventing writes" do
<add> assert_raises ActiveRecord::StatementInvalid do
<add> ActiveRecord::Base.connection.while_preventing_writes do
<add> bird = Bird.create! name: "Bluejay"
<add> end
<add> end
<add> end
<add>
<add> test "updating a record raises if preventing writes" do
<add> bird = Bird.create! name: "Bluejay"
<add>
<add> assert_raises ActiveRecord::StatementInvalid do
<add> ActiveRecord::Base.connection.while_preventing_writes do
<add> bird.update! name: "Robin"
<add> end
<add> end
<add> end
<add>
<add> test "deleting a record raises if preventing writes" do
<add> bird = Bird.create! name: "Bluejay"
<add>
<add> assert_raises ActiveRecord::StatementInvalid do
<add> ActiveRecord::Base.connection.while_preventing_writes do
<add> bird.destroy!
<add> end
<add> end
<add> end
<add>
<add> test "selecting a record does not raise if preventing writes" do
<add> bird = Bird.create! name: "Bluejay"
<add>
<add> ActiveRecord::Base.connection.while_preventing_writes do
<add> assert_equal bird, Bird.where(name: "Bluejay").first
<add> end
<add> end
<ide> end | 10 |
Java | Java | delete unused imports | 2719dcb29b871ec24d6f10028dce76e440691d20 | <ide><path>spring-context-indexer/src/test/java/org/springframework/context/index/test/TestCompiler.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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.nio.file.Path;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<del>import java.util.List;
<del>import java.util.stream.Collectors;
<ide>
<ide> import javax.annotation.processing.Processor;
<ide> import javax.tools.JavaCompiler; | 1 |
Text | Text | fix document errors related to ticks | 946c6d0617bfa0eb21e86f6f75d7f34b2bb1dc85 | <ide><path>docs/axes/cartesian/README.md
<ide> The following options are common to all cartesian axes but do not apply to other
<ide> | `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to `maxRotation` before skipping any. Turn `autoSkip` off to show all labels no matter what.
<ide> | `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled.
<ide> | `labelOffset` | `number` | `0` | Distance in pixels to offset the label from the centre point of the tick (in the x direction for the x axis, and the y direction for the y axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas*
<del>| `maxRotation` | `number` | `90` | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.*
<add>| `maxRotation` | `number` | `50` | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.*
<ide> | `minRotation` | `number` | `0` | Minimum rotation for tick labels. *Note: Only applicable to horizontal scales.*
<ide> | `mirror` | `boolean` | `false` | Flips tick labels around axis, displaying the labels inside the chart instead of outside. *Note: Only applicable to vertical scales.*
<del>| `padding` | `number` | `10` | Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction.
<add>| `padding` | `number` | `0` | Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction.
<ide>
<ide> ### Axis ID
<ide> The properties `dataset.xAxisID` or `dataset.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used.
<ide><path>docs/axes/styling.md
<ide> The minorTick configuration is nested under the ticks configuration in the `mino
<ide> | `lineHeight` | <code>number|string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).
<ide>
<ide> ## Major Tick Configuration
<del>The majorTick configuration is nested under the ticks configuration in the `major` key. It defines options for the major tick marks that are generated by the axis. Omitted options are inherited from `ticks` configuration.
<add>The majorTick configuration is nested under the ticks configuration in the `major` key. It defines options for the major tick marks that are generated by the axis. Omitted options are inherited from `ticks` configuration. These options are disabled by default.
<ide>
<ide> | Name | Type | Default | Description
<ide> | ---- | ---- | ------- | -----------
<add>| `enabled` | `boolean` | `false` | If true, major tick options are used to show major ticks.
<ide> | `callback` | `function` | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats).
<ide> | `fontColor` | `Color` | `'#666'` | Font color for tick labels.
<ide> | `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the tick labels, follows CSS font-family options. | 2 |
Ruby | Ruby | use 1.9 hash syntax instead | 7c9bcbb5e486a5d5e35d38c5fbcbea6af88fc23a | <ide><path>railties/lib/rails/generators/generated_attribute.rb
<ide> def has_uniq_index?
<ide> end
<ide>
<ide> def inject_options
<del> @attr_options.blank? ? '' : ", #{@attr_options.to_s.gsub(/[{}]/, '')}"
<add> "".tap { |s| @attr_options.each { |k,v| s << ", #{k}: #{v.inspect}" } }
<ide> end
<ide>
<ide> def inject_index_options
<del> has_uniq_index? ? ", :unique => true" : ''
<add> has_uniq_index? ? ", unique: true" : ""
<ide> end
<ide> end
<ide> end
<ide><path>railties/test/generators/migration_generator_test.rb
<ide> def test_add_migration_with_attributes_and_indices
<ide> assert_match(/add_column :posts, :user_id, :integer/, up)
<ide> end
<ide> assert_match(/add_index :posts, :title/, content)
<del> assert_match(/add_index :posts, :user_id, :unique => true/, content)
<add> assert_match(/add_index :posts, :user_id, unique: true/, content)
<ide> end
<ide> end
<ide>
<ide> def test_add_migration_with_attributes_without_type_and_index
<ide> assert_match(/add_column :posts, :user_uuid, :string/, up)
<ide> end
<ide> assert_match(/add_index :posts, :title/, content)
<del> assert_match(/add_index :posts, :user_uuid, :unique => true/, content)
<add> assert_match(/add_index :posts, :user_uuid, unique: true/, content)
<ide> end
<ide> end
<ide>
<ide> def test_add_migration_with_attributes_index_declaration_and_attribute_options
<ide>
<ide> assert_migration "db/migrate/#{migration}.rb" do |content|
<ide> assert_method :change, content do |up|
<del> assert_match(/add_column :books, :title, :string, :limit=>40/, up)
<del> assert_match(/add_column :books, :content, :string, :limit=>255/, up)
<del> assert_match(/add_column :books, :price, :decimal, :precision=>5, :scale=>2/, up)
<del> assert_match(/add_column :books, :discount, :decimal, :precision=>3, :scale=>2/, up)
<add> assert_match(/add_column :books, :title, :string, limit: 40/, up)
<add> assert_match(/add_column :books, :content, :string, limit: 255/, up)
<add> assert_match(/add_column :books, :price, :decimal, precision: 5, scale: 2/, up)
<add> assert_match(/add_column :books, :discount, :decimal, precision: 3, scale: 2/, up)
<ide> end
<ide> assert_match(/add_index :books, :title/, content)
<ide> assert_match(/add_index :books, :price/, content)
<del> assert_match(/add_index :books, :discount, :unique => true/, content)
<add> assert_match(/add_index :books, :discount, unique: true/, content)
<ide> end
<ide> end
<ide>
<ide><path>railties/test/generators/model_generator_test.rb
<ide> def test_migration_with_attributes_and_with_index
<ide>
<ide> assert_match(/add_index :products, :name/, up)
<ide> assert_match(/add_index :products, :supplier_id/, up)
<del> assert_match(/add_index :products, :user_id, :unique => true/, up)
<del> assert_match(/add_index :products, :order_id, :unique => true/, up)
<add> assert_match(/add_index :products, :user_id, unique: true/, up)
<add> assert_match(/add_index :products, :order_id, unique: true/, up)
<ide> end
<ide> end
<ide> end
<ide> def test_add_migration_with_attributes_index_declaration_and_attribute_options
<ide> assert_migration "db/migrate/create_products.rb" do |content|
<ide> assert_method :change, content do |up|
<ide> assert_match(/create_table :products/, up)
<del> assert_match(/t.string :title, :limit=>40/, up)
<del> assert_match(/t.string :content, :limit=>255/, up)
<del> assert_match(/t.decimal :price, :precision=>5, :scale=>2/, up)
<add> assert_match(/t.string :title, limit: 40/, up)
<add> assert_match(/t.string :content, limit: 255/, up)
<add> assert_match(/t.decimal :price, precision: 5, scale: 2/, up)
<ide> end
<ide> assert_match(/add_index :products, :title/, content)
<ide> assert_match(/add_index :products, :price/, content)
<del> assert_match(/add_index :products, :discount, :unique => true/, content)
<add> assert_match(/add_index :products, :discount, unique: true/, content)
<ide> end
<ide> end
<ide> | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.