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
Go
Go
fix error string in docker cli test
76ace9bb5e2c5ecdd02046956ab00f76c3b25a3a
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunAttachFailedNoLeak(c *check.C) { <ide> // TODO Windows Post TP5. Fix the error message string <ide> c.Assert(strings.Contains(string(out), "port is already allocated") || <ide> strings.Contains(string(out), "were not connected because a duplicate name exists") || <add> strings.Contains(string(out), "The specified port already exists") || <ide> strings.Contains(string(out), "HNS failed with error : Failed to create endpoint") || <ide> strings.Contains(string(out), "HNS failed with error : The object already exists"), checker.Equals, true, check.Commentf("Output: %s", out)) <ide> dockerCmd(c, "rm", "-f", "test")
1
Javascript
Javascript
drop reactdom from internal dom extensions
531c2bc4c9a25f98c794a2c732a1232975ab9bbb
<ide><path>src/browser/ui/dom/components/ReactDOMButton.js <ide> var AutoFocusMixin = require('AutoFocusMixin'); <ide> var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <ide> var ReactClass = require('ReactClass'); <ide> var ReactElement = require('ReactElement'); <del>var ReactDOM = require('ReactDOM'); <ide> <ide> var keyMirror = require('keyMirror'); <ide> <del>// Store a reference to the <button> `ReactDOMComponent`. TODO: use string <del>var button = ReactElement.createFactory(ReactDOM.button.type); <add>var button = ReactElement.createFactory('button'); <ide> <ide> var mouseListenerNames = keyMirror({ <ide> onClick: true, <ide><path>src/browser/ui/dom/components/ReactDOMForm.js <ide> var LocalEventTrapMixin = require('LocalEventTrapMixin'); <ide> var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <ide> var ReactClass = require('ReactClass'); <ide> var ReactElement = require('ReactElement'); <del>var ReactDOM = require('ReactDOM'); <ide> <del>// Store a reference to the <form> `ReactDOMComponent`. TODO: use string <del>var form = ReactElement.createFactory(ReactDOM.form.type); <add>var form = ReactElement.createFactory('form'); <ide> <ide> /** <ide> * Since onSubmit doesn't bubble OR capture on the top level in IE8, we need <ide><path>src/browser/ui/dom/components/ReactDOMImg.js <ide> var LocalEventTrapMixin = require('LocalEventTrapMixin'); <ide> var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <ide> var ReactClass = require('ReactClass'); <ide> var ReactElement = require('ReactElement'); <del>var ReactDOM = require('ReactDOM'); <ide> <del>// Store a reference to the <img> `ReactDOMComponent`. TODO: use string <del>var img = ReactElement.createFactory(ReactDOM.img.type); <add>var img = ReactElement.createFactory('img'); <ide> <ide> /** <ide> * Since onLoad doesn't bubble OR capture on the top level in IE8, we need to <ide><path>src/browser/ui/dom/components/ReactDOMInput.js <ide> var LinkedValueUtils = require('LinkedValueUtils'); <ide> var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <ide> var ReactClass = require('ReactClass'); <ide> var ReactElement = require('ReactElement'); <del>var ReactDOM = require('ReactDOM'); <ide> var ReactMount = require('ReactMount'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> <ide> var assign = require('Object.assign'); <ide> var invariant = require('invariant'); <ide> <del>// Store a reference to the <input> `ReactDOMComponent`. TODO: use string <del>var input = ReactElement.createFactory(ReactDOM.input.type); <add>var input = ReactElement.createFactory('input'); <ide> <ide> var instancesByReactID = {}; <ide> <ide><path>src/browser/ui/dom/components/ReactDOMOption.js <ide> var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <ide> var ReactClass = require('ReactClass'); <ide> var ReactElement = require('ReactElement'); <del>var ReactDOM = require('ReactDOM'); <ide> <ide> var warning = require('warning'); <ide> <del>// Store a reference to the <option> `ReactDOMComponent`. TODO: use string <del>var option = ReactElement.createFactory(ReactDOM.option.type); <add>var option = ReactElement.createFactory('option'); <ide> <ide> /** <ide> * Implements an <option> native component that warns when `selected` is set. <ide><path>src/browser/ui/dom/components/ReactDOMSelect.js <ide> var LinkedValueUtils = require('LinkedValueUtils'); <ide> var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <ide> var ReactClass = require('ReactClass'); <ide> var ReactElement = require('ReactElement'); <del>var ReactDOM = require('ReactDOM'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> <ide> var assign = require('Object.assign'); <ide> <del>// Store a reference to the <select> `ReactDOMComponent`. TODO: use string <del>var select = ReactElement.createFactory(ReactDOM.select.type); <add>var select = ReactElement.createFactory('select'); <ide> <ide> function updateWithPendingValueIfMounted() { <ide> /*jshint validthis:true */ <ide><path>src/browser/ui/dom/components/ReactDOMTextarea.js <ide> var LinkedValueUtils = require('LinkedValueUtils'); <ide> var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <ide> var ReactClass = require('ReactClass'); <ide> var ReactElement = require('ReactElement'); <del>var ReactDOM = require('ReactDOM'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> <ide> var assign = require('Object.assign'); <ide> var invariant = require('invariant'); <ide> <ide> var warning = require('warning'); <ide> <del>// Store a reference to the <textarea> `ReactDOMComponent`. TODO: use string <del>var textarea = ReactElement.createFactory(ReactDOM.textarea.type); <add>var textarea = ReactElement.createFactory('textarea'); <ide> <ide> function forceUpdateIfMounted() { <ide> /*jshint validthis:true */
7
Python
Python
add host header by default to all requests
4cf416d25b06f489f7cc4d52b5bc6c3cd9a0666a
<ide><path>libcloud/base.py <ide> def request(self, action, params={}, data='', headers={}, method='GET'): <ide> # We always send a content length and user-agent header <ide> headers.update({'Content-Length': len(data)}) <ide> headers.update({'User-Agent': 'libcloud/%s' % (self.driver.name)}) <add> headers.update({'Host': self.host}) <ide> # Encode data if necessary <ide> if data != '': <ide> data = self.encode_data(data) <ide><path>libcloud/drivers/ec2.py <ide> class EC2Connection(ConnectionUserAndKey): <ide> host = EC2_US_HOST <ide> responseCls = EC2Response <ide> <del> def add_default_headers(self, headers): <del> headers['Host'] = self.host <del> return headers <del> <ide> def add_default_params(self, params): <ide> params['SignatureVersion'] = '2' <ide> params['SignatureMethod'] = 'HmacSHA256'
2
Mixed
Ruby
standardize nodoc comments
18707ab17fa492eb25ad2e8f9818a320dc20b823
<ide><path>actioncable/lib/action_cable/channel/broadcasting.rb <ide> def broadcasting_for(model) <ide> serialize_broadcasting([ channel_name, model ]) <ide> end <ide> <del> def serialize_broadcasting(object) #:nodoc: <add> def serialize_broadcasting(object) # :nodoc: <ide> case <ide> when object.is_a?(Array) <ide> object.map { |m| serialize_broadcasting(m) }.join(":") <ide><path>actioncable/lib/action_cable/connection/base.rb <ide> def initialize(server, env, coder: ActiveSupport::JSON) <ide> <ide> # Called by the server when a new WebSocket connection is established. This configures the callbacks intended for overwriting by the user. <ide> # This method should not be called directly -- instead rely upon on the #connect (and #disconnect) callbacks. <del> def process #:nodoc: <add> def process # :nodoc: <ide> logger.info started_request_message <ide> <ide> if websocket.possible? && allow_request_origin? <ide> def process #:nodoc: <ide> <ide> # Decodes WebSocket messages and dispatches them to subscribed channels. <ide> # WebSocket message transfer encoding is always JSON. <del> def receive(websocket_message) #:nodoc: <add> def receive(websocket_message) # :nodoc: <ide> send_async :dispatch_websocket_message, websocket_message <ide> end <ide> <del> def dispatch_websocket_message(websocket_message) #:nodoc: <add> def dispatch_websocket_message(websocket_message) # :nodoc: <ide> if websocket.alive? <ide> subscriptions.execute_command decode(websocket_message) <ide> else <ide><path>actionmailbox/app/models/action_mailbox/record.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionMailbox <del> class Record < ActiveRecord::Base #:nodoc: <add> class Record < ActiveRecord::Base # :nodoc: <ide> self.abstract_class = true <ide> end <ide> end <ide><path>actionmailbox/lib/action_mailbox/base.rb <ide> def initialize(inbound_email) <ide> @inbound_email = inbound_email <ide> end <ide> <del> def perform_processing #:nodoc: <add> def perform_processing # :nodoc: <ide> track_status_of_inbound_email do <ide> run_callbacks :process do <ide> process <ide> def process <ide> # Overwrite in subclasses <ide> end <ide> <del> def finished_processing? #:nodoc: <add> def finished_processing? # :nodoc: <ide> inbound_email.delivered? || inbound_email.bounced? <ide> end <ide> <ide><path>actionmailer/lib/action_mailer/base.rb <ide> def default(value = nil) <ide> # through a callback when you call <tt>:deliver</tt> on the <tt>Mail::Message</tt>, <ide> # calling +deliver_mail+ directly and passing a <tt>Mail::Message</tt> will do <ide> # nothing except tell the logger you sent the email. <del> def deliver_mail(mail) #:nodoc: <add> def deliver_mail(mail) # :nodoc: <ide> ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload| <ide> set_payload_for_mail(payload, mail) <ide> yield # Let Mail do the delivery actions <ide> def initialize <ide> @_message = Mail.new <ide> end <ide> <del> def process(method_name, *args) #:nodoc: <add> def process(method_name, *args) # :nodoc: <ide> payload = { <ide> mailer: self.class.name, <ide> action: method_name, <ide> def process(method_name, *args) #:nodoc: <ide> end <ide> end <ide> <del> class NullMail #:nodoc: <add> class NullMail # :nodoc: <ide> def body; "" end <ide> def header; {} end <ide> <ide><path>actionmailer/lib/action_mailer/delivery_job.rb <ide> class DeliveryJob < ActiveJob::Base # :nodoc: <ide> MSG <ide> end <ide> <del> def perform(mailer, mail_method, delivery_method, *args) #:nodoc: <add> def perform(mailer, mail_method, delivery_method, *args) # :nodoc: <ide> mailer.constantize.public_send(mail_method, *args).send(delivery_method) <ide> end <ide> ruby2_keywords(:perform) <ide><path>actionmailer/lib/action_mailer/inline_preview_interceptor.rb <ide> class InlinePreviewInterceptor <ide> <ide> include Base64 <ide> <del> def self.previewing_email(message) #:nodoc: <add> def self.previewing_email(message) # :nodoc: <ide> new(message).transform! <ide> end <ide> <del> def initialize(message) #:nodoc: <add> def initialize(message) # :nodoc: <ide> @message = message <ide> end <ide> <del> def transform! #:nodoc: <add> def transform! # :nodoc: <ide> return message if html_part.blank? <ide> <ide> html_part.body = html_part.decoded.gsub(PATTERN) do |match| <ide><path>actionmailer/lib/action_mailer/message_delivery.rb <ide> module ActionMailer <ide> # Notifier.welcome(User.first).deliver_later # enqueue email delivery as a job through Active Job <ide> # Notifier.welcome(User.first).message # a Mail::Message object <ide> class MessageDelivery < Delegator <del> def initialize(mailer_class, action, *args) #:nodoc: <add> def initialize(mailer_class, action, *args) # :nodoc: <ide> @mailer_class, @action, @args = mailer_class, action, args <ide> <ide> # The mail is only processed if we try to call any methods on it. <ide> def initialize(mailer_class, action, *args) #:nodoc: <ide> ruby2_keywords(:initialize) <ide> <ide> # Method calls are delegated to the Mail::Message that's ready to deliver. <del> def __getobj__ #:nodoc: <add> def __getobj__ # :nodoc: <ide> @mail_message ||= processed_mailer.message <ide> end <ide> <ide> # Unused except for delegator internals (dup, marshalling). <del> def __setobj__(mail_message) #:nodoc: <add> def __setobj__(mail_message) # :nodoc: <ide> @mail_message = mail_message <ide> end <ide> <ide><path>actionmailer/lib/action_mailer/preview.rb <ide> require "active_support/descendants_tracker" <ide> <ide> module ActionMailer <del> module Previews #:nodoc: <add> module Previews # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>actionmailer/lib/action_mailer/rescuable.rb <ide> # frozen_string_literal: true <ide> <del>module ActionMailer #:nodoc: <add>module ActionMailer # :nodoc: <ide> # Provides +rescue_from+ for mailers. Wraps mailer action processing, <ide> # mail job processing, and mail delivery. <ide> module Rescuable <ide> extend ActiveSupport::Concern <ide> include ActiveSupport::Rescuable <ide> <ide> class_methods do <del> def handle_exception(exception) #:nodoc: <add> def handle_exception(exception) # :nodoc: <ide> rescue_with_handler(exception) || raise(exception) <ide> end <ide> end <ide> <del> def handle_exceptions #:nodoc: <add> def handle_exceptions # :nodoc: <ide> yield <ide> rescue => exception <ide> rescue_with_handler(exception) || raise <ide><path>actionpack/lib/abstract_controller/asset_paths.rb <ide> # frozen_string_literal: true <ide> <ide> module AbstractController <del> module AssetPaths #:nodoc: <add> module AssetPaths # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>actionpack/lib/abstract_controller/error.rb <ide> # frozen_string_literal: true <ide> <ide> module AbstractController <del> class Error < StandardError #:nodoc: <add> class Error < StandardError # :nodoc: <ide> end <ide> end <ide><path>actionpack/lib/abstract_controller/logger.rb <ide> require "active_support/benchmarkable" <ide> <ide> module AbstractController <del> module Logger #:nodoc: <add> module Logger # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>actionpack/lib/action_controller/metal.rb <ide> module ActionController <ide> # use AuthenticationMiddleware, except: [:index, :show] <ide> # end <ide> # <del> class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc: <del> class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc: <add> class MiddlewareStack < ActionDispatch::MiddlewareStack # :nodoc: <add> class Middleware < ActionDispatch::MiddlewareStack::Middleware # :nodoc: <ide> def initialize(klass, args, actions, strategy, block) <ide> @actions = actions <ide> @strategy = strategy <ide> def performed? <ide> response_body || response.committed? <ide> end <ide> <del> def dispatch(name, request, response) #:nodoc: <add> def dispatch(name, request, response) # :nodoc: <ide> set_request!(request) <ide> set_response!(response) <ide> process(name) <ide> def set_response!(response) # :nodoc: <ide> @_response = response <ide> end <ide> <del> def set_request!(request) #:nodoc: <add> def set_request!(request) # :nodoc: <ide> @_request = request <ide> @_request.controller_instance = self <ide> end <ide> <del> def to_a #:nodoc: <add> def to_a # :nodoc: <ide> response.to_a <ide> end <ide> <ide><path>actionpack/lib/action_controller/metal/content_security_policy.rb <ide> # frozen_string_literal: true <ide> <del>module ActionController #:nodoc: <add>module ActionController # :nodoc: <ide> module ContentSecurityPolicy <ide> # TODO: Documentation <ide> extend ActiveSupport::Concern <ide><path>actionpack/lib/action_controller/metal/cookies.rb <ide> # frozen_string_literal: true <ide> <del>module ActionController #:nodoc: <add>module ActionController # :nodoc: <ide> module Cookies <ide> extend ActiveSupport::Concern <ide> <ide><path>actionpack/lib/action_controller/metal/data_streaming.rb <ide> require "action_controller/metal/exceptions" <ide> require "action_dispatch/http/content_disposition" <ide> <del>module ActionController #:nodoc: <add>module ActionController # :nodoc: <ide> # Methods for sending arbitrary data and for streaming files to the browser, <ide> # instead of rendering. <ide> module DataStreaming <ide> extend ActiveSupport::Concern <ide> <ide> include ActionController::Rendering <ide> <del> DEFAULT_SEND_FILE_TYPE = "application/octet-stream" #:nodoc: <del> DEFAULT_SEND_FILE_DISPOSITION = "attachment" #:nodoc: <add> DEFAULT_SEND_FILE_TYPE = "application/octet-stream" # :nodoc: <add> DEFAULT_SEND_FILE_DISPOSITION = "attachment" # :nodoc: <ide> <ide> private <ide> # Sends the file. This uses a server-appropriate method (such as X-Sendfile) <ide><path>actionpack/lib/action_controller/metal/exceptions.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionController <del> class ActionControllerError < StandardError #:nodoc: <add> class ActionControllerError < StandardError # :nodoc: <ide> end <ide> <del> class BadRequest < ActionControllerError #:nodoc: <add> class BadRequest < ActionControllerError # :nodoc: <ide> def initialize(msg = nil) <ide> super(msg) <ide> set_backtrace $!.backtrace if $! <ide> end <ide> end <ide> <del> class RenderError < ActionControllerError #:nodoc: <add> class RenderError < ActionControllerError # :nodoc: <ide> end <ide> <del> class RoutingError < ActionControllerError #:nodoc: <add> class RoutingError < ActionControllerError # :nodoc: <ide> attr_reader :failures <ide> def initialize(message, failures = []) <ide> super(message) <ide> @failures = failures <ide> end <ide> end <ide> <del> class UrlGenerationError < ActionControllerError #:nodoc: <add> class UrlGenerationError < ActionControllerError # :nodoc: <ide> attr_reader :routes, :route_name, :method_name <ide> <ide> def initialize(message, routes = nil, route_name = nil, method_name = nil) <ide> def corrections <ide> end <ide> end <ide> <del> class MethodNotAllowed < ActionControllerError #:nodoc: <add> class MethodNotAllowed < ActionControllerError # :nodoc: <ide> def initialize(*allowed_methods) <ide> super("Only #{allowed_methods.to_sentence} requests are allowed.") <ide> end <ide> end <ide> <del> class NotImplemented < MethodNotAllowed #:nodoc: <add> class NotImplemented < MethodNotAllowed # :nodoc: <ide> end <ide> <del> class MissingFile < ActionControllerError #:nodoc: <add> class MissingFile < ActionControllerError # :nodoc: <ide> end <ide> <del> class SessionOverflowError < ActionControllerError #:nodoc: <add> class SessionOverflowError < ActionControllerError # :nodoc: <ide> DEFAULT_MESSAGE = "Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data." <ide> <ide> def initialize(message = nil) <ide> super(message || DEFAULT_MESSAGE) <ide> end <ide> end <ide> <del> class UnknownHttpMethod < ActionControllerError #:nodoc: <add> class UnknownHttpMethod < ActionControllerError # :nodoc: <ide> end <ide> <del> class UnknownFormat < ActionControllerError #:nodoc: <add> class UnknownFormat < ActionControllerError # :nodoc: <ide> end <ide> <ide> # Raised when a nested respond_to is triggered and the content types of each <ide> def initialize(message = nil) <ide> end <ide> end <ide> <del> class MissingExactTemplate < UnknownFormat #:nodoc: <add> class MissingExactTemplate < UnknownFormat # :nodoc: <ide> end <ide> end <ide><path>actionpack/lib/action_controller/metal/flash.rb <ide> # frozen_string_literal: true <ide> <del>module ActionController #:nodoc: <add>module ActionController # :nodoc: <ide> module Flash <ide> extend ActiveSupport::Concern <ide> <ide> def add_flash_types(*types) <ide> end <ide> end <ide> <del> def action_methods #:nodoc: <add> def action_methods # :nodoc: <ide> @action_methods ||= super - _flash_types.map(&:to_s).to_set <ide> end <ide> end <ide><path>actionpack/lib/action_controller/metal/instrumentation.rb <ide> module ClassMethods <ide> # A hook which allows other frameworks to log what happened during <ide> # controller process action. This method should return an array <ide> # with the messages to be added. <del> def log_process_action(payload) #:nodoc: <add> def log_process_action(payload) # :nodoc: <ide> messages, view_runtime = [], payload[:view_runtime] <ide> messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime <ide> messages <ide><path>actionpack/lib/action_controller/metal/live.rb <ide> def perform_write(json, options) <ide> class ClientDisconnected < RuntimeError <ide> end <ide> <del> class Buffer < ActionDispatch::Response::Buffer #:nodoc: <add> class Buffer < ActionDispatch::Response::Buffer # :nodoc: <ide> include MonitorMixin <ide> <ide> class << self <ide> def build_queue(queue_size) <ide> end <ide> end <ide> <del> class Response < ActionDispatch::Response #:nodoc: all <add> class Response < ActionDispatch::Response # :nodoc: all <ide> private <ide> def before_committed <ide> super <ide><path>actionpack/lib/action_controller/metal/mime_responds.rb <ide> <ide> require "abstract_controller/collector" <ide> <del>module ActionController #:nodoc: <add>module ActionController # :nodoc: <ide> module MimeResponds <ide> # Without web-service support, an action which collects the data for displaying a list of people <ide> # might look something like this: <ide> def negotiate_format(request) <ide> @format = request.negotiate_mime(@responses.keys) <ide> end <ide> <del> class VariantCollector #:nodoc: <add> class VariantCollector # :nodoc: <ide> def initialize(variant = nil) <ide> @variant = variant <ide> @variants = {} <ide><path>actionpack/lib/action_controller/metal/permissions_policy.rb <ide> # frozen_string_literal: true <ide> <del>module ActionController #:nodoc: <add>module ActionController # :nodoc: <ide> # HTTP Permissions Policy is a web standard for defining a mechanism to <ide> # allow and deny the use of browser permissions in its own context, and <ide> # in content within any <iframe> elements in the document. <ide><path>actionpack/lib/action_controller/metal/redirecting.rb <ide> def _compute_safe_redirect_to_location(request, options, response_options) <ide> end <ide> end <ide> <del> def _compute_redirect_to_location(request, options) #:nodoc: <add> def _compute_redirect_to_location(request, options) # :nodoc: <ide> case options <ide> # The scheme name consist of a letter followed by any combination of <ide> # letters, digits, and the plus ("+"), period ("."), or hyphen ("-") <ide><path>actionpack/lib/action_controller/metal/rendering.rb <ide> def inherited(klass) <ide> end <ide> <ide> # Check for double render errors and set the content_type after rendering. <del> def render(*args) #:nodoc: <add> def render(*args) # :nodoc: <ide> raise ::AbstractController::DoubleRenderError if response_body <ide> super <ide> end <ide> def render_to_body(options = {}) <ide> <ide> private <ide> # Before processing, set the request formats in current controller formats. <del> def process_action(*) #:nodoc: <add> def process_action(*) # :nodoc: <ide> self.formats = request.formats.filter_map(&:ref) <ide> super <ide> end <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb <ide> require "action_controller/metal/exceptions" <ide> require "active_support/security_utils" <ide> <del>module ActionController #:nodoc: <del> class InvalidAuthenticityToken < ActionControllerError #:nodoc: <add>module ActionController # :nodoc: <add> class InvalidAuthenticityToken < ActionControllerError # :nodoc: <ide> end <ide> <del> class InvalidCrossOriginRequest < ActionControllerError #:nodoc: <add> class InvalidCrossOriginRequest < ActionControllerError # :nodoc: <ide> end <ide> <ide> # Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks <ide> def handle_unverified_request <ide> end <ide> <ide> private <del> class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc: <add> class NullSessionHash < Rack::Session::Abstract::SessionHash # :nodoc: <ide> def initialize(req) <ide> super(nil, req) <ide> @data = {} <ide> def enabled? <ide> end <ide> end <ide> <del> class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc: <add> class NullCookieJar < ActionDispatch::Cookies::CookieJar # :nodoc: <ide> def write(*) <ide> # nothing <ide> end <ide> def handle_unverified_request # :doc: <ide> protection_strategy.handle_unverified_request <ide> end <ide> <del> def unverified_request_warning_message #:nodoc: <add> def unverified_request_warning_message # :nodoc: <ide> if valid_request_origin? <ide> "Can't verify CSRF token authenticity." <ide> else <ide> "HTTP Origin header (#{request.origin}) didn't match request.base_url (#{request.base_url})" <ide> end <ide> end <ide> <del> #:nodoc: <add> # :nodoc: <ide> CROSS_ORIGIN_JAVASCRIPT_WARNING = "Security warning: an embedded " \ <ide> "<script> tag on another site requested protected JavaScript. " \ <ide> "If you know what you're doing, go ahead and disable forgery " \ <ide><path>actionpack/lib/action_controller/metal/rescue.rb <ide> # frozen_string_literal: true <ide> <del>module ActionController #:nodoc: <add>module ActionController # :nodoc: <ide> # This module is responsible for providing +rescue_from+ helpers <ide> # to controllers and configuring when detailed exceptions must be <ide> # shown. <ide><path>actionpack/lib/action_controller/metal/streaming.rb <ide> <ide> require "rack/chunked" <ide> <del>module ActionController #:nodoc: <add>module ActionController # :nodoc: <ide> # Allows views to be streamed back to the client as they are rendered. <ide> # <ide> # By default, Rails renders views by first rendering the template <ide><path>actionpack/lib/action_controller/railtie.rb <ide> require "action_view/railtie" <ide> <ide> module ActionController <del> class Railtie < Rails::Railtie #:nodoc: <add> class Railtie < Rails::Railtie # :nodoc: <ide> config.action_controller = ActiveSupport::OrderedOptions.new <ide> config.action_controller.raise_on_open_redirects = false <ide> <ide><path>actionpack/lib/action_controller/test_case.rb <ide> def new_controller_thread # :nodoc: <ide> <ide> # ActionController::TestCase will be deprecated and moved to a gem in the future. <ide> # Please use ActionDispatch::IntegrationTest going forward. <del> class TestRequest < ActionDispatch::TestRequest #:nodoc: <add> class TestRequest < ActionDispatch::TestRequest # :nodoc: <ide> DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup <ide> DEFAULT_ENV.delete "PATH_INFO" <ide> <ide> class LiveTestResponse < Live::Response <ide> <ide> # Methods #destroy and #load! are overridden to avoid calling methods on the <ide> # @store object, which does not exist for the TestSession class. <del> class TestSession < Rack::Session::Abstract::PersistedSecure::SecureSessionHash #:nodoc: <add> class TestSession < Rack::Session::Abstract::PersistedSecure::SecureSessionHash # :nodoc: <ide> DEFAULT_OPTIONS = Rack::Session::Abstract::Persisted::DEFAULT_OPTIONS <ide> <ide> def initialize(session = {}) <ide><path>actionpack/lib/action_dispatch/http/content_security_policy.rb <ide> <ide> require "active_support/core_ext/object/deep_dup" <ide> <del>module ActionDispatch #:nodoc: <add>module ActionDispatch # :nodoc: <ide> class ContentSecurityPolicy <ide> class Middleware <ide> CONTENT_TYPE = "Content-Type" <ide><path>actionpack/lib/action_dispatch/http/mime_type.rb <ide> class Type <ide> @register_callbacks = [] <ide> <ide> # A simple helper class used in parsing the accept header. <del> class AcceptItem #:nodoc: <add> class AcceptItem # :nodoc: <ide> attr_accessor :index, :name, :q <ide> alias :to_s :name <ide> <ide> def <=>(item) <ide> end <ide> end <ide> <del> class AcceptList #:nodoc: <add> class AcceptList # :nodoc: <ide> def self.sort!(list) <ide> list.sort! <ide> <ide><path>actionpack/lib/action_dispatch/http/parameters.rb <ide> def parameters <ide> end <ide> alias :params :parameters <ide> <del> def path_parameters=(parameters) #:nodoc: <add> def path_parameters=(parameters) # :nodoc: <ide> delete_header("action_dispatch.request.parameters") <ide> <ide> parameters = Request::Utils.set_binary_encoding(self, parameters, parameters[:controller], parameters[:action]) <ide><path>actionpack/lib/action_dispatch/http/permissions_policy.rb <ide> <ide> require "active_support/core_ext/object/deep_dup" <ide> <del>module ActionDispatch #:nodoc: <add>module ActionDispatch # :nodoc: <ide> class PermissionsPolicy <ide> class Middleware <ide> CONTENT_TYPE = "Content-Type" <ide><path>actionpack/lib/action_dispatch/http/request.rb <ide> def engine_script_name=(name) # :nodoc: <ide> set_header(routes.env_key, name.dup) <ide> end <ide> <del> def request_method=(request_method) #:nodoc: <add> def request_method=(request_method) # :nodoc: <ide> if check_method(request_method) <ide> @request_method = set_header("REQUEST_METHOD", request_method) <ide> end <ide> def form_data? <ide> FORM_DATA_MEDIA_TYPES.include?(media_type) <ide> end <ide> <del> def body_stream #:nodoc: <add> def body_stream # :nodoc: <ide> get_header("rack.input") <ide> end <ide> <ide> def reset_session <ide> session.destroy <ide> end <ide> <del> def session=(session) #:nodoc: <add> def session=(session) # :nodoc: <ide> Session.set self, session <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/http/response.rb <ide> def body=(body) <ide> # Avoid having to pass an open file handle as the response body. <ide> # Rack::Sendfile will usually intercept the response and uses <ide> # the path directly, so there is no reason to open the file. <del> class FileBody #:nodoc: <add> class FileBody # :nodoc: <ide> attr_reader :to_path <ide> <ide> def initialize(path) <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> def signed_cookie_digest <ide> end <ide> end <ide> <del> class CookieJar #:nodoc: <add> class CookieJar # :nodoc: <ide> include Enumerable, ChainedCookieJars <ide> <ide> # This regular expression is used to split the levels of a domain. <ide><path>actionpack/lib/action_dispatch/middleware/flash.rb <ide> def reset_session # :nodoc: <ide> end <ide> end <ide> <del> class FlashNow #:nodoc: <add> class FlashNow # :nodoc: <ide> attr_accessor :flash <ide> <ide> def initialize(flash) <ide> def notice=(message) <ide> class FlashHash <ide> include Enumerable <ide> <del> def self.from_session_value(value) #:nodoc: <add> def self.from_session_value(value) # :nodoc: <ide> case value <ide> when FlashHash # Rails 3.1, 3.2 <ide> flashes = value.instance_variable_get(:@flashes) <ide> def self.from_session_value(value) #:nodoc: <ide> <ide> # Builds a hash containing the flashes to keep for the next request. <ide> # If there are none to keep, returns +nil+. <del> def to_session_value #:nodoc: <add> def to_session_value # :nodoc: <ide> flashes_to_keep = @flashes.except(*@discard) <ide> return nil if flashes_to_keep.empty? <ide> { "discard" => [], "flashes" => flashes_to_keep } <ide> end <ide> <del> def initialize(flashes = {}, discard = []) #:nodoc: <add> def initialize(flashes = {}, discard = []) # :nodoc: <ide> @discard = Set.new(stringify_array(discard)) <ide> @flashes = flashes.stringify_keys <ide> @now = nil <ide> def [](k) <ide> @flashes[k.to_s] <ide> end <ide> <del> def update(h) #:nodoc: <add> def update(h) # :nodoc: <ide> @discard.subtract stringify_array(h.keys) <ide> @flashes.update h.stringify_keys <ide> self <ide> def each(&block) <ide> <ide> alias :merge! :update <ide> <del> def replace(h) #:nodoc: <add> def replace(h) # :nodoc: <ide> @discard.clear <ide> @flashes.replace h.stringify_keys <ide> self <ide> def discard(k = nil) <ide> # Mark for removal entries that were kept, and delete unkept ones. <ide> # <ide> # This method is called automatically by filters, so you generally don't need to care about it. <del> def sweep #:nodoc: <add> def sweep # :nodoc: <ide> @discard.each { |k| @flashes.delete k } <ide> @discard.replace @flashes.keys <ide> end <ide><path>actionpack/lib/action_dispatch/middleware/session/abstract_store.rb <ide> <ide> module ActionDispatch <ide> module Session <del> class SessionRestoreError < StandardError #:nodoc: <add> class SessionRestoreError < StandardError # :nodoc: <ide> def initialize <ide> super("Session contains objects whose class definition isn't available.\n" \ <ide> "Remember to require the classes for all objects kept in the session.\n" \ <ide><path>actionpack/lib/action_dispatch/request/session.rb <ide> def self.delete(req) <ide> req.delete_header ENV_SESSION_KEY <ide> end <ide> <del> class Options #:nodoc: <add> class Options # :nodoc: <ide> def self.set(req, options) <ide> req.set_header ENV_SESSION_OPTIONS_KEY, options <ide> end <ide><path>actionpack/lib/action_dispatch/routing.rb <ide> module Routing <ide> autoload :UrlFor <ide> autoload :PolymorphicRoutes <ide> <del> SEPARATORS = %w( / . ? ) #:nodoc: <del> HTTP_METHODS = [:get, :head, :post, :patch, :put, :delete, :options] #:nodoc: <add> SEPARATORS = %w( / . ? ) # :nodoc: <add> HTTP_METHODS = [:get, :head, :post, :patch, :put, :delete, :options] # :nodoc: <ide> end <ide> end <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> module Routing <ide> class Mapper <ide> URL_OPTIONS = [:protocol, :subdomain, :domain, :host, :port] <ide> <del> class Constraints < Routing::Endpoint #:nodoc: <add> class Constraints < Routing::Endpoint # :nodoc: <ide> attr_reader :app, :constraints <ide> <ide> SERVE = ->(app, req) { app.serve req } <ide> def constraint_args(constraint, request) <ide> end <ide> end <ide> <del> class Mapping #:nodoc: <add> class Mapping # :nodoc: <ide> ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} <ide> OPTIONAL_FORMAT_REGEX = %r{(?:\(\.:format\)+|\.:format|/)\Z} <ide> <ide> module Resources <ide> RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns] <ide> CANONICAL_ACTIONS = %w(index create new show update destroy) <ide> <del> class Resource #:nodoc: <add> class Resource # :nodoc: <ide> attr_reader :controller, :path, :param <ide> <ide> def initialize(entities, api_only, shallow, options = {}) <ide> def shallow? <ide> def singleton?; false; end <ide> end <ide> <del> class SingletonResource < Resource #:nodoc: <add> class SingletonResource < Resource # :nodoc: <ide> def initialize(entities, api_only, shallow, options) <ide> super <ide> @as = nil <ide> def frame; @hash; end <ide> NULL = Scope.new(nil, nil) <ide> end <ide> <del> def initialize(set) #:nodoc: <add> def initialize(set) # :nodoc: <ide> @set = set <ide> @draw_paths = set.draw_paths <ide> @scope = Scope.new(path_names: @set.resources_path_names) <ide><path>actionpack/lib/action_dispatch/routing/routes_proxy.rb <ide> <ide> module ActionDispatch <ide> module Routing <del> class RoutesProxy #:nodoc: <add> class RoutesProxy # :nodoc: <ide> include ActionDispatch::Routing::UrlFor <ide> <ide> attr_accessor :scope, :routes <ide><path>actionpack/lib/action_dispatch/testing/integration.rb <ide> require "action_dispatch/testing/request_encoder" <ide> <ide> module ActionDispatch <del> module Integration #:nodoc: <add> module Integration # :nodoc: <ide> module RequestHelpers <ide> # Performs a GET request with the given parameters. See ActionDispatch::Integration::Session#process <ide> # for more details. <ide> def assertions=(assertions) # :nodoc: <ide> <ide> # Copy the instance variables from the current session instance into the <ide> # test instance. <del> def copy_session_variables! #:nodoc: <add> def copy_session_variables! # :nodoc: <ide> @controller = @integration_session.controller <ide> @response = @integration_session.response <ide> @request = @integration_session.request <ide><path>actiontext/app/helpers/action_text/content_helper.rb <ide> def render_action_text_attachments(content) <ide> end <ide> end <ide> <del> def render_action_text_attachment(attachment, locals: {}) #:nodoc: <add> def render_action_text_attachment(attachment, locals: {}) # :nodoc: <ide> options = { locals: locals, object: attachment, partial: attachment } <ide> <ide> if attachment.respond_to?(:to_attachable_partial_path) <ide><path>actiontext/app/models/action_text/record.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionText <del> class Record < ActiveRecord::Base #:nodoc: <add> class Record < ActiveRecord::Base # :nodoc: <ide> self.abstract_class = true <ide> end <ide> end <ide><path>actiontext/lib/action_text/rendering.rb <ide> require "active_support/core_ext/module/attribute_accessors_per_thread" <ide> <ide> module ActionText <del> module Rendering #:nodoc: <add> module Rendering # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>actionview/lib/action_view/base.rb <ide> require "action_view/template" <ide> require "action_view/lookup_context" <ide> <del>module ActionView #:nodoc: <add>module ActionView # :nodoc: <ide> # = Action View Base <ide> # <ide> # Action View templates can be written in several ways. <ide> def cache_template_loading=(value) <ide> ActionView::Resolver.caching = value <ide> end <ide> <del> def xss_safe? #:nodoc: <add> def xss_safe? # :nodoc: <ide> true <ide> end <ide> <ide> def self.with_context(context, assigns = {}, controller = nil) <ide> <ide> # :startdoc: <ide> <del> def initialize(lookup_context, assigns, controller) #:nodoc: <add> def initialize(lookup_context, assigns, controller) # :nodoc: <ide> @_config = ActiveSupport::InheritableOptions.new <ide> <ide> @lookup_context = lookup_context <ide><path>actionview/lib/action_view/buffers.rb <ide> module ActionView <ide> # sbuf << 5 <ide> # puts sbuf # => "hello\u0005" <ide> # <del> class OutputBuffer < ActiveSupport::SafeBuffer #:nodoc: <add> class OutputBuffer < ActiveSupport::SafeBuffer # :nodoc: <ide> def initialize(*) <ide> super <ide> encode! <ide> def safe_expr_append=(val) <ide> alias :safe_append= :safe_concat <ide> end <ide> <del> class StreamingBuffer #:nodoc: <add> class StreamingBuffer # :nodoc: <ide> def initialize(block) <ide> @block = block <ide> end <ide><path>actionview/lib/action_view/flows.rb <ide> require "active_support/core_ext/string/output_safety" <ide> <ide> module ActionView <del> class OutputFlow #:nodoc: <add> class OutputFlow # :nodoc: <ide> attr_reader :content <ide> <ide> def initialize <ide> def append(key, value) <ide> alias_method :append!, :append <ide> end <ide> <del> class StreamingFlow < OutputFlow #:nodoc: <add> class StreamingFlow < OutputFlow # :nodoc: <ide> def initialize(view, fiber) <ide> @view = view <ide> @parent = nil <ide><path>actionview/lib/action_view/helpers.rb <ide> require "action_view/helpers/rendering_helper" <ide> require "action_view/helpers/translation_helper" <ide> <del>module ActionView #:nodoc: <del> module Helpers #:nodoc: <add>module ActionView # :nodoc: <add> module Helpers # :nodoc: <ide> extend ActiveSupport::Autoload <ide> <ide> autoload :Tags <ide><path>actionview/lib/action_view/helpers/active_model_helper.rb <ide> <ide> module ActionView <ide> # = Active Model Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module ActiveModelHelper <ide> end <ide> <ide><path>actionview/lib/action_view/helpers/asset_tag_helper.rb <ide> <ide> module ActionView <ide> # = Action View Asset Tag Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # This module provides methods for generating HTML that links views to assets such <ide> # as images, JavaScripts, stylesheets, and feeds. These methods do not verify <ide> # the assets exist before linking to them: <ide><path>actionview/lib/action_view/helpers/asset_url_helper.rb <ide> <ide> module ActionView <ide> # = Action View Asset URL Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # This module provides methods for generating asset paths and <ide> # URLs. <ide> # <ide><path>actionview/lib/action_view/helpers/atom_feed_helper.rb <ide> <ide> module ActionView <ide> # = Action View Atom Feed Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module AtomFeedHelper <ide> # Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERB or any other <ide> # template languages). <ide> def atom_feed(options = {}, &block) <ide> end <ide> end <ide> <del> class AtomBuilder #:nodoc: <add> class AtomBuilder # :nodoc: <ide> XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set <ide> <ide> def initialize(xml) <ide> def xhtml_block?(method, arguments) <ide> end <ide> end <ide> <del> class AtomFeedBuilder < AtomBuilder #:nodoc: <add> class AtomFeedBuilder < AtomBuilder # :nodoc: <ide> def initialize(xml, view, feed_options = {}) <ide> @xml, @view, @feed_options = xml, view, feed_options <ide> end <ide><path>actionview/lib/action_view/helpers/cache_helper.rb <ide> <ide> module ActionView <ide> # = Action View Cache Helper <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module CacheHelper <ide> # This helper exposes a method for caching fragments of a view <ide> # rather than an entire action or page. This technique is useful <ide><path>actionview/lib/action_view/helpers/capture_helper.rb <ide> <ide> module ActionView <ide> # = Action View Capture Helper <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # CaptureHelper exposes methods to let you extract generated markup which <ide> # can be used in other parts of a template or layout file. <ide> # <ide> def content_for?(name) <ide> <ide> # Use an alternate output buffer for the duration of the block. <ide> # Defaults to a new empty string. <del> def with_output_buffer(buf = nil) #:nodoc: <add> def with_output_buffer(buf = nil) # :nodoc: <ide> unless buf <ide> buf = ActionView::OutputBuffer.new <ide> if output_buffer && output_buffer.respond_to?(:encoding) <ide><path>actionview/lib/action_view/helpers/controller_helper.rb <ide> require "active_support/core_ext/module/attr_internal" <ide> <ide> module ActionView <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # This module keeps all methods and behavior in ActionView <ide> # that simply delegates to the controller. <del> module ControllerHelper #:nodoc: <add> module ControllerHelper # :nodoc: <ide> attr_internal :controller, :request <ide> <ide> CONTROLLER_DELEGATES = [:request_forgery_protection_token, :params, <ide><path>actionview/lib/action_view/helpers/csp_helper.rb <ide> <ide> module ActionView <ide> # = Action View CSP Helper <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module CspHelper <ide> # Returns a meta tag "csp-nonce" with the per-session nonce value <ide> # for allowing inline <script> tags. <ide><path>actionview/lib/action_view/helpers/csrf_helper.rb <ide> <ide> module ActionView <ide> # = Action View CSRF Helper <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module CsrfHelper <ide> # Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site <ide> # request forgery protection parameter and token, respectively. <ide><path>actionview/lib/action_view/helpers/date_helper.rb <ide> require "active_support/core_ext/object/with_options" <ide> <ide> module ActionView <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # = Action View Date Helpers <ide> # <ide> # The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time <ide> def normalize_distance_of_time_argument_to_time(value) <ide> end <ide> end <ide> <del> class DateTimeSelector #:nodoc: <add> class DateTimeSelector # :nodoc: <ide> include ActionView::Helpers::TagHelper <ide> <ide> DEFAULT_PREFIX = "date" <ide><path>actionview/lib/action_view/helpers/debug_helper.rb <ide> module ActionView <ide> # = Action View Debug Helper <ide> # <ide> # Provides a set of methods for making it easier to debug Rails objects. <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module DebugHelper <ide> include TagHelper <ide> <ide><path>actionview/lib/action_view/helpers/form_helper.rb <ide> <ide> module ActionView <ide> # = Action View Form Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # Form helpers are designed to make working with resources much easier <ide> # compared to using vanilla HTML. <ide> # <ide> def form_for(record, options = {}, &block) <ide> form_tag_with_body(html_options, output) <ide> end <ide> <del> def apply_form_for_options!(record, object, options) #:nodoc: <add> def apply_form_for_options!(record, object, options) # :nodoc: <ide> object = convert_to_model(object) <ide> <ide> as = options[:as] <ide><path>actionview/lib/action_view/helpers/form_options_helper.rb <ide> <ide> module ActionView <ide> # = Action View Form Option Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # Provides a number of methods for turning different kinds of containers into a set of option tags. <ide> # <ide> # The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash: <ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb <ide> <ide> module ActionView <ide> # = Action View Form Tag Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like <ide> # FormHelper does. Instead, you provide the names and values manually. <ide> # <ide><path>actionview/lib/action_view/helpers/javascript_helper.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionView <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module JavaScriptHelper <ide> JS_ESCAPE_MAP = { <ide> "\\" => "\\\\", <ide> def javascript_tag(content_or_options_with_block = nil, html_options = {}, &bloc <ide> content_tag("script", javascript_cdata_section(content), html_options) <ide> end <ide> <del> def javascript_cdata_section(content) #:nodoc: <add> def javascript_cdata_section(content) # :nodoc: <ide> "\n//#{cdata_section("\n#{content}\n//")}\n".html_safe <ide> end <ide> end <ide><path>actionview/lib/action_view/helpers/number_helper.rb <ide> <ide> module ActionView <ide> # = Action View Number Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # Provides methods for converting numbers into formatted strings. <ide> # Methods are provided for phone numbers, currency, percentage, <ide> # precision, positional notation, file size and pretty printing. <ide><path>actionview/lib/action_view/helpers/output_safety_helper.rb <ide> <ide> require "active_support/core_ext/string/output_safety" <ide> <del>module ActionView #:nodoc: <add>module ActionView # :nodoc: <ide> # = Action View Raw Output Helper <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module OutputSafetyHelper <ide> # This method outputs without escaping a string. Since escaping tags is <ide> # now default, this can be used when you don't want Rails to automatically <ide><path>actionview/lib/action_view/helpers/rendering_helper.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionView <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # = Action View Rendering <ide> # <ide> # Implements methods that allow rendering from a view context. <ide><path>actionview/lib/action_view/helpers/sanitize_helper.rb <ide> <ide> module ActionView <ide> # = Action View Sanitize Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements. <ide> # These helper methods extend Action View making them callable within your template files. <ide> module SanitizeHelper <ide> def strip_links(html) <ide> self.class.link_sanitizer.sanitize(html) <ide> end <ide> <del> module ClassMethods #:nodoc: <add> module ClassMethods # :nodoc: <ide> attr_writer :full_sanitizer, :link_sanitizer, :safe_list_sanitizer <ide> <ide> def sanitizer_vendor <ide><path>actionview/lib/action_view/helpers/tag_helper.rb <ide> <ide> module ActionView <ide> # = Action View Tag Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # Provides methods to generate HTML tags programmatically both as a modern <ide> # HTML5 compliant builder style and legacy XHTML compliant tags. <ide> module TagHelper <ide> module TagHelper <ide> PRE_CONTENT_STRINGS[:textarea] = "\n" <ide> PRE_CONTENT_STRINGS["textarea"] = "\n" <ide> <del> class TagBuilder #:nodoc: <add> class TagBuilder # :nodoc: <ide> include CaptureHelper <ide> include OutputSafetyHelper <ide> <ide><path>actionview/lib/action_view/helpers/tags.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionView <del> module Helpers #:nodoc: <del> module Tags #:nodoc: <add> module Helpers # :nodoc: <add> module Tags # :nodoc: <ide> extend ActiveSupport::Autoload <ide> <ide> eager_autoload do <ide><path>actionview/lib/action_view/helpers/tags/check_box.rb <ide> module ActionView <ide> module Helpers <ide> module Tags # :nodoc: <del> class CheckBox < Base #:nodoc: <add> class CheckBox < Base # :nodoc: <ide> include Checkable <ide> <ide> def initialize(object_name, method_name, template_object, checked_value, unchecked_value, options) <ide><path>actionview/lib/action_view/helpers/tags/collection_select.rb <ide> module ActionView <ide> module Helpers <ide> module Tags # :nodoc: <del> class CollectionSelect < Base #:nodoc: <add> class CollectionSelect < Base # :nodoc: <ide> def initialize(object_name, method_name, template_object, collection, value_method, text_method, options, html_options) <ide> @collection = collection <ide> @value_method = value_method <ide><path>actionview/lib/action_view/helpers/text_helper.rb <ide> <ide> module ActionView <ide> # = Action View Text Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # The TextHelper module provides a set of methods for filtering, formatting <ide> # and transforming strings, which can reduce the amount of inline Ruby code in <ide> # your views. These helper methods extend Action View making them callable <ide> def reset_cycle(name = "default") <ide> cycle.reset if cycle <ide> end <ide> <del> class Cycle #:nodoc: <add> class Cycle # :nodoc: <ide> attr_reader :values <ide> <ide> def initialize(first_value, *values) <ide><path>actionview/lib/action_view/helpers/translation_helper.rb <ide> <ide> module ActionView <ide> # = Action View Translation Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> module TranslationHelper <ide> extend ActiveSupport::Concern <ide> <ide><path>actionview/lib/action_view/helpers/url_helper.rb <ide> <ide> module ActionView <ide> # = Action View URL Helpers <del> module Helpers #:nodoc: <add> module Helpers # :nodoc: <ide> # Provides a set of methods for making links and getting URLs that <ide> # depend on the routing subsystem (see ActionDispatch::Routing). <ide> # This allows you to use the same format for links in views <ide><path>actionview/lib/action_view/lookup_context.rb <ide> module ActionView <ide> # <tt>LookupContext</tt> is also responsible for generating a key, given to <ide> # view paths, used in the resolver cache lookup. Since this key is generated <ide> # only once during the request, it speeds up all cache accesses. <del> class LookupContext #:nodoc: <add> class LookupContext # :nodoc: <ide> attr_accessor :prefixes, :rendered_format <ide> <ide> singleton_class.attr_accessor :registered_details <ide> def #{name}=(value) <ide> end <ide> <ide> # Holds accessors for the registered details. <del> module Accessors #:nodoc: <add> module Accessors # :nodoc: <ide> DEFAULT_PROCS = {} <ide> end <ide> <ide> module Accessors #:nodoc: <ide> register_detail(:variants) { [] } <ide> register_detail(:handlers) { Template::Handlers.extensions } <ide> <del> class DetailsKey #:nodoc: <add> class DetailsKey # :nodoc: <ide> alias :eql? :equal? <ide> <ide> @details_keys = Concurrent::Map.new <ide> module DetailsCache <ide> <ide> # Calculate the details key. Remove the handlers from calculation to improve performance <ide> # since the user cannot modify it explicitly. <del> def details_key #:nodoc: <add> def details_key # :nodoc: <ide> @details_key ||= DetailsKey.details_cache_key(@details) if @cache <ide> end <ide> <ide><path>actionview/lib/action_view/model_naming.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionView <del> module ModelNaming #:nodoc: <add> module ModelNaming # :nodoc: <ide> # Converts the given object to an ActiveModel compliant one. <ide> def convert_to_model(object) <ide> object.respond_to?(:to_model) ? object.to_model : object <ide><path>actionview/lib/action_view/path_set.rb <ide> # frozen_string_literal: true <ide> <del>module ActionView #:nodoc: <add>module ActionView # :nodoc: <ide> # = Action View PathSet <ide> # <ide> # This class is used to store and access paths in Action View. A number of <ide> # operations are defined so that you can search among the paths in this <ide> # set and also perform operations on other +PathSet+ objects. <ide> # <ide> # A +LookupContext+ will use a +PathSet+ to store the paths in its context. <del> class PathSet #:nodoc: <add> class PathSet # :nodoc: <ide> include Enumerable <ide> <ide> attr_reader :paths <ide><path>actionview/lib/action_view/renderer/abstract_renderer.rb <ide> module ActionView <ide> # renderer object of the correct type is created, and the +render+ method on <ide> # that new object is called in turn. This abstracts the set up and rendering <ide> # into a separate classes for partials and templates. <del> class AbstractRenderer #:nodoc: <add> class AbstractRenderer # :nodoc: <ide> delegate :template_exists?, :any_templates?, :formats, to: :@lookup_context <ide> <ide> def initialize(lookup_context) <ide><path>actionview/lib/action_view/renderer/renderer.rb <ide> def render_body(context, options) <ide> end <ide> <ide> # Direct access to template rendering. <del> def render_template(context, options) #:nodoc: <add> def render_template(context, options) # :nodoc: <ide> render_template_to_object(context, options).body <ide> end <ide> <ide> # Direct access to partial rendering. <del> def render_partial(context, options, &block) #:nodoc: <add> def render_partial(context, options, &block) # :nodoc: <ide> render_partial_to_object(context, options, &block).body <ide> end <ide> <ide> def cache_hits # :nodoc: <ide> @cache_hits ||= {} <ide> end <ide> <del> def render_template_to_object(context, options) #:nodoc: <add> def render_template_to_object(context, options) # :nodoc: <ide> TemplateRenderer.new(@lookup_context).render(context, options) <ide> end <ide> <del> def render_partial_to_object(context, options, &block) #:nodoc: <add> def render_partial_to_object(context, options, &block) # :nodoc: <ide> partial = options[:partial] <ide> if String === partial <ide> collection = collection_from_options(options) <ide><path>actionview/lib/action_view/renderer/streaming_template_renderer.rb <ide> module ActionView <ide> # <ide> # * Support streaming from child templates, partials and so on. <ide> # * Rack::Cache needs to support streaming bodies <del> class StreamingTemplateRenderer < TemplateRenderer #:nodoc: <add> class StreamingTemplateRenderer < TemplateRenderer # :nodoc: <ide> # A valid Rack::Body (i.e. it responds to each). <ide> # It is initialized with a block that, when called, starts <ide> # rendering the template. <del> class Body #:nodoc: <add> class Body # :nodoc: <ide> def initialize(&start) <ide> @start = start <ide> end <ide> def log_error(exception) <ide> # For streaming, instead of rendering a given a template, we return a Body <ide> # object that responds to each. This object is initialized with a block <ide> # that knows how to render the template. <del> def render_template(view, template, layout_name = nil, locals = {}) #:nodoc: <add> def render_template(view, template, layout_name = nil, locals = {}) # :nodoc: <ide> return [super.body] unless layout_name && template.supports_streaming? <ide> <ide> locals ||= {} <ide><path>actionview/lib/action_view/renderer/template_renderer.rb <ide> # frozen_string_literal: true <ide> <ide> module ActionView <del> class TemplateRenderer < AbstractRenderer #:nodoc: <add> class TemplateRenderer < AbstractRenderer # :nodoc: <ide> def render(context, options) <ide> @details = extract_details(options) <ide> template = determine_template(options) <ide><path>actionview/lib/action_view/rendering.rb <ide> module ActionView <ide> # This is a class to fix I18n global state. Whenever you provide I18n.locale during a request, <ide> # it will trigger the lookup_context and consequently expire the cache. <del> class I18nProxy < ::I18n::Config #:nodoc: <add> class I18nProxy < ::I18n::Config # :nodoc: <ide> attr_reader :original_config, :lookup_context <ide> <ide> def initialize(original_config, lookup_context) <ide> def initialize <ide> end <ide> <ide> # Overwrite process to set up I18n proxy. <del> def process(*) #:nodoc: <add> def process(*) # :nodoc: <ide> old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context) <ide> super <ide> ensure <ide><path>actionview/lib/action_view/routing_url_for.rb <ide> def url_for(options = nil) <ide> end <ide> end <ide> <del> def url_options #:nodoc: <add> def url_options # :nodoc: <ide> return super unless controller.respond_to?(:url_options) <ide> controller.url_options <ide> end <ide><path>actionview/lib/action_view/template/error.rb <ide> <ide> module ActionView <ide> # = Action View Errors <del> class ActionViewError < StandardError #:nodoc: <add> class ActionViewError < StandardError # :nodoc: <ide> end <ide> <del> class EncodingError < StandardError #:nodoc: <add> class EncodingError < StandardError # :nodoc: <ide> end <ide> <del> class WrongEncodingError < EncodingError #:nodoc: <add> class WrongEncodingError < EncodingError # :nodoc: <ide> def initialize(string, encoding) <ide> @string, @encoding = string, encoding <ide> end <ide> def message <ide> end <ide> end <ide> <del> class MissingTemplate < ActionViewError #:nodoc: <add> class MissingTemplate < ActionViewError # :nodoc: <ide> attr_reader :path, :paths, :prefixes, :partial <ide> <ide> def initialize(paths, path, prefixes, partial, details, *) <ide> class Template <ide> # The Template::Error exception is raised when the compilation or rendering of the template <ide> # fails. This exception then gathers a bunch of intimate details and uses it to report a <ide> # precise exception message. <del> class Error < ActionViewError #:nodoc: <add> class Error < ActionViewError # :nodoc: <ide> SOURCE_CODE_RADIUS = 3 <ide> <ide> # Override to prevent #cause resetting during re-raise. <ide> def formatted_code_for(source_code, line_counter, indent) <ide> <ide> TemplateError = Template::Error <ide> <del> class SyntaxErrorInTemplate < TemplateError #:nodoc: <add> class SyntaxErrorInTemplate < TemplateError # :nodoc: <ide> def initialize(template, offending_code_string) <ide> @offending_code_string = offending_code_string <ide> super(template) <ide><path>actionview/lib/action_view/template/handlers.rb <ide> # frozen_string_literal: true <ide> <del>module ActionView #:nodoc: <add>module ActionView # :nodoc: <ide> # = Action View Template Handlers <del> class Template #:nodoc: <del> module Handlers #:nodoc: <add> class Template # :nodoc: <add> module Handlers # :nodoc: <ide> autoload :Raw, "action_view/template/handlers/raw" <ide> autoload :ERB, "action_view/template/handlers/erb" <ide> autoload :Html, "action_view/template/handlers/html" <ide><path>actionview/lib/action_view/template/html.rb <ide> # frozen_string_literal: true <ide> <del>module ActionView #:nodoc: <add>module ActionView # :nodoc: <ide> # = Action View HTML Template <del> class Template #:nodoc: <del> class HTML #:nodoc: <add> class Template # :nodoc: <add> class HTML # :nodoc: <ide> attr_reader :type <ide> <ide> def initialize(string, type) <ide><path>actionview/lib/action_view/template/inline.rb <ide> # frozen_string_literal: true <ide> <del>module ActionView #:nodoc: <del> class Template #:nodoc: <del> class Inline < Template #:nodoc: <add>module ActionView # :nodoc: <add> class Template # :nodoc: <add> class Inline < Template # :nodoc: <ide> # This finalizer is needed (and exactly with a proc inside another proc) <ide> # otherwise templates leak in development. <ide> Finalizer = proc do |method_name, mod| # :nodoc: <ide><path>actionview/lib/action_view/template/raw_file.rb <ide> # frozen_string_literal: true <ide> <del>module ActionView #:nodoc: <add>module ActionView # :nodoc: <ide> # = Action View RawFile Template <del> class Template #:nodoc: <del> class RawFile #:nodoc: <add> class Template # :nodoc: <add> class RawFile # :nodoc: <ide> attr_accessor :type, :format <ide> <ide> def initialize(filename) <ide><path>actionview/lib/action_view/template/resolver.rb <ide> def parse(path) <ide> end <ide> <ide> # Threadsafe template cache <del> class Cache #:nodoc: <add> class Cache # :nodoc: <ide> class SmallCache < Concurrent::Map <ide> def initialize(options = {}) <ide> super(options.merge(initial_capacity: 2)) <ide><path>actionview/lib/action_view/template/text.rb <ide> # frozen_string_literal: true <ide> <del>module ActionView #:nodoc: <add>module ActionView # :nodoc: <ide> # = Action View Text Template <del> class Template #:nodoc: <del> class Text #:nodoc: <add> class Template # :nodoc: <add> class Text # :nodoc: <ide> attr_accessor :type <ide> <ide> def initialize(string) <ide><path>actionview/lib/action_view/template/types.rb <ide> require "active_support/core_ext/module/attribute_accessors" <ide> <ide> module ActionView <del> class Template #:nodoc: <add> class Template # :nodoc: <ide> module Types <ide> class Type <ide> SET = Struct.new(:symbols).new([ :html, :text, :js, :css, :xml, :json ]) <ide><path>actionview/lib/action_view/testing/resolvers.rb <ide> <ide> require "action_view/template/resolver" <ide> <del>module ActionView #:nodoc: <add>module ActionView # :nodoc: <ide> # Use FixtureResolver in your tests to simulate the presence of files on the <ide> # file system. This is used internally by Rails' own test suite, and is <ide> # useful for testing extensions that have no way of knowing what the file <ide><path>activejob/lib/active_job/arguments.rb <ide> module ActiveJob <ide> # <ide> # Wraps the original exception raised as +cause+. <ide> class DeserializationError < StandardError <del> def initialize #:nodoc: <add> def initialize # :nodoc: <ide> super("Error while trying to deserialize arguments: #{$!.message}") <ide> set_backtrace $!.backtrace <ide> end <ide><path>activejob/lib/active_job/base.rb <ide> require "active_job/timezones" <ide> require "active_job/translation" <ide> <del>module ActiveJob #:nodoc: <add>module ActiveJob # :nodoc: <ide> # = Active Job <ide> # <ide> # Active Job objects can be configured to work with different backend <ide><path>activejob/lib/active_job/configured_job.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveJob <del> class ConfiguredJob #:nodoc: <add> class ConfiguredJob # :nodoc: <ide> def initialize(job_class, options = {}) <ide> @options = options <ide> @job_class = job_class <ide><path>activejob/lib/active_job/execution.rb <ide> def perform_now(...) <ide> job_or_instantiate(...).perform_now <ide> end <ide> <del> def execute(job_data) #:nodoc: <add> def execute(job_data) # :nodoc: <ide> ActiveJob::Callbacks.run_callbacks(:execute) do <ide> job = deserialize(job_data) <ide> job.perform_now <ide><path>activejob/lib/active_job/instrumentation.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveJob <del> module Instrumentation #:nodoc: <add> module Instrumentation # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>activejob/lib/active_job/log_subscriber.rb <ide> require "active_support/log_subscriber" <ide> <ide> module ActiveJob <del> class LogSubscriber < ActiveSupport::LogSubscriber #:nodoc: <add> class LogSubscriber < ActiveSupport::LogSubscriber # :nodoc: <ide> def enqueue(event) <ide> job = event.payload[:job] <ide> ex = event.payload[:exception_object] <ide><path>activejob/lib/active_job/logging.rb <ide> require "active_support/logger" <ide> <ide> module ActiveJob <del> module Logging #:nodoc: <add> module Logging # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>activejob/lib/active_job/queue_adapter.rb <ide> module ActiveJob <ide> # The <tt>ActiveJob::QueueAdapter</tt> module is used to load the <ide> # correct adapter. The default queue adapter is the +:async+ queue. <del> module QueueAdapter #:nodoc: <add> module QueueAdapter # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>activejob/lib/active_job/queue_adapters/async_adapter.rb <ide> def initialize(**executor_options) <ide> @scheduler = Scheduler.new(**executor_options) <ide> end <ide> <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> @scheduler.enqueue JobWrapper.new(job), queue_name: job.queue_name <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> @scheduler.enqueue_at JobWrapper.new(job), timestamp, queue_name: job.queue_name <ide> end <ide> <ide> # Gracefully stop processing jobs. Finishes in-progress work and handles <ide> # any new jobs following the executor's fallback policy (`caller_runs`). <ide> # Waits for termination by default. Pass `wait: false` to continue. <del> def shutdown(wait: true) #:nodoc: <add> def shutdown(wait: true) # :nodoc: <ide> @scheduler.shutdown wait: wait <ide> end <ide> <ide> # Used for our test suite. <del> def immediate=(immediate) #:nodoc: <add> def immediate=(immediate) # :nodoc: <ide> @scheduler.immediate = immediate <ide> end <ide> <ide> # Note that we don't actually need to serialize the jobs since we're <ide> # performing them in-process, but we do so anyway for parity with other <ide> # adapters and deployment environments. Otherwise, serialization bugs <ide> # may creep in undetected. <del> class JobWrapper #:nodoc: <add> class JobWrapper # :nodoc: <ide> def initialize(job) <ide> job.provider_job_id = SecureRandom.uuid <ide> @job_data = job.serialize <ide> def perform <ide> end <ide> end <ide> <del> class Scheduler #:nodoc: <add> class Scheduler # :nodoc: <ide> DEFAULT_EXECUTOR_OPTIONS = { <ide> min_threads: 0, <ide> max_threads: Concurrent.processor_count, <ide><path>activejob/lib/active_job/queue_adapters/backburner_adapter.rb <ide> module QueueAdapters <ide> # <ide> # Rails.application.config.active_job.queue_adapter = :backburner <ide> class BackburnerAdapter <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> Backburner::Worker.enqueue(JobWrapper, [job.serialize], queue: job.queue_name, pri: job.priority) <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> delay = timestamp - Time.current.to_f <ide> Backburner::Worker.enqueue(JobWrapper, [job.serialize], queue: job.queue_name, pri: job.priority, delay: delay) <ide> end <ide> <del> class JobWrapper #:nodoc: <add> class JobWrapper # :nodoc: <ide> class << self <ide> def perform(job_data) <ide> Base.execute job_data <ide><path>activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb <ide> module QueueAdapters <ide> # <ide> # Rails.application.config.active_job.queue_adapter = :delayed_job <ide> class DelayedJobAdapter <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> delayed_job = Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name, priority: job.priority) <ide> job.provider_job_id = delayed_job.id <ide> delayed_job <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> delayed_job = Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name, priority: job.priority, run_at: Time.at(timestamp)) <ide> job.provider_job_id = delayed_job.id <ide> delayed_job <ide> end <ide> <del> class JobWrapper #:nodoc: <add> class JobWrapper # :nodoc: <ide> attr_accessor :job_data <ide> <ide> def initialize(job_data) <ide><path>activejob/lib/active_job/queue_adapters/inline_adapter.rb <ide> module QueueAdapters <ide> # <ide> # Rails.application.config.active_job.queue_adapter = :inline <ide> class InlineAdapter <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> Base.execute(job.serialize) <ide> end <ide> <del> def enqueue_at(*) #:nodoc: <add> def enqueue_at(*) # :nodoc: <ide> raise NotImplementedError, "Use a queueing backend to enqueue jobs in the future. Read more at https://guides.rubyonrails.org/active_job_basics.html" <ide> end <ide> end <ide><path>activejob/lib/active_job/queue_adapters/que_adapter.rb <ide> module QueueAdapters <ide> # <ide> # Rails.application.config.active_job.queue_adapter = :que <ide> class QueAdapter <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> que_job = JobWrapper.enqueue job.serialize, priority: job.priority, queue: job.queue_name <ide> job.provider_job_id = que_job.attrs["job_id"] <ide> que_job <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> que_job = JobWrapper.enqueue job.serialize, priority: job.priority, queue: job.queue_name, run_at: Time.at(timestamp) <ide> job.provider_job_id = que_job.attrs["job_id"] <ide> que_job <ide> end <ide> <del> class JobWrapper < Que::Job #:nodoc: <add> class JobWrapper < Que::Job # :nodoc: <ide> def run(job_data) <ide> Base.execute job_data <ide> end <ide><path>activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb <ide> module QueueAdapters <ide> # <ide> # Rails.application.config.active_job.queue_adapter = :queue_classic <ide> class QueueClassicAdapter <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> qc_job = build_queue(job.queue_name).enqueue("#{JobWrapper.name}.perform", job.serialize) <ide> job.provider_job_id = qc_job["id"] if qc_job.is_a?(Hash) <ide> qc_job <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> queue = build_queue(job.queue_name) <ide> unless queue.respond_to?(:enqueue_at) <ide> raise NotImplementedError, "To be able to schedule jobs with queue_classic " \ <ide> def build_queue(queue_name) <ide> QC::Queue.new(queue_name) <ide> end <ide> <del> class JobWrapper #:nodoc: <add> class JobWrapper # :nodoc: <ide> class << self <ide> def perform(job_data) <ide> Base.execute job_data <ide><path>activejob/lib/active_job/queue_adapters/resque_adapter.rb <ide> module QueueAdapters <ide> # <ide> # Rails.application.config.active_job.queue_adapter = :resque <ide> class ResqueAdapter <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> JobWrapper.instance_variable_set(:@queue, job.queue_name) <ide> Resque.enqueue_to job.queue_name, JobWrapper, job.serialize <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> unless Resque.respond_to?(:enqueue_at_with_queue) <ide> raise NotImplementedError, "To be able to schedule jobs with Resque you need the " \ <ide> "resque-scheduler gem. Please add it to your Gemfile and run bundle install" <ide> end <ide> Resque.enqueue_at_with_queue job.queue_name, timestamp, JobWrapper, job.serialize <ide> end <ide> <del> class JobWrapper #:nodoc: <add> class JobWrapper # :nodoc: <ide> class << self <ide> def perform(job_data) <ide> Base.execute job_data <ide><path>activejob/lib/active_job/queue_adapters/sidekiq_adapter.rb <ide> module QueueAdapters <ide> # <ide> # Rails.application.config.active_job.queue_adapter = :sidekiq <ide> class SidekiqAdapter <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> # Sidekiq::Client does not support symbols as keys <ide> job.provider_job_id = Sidekiq::Client.push \ <ide> "class" => JobWrapper, <ide> def enqueue(job) #:nodoc: <ide> "args" => [ job.serialize ] <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> job.provider_job_id = Sidekiq::Client.push \ <ide> "class" => JobWrapper, <ide> "wrapped" => job.class, <ide> def enqueue_at(job, timestamp) #:nodoc: <ide> "at" => timestamp <ide> end <ide> <del> class JobWrapper #:nodoc: <add> class JobWrapper # :nodoc: <ide> include Sidekiq::Worker <ide> <ide> def perform(job_data) <ide><path>activejob/lib/active_job/queue_adapters/sneakers_adapter.rb <ide> def initialize <ide> @monitor = Monitor.new <ide> end <ide> <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> @monitor.synchronize do <ide> JobWrapper.from_queue job.queue_name <ide> JobWrapper.enqueue ActiveSupport::JSON.encode(job.serialize) <ide> end <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> raise NotImplementedError, "This queueing backend does not support scheduling jobs. To see what features are supported go to http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html" <ide> end <ide> <del> class JobWrapper #:nodoc: <add> class JobWrapper # :nodoc: <ide> include Sneakers::Worker <ide> from_queue "default" <ide> <ide><path>activejob/lib/active_job/queue_adapters/sucker_punch_adapter.rb <ide> module QueueAdapters <ide> # <ide> # Rails.application.config.active_job.queue_adapter = :sucker_punch <ide> class SuckerPunchAdapter <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> if JobWrapper.respond_to?(:perform_async) <ide> # sucker_punch 2.0 API <ide> JobWrapper.perform_async job.serialize <ide> def enqueue(job) #:nodoc: <ide> end <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> if JobWrapper.respond_to?(:perform_in) <ide> delay = timestamp - Time.current.to_f <ide> JobWrapper.perform_in delay, job.serialize <ide> def enqueue_at(job, timestamp) #:nodoc: <ide> end <ide> end <ide> <del> class JobWrapper #:nodoc: <add> class JobWrapper # :nodoc: <ide> include SuckerPunch::Job <ide> <ide> def perform(job_data) <ide><path>activejob/lib/active_job/queue_adapters/test_adapter.rb <ide> def performed_jobs <ide> @performed_jobs ||= [] <ide> end <ide> <del> def enqueue(job) #:nodoc: <add> def enqueue(job) # :nodoc: <ide> job_data = job_to_hash(job) <ide> perform_or_enqueue(perform_enqueued_jobs && !filtered?(job), job, job_data) <ide> end <ide> <del> def enqueue_at(job, timestamp) #:nodoc: <add> def enqueue_at(job, timestamp) # :nodoc: <ide> job_data = job_to_hash(job, at: timestamp) <ide> perform_or_enqueue(perform_enqueued_at_jobs && !filtered?(job), job, job_data) <ide> end <ide><path>activejob/lib/active_job/queue_name.rb <ide> def queue_as(part_name = nil, &block) <ide> end <ide> end <ide> <del> def queue_name_from_part(part_name) #:nodoc: <add> def queue_name_from_part(part_name) # :nodoc: <ide> queue_name = part_name || default_queue_name <ide> name_parts = [queue_name_prefix.presence, queue_name] <ide> -name_parts.compact.join(queue_name_delimiter) <ide><path>activejob/lib/active_job/timezones.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveJob <del> module Timezones #:nodoc: <add> module Timezones # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>activejob/lib/active_job/translation.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveJob <del> module Translation #:nodoc: <add> module Translation # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>activemodel/lib/active_model/attribute_methods.rb <ide> def define_proxy_call(code_generator, name, target, parameters, *call_args, name <ide> end <ide> end <ide> <del> class AttributeMethodMatcher #:nodoc: <add> class AttributeMethodMatcher # :nodoc: <ide> attr_reader :prefix, :suffix, :target, :parameters <ide> <ide> AttributeMethodMatch = Struct.new(:target, :attr_name) <ide><path>activemodel/lib/active_model/attributes.rb <ide> require "active_model/attribute/user_provided_default" <ide> <ide> module ActiveModel <del> module Attributes #:nodoc: <add> module Attributes # :nodoc: <ide> extend ActiveSupport::Concern <ide> include ActiveModel::AttributeMethods <ide> <ide><path>activemodel/lib/active_model/callbacks.rb <ide> module ActiveModel <ide> # NOTE: Calling the same callback multiple times will overwrite previous callback definitions. <ide> # <ide> module Callbacks <del> def self.extended(base) #:nodoc: <add> def self.extended(base) # :nodoc: <ide> base.class_eval do <ide> include ActiveSupport::Callbacks <ide> end <ide><path>activemodel/lib/active_model/conversion.rb <ide> def to_partial_path <ide> self.class._to_partial_path <ide> end <ide> <del> module ClassMethods #:nodoc: <add> module ClassMethods # :nodoc: <ide> # Provide a class level cache for #to_partial_path. This is an <ide> # internal method and should not be accessed directly. <del> def _to_partial_path #:nodoc: <add> def _to_partial_path # :nodoc: <ide> @_to_partial_path ||= begin <ide> element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(name)) <ide> collection = ActiveSupport::Inflector.tableize(name) <ide><path>activemodel/lib/active_model/naming.rb <ide> def _singularize(string) <ide> # is required to pass the \Active \Model Lint test. So either extending the <ide> # provided method below, or rolling your own is required. <ide> module Naming <del> def self.extended(base) #:nodoc: <add> def self.extended(base) # :nodoc: <ide> base.silence_redefinition_of_method :model_name <ide> base.delegate :model_name, to: :class <ide> end <ide> def self.param_key(record_or_class) <ide> model_name_from_record_or_class(record_or_class).param_key <ide> end <ide> <del> def self.model_name_from_record_or_class(record_or_class) #:nodoc: <add> def self.model_name_from_record_or_class(record_or_class) # :nodoc: <ide> if record_or_class.respond_to?(:to_model) <ide> record_or_class.to_model.model_name <ide> else <ide><path>activemodel/lib/active_model/serialization.rb <ide> def serializable_attributes(attribute_names) <ide> # +association+ - name of the association <ide> # +records+ - the association record(s) to be serialized <ide> # +opts+ - options for the association records <del> def serializable_add_includes(options = {}) #:nodoc: <add> def serializable_add_includes(options = {}) # :nodoc: <ide> return unless includes = options[:include] <ide> <ide> unless includes.is_a?(Hash) <ide><path>activemodel/lib/active_model/validations.rb <ide> def attribute_method?(attribute) <ide> end <ide> <ide> # Copy validators on inheritance. <del> def inherited(base) #:nodoc: <add> def inherited(base) # :nodoc: <ide> dup = _validators.dup <ide> base._validators = dup.each { |k, v| dup[k] = v.dup } <ide> super <ide> end <ide> end <ide> <ide> # Clean the +Errors+ object if instance is duped. <del> def initialize_dup(other) #:nodoc: <add> def initialize_dup(other) # :nodoc: <ide> @errors = nil <ide> super <ide> end <ide><path>activemodel/lib/active_model/validations/absence.rb <ide> module ActiveModel <ide> module Validations <ide> # == \Active \Model Absence Validator <del> class AbsenceValidator < EachValidator #:nodoc: <add> class AbsenceValidator < EachValidator # :nodoc: <ide> def validate_each(record, attr_name, value) <ide> record.errors.add(attr_name, :present, **options) if value.present? <ide> end <ide><path>activemodel/lib/active_model/validations/clusivity.rb <ide> <ide> module ActiveModel <ide> module Validations <del> module Clusivity #:nodoc: <add> module Clusivity # :nodoc: <ide> ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " \ <ide> "and must be supplied as the :in (or :within) option of the configuration hash" <ide> <ide><path>activemodel/lib/active_model/validations/comparability.rb <ide> <ide> module ActiveModel <ide> module Validations <del> module Comparability #:nodoc: <add> module Comparability # :nodoc: <ide> COMPARE_CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=, <ide> equal_to: :==, less_than: :<, less_than_or_equal_to: :<=, <ide> other_than: :!= }.freeze <ide><path>activemodel/lib/active_model/validator.rb <ide> def prepare_value_for_validation(value, record, attr_name) <ide> <ide> # +BlockValidator+ is a special +EachValidator+ which receives a block on initialization <ide> # and call this block for each attribute being validated. +validates_each+ uses this validator. <del> class BlockValidator < EachValidator #:nodoc: <add> class BlockValidator < EachValidator # :nodoc: <ide> def initialize(options, &block) <ide> @block = block <ide> super <ide><path>activerecord/lib/active_record/associations.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveRecord <del> class AssociationNotFoundError < ConfigurationError #:nodoc: <add> class AssociationNotFoundError < ConfigurationError # :nodoc: <ide> attr_reader :record, :association_name <ide> <ide> def initialize(record = nil, association_name = nil) <ide> def corrections <ide> end <ide> end <ide> <del> class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc: <add> class InverseOfAssociationNotFoundError < ActiveRecordError # :nodoc: <ide> attr_reader :reflection, :associated_class <ide> <ide> def initialize(reflection = nil, associated_class = nil) <ide> def corrections <ide> end <ide> end <ide> <del> class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc: <add> class HasManyThroughAssociationNotFoundError < ActiveRecordError # :nodoc: <ide> attr_reader :owner_class, :reflection <ide> <ide> def initialize(owner_class = nil, reflection = nil) <ide> def corrections <ide> end <ide> end <ide> <del> class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc: <add> class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError # :nodoc: <ide> def initialize(owner_class_name = nil, reflection = nil, source_reflection = nil) <ide> if owner_class_name && reflection && source_reflection <ide> super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}' without 'source_type'. Try adding 'source_type: \"#{reflection.name.to_s.classify}\"' to 'has_many :through' definition.") <ide> def initialize(owner_class_name = nil, reflection = nil, source_reflection = nil <ide> end <ide> end <ide> <del> class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc: <add> class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError # :nodoc: <ide> def initialize(owner_class_name = nil, reflection = nil) <ide> if owner_class_name && reflection <ide> super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.") <ide> def initialize(owner_class_name = nil, reflection = nil) <ide> end <ide> end <ide> <del> class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc: <add> class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError # :nodoc: <ide> def initialize(owner_class_name = nil, reflection = nil, source_reflection = nil) <ide> if owner_class_name && reflection && source_reflection <ide> super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.") <ide> def initialize(owner_class_name = nil, reflection = nil, source_reflection = nil <ide> end <ide> end <ide> <del> class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc: <add> class HasOneThroughCantAssociateThroughCollection < ActiveRecordError # :nodoc: <ide> def initialize(owner_class_name = nil, reflection = nil, through_reflection = nil) <ide> if owner_class_name && reflection && through_reflection <ide> super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.") <ide> def initialize(owner_class_name = nil, reflection = nil, through_reflection = ni <ide> end <ide> end <ide> <del> class HasOneAssociationPolymorphicThroughError < ActiveRecordError #:nodoc: <add> class HasOneAssociationPolymorphicThroughError < ActiveRecordError # :nodoc: <ide> def initialize(owner_class_name = nil, reflection = nil) <ide> if owner_class_name && reflection <ide> super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.") <ide> def initialize(owner_class_name = nil, reflection = nil) <ide> end <ide> end <ide> <del> class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc: <add> class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError # :nodoc: <ide> def initialize(reflection = nil) <ide> if reflection <ide> through_reflection = reflection.through_reflection <ide> def initialize(reflection = nil) <ide> end <ide> end <ide> <del> class HasManyThroughOrderError < ActiveRecordError #:nodoc: <add> class HasManyThroughOrderError < ActiveRecordError # :nodoc: <ide> def initialize(owner_class_name = nil, reflection = nil, through_reflection = nil) <ide> if owner_class_name && reflection && through_reflection <ide> super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through '#{owner_class_name}##{through_reflection.name}' before the through association is defined.") <ide> def initialize(owner_class_name = nil, reflection = nil, through_reflection = ni <ide> end <ide> end <ide> <del> class ThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc: <add> class ThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError # :nodoc: <ide> def initialize(owner = nil, reflection = nil) <ide> if owner && reflection <ide> super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.") <ide> def initialize(klass, macro, association_name, options, possible_sources) <ide> end <ide> end <ide> <del> class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc: <add> class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection # :nodoc: <ide> end <ide> <del> class HasOneThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc: <add> class HasOneThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection # :nodoc: <ide> end <ide> <del> class ThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc: <add> class ThroughNestedAssociationsAreReadonly < ActiveRecordError # :nodoc: <ide> def initialize(owner = nil, reflection = nil) <ide> if owner && reflection <ide> super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.") <ide> def initialize(owner = nil, reflection = nil) <ide> end <ide> end <ide> <del> class HasManyThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly #:nodoc: <add> class HasManyThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly # :nodoc: <ide> end <ide> <del> class HasOneThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly #:nodoc: <add> class HasOneThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly # :nodoc: <ide> end <ide> <ide> # This error is raised when trying to eager load a polymorphic association using a JOIN. <ide> def initialize(reflection = nil) <ide> # This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations <ide> # (has_many, has_one) when there is at least 1 child associated instance. <ide> # ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project <del> class DeleteRestrictionError < ActiveRecordError #:nodoc: <add> class DeleteRestrictionError < ActiveRecordError # :nodoc: <ide> def initialize(name = nil) <ide> if name <ide> super("Cannot delete record because of dependent #{name}") <ide> module Associations # :nodoc: <ide> autoload :CollectionProxy <ide> autoload :ThroughAssociation <ide> <del> module Builder #:nodoc: <add> module Builder # :nodoc: <ide> autoload :Association, "active_record/associations/builder/association" <ide> autoload :SingularAssociation, "active_record/associations/builder/singular_association" <ide> autoload :CollectionAssociation, "active_record/associations/builder/collection_association" <ide> def self.eager_load! <ide> end <ide> <ide> # Returns the association instance for the given name, instantiating it if it doesn't already exist <del> def association(name) #:nodoc: <add> def association(name) # :nodoc: <ide> association = association_instance_get(name) <ide> <ide> if association.nil? <ide><path>activerecord/lib/active_record/associations/association.rb <ide> module Associations <ide> # The association of <tt>blog.posts</tt> has the object +blog+ as its <ide> # <tt>owner</tt>, the collection of its posts as <tt>target</tt>, and <ide> # the <tt>reflection</tt> object represents a <tt>:has_many</tt> macro. <del> class Association #:nodoc: <add> class Association # :nodoc: <ide> attr_reader :owner, :target, :reflection, :disable_joins <ide> <ide> delegate :options, to: :reflection <ide> def marshal_load(data) <ide> @reflection = @owner.class._reflect_on_association(reflection_name) <ide> end <ide> <del> def initialize_attributes(record, except_from_scope_attributes = nil) #:nodoc: <add> def initialize_attributes(record, except_from_scope_attributes = nil) # :nodoc: <ide> except_from_scope_attributes ||= {} <ide> skip_assign = [reflection.foreign_key, reflection.type].compact <ide> assigned_keys = record.changed_attribute_names_to_save <ide><path>activerecord/lib/active_record/associations/association_scope.rb <ide> <ide> module ActiveRecord <ide> module Associations <del> class AssociationScope #:nodoc: <add> class AssociationScope # :nodoc: <ide> def self.scope(association) <ide> INSTANCE.scope(association) <ide> end <ide><path>activerecord/lib/active_record/associations/belongs_to_association.rb <ide> module ActiveRecord <ide> module Associations <ide> # = Active Record Belongs To Association <del> class BelongsToAssociation < SingularAssociation #:nodoc: <add> class BelongsToAssociation < SingularAssociation # :nodoc: <ide> def handle_dependency <ide> return unless load_target <ide> <ide><path>activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb <ide> module ActiveRecord <ide> module Associations <ide> # = Active Record Belongs To Polymorphic Association <del> class BelongsToPolymorphicAssociation < BelongsToAssociation #:nodoc: <add> class BelongsToPolymorphicAssociation < BelongsToAssociation # :nodoc: <ide> def klass <ide> type = owner[reflection.foreign_type] <ide> type.presence && owner.class.polymorphic_class_for(type) <ide><path>activerecord/lib/active_record/associations/builder/association.rb <ide> # - HasManyAssociation <ide> <ide> module ActiveRecord::Associations::Builder # :nodoc: <del> class Association #:nodoc: <add> class Association # :nodoc: <ide> class << self <ide> attr_accessor :extensions <ide> end <ide><path>activerecord/lib/active_record/associations/builder/belongs_to.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveRecord::Associations::Builder # :nodoc: <del> class BelongsTo < SingularAssociation #:nodoc: <add> class BelongsTo < SingularAssociation # :nodoc: <ide> def self.macro <ide> :belongs_to <ide> end <ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb <ide> require "active_record/associations" <ide> <ide> module ActiveRecord::Associations::Builder # :nodoc: <del> class CollectionAssociation < Association #:nodoc: <add> class CollectionAssociation < Association # :nodoc: <ide> CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove] <ide> <ide> def self.valid_options(options) <ide><path>activerecord/lib/active_record/associations/builder/has_many.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveRecord::Associations::Builder # :nodoc: <del> class HasMany < CollectionAssociation #:nodoc: <add> class HasMany < CollectionAssociation # :nodoc: <ide> def self.macro <ide> :has_many <ide> end <ide><path>activerecord/lib/active_record/associations/builder/has_one.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveRecord::Associations::Builder # :nodoc: <del> class HasOne < SingularAssociation #:nodoc: <add> class HasOne < SingularAssociation # :nodoc: <ide> def self.macro <ide> :has_one <ide> end <ide><path>activerecord/lib/active_record/associations/builder/singular_association.rb <ide> # This class is inherited by the has_one and belongs_to association classes <ide> <ide> module ActiveRecord::Associations::Builder # :nodoc: <del> class SingularAssociation < Association #:nodoc: <add> class SingularAssociation < Association # :nodoc: <ide> def self.valid_options(options) <ide> super + [:required, :touch] <ide> end <ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> module Associations <ide> # <ide> # If you need to work on all current children, new and existing records, <ide> # +load_target+ and the +loaded+ flag are your friends. <del> class CollectionAssociation < Association #:nodoc: <add> class CollectionAssociation < Association # :nodoc: <ide> # Implements the reader method, e.g. foo.items for Foo.has_many :items <ide> def reader <ide> ensure_klass_exists! <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb <ide> module Associations <ide> # is computed directly through SQL and does not trigger by itself the <ide> # instantiation of the actual post records. <ide> class CollectionProxy < Relation <del> def initialize(klass, association, **) #:nodoc: <add> def initialize(klass, association, **) # :nodoc: <ide> @association = association <ide> super klass <ide> <ide><path>activerecord/lib/active_record/associations/has_many_association.rb <ide> module Associations <ide> # <ide> # If the association has a <tt>:through</tt> option further specialization <ide> # is provided by its child HasManyThroughAssociation. <del> class HasManyAssociation < CollectionAssociation #:nodoc: <add> class HasManyAssociation < CollectionAssociation # :nodoc: <ide> include ForeignAssociation <ide> <ide> def handle_dependency <ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb <ide> module ActiveRecord <ide> module Associations <ide> # = Active Record Has Many Through Association <del> class HasManyThroughAssociation < HasManyAssociation #:nodoc: <add> class HasManyThroughAssociation < HasManyAssociation # :nodoc: <ide> include ThroughAssociation <ide> <ide> def initialize(owner, reflection) <ide><path>activerecord/lib/active_record/associations/has_one_association.rb <ide> module ActiveRecord <ide> module Associations <ide> # = Active Record Has One Association <del> class HasOneAssociation < SingularAssociation #:nodoc: <add> class HasOneAssociation < SingularAssociation # :nodoc: <ide> include ForeignAssociation <ide> <ide> def handle_dependency <ide><path>activerecord/lib/active_record/associations/has_one_through_association.rb <ide> module ActiveRecord <ide> module Associations <ide> # = Active Record Has One Through Association <del> class HasOneThroughAssociation < HasOneAssociation #:nodoc: <add> class HasOneThroughAssociation < HasOneAssociation # :nodoc: <ide> include ThroughAssociation <ide> <ide> private <ide><path>activerecord/lib/active_record/associations/preloader.rb <ide> module Associations <ide> # <ide> # This could result in many rows that contain redundant data and it performs poorly at scale <ide> # and is therefore only used when necessary. <del> class Preloader #:nodoc: <add> class Preloader # :nodoc: <ide> extend ActiveSupport::Autoload <ide> <ide> eager_autoload do <ide><path>activerecord/lib/active_record/associations/preloader/association.rb <ide> module ActiveRecord <ide> module Associations <ide> class Preloader <del> class Association #:nodoc: <add> class Association # :nodoc: <ide> class LoaderQuery <ide> attr_reader :scope, :association_key_name <ide> <ide><path>activerecord/lib/active_record/associations/preloader/batch.rb <ide> module ActiveRecord <ide> module Associations <ide> class Preloader <del> class Batch #:nodoc: <add> class Batch # :nodoc: <ide> def initialize(preloaders, available_records:) <ide> @preloaders = preloaders.reject(&:empty?) <ide> @available_records = available_records.flatten.group_by(&:class) <ide><path>activerecord/lib/active_record/associations/preloader/branch.rb <ide> module ActiveRecord <ide> module Associations <ide> class Preloader <del> class Branch #:nodoc: <add> class Branch # :nodoc: <ide> attr_reader :association, :children, :parent <ide> attr_reader :scope, :associate_by_default <ide> attr_writer :preloaded_records <ide><path>activerecord/lib/active_record/associations/singular_association.rb <ide> <ide> module ActiveRecord <ide> module Associations <del> class SingularAssociation < Association #:nodoc: <add> class SingularAssociation < Association # :nodoc: <ide> # Implements the reader method, e.g. foo.bar for Foo.has_one :bar <ide> def reader <ide> ensure_klass_exists! <ide><path>activerecord/lib/active_record/associations/through_association.rb <ide> module ActiveRecord <ide> module Associations <ide> # = Active Record Through Association <del> module ThroughAssociation #:nodoc: <add> module ThroughAssociation # :nodoc: <ide> delegate :source_reflection, to: :reflection <ide> <ide> private <ide><path>activerecord/lib/active_record/attribute_methods.rb <ide> module AttributeMethods <ide> <ide> RESTRICTED_CLASS_METHODS = %w(private public protected allocate new name parent superclass) <ide> <del> class GeneratedAttributeMethods < Module #:nodoc: <add> class GeneratedAttributeMethods < Module # :nodoc: <ide> include Mutex_m <ide> end <ide> <ide> def dangerous_attribute_methods # :nodoc: <ide> end <ide> <ide> module ClassMethods <del> def inherited(child_class) #:nodoc: <add> def inherited(child_class) # :nodoc: <ide> child_class.initialize_generated_modules <ide> super <ide> end <ide><path>activerecord/lib/active_record/attribute_methods/primary_key.rb <ide> def quoted_primary_key <ide> @quoted_primary_key ||= connection.quote_column_name(primary_key) <ide> end <ide> <del> def reset_primary_key #:nodoc: <add> def reset_primary_key # :nodoc: <ide> if base_class? <ide> self.primary_key = get_primary_key(base_class.name) <ide> else <ide> self.primary_key = base_class.primary_key <ide> end <ide> end <ide> <del> def get_primary_key(base_name) #:nodoc: <add> def get_primary_key(base_name) # :nodoc: <ide> if base_name && primary_key_prefix_type == :table_name <ide> base_name.foreign_key(false) <ide> elsif base_name && primary_key_prefix_type == :table_name_with_underscore <ide><path>activerecord/lib/active_record/autosave_association.rb <ide> module ActiveRecord <ide> module AutosaveAssociation <ide> extend ActiveSupport::Concern <ide> <del> module AssociationBuilderExtension #:nodoc: <add> module AssociationBuilderExtension # :nodoc: <ide> def self.build(model, reflection) <ide> model.send(:add_autosave_association_callbacks, reflection) <ide> end <ide><path>activerecord/lib/active_record/base.rb <ide> require "active_record/type_caster" <ide> require "active_record/database_configurations" <ide> <del>module ActiveRecord #:nodoc: <add>module ActiveRecord # :nodoc: <ide> # = Active Record <ide> # <ide> # Active Record objects don't specify their attributes directly, but rather infer them from <ide><path>activerecord/lib/active_record/callbacks.rb <ide> module ClassMethods <ide> define_model_callbacks :save, :create, :update, :destroy <ide> end <ide> <del> def destroy #:nodoc: <add> def destroy # :nodoc: <ide> @_destroy_callback_already_called ||= false <ide> return if @_destroy_callback_already_called <ide> @_destroy_callback_already_called = true <ide> def destroy #:nodoc: <ide> @_destroy_callback_already_called = false <ide> end <ide> <del> def touch(*, **) #:nodoc: <add> def touch(*, **) # :nodoc: <ide> _run_touch_callbacks { super } <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def transaction(requires_new: nil, isolation: nil, joinable: true) <ide> # rollbacks are silently swallowed <ide> end <ide> <del> attr_reader :transaction_manager #:nodoc: <add> attr_reader :transaction_manager # :nodoc: <ide> <ide> delegate :within_new_transaction, :open_transactions, :current_transaction, :begin_transaction, <ide> :commit_transaction, :rollback_transaction, :materialize_transactions, <ide> def transaction_open? <ide> current_transaction.open? <ide> end <ide> <del> def reset_transaction #:nodoc: <add> def reset_transaction # :nodoc: <ide> @transaction_manager = ConnectionAdapters::TransactionManager.new(self) <ide> end <ide> <ide> def rollback_db_transaction <ide> exec_rollback_db_transaction <ide> end <ide> <del> def exec_rollback_db_transaction() end #:nodoc: <add> def exec_rollback_db_transaction() end # :nodoc: <ide> <ide> def rollback_to_savepoint(name = nil) <ide> exec_rollback_to_savepoint(name) <ide><path>activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb <ide> module ActiveRecord <ide> module ConnectionAdapters # :nodoc: <ide> module QueryCache <ide> class << self <del> def included(base) #:nodoc: <add> def included(base) # :nodoc: <ide> dirties_query_cache base, :create, :insert, :update, :delete, :truncate, :truncate_tables, <ide> :rollback_to_savepoint, :rollback_db_transaction, :exec_insert_all <ide> <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveRecord <del> module ConnectionAdapters #:nodoc: <add> module ConnectionAdapters # :nodoc: <ide> # Abstract representation of an index definition on a table. Instances of <ide> # this type are typically created and returned by methods in database <ide> # adapters. e.g. ActiveRecord::ConnectionAdapters::MySQL::SchemaStatements#indexes <ide> def aliased_types(name, fallback) <ide> <ide> AddColumnDefinition = Struct.new(:column) # :nodoc: <ide> <del> ChangeColumnDefinition = Struct.new(:column, :name) #:nodoc: <add> ChangeColumnDefinition = Struct.new(:column, :name) # :nodoc: <ide> <ide> CreateIndexDefinition = Struct.new(:index, :algorithm, :if_not_exists) # :nodoc: <ide> <ide> PrimaryKeyDefinition = Struct.new(:name) # :nodoc: <ide> <del> ForeignKeyDefinition = Struct.new(:from_table, :to_table, :options) do #:nodoc: <add> ForeignKeyDefinition = Struct.new(:from_table, :to_table, :options) do # :nodoc: <ide> def name <ide> options[:name] <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def rename_index(table_name, old_name, new_name) <ide> remove_index(table_name, name: old_name) <ide> end <ide> <del> def index_name(table_name, options) #:nodoc: <add> def index_name(table_name, options) # :nodoc: <ide> if Hash === options <ide> if options[:column] <ide> "index_#{table_name}_on_#{Array(options[:column]) * '_and_'}" <ide> def remove_timestamps(table_name, **options) <ide> remove_columns table_name, :updated_at, :created_at <ide> end <ide> <del> def update_table_definition(table_name, base) #:nodoc: <add> def update_table_definition(table_name, base) # :nodoc: <ide> Table.new(table_name, base) <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/abstract/transaction.rb <ide> def nullify! <ide> end <ide> end <ide> <del> class NullTransaction #:nodoc: <add> class NullTransaction # :nodoc: <ide> def initialize; end <ide> def state; end <ide> def closed?; true; end <ide> def joinable?; false; end <ide> def add_record(record, _ = true); end <ide> end <ide> <del> class Transaction #:nodoc: <add> class Transaction # :nodoc: <ide> attr_reader :connection, :state, :savepoint_name, :isolation_level <ide> attr_accessor :written <ide> <ide> def commit <ide> end <ide> end <ide> <del> class TransactionManager #:nodoc: <add> class TransactionManager # :nodoc: <ide> def initialize(connection) <ide> @stack = [] <ide> @connection = connection <ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def initialize(connection, logger, connection_options, config) <ide> super(connection, logger, config) <ide> end <ide> <del> def get_database_version #:nodoc: <add> def get_database_version # :nodoc: <ide> full_version_string = get_full_version <ide> version_string = version_string(full_version_string) <ide> Version.new(version_string, full_version_string) <ide> def error_number(exception) # :nodoc: <ide> <ide> # REFERENTIAL INTEGRITY ==================================== <ide> <del> def disable_referential_integrity #:nodoc: <add> def disable_referential_integrity # :nodoc: <ide> old = query_value("SELECT @@FOREIGN_KEY_CHECKS") <ide> <ide> begin <ide> def create_database(name, options = {}) <ide> # <ide> # Example: <ide> # drop_database('sebastian_development') <del> def drop_database(name) #:nodoc: <add> def drop_database(name) # :nodoc: <ide> execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}" <ide> end <ide> <ide> def rename_index(table_name, old_name, new_name) <ide> end <ide> end <ide> <del> def change_column_default(table_name, column_name, default_or_changes) #:nodoc: <add> def change_column_default(table_name, column_name, default_or_changes) # :nodoc: <ide> default = extract_new_default_value(default_or_changes) <ide> change_column table_name, column_name, nil, default: default <ide> end <ide> <del> def change_column_null(table_name, column_name, null, default = nil) #:nodoc: <add> def change_column_null(table_name, column_name, null, default = nil) # :nodoc: <ide> unless null || default.nil? <ide> execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") <ide> end <ide> def change_column_comment(table_name, column_name, comment_or_changes) # :nodoc: <ide> change_column table_name, column_name, nil, comment: comment <ide> end <ide> <del> def change_column(table_name, column_name, type, **options) #:nodoc: <add> def change_column(table_name, column_name, type, **options) # :nodoc: <ide> execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_for_alter(table_name, column_name, type, **options)}") <ide> end <ide> <del> def rename_column(table_name, column_name, new_column_name) #:nodoc: <add> def rename_column(table_name, column_name, new_column_name) # :nodoc: <ide> execute("ALTER TABLE #{quote_table_name(table_name)} #{rename_column_for_alter(table_name, column_name, new_column_name)}") <ide> rename_column_indexes(table_name, column_name, new_column_name) <ide> end <ide> <del> def add_index(table_name, column_name, **options) #:nodoc: <add> def add_index(table_name, column_name, **options) # :nodoc: <ide> index, algorithm, if_not_exists = add_index_options(table_name, column_name, **options) <ide> <ide> return if if_not_exists && index_exists?(table_name, column_name, name: index.name) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb <ide> def explain(arel, binds = []) <ide> end <ide> <ide> # Queries the database and returns the results in an Array-like object <del> def query(sql, name = nil) #:nodoc: <add> def query(sql, name = nil) # :nodoc: <ide> materialize_transactions <ide> mark_transaction_written_if_write(sql) <ide> <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb <ide> def unescape_bytea(value) <ide> end <ide> <ide> # Quotes strings for use in SQL input. <del> def quote_string(s) #:nodoc: <add> def quote_string(s) # :nodoc: <ide> PG::Connection.escape(s) <ide> end <ide> <ide> def quote_column_name(name) # :nodoc: <ide> end <ide> <ide> # Quote date/time values for use in SQL input. <del> def quoted_date(value) #:nodoc: <add> def quoted_date(value) # :nodoc: <ide> if value.year <= 0 <ide> bce_year = format("%04d", -value.year + 1) <ide> super.sub(/^-?\d+/, bce_year) + " BC" <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb <ide> module PostgreSQL <ide> module SchemaStatements <ide> # Drops the database specified on the +name+ attribute <ide> # and creates it again using the provided +options+. <del> def recreate_database(name, options = {}) #:nodoc: <add> def recreate_database(name, options = {}) # :nodoc: <ide> drop_database(name) <ide> create_database(name, options) <ide> end <ide> def create_database(name, options = {}) <ide> # <ide> # Example: <ide> # drop_database 'matt_development' <del> def drop_database(name) #:nodoc: <add> def drop_database(name) # :nodoc: <ide> execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}" <ide> end <ide> <ide> def client_min_messages=(level) <ide> end <ide> <ide> # Returns the sequence name for a table's primary key or some other specified key. <del> def default_sequence_name(table_name, pk = "id") #:nodoc: <add> def default_sequence_name(table_name, pk = "id") # :nodoc: <ide> result = serial_sequence(table_name, pk) <ide> return nil unless result <ide> Utils.extract_schema_qualified_name(result).to_s <ide> def serial_sequence(table, column) <ide> end <ide> <ide> # Sets the sequence of a table's primary key to the specified value. <del> def set_pk_sequence!(table, value) #:nodoc: <add> def set_pk_sequence!(table, value) # :nodoc: <ide> pk, sequence = pk_and_sequence_for(table) <ide> <ide> if pk <ide> def set_pk_sequence!(table, value) #:nodoc: <ide> end <ide> <ide> # Resets the sequence of a table's primary key to the maximum value. <del> def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc: <add> def reset_pk_sequence!(table, pk = nil, sequence = nil) # :nodoc: <ide> unless pk && sequence <ide> default_pk, default_sequence = pk_and_sequence_for(table) <ide> <ide> def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc: <ide> end <ide> <ide> # Returns a table's primary key and belonging sequence. <del> def pk_and_sequence_for(table) #:nodoc: <add> def pk_and_sequence_for(table) # :nodoc: <ide> # First try looking for a sequence with a dependency on the <ide> # given table's primary key. <ide> result = query(<<~SQL, "SCHEMA")[0] <ide> def rename_table(table_name, new_name) <ide> rename_table_indexes(table_name, new_name) <ide> end <ide> <del> def add_column(table_name, column_name, type, **options) #:nodoc: <add> def add_column(table_name, column_name, type, **options) # :nodoc: <ide> clear_cache! <ide> super <ide> change_column_comment(table_name, column_name, options[:comment]) if options.key?(:comment) <ide> end <ide> <del> def change_column(table_name, column_name, type, **options) #:nodoc: <add> def change_column(table_name, column_name, type, **options) # :nodoc: <ide> clear_cache! <ide> sqls, procs = Array(change_column_for_alter(table_name, column_name, type, **options)).partition { |v| v.is_a?(String) } <ide> execute "ALTER TABLE #{quote_table_name(table_name)} #{sqls.join(", ")}" <ide> def change_column_default(table_name, column_name, default_or_changes) # :nodoc: <ide> execute "ALTER TABLE #{quote_table_name(table_name)} #{change_column_default_for_alter(table_name, column_name, default_or_changes)}" <ide> end <ide> <del> def change_column_null(table_name, column_name, null, default = nil) #:nodoc: <add> def change_column_null(table_name, column_name, null, default = nil) # :nodoc: <ide> clear_cache! <ide> unless null || default.nil? <ide> column = column_for(table_name, column_name) <ide> def change_table_comment(table_name, comment_or_changes) # :nodoc: <ide> end <ide> <ide> # Renames a column in a table. <del> def rename_column(table_name, column_name, new_column_name) #:nodoc: <add> def rename_column(table_name, column_name, new_column_name) # :nodoc: <ide> clear_cache! <ide> execute("ALTER TABLE #{quote_table_name(table_name)} #{rename_column_sql(table_name, column_name, new_column_name)}") <ide> rename_column_indexes(table_name, column_name, new_column_name) <ide> end <ide> <del> def add_index(table_name, column_name, **options) #:nodoc: <add> def add_index(table_name, column_name, **options) # :nodoc: <ide> index, algorithm, if_not_exists = add_index_options(table_name, column_name, **options) <ide> <ide> create_index = CreateIndexDefinition.new(index, algorithm, if_not_exists) <ide> def type_to_sql(type, limit: nil, precision: nil, scale: nil, array: nil, **) # <ide> <ide> # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and <ide> # requires that the ORDER BY include the distinct column. <del> def columns_for_distinct(columns, orders) #:nodoc: <add> def columns_for_distinct(columns, orders) # :nodoc: <ide> order_columns = orders.compact_blank.map { |s| <ide> # Convert Arel node to string <ide> s = visitor.compile(s) unless s.is_a?(String) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def new_client(conn_params) <ide> oid: { name: "oid" }, <ide> } <ide> <del> OID = PostgreSQL::OID #:nodoc: <add> OID = PostgreSQL::OID # :nodoc: <ide> <ide> include PostgreSQL::Quoting <ide> include PostgreSQL::ReferentialIntegrity <ide> def discard! # :nodoc: <ide> @connection = nil <ide> end <ide> <del> def native_database_types #:nodoc: <add> def native_database_types # :nodoc: <ide> self.class.native_database_types <ide> end <ide> <del> def self.native_database_types #:nodoc: <add> def self.native_database_types # :nodoc: <ide> @native_database_types ||= begin <ide> types = NATIVE_DATABASE_TYPES.dup <ide> types[:datetime] = types[datetime_type] <ide> def load_types_queries(initializer, oids) <ide> end <ide> end <ide> <del> FEATURE_NOT_SUPPORTED = "0A000" #:nodoc: <add> FEATURE_NOT_SUPPORTED = "0A000" # :nodoc: <ide> <ide> def execute_and_clear(sql, name, binds, prepare: false, async: false) <ide> check_if_write_query(sql) <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3/database_statements.rb <ide> def explain(arel, binds = []) <ide> SQLite3::ExplainPrettyPrinter.new.pp(exec_query(sql, "EXPLAIN", [])) <ide> end <ide> <del> def execute(sql, name = nil) #:nodoc: <add> def execute(sql, name = nil) # :nodoc: <ide> check_if_write_query(sql) <ide> <ide> materialize_transactions <ide> def execute(sql, name = nil) #:nodoc: <ide> end <ide> end <ide> <del> def exec_query(sql, name = nil, binds = [], prepare: false, async: false) #:nodoc: <add> def exec_query(sql, name = nil, binds = [], prepare: false, async: false) # :nodoc: <ide> check_if_write_query(sql) <ide> <ide> materialize_transactions <ide> def exec_query(sql, name = nil, binds = [], prepare: false, async: false) #:nodo <ide> end <ide> end <ide> <del> def exec_delete(sql, name = "SQL", binds = []) #:nodoc: <add> def exec_delete(sql, name = "SQL", binds = []) # :nodoc: <ide> exec_query(sql, name, binds) <ide> @connection.changes <ide> end <ide> alias :exec_update :exec_delete <ide> <del> def begin_isolated_db_transaction(isolation) #:nodoc: <add> def begin_isolated_db_transaction(isolation) # :nodoc: <ide> raise TransactionIsolationError, "SQLite3 only supports the `read_uncommitted` transaction isolation level" if isolation != :read_uncommitted <ide> raise StandardError, "You need to enable the shared-cache mode in SQLite mode before attempting to change the transaction isolation level" unless shared_cache? <ide> <ide> def begin_isolated_db_transaction(isolation) #:nodoc: <ide> begin_db_transaction <ide> end <ide> <del> def begin_db_transaction #:nodoc: <add> def begin_db_transaction # :nodoc: <ide> log("begin transaction", "TRANSACTION") { @connection.transaction } <ide> end <ide> <del> def commit_db_transaction #:nodoc: <add> def commit_db_transaction # :nodoc: <ide> log("commit transaction", "TRANSACTION") { @connection.commit } <ide> reset_read_uncommitted <ide> end <ide> <del> def exec_rollback_db_transaction #:nodoc: <add> def exec_rollback_db_transaction # :nodoc: <ide> log("rollback transaction", "TRANSACTION") { @connection.rollback } <ide> reset_read_uncommitted <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def sqlite3_connection(config) <ide> end <ide> end <ide> <del> module ConnectionAdapters #:nodoc: <add> module ConnectionAdapters # :nodoc: <ide> # The SQLite3 adapter works with the sqlite3-ruby drivers <ide> # (available as gem from https://rubygems.org/gems/sqlite3). <ide> # <ide> def supports_index_sort_order? <ide> true <ide> end <ide> <del> def native_database_types #:nodoc: <add> def native_database_types # :nodoc: <ide> NATIVE_DATABASE_TYPES <ide> end <ide> <ide> def rename_table(table_name, new_name) <ide> rename_table_indexes(table_name, new_name) <ide> end <ide> <del> def add_column(table_name, column_name, type, **options) #:nodoc: <add> def add_column(table_name, column_name, type, **options) # :nodoc: <ide> if invalid_alter_table_type?(type, options) <ide> alter_table(table_name) do |definition| <ide> definition.column(column_name, type, **options) <ide> def add_column(table_name, column_name, type, **options) #:nodoc: <ide> end <ide> end <ide> <del> def remove_column(table_name, column_name, type = nil, **options) #:nodoc: <add> def remove_column(table_name, column_name, type = nil, **options) # :nodoc: <ide> alter_table(table_name) do |definition| <ide> definition.remove_column column_name <ide> definition.foreign_keys.delete_if { |fk| fk.column == column_name.to_s } <ide> def remove_columns(table_name, *column_names, type: nil, **options) # :nodoc: <ide> end <ide> end <ide> <del> def change_column_default(table_name, column_name, default_or_changes) #:nodoc: <add> def change_column_default(table_name, column_name, default_or_changes) # :nodoc: <ide> default = extract_new_default_value(default_or_changes) <ide> <ide> alter_table(table_name) do |definition| <ide> definition[column_name].default = default <ide> end <ide> end <ide> <del> def change_column_null(table_name, column_name, null, default = nil) #:nodoc: <add> def change_column_null(table_name, column_name, null, default = nil) # :nodoc: <ide> unless null || default.nil? <ide> exec_query("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") <ide> end <ide> def change_column_null(table_name, column_name, null, default = nil) #:nodoc: <ide> end <ide> end <ide> <del> def change_column(table_name, column_name, type, **options) #:nodoc: <add> def change_column(table_name, column_name, type, **options) # :nodoc: <ide> alter_table(table_name) do |definition| <ide> definition[column_name].instance_eval do <ide> self.type = aliased_types(type.to_s, type) <ide> def change_column(table_name, column_name, type, **options) #:nodoc: <ide> end <ide> end <ide> <del> def rename_column(table_name, column_name, new_column_name) #:nodoc: <add> def rename_column(table_name, column_name, new_column_name) # :nodoc: <ide> column = column_for(table_name, column_name) <ide> alter_table(table_name, rename: { column.name => new_column_name.to_s }) <ide> rename_column_indexes(table_name, column.name, new_column_name) <ide><path>activerecord/lib/active_record/dynamic_matchers.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveRecord <del> module DynamicMatchers #:nodoc: <add> module DynamicMatchers # :nodoc: <ide> private <ide> def respond_to_missing?(name, _) <ide> if self == Base <ide><path>activerecord/lib/active_record/encryption/configurable.rb <ide> module Configurable <ide> delegate name, to: :context <ide> end <ide> <del> def configure(primary_key:, deterministic_key:, key_derivation_salt:, **properties) #:nodoc: <add> def configure(primary_key:, deterministic_key:, key_derivation_salt:, **properties) # :nodoc: <ide> config.primary_key = primary_key <ide> config.deterministic_key = deterministic_key <ide> config.key_derivation_salt = key_derivation_salt <ide> def on_encrypted_attribute_declared(&block) <ide> self.encrypted_attribute_declaration_listeners << block <ide> end <ide> <del> def encrypted_attribute_was_declared(klass, name) #:nodoc: <add> def encrypted_attribute_was_declared(klass, name) # :nodoc: <ide> self.encrypted_attribute_declaration_listeners&.each do |block| <ide> block.call(klass, name) <ide> end <ide> end <ide> <del> def install_auto_filtered_parameters(application) #:nodoc: <add> def install_auto_filtered_parameters(application) # :nodoc: <ide> ActiveRecord::Encryption.on_encrypted_attribute_declared do |klass, encrypted_attribute_name| <ide> application.config.filter_parameters << encrypted_attribute_name unless ActiveRecord::Encryption.config.excluded_from_filter_parameters.include?(name) <ide> end <ide><path>activerecord/lib/active_record/fixtures.rb <ide> require "active_record/test_fixtures" <ide> <ide> module ActiveRecord <del> class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc: <add> class FixtureClassNotFound < ActiveRecord::ActiveRecordError # :nodoc: <ide> end <ide> <ide> # \Fixtures are a way of organizing data that you want to test against; in short, sample data. <ide> def yaml_file_path(path) <ide> end <ide> end <ide> <del> class Fixture #:nodoc: <add> class Fixture # :nodoc: <ide> include Enumerable <ide> <del> class FixtureError < StandardError #:nodoc: <add> class FixtureError < StandardError # :nodoc: <ide> end <ide> <del> class FormatError < FixtureError #:nodoc: <add> class FormatError < FixtureError # :nodoc: <ide> end <ide> <ide> attr_reader :model_class, :fixture <ide><path>activerecord/lib/active_record/inheritance.rb <ide> def descends_from_active_record? <ide> end <ide> end <ide> <del> def finder_needs_type_condition? #:nodoc: <add> def finder_needs_type_condition? # :nodoc: <ide> # This is like this because benchmarking justifies the strange :false stuff <ide> :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) <ide> end <ide><path>activerecord/lib/active_record/locking/optimistic.rb <ide> module Optimistic <ide> class_attribute :lock_optimistically, instance_writer: false, default: true <ide> end <ide> <del> def locking_enabled? #:nodoc: <add> def locking_enabled? # :nodoc: <ide> self.class.locking_enabled? <ide> end <ide> <del> def increment!(*, **) #:nodoc: <add> def increment!(*, **) # :nodoc: <ide> super.tap do <ide> if locking_enabled? <ide> self[self.class.locking_column] += 1 <ide><path>activerecord/lib/active_record/migration.rb <ide> require "active_support/actionable_error" <ide> <ide> module ActiveRecord <del> class MigrationError < ActiveRecordError #:nodoc: <add> class MigrationError < ActiveRecordError # :nodoc: <ide> def initialize(message = nil) <ide> message = "\n\n#{message}\n\n" if message <ide> super <ide> def initialize(message = nil) <ide> class IrreversibleMigration < MigrationError <ide> end <ide> <del> class DuplicateMigrationVersionError < MigrationError #:nodoc: <add> class DuplicateMigrationVersionError < MigrationError # :nodoc: <ide> def initialize(version = nil) <ide> if version <ide> super("Multiple migrations have the version number #{version}.") <ide> def initialize(version = nil) <ide> end <ide> end <ide> <del> class DuplicateMigrationNameError < MigrationError #:nodoc: <add> class DuplicateMigrationNameError < MigrationError # :nodoc: <ide> def initialize(name = nil) <ide> if name <ide> super("Multiple migrations have the name #{name}.") <ide> def initialize(name = nil) <ide> end <ide> end <ide> <del> class UnknownMigrationVersionError < MigrationError #:nodoc: <add> class UnknownMigrationVersionError < MigrationError # :nodoc: <ide> def initialize(version = nil) <ide> if version <ide> super("No migration with version number #{version}.") <ide> def initialize(version = nil) <ide> end <ide> end <ide> <del> class IllegalMigrationNameError < MigrationError #:nodoc: <add> class IllegalMigrationNameError < MigrationError # :nodoc: <ide> def initialize(name = nil) <ide> if name <ide> super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed).") <ide> def initialize(name = nil) <ide> end <ide> end <ide> <del> class PendingMigrationError < MigrationError #:nodoc: <add> class PendingMigrationError < MigrationError # :nodoc: <ide> include ActiveSupport::ActionableError <ide> <ide> action "Run pending migrations" do <ide> def detailed_migration_message <ide> end <ide> end <ide> <del> class ConcurrentMigrationError < MigrationError #:nodoc: <add> class ConcurrentMigrationError < MigrationError # :nodoc: <ide> DEFAULT_MESSAGE = "Cannot run migrations because another migration process is currently running." <ide> RELEASE_LOCK_FAILED_MESSAGE = "Failed to release advisory lock" <ide> <ide> def initialize(message = DEFAULT_MESSAGE) <ide> end <ide> end <ide> <del> class NoEnvironmentInSchemaError < MigrationError #:nodoc: <add> class NoEnvironmentInSchemaError < MigrationError # :nodoc: <ide> def initialize <ide> msg = "Environment data not found in the schema. To resolve this issue, run: \n\n bin/rails db:environment:set" <ide> if defined?(Rails.env) <ide> def initialize <ide> end <ide> end <ide> <del> class ProtectedEnvironmentError < ActiveRecordError #:nodoc: <add> class ProtectedEnvironmentError < ActiveRecordError # :nodoc: <ide> def initialize(env = "production") <ide> msg = +"You are attempting to run a destructive action against your '#{env}' database.\n" <ide> msg << "If you are sure you want to continue, run the same command with the environment variable:\n" <ide> class Migration <ide> autoload :JoinTable, "active_record/migration/join_table" <ide> <ide> # This must be defined before the inherited hook, below <del> class Current < Migration #:nodoc: <add> class Current < Migration # :nodoc: <ide> end <ide> <del> def self.inherited(subclass) #:nodoc: <add> def self.inherited(subclass) # :nodoc: <ide> super <ide> if subclass.superclass == Migration <ide> major = ActiveRecord::VERSION::MAJOR <ide> def self.current_version <ide> ActiveRecord::VERSION::STRING.to_f <ide> end <ide> <del> MigrationFilenameRegexp = /\A([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/ #:nodoc: <add> MigrationFilenameRegexp = /\A([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/ # :nodoc: <ide> <ide> # This class is used to verify that all migrations have been run before <ide> # loading a web page if <tt>config.active_record.migration_error</tt> is set to :page_load <ide> def connection <ide> end <ide> <ide> class << self <del> attr_accessor :delegate #:nodoc: <del> attr_accessor :disable_ddl_transaction #:nodoc: <add> attr_accessor :delegate # :nodoc: <add> attr_accessor :disable_ddl_transaction # :nodoc: <ide> <del> def nearest_delegate #:nodoc: <add> def nearest_delegate # :nodoc: <ide> delegate || superclass.nearest_delegate <ide> end <ide> <ide> def load_schema_if_pending! <ide> check_pending! <ide> end <ide> <del> def maintain_test_schema! #:nodoc: <add> def maintain_test_schema! # :nodoc: <ide> if ActiveRecord.maintain_test_schema <ide> suppress_messages { load_schema_if_pending! } <ide> end <ide> end <ide> <del> def method_missing(name, *args, &block) #:nodoc: <add> def method_missing(name, *args, &block) # :nodoc: <ide> nearest_delegate.send(name, *args, &block) <ide> end <ide> ruby2_keywords(:method_missing) <ide> def disable_ddl_transaction! <ide> end <ide> end <ide> <del> def disable_ddl_transaction #:nodoc: <add> def disable_ddl_transaction # :nodoc: <ide> self.class.disable_ddl_transaction <ide> end <ide> <ide> def reverting? <ide> connection.respond_to?(:reverting) && connection.reverting <ide> end <ide> <del> ReversibleBlockHelper = Struct.new(:reverting) do #:nodoc: <add> ReversibleBlockHelper = Struct.new(:reverting) do # :nodoc: <ide> def up <ide> yield unless reverting <ide> end <ide> def next_migration_number(number) <ide> <ide> # Builds a hash for use in ActiveRecord::Migration#proper_table_name using <ide> # the Active Record object's table_name prefix and suffix <del> def table_name_options(config = ActiveRecord::Base) #:nodoc: <add> def table_name_options(config = ActiveRecord::Base) # :nodoc: <ide> { <ide> table_name_prefix: config.table_name_prefix, <ide> table_name_suffix: config.table_name_suffix <ide><path>activerecord/lib/active_record/migration/join_table.rb <ide> <ide> module ActiveRecord <ide> class Migration <del> module JoinTable #:nodoc: <add> module JoinTable # :nodoc: <ide> private <ide> def find_join_table_name(table_1, table_2, options = {}) <ide> options.delete(:table_name) || join_table_name(table_1, table_2) <ide><path>activerecord/lib/active_record/model_schema.rb <ide> def quoted_table_name <ide> end <ide> <ide> # Computes the table name, (re)sets it internally, and returns it. <del> def reset_table_name #:nodoc: <add> def reset_table_name # :nodoc: <ide> self.table_name = if abstract_class? <ide> superclass == Base ? nil : superclass.table_name <ide> elsif superclass.abstract_class? <ide> def reset_table_name #:nodoc: <ide> end <ide> end <ide> <del> def full_table_name_prefix #:nodoc: <add> def full_table_name_prefix # :nodoc: <ide> (module_parents.detect { |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix <ide> end <ide> <del> def full_table_name_suffix #:nodoc: <add> def full_table_name_suffix # :nodoc: <ide> (module_parents.detect { |p| p.respond_to?(:table_name_suffix) } || self).table_name_suffix <ide> end <ide> <ide> def sequence_name <ide> end <ide> end <ide> <del> def reset_sequence_name #:nodoc: <add> def reset_sequence_name # :nodoc: <ide> @explicit_sequence_name = false <ide> @sequence_name = connection.default_sequence_name(table_name, primary_key) <ide> end <ide><path>activerecord/lib/active_record/nested_attributes.rb <ide> require "active_support/core_ext/hash/indifferent_access" <ide> <ide> module ActiveRecord <del> module NestedAttributes #:nodoc: <add> module NestedAttributes # :nodoc: <ide> class TooManyRecords < ActiveRecordError <ide> end <ide> <ide><path>activerecord/lib/active_record/no_touching.rb <ide> def no_touching(&block) <ide> end <ide> <ide> class << self <del> def apply_to(klass) #:nodoc: <add> def apply_to(klass) # :nodoc: <ide> klasses.push(klass) <ide> yield <ide> ensure <ide> klasses.pop <ide> end <ide> <del> def applied_to?(klass) #:nodoc: <add> def applied_to?(klass) # :nodoc: <ide> klasses.any? { |k| k >= klass } <ide> end <ide> <ide><path>activerecord/lib/active_record/railties/controller_runtime.rb <ide> <ide> module ActiveRecord <ide> module Railties # :nodoc: <del> module ControllerRuntime #:nodoc: <add> module ControllerRuntime # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> module ClassMethods # :nodoc: <ide><path>activerecord/lib/active_record/reflection.rb <ide> def reflect_on_association(association) <ide> reflections[association.to_s] <ide> end <ide> <del> def _reflect_on_association(association) #:nodoc: <add> def _reflect_on_association(association) # :nodoc: <ide> _reflections[association.to_s] <ide> end <ide> <ide> def derive_class_name <ide> <ide> # Holds all the metadata about an aggregation as it was specified in the <ide> # Active Record class. <del> class AggregateReflection < MacroReflection #:nodoc: <add> class AggregateReflection < MacroReflection # :nodoc: <ide> def mapping <ide> mapping = options[:mapping] || [name, name] <ide> mapping.first.is_a?(Array) ? mapping : [mapping] <ide> def mapping <ide> <ide> # Holds all the metadata about an association as it was specified in the <ide> # Active Record class. <del> class AssociationReflection < MacroReflection #:nodoc: <add> class AssociationReflection < MacroReflection # :nodoc: <ide> def compute_class(name) <ide> if polymorphic? <ide> raise ArgumentError, "Polymorphic associations do not support computing the class." <ide> def collection? <ide> <ide> # Holds all the metadata about a :through association as it was specified <ide> # in the Active Record class. <del> class ThroughReflection < AbstractReflection #:nodoc: <add> class ThroughReflection < AbstractReflection # :nodoc: <ide> delegate :foreign_key, :foreign_type, :association_foreign_key, :join_id_for, :type, <ide> :active_record_primary_key, :join_foreign_key, to: :source_reflection <ide> <ide><path>activerecord/lib/active_record/relation/batches/batch_enumerator.rb <ide> module Batches <ide> class BatchEnumerator <ide> include Enumerable <ide> <del> def initialize(of: 1000, start: nil, finish: nil, relation:) #:nodoc: <add> def initialize(of: 1000, start: nil, finish: nil, relation:) # :nodoc: <ide> @of = of <ide> @relation = relation <ide> @start = start <ide><path>activerecord/lib/active_record/relation/calculations.rb <ide> def operation_over_aggregate_column(column, operation, distinct) <ide> operation == "count" ? column.count(distinct) : column.public_send(operation) <ide> end <ide> <del> def execute_simple_calculation(operation, column_name, distinct) #:nodoc: <add> def execute_simple_calculation(operation, column_name, distinct) # :nodoc: <ide> if operation == "count" && (column_name == :all && distinct || has_limit_or_offset?) <ide> # Shortcut when limit is zero. <ide> return 0 if limit_value == 0 <ide> def execute_simple_calculation(operation, column_name, distinct) #:nodoc: <ide> type_cast_calculated_value(result.cast_values.first, operation, type) <ide> end <ide> <del> def execute_grouped_calculation(operation, column_name, distinct) #:nodoc: <add> def execute_grouped_calculation(operation, column_name, distinct) # :nodoc: <ide> group_fields = group_values <ide> group_fields = group_fields.uniq if group_fields.size > 1 <ide> <ide><path>activerecord/lib/active_record/relation/spawn_methods.rb <ide> module ActiveRecord <ide> module SpawnMethods <ide> # This is overridden by Associations::CollectionProxy <del> def spawn #:nodoc: <add> def spawn # :nodoc: <ide> already_in_scope?(klass.scope_registry) ? klass.all : clone <ide> end <ide> <ide><path>activerecord/lib/active_record/schema_dumper.rb <ide> module ActiveRecord <ide> # <ide> # This class is used to dump the database schema for some connection to some <ide> # output format (i.e., ActiveRecord::Schema). <del> class SchemaDumper #:nodoc: <add> class SchemaDumper # :nodoc: <ide> private_class_method :new <ide> <ide> ## <ide><path>activerecord/lib/active_record/scoping/default.rb <ide> def scope_attributes? # :nodoc: <ide> super || default_scopes.any? || respond_to?(:default_scope) <ide> end <ide> <del> def before_remove_const #:nodoc: <add> def before_remove_const # :nodoc: <ide> self.current_scope = nil <ide> end <ide> <ide><path>activerecord/lib/active_record/serialization.rb <ide> # frozen_string_literal: true <ide> <del>module ActiveRecord #:nodoc: <add>module ActiveRecord # :nodoc: <ide> # = Active Record \Serialization <ide> module Serialization <ide> extend ActiveSupport::Concern <ide><path>activerecord/lib/active_record/transactions.rb <ide> module ActiveRecord <ide> # See ActiveRecord::Transactions::ClassMethods for documentation. <ide> module Transactions <ide> extend ActiveSupport::Concern <del> #:nodoc: <add> # :nodoc: <ide> ACTIONS = [:create, :destroy, :update] <ide> <ide> included do <ide> def transaction(**options, &block) <ide> self.class.transaction(**options, &block) <ide> end <ide> <del> def destroy #:nodoc: <add> def destroy # :nodoc: <ide> with_transaction_returning_status { super } <ide> end <ide> <del> def save(**) #:nodoc: <add> def save(**) # :nodoc: <ide> with_transaction_returning_status { super } <ide> end <ide> <del> def save!(**) #:nodoc: <add> def save!(**) # :nodoc: <ide> with_transaction_returning_status { super } <ide> end <ide> <del> def touch(*, **) #:nodoc: <add> def touch(*, **) # :nodoc: <ide> with_transaction_returning_status { super } <ide> end <ide> <ide> def before_committed! # :nodoc: <ide> # <ide> # Ensure that it is not called if the object was never persisted (failed create), <ide> # but call it after the commit of a destroyed object. <del> def committed!(should_run_callbacks: true) #:nodoc: <add> def committed!(should_run_callbacks: true) # :nodoc: <ide> @_start_transaction_state = nil <ide> if should_run_callbacks <ide> @_committed_already_called = true <ide> def committed!(should_run_callbacks: true) #:nodoc: <ide> <ide> # Call the #after_rollback callbacks. The +force_restore_state+ argument indicates if the record <ide> # state should be rolled back to the beginning or just to the last savepoint. <del> def rolledback!(force_restore_state: false, should_run_callbacks: true) #:nodoc: <add> def rolledback!(force_restore_state: false, should_run_callbacks: true) # :nodoc: <ide> if should_run_callbacks <ide> _run_rollback_callbacks <ide> end <ide><path>activerecord/lib/active_record/translation.rb <ide> module Translation <ide> include ActiveModel::Translation <ide> <ide> # Set the lookup ancestors for ActiveModel. <del> def lookup_ancestors #:nodoc: <add> def lookup_ancestors # :nodoc: <ide> klass = self <ide> classes = [klass] <ide> return classes if klass == ActiveRecord::Base <ide> def lookup_ancestors #:nodoc: <ide> end <ide> <ide> # Set the i18n scope to overwrite ActiveModel. <del> def i18n_scope #:nodoc: <add> def i18n_scope # :nodoc: <ide> :activerecord <ide> end <ide> end <ide><path>activerecord/lib/active_record/validations/associated.rb <ide> <ide> module ActiveRecord <ide> module Validations <del> class AssociatedValidator < ActiveModel::EachValidator #:nodoc: <add> class AssociatedValidator < ActiveModel::EachValidator # :nodoc: <ide> def validate_each(record, attribute, value) <ide> if Array(value).reject { |r| valid_object?(r) }.any? <ide> record.errors.add(attribute, :invalid, **options.merge(value: value)) <ide><path>activerecord/test/cases/test_case.rb <ide> module ActiveRecord <ide> # = Active Record Test Case <ide> # <ide> # Defines some test assertions to test against SQL queries. <del> class TestCase < ActiveSupport::TestCase #:nodoc: <add> class TestCase < ActiveSupport::TestCase # :nodoc: <ide> include ActiveSupport::Testing::MethodCallAssertions <ide> include ActiveSupport::Testing::Stream <ide> include ActiveRecord::TestFixtures <ide><path>activestorage/app/controllers/active_storage/representations/base_controller.rb <ide> # frozen_string_literal: true <ide> <del>class ActiveStorage::Representations::BaseController < ActiveStorage::BaseController #:nodoc: <add>class ActiveStorage::Representations::BaseController < ActiveStorage::BaseController # :nodoc: <ide> include ActiveStorage::SetBlob <ide> <ide> before_action :set_representation <ide><path>activestorage/app/controllers/concerns/active_storage/set_blob.rb <ide> # frozen_string_literal: true <ide> <del>module ActiveStorage::SetBlob #:nodoc: <add>module ActiveStorage::SetBlob # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>activestorage/app/models/active_storage/blob.rb <ide> def find_signed!(id, record: nil, purpose: :blob_id) <ide> super(id, purpose: purpose) <ide> end <ide> <del> def build_after_unfurling(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) #:nodoc: <add> def build_after_unfurling(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) # :nodoc: <ide> new(key: key, filename: filename, content_type: content_type, metadata: metadata, service_name: service_name).tap do |blob| <ide> blob.unfurl(io, identify: identify) <ide> end <ide> end <ide> <del> def create_after_unfurling!(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) #:nodoc: <add> def create_after_unfurling!(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) # :nodoc: <ide> build_after_unfurling(key: key, io: io, filename: filename, content_type: content_type, metadata: metadata, service_name: service_name, identify: identify).tap(&:save!) <ide> end <ide> <ide> def generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) <ide> end <ide> <ide> # Customize signed ID purposes for backwards compatibility. <del> def combine_signed_id_purposes(purpose) #:nodoc: <add> def combine_signed_id_purposes(purpose) # :nodoc: <ide> purpose.to_s <ide> end <ide> <ide> # Customize the default signed ID verifier for backwards compatibility. <ide> # <ide> # We override the reader (.signed_id_verifier) instead of just calling the writer (.signed_id_verifier=) <ide> # to guard against the case where ActiveStorage.verifier isn't yet initialized at load time. <del> def signed_id_verifier #:nodoc: <add> def signed_id_verifier # :nodoc: <ide> @signed_id_verifier ||= ActiveStorage.verifier <ide> end <ide> <del> def scope_for_strict_loading #:nodoc: <add> def scope_for_strict_loading # :nodoc: <ide> if strict_loading_by_default? && ActiveStorage.track_variants <ide> includes(variant_records: { image_attachment: :blob }, preview_image_attachment: :blob) <ide> else <ide> def service_headers_for_direct_upload <ide> service.headers_for_direct_upload key, filename: filename, content_type: content_type, content_length: byte_size, checksum: checksum <ide> end <ide> <del> def content_type_for_serving #:nodoc: <add> def content_type_for_serving # :nodoc: <ide> forcibly_serve_as_binary? ? ActiveStorage.binary_content_type : content_type <ide> end <ide> <del> def forced_disposition_for_serving #:nodoc: <add> def forced_disposition_for_serving # :nodoc: <ide> if forcibly_serve_as_binary? || !allowed_inline? <ide> :attachment <ide> end <ide> def upload(io, identify: true) <ide> upload_without_unfurling io <ide> end <ide> <del> def unfurl(io, identify: true) #:nodoc: <add> def unfurl(io, identify: true) # :nodoc: <ide> self.checksum = compute_checksum_in_chunks(io) <ide> self.content_type = extract_content_type(io) if content_type.nil? || identify <ide> self.byte_size = io.size <ide> self.identified = true <ide> end <ide> <del> def upload_without_unfurling(io) #:nodoc: <add> def upload_without_unfurling(io) # :nodoc: <ide> service.upload key, io, checksum: checksum, **service_metadata <ide> end <ide> <ide> def open(tmpdir: nil, &block) <ide> name: [ "ActiveStorage-#{id}-", filename.extension_with_delimiter ], tmpdir: tmpdir, &block <ide> end <ide> <del> def mirror_later #:nodoc: <add> def mirror_later # :nodoc: <ide> ActiveStorage::MirrorJob.perform_later(key, checksum: checksum) if service.respond_to?(:mirror) <ide> end <ide> <ide><path>activestorage/app/models/active_storage/current.rb <ide> # frozen_string_literal: true <ide> <del>class ActiveStorage::Current < ActiveSupport::CurrentAttributes #:nodoc: <add>class ActiveStorage::Current < ActiveSupport::CurrentAttributes # :nodoc: <ide> attribute :url_options <ide> <ide> def host=(host) <ide><path>activestorage/app/models/active_storage/record.rb <ide> # frozen_string_literal: true <ide> <del>class ActiveStorage::Record < ActiveRecord::Base #:nodoc: <add>class ActiveStorage::Record < ActiveRecord::Base # :nodoc: <ide> self.abstract_class = true <ide> end <ide> <ide><path>activestorage/app/models/active_storage/variant.rb <ide> def filename <ide> <ide> alias_method :content_type_for_serving, :content_type <ide> <del> def forced_disposition_for_serving #:nodoc: <add> def forced_disposition_for_serving # :nodoc: <ide> nil <ide> end <ide> <ide><path>activestorage/lib/active_storage/attached/changes.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> module Attached::Changes #:nodoc: <add> module Attached::Changes # :nodoc: <ide> extend ActiveSupport::Autoload <ide> <ide> eager_autoload do <ide><path>activestorage/lib/active_storage/attached/changes/create_many.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Attached::Changes::CreateMany #:nodoc: <add> class Attached::Changes::CreateMany # :nodoc: <ide> attr_reader :name, :record, :attachables <ide> <ide> def initialize(name, record, attachables) <ide><path>activestorage/lib/active_storage/attached/changes/create_one.rb <ide> require "action_dispatch/http/upload" <ide> <ide> module ActiveStorage <del> class Attached::Changes::CreateOne #:nodoc: <add> class Attached::Changes::CreateOne # :nodoc: <ide> attr_reader :name, :record, :attachable <ide> <ide> def initialize(name, record, attachable) <ide><path>activestorage/lib/active_storage/attached/changes/create_one_of_many.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Attached::Changes::CreateOneOfMany < Attached::Changes::CreateOne #:nodoc: <add> class Attached::Changes::CreateOneOfMany < Attached::Changes::CreateOne # :nodoc: <ide> private <ide> def find_attachment <ide> record.public_send("#{name}_attachments").detect { |attachment| attachment.blob_id == blob.id } <ide><path>activestorage/lib/active_storage/attached/changes/delete_many.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Attached::Changes::DeleteMany #:nodoc: <add> class Attached::Changes::DeleteMany # :nodoc: <ide> attr_reader :name, :record <ide> <ide> def initialize(name, record) <ide><path>activestorage/lib/active_storage/attached/changes/delete_one.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Attached::Changes::DeleteOne #:nodoc: <add> class Attached::Changes::DeleteOne # :nodoc: <ide> attr_reader :name, :record <ide> <ide> def initialize(name, record) <ide><path>activestorage/lib/active_storage/attached/changes/detach_many.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Attached::Changes::DetachMany #:nodoc: <add> class Attached::Changes::DetachMany # :nodoc: <ide> attr_reader :name, :record, :attachments <ide> <ide> def initialize(name, record, attachments) <ide><path>activestorage/lib/active_storage/attached/changes/detach_one.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Attached::Changes::DetachOne #:nodoc: <add> class Attached::Changes::DetachOne # :nodoc: <ide> attr_reader :name, :record, :attachment <ide> <ide> def initialize(name, record, attachment) <ide><path>activestorage/lib/active_storage/attached/changes/purge_many.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Attached::Changes::PurgeMany #:nodoc: <add> class Attached::Changes::PurgeMany # :nodoc: <ide> attr_reader :name, :record, :attachments <ide> <ide> def initialize(name, record, attachments) <ide><path>activestorage/lib/active_storage/attached/changes/purge_one.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Attached::Changes::PurgeOne #:nodoc: <add> class Attached::Changes::PurgeOne # :nodoc: <ide> attr_reader :name, :record, :attachment <ide> <ide> def initialize(name, record, attachment) <ide><path>activestorage/lib/active_storage/attached/model.rb <ide> def validate_service_configuration(association_name, service) <ide> end <ide> end <ide> <del> def attachment_changes #:nodoc: <add> def attachment_changes # :nodoc: <ide> @attachment_changes ||= {} <ide> end <ide> <del> def changed_for_autosave? #:nodoc: <add> def changed_for_autosave? # :nodoc: <ide> super || attachment_changes.any? <ide> end <ide> <del> def initialize_dup(*) #:nodoc: <add> def initialize_dup(*) # :nodoc: <ide> super <ide> @active_storage_attached = nil <ide> @attachment_changes = nil <ide> end <ide> <del> def reload(*) #:nodoc: <add> def reload(*) # :nodoc: <ide> super.tap { @attachment_changes = nil } <ide> end <ide> end <ide><path>activestorage/lib/active_storage/downloader.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Downloader #:nodoc: <add> class Downloader # :nodoc: <ide> attr_reader :service <ide> <ide> def initialize(service) <ide><path>activestorage/lib/active_storage/reflection.rb <ide> <ide> module ActiveStorage <ide> module Reflection <del> class HasAttachedReflection < ActiveRecord::Reflection::MacroReflection #:nodoc: <add> class HasAttachedReflection < ActiveRecord::Reflection::MacroReflection # :nodoc: <ide> def variant(name, transformations) <ide> variants[name] = transformations <ide> end <ide> def variants <ide> <ide> # Holds all the metadata about a has_one_attached attachment as it was <ide> # specified in the Active Record class. <del> class HasOneAttachedReflection < HasAttachedReflection #:nodoc: <add> class HasOneAttachedReflection < HasAttachedReflection # :nodoc: <ide> def macro <ide> :has_one_attached <ide> end <ide> end <ide> <ide> # Holds all the metadata about a has_many_attached attachment as it was <ide> # specified in the Active Record class. <del> class HasManyAttachedReflection < HasAttachedReflection #:nodoc: <add> class HasManyAttachedReflection < HasAttachedReflection # :nodoc: <ide> def macro <ide> :has_many_attached <ide> end <ide><path>activestorage/lib/active_storage/service.rb <ide> def configure(service_name, configurations) <ide> # Passes the configurator and all of the service's config as keyword args. <ide> # <ide> # See MirrorService for an example. <del> def build(configurator:, name:, service: nil, **service_config) #:nodoc: <add> def build(configurator:, name:, service: nil, **service_config) # :nodoc: <ide> new(**service_config).tap do |service_instance| <ide> service_instance.name = name <ide> end <ide><path>activestorage/lib/active_storage/service/configurator.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Service::Configurator #:nodoc: <add> class Service::Configurator # :nodoc: <ide> attr_reader :configurations <ide> <ide> def self.build(service_name, configurations) <ide><path>activestorage/lib/active_storage/service/disk_service.rb <ide> def headers_for_direct_upload(key, content_type:, **) <ide> { "Content-Type" => content_type } <ide> end <ide> <del> def path_for(key) #:nodoc: <add> def path_for(key) # :nodoc: <ide> File.join root, folder_for(key), key <ide> end <ide> <ide><path>activestorage/lib/active_storage/service/mirror_service.rb <ide> class Service::MirrorService < Service <ide> :url_for_direct_upload, :headers_for_direct_upload, :path_for, to: :primary <ide> <ide> # Stitch together from named services. <del> def self.build(primary:, mirrors:, name:, configurator:, **options) #:nodoc: <add> def self.build(primary:, mirrors:, name:, configurator:, **options) # :nodoc: <ide> new( <ide> primary: configurator.build(primary), <ide> mirrors: mirrors.collect { |mirror_name| configurator.build mirror_name } <ide><path>activestorage/lib/active_storage/service/registry.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveStorage <del> class Service::Registry #:nodoc: <add> class Service::Registry # :nodoc: <ide> def initialize(configurations) <ide> @configurations = configurations.deep_symbolize_keys <ide> @services = {} <ide><path>activesupport/lib/active_support/cache/redis_cache_store.rb <ide> class << self <ide> # :url String -> Redis.new(url: …) <ide> # :url Array -> Redis::Distributed.new([{ url: … }, { url: … }, …]) <ide> # <del> def build_redis(redis: nil, url: nil, **redis_options) #:nodoc: <add> def build_redis(redis: nil, url: nil, **redis_options) # :nodoc: <ide> urls = Array(url) <ide> <ide> if redis.is_a?(Proc) <ide> def stats <ide> redis.with { |c| c.info } <ide> end <ide> <del> def mget_capable? #:nodoc: <add> def mget_capable? # :nodoc: <ide> set_redis_capabilities unless defined? @mget_capable <ide> @mget_capable <ide> end <ide> <del> def mset_capable? #:nodoc: <add> def mset_capable? # :nodoc: <ide> set_redis_capabilities unless defined? @mset_capable <ide> @mset_capable <ide> end <ide><path>activesupport/lib/active_support/callbacks.rb <ide> def self.simple(callback_sequence, user_callback) <ide> end <ide> end <ide> <del> class Callback #:nodoc:# <add> class Callback # :nodoc:# <ide> def self.build(chain, filter, kind, options) <ide> if filter.is_a?(String) <ide> raise ArgumentError, <<-MSG.squish <ide> def invoke_after(arg) <ide> end <ide> end <ide> <del> class CallbackChain #:nodoc:# <add> class CallbackChain # :nodoc:# <ide> include Enumerable <ide> <ide> attr_reader :name, :config <ide> def normalize_callback_params(filters, block) # :nodoc: <ide> <ide> # This is used internally to append, prepend and skip callbacks to the <ide> # CallbackChain. <del> def __update_callbacks(name) #:nodoc: <add> def __update_callbacks(name) # :nodoc: <ide> ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target| <ide> chain = target.get_callbacks name <ide> yield target, chain.dup <ide><path>activesupport/lib/active_support/concern.rb <ide> module ActiveSupport <ide> # <ide> # <tt>prepend</tt> is also used for any dependencies. <ide> module Concern <del> class MultipleIncludedBlocks < StandardError #:nodoc: <add> class MultipleIncludedBlocks < StandardError # :nodoc: <ide> def initialize <ide> super "Cannot define multiple 'included' blocks for a Concern" <ide> end <ide> end <ide> <del> class MultiplePrependBlocks < StandardError #:nodoc: <add> class MultiplePrependBlocks < StandardError # :nodoc: <ide> def initialize <ide> super "Cannot define multiple 'prepended' blocks for a Concern" <ide> end <ide> end <ide> <del> def self.extended(base) #:nodoc: <add> def self.extended(base) # :nodoc: <ide> base.instance_variable_set(:@_dependencies, []) <ide> end <ide> <del> def append_features(base) #:nodoc: <add> def append_features(base) # :nodoc: <ide> if base.instance_variable_defined?(:@_dependencies) <ide> base.instance_variable_get(:@_dependencies) << self <ide> false <ide> def append_features(base) #:nodoc: <ide> end <ide> end <ide> <del> def prepend_features(base) #:nodoc: <add> def prepend_features(base) # :nodoc: <ide> if base.instance_variable_defined?(:@_dependencies) <ide> base.instance_variable_get(:@_dependencies).unshift self <ide> false <ide><path>activesupport/lib/active_support/core_ext/big_decimal/conversions.rb <ide> require "bigdecimal/util" <ide> <ide> module ActiveSupport <del> module BigDecimalWithDefaultFormat #:nodoc: <add> module BigDecimalWithDefaultFormat # :nodoc: <ide> def to_s(format = "F") <ide> super(format) <ide> end <ide><path>activesupport/lib/active_support/core_ext/date/blank.rb <ide> <ide> require "date" <ide> <del>class Date #:nodoc: <add>class Date # :nodoc: <ide> # No Date is blank: <ide> # <ide> # Date.today.blank? # => false <ide><path>activesupport/lib/active_support/core_ext/date/calculations.rb <ide> def end_of_day <ide> end <ide> alias :at_end_of_day :end_of_day <ide> <del> def plus_with_duration(other) #:nodoc: <add> def plus_with_duration(other) # :nodoc: <ide> if ActiveSupport::Duration === other <ide> other.since(self) <ide> else <ide> def plus_with_duration(other) #:nodoc: <ide> alias_method :plus_without_duration, :+ <ide> alias_method :+, :plus_with_duration <ide> <del> def minus_with_duration(other) #:nodoc: <add> def minus_with_duration(other) # :nodoc: <ide> if ActiveSupport::Duration === other <ide> plus_with_duration(-other) <ide> else <ide><path>activesupport/lib/active_support/core_ext/date_time/blank.rb <ide> <ide> require "date" <ide> <del>class DateTime #:nodoc: <add>class DateTime # :nodoc: <ide> # No DateTime is ever blank: <ide> # <ide> # DateTime.now.blank? # => false <ide><path>activesupport/lib/active_support/core_ext/digest/uuid.rb <ide> <ide> module Digest <ide> module UUID <del> DNS_NAMESPACE = "k\xA7\xB8\x10\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc: <del> URL_NAMESPACE = "k\xA7\xB8\x11\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc: <del> OID_NAMESPACE = "k\xA7\xB8\x12\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc: <del> X500_NAMESPACE = "k\xA7\xB8\x14\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc: <add> DNS_NAMESPACE = "k\xA7\xB8\x10\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" # :nodoc: <add> URL_NAMESPACE = "k\xA7\xB8\x11\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" # :nodoc: <add> OID_NAMESPACE = "k\xA7\xB8\x12\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" # :nodoc: <add> X500_NAMESPACE = "k\xA7\xB8\x14\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" # :nodoc: <ide> <ide> # Generates a v5 non-random UUID (Universally Unique IDentifier). <ide> # <ide><path>activesupport/lib/active_support/core_ext/enumerable.rb <ide> def sole <ide> <ide> class Hash <ide> # Hash#reject has its own definition, so this needs one too. <del> def compact_blank #:nodoc: <add> def compact_blank # :nodoc: <ide> reject { |_k, v| v.blank? } <ide> end <ide> <ide> def compact_blank! <ide> end <ide> end <ide> <del>class Range #:nodoc: <add>class Range # :nodoc: <ide> # Optimize range sum to use arithmetic progression if a block is not given and <ide> # we have a range of numeric values. <ide> def sum(identity = nil) <ide> def sum(identity = nil) <ide> end <ide> } <ide> <del>class Array #:nodoc: <add>class Array # :nodoc: <ide> def sum(init = nil, &block) <ide> if init.is_a?(Numeric) || first.is_a?(Numeric) <ide> init ||= 0 <ide><path>activesupport/lib/active_support/core_ext/file/atomic.rb <ide> def self.atomic_write(file_name, temp_dir = dirname(file_name)) <ide> end <ide> <ide> # Private utility method. <del> def self.probe_stat_in(dir) #:nodoc: <add> def self.probe_stat_in(dir) # :nodoc: <ide> basename = [ <ide> ".permissions_check", <ide> Thread.current.object_id, <ide><path>activesupport/lib/active_support/core_ext/object/blank.rb <ide> def blank? <ide> end <ide> end <ide> <del>class Numeric #:nodoc: <add>class Numeric # :nodoc: <ide> # No number is blank: <ide> # <ide> # 1.blank? # => false <ide> def blank? <ide> end <ide> end <ide> <del>class Time #:nodoc: <add>class Time # :nodoc: <ide> # No Time is blank: <ide> # <ide> # Time.now.blank? # => false <ide><path>activesupport/lib/active_support/core_ext/object/json.rb <ide> def to_json(options = nil) <ide> end <ide> <ide> class Module <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> name <ide> end <ide> end <ide> <ide> class Object <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> if respond_to?(:to_hash) <ide> to_hash.as_json(options) <ide> else <ide> def as_json(options = nil) #:nodoc: <ide> end <ide> end <ide> <del>class Struct #:nodoc: <add>class Struct # :nodoc: <ide> def as_json(options = nil) <ide> Hash[members.zip(values)].as_json(options) <ide> end <ide> end <ide> <ide> class TrueClass <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> self <ide> end <ide> end <ide> <ide> class FalseClass <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> self <ide> end <ide> end <ide> <ide> class NilClass <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> self <ide> end <ide> end <ide> <ide> class String <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> self <ide> end <ide> end <ide> <ide> class Symbol <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> to_s <ide> end <ide> end <ide> <ide> class Numeric <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> self <ide> end <ide> end <ide> <ide> class Float <ide> # Encoding Infinity or NaN to JSON should return "null". The default returns <ide> # "Infinity" or "NaN" which are not valid JSON. <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> finite? ? self : nil <ide> end <ide> end <ide> class BigDecimal <ide> # if the other end knows by contract that the data is supposed to be a <ide> # BigDecimal, it still has the chance to post-process the string and get the <ide> # real value. <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> finite? ? to_s : nil <ide> end <ide> end <ide> <ide> class Regexp <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> to_s <ide> end <ide> end <ide> <ide> module Enumerable <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> to_a.as_json(options) <ide> end <ide> end <ide> <ide> class IO <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> to_s <ide> end <ide> end <ide> <ide> class Range <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> to_s <ide> end <ide> end <ide> <ide> class Array <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> map { |v| options ? v.as_json(options.dup) : v.as_json } <ide> end <ide> end <ide> <ide> class Hash <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> # create a subset of the hash by applying :only or :except <ide> subset = if options <ide> if attrs = options[:only] <ide> def as_json(options = nil) #:nodoc: <ide> end <ide> <ide> class Time <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> if ActiveSupport::JSON::Encoding.use_standard_json_time_format <ide> xmlschema(ActiveSupport::JSON::Encoding.time_precision) <ide> else <ide> def as_json(options = nil) #:nodoc: <ide> end <ide> <ide> class Date <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> if ActiveSupport::JSON::Encoding.use_standard_json_time_format <ide> strftime("%Y-%m-%d") <ide> else <ide> def as_json(options = nil) #:nodoc: <ide> end <ide> <ide> class DateTime <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> if ActiveSupport::JSON::Encoding.use_standard_json_time_format <ide> xmlschema(ActiveSupport::JSON::Encoding.time_precision) <ide> else <ide> def as_json(options = nil) #:nodoc: <ide> end <ide> end <ide> <del>class URI::Generic #:nodoc: <add>class URI::Generic # :nodoc: <ide> def as_json(options = nil) <ide> to_s <ide> end <ide> end <ide> <del>class Pathname #:nodoc: <add>class Pathname # :nodoc: <ide> def as_json(options = nil) <ide> to_s <ide> end <ide> def as_json(options = nil) <ide> end <ide> end <ide> <del>class Process::Status #:nodoc: <add>class Process::Status # :nodoc: <ide> def as_json(options = nil) <ide> { exitstatus: exitstatus, pid: pid } <ide> end <ide><path>activesupport/lib/active_support/core_ext/object/try.rb <ide> require "delegate" <ide> <ide> module ActiveSupport <del> module Tryable #:nodoc: <add> module Tryable # :nodoc: <ide> def try(*args, &block) <ide> if args.empty? && block_given? <ide> if block.arity == 0 <ide><path>activesupport/lib/active_support/core_ext/range/each.rb <ide> require "active_support/time_with_zone" <ide> <ide> module ActiveSupport <del> module EachTimeWithZone #:nodoc: <add> module EachTimeWithZone # :nodoc: <ide> def each(&block) <ide> ensure_iteration_allowed <ide> super <ide><path>activesupport/lib/active_support/core_ext/range/include_time_with_zone.rb <ide> require "active_support/deprecation" <ide> <ide> module ActiveSupport <del> module IncludeTimeWithZone #:nodoc: <add> module IncludeTimeWithZone # :nodoc: <ide> # Extends the default Range#include? to support ActiveSupport::TimeWithZone. <ide> # <ide> # (1.hour.ago..1.hour.from_now).include?(Time.current) # => true <ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb <ide> def html_safe? <ide> end <ide> end <ide> <del>module ActiveSupport #:nodoc: <add>module ActiveSupport # :nodoc: <ide> class SafeBuffer < String <ide> UNSAFE_STRING_METHODS = %w( <ide> capitalize chomp chop delete delete_prefix delete_suffix <ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb <ide> def end_of_minute <ide> end <ide> alias :at_end_of_minute :end_of_minute <ide> <del> def plus_with_duration(other) #:nodoc: <add> def plus_with_duration(other) # :nodoc: <ide> if ActiveSupport::Duration === other <ide> other.since(self) <ide> else <ide> def plus_with_duration(other) #:nodoc: <ide> alias_method :plus_without_duration, :+ <ide> alias_method :+, :plus_with_duration <ide> <del> def minus_with_duration(other) #:nodoc: <add> def minus_with_duration(other) # :nodoc: <ide> if ActiveSupport::Duration === other <ide> other.until(self) <ide> else <ide><path>activesupport/lib/active_support/dependencies.rb <ide> require "active_support/dependencies/interlock" <ide> require "active_support/inflector" <ide> <del>module ActiveSupport #:nodoc: <del> module Dependencies #:nodoc: <add>module ActiveSupport # :nodoc: <add> module Dependencies # :nodoc: <ide> extend self <ide> <ide> UNBOUND_METHOD_MODULE_NAME = Module.instance_method(:name) <ide> def pop_modules(modules) <ide> mattr_accessor :constant_watch_stack, default: WatchStack.new <ide> <ide> # Module includes this module. <del> module ModuleConstMissing #:nodoc: <add> module ModuleConstMissing # :nodoc: <ide> def self.append_features(base) <ide> base.class_eval do <ide> # Emulate #exclude via an ivar <ide> def unloadable(const_desc = self) <ide> end <ide> <ide> # Object includes this module. <del> module Loadable #:nodoc: <add> module Loadable # :nodoc: <ide> def self.exclude_from(base) <ide> base.class_eval do <ide> define_method(:load, Kernel.instance_method(:load)) <ide> def new_constants_in(*descs) <ide> <ide> # Convert the provided const desc to a qualified constant name (as a string). <ide> # A module, class, symbol, or string may be provided. <del> def to_constant_name(desc) #:nodoc: <add> def to_constant_name(desc) # :nodoc: <ide> case desc <ide> when String then desc.delete_prefix("::") <ide> when Symbol then desc.to_s <ide> def to_constant_name(desc) #:nodoc: <ide> end <ide> end <ide> <del> def remove_constant(const) #:nodoc: <add> def remove_constant(const) # :nodoc: <ide> # Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo. <ide> normalized = const.to_s.delete_prefix("::") <ide> normalized.sub!(/\A(Object::)+/, "") <ide><path>activesupport/lib/active_support/dependencies/interlock.rb <ide> <ide> require "active_support/concurrency/share_lock" <ide> <del>module ActiveSupport #:nodoc: <del> module Dependencies #:nodoc: <add>module ActiveSupport # :nodoc: <add> module Dependencies # :nodoc: <ide> class Interlock <ide> def initialize # :nodoc: <ide> @lock = ActiveSupport::Concurrency::ShareLock.new <ide><path>activesupport/lib/active_support/deprecation/proxy_wrappers.rb <ide> <ide> module ActiveSupport <ide> class Deprecation <del> class DeprecationProxy #:nodoc: <add> class DeprecationProxy # :nodoc: <ide> def self.new(*args, &block) <ide> object = args.first <ide> <ide><path>activesupport/lib/active_support/digest.rb <ide> require "openssl" <ide> <ide> module ActiveSupport <del> class Digest #:nodoc: <add> class Digest # :nodoc: <ide> class << self <ide> def hash_digest_class <ide> @hash_digest_class ||= OpenSSL::Digest::MD5 <ide><path>activesupport/lib/active_support/duration.rb <ide> module ActiveSupport <ide> # <ide> # 1.month.ago # equivalent to Time.now.advance(months: -1) <ide> class Duration <del> class Scalar < Numeric #:nodoc: <add> class Scalar < Numeric # :nodoc: <ide> attr_reader :value <ide> delegate :to_i, :to_f, :to_s, to: :value <ide> <ide> def %(other) <ide> end <ide> end <ide> <del> def variable? #:nodoc: <add> def variable? # :nodoc: <ide> false <ide> end <ide> <ide> def parse(iso8601duration) <ide> new(calculate_total_seconds(parts), parts) <ide> end <ide> <del> def ===(other) #:nodoc: <add> def ===(other) # :nodoc: <ide> other.is_a?(Duration) <ide> rescue ::NoMethodError <ide> false <ide> end <ide> <del> def seconds(value) #:nodoc: <add> def seconds(value) # :nodoc: <ide> new(value, { seconds: value }, false) <ide> end <ide> <del> def minutes(value) #:nodoc: <add> def minutes(value) # :nodoc: <ide> new(value * SECONDS_PER_MINUTE, { minutes: value }, false) <ide> end <ide> <del> def hours(value) #:nodoc: <add> def hours(value) # :nodoc: <ide> new(value * SECONDS_PER_HOUR, { hours: value }, false) <ide> end <ide> <del> def days(value) #:nodoc: <add> def days(value) # :nodoc: <ide> new(value * SECONDS_PER_DAY, { days: value }, true) <ide> end <ide> <del> def weeks(value) #:nodoc: <add> def weeks(value) # :nodoc: <ide> new(value * SECONDS_PER_WEEK, { weeks: value }, true) <ide> end <ide> <del> def months(value) #:nodoc: <add> def months(value) # :nodoc: <ide> new(value * SECONDS_PER_MONTH, { months: value }, true) <ide> end <ide> <del> def years(value) #:nodoc: <add> def years(value) # :nodoc: <ide> new(value * SECONDS_PER_YEAR, { years: value }, true) <ide> end <ide> <ide> def calculate_total_seconds(parts) <ide> end <ide> end <ide> <del> def initialize(value, parts, variable = nil) #:nodoc: <add> def initialize(value, parts, variable = nil) # :nodoc: <ide> @value, @parts = value, parts <ide> @parts.reject! { |k, v| v.zero? } unless value == 0 <ide> @parts.freeze <ide> def parts <ide> @parts.dup <ide> end <ide> <del> def coerce(other) #:nodoc: <add> def coerce(other) # :nodoc: <ide> case other <ide> when Scalar <ide> [other, self] <ide> def %(other) <ide> end <ide> end <ide> <del> def -@ #:nodoc: <add> def -@ # :nodoc: <ide> Duration.new(-value, @parts.transform_values(&:-@), @variable) <ide> end <ide> <del> def +@ #:nodoc: <add> def +@ # :nodoc: <ide> self <ide> end <ide> <del> def is_a?(klass) #:nodoc: <add> def is_a?(klass) # :nodoc: <ide> Duration == klass || value.is_a?(klass) <ide> end <ide> alias :kind_of? :is_a? <ide> def ago(time = ::Time.current) <ide> alias :until :ago <ide> alias :before :ago <ide> <del> def inspect #:nodoc: <add> def inspect # :nodoc: <ide> return "#{value} seconds" if @parts.empty? <ide> <ide> @parts. <ide> def inspect #:nodoc: <ide> to_sentence(locale: false) <ide> end <ide> <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> to_i <ide> end <ide> <del> def init_with(coder) #:nodoc: <add> def init_with(coder) # :nodoc: <ide> initialize(coder["value"], coder["parts"]) <ide> end <ide> <del> def encode_with(coder) #:nodoc: <add> def encode_with(coder) # :nodoc: <ide> coder.map = { "value" => @value, "parts" => @parts } <ide> end <ide> <ide> def iso8601(precision: nil) <ide> ISO8601Serializer.new(self, precision: precision).serialize <ide> end <ide> <del> def variable? #:nodoc: <add> def variable? # :nodoc: <ide> @variable <ide> end <ide> <del> def _parts #:nodoc: <add> def _parts # :nodoc: <ide> @parts <ide> end <ide> <ide><path>activesupport/lib/active_support/environment_inquirer.rb <ide> require "active_support/string_inquirer" <ide> <ide> module ActiveSupport <del> class EnvironmentInquirer < StringInquirer #:nodoc: <add> class EnvironmentInquirer < StringInquirer # :nodoc: <ide> DEFAULT_ENVIRONMENTS = ["development", "test", "production"] <ide> def initialize(env) <ide> super(env) <ide><path>activesupport/lib/active_support/evented_file_update_checker.rb <ide> module ActiveSupport <ide> # checker.execute_if_updated <ide> # # => "changed" <ide> # <del> class EventedFileUpdateChecker #:nodoc: all <add> class EventedFileUpdateChecker # :nodoc: all <ide> def initialize(files, dirs = {}, &block) <ide> unless block <ide> raise ArgumentError, "A block is required to initialize an EventedFileUpdateChecker" <ide><path>activesupport/lib/active_support/json/encoding.rb <ide> def self.encode(value, options = nil) <ide> Encoding.json_encoder.new(options).encode(value) <ide> end <ide> <del> module Encoding #:nodoc: <del> class JSONGemEncoder #:nodoc: <add> module Encoding # :nodoc: <add> class JSONGemEncoder # :nodoc: <ide> attr_reader :options <ide> <ide> def initialize(options = nil) <ide> def encode(value) <ide> ESCAPE_REGEX_WITHOUT_HTML_ENTITIES = /[\u2028\u2029]/u <ide> <ide> # This class wraps all the strings we see and does the extra escaping <del> class EscapedString < String #:nodoc: <add> class EscapedString < String # :nodoc: <ide> def to_json(*) <ide> if Encoding.escape_html_entities_in_json <ide> s = super <ide><path>activesupport/lib/active_support/logger_thread_safe_level.rb <ide> def log_at(level) <ide> <ide> # Redefined to check severity against #level, and thus the thread-local level, rather than +@level+. <ide> # FIXME: Remove when the minimum Ruby version supports overriding Logger#level. <del> def add(severity, message = nil, progname = nil, &block) #:nodoc: <add> def add(severity, message = nil, progname = nil, &block) # :nodoc: <ide> severity ||= UNKNOWN <ide> progname ||= @progname <ide> <ide><path>activesupport/lib/active_support/message_encryptor.rb <ide> class MessageEncryptor <ide> cattr_accessor :use_authenticated_message_encryption, instance_accessor: false, default: false <ide> <ide> class << self <del> def default_cipher #:nodoc: <add> def default_cipher # :nodoc: <ide> if use_authenticated_message_encryption <ide> "aes-256-gcm" <ide> else <ide> def default_cipher #:nodoc: <ide> end <ide> end <ide> <del> module NullSerializer #:nodoc: <add> module NullSerializer # :nodoc: <ide> def self.load(value) <ide> value <ide> end <ide> def self.dump(value) <ide> end <ide> end <ide> <del> module NullVerifier #:nodoc: <add> module NullVerifier # :nodoc: <ide> def self.verify(value) <ide> value <ide> end <ide><path>activesupport/lib/active_support/messages/metadata.rb <ide> require "time" <ide> <ide> module ActiveSupport <del> module Messages #:nodoc: <del> class Metadata #:nodoc: <add> module Messages # :nodoc: <add> class Metadata # :nodoc: <ide> def initialize(message, expires_at = nil, purpose = nil) <ide> @message, @purpose = message, purpose <ide> @expires_at = expires_at.is_a?(String) ? parse_expires_at(expires_at) : expires_at <ide><path>activesupport/lib/active_support/multibyte.rb <ide> # frozen_string_literal: true <ide> <del>module ActiveSupport #:nodoc: <add>module ActiveSupport # :nodoc: <ide> module Multibyte <ide> autoload :Chars, "active_support/multibyte/chars" <ide> autoload :Unicode, "active_support/multibyte/unicode" <ide><path>activesupport/lib/active_support/multibyte/chars.rb <ide> require "active_support/core_ext/string/behavior" <ide> require "active_support/core_ext/module/delegation" <ide> <del>module ActiveSupport #:nodoc: <del> module Multibyte #:nodoc: <add>module ActiveSupport # :nodoc: <add> module Multibyte # :nodoc: <ide> # Chars enables you to work transparently with UTF-8 encoding in the Ruby <ide> # String class without having extensive knowledge about the encoding. A <ide> # Chars object accepts a string upon initialization and proxies String <ide> def tidy_bytes(force = false) <ide> chars(Unicode.tidy_bytes(@wrapped_string, force)) <ide> end <ide> <del> def as_json(options = nil) #:nodoc: <add> def as_json(options = nil) # :nodoc: <ide> to_s.as_json(options) <ide> end <ide> <ide><path>activesupport/lib/active_support/notifications/fanout.rb <ide> def self.wrap_all(pattern, subscriber) <ide> end <ide> end <ide> <del> class Matcher #:nodoc: <add> class Matcher # :nodoc: <ide> attr_reader :pattern, :exclusions <ide> <ide> def self.wrap(pattern) <ide> def ===(name) <ide> end <ide> end <ide> <del> class Evented #:nodoc: <add> class Evented # :nodoc: <ide> attr_reader :pattern <ide> <ide> def initialize(pattern, delegate) <ide><path>activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb <ide> <ide> module ActiveSupport <ide> module NumberHelper <del> class NumberToDelimitedConverter < NumberConverter #:nodoc: <add> class NumberToDelimitedConverter < NumberConverter # :nodoc: <ide> self.validate_float = true <ide> <ide> DEFAULT_DELIMITER_REGEX = /(\d)(?=(\d\d\d)+(?!\d))/ <ide><path>activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb <ide> <ide> module ActiveSupport <ide> module NumberHelper <del> class NumberToHumanSizeConverter < NumberConverter #:nodoc: <add> class NumberToHumanSizeConverter < NumberConverter # :nodoc: <ide> STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb, :pb, :eb] <ide> <ide> self.namespace = :human <ide><path>activesupport/lib/active_support/number_helper/number_to_phone_converter.rb <ide> <ide> module ActiveSupport <ide> module NumberHelper <del> class NumberToPhoneConverter < NumberConverter #:nodoc: <add> class NumberToPhoneConverter < NumberConverter # :nodoc: <ide> def convert <ide> str = country_code(opts[:country_code]).dup <ide> str << convert_to_phone_number(number.to_s.strip) <ide><path>activesupport/lib/active_support/option_merger.rb <ide> require "active_support/core_ext/hash/deep_merge" <ide> <ide> module ActiveSupport <del> class OptionMerger #:nodoc: <add> class OptionMerger # :nodoc: <ide> instance_methods.each do |method| <ide> undef_method(method) unless method.start_with?("__", "instance_eval", "class", "object_id") <ide> end <ide><path>activesupport/lib/active_support/rescuable.rb <ide> def rescue_with_handler(exception, object: self, visited_exceptions: []) <ide> end <ide> end <ide> <del> def handler_for_rescue(exception, object: self) #:nodoc: <add> def handler_for_rescue(exception, object: self) # :nodoc: <ide> case rescuer = find_rescue_handler(exception) <ide> when Symbol <ide> method = object.method(rescuer) <ide> def rescue_with_handler(exception) <ide> <ide> # Internal handler lookup. Delegates to class method. Some libraries call <ide> # this directly, so keeping it around for compatibility. <del> def handler_for_rescue(exception) #:nodoc: <add> def handler_for_rescue(exception) # :nodoc: <ide> self.class.handler_for_rescue exception, object: self <ide> end <ide> end <ide><path>activesupport/lib/active_support/testing/deprecation.rb <ide> <ide> module ActiveSupport <ide> module Testing <del> module Deprecation #:nodoc: <add> module Deprecation # :nodoc: <ide> def assert_deprecated(match = nil, deprecator = nil, &block) <ide> result, warnings = collect_deprecations(deprecator, &block) <ide> assert !warnings.empty?, "Expected a deprecation warning within the block but received none" <ide><path>activesupport/lib/active_support/testing/isolation.rb <ide> module Testing <ide> module Isolation <ide> require "thread" <ide> <del> def self.included(klass) #:nodoc: <add> def self.included(klass) # :nodoc: <ide> klass.class_eval do <ide> parallelize_me! <ide> end <ide><path>activesupport/lib/active_support/testing/stream.rb <ide> <ide> module ActiveSupport <ide> module Testing <del> module Stream #:nodoc: <add> module Stream # :nodoc: <ide> private <ide> def silence_stream(stream) <ide> old_stream = stream.dup <ide><path>activesupport/lib/active_support/testing/tagged_logging.rb <ide> module ActiveSupport <ide> module Testing <ide> # Logs a "PostsControllerTest: test name" heading before each test to <ide> # make test.log easier to search and follow along with. <del> module TaggedLogging #:nodoc: <add> module TaggedLogging # :nodoc: <ide> attr_writer :tagged_logger <ide> <ide> def before_setup <ide><path>activesupport/lib/active_support/time_with_zone.rb <ide> def as_json(options = nil) <ide> end <ide> end <ide> <del> def init_with(coder) #:nodoc: <add> def init_with(coder) # :nodoc: <ide> initialize(coder["utc"], coder["zone"], coder["time"]) <ide> end <ide> <del> def encode_with(coder) #:nodoc: <add> def encode_with(coder) # :nodoc: <ide> coder.map = { "utc" => utc, "zone" => time_zone, "time" => time } <ide> end <ide> <ide><path>activesupport/lib/active_support/values/time_zone.rb <ide> def country_zones(country_code) <ide> @country_zones[code] ||= load_country_zones(code) <ide> end <ide> <del> def clear #:nodoc: <add> def clear # :nodoc: <ide> @lazy_zones_map = Concurrent::Map.new <ide> @country_zones = Concurrent::Map.new <ide> @zones = nil <ide> def period_for_local(time, dst = true) <ide> tzinfo.period_for_local(time, dst) { |periods| periods.last } <ide> end <ide> <del> def periods_for_local(time) #:nodoc: <add> def periods_for_local(time) # :nodoc: <ide> tzinfo.periods_for_local(time) <ide> end <ide> <del> def init_with(coder) #:nodoc: <add> def init_with(coder) # :nodoc: <ide> initialize(coder["name"]) <ide> end <ide> <del> def encode_with(coder) #:nodoc: <add> def encode_with(coder) # :nodoc: <ide> coder.tag = "!ruby/object:#{self.class}" <ide> coder.map = { "name" => tzinfo.name } <ide> end <ide><path>activesupport/lib/active_support/xml_mini.rb <ide> module XmlMini <ide> <ide> # This module decorates files deserialized using Hash.from_xml with <ide> # the <tt>original_filename</tt> and <tt>content_type</tt> methods. <del> module FileLike #:nodoc: <add> module FileLike # :nodoc: <ide> attr_writer :original_filename, :content_type <ide> <ide> def original_filename <ide><path>activesupport/lib/active_support/xml_mini/jdom.rb <ide> java_import org.w3c.dom.Node unless defined? Node <ide> <ide> module ActiveSupport <del> module XmlMini_JDOM #:nodoc: <add> module XmlMini_JDOM # :nodoc: <ide> extend self <ide> <ide> CONTENT_KEY = "__content__" <ide><path>activesupport/lib/active_support/xml_mini/libxml.rb <ide> require "stringio" <ide> <ide> module ActiveSupport <del> module XmlMini_LibXML #:nodoc: <add> module XmlMini_LibXML # :nodoc: <ide> extend self <ide> <ide> # Parse an XML Document string or IO into a simple hash using libxml. <ide> def parse(data) <ide> end <ide> end <ide> <del>module LibXML #:nodoc: <del> module Conversions #:nodoc: <del> module Document #:nodoc: <add>module LibXML # :nodoc: <add> module Conversions # :nodoc: <add> module Document # :nodoc: <ide> def to_hash <ide> root.to_hash <ide> end <ide> end <ide> <del> module Node #:nodoc: <add> module Node # :nodoc: <ide> CONTENT_ROOT = "__content__" <ide> <ide> # Convert XML document to hash. <ide><path>activesupport/lib/active_support/xml_mini/libxmlsax.rb <ide> require "stringio" <ide> <ide> module ActiveSupport <del> module XmlMini_LibXMLSAX #:nodoc: <add> module XmlMini_LibXMLSAX # :nodoc: <ide> extend self <ide> <ide> # Class that will build the hash while the XML document <ide><path>activesupport/lib/active_support/xml_mini/nokogiri.rb <ide> require "stringio" <ide> <ide> module ActiveSupport <del> module XmlMini_Nokogiri #:nodoc: <add> module XmlMini_Nokogiri # :nodoc: <ide> extend self <ide> <ide> # Parse an XML Document string or IO into a simple hash using libxml / nokogiri. <ide> def parse(data) <ide> end <ide> end <ide> <del> module Conversions #:nodoc: <del> module Document #:nodoc: <add> module Conversions # :nodoc: <add> module Document # :nodoc: <ide> def to_hash <ide> root.to_hash <ide> end <ide> end <ide> <del> module Node #:nodoc: <add> module Node # :nodoc: <ide> CONTENT_ROOT = "__content__" <ide> <ide> # Convert XML document to hash. <ide><path>activesupport/lib/active_support/xml_mini/nokogirisax.rb <ide> require "stringio" <ide> <ide> module ActiveSupport <del> module XmlMini_NokogiriSAX #:nodoc: <add> module XmlMini_NokogiriSAX # :nodoc: <ide> extend self <ide> <ide> # Class that will build the hash while the XML document <ide><path>activesupport/lib/active_support/xml_mini/rexml.rb <ide> require "stringio" <ide> <ide> module ActiveSupport <del> module XmlMini_REXML #:nodoc: <add> module XmlMini_REXML # :nodoc: <ide> extend self <ide> <ide> CONTENT_KEY = "__content__" <ide><path>guides/source/api_documentation_guidelines.md <ide> An example of this is `ActiveRecord::Core::ClassMethods#arel_table`: <ide> <ide> ```ruby <ide> module ActiveRecord::Core::ClassMethods <del> def arel_table #:nodoc: <add> def arel_table # :nodoc: <ide> # do some magic.. <ide> end <ide> end <ide><path>guides/source/initialization.md <ide> defined in `rails/application.rb`. <ide> The `initialize!` method looks like this: <ide> <ide> ```ruby <del>def initialize!(group = :default) #:nodoc: <add>def initialize!(group = :default) # :nodoc: <ide> raise "Application has been already initialized." if @initialized <ide> run_initializers(group, self) <ide> @initialized = true <ide><path>guides/source/plugins.md <ide> The first step is to update the README file with detailed information about how <ide> * How to add the functionality to the app (several examples of common use cases) <ide> * Warnings, gotchas or tips that might help users and save them time <ide> <del>Once your README is solid, go through and add rdoc comments to all the methods that developers will use. It's also customary to add `#:nodoc:` comments to those parts of the code that are not included in the public API. <add>Once your README is solid, go through and add rdoc comments to all the methods that developers will use. It's also customary to add `# :nodoc:` comments to those parts of the code that are not included in the public API. <ide> <ide> Once your comments are good to go, navigate to your plugin directory and run: <ide> <ide><path>railties/lib/rails/application.rb <ide> def isolate_namespace(mod) <ide> # are changing config.root inside your application definition or having a custom <ide> # Rails application, you will need to add lib to $LOAD_PATH on your own in case <ide> # you need to load files in lib/ during the application configuration as well. <del> def self.add_lib_to_load_path!(root) #:nodoc: <add> def self.add_lib_to_load_path!(root) # :nodoc: <ide> path = File.join root, "lib" <ide> if File.exist?(path) && !$LOAD_PATH.include?(path) <ide> $LOAD_PATH.unshift(path) <ide> end <ide> end <ide> <del> def require_environment! #:nodoc: <add> def require_environment! # :nodoc: <ide> environment = paths["config/environment"].existent.first <ide> require environment if environment <ide> end <ide> <del> def routes_reloader #:nodoc: <add> def routes_reloader # :nodoc: <ide> @routes_reloader ||= RoutesReloader.new <ide> end <ide> <ide> # Returns an array of file paths appended with a hash of <ide> # directories-extensions suitable for ActiveSupport::FileUpdateChecker <ide> # API. <del> def watchable_args #:nodoc: <add> def watchable_args # :nodoc: <ide> files, dirs = config.watchable_files.dup, config.watchable_dirs.dup <ide> <ide> ActiveSupport::Dependencies.autoload_paths.each do |path| <ide> def watchable_args #:nodoc: <ide> <ide> # Initialize the application passing the given group. By default, the <ide> # group is :default <del> def initialize!(group = :default) #:nodoc: <add> def initialize!(group = :default) # :nodoc: <ide> raise "Application has been already initialized." if @initialized <ide> run_initializers(group, self) <ide> @initialized = true <ide> self <ide> end <ide> <del> def initializers #:nodoc: <add> def initializers # :nodoc: <ide> Bootstrap.initializers_for(self) + <ide> railties_initializers(super) + <ide> Finisher.initializers_for(self) <ide> end <ide> <del> def config #:nodoc: <add> def config # :nodoc: <ide> @config ||= Application::Configuration.new(self.class.find_root(self.class.called_from)) <ide> end <ide> <ide> def encrypted(path, key_path: "config/master.key", env_key: "RAILS_MASTER_KEY") <ide> ) <ide> end <ide> <del> def to_app #:nodoc: <add> def to_app # :nodoc: <ide> self <ide> end <ide> <del> def helpers_paths #:nodoc: <add> def helpers_paths # :nodoc: <ide> config.helpers_paths <ide> end <ide> <ide> def eager_load! <ide> protected <ide> alias :build_middleware_stack :app <ide> <del> def run_tasks_blocks(app) #:nodoc: <add> def run_tasks_blocks(app) # :nodoc: <ide> railties.each { |r| r.run_tasks_blocks(app) } <ide> super <ide> load "rails/tasks.rb" <ide> def run_tasks_blocks(app) #:nodoc: <ide> end <ide> end <ide> <del> def run_generators_blocks(app) #:nodoc: <add> def run_generators_blocks(app) # :nodoc: <ide> railties.each { |r| r.run_generators_blocks(app) } <ide> super <ide> end <ide> <del> def run_runner_blocks(app) #:nodoc: <add> def run_runner_blocks(app) # :nodoc: <ide> railties.each { |r| r.run_runner_blocks(app) } <ide> super <ide> end <ide> <del> def run_console_blocks(app) #:nodoc: <add> def run_console_blocks(app) # :nodoc: <ide> railties.each { |r| r.run_console_blocks(app) } <ide> super <ide> end <ide> <del> def run_server_blocks(app) #:nodoc: <add> def run_server_blocks(app) # :nodoc: <ide> railties.each { |r| r.run_server_blocks(app) } <ide> super <ide> end <ide> <ide> # Returns the ordered railties for this application considering railties_order. <del> def ordered_railties #:nodoc: <add> def ordered_railties # :nodoc: <ide> @ordered_railties ||= begin <ide> order = config.railties_order.map do |railtie| <ide> if railtie == :main_app <ide> def ordered_railties #:nodoc: <ide> end <ide> end <ide> <del> def railties_initializers(current) #:nodoc: <add> def railties_initializers(current) # :nodoc: <ide> initializers = [] <ide> ordered_railties.reverse.flatten.each do |r| <ide> if r == self <ide> def railties_initializers(current) #:nodoc: <ide> initializers <ide> end <ide> <del> def default_middleware_stack #:nodoc: <add> def default_middleware_stack # :nodoc: <ide> default_stack = DefaultMiddlewareStack.new(self, config, paths) <ide> default_stack.build_stack <ide> end <ide><path>railties/lib/rails/application/configuration.rb <ide> def session_store(new_session_store = nil, **options) <ide> end <ide> end <ide> <del> def session_store? #:nodoc: <add> def session_store? # :nodoc: <ide> @session_store <ide> end <ide> <ide> def default_log_file <ide> f <ide> end <ide> <del> class Custom #:nodoc: <add> class Custom # :nodoc: <ide> def initialize <ide> @configurations = Hash.new <ide> end <ide><path>railties/lib/rails/code_statistics.rb <ide> require "rails/code_statistics_calculator" <ide> require "active_support/core_ext/enumerable" <ide> <del>class CodeStatistics #:nodoc: <add>class CodeStatistics # :nodoc: <ide> TEST_TYPES = ["Controller tests", <ide> "Helper tests", <ide> "Model tests", <ide><path>railties/lib/rails/code_statistics_calculator.rb <ide> # frozen_string_literal: true <ide> <del>class CodeStatisticsCalculator #:nodoc: <add>class CodeStatisticsCalculator # :nodoc: <ide> attr_reader :lines, :code_lines, :classes, :methods <ide> <ide> PATTERNS = { <ide><path>railties/lib/rails/command/base.rb <ide> def hide_command! <ide> Rails::Command.hidden_commands << self <ide> end <ide> <del> def inherited(base) #:nodoc: <add> def inherited(base) # :nodoc: <ide> super <ide> <ide> if base.name && !base.name.end_with?("Base") <ide><path>railties/lib/rails/command/behavior.rb <ide> <ide> module Rails <ide> module Command <del> module Behavior #:nodoc: <add> module Behavior # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> class_methods do <ide><path>railties/lib/rails/command/environment_argument.rb <ide> <ide> module Rails <ide> module Command <del> module EnvironmentArgument #:nodoc: <add> module EnvironmentArgument # :nodoc: <ide> extend ActiveSupport::Concern <ide> <ide> included do <ide><path>railties/lib/rails/configuration.rb <ide> def unshift(...) <ide> @operations << -> middleware { middleware.unshift(...) } <ide> end <ide> <del> def merge_into(other) #:nodoc: <add> def merge_into(other) # :nodoc: <ide> (@operations + @delete_operations).each do |operation| <ide> operation.call(other) <ide> end <ide> def +(other) # :nodoc: <ide> attr_reader :operations, :delete_operations <ide> end <ide> <del> class Generators #:nodoc: <add> class Generators # :nodoc: <ide> attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging, :api_only <ide> attr_reader :hidden_namespaces, :after_generate_callbacks <ide> <ide><path>railties/lib/rails/engine.rb <ide> def load_seed <ide> end <ide> end <ide> <del> def routes? #:nodoc: <add> def routes? # :nodoc: <ide> @routes <ide> end <ide> <ide> protected <del> def run_tasks_blocks(*) #:nodoc: <add> def run_tasks_blocks(*) # :nodoc: <ide> super <ide> paths["lib/tasks"].existent.sort.each { |ext| load(ext) } <ide> end <ide> def has_migrations? <ide> paths["db/migrate"].existent.any? <ide> end <ide> <del> def self.find_root_with_flag(flag, root_path, default = nil) #:nodoc: <add> def self.find_root_with_flag(flag, root_path, default = nil) # :nodoc: <ide> while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") <ide> parent = File.dirname(root_path) <ide> root_path = parent != root_path && parent <ide><path>railties/lib/rails/generators.rb <ide> module Generators <ide> } <ide> <ide> class << self <del> def configure!(config) #:nodoc: <add> def configure!(config) # :nodoc: <ide> api_only! if config.api_only <ide> no_color! unless config.colorize_logging <ide> aliases.deep_merge! config.aliases <ide> def configure!(config) #:nodoc: <ide> after_generate_callbacks.replace config.after_generate_callbacks <ide> end <ide> <del> def templates_path #:nodoc: <add> def templates_path # :nodoc: <ide> @templates_path ||= [] <ide> end <ide> <del> def aliases #:nodoc: <add> def aliases # :nodoc: <ide> @aliases ||= DEFAULT_ALIASES.dup <ide> end <ide> <del> def options #:nodoc: <add> def options # :nodoc: <ide> @options ||= DEFAULT_OPTIONS.dup <ide> end <ide> <ide> def sorted_groups <ide> # <ide> # Notice that "rails:generators:webrat" could be loaded as well, what <ide> # Rails looks for is the first and last parts of the namespace. <del> def find_by_namespace(name, base = nil, context = nil) #:nodoc: <add> def find_by_namespace(name, base = nil, context = nil) # :nodoc: <ide> lookups = [] <ide> lookups << "#{base}:#{name}" if base <ide> lookups << "#{name}:#{context}" if context <ide><path>railties/lib/rails/generators/actions/create_migration.rb <ide> module Rails <ide> module Generators <ide> module Actions <del> class CreateMigration < Thor::Actions::CreateFile #:nodoc: <add> class CreateMigration < Thor::Actions::CreateFile # :nodoc: <ide> def migration_dir <ide> File.dirname(@destination) <ide> end <ide><path>railties/lib/rails/generators/base.rb <ide> def self.remove_hook_for(*names) <ide> end <ide> <ide> # Make class option aware of Rails::Generators.options and Rails::Generators.aliases. <del> def self.class_option(name, options = {}) #:nodoc: <add> def self.class_option(name, options = {}) # :nodoc: <ide> options[:desc] = "Indicates when to generate #{name.to_s.humanize.downcase}" unless options.key?(:desc) <ide> options[:aliases] = default_aliases_for_option(name, options) <ide> options[:default] = default_value_for_option(name, options) <ide> def self.base_root <ide> <ide> # Cache source root and add lib/generators/base/generator/templates to <ide> # source paths. <del> def self.inherited(base) #:nodoc: <add> def self.inherited(base) # :nodoc: <ide> super <ide> <ide> # Invoke source_root so the default_source_root is set. <ide> def self.default_for_option(config, name, options, default) # :doc: <ide> end <ide> <ide> # Keep hooks configuration that are used on prepare_for_invocation. <del> def self.hooks #:nodoc: <add> def self.hooks # :nodoc: <ide> @hooks ||= from_superclass(:hooks, {}) <ide> end <ide> <ide> # Prepare class invocation to search on Rails namespace if a previous <ide> # added hook is being used. <del> def self.prepare_for_invocation(name, value) #:nodoc: <add> def self.prepare_for_invocation(name, value) # :nodoc: <ide> return super unless value.is_a?(String) || value.is_a?(Symbol) <ide> <ide> if value && constants = hooks[name] <ide><path>railties/lib/rails/generators/erb.rb <ide> <ide> module Erb # :nodoc: <ide> module Generators # :nodoc: <del> class Base < Rails::Generators::NamedBase #:nodoc: <add> class Base < Rails::Generators::NamedBase # :nodoc: <ide> private <ide> def formats <ide> [format] <ide><path>railties/lib/rails/generators/migration.rb <ide> module Migration <ide> extend ActiveSupport::Concern <ide> attr_reader :migration_number, :migration_file_name, :migration_class_name <ide> <del> module ClassMethods #:nodoc: <add> module ClassMethods # :nodoc: <ide> def migration_lookup_at(dirname) <ide> Dir.glob("#{dirname}/[0-9]*_*.rb") <ide> end <ide><path>railties/lib/rails/generators/model_helpers.rb <ide> module ModelHelpers # :nodoc: <ide> ERROR <ide> mattr_accessor :skip_warn <ide> <del> def self.included(base) #:nodoc: <add> def self.included(base) # :nodoc: <ide> base.class_option :force_plural, type: :boolean, default: false, desc: "Forces the use of the given model name" <ide> end <ide> <ide><path>railties/lib/rails/generators/named_base.rb <ide> module Generators <ide> class NamedBase < Base <ide> argument :name, type: :string <ide> <del> def initialize(args, *options) #:nodoc: <add> def initialize(args, *options) # :nodoc: <ide> @inside_template = nil <ide> # Unfreeze name in case it's given as a frozen string <ide> args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen? <ide><path>railties/lib/rails/generators/resource_helpers.rb <ide> module Generators <ide> # Deal with controller names on scaffold and add some helpers to deal with <ide> # ActiveModel. <ide> module ResourceHelpers # :nodoc: <del> def self.included(base) #:nodoc: <add> def self.included(base) # :nodoc: <ide> base.include(Rails::Generators::ModelHelpers) <ide> base.class_option :model_name, type: :string, desc: "ModelName to be used" <ide> end <ide> <ide> # Set controller variables on initialization. <del> def initialize(*args) #:nodoc: <add> def initialize(*args) # :nodoc: <ide> super <ide> controller_name = name <ide> if options[:model_name] <ide><path>railties/lib/rails/info.rb <ide> def value_for(property_name) <ide> end <ide> end <ide> <del> class << self #:nodoc: <add> class << self # :nodoc: <ide> def property(name, value = nil) <ide> value ||= yield <ide> properties << [name, value] if value <ide><path>railties/lib/rails/initializable.rb <ide> <ide> module Rails <ide> module Initializable <del> def self.included(base) #:nodoc: <add> def self.included(base) # :nodoc: <ide> base.extend ClassMethods <ide> end <ide> <ide><path>railties/lib/rails/railtie.rb <ide> def register_block_for(type, &blk) <ide> <ide> delegate :railtie_name, to: :class <ide> <del> def initialize #:nodoc: <add> def initialize # :nodoc: <ide> if self.class.abstract_railtie? <ide> raise "#{self.class.name} is abstract, you cannot instantiate it directly." <ide> end <ide> end <ide> <del> def configure(&block) #:nodoc: <add> def configure(&block) # :nodoc: <ide> instance_eval(&block) <ide> end <ide> <ide> def config <ide> @config ||= Railtie::Configuration.new <ide> end <ide> <del> def railtie_namespace #:nodoc: <add> def railtie_namespace # :nodoc: <ide> @railtie_namespace ||= self.class.module_parents.detect { |n| n.respond_to?(:railtie_namespace) } <ide> end <ide> <ide> protected <del> def run_console_blocks(app) #:nodoc: <add> def run_console_blocks(app) # :nodoc: <ide> each_registered_block(:console) { |block| block.call(app) } <ide> end <ide> <del> def run_generators_blocks(app) #:nodoc: <add> def run_generators_blocks(app) # :nodoc: <ide> each_registered_block(:generators) { |block| block.call(app) } <ide> end <ide> <del> def run_runner_blocks(app) #:nodoc: <add> def run_runner_blocks(app) # :nodoc: <ide> each_registered_block(:runner) { |block| block.call(app) } <ide> end <ide> <del> def run_tasks_blocks(app) #:nodoc: <add> def run_tasks_blocks(app) # :nodoc: <ide> extend Rake::DSL <ide> each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) } <ide> end <ide> <del> def run_server_blocks(app) #:nodoc: <add> def run_server_blocks(app) # :nodoc: <ide> each_registered_block(:server) { |block| block.call(app) } <ide> end <ide> <ide><path>railties/lib/rails/railtie/configuration.rb <ide> def initialize <ide> end <ide> <ide> # Expose the eager_load_namespaces at "module" level for convenience. <del> def self.eager_load_namespaces #:nodoc: <add> def self.eager_load_namespaces # :nodoc: <ide> @@eager_load_namespaces ||= [] <ide> end <ide>
287
Mixed
Go
use fs cgroups by default
419fd7449fe1a984f582731fcd4d9455000846b0
<ide><path>daemon/execdriver/native/driver.go <ide> func NewDriver(root, initPath string, options []string) (*Driver, error) { <ide> // this makes sure there are no breaking changes to people <ide> // who upgrade from versions without native.cgroupdriver opt <ide> cgm := libcontainer.Cgroupfs <del> if systemd.UseSystemd() { <del> cgm = libcontainer.SystemdCgroups <del> } <ide> <ide> // parse the options <ide> for _, option := range options { <ide><path>docs/reference/commandline/daemon.md <ide> single `native.cgroupdriver` option is available. <ide> <ide> The `native.cgroupdriver` option specifies the management of the container's <ide> cgroups. You can specify `cgroupfs` or `systemd`. If you specify `systemd` and <del>it is not available, the system uses `cgroupfs`. By default, if no option is <del>specified, the execdriver first tries `systemd` and falls back to `cgroupfs`. <del>This example sets the execdriver to `cgroupfs`: <add>it is not available, the system uses `cgroupfs`. If you omit the <add>`native.cgroupdriver` option,` cgroupfs` is used. <add>This example sets the `cgroupdriver` to `systemd`: <ide> <del> $ sudo docker daemon --exec-opt native.cgroupdriver=cgroupfs <add> $ sudo docker daemon --exec-opt native.cgroupdriver=systemd <ide> <ide> Setting this option applies to all containers the daemon launches. <ide>
2
Javascript
Javascript
fix some leftovers
69c71c9332ce8d79c97ca7127e7a1ed531b12bd6
<ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> } <ide> <ide> this.current.fontSize = size; <del> this.ctx.font = this.current.fontSize +'px "' + fontName + '", Symbol'; <add> this.ctx.font = this.current.fontSize +'px "' + fontName + '"'; <ide> }, <ide> setTextRenderingMode: function(mode) { <ide> TODO("text rendering mode"); <ide> var CanvasGraphics = (function() { <ide> // normalize transform matrix so each step <ide> // takes up the entire tmpCanvas (need to remove white borders) <ide> if (matrix[1] === 0 && matrix[2] === 0) { <del> matrix[0] = tmpCanvas.width / xstep; <add> matrix[0] = tmpCanvas.width / xstep; <ide> matrix[3] = tmpCanvas.height / ystep; <ide> topLeft = applyMatrix([x0,y0], matrix); <ide> }
1
Text
Text
update docs to use tf_model_garden gcs bucket
a4b919de434b5eb9662cb035fe8dbebb8e757120
<ide><path>official/nlp/docs/pretrained_models.md <ide> in order to keep consistent with BERT paper. <ide> <ide> Model | Configuration | Training Data | Checkpoint & Vocabulary | TF-HUB SavedModels <ide> ---------------------------------------- | :--------------------------: | ------------: | ----------------------: | ------: <del>BERT-base uncased English | uncased_L-12_H-768_A-12 | Wiki + Books | [uncased_L-12_H-768_A-12](https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/uncased_L-12_H-768_A-12.tar.gz) | [`BERT-Base, Uncased`](https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/) <del>BERT-base cased English | cased_L-12_H-768_A-12 | Wiki + Books | [cased_L-12_H-768_A-12](https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/cased_L-12_H-768_A-12.tar.gz) | [`BERT-Base, Cased`](https://tfhub.dev/tensorflow/bert_en_cased_L-12_H-768_A-12/) <del>BERT-large uncased English | uncased_L-24_H-1024_A-16 | Wiki + Books | [uncased_L-24_H-1024_A-16](https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/uncased_L-24_H-1024_A-16.tar.gz) | [`BERT-Large, Uncased`](https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/) <del>BERT-large cased English | cased_L-24_H-1024_A-16 | Wiki + Books | [cased_L-24_H-1024_A-16](https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/cased_L-24_H-1024_A-16.tar.gz) | [`BERT-Large, Cased`](https://tfhub.dev/tensorflow/bert_en_cased_L-24_H-1024_A-16/) <del>BERT-large, Uncased (Whole Word Masking) | wwm_uncased_L-24_H-1024_A-16 | Wiki + Books | [wwm_uncased_L-24_H-1024_A-16](https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/wwm_uncased_L-24_H-1024_A-16.tar.gz) | [`BERT-Large, Uncased (Whole Word Masking)`](https://tfhub.dev/tensorflow/bert_en_wwm_uncased_L-24_H-1024_A-16/) <del>BERT-large, Cased (Whole Word Masking) | wwm_cased_L-24_H-1024_A-16 | Wiki + Books | [wwm_cased_L-24_H-1024_A-16](https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/wwm_cased_L-24_H-1024_A-16.tar.gz) | [`BERT-Large, Cased (Whole Word Masking)`](https://tfhub.dev/tensorflow/bert_en_wwm_cased_L-24_H-1024_A-16/) <del>BERT-base MultiLingual | multi_cased_L-12_H-768_A-12 | Wiki + Books | [multi_cased_L-12_H-768_A-12](https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/multi_cased_L-12_H-768_A-12.tar.gz) | [`BERT-Base, Multilingual Cased`](https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/) <del>BERT-base Chinese | chinese_L-12_H-768_A-12 | Wiki + Books | [chinese_L-12_H-768_A-12](https://storage.googleapis.com/cloud-tpu-checkpoints/bert/v3/chinese_L-12_H-768_A-12.tar.gz) | [`BERT-Base, Chinese`](https://tfhub.dev/tensorflow/bert_zh_L-12_H-768_A-12/) <add>BERT-base uncased English | uncased_L-12_H-768_A-12 | Wiki + Books | [uncased_L-12_H-768_A-12](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/uncased_L-12_H-768_A-12.tar.gz) | [`BERT-Base, Uncased`](https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/) <add>BERT-base cased English | cased_L-12_H-768_A-12 | Wiki + Books | [cased_L-12_H-768_A-12](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/cased_L-12_H-768_A-12.tar.gz) | [`BERT-Base, Cased`](https://tfhub.dev/tensorflow/bert_en_cased_L-12_H-768_A-12/) <add>BERT-large uncased English | uncased_L-24_H-1024_A-16 | Wiki + Books | [uncased_L-24_H-1024_A-16](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/uncased_L-24_H-1024_A-16.tar.gz) | [`BERT-Large, Uncased`](https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/) <add>BERT-large cased English | cased_L-24_H-1024_A-16 | Wiki + Books | [cased_L-24_H-1024_A-16](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/cased_L-24_H-1024_A-16.tar.gz) | [`BERT-Large, Cased`](https://tfhub.dev/tensorflow/bert_en_cased_L-24_H-1024_A-16/) <add>BERT-large, Uncased (Whole Word Masking) | wwm_uncased_L-24_H-1024_A-16 | Wiki + Books | [wwm_uncased_L-24_H-1024_A-16](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/wwm_uncased_L-24_H-1024_A-16.tar.gz) | [`BERT-Large, Uncased (Whole Word Masking)`](https://tfhub.dev/tensorflow/bert_en_wwm_uncased_L-24_H-1024_A-16/) <add>BERT-large, Cased (Whole Word Masking) | wwm_cased_L-24_H-1024_A-16 | Wiki + Books | [wwm_cased_L-24_H-1024_A-16](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/wwm_cased_L-24_H-1024_A-16.tar.gz) | [`BERT-Large, Cased (Whole Word Masking)`](https://tfhub.dev/tensorflow/bert_en_wwm_cased_L-24_H-1024_A-16/) <add>BERT-base MultiLingual | multi_cased_L-12_H-768_A-12 | Wiki + Books | [multi_cased_L-12_H-768_A-12](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/multi_cased_L-12_H-768_A-12.tar.gz) | [`BERT-Base, Multilingual Cased`](https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/) <add>BERT-base Chinese | chinese_L-12_H-768_A-12 | Wiki + Books | [chinese_L-12_H-768_A-12](https://storage.googleapis.com/tf_model_garden/nlp/bert/v3/chinese_L-12_H-768_A-12.tar.gz) | [`BERT-Base, Chinese`](https://tfhub.dev/tensorflow/bert_zh_L-12_H-768_A-12/) <ide> <ide> You may explore more in the TF-Hub BERT collection: <ide> https://tfhub.dev/google/collections/bert/1
1
Python
Python
add surface area of cuboid, conical frustum
467ade28a04ed3e77b6c89542fd99f390139b5bd
<ide><path>maths/area.py <ide> def surface_area_cube(side_length: float) -> float: <ide> """ <ide> Calculate the Surface Area of a Cube. <del> <ide> >>> surface_area_cube(1) <ide> 6 <add> >>> surface_area_cube(1.6) <add> 15.360000000000003 <add> >>> surface_area_cube(0) <add> 0 <ide> >>> surface_area_cube(3) <ide> 54 <ide> >>> surface_area_cube(-1) <ide> def surface_area_cube(side_length: float) -> float: <ide> return 6 * side_length**2 <ide> <ide> <add>def surface_area_cuboid(length: float, breadth: float, height: float) -> float: <add> """ <add> Calculate the Surface Area of a Cuboid. <add> >>> surface_area_cuboid(1, 2, 3) <add> 22 <add> >>> surface_area_cuboid(0, 0, 0) <add> 0 <add> >>> surface_area_cuboid(1.6, 2.6, 3.6) <add> 38.56 <add> >>> surface_area_cuboid(-1, 2, 3) <add> Traceback (most recent call last): <add> ... <add> ValueError: surface_area_cuboid() only accepts non-negative values <add> >>> surface_area_cuboid(1, -2, 3) <add> Traceback (most recent call last): <add> ... <add> ValueError: surface_area_cuboid() only accepts non-negative values <add> >>> surface_area_cuboid(1, 2, -3) <add> Traceback (most recent call last): <add> ... <add> ValueError: surface_area_cuboid() only accepts non-negative values <add> """ <add> if length < 0 or breadth < 0 or height < 0: <add> raise ValueError("surface_area_cuboid() only accepts non-negative values") <add> return 2 * ((length * breadth) + (breadth * height) + (length * height)) <add> <add> <ide> def surface_area_sphere(radius: float) -> float: <ide> """ <ide> Calculate the Surface Area of a Sphere. <ide> Wikipedia reference: https://en.wikipedia.org/wiki/Sphere <ide> Formula: 4 * pi * r^2 <del> <ide> >>> surface_area_sphere(5) <ide> 314.1592653589793 <ide> >>> surface_area_sphere(1) <ide> 12.566370614359172 <add> >>> surface_area_sphere(1.6) <add> 32.169908772759484 <add> >>> surface_area_sphere(0) <add> 0.0 <ide> >>> surface_area_sphere(-1) <ide> Traceback (most recent call last): <ide> ... <ide> def surface_area_hemisphere(radius: float) -> float: <ide> """ <ide> Calculate the Surface Area of a Hemisphere. <ide> Formula: 3 * pi * r^2 <del> <ide> >>> surface_area_hemisphere(5) <ide> 235.61944901923448 <ide> >>> surface_area_hemisphere(1) <ide> def surface_area_cone(radius: float, height: float) -> float: <ide> Calculate the Surface Area of a Cone. <ide> Wikipedia reference: https://en.wikipedia.org/wiki/Cone <ide> Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5) <del> <ide> >>> surface_area_cone(10, 24) <ide> 1130.9733552923256 <ide> >>> surface_area_cone(6, 8) <ide> 301.59289474462014 <add> >>> surface_area_cone(1.6, 2.6) <add> 23.387862992395807 <add> >>> surface_area_cone(0, 0) <add> 0.0 <ide> >>> surface_area_cone(-1, -2) <ide> Traceback (most recent call last): <ide> ... <ide> def surface_area_cone(radius: float, height: float) -> float: <ide> return pi * radius * (radius + (height**2 + radius**2) ** 0.5) <ide> <ide> <add>def surface_area_conical_frustum( <add> radius_1: float, radius_2: float, height: float <add>) -> float: <add> """ <add> Calculate the Surface Area of a Conical Frustum. <add> >>> surface_area_conical_frustum(1, 2, 3) <add> 45.511728065337266 <add> >>> surface_area_conical_frustum(4, 5, 6) <add> 300.7913575056268 <add> >>> surface_area_conical_frustum(0, 0, 0) <add> 0.0 <add> >>> surface_area_conical_frustum(1.6, 2.6, 3.6) <add> 78.57907060751548 <add> >>> surface_area_conical_frustum(-1, 2, 3) <add> Traceback (most recent call last): <add> ... <add> ValueError: surface_area_conical_frustum() only accepts non-negative values <add> >>> surface_area_conical_frustum(1, -2, 3) <add> Traceback (most recent call last): <add> ... <add> ValueError: surface_area_conical_frustum() only accepts non-negative values <add> >>> surface_area_conical_frustum(1, 2, -3) <add> Traceback (most recent call last): <add> ... <add> ValueError: surface_area_conical_frustum() only accepts non-negative values <add> """ <add> if radius_1 < 0 or radius_2 < 0 or height < 0: <add> raise ValueError( <add> "surface_area_conical_frustum() only accepts non-negative values" <add> ) <add> slant_height = (height**2 + (radius_1 - radius_2) ** 2) ** 0.5 <add> return pi * ((slant_height * (radius_1 + radius_2)) + radius_1**2 + radius_2**2) <add> <add> <ide> def surface_area_cylinder(radius: float, height: float) -> float: <ide> """ <ide> Calculate the Surface Area of a Cylinder. <ide> Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder <ide> Formula: 2 * pi * r * (h + r) <del> <ide> >>> surface_area_cylinder(7, 10) <ide> 747.6990515543707 <add> >>> surface_area_cylinder(1.6, 2.6) <add> 42.22300526424682 <add> >>> surface_area_cylinder(0, 0) <add> 0.0 <ide> >>> surface_area_cylinder(6, 8) <ide> 527.7875658030853 <ide> >>> surface_area_cylinder(-1, -2) <ide> def surface_area_cylinder(radius: float, height: float) -> float: <ide> def area_rectangle(length: float, width: float) -> float: <ide> """ <ide> Calculate the area of a rectangle. <del> <ide> >>> area_rectangle(10, 20) <ide> 200 <add> >>> area_rectangle(1.6, 2.6) <add> 4.16 <add> >>> area_rectangle(0, 0) <add> 0 <ide> >>> area_rectangle(-1, -2) <ide> Traceback (most recent call last): <ide> ... <ide> def area_rectangle(length: float, width: float) -> float: <ide> def area_square(side_length: float) -> float: <ide> """ <ide> Calculate the area of a square. <del> <ide> >>> area_square(10) <ide> 100 <add> >>> area_square(0) <add> 0 <add> >>> area_square(1.6) <add> 2.5600000000000005 <ide> >>> area_square(-1) <ide> Traceback (most recent call last): <ide> ... <ide> def area_square(side_length: float) -> float: <ide> def area_triangle(base: float, height: float) -> float: <ide> """ <ide> Calculate the area of a triangle given the base and height. <del> <ide> >>> area_triangle(10, 10) <ide> 50.0 <add> >>> area_triangle(1.6, 2.6) <add> 2.08 <add> >>> area_triangle(0, 0) <add> 0.0 <ide> >>> area_triangle(-1, -2) <ide> Traceback (most recent call last): <ide> ... <ide> def area_triangle(base: float, height: float) -> float: <ide> def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float: <ide> """ <ide> Calculate area of triangle when the length of 3 sides are known. <del> <ide> This function uses Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula <del> <ide> >>> area_triangle_three_sides(5, 12, 13) <ide> 30.0 <ide> >>> area_triangle_three_sides(10, 11, 12) <ide> 51.521233486786784 <add> >>> area_triangle_three_sides(0, 0, 0) <add> 0.0 <add> >>> area_triangle_three_sides(1.6, 2.6, 3.6) <add> 1.8703742940919619 <ide> >>> area_triangle_three_sides(-1, -2, -1) <ide> Traceback (most recent call last): <ide> ... <ide> def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float <ide> def area_parallelogram(base: float, height: float) -> float: <ide> """ <ide> Calculate the area of a parallelogram. <del> <ide> >>> area_parallelogram(10, 20) <ide> 200 <add> >>> area_parallelogram(1.6, 2.6) <add> 4.16 <add> >>> area_parallelogram(0, 0) <add> 0 <ide> >>> area_parallelogram(-1, -2) <ide> Traceback (most recent call last): <ide> ... <ide> def area_parallelogram(base: float, height: float) -> float: <ide> def area_trapezium(base1: float, base2: float, height: float) -> float: <ide> """ <ide> Calculate the area of a trapezium. <del> <ide> >>> area_trapezium(10, 20, 30) <ide> 450.0 <add> >>> area_trapezium(1.6, 2.6, 3.6) <add> 7.5600000000000005 <add> >>> area_trapezium(0, 0, 0) <add> 0.0 <ide> >>> area_trapezium(-1, -2, -3) <ide> Traceback (most recent call last): <ide> ... <ide> def area_trapezium(base1: float, base2: float, height: float) -> float: <ide> def area_circle(radius: float) -> float: <ide> """ <ide> Calculate the area of a circle. <del> <ide> >>> area_circle(20) <ide> 1256.6370614359173 <add> >>> area_circle(1.6) <add> 8.042477193189871 <add> >>> area_circle(0) <add> 0.0 <ide> >>> area_circle(-1) <ide> Traceback (most recent call last): <ide> ... <ide> def area_circle(radius: float) -> float: <ide> def area_ellipse(radius_x: float, radius_y: float) -> float: <ide> """ <ide> Calculate the area of a ellipse. <del> <ide> >>> area_ellipse(10, 10) <ide> 314.1592653589793 <ide> >>> area_ellipse(10, 20) <ide> 628.3185307179587 <add> >>> area_ellipse(0, 0) <add> 0.0 <add> >>> area_ellipse(1.6, 2.6) <add> 13.06902543893354 <ide> >>> area_ellipse(-10, 20) <ide> Traceback (most recent call last): <ide> ... <ide> def area_ellipse(radius_x: float, radius_y: float) -> float: <ide> def area_rhombus(diagonal_1: float, diagonal_2: float) -> float: <ide> """ <ide> Calculate the area of a rhombus. <del> <ide> >>> area_rhombus(10, 20) <ide> 100.0 <add> >>> area_rhombus(1.6, 2.6) <add> 2.08 <add> >>> area_rhombus(0, 0) <add> 0.0 <ide> >>> area_rhombus(-1, -2) <ide> Traceback (most recent call last): <ide> ... <ide> def area_rhombus(diagonal_1: float, diagonal_2: float) -> float: <ide> print(f"Rhombus: {area_rhombus(10, 20) = }") <ide> print(f"Trapezium: {area_trapezium(10, 20, 30) = }") <ide> print(f"Circle: {area_circle(20) = }") <add> print(f"Ellipse: {area_ellipse(10, 20) = }") <ide> print("\nSurface Areas of various geometric shapes: \n") <ide> print(f"Cube: {surface_area_cube(20) = }") <add> print(f"Cuboid: {surface_area_cuboid(10, 20, 30) = }") <ide> print(f"Sphere: {surface_area_sphere(20) = }") <ide> print(f"Hemisphere: {surface_area_hemisphere(20) = }") <ide> print(f"Cone: {surface_area_cone(10, 20) = }") <add> print(f"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }") <ide> print(f"Cylinder: {surface_area_cylinder(10, 20) = }")
1
Java
Java
use concatwith instead of mergewith
09af706af6857d67708071703c515b3554b2576a
<ide><path>spring-core/src/test/java/org/springframework/core/codec/ByteArrayDecoderTests.java <ide> public void decode() { <ide> public void decodeError() { <ide> DataBuffer fooBuffer = stringBuffer("foo"); <ide> Flux<DataBuffer> source = <del> Flux.just(fooBuffer).mergeWith(Flux.error(new RuntimeException())); <add> Flux.just(fooBuffer).concatWith(Flux.error(new RuntimeException())); <ide> Flux<byte[]> output = this.decoder.decode(source, <ide> ResolvableType.forClassWithGenerics(Publisher.class, byte[].class), <ide> null, Collections.emptyMap()); <ide><path>spring-core/src/test/java/org/springframework/core/codec/ByteBufferDecoderTests.java <ide> public void decode() { <ide> public void decodeError() { <ide> DataBuffer fooBuffer = stringBuffer("foo"); <ide> Flux<DataBuffer> source = <del> Flux.just(fooBuffer).mergeWith(Flux.error(new RuntimeException())); <add> Flux.just(fooBuffer).concatWith(Flux.error(new RuntimeException())); <ide> Flux<ByteBuffer> output = this.decoder.decode(source, <ide> ResolvableType.forClassWithGenerics(Publisher.class, ByteBuffer.class), <ide> null, Collections.emptyMap()); <ide><path>spring-core/src/test/java/org/springframework/core/codec/ResourceDecoderTests.java <ide> public void decode() { <ide> public void decodeError() { <ide> DataBuffer fooBuffer = stringBuffer("foo"); <ide> Flux<DataBuffer> source = <del> Flux.just(fooBuffer).mergeWith(Flux.error(new RuntimeException())); <add> Flux.just(fooBuffer).concatWith(Flux.error(new RuntimeException())); <ide> <ide> <ide> Flux<Resource> result = this.decoder <ide><path>spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java <ide> public void decodeEmptyDataBuffer() { <ide> public void decodeError() { <ide> DataBuffer fooBuffer = stringBuffer("foo\n"); <ide> Flux<DataBuffer> source = <del> Flux.just(fooBuffer).mergeWith(Flux.error(new RuntimeException())); <add> Flux.just(fooBuffer).concatWith(Flux.error(new RuntimeException())); <ide> <ide> Flux<String> output = this.decoder.decode(source, <ide> ResolvableType.forClass(String.class), null, Collections.emptyMap()); <ide><path>spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageReaderTests.java <ide> public void readFormAsFlux() { <ide> public void readFormError() { <ide> DataBuffer fooBuffer = stringBuffer("name=value"); <ide> Flux<DataBuffer> body = <del> Flux.just(fooBuffer).mergeWith(Flux.error(new RuntimeException())); <add> Flux.just(fooBuffer).concatWith(Flux.error(new RuntimeException())); <ide> MockServerHttpRequest request = request(body); <ide> <ide> Flux<MultiValueMap<String, String>> result = this.reader.read(null, request, null); <ide><path>spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java <ide> public void readError() { <ide> <ide> Flux<DataBuffer> body = <ide> Flux.just(stringBuffer("data:foo\ndata:bar\n\ndata:baz\n\n")) <del> .mergeWith(Flux.error(new RuntimeException())); <add> .concatWith(Flux.error(new RuntimeException())); <ide> <ide> MockServerHttpRequest request = MockServerHttpRequest.post("/") <ide> .body(body);
6
PHP
PHP
convert write() to use immutable patterns
8dbd685e3793d359e772bc89dc7ea4a434ee6017
<ide><path>src/Http/Cookie/Cookie.php <ide> class Cookie implements CookieInterface <ide> * @param bool $secure Is secure <ide> * @param bool $httpOnly HTTP Only <ide> */ <del> public function __construct($name, $value = '', $expiresAt = null, $path = '', $domain = '', $secure = false, $httpOnly = false) <del> { <add> public function __construct( <add> $name, <add> $value = '', <add> DateTimeInterface $expiresAt = null, <add> $path = '', <add> $domain = '', <add> $secure = false, <add> $httpOnly = false <add> ) { <ide> $this->validateName($name); <ide> $this->name = $name; <ide> <ide> public function __construct($name, $value = '', $expiresAt = null, $path = '', $ <ide> $this->secure = $secure; <ide> <ide> if ($expiresAt !== null) { <del> $this->expiresAt($expiresAt); <add> $this->expiresAt = (int)$expiresAt->format('U'); <ide> } <ide> } <ide> <ide> public function toHeaderValue() <ide> } <ide> <ide> /** <del> * Sets the cookie name <add> * Create a cookie with an updated name <ide> * <ide> * @param string $name Name of the cookie <del> * @return $this <add> * @return static <ide> */ <del> public function setName($name) <add> public function withName($name) <ide> { <ide> $this->validateName($name); <del> $this->name = $name; <add> $new = clone $this; <add> $new->name = $name; <ide> <del> return $this; <add> return $new; <ide> } <ide> <ide> /** <ide> public function isHttpOnly() <ide> } <ide> <ide> /** <del> * Sets the expiration date <add> * Create a cookie with an updated expiration date <ide> * <ide> * @param \DateTimeInterface $dateTime Date time object <del> * @return $this <add> * @return static <ide> */ <del> public function expiresAt(DateTimeInterface $dateTime) <add> public function withExpiry(DateTimeInterface $dateTime) <ide> { <del> $this->expiresAt = (int)$dateTime->format('U'); <add> $new = clone $this; <add> $new->expiresAt = (int)$dateTime->format('U'); <ide> <del> return $this; <add> return $new; <ide> } <ide> <ide> /** <ide> public function check($path) <ide> } <ide> <ide> /** <del> * Writes data to the cookie <add> * Create a new cookie with updated data. <ide> * <ide> * @param string $path Path to write to <ide> * @param mixed $value Value to write <del> * @return $this <add> * @return static <ide> */ <del> public function write($path, $value) <add> public function withAddedValue($path, $value) <ide> { <ide> $this->_isExpanded(); <add> $new = clone $this; <add> $new->value = Hash::insert($new->value, $path, $value); <ide> <del> Hash::insert($this->value, $path, $value); <add> return $new; <add> } <ide> <del> return $this; <add> /** <add> * Create a new cookie without a specific path <add> * <add> * @param string $path Path to remove <add> * @return static <add> */ <add> public function withoutAddedValue($path) <add> { <add> $this->_isExpanded(); <add> $new = clone $this; <add> $new->value = Hash::remove($new->value, $path); <add> <add> return $new; <ide> } <ide> <ide> /** <ide><path>src/Http/Cookie/CookieInterface.php <ide> interface CookieInterface <ide> * Sets the cookie name <ide> * <ide> * @param string $name Name of the cookie <del> * @return $this <add> * @return static <ide> */ <del> public function setName($name); <add> public function withName($name); <ide> <ide> /** <ide> * Gets the cookie name <ide><path>tests/TestCase/Http/Cookie/CookieTest.php <ide> public function testToHeaderValue() <ide> <ide> $cookie = new Cookie('cakephp', 'cakephp-rocks'); <ide> $cookie = $cookie->withDomain('cakephp.org') <add> ->withExpiry($date) <ide> ->withHttpOnly(true) <ide> ->withSecure(true); <del> $cookie->expiresAt($date); <ide> $result = $cookie->toHeaderValue(); <ide> <ide> $expected = 'cakephp=cakephp-rocks; expires=Tue, 01-Dec-2026 12:00:00 GMT; domain=cakephp.org; secure; httponly'; <ide> public function testWithExpired() <ide> $cookie = new Cookie('cakephp', 'cakephp-rocks'); <ide> $new = $cookie->withExpired(); <ide> $this->assertNotSame($new, $cookie, 'Should clone'); <add> $this->assertNotContains('expiry', $cookie->toHeaderValue()); <ide> <ide> $now = Chronos::parse('-1 year'); <ide> $this->assertContains($now->format('Y'), $new->toHeaderValue()); <ide> } <ide> <add> /** <add> * Test the withExpiry method <add> * <add> * @return void <add> */ <add> public function testWithExpiry() <add> { <add> $cookie = new Cookie('cakephp', 'cakephp-rocks'); <add> $new = $cookie->withExpiry(Chronos::createFromDate(2022, 6, 15)); <add> $this->assertNotSame($new, $cookie, 'Should clone'); <add> $this->assertNotContains('expires', $cookie->toHeaderValue()); <add> <add> $this->assertContains('expires=Wed, 15-Jun-2022', $new->toHeaderValue()); <add> } <add> <add> /** <add> * Test the withName method <add> * <add> * @return void <add> */ <add> public function testWithName() <add> { <add> $cookie = new Cookie('cakephp', 'cakephp-rocks'); <add> $new = $cookie->withName('user'); <add> $this->assertNotSame($new, $cookie, 'Should clone'); <add> $this->assertNotSame('user', $cookie->getName()); <add> $this->assertSame('user', $new->getName()); <add> } <add> <add> /** <add> * Test the withAddedValue method <add> * <add> * @return void <add> */ <add> public function testWithAddedValue() <add> { <add> $cookie = new Cookie('cakephp', '{"type":"mvc", "icing": true}'); <add> $cookie->expand(); <add> $new = $cookie->withAddedValue('type', 'mvc') <add> ->withAddedValue('user.name', 'mark'); <add> $this->assertNotSame($new, $cookie, 'Should clone'); <add> $this->assertNull($cookie->read('user.name')); <add> $this->assertSame('mvc', $new->read('type')); <add> $this->assertSame('mark', $new->read('user.name')); <add> } <add> <add> /** <add> * Test the withoutAddedValue method <add> * <add> * @return void <add> */ <add> public function testWithoutAddedValue() <add> { <add> $cookie = new Cookie('cakephp', '{"type":"mvc", "user": {"name":"mark"}}'); <add> $cookie->expand(); <add> $new = $cookie->withoutAddedValue('type', 'mvc') <add> ->withoutAddedValue('user.name'); <add> $this->assertNotSame($new, $cookie, 'Should clone'); <add> <add> $this->assertNotNull($cookie->read('type')); <add> $this->assertNull($new->read('type')); <add> $this->assertNull($new->read('user.name')); <add> } <add> <ide> /** <ide> * testInflateAndExpand <ide> *
3
Text
Text
add documentation about default scales
8c6335106707309d1b2441c82ac66bd9641c13cd
<ide><path>docs/axes/index.md <ide> Scales in Chart.js >v2.0 are significantly more powerful, but also different tha <ide> * Scale titles are supported. <ide> * New scale types can be extended without writing an entirely new chart type. <ide> <add>## Default scales <add> <add>The default `scaleId`'s for carterian charts are `'x'` and `'y'`. For radial charts: `'r'`. <add>Each dataset is mapped to a scale for each axis (x, y or r) it requires. The scaleId's that a dataset is mapped to, is determined by the `xAxisID`, `yAxisID` or `rAxisID`. <add>If the ID for an axis is not specified, first scale for that axis is used. If no scale for an axis is found, a new scale is created. <add> <add>Some examples: <add> <add>The following chart will have `'x'` and `'y'` scales: <add> <add>```js <add>let chart = new Chart(ctx, { <add> type: 'line' <add>}); <add>``` <add> <add>The following chart will have scales `'x'` and `'myScale'`: <add> <add>```js <add>let chart = new Chart(ctx, { <add> type: 'bar', <add> data: { <add> datasets: [{ <add> data: [1, 2, 3] <add> }] <add> }, <add> options: { <add> scales: { <add> myScale: { <add> type: 'logarithmic', <add> position: 'right', // `axis` is determined by the position as `'y'` <add> } <add> } <add> } <add>}); <add>``` <add> <add>The following chart will have scales `'xAxis'` and `'yAxis'`: <add> <add>```js <add>let chart = new Chart(ctx, { <add> type: 'bar', <add> data: { <add> datasets: [{ <add> yAxisID: 'yAxis' <add> }] <add> }, <add> options: { <add> scales: { <add> xAxis: { <add> // The axis for this scale is determined from the first letter of the id as `'x'` <add> // It is recommended to specify `position` and / or `axis` explicitly. <add> type: 'time', <add> } <add> } <add> } <add>}); <add>``` <add> <add>The following chart will have `'r'` scale: <add> <add>```js <add>let chart = new Chart(ctx, { <add> type: 'radar' <add>}); <add>``` <add> <add>The following chart will have `'myScale'` scale: <add> <add>```js <add>let chart = new Chart(ctx, { <add> type: 'radar', <add> scales: { <add> myScale: { <add> axis: 'r' <add> } <add> } <add>}); <add>``` <add> <ide> ## Common Configuration <ide> <ide> !!!include(axes/_common.md)!!!
1
PHP
PHP
refactor the memcache class
25ebe9fb97ee67c8b98830241e20f691790b20ab
<ide><path>system/memcached.php <ide> class Memcached { <ide> */ <ide> public static function instance() <ide> { <del> return ( ! is_null(static::$instance)) ? static::$instance : static::$instance = static::connect(Config::get('cache.servers')); <add> if (is_null(static::$instance)) <add> { <add> static::$instance = static::connect(Config::get('cache.servers')); <add> } <add> <add> return static::$instance; <ide> } <ide> <ide> /**
1
Ruby
Ruby
remove unwanted `to_sym` call
b9c43e0ee9beda5d1587e168695afa80186f8c22
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb <ide> class SchemaCreation < AbstractAdapter::SchemaCreation <ide> private <ide> <ide> def visit_AddColumn(o) <del> sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale) <add> sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale) <ide> sql = "ADD COLUMN #{quote_column_name(o.name)} #{sql_type}" <ide> add_column_options!(sql, column_options(o)) <ide> end
1
Ruby
Ruby
add non-/usr/local bottles support
20c0ddc40100b08f26d274c550ab0051d9831d21
<ide><path>Library/Homebrew/bottles.rb <ide> def bottle_filename f, bottle_revision=nil <ide> end <ide> <ide> def install_bottle? f <del> return true if ARGV.include? '--install-bottle' and MacOS.bottles_supported?(true) <ide> return true if f.downloader and defined? f.downloader.local_bottle_path \ <ide> and f.downloader.local_bottle_path <ide> <ide> def install_bottle? f <ide> return false unless f.pour_bottle? <ide> return false unless f.build.used_options.empty? <ide> return false unless bottle_current?(f) <add> return false if f.bottle.cellar != :any && f.bottle.cellar != HOMEBREW_CELLAR.to_s <ide> <ide> true <ide> end <ide><path>Library/Homebrew/cmd/bottle.rb <ide> def bottle_formula f <ide> <ide> HOMEBREW_CELLAR.cd do <ide> ohai "Bottling #{f.name} #{f.version}..." <add> bottle_relocatable = !quiet_system( <add> 'grep', '--recursive', '--quiet', '--max-count=1', <add> HOMEBREW_CELLAR, "#{f.name}/#{f.version}") <add> cellar = nil <add> if bottle_relocatable <add> cellar = ':any' <add> elsif HOMEBREW_CELLAR.to_s != '/usr/local/Cellar' <add> cellar = "'#{HOMEBREW_CELLAR}'" <add> end <ide> # Use gzip, faster to compress than bzip2, faster to uncompress than bzip2 <ide> # or an uncompressed tarball (and more bandwidth friendly). <ide> safe_system 'tar', 'czf', bottle_path, "#{f.name}/#{f.version}" <ide> sha1 = bottle_path.sha1 <ide> puts "./#{filename}" <ide> puts "bottle do" <add> puts " cellar #{cellar}" if cellar <ide> puts " revision #{bottle_revision}" if bottle_revision > 0 <ide> puts " sha1 '#{sha1}' => :#{MacOS.cat}" <ide> puts "end" <ide><path>Library/Homebrew/formula_support.rb <ide> def verify_download_integrity fn <ide> <ide> class Bottle < SoftwareSpec <ide> attr_writer :url <del> attr_reader :revision, :root_url <add> attr_reader :revision, :root_url, :cellar <ide> # TODO: Can be removed when all bottles migrated to underscored cat symbols. <ide> attr_reader :cat_without_underscores <ide> <ide> def initialize <ide> super <ide> @revision = 0 <add> @cellar = '/usr/local/Cellar' <ide> @cat_without_underscores = false <ide> end <ide> <ide> def root_url val=nil <ide> val.nil? ? @root_url : @root_url = val <ide> end <ide> <add> def cellar val=nil <add> val.nil? ? @cellar : @cellar = val <add> end <add> <ide> def revision val=nil <ide> val.nil? ? @revision : @revision = val <ide> end <ide><path>Library/Homebrew/macos.rb <ide> def bottles_supported? raise_if_failed=false <ide> raise "Bottles are not supported on 32-bit Snow Leopard." <ide> end <ide> <del> unless HOMEBREW_PREFIX.to_s == '/usr/local' <del> return false unless raise_if_failed <del> raise "Bottles are only supported with a /usr/local prefix." <del> end <del> <del> unless HOMEBREW_CELLAR.to_s == '/usr/local/Cellar' <del> return false unless raise_if_failed <del> raise "Bottles are only supported with a /usr/local/Cellar cellar." <del> end <del> <ide> true <ide> end <ide> end <ide><path>Library/Homebrew/test/testball.rb <ide> class SnowLeopardBottleSpecTestBall < Formula <ide> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5' <ide> <ide> bottle do <add> cellar :any <ide> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard <ide> end <ide> <ide> class LionBottleSpecTestBall < Formula <ide> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5' <ide> <ide> bottle do <add> cellar :any <ide> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :lion <ide> end <ide> <ide> class AllCatsBottleSpecTestBall < Formula <ide> sha1 '482e737739d946b7c8cbaf127d9ee9c148b999f5' <ide> <ide> bottle do <add> cellar '/private/tmp/testbrew/cellar' <ide> sha1 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' => :snow_leopard <ide> sha1 'baadf00dbaadf00dbaadf00dbaadf00dbaadf00d' => :lion <ide> sha1 '8badf00d8badf00d8badf00d8badf00d8badf00d' => :mountain_lion
5
Python
Python
check lower limit of base in base_repr
857c3a8ec160a618a54edd9407f77fbfc2a07678
<ide><path>numpy/core/numeric.py <ide> def base_repr(number, base=2, padding=0): <ide> digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' <ide> if base > len(digits): <ide> raise ValueError("Bases greater than 36 not handled in base_repr.") <add> elif base < 2: <add> raise ValueError("Bases less than 2 not handled in base_repr.") <ide> <ide> num = abs(number) <ide> res = []
1
Text
Text
update changelog for 2.8.4
9f0aaa2e79528d48b3d60743dd78eb94f1673da8
<ide><path>CHANGELOG.md <ide> Changelog <ide> ========= <ide> <add>### 2.8.4 [See full changelog](https://gist.github.com/ichernev/a4fcb0a46d74e4b9b996) <add> <add>Features: <add> <add>* [#2000](https://github.com/moment/moment/issues/2000) Add LTS localised format that includes seconds <add>* [#1960](https://github.com/moment/moment/issues/1960) added formatToken 'x' for unix offset in milliseconds #1938 <add>* [#1965](https://github.com/moment/moment/issues/1965) Support 24:00:00.000 to mean next day, at midnight. <add>* [#2002](https://github.com/moment/moment/issues/2002) Accept 'date' key when creating moment with object <add>* [#2009](https://github.com/moment/moment/issues/2009) Use native toISOString when we can <add> <add>Some bugfixes and language improvements -- [full changelog](https://gist.github.com/ichernev/a4fcb0a46d74e4b9b996) <add> <ide> ### 2.8.3 <ide> <ide> Bugfixes:
1
Go
Go
use gotest.tools/v3/assert more
71119a5649ae44b25b0ab5cdb589c6000a448c25
<ide><path>daemon/logger/awslogs/cloudwatchlogs_test.go <ide> func TestCreateSuccess(t *testing.T) { <ide> <ide> err := stream.create() <ide> <del> if err != nil { <del> t.Errorf("Received unexpected err: %v\n", err) <del> } <del> if input.LogGroupName == nil { <del> t.Fatal("Expected non-nil LogGroupName") <del> } <del> if *input.LogGroupName != groupName { <del> t.Errorf("Expected LogGroupName to be %s", groupName) <del> } <del> if input.LogStreamName == nil { <del> t.Fatal("Expected non-nil LogStreamName") <del> } <del> if *input.LogStreamName != streamName { <del> t.Errorf("Expected LogStreamName to be %s", streamName) <del> } <add> assert.NilError(t, err) <add> assert.Equal(t, groupName, aws.StringValue(input.LogGroupName), "LogGroupName") <add> assert.Equal(t, streamName, aws.StringValue(input.LogStreamName), "LogStreamName") <ide> } <ide> <ide> func TestCreateStreamSkipped(t *testing.T) { <ide> func TestCreateStreamSkipped(t *testing.T) { <ide> <ide> err := stream.create() <ide> <del> if err != nil { <del> t.Errorf("Received unexpected err: %v\n", err) <del> } <add> assert.NilError(t, err) <ide> } <ide> <ide> func TestCreateLogGroupSuccess(t *testing.T) { <ide> func TestCreateLogGroupSuccess(t *testing.T) { <ide> <ide> err := stream.create() <ide> <del> if err != nil { <del> t.Errorf("Received unexpected err: %v\n", err) <del> } <add> assert.NilError(t, err) <ide> if createLogStreamCalls < 2 { <ide> t.Errorf("Expected CreateLogStream to be called twice, was called %d times", createLogStreamCalls) <ide> } <del> if logGroupInput == nil { <del> t.Fatal("LogGroupInput should not be nil") <del> } <del> if logGroupInput.LogGroupName == nil { <del> t.Fatal("Expected non-nil LogGroupName in CreateLogGroup") <del> } <del> if *logGroupInput.LogGroupName != groupName { <del> t.Errorf("Expected LogGroupName to be %s in CreateLogGroup", groupName) <del> } <del> if logStreamInput.LogGroupName == nil { <del> t.Fatal("Expected non-nil LogGroupName in CreateLogStream") <del> } <del> if *logStreamInput.LogGroupName != groupName { <del> t.Errorf("Expected LogGroupName to be %s in CreateLogStream", groupName) <del> } <del> if logStreamInput.LogStreamName == nil { <del> t.Fatal("Expected non-nil LogStreamName") <del> } <del> if *logStreamInput.LogStreamName != streamName { <del> t.Errorf("Expected LogStreamName to be %s", streamName) <del> } <add> assert.Check(t, logGroupInput != nil) <add> assert.Equal(t, groupName, aws.StringValue(logGroupInput.LogGroupName), "LogGroupName in LogGroupInput") <add> assert.Check(t, logStreamInput != nil) <add> assert.Equal(t, groupName, aws.StringValue(logStreamInput.LogGroupName), "LogGroupName in LogStreamInput") <add> assert.Equal(t, streamName, aws.StringValue(logStreamInput.LogStreamName), "LogStreamName in LogStreamInput") <ide> } <ide> <ide> func TestCreateError(t *testing.T) { <ide> func TestLogClosed(t *testing.T) { <ide> closed: true, <ide> } <ide> err := stream.Log(&logger.Message{}) <del> if err == nil { <del> t.Fatal("Expected non-nil error") <del> } <add> assert.Check(t, err != nil) <ide> } <ide> <ide> // TestLogBlocking tests that the Log method blocks appropriately when <ide> func TestLogNonBlockingBufferFull(t *testing.T) { <ide> <-started <ide> select { <ide> case err := <-errorCh: <del> if err == nil { <del> t.Fatal("Expected non-nil error") <del> } <add> assert.Check(t, err != nil) <ide> case <-time.After(30 * time.Second): <ide> t.Fatal("Expected Log call to not block") <ide> } <ide> func TestPublishBatchSuccess(t *testing.T) { <ide> } <ide> <ide> stream.publishBatch(testEventBatch(events)) <del> if stream.sequenceToken == nil { <del> t.Fatal("Expected non-nil sequenceToken") <del> } <del> if *stream.sequenceToken != nextSequenceToken { <del> t.Errorf("Expected sequenceToken to be %s, but was %s", nextSequenceToken, *stream.sequenceToken) <del> } <del> if input == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if input.SequenceToken == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput.SequenceToken") <del> } <del> if *input.SequenceToken != sequenceToken { <del> t.Errorf("Expected PutLogEventsInput.SequenceToken to be %s, but was %s", sequenceToken, *input.SequenceToken) <del> } <del> if len(input.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain 1 element, but contains %d", len(input.LogEvents)) <del> } <del> if input.LogEvents[0] != events[0].inputLogEvent { <del> t.Error("Expected event to equal input") <del> } <add> assert.Equal(t, nextSequenceToken, aws.StringValue(stream.sequenceToken), "sequenceToken") <add> assert.Assert(t, input != nil) <add> assert.Equal(t, sequenceToken, aws.StringValue(input.SequenceToken), "input.SequenceToken") <add> assert.Assert(t, len(input.LogEvents) == 1) <add> assert.Equal(t, events[0].inputLogEvent, input.LogEvents[0]) <ide> } <ide> <ide> func TestPublishBatchError(t *testing.T) { <ide> func TestPublishBatchError(t *testing.T) { <ide> } <ide> <ide> stream.publishBatch(testEventBatch(events)) <del> if stream.sequenceToken == nil { <del> t.Fatal("Expected non-nil sequenceToken") <del> } <del> if *stream.sequenceToken != sequenceToken { <del> t.Errorf("Expected sequenceToken to be %s, but was %s", sequenceToken, *stream.sequenceToken) <del> } <add> assert.Equal(t, sequenceToken, aws.StringValue(stream.sequenceToken)) <ide> } <ide> <ide> func TestPublishBatchInvalidSeqSuccess(t *testing.T) { <ide> func TestPublishBatchInvalidSeqSuccess(t *testing.T) { <ide> } <ide> <ide> stream.publishBatch(testEventBatch(events)) <del> if stream.sequenceToken == nil { <del> t.Fatal("Expected non-nil sequenceToken") <del> } <del> if *stream.sequenceToken != nextSequenceToken { <del> t.Errorf("Expected sequenceToken to be %s, but was %s", nextSequenceToken, *stream.sequenceToken) <del> } <del> <del> if len(calls) != 2 { <del> t.Fatalf("Expected two calls to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Equal(t, nextSequenceToken, aws.StringValue(stream.sequenceToken)) <add> assert.Assert(t, len(calls) == 2) <ide> argument := calls[0] <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if argument.SequenceToken == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput.SequenceToken") <del> } <del> if *argument.SequenceToken != sequenceToken { <del> t.Errorf("Expected PutLogEventsInput.SequenceToken to be %s, but was %s", sequenceToken, *argument.SequenceToken) <del> } <del> if len(argument.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain 1 element, but contains %d", len(argument.LogEvents)) <del> } <del> if argument.LogEvents[0] != events[0].inputLogEvent { <del> t.Error("Expected event to equal input") <del> } <add> assert.Assert(t, argument != nil) <add> assert.Equal(t, sequenceToken, aws.StringValue(argument.SequenceToken)) <add> assert.Assert(t, len(argument.LogEvents) == 1) <add> assert.Equal(t, events[0].inputLogEvent, argument.LogEvents[0]) <ide> <ide> argument = calls[1] <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if argument.SequenceToken == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput.SequenceToken") <del> } <del> if *argument.SequenceToken != "token" { <del> t.Errorf("Expected PutLogEventsInput.SequenceToken to be %s, but was %s", "token", *argument.SequenceToken) <del> } <del> if len(argument.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain 1 element, but contains %d", len(argument.LogEvents)) <del> } <del> if argument.LogEvents[0] != events[0].inputLogEvent { <del> t.Error("Expected event to equal input") <del> } <add> assert.Assert(t, argument != nil) <add> assert.Equal(t, "token", aws.StringValue(argument.SequenceToken)) <add> assert.Assert(t, len(argument.LogEvents) == 1) <add> assert.Equal(t, events[0].inputLogEvent, argument.LogEvents[0]) <ide> } <ide> <ide> func TestPublishBatchAlreadyAccepted(t *testing.T) { <ide> func TestPublishBatchAlreadyAccepted(t *testing.T) { <ide> } <ide> <ide> stream.publishBatch(testEventBatch(events)) <del> if stream.sequenceToken == nil { <del> t.Fatal("Expected non-nil sequenceToken") <del> } <del> if *stream.sequenceToken != "token" { <del> t.Errorf("Expected sequenceToken to be %s, but was %s", "token", *stream.sequenceToken) <del> } <del> <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, stream.sequenceToken != nil) <add> assert.Equal(t, "token", aws.StringValue(stream.sequenceToken)) <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if argument.SequenceToken == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput.SequenceToken") <del> } <del> if *argument.SequenceToken != sequenceToken { <del> t.Errorf("Expected PutLogEventsInput.SequenceToken to be %s, but was %s", sequenceToken, *argument.SequenceToken) <del> } <del> if len(argument.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain 1 element, but contains %d", len(argument.LogEvents)) <del> } <del> if argument.LogEvents[0] != events[0].inputLogEvent { <del> t.Error("Expected event to equal input") <del> } <add> assert.Assert(t, argument != nil) <add> assert.Equal(t, sequenceToken, aws.StringValue(argument.SequenceToken)) <add> assert.Assert(t, len(argument.LogEvents) == 1) <add> assert.Equal(t, events[0].inputLogEvent, argument.LogEvents[0]) <ide> } <ide> <ide> func TestCollectBatchSimple(t *testing.T) { <ide> func TestCollectBatchSimple(t *testing.T) { <ide> ticks <- time.Time{} <ide> stream.Close() <ide> <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain 1 element, but contains %d", len(argument.LogEvents)) <del> } <del> if *argument.LogEvents[0].Message != logline { <del> t.Errorf("Expected message to be %s but was %s", logline, *argument.LogEvents[0].Message) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Assert(t, len(argument.LogEvents) == 1) <add> assert.Equal(t, logline, aws.StringValue(argument.LogEvents[0].Message)) <ide> } <ide> <ide> func TestCollectBatchTicker(t *testing.T) { <ide> func TestCollectBatchTicker(t *testing.T) { <ide> ticks <- time.Time{} <ide> // Verify first batch <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> calls = calls[1:] <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != 2 { <del> t.Errorf("Expected LogEvents to contain 2 elements, but contains %d", len(argument.LogEvents)) <del> } <del> if *argument.LogEvents[0].Message != logline+" 1" { <del> t.Errorf("Expected message to be %s but was %s", logline+" 1", *argument.LogEvents[0].Message) <del> } <del> if *argument.LogEvents[1].Message != logline+" 2" { <del> t.Errorf("Expected message to be %s but was %s", logline+" 2", *argument.LogEvents[0].Message) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Assert(t, len(argument.LogEvents) == 2) <add> assert.Equal(t, logline+" 1", aws.StringValue(argument.LogEvents[0].Message)) <add> assert.Equal(t, logline+" 2", aws.StringValue(argument.LogEvents[1].Message)) <ide> <ide> stream.Log(&logger.Message{ <ide> Line: []byte(logline + " 3"), <ide> func TestCollectBatchTicker(t *testing.T) { <ide> <ide> ticks <- time.Time{} <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument = calls[0] <ide> close(called) <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain 1 elements, but contains %d", len(argument.LogEvents)) <del> } <del> if *argument.LogEvents[0].Message != logline+" 3" { <del> t.Errorf("Expected message to be %s but was %s", logline+" 3", *argument.LogEvents[0].Message) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Assert(t, len(argument.LogEvents) == 1) <add> assert.Equal(t, logline+" 3", aws.StringValue(argument.LogEvents[0].Message)) <ide> <ide> stream.Close() <ide> <ide> func TestCollectBatchMultilinePattern(t *testing.T) { <ide> <ide> // Verify single multiline event <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> calls = calls[1:] <ide> assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput") <ide> func TestCollectBatchMultilinePattern(t *testing.T) { <ide> <ide> // Verify single event <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument = calls[0] <ide> close(called) <ide> assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput") <ide> func TestCollectBatchMultilinePatternMaxEventAge(t *testing.T) { <ide> <ide> // Verify single multiline event is flushed after maximum event buffer age (defaultForceFlushInterval) <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> calls = calls[1:] <ide> assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput") <ide> func TestCollectBatchMultilinePatternMaxEventAge(t *testing.T) { <ide> <ide> // Verify the event buffer is truly flushed - we should only receive a single event <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument = calls[0] <ide> close(called) <ide> assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput") <ide> func TestCollectBatchMultilinePatternNegativeEventAge(t *testing.T) { <ide> <ide> // Verify single multiline event is flushed with a negative event buffer age <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> close(called) <ide> assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput") <ide> func TestCollectBatchMultilinePatternMaxEventSize(t *testing.T) { <ide> // We expect a maximum sized event with no new line characters and a <ide> // second short event with a new line character at the end <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> close(called) <ide> assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput") <ide> func TestCollectBatchClose(t *testing.T) { <ide> stream.Close() <ide> <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> close(called) <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain 1 element, but contains %d", len(argument.LogEvents)) <del> } <del> if *argument.LogEvents[0].Message != logline { <del> t.Errorf("Expected message to be %s but was %s", logline, *argument.LogEvents[0].Message) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Assert(t, len(argument.LogEvents) == 1) <add> assert.Equal(t, logline, aws.StringValue((argument.LogEvents[0].Message))) <ide> } <ide> <ide> func TestEffectiveLen(t *testing.T) { <ide> func TestCollectBatchLineSplit(t *testing.T) { <ide> stream.Close() <ide> <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> close(called) <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != 2 { <del> t.Errorf("Expected LogEvents to contain 2 elements, but contains %d", len(argument.LogEvents)) <del> } <del> if *argument.LogEvents[0].Message != longline { <del> t.Errorf("Expected message to be %s but was %s", longline, *argument.LogEvents[0].Message) <del> } <del> if *argument.LogEvents[1].Message != "B" { <del> t.Errorf("Expected message to be %s but was %s", "B", *argument.LogEvents[1].Message) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Assert(t, len(argument.LogEvents) == 2) <add> assert.Equal(t, longline, aws.StringValue(argument.LogEvents[0].Message)) <add> assert.Equal(t, "B", aws.StringValue(argument.LogEvents[1].Message)) <ide> } <ide> <ide> func TestCollectBatchLineSplitWithBinary(t *testing.T) { <ide> func TestCollectBatchLineSplitWithBinary(t *testing.T) { <ide> stream.Close() <ide> <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> close(called) <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != 2 { <del> t.Errorf("Expected LogEvents to contain 2 elements, but contains %d", len(argument.LogEvents)) <del> } <del> if *argument.LogEvents[0].Message != longline { <del> t.Errorf("Expected message to be %s but was %s", longline, *argument.LogEvents[0].Message) <del> } <del> if *argument.LogEvents[1].Message != "\xFD" { <del> t.Errorf("Expected message to be %s but was %s", "\xFD", *argument.LogEvents[1].Message) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Assert(t, len(argument.LogEvents) == 2) <add> assert.Equal(t, longline, aws.StringValue(argument.LogEvents[0].Message)) <add> assert.Equal(t, "\xFD", aws.StringValue(argument.LogEvents[1].Message)) <ide> } <ide> <ide> func TestCollectBatchMaxEvents(t *testing.T) { <ide> func TestCollectBatchMaxEvents(t *testing.T) { <ide> <ide> <-called <ide> <-called <del> if len(calls) != 2 { <del> t.Fatalf("Expected two calls to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 2) <ide> argument := calls[0] <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != maximumLogEventsPerPut { <del> t.Errorf("Expected LogEvents to contain %d elements, but contains %d", maximumLogEventsPerPut, len(argument.LogEvents)) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Check(t, len(argument.LogEvents) == maximumLogEventsPerPut) <ide> <ide> argument = calls[1] <ide> close(called) <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain %d elements, but contains %d", 1, len(argument.LogEvents)) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Assert(t, len(argument.LogEvents) == 1) <ide> } <ide> <ide> func TestCollectBatchMaxTotalBytes(t *testing.T) { <ide> func TestCollectBatchMaxTotalBytes(t *testing.T) { <ide> for i := 0; i < expectedPuts; i++ { <ide> <-called <ide> } <del> if len(calls) != expectedPuts { <del> t.Fatalf("Expected %d calls to PutLogEvents, was %d: %v", expectedPuts, len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == expectedPuts) <ide> argument := calls[0] <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <add> assert.Assert(t, argument != nil) <ide> <ide> // Should total to the maximum allowed bytes. <ide> eventBytes := 0 <ide> func TestCollectBatchMaxTotalBytes(t *testing.T) { <ide> // don't lend themselves to align with the maximum event size. <ide> lowestMaxBatch := maximumBytesPerPut - maximumBytesPerEvent <ide> <del> if payloadTotal > maximumBytesPerPut { <del> t.Errorf("Expected <= %d bytes but was %d", maximumBytesPerPut, payloadTotal) <del> } <del> if payloadTotal < lowestMaxBatch { <del> t.Errorf("Batch to be no less than %d but was %d", lowestMaxBatch, payloadTotal) <del> } <add> assert.Check(t, payloadTotal <= maximumBytesPerPut) <add> assert.Check(t, payloadTotal >= lowestMaxBatch) <ide> <ide> argument = calls[1] <del> if len(argument.LogEvents) != 1 { <del> t.Errorf("Expected LogEvents to contain 1 elements, but contains %d", len(argument.LogEvents)) <del> } <add> assert.Assert(t, len(argument.LogEvents) == 1) <ide> message := *argument.LogEvents[len(argument.LogEvents)-1].Message <del> if message[len(message)-1:] != "B" { <del> t.Errorf("Expected message to be %s but was %s", "B", message[len(message)-1:]) <del> } <add> assert.Equal(t, "B", message[len(message)-1:]) <ide> } <ide> <ide> func TestCollectBatchMaxTotalBytesWithBinary(t *testing.T) { <ide> func TestCollectBatchMaxTotalBytesWithBinary(t *testing.T) { <ide> for i := 0; i < expectedPuts; i++ { <ide> <-called <ide> } <del> if len(calls) != expectedPuts { <del> t.Fatalf("Expected %d calls to PutLogEvents, was %d: %v", expectedPuts, len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == expectedPuts) <ide> argument := calls[0] <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <add> assert.Assert(t, argument != nil) <ide> <ide> // Should total to the maximum allowed bytes. <ide> eventBytes := 0 <ide> func TestCollectBatchMaxTotalBytesWithBinary(t *testing.T) { <ide> // don't lend themselves to align with the maximum event size. <ide> lowestMaxBatch := maximumBytesPerPut - maximumBytesPerEvent <ide> <del> if payloadTotal > maximumBytesPerPut { <del> t.Errorf("Expected <= %d bytes but was %d", maximumBytesPerPut, payloadTotal) <del> } <del> if payloadTotal < lowestMaxBatch { <del> t.Errorf("Batch to be no less than %d but was %d", lowestMaxBatch, payloadTotal) <del> } <add> assert.Check(t, payloadTotal <= maximumBytesPerPut) <add> assert.Check(t, payloadTotal >= lowestMaxBatch) <ide> <ide> argument = calls[1] <ide> message := *argument.LogEvents[len(argument.LogEvents)-1].Message <del> if message[len(message)-1:] != "B" { <del> t.Errorf("Expected message to be %s but was %s", "B", message[len(message)-1:]) <del> } <add> assert.Equal(t, "B", message[len(message)-1:]) <ide> } <ide> <ide> func TestCollectBatchWithDuplicateTimestamps(t *testing.T) { <ide> func TestCollectBatchWithDuplicateTimestamps(t *testing.T) { <ide> stream.Close() <ide> <ide> <-called <del> if len(calls) != 1 { <del> t.Fatalf("Expected one call to PutLogEvents, was %d: %v", len(calls), calls) <del> } <add> assert.Assert(t, len(calls) == 1) <ide> argument := calls[0] <ide> close(called) <del> if argument == nil { <del> t.Fatal("Expected non-nil PutLogEventsInput") <del> } <del> if len(argument.LogEvents) != times { <del> t.Errorf("Expected LogEvents to contain %d elements, but contains %d", times, len(argument.LogEvents)) <del> } <add> assert.Assert(t, argument != nil) <add> assert.Assert(t, len(argument.LogEvents) == times) <ide> for i := 0; i < times; i++ { <ide> if !reflect.DeepEqual(*argument.LogEvents[i], *expectedEvents[i]) { <ide> t.Errorf("Expected event to be %v but was %v", *expectedEvents[i], *argument.LogEvents[i]) <ide> func TestCreateTagSuccess(t *testing.T) { <ide> assert.Equal(t, 1, len(calls)) <ide> argument := calls[0] <ide> <del> if *argument.LogStreamName != "test-container/container-abcdefghijklmnopqrstuvwxyz01234567890" { <del> t.Errorf("Expected LogStreamName to be %s", "test-container/container-abcdefghijklmnopqrstuvwxyz01234567890") <del> } <add> assert.Equal(t, "test-container/container-abcdefghijklmnopqrstuvwxyz01234567890", aws.StringValue(argument.LogStreamName)) <ide> } <ide> <ide> func BenchmarkUnwrapEvents(b *testing.B) {
1
Go
Go
improve aufs cleanup and debugging
43899a77bf638d4baa42291c1988bcb2a75e8ef5
<ide><path>graphdriver/aufs/aufs.go <ide> func (a *AufsDriver) Remove(id string) error { <ide> return err <ide> } <ide> realPath := path.Join(a.rootPath(), p, id) <del> if err := os.Rename(realPath, tmp); err != nil { <add> if err := os.Rename(realPath, tmp); err != nil && !os.IsNotExist(err) { <ide> return err <ide> } <ide> defer os.RemoveAll(tmp) <ide> } <ide> <ide> // Remove the layers file for the id <del> return os.Remove(path.Join(a.rootPath(), "layers", id)) <add> if err := os.Remove(path.Join(a.rootPath(), "layers", id)); err != nil && !os.IsNotExist(err) { <add> return err <add> } <add> return nil <ide> } <ide> <ide> // Return the rootfs path for the id <ide> func (a *AufsDriver) Cleanup() error { <ide> } <ide> for _, id := range ids { <ide> if err := a.unmount(id); err != nil { <del> return err <add> utils.Errorf("Unmounting %s: %s", utils.TruncateID(id), err) <ide> } <ide> } <ide> return nil <ide><path>runtime.go <ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) { <ide> } <ide> <ide> func (runtime *Runtime) Close() error { <del> runtime.networkManager.Close() <del> runtime.driver.Cleanup() <del> return runtime.containerGraph.Close() <add> errorsStrings := []string{} <add> if err := runtime.networkManager.Close(); err != nil { <add> utils.Errorf("runtime.networkManager.Close(): %s", err.Error()) <add> errorsStrings = append(errorsStrings, err.Error()) <add> } <add> if err := runtime.driver.Cleanup(); err != nil { <add> utils.Errorf("runtime.driver.Cleanup(): %s", err.Error()) <add> errorsStrings = append(errorsStrings, err.Error()) <add> } <add> if err := runtime.containerGraph.Close(); err != nil { <add> utils.Errorf("runtime.containerGraph.Close(): %s", err.Error()) <add> errorsStrings = append(errorsStrings, err.Error()) <add> } <add> if len(errorsStrings) > 0 { <add> return fmt.Errorf("%s", strings.Join(errorsStrings, ", ")) <add> } <add> return nil <ide> } <ide> <ide> func (runtime *Runtime) Mount(container *Container) error {
2
PHP
PHP
apply fixes from styleci
ab149811dca29130ee354d9e9ff448ab81004ec3
<ide><path>src/Illuminate/Database/Eloquent/Relations/Pivot.php <ide> protected function getDeleteQuery() <ide> { <ide> return $this->newQuery()->where([ <ide> $this->foreignKey => $this->getAttribute($this->foreignKey), <del> $this->relatedKey => $this->getAttribute($this->relatedKey) <add> $this->relatedKey => $this->getAttribute($this->relatedKey), <ide> ]); <ide> } <ide>
1
Javascript
Javascript
update incorrect comment
1882a198de3ff126a5ed1e321308a112f9e76b86
<ide><path>lib/dependencies/HarmonyExportInitFragment.js <ide> const EMPTY_SET = new Set(); <ide> <ide> class HarmonyExportInitFragment extends InitFragment { <ide> /** <del> * @param {string} exportsArgument the promises that should be awaited <add> * @param {string} exportsArgument the exports identifier <ide> * @param {Map<string, string>} exportMap mapping from used name to exposed variable name <ide> * @param {Set<string>} unusedExports list of unused export names <ide> */
1
Ruby
Ruby
remove deprecated option
b33a24feb0e29986345bec56db0c5f56eacfac56
<ide><path>Library/Homebrew/homebrew_bootsnap.rb <ide> raise "Needs HOMEBREW_TEMP or HOMEBREW_DEFAULT_TEMP!" unless tmp <ide> <ide> Bootsnap.setup( <del> cache_dir: "#{tmp}/homebrew-bootsnap", <del> development_mode: false, # TODO: use ENV["HOMEBREW_DEVELOPER"]?, <del> load_path_cache: true, <del> autoload_paths_cache: true, <del> compile_cache_iseq: true, <del> compile_cache_yaml: true, <add> cache_dir: "#{tmp}/homebrew-bootsnap", <add> development_mode: false, # TODO: use ENV["HOMEBREW_DEVELOPER"]?, <add> load_path_cache: true, <add> compile_cache_iseq: true, <add> compile_cache_yaml: true, <ide> )
1
PHP
PHP
fix windows test
094b1c9b036c1c781cdab342fe5b27ffd2680d10
<ide><path>tests/TestCase/Console/ConsoleIoTest.php <ide> public function testOverwrite() <ide> [str_repeat("\x08", $number), 0], <ide> ['Less text', 0], <ide> [str_repeat(' ', $number - 9), 0], <del> ["\n", 0] <add> [PHP_EOL, 0] <ide> ) <ide> ->will($this->onConsecutiveCalls( <ide> $number,
1
Java
Java
add websocketclient for java websocket (jsr-356)
30ee71ea1a71e05ab7a725a8cda8d3c0b5c68d3a
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/StandardEndpoint.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.reactive.socket.adapter; <add> <add>import java.nio.ByteBuffer; <add>import java.nio.charset.StandardCharsets; <add>import javax.websocket.CloseReason; <add>import javax.websocket.Endpoint; <add>import javax.websocket.EndpointConfig; <add>import javax.websocket.PongMessage; <add>import javax.websocket.Session; <add> <add>import org.reactivestreams.Subscriber; <add>import org.reactivestreams.Subscription; <add> <add>import reactor.core.publisher.MonoProcessor; <add> <add>import org.springframework.core.io.buffer.DataBuffer; <add>import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.web.reactive.socket.CloseStatus; <add>import org.springframework.web.reactive.socket.HandshakeInfo; <add>import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.WebSocketMessage; <add>import org.springframework.web.reactive.socket.WebSocketMessage.Type; <add> <add>/** <add> * {@link Endpoint} delegating events <add> * to a reactive {@link WebSocketHandler} and its session. <add> * <add> * @author Violeta Georgieva <add> * @since 5.0 <add> */ <add>public class StandardEndpoint extends Endpoint { <add> <add> private final WebSocketHandler handler; <add> <add> private final HandshakeInfo info; <add> <add> private final DataBufferFactory bufferFactory; <add> <add> private StandardWebSocketSession delegateSession; <add> <add> private final MonoProcessor<Void> completionMono; <add> <add> <add> public StandardEndpoint(WebSocketHandler handler, HandshakeInfo info, <add> DataBufferFactory bufferFactory) { <add> this(handler, info, bufferFactory, null); <add> } <add> <add> public StandardEndpoint(WebSocketHandler handler, HandshakeInfo info, <add> DataBufferFactory bufferFactory, MonoProcessor<Void> completionMono) { <add> this.handler = handler; <add> this.info = info; <add> this.bufferFactory = bufferFactory; <add> this.completionMono = completionMono; <add> } <add> <add> <add> @Override <add> public void onOpen(Session nativeSession, EndpointConfig config) { <add> <add> this.delegateSession = new StandardWebSocketSession(nativeSession, this.info, this.bufferFactory); <add> <add> nativeSession.addMessageHandler(String.class, message -> { <add> WebSocketMessage webSocketMessage = toMessage(message); <add> this.delegateSession.handleMessage(webSocketMessage.getType(), webSocketMessage); <add> }); <add> nativeSession.addMessageHandler(ByteBuffer.class, message -> { <add> WebSocketMessage webSocketMessage = toMessage(message); <add> this.delegateSession.handleMessage(webSocketMessage.getType(), webSocketMessage); <add> }); <add> nativeSession.addMessageHandler(PongMessage.class, message -> { <add> WebSocketMessage webSocketMessage = toMessage(message); <add> this.delegateSession.handleMessage(webSocketMessage.getType(), webSocketMessage); <add> }); <add> <add> HandlerResultSubscriber resultSubscriber = new HandlerResultSubscriber(); <add> this.handler.handle(this.delegateSession).subscribe(resultSubscriber); <add> } <add> <add> private <T> WebSocketMessage toMessage(T message) { <add> if (message instanceof String) { <add> byte[] bytes = ((String) message).getBytes(StandardCharsets.UTF_8); <add> return new WebSocketMessage(Type.TEXT, this.bufferFactory.wrap(bytes)); <add> } <add> else if (message instanceof ByteBuffer) { <add> DataBuffer buffer = this.bufferFactory.wrap((ByteBuffer) message); <add> return new WebSocketMessage(Type.BINARY, buffer); <add> } <add> else if (message instanceof PongMessage) { <add> DataBuffer buffer = this.bufferFactory.wrap(((PongMessage) message).getApplicationData()); <add> return new WebSocketMessage(Type.PONG, buffer); <add> } <add> else { <add> throw new IllegalArgumentException("Unexpected message type: " + message); <add> } <add> } <add> <add> @Override <add> public void onClose(Session session, CloseReason reason) { <add> if (this.delegateSession != null) { <add> int code = reason.getCloseCode().getCode(); <add> this.delegateSession.handleClose(new CloseStatus(code, reason.getReasonPhrase())); <add> } <add> } <add> <add> @Override <add> public void onError(Session session, Throwable exception) { <add> if (this.delegateSession != null) { <add> this.delegateSession.handleError(exception); <add> } <add> } <add> <add> protected HandshakeInfo getHandshakeInfo() { <add> return this.info; <add> } <add> <add> <add> private final class HandlerResultSubscriber implements Subscriber<Void> { <add> <add> @Override <add> public void onSubscribe(Subscription subscription) { <add> subscription.request(Long.MAX_VALUE); <add> } <add> <add> @Override <add> public void onNext(Void aVoid) { <add> // no op <add> } <add> <add> @Override <add> public void onError(Throwable ex) { <add> if (completionMono != null) { <add> completionMono.onError(ex); <add> } <add> if (delegateSession != null) { <add> int code = CloseStatus.SERVER_ERROR.getCode(); <add> delegateSession.close(new CloseStatus(code, ex.getMessage())); <add> } <add> } <add> <add> @Override <add> public void onComplete() { <add> if (completionMono != null) { <add> completionMono.onComplete(); <add> } <add> if (delegateSession != null) { <add> delegateSession.close(); <add> } <add> } <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/StandardWebSocketHandlerAdapter.java <ide> <ide> package org.springframework.web.reactive.socket.adapter; <ide> <del>import java.nio.ByteBuffer; <del>import java.nio.charset.StandardCharsets; <del>import javax.websocket.CloseReason; <ide> import javax.websocket.Endpoint; <del>import javax.websocket.EndpointConfig; <del>import javax.websocket.PongMessage; <del>import javax.websocket.Session; <ide> <del>import org.reactivestreams.Subscriber; <del>import org.reactivestreams.Subscription; <del> <del>import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <del>import org.springframework.web.reactive.socket.CloseStatus; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <del>import org.springframework.web.reactive.socket.WebSocketMessage; <del>import org.springframework.web.reactive.socket.WebSocketMessage.Type; <ide> <ide> /** <del> * Adapter for Java WebSocket API (JSR-356) {@link Endpoint} delegating events <del> * to a reactive {@link WebSocketHandler} and its session. <add> * Adapter for Java WebSocket API (JSR-356). <ide> * <ide> * @author Violeta Georgieva <ide> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> */ <ide> public class StandardWebSocketHandlerAdapter extends WebSocketHandlerAdapterSupport { <ide> <del> private StandardWebSocketSession delegateSession; <del> <ide> <ide> public StandardWebSocketHandlerAdapter(WebSocketHandler delegate, HandshakeInfo info, <ide> DataBufferFactory bufferFactory) { <ide> public StandardWebSocketHandlerAdapter(WebSocketHandler delegate, HandshakeInfo <ide> <ide> <ide> public Endpoint getEndpoint() { <del> return new StandardEndpoint(); <del> } <del> <del> <del> private class StandardEndpoint extends Endpoint { <del> <del> @Override <del> public void onOpen(Session nativeSession, EndpointConfig config) { <del> <del> delegateSession = new StandardWebSocketSession(nativeSession, getHandshakeInfo(), bufferFactory()); <del> <del> nativeSession.addMessageHandler(String.class, message -> { <del> WebSocketMessage webSocketMessage = toMessage(message); <del> delegateSession.handleMessage(webSocketMessage.getType(), webSocketMessage); <del> }); <del> nativeSession.addMessageHandler(ByteBuffer.class, message -> { <del> WebSocketMessage webSocketMessage = toMessage(message); <del> delegateSession.handleMessage(webSocketMessage.getType(), webSocketMessage); <del> }); <del> nativeSession.addMessageHandler(PongMessage.class, message -> { <del> WebSocketMessage webSocketMessage = toMessage(message); <del> delegateSession.handleMessage(webSocketMessage.getType(), webSocketMessage); <del> }); <del> <del> HandlerResultSubscriber resultSubscriber = new HandlerResultSubscriber(); <del> getDelegate().handle(delegateSession).subscribe(resultSubscriber); <del> } <del> <del> private <T> WebSocketMessage toMessage(T message) { <del> if (message instanceof String) { <del> byte[] bytes = ((String) message).getBytes(StandardCharsets.UTF_8); <del> return new WebSocketMessage(Type.TEXT, bufferFactory().wrap(bytes)); <del> } <del> else if (message instanceof ByteBuffer) { <del> DataBuffer buffer = bufferFactory().wrap((ByteBuffer) message); <del> return new WebSocketMessage(Type.BINARY, buffer); <del> } <del> else if (message instanceof PongMessage) { <del> DataBuffer buffer = bufferFactory().wrap(((PongMessage) message).getApplicationData()); <del> return new WebSocketMessage(Type.PONG, buffer); <del> } <del> else { <del> throw new IllegalArgumentException("Unexpected message type: " + message); <del> } <del> } <del> <del> @Override <del> public void onClose(Session session, CloseReason reason) { <del> if (delegateSession != null) { <del> int code = reason.getCloseCode().getCode(); <del> delegateSession.handleClose(new CloseStatus(code, reason.getReasonPhrase())); <del> } <del> } <del> <del> @Override <del> public void onError(Session session, Throwable exception) { <del> if (delegateSession != null) { <del> delegateSession.handleError(exception); <del> } <del> } <del> } <del> <del> private final class HandlerResultSubscriber implements Subscriber<Void> { <del> <del> @Override <del> public void onSubscribe(Subscription subscription) { <del> subscription.request(Long.MAX_VALUE); <del> } <del> <del> @Override <del> public void onNext(Void aVoid) { <del> // no op <del> } <del> <del> @Override <del> public void onError(Throwable ex) { <del> if (delegateSession != null) { <del> int code = CloseStatus.SERVER_ERROR.getCode(); <del> delegateSession.close(new CloseStatus(code, ex.getMessage())); <del> } <del> } <del> <del> @Override <del> public void onComplete() { <del> if (delegateSession != null) { <del> delegateSession.close(); <del> } <del> } <add> return new StandardEndpoint(getDelegate(), getHandshakeInfo(), bufferFactory()); <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/client/StandardWebSocketClient.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.reactive.socket.client; <add> <add>import java.net.URI; <add>import java.util.Arrays; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.Optional; <add>import javax.websocket.ClientEndpointConfig; <add>import javax.websocket.ContainerProvider; <add>import javax.websocket.Endpoint; <add>import javax.websocket.EndpointConfig; <add>import javax.websocket.HandshakeResponse; <add>import javax.websocket.Session; <add>import javax.websocket.WebSocketContainer; <add>import javax.websocket.ClientEndpointConfig.Configurator; <add> <add>import reactor.core.publisher.Mono; <add>import reactor.core.publisher.MonoProcessor; <add> <add>import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.core.io.buffer.DefaultDataBufferFactory; <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.web.reactive.socket.HandshakeInfo; <add>import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.adapter.StandardEndpoint; <add> <add>/** <add> * A Java WebSocket API (JSR-356) based implementation of <add> * {@link WebSocketClient}. <add> * <add> * @author Violeta Georgieva <add> * @since 5.0 <add> */ <add>public class StandardWebSocketClient extends WebSocketClientSupport implements WebSocketClient { <add> <add> private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory(); <add> <add> private final WebSocketContainer wsContainer; <add> <add> <add> /** <add> * Default constructor that calls {@code ContainerProvider.getWebSocketContainer()} <add> * to obtain a (new) {@link WebSocketContainer} instance. <add> */ <add> public StandardWebSocketClient() { <add> this(ContainerProvider.getWebSocketContainer()); <add> } <add> <add> /** <add> * Constructor accepting an existing {@link WebSocketContainer} instance. <add> * @param wsContainer a web socket container <add> */ <add> public StandardWebSocketClient(WebSocketContainer wsContainer) { <add> this.wsContainer = wsContainer; <add> } <add> <add> <add> @Override <add> public Mono<Void> execute(URI url, WebSocketHandler handler) { <add> return execute(url, new HttpHeaders(), handler); <add> } <add> <add> @Override <add> public Mono<Void> execute(URI url, HttpHeaders headers, WebSocketHandler handler) { <add> return connectInternal(url, headers, handler); <add> } <add> <add> private Mono<Void> connectInternal(URI url, HttpHeaders headers, WebSocketHandler handler) { <add> MonoProcessor<Void> processor = MonoProcessor.create(); <add> return Mono.fromCallable(() -> { <add> StandardWebSocketClientConfigurator configurator = <add> new StandardWebSocketClientConfigurator(headers); <add> <add> ClientEndpointConfig endpointConfig = createClientEndpointConfig( <add> configurator, beforeHandshake(url, headers, handler)); <add> <add> HandshakeInfo info = new HandshakeInfo(url, Mono.empty()); <add> <add> Endpoint endpoint = new StandardClientEndpoint(handler, info, <add> this.bufferFactory, configurator, processor); <add> <add> Session session = this.wsContainer.connectToServer(endpoint, endpointConfig, url); <add> return session; <add> }).then(processor); <add> } <add> <add> private ClientEndpointConfig createClientEndpointConfig( <add> StandardWebSocketClientConfigurator configurator, String[] subProtocols) { <add> <add> return ClientEndpointConfig.Builder.create() <add> .configurator(configurator) <add> .preferredSubprotocols(Arrays.asList(subProtocols)) <add> .build(); <add> } <add> <add> <add> private static final class StandardClientEndpoint extends StandardEndpoint { <add> <add> private final StandardWebSocketClientConfigurator configurator; <add> <add> public StandardClientEndpoint(WebSocketHandler handler, HandshakeInfo info, <add> DataBufferFactory bufferFactory, StandardWebSocketClientConfigurator configurator, <add> MonoProcessor<Void> processor) { <add> super(handler, info, bufferFactory, processor); <add> this.configurator = configurator; <add> } <add> <add> @Override <add> public void onOpen(Session nativeSession, EndpointConfig config) { <add> getHandshakeInfo().setHeaders(this.configurator.getResponseHeaders()); <add> getHandshakeInfo().setSubProtocol( <add> Optional.ofNullable(nativeSession.getNegotiatedSubprotocol())); <add> <add> super.onOpen(nativeSession, config); <add> } <add> } <add> <add> <add> private static final class StandardWebSocketClientConfigurator extends Configurator { <add> <add> private final HttpHeaders requestHeaders; <add> <add> private HttpHeaders responseHeaders = new HttpHeaders(); <add> <add> public StandardWebSocketClientConfigurator(HttpHeaders requestHeaders) { <add> this.requestHeaders = requestHeaders; <add> } <add> <add> @Override <add> public void beforeRequest(Map<String, List<String>> requestHeaders) { <add> requestHeaders.putAll(this.requestHeaders); <add> } <add> <add> @Override <add> public void afterResponse(HandshakeResponse response) { <add> response.getHeaders().forEach((k, v) -> responseHeaders.put(k, v)); <add> } <add> <add> public HttpHeaders getResponseHeaders() { <add> return this.responseHeaders; <add> } <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/TomcatRequestUpgradeStrategy.java <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> import javax.websocket.Endpoint; <del>import javax.websocket.server.ServerEndpointConfig; <ide> <ide> import org.apache.tomcat.websocket.server.WsServerContainer; <ide> import reactor.core.publisher.Mono; <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/socket/server/WebSocketIntegrationTests.java <ide> import org.springframework.web.reactive.socket.client.JettyWebSocketClient; <ide> import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; <ide> import org.springframework.web.reactive.socket.client.RxNettyWebSocketClient; <add>import org.springframework.web.reactive.socket.client.StandardWebSocketClient; <ide> import org.springframework.web.reactive.socket.client.WebSocketClient; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> public void echoJettyClient() throws Exception { <ide> client.stop(); <ide> } <ide> <add> @Test <add> public void echoStandardClient() throws Exception { <add> testEcho(new StandardWebSocketClient()); <add> } <add> <ide> private void testEcho(WebSocketClient client) throws URISyntaxException { <ide> int count = 100; <ide> Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index); <ide> public void subProtocolJettyClient() throws Exception { <ide> client.stop(); <ide> } <ide> <add> @Test <add> public void subProtocolStandardClient() throws Exception { <add> testSubProtocol(new StandardWebSocketClient()); <add> } <add> <ide> private void testSubProtocol(WebSocketClient client) throws URISyntaxException { <ide> String protocol = "echo-v1"; <ide> AtomicReference<HandshakeInfo> infoRef = new AtomicReference<>();
5
Javascript
Javascript
fix issues and
f0bf3954fe363eda86a3db170063aba34f1be08e
<ide><path>src/scales/scale.logarithmic.js <ide> module.exports = function(Chart) { <ide> determineDataLimits: function() { <ide> var me = this; <ide> var opts = me.options; <del> var tickOpts = opts.ticks; <ide> var chart = me.chart; <ide> var data = chart.data; <ide> var datasets = data.datasets; <del> var valueOrDefault = helpers.valueOrDefault; <ide> var isHorizontal = me.isHorizontal(); <ide> function IDMatches(meta) { <ide> return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; <ide> module.exports = function(Chart) { <ide> helpers.each(dataset.data, function(rawValue, index) { <ide> var values = valuesPerStack[key]; <ide> var value = +me.getRightValue(rawValue); <del> if (isNaN(value) || meta.data[index].hidden) { <add> // invalid, hidden and negative values are ignored <add> if (isNaN(value) || meta.data[index].hidden || value < 0) { <ide> return; <ide> } <del> <ide> values[index] = values[index] || 0; <del> <del> if (opts.relativePoints) { <del> values[index] = 100; <del> } else { <del> // Don't need to split positive and negative since the log scale can't handle a 0 crossing <del> values[index] += value; <del> } <add> values[index] += value; <ide> }); <ide> } <ide> }); <ide> <ide> helpers.each(valuesPerStack, function(valuesForType) { <del> var minVal = helpers.min(valuesForType); <del> var maxVal = helpers.max(valuesForType); <del> me.min = me.min === null ? minVal : Math.min(me.min, minVal); <del> me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); <add> if (valuesForType.length > 0) { <add> var minVal = helpers.min(valuesForType); <add> var maxVal = helpers.max(valuesForType); <add> me.min = me.min === null ? minVal : Math.min(me.min, minVal); <add> me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); <add> } <ide> }); <ide> <ide> } else { <ide> module.exports = function(Chart) { <ide> if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { <ide> helpers.each(dataset.data, function(rawValue, index) { <ide> var value = +me.getRightValue(rawValue); <del> if (isNaN(value) || meta.data[index].hidden) { <add> // invalid, hidden and negative values are ignored <add> if (isNaN(value) || meta.data[index].hidden || value < 0) { <ide> return; <ide> } <ide> <ide> module.exports = function(Chart) { <ide> }); <ide> } <ide> <add> // Common base implementation to handle ticks.min, ticks.max <add> this.handleTickRangeOptions(); <add> }, <add> handleTickRangeOptions: function() { <add> var me = this; <add> var opts = me.options; <add> var tickOpts = opts.ticks; <add> var valueOrDefault = helpers.valueOrDefault; <add> var DEFAULT_MIN = 1; <add> var DEFAULT_MAX = 10; <add> <ide> me.min = valueOrDefault(tickOpts.min, me.min); <ide> me.max = valueOrDefault(tickOpts.max, me.max); <ide> <ide> module.exports = function(Chart) { <ide> me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1); <ide> me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1); <ide> } else { <del> me.min = 1; <del> me.max = 10; <add> me.min = DEFAULT_MIN; <add> me.max = DEFAULT_MAX; <add> } <add> } <add> if (me.min === null) { <add> me.min = Math.pow(10, Math.floor(helpers.log10(me.max)) - 1); <add> } <add> if (me.max === null) { <add> me.max = me.min !== 0 <add> ? Math.pow(10, Math.floor(helpers.log10(me.min)) + 1) <add> : DEFAULT_MAX; <add> } <add> if (me.minNotZero === null) { <add> if (me.min > 0) { <add> me.minNotZero = me.min; <add> } else if (me.max < 1) { <add> me.minNotZero = Math.pow(10, Math.floor(helpers.log10(me.max))); <add> } else { <add> me.minNotZero = DEFAULT_MIN; <ide> } <ide> } <ide> }, <ide><path>test/specs/scale.logarithmic.tests.js <ide> describe('Logarithmic Scale tests', function() { <ide> expect(chart.scales.yScale1.getLabelForIndex(0, 2)).toBe(150); <ide> }); <ide> <del> it('should get the correct pixel value for a point', function() { <del> var chart = window.acquireChart({ <del> type: 'line', <del> data: { <del> datasets: [{ <del> xAxisID: 'xScale', // for the horizontal scale <del> yAxisID: 'yScale', <del> data: [{x: 10, y: 10}, {x: 5, y: 5}, {x: 1, y: 1}, {x: 25, y: 25}, {x: 78, y: 78}] <del> }], <add> describe('when', function() { <add> var data = [ <add> { <add> data: [1, 39], <add> stack: 'stack' <ide> }, <del> options: { <del> scales: { <del> xAxes: [{ <del> id: 'xScale', <del> type: 'logarithmic' <del> }], <add> { <add> data: [1, 39], <add> stack: 'stack' <add> }, <add> ]; <add> var dataWithEmptyStacks = [ <add> { <add> data: [] <add> }, <add> { <add> data: [] <add> } <add> ].concat(data); <add> var config = [ <add> { <add> axis: 'y', <add> firstTick: 1, // start of the axis (minimum) <add> describe: 'all stacks are defined' <add> }, <add> { <add> axis: 'y', <add> data: dataWithEmptyStacks, <add> firstTick: 1, <add> describe: 'not all stacks are defined' <add> }, <add> { <add> axis: 'y', <add> scale: { <ide> yAxes: [{ <del> id: 'yScale', <del> type: 'logarithmic' <add> ticks: { <add> min: 0 <add> } <ide> }] <del> } <add> }, <add> firstTick: 0, <add> describe: 'all stacks are defined and ticks.min: 0' <add> }, <add> { <add> axis: 'y', <add> data: dataWithEmptyStacks, <add> scale: { <add> yAxes: [{ <add> ticks: { <add> min: 0 <add> } <add> }] <add> }, <add> firstTick: 0, <add> describe: 'not stacks are defined and ticks.min: 0' <add> }, <add> { <add> axis: 'x', <add> firstTick: 1, <add> describe: 'all stacks are defined' <add> }, <add> { <add> axis: 'x', <add> data: dataWithEmptyStacks, <add> firstTick: 1, <add> describe: 'not all stacks are defined' <add> }, <add> { <add> axis: 'x', <add> scale: { <add> xAxes: [{ <add> ticks: { <add> min: 0 <add> } <add> }] <add> }, <add> firstTick: 0, <add> describe: 'all stacks are defined and ticks.min: 0' <add> }, <add> { <add> axis: 'x', <add> data: dataWithEmptyStacks, <add> scale: { <add> xAxes: [{ <add> ticks: { <add> min: 0 <add> } <add> }] <add> }, <add> firstTick: 0, <add> describe: 'not all stacks are defined and ticks.min: 0' <add> }, <add> ]; <add> config.forEach(function(setup) { <add> var scaleConfig = {}; <add> var type, chartStart, chartEnd; <add> <add> if (setup.axis === 'x') { <add> type = 'horizontalBar'; <add> chartStart = 'left'; <add> chartEnd = 'right'; <add> } else { <add> type = 'bar'; <add> chartStart = 'bottom'; <add> chartEnd = 'top'; <ide> } <del> }); <add> scaleConfig[setup.axis + 'Axes'] = [{ <add> type: 'logarithmic' <add> }]; <add> Chart.helpers.extend(scaleConfig, setup.scale); <add> var description = 'dataset has stack option and ' + setup.describe <add> + ' and axis is "' + setup.axis + '";'; <add> describe(description, function() { <add> it('should define the correct axis limits', function() { <add> var chart = window.acquireChart({ <add> type: type, <add> data: { <add> labels: ['category 1', 'category 2'], <add> datasets: setup.data || data, <add> }, <add> options: { <add> scales: scaleConfig <add> } <add> }); <ide> <del> var xScale = chart.scales.xScale; <del> expect(xScale.getPixelForValue(80, 0, 0)).toBeCloseToPixel(495); // right - paddingRight <del> expect(xScale.getPixelForValue(1, 0, 0)).toBeCloseToPixel(37 + 6); // left + paddingLeft + lineSpace <del> expect(xScale.getPixelForValue(10, 0, 0)).toBeCloseToPixel(278 + 6 / 2); // halfway <del> expect(xScale.getPixelForValue(0, 0, 0)).toBeCloseToPixel(37 + 6); // 0 is invalid, put it on the left. <add> var axisID = setup.axis + '-axis-0'; <add> var scale = chart.scales[axisID]; <add> var firstTick = setup.firstTick; <add> var lastTick = 80; // last tick (should be first available tick after: 2 * 39) <add> var start = chart.chartArea[chartStart]; <add> var end = chart.chartArea[chartEnd]; <ide> <del> expect(xScale.getValueForPixel(495)).toBeCloseToPixel(80); <del> expect(xScale.getValueForPixel(48)).toBeCloseTo(1, 1e-4); <del> expect(xScale.getValueForPixel(278)).toBeCloseTo(10, 1e-4); <add> expect(scale.getPixelForValue(firstTick, 0, 0)).toBe(start); <add> expect(scale.getPixelForValue(lastTick, 0, 0)).toBe(end); <ide> <del> var yScale = chart.scales.yScale; <del> expect(yScale.getPixelForValue(80, 0, 0)).toBeCloseToPixel(32); // top + paddingTop <del> expect(yScale.getPixelForValue(1, 0, 0)).toBeCloseToPixel(484); // bottom - paddingBottom <del> expect(yScale.getPixelForValue(10, 0, 0)).toBeCloseToPixel(246); // halfway <del> expect(yScale.getPixelForValue(0, 0, 0)).toBeCloseToPixel(484); // 0 is invalid. force it on bottom <del> <del> expect(yScale.getValueForPixel(32)).toBeCloseTo(80, 1e-4); <del> expect(yScale.getValueForPixel(484)).toBeCloseTo(1, 1e-4); <del> expect(yScale.getValueForPixel(246)).toBeCloseTo(10, 1e-4); <add> expect(scale.getValueForPixel(start)).toBeCloseTo(firstTick, 4); <add> expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4); <add> <add> chart.scales[axisID].options.ticks.reverse = true; // Reverse mode <add> chart.update(); <add> <add> // chartArea might have been resized in update <add> start = chart.chartArea[chartEnd]; <add> end = chart.chartArea[chartStart]; <add> <add> expect(scale.getPixelForValue(firstTick, 0, 0)).toBe(start); <add> expect(scale.getPixelForValue(lastTick, 0, 0)).toBe(end); <add> <add> expect(scale.getValueForPixel(start)).toBeCloseTo(firstTick, 4); <add> expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4); <add> }); <add> }); <add> }); <ide> }); <ide> <del> it('should get the correct pixel value for a point when 0 values are present or min: 0', function() { <add> describe('when', function() { <ide> var config = [ <ide> { <del> dataset: [{x: 0, y: 0}, {x: 10, y: 10}, {x: 1.2, y: 1.2}, {x: 25, y: 25}, {x: 78, y: 78}], <add> dataset: [], <ide> firstTick: 1, // value of the first tick <del> lastTick: 80 <add> lastTick: 10, // value of the last tick <add> describe: 'empty dataset, without ticks.min/max' <add> }, <add> { <add> dataset: [], <add> scale: {stacked: true}, <add> firstTick: 1, <add> lastTick: 10, <add> describe: 'empty dataset, without ticks.min/max, with stacked: true' <add> }, <add> { <add> data: { <add> datasets: [ <add> {data: [], stack: 'stack'}, <add> {data: [], stack: 'stack'}, <add> ], <add> }, <add> type: 'bar', <add> firstTick: 1, <add> lastTick: 10, <add> describe: 'empty dataset with stack option, without ticks.min/max' <add> }, <add> { <add> data: { <add> datasets: [ <add> {data: [], stack: 'stack'}, <add> {data: [], stack: 'stack'}, <add> ], <add> }, <add> type: 'horizontalBar', <add> firstTick: 1, <add> lastTick: 10, <add> describe: 'empty dataset with stack option, without ticks.min/max' <add> }, <add> { <add> dataset: [], <add> scale: {ticks: {min: 1}}, <add> firstTick: 1, <add> lastTick: 10, <add> describe: 'empty dataset, ticks.min: 1, without ticks.max' <add> }, <add> { <add> dataset: [], <add> scale: {ticks: {max: 80}}, <add> firstTick: 1, <add> lastTick: 80, <add> describe: 'empty dataset, ticks.max: 80, without ticks.min' <add> }, <add> { <add> dataset: [], <add> scale: {ticks: {max: 0.8}}, <add> firstTick: 0.01, <add> lastTick: 0.8, <add> describe: 'empty dataset, ticks.max: 0.8, without ticks.min' <add> }, <add> { <add> dataset: [{x: 10, y: 10}, {x: 5, y: 5}, {x: 1, y: 1}, {x: 25, y: 25}, {x: 78, y: 78}], <add> firstTick: 1, <add> lastTick: 80, <add> describe: 'dataset min point {x: 1, y: 1}, max point {x:78, y:78}' <add> }, <add> ]; <add> config.forEach(function(setup) { <add> var axes = [ <add> { <add> id: 'x', // horizontal scale <add> start: 'left', <add> end: 'right' <add> }, <add> { <add> id: 'y', // vertical scale <add> start: 'bottom', <add> end: 'top' <add> } <add> ]; <add> axes.forEach(function(axis) { <add> var expectation = 'min = ' + setup.firstTick + ', max = ' + setup.lastTick; <add> describe(setup.describe + ' and axis is "' + axis.id + '"; expect: ' + expectation + ';', function() { <add> beforeEach(function() { <add> var xScaleConfig = { <add> type: 'logarithmic', <add> }; <add> var yScaleConfig = { <add> type: 'logarithmic', <add> }; <add> var data = setup.data || { <add> datasets: [{ <add> data: setup.dataset <add> }], <add> }; <add> Chart.helpers.extend(xScaleConfig, setup.scale); <add> Chart.helpers.extend(yScaleConfig, setup.scale); <add> Chart.helpers.extend(data, setup.data || {}); <add> this.chart = window.acquireChart({ <add> type: 'line', <add> data: data, <add> options: { <add> scales: { <add> xAxes: [xScaleConfig], <add> yAxes: [yScaleConfig] <add> } <add> } <add> }); <add> }); <add> <add> it('should get the correct pixel value for a point', function() { <add> var chart = this.chart; <add> var axisID = axis.id + '-axis-0'; <add> var scale = chart.scales[axisID]; <add> var firstTick = setup.firstTick; <add> var lastTick = setup.lastTick; <add> var start = chart.chartArea[axis.start]; <add> var end = chart.chartArea[axis.end]; <add> <add> expect(scale.getPixelForValue(firstTick, 0, 0)).toBe(start); <add> expect(scale.getPixelForValue(lastTick, 0, 0)).toBe(end); <add> expect(scale.getPixelForValue(0, 0, 0)).toBe(start); // 0 is invalid, put it at the start. <add> <add> expect(scale.getValueForPixel(start)).toBeCloseTo(firstTick, 4); <add> expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4); <add> <add> chart.scales[axisID].options.ticks.reverse = true; // Reverse mode <add> chart.update(); <add> <add> // chartArea might have been resized in update <add> start = chart.chartArea[axis.end]; <add> end = chart.chartArea[axis.start]; <add> <add> expect(scale.getPixelForValue(firstTick, 0, 0)).toBe(start); <add> expect(scale.getPixelForValue(lastTick, 0, 0)).toBe(end); <add> <add> expect(scale.getValueForPixel(start)).toBeCloseTo(firstTick, 4); <add> expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4); <add> }); <add> }); <add> }); <add> }); <add> }); <add> <add> describe('when', function() { <add> var config = [ <add> { <add> dataset: [], <add> scale: {ticks: {min: 0}}, <add> firstTick: 1, // value of the first tick <add> lastTick: 10, // value of the last tick <add> describe: 'empty dataset, ticks.min: 0, without ticks.max' <add> }, <add> { <add> dataset: [], <add> scale: {ticks: {min: 0, max: 80}}, <add> firstTick: 1, <add> lastTick: 80, <add> describe: 'empty dataset, ticks.min: 0, ticks.max: 80' <add> }, <add> { <add> dataset: [], <add> scale: {ticks: {min: 0, max: 0.8}}, <add> firstTick: 0.1, <add> lastTick: 0.8, <add> describe: 'empty dataset, ticks.min: 0, ticks.max: 0.8' <add> }, <add> { <add> dataset: [{x: 0, y: 0}, {x: 10, y: 10}, {x: 1.2, y: 1.2}, {x: 25, y: 25}, {x: 78, y: 78}], <add> firstTick: 1, <add> lastTick: 80, <add> describe: 'dataset min point {x: 0, y: 0}, max point {x:78, y:78}, minNotZero {x: 1.2, y: 1.2}' <ide> }, <ide> { <ide> dataset: [{x: 0, y: 0}, {x: 10, y: 10}, {x: 6.3, y: 6.3}, {x: 25, y: 25}, {x: 78, y: 78}], <ide> firstTick: 6, <del> lastTick: 80 <add> lastTick: 80, <add> describe: 'dataset min point {x: 0, y: 0}, max point {x:78, y:78}, minNotZero {x: 6.3, y: 6.3}' <ide> }, <ide> { <ide> dataset: [{x: 10, y: 10}, {x: 1.2, y: 1.2}, {x: 25, y: 25}, {x: 78, y: 78}], <ide> scale: {ticks: {min: 0}}, <ide> firstTick: 1, <del> lastTick: 80 <add> lastTick: 80, <add> describe: 'dataset min point {x: 1.2, y: 1.2}, max point {x:78, y:78}, ticks.min: 0' <ide> }, <ide> { <ide> dataset: [{x: 10, y: 10}, {x: 6.3, y: 6.3}, {x: 25, y: 25}, {x: 78, y: 78}], <ide> scale: {ticks: {min: 0}}, <ide> firstTick: 6, <del> lastTick: 80 <add> lastTick: 80, <add> describe: 'dataset min point {x: 6.3, y: 6.3}, max point {x:78, y:78}, ticks.min: 0' <ide> }, <ide> ]; <del> Chart.helpers.each(config, function(setup) { <del> var xScaleConfig = { <del> type: 'logarithmic' <del> }; <del> var yScaleConfig = { <del> type: 'logarithmic' <del> }; <del> Chart.helpers.extend(xScaleConfig, setup.scale); <del> Chart.helpers.extend(yScaleConfig, setup.scale); <del> var chart = window.acquireChart({ <del> type: 'line', <del> data: { <del> datasets: [{ <del> data: setup.dataset <del> }], <del> }, <del> options: { <del> scales: { <del> xAxes: [xScaleConfig], <del> yAxes: [yScaleConfig] <del> } <del> } <del> }); <del> <del> var chartArea = chart.chartArea; <del> var expectations = [ <add> config.forEach(function(setup) { <add> var axes = [ <ide> { <del> id: 'x-axis-0', // horizontal scale <del> axis: 'xAxes', <del> start: chartArea.left, <del> end: chartArea.right <add> id: 'x', // horizontal scale <add> start: 'left', <add> end: 'right' <ide> }, <ide> { <del> id: 'y-axis-0', // vertical scale <del> axis: 'yAxes', <del> start: chartArea.bottom, <del> end: chartArea.top <add> id: 'y', // vertical scale <add> start: 'bottom', <add> end: 'top' <ide> } <ide> ]; <del> Chart.helpers.each(expectations, function(expectation) { <del> var scale = chart.scales[expectation.id]; <del> var firstTick = setup.firstTick; <del> var lastTick = setup.lastTick; <del> var fontSize = chart.options.defaultFontSize; <del> var start = expectation.start; <del> var end = expectation.end; <del> var sign = scale.isHorizontal() ? 1 : -1; <del> <del> expect(scale.getPixelForValue(0, 0, 0)).toBeCloseToPixel(start); <del> expect(scale.getPixelForValue(lastTick, 0, 0)).toBeCloseToPixel(end); <del> expect(scale.getPixelForValue(firstTick, 0, 0)).toBeCloseToPixel(start + sign * fontSize); <del> <del> expect(scale.getValueForPixel(start)).toBeCloseTo(0); <del> expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick); <del> expect(scale.getValueForPixel(start + sign * fontSize)).toBeCloseTo(firstTick); <del> <del> chart.options.scales[expectation.axis][0].ticks.reverse = true; // Reverse mode <del> chart.update(); <del> <del> expect(scale.getPixelForValue(0, 0, 0)).toBeCloseToPixel(end); <del> expect(scale.getPixelForValue(lastTick, 0, 0)).toBeCloseToPixel(start); <del> expect(scale.getPixelForValue(firstTick, 0, 0)).toBeCloseToPixel(end - sign * fontSize); <del> <del> expect(scale.getValueForPixel(end)).toBeCloseTo(0); <del> expect(scale.getValueForPixel(start)).toBeCloseTo(lastTick); <del> expect(scale.getValueForPixel(end - sign * fontSize)).toBeCloseTo(firstTick); <add> axes.forEach(function(axis) { <add> var expectation = 'min = 0, max = ' + setup.lastTick + ', first tick = ' + setup.firstTick; <add> describe(setup.describe + ' and axis is "' + axis.id + '"; expect: ' + expectation + ';', function() { <add> beforeEach(function() { <add> var xScaleConfig = { <add> type: 'logarithmic', <add> }; <add> var yScaleConfig = { <add> type: 'logarithmic', <add> }; <add> var data = setup.data || { <add> datasets: [{ <add> data: setup.dataset <add> }], <add> }; <add> Chart.helpers.extend(xScaleConfig, setup.scale); <add> Chart.helpers.extend(yScaleConfig, setup.scale); <add> Chart.helpers.extend(data, setup.data || {}); <add> this.chart = window.acquireChart({ <add> type: 'line', <add> data: data, <add> options: { <add> scales: { <add> xAxes: [xScaleConfig], <add> yAxes: [yScaleConfig] <add> } <add> } <add> }); <add> }); <add> <add> it('should get the correct pixel value for a point', function() { <add> var chart = this.chart; <add> var axisID = axis.id + '-axis-0'; <add> var scale = chart.scales[axisID]; <add> var firstTick = setup.firstTick; <add> var lastTick = setup.lastTick; <add> var fontSize = chart.options.defaultFontSize; <add> var start = chart.chartArea[axis.start]; <add> var end = chart.chartArea[axis.end]; <add> var sign = scale.isHorizontal() ? 1 : -1; <add> <add> expect(scale.getPixelForValue(0, 0, 0)).toBe(start); <add> expect(scale.getPixelForValue(lastTick, 0, 0)).toBe(end); <add> expect(scale.getPixelForValue(firstTick, 0, 0)).toBe(start + sign * fontSize); <add> <add> expect(scale.getValueForPixel(start)).toBeCloseTo(0, 4); <add> expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4); <add> expect(scale.getValueForPixel(start + sign * fontSize)).toBeCloseTo(firstTick, 4); <add> <add> chart.scales[axisID].options.ticks.reverse = true; // Reverse mode <add> chart.update(); <add> <add> // chartArea might have been resized in update <add> start = chart.chartArea[axis.end]; <add> end = chart.chartArea[axis.start]; <add> <add> expect(scale.getPixelForValue(0, 0, 0)).toBe(start); <add> expect(scale.getPixelForValue(lastTick, 0, 0)).toBe(end); <add> expect(scale.getPixelForValue(firstTick, 0, 0)).toBe(start - sign * fontSize, 4); <add> <add> expect(scale.getValueForPixel(start)).toBeCloseTo(0, 4); <add> expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4); <add> expect(scale.getValueForPixel(start - sign * fontSize)).toBeCloseTo(firstTick, 4); <add> }); <add> }); <ide> }); <ide> }); <ide> });
2
PHP
PHP
add a method to retreive the policies
6d8e53082c188c89f765bf016d1e4bca7802b025
<ide><path>src/Illuminate/Foundation/Support/Providers/AuthServiceProvider.php <ide> public function register() <ide> { <ide> // <ide> } <add> <add> /** <add> * Get the policies defined on the provider. <add> * <add> * @return array <add> */ <add> public function policies() <add> { <add> return $this->policies; <add> } <ide> }
1
Javascript
Javascript
remove wrong @restrict and add missing @param
573d41b73cf67b59b2c9f84ace7f9491793fa179
<ide><path>src/ng/directive/input.js <ide> var ngModelDirective = function() { <ide> /** <ide> * @ngdoc directive <ide> * @name ng.directive:ngChange <del> * @restrict E <ide> * <ide> * @description <ide> * Evaluate given expression when user changes the input. <ide> var ngModelDirective = function() { <ide> * Note, this directive requires `ngModel` to be present. <ide> * <ide> * @element input <add> * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change <add> * in input value. <ide> * <ide> * @example <ide> * <doc:example>
1
Ruby
Ruby
reduce the number of calls to camelize
40761c4bf39826254b7a5266210f91742591f58c
<ide><path>activerecord/lib/active_record/migration.rb <ide> def migrations(path) <ide> <ide> migrations = files.inject([]) do |klasses, file| <ide> version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?.rb/).first <add> name = name.camelize <ide> <ide> raise IllegalMigrationNameError.new(file) unless version <ide> version = version.to_i <ide> def migrations(path) <ide> raise DuplicateMigrationVersionError.new(version) <ide> end <ide> <del> if klasses.detect { |m| m.name == name.camelize && m.scope == scope } <del> raise DuplicateMigrationNameError.new(name.camelize) <add> if klasses.detect { |m| m.name == name && m.scope == scope } <add> raise DuplicateMigrationNameError.new(name) <ide> end <ide> <del> migration = MigrationProxy.new(name.camelize, version, file, scope) <add> migration = MigrationProxy.new(name, version, file, scope) <ide> klasses << migration <ide> end <ide>
1
Text
Text
release notes for v3.27.1
ac201b8e3e52226dbc74daf7be476985f9109a61
<ide><path>CHANGELOG.md <ide> <ide> - [#19472](https://github.com/emberjs/ember.js/pull/19472) [BUGFIX] Prevent transformation of block params called `attrs` <ide> <add>### v3.27.1 (May 13, 2021) <add> <add>- [#19540](https://github.com/emberjs/ember.js/pull/19540) [BUGFIX] Ensure ember-testing is loaded lazily <add>- [#19541](https://github.com/emberjs/ember.js/pull/19541) [BUGFIX] Add missing metadata for some deprecations enabled in 3.27.0 <add>- [#19541](https://github.com/emberjs/ember.js/pull/19541) [BUGFIX] Ensure passing `@href` to `<LinkTo>` throws an error <add>- [#19541](https://github.com/emberjs/ember.js/pull/19541) [CLEANUP] Consistently use https://deprecations.emberjs.com/ in deprecation URLs <add> <ide> ### v3.27.0 (May 3, 2021) <ide> <ide> - [#19309](https://github.com/emberjs/ember.js/pull/19309) / [#19487](https://github.com/emberjs/ember.js/pull/19487) / [#19474](https://github.com/emberjs/ember.js/pull/19474) [FEATURE] Enable `(helper` and `(modifier` helpers per [RFC #432](https://github.com/emberjs/rfcs/blob/master/text/0432-contextual-helpers.md). <ide> - [#19442](https://github.com/emberjs/ember.js/pull/19442) [DEPRECATION] Add deprecation for `Route#render` method per [RFC #418](https://github.com/emberjs/rfcs/blob/master/text/0418-deprecate-route-render-methods.md). <ide> - [#19429](https://github.com/emberjs/ember.js/pull/19429) [DEPRECATION] `registerPlugin` / `unregisterPlugin` and legacy class based AST plugins (private APIs) <ide> - [#19499](https://github.com/emberjs/ember.js/pull/19499) [DEPRECATION] Deprecate `@foo={{helper}}` per [RFC #496](https://github.com/emberjs/rfcs/blob/master/text/0496-handlebars-strict-mode.md#3-no-implicit-invocation-of-argument-less-helpers). <del>- [#19499](https://github.com/emberjs/ember.js/pull/19499) [BUGFIX] Update rendering engine to `@glimmer/*` 0.78.2 for fixes including: <add>- [#19499](https://github.com/emberjs/ember.js/pull/19499) [BUGFIX] Update rendering engine to `@glimmer/*` 0.78.2 for fixes including: <ide> - `<:else>` and `<:inverse>` should be aliases (see https://github.com/glimmerjs/glimmer-vm/pull/1296) <ide> - Fix nested calls to helpers in dynamic helpers (see https://github.com/glimmerjs/glimmer-vm/pull/1293) <ide> - [#19477](https://github.com/emberjs/ember.js/pull/19477) [BUGFIX] Allow `<LinkToExternal />` to override internal assertion <ide> <ide> ### v3.24.0 (December 28, 2020) <ide> <del>- [#19224](https://github.com/emberjs/ember.js/pull/19224) [FEATURE] Add `{{page-title}}` helper to route template blueprints to implement [RFC #0654](https://github.com/emberjs/rfcs/blob/master/text/0645-add-ember-page-title-addon.md). <add>- [#19224](https://github.com/emberjs/ember.js/pull/19224) [FEATURE] Add `{{page-title}}` helper to route template blueprints to implement [RFC #0654](https://github.com/emberjs/rfcs/blob/master/text/0645-add-ember-page-title-addon.md). <ide> - [#19133](https://github.com/emberjs/ember.js/pull/19133) [FEATURE / DEPRECATION] Add new options to `deprecate()` for `for` and `since` and deprecate using `deprecate()` without those options per the [Deprecation Staging RFC](https://github.com/emberjs/rfcs/blob/master/text/0649-deprecation-staging.md). <ide> - [#19211](https://github.com/emberjs/ember.js/pull/19211) [DEPRECATION] Deprecate `Ember.String.loc` and `{{loc}}` per the [Deprecate Ember String RFC](https://github.com/emberjs/rfcs/blob/master/text/0236-deprecation-ember-string.md). <ide> - [#19234](https://github.com/emberjs/ember.js/pull/19234) [DEPRECATION] Deprecate String Prototype extensions per the [Deprecate Ember String RFC](https://github.com/emberjs/rfcs/blob/master/text/0236-deprecation-ember-string.md). <ide> <ide> - [#19160](https://github.com/emberjs/ember.js/pull/19160) / [#19182](https://github.com/emberjs/ember.js/pull/19182) [FEATURE] Implements the helper manager feature specified in the [Helper Managers RFC](https://github.com/emberjs/rfcs/blob/master/text/0625-helper-managers.md). <ide> - [#19171](https://github.com/emberjs/ember.js/pull/19171) / [#19182](https://github.com/emberjs/ember.js/pull/19182) [FEATURE] Implements `invokeHelper` from the [JavaScript Helper Invocation API RFC](https://github.com/emberjs/rfcs/blob/master/text/0626-invoke-helper.md). <del>- [#19148](https://github.com/emberjs/ember.js/pull/19148) / [#19119](https://github.com/emberjs/ember.js/pull/19119) Update rendering engine to `@glimmer/*` 0.62.1 <add>- [#19148](https://github.com/emberjs/ember.js/pull/19148) / [#19119](https://github.com/emberjs/ember.js/pull/19119) Update rendering engine to `@glimmer/*` 0.62.1 <ide> - [#19122](https://github.com/emberjs/ember.js/pull/19122) [BUGFIX] Prevents dynamic invocations of string values when referenced directly in angle brackets <ide> - [#19136](https://github.com/emberjs/ember.js/pull/19136) [BUGFIX] Update router microlib to improve Transition related debugging <ide> - [#19173](https://github.com/emberjs/ember.js/pull/19173) [BUGFIX] Enforce usage of `capabilities` generation. <ide> - [#19062](https://github.com/emberjs/ember.js/pull/19062) / [#19068](https://github.com/emberjs/ember.js/pull/19068) [FEATURE] Add @ember/destroyable feature from the [Destroyables RFC](https://github.com/emberjs/rfcs/blob/master/text/0580-destroyables.md). <ide> - [#18984](https://github.com/emberjs/ember.js/pull/18984) / [#19067](https://github.com/emberjs/ember.js/pull/19067) [FEATURE] Add low-level Cache API per [Autotracking Memoization RFC](https://github.com/emberjs/rfcs/blob/master/text/0615-autotracking-memoization.md) <ide> - [#19086](https://github.com/emberjs/ember.js/pull/19086) [FEATURE] Pass transition object to activate/deactivate hooks and events <del>- [#19094](https://github.com/emberjs/ember.js/pull/19094) [BUGFIX] Fix RouterService#isActive() to work with tracking <add>- [#19094](https://github.com/emberjs/ember.js/pull/19094) [BUGFIX] Fix RouterService#isActive() to work with tracking <ide> - [#19163](https://github.com/emberjs/ember.js/pull/19163) [BUGFIX] Use args proxy for modifier managers. <ide> - [#19170](https://github.com/emberjs/ember.js/pull/19170) [BUGFIX] Make modifier manager 3.22 accept the resolved value directly. <ide> - [#19124](https://github.com/emberjs/ember.js/pull/19124) [BUGFIX] Fix rendering engine usage within a `fastboot` sandbox <ide> <ide> - [#18993](https://github.com/emberjs/ember.js/pull/18993) [DEPRECATION] Deprecate `getWithDefault` per [RFC #554](https://github.com/emberjs/rfcs/blob/master/text/0554-deprecate-getwithdefault.md). <ide> - [#19087](https://github.com/emberjs/ember.js/pull/19087) [BUGFIX] Generated initializer tests no longer causes a deprecation warning <del>- [#17571](https://github.com/emberjs/ember.js/pull/17571) [BUGFIX] Avoid tampering `queryParam` argument in RouterService#isActive <add>- [#17571](https://github.com/emberjs/ember.js/pull/17571) [BUGFIX] Avoid tampering `queryParam` argument in RouterService#isActive <ide> <ide> ### v3.20.6 (November 11, 2020) <ide> <ide> - Fix: Rerender an `{{#each`s block only when the specific item has changed <ide> - [#18958](https://github.com/emberjs/ember.js/pull/18958) [BUGFIX] Ensure AST transforms using `in-element` work properly. <ide> - [#18960](https://github.com/emberjs/ember.js/pull/18960) [BUGFIX] More assertions for Application lifecycle methods <del>- [#18919](https://github.com/emberjs/ember.js/pull/18919) [BUGFIX] Add error for modifier manager without capabilities. <add>- [#18919](https://github.com/emberjs/ember.js/pull/18919) [BUGFIX] Add error for modifier manager without capabilities. <ide> - [#18828](https://github.com/emberjs/ember.js/pull/18828) [BUGFIX] Prepend 'TODO: ' to 'Replace this with your real tests' comments in generated tests <ide> - [#18353](https://github.com/emberjs/ember.js/pull/18353) [BUGFIX] Improve `fn` & `on` undefined callback message <ide> - [#18824](https://github.com/emberjs/ember.js/pull/18824) [CLEANUP] Remove deprecated private `window.ENV`
1
Javascript
Javascript
add workaround for ios jit error in isarraylike
154166458284bcce7d6a86328b7fd13483232a1a
<ide><path>src/core.js <ide> function(i, name) { <ide> }); <ide> <ide> function isArraylike( obj ) { <del> var length = obj.length, <add> <add> // Support: iOS 8.2 (not reproducible in simulator) <add> // `in` check used to prevent JIT error (gh-2145) <add> // hasOwn isn't used here due to false negatives <add> // regarding Nodelist length in IE <add> var length = "length" in obj && obj.length, <ide> type = jQuery.type( obj ); <ide> <ide> if ( type === "function" || jQuery.isWindow( obj ) ) { <ide><path>test/unit/core.js <ide> test("jQuery.each(Object,Function)", function() { <ide> equal( i, document.styleSheets.length, "Iteration over document.styleSheets" ); <ide> }); <ide> <add>test( "JIT compilation does not interfere with length retrieval (gh-2145)", function() { <add> expect( 4 ); <add> <add> var i; <add> <add> // Trigger JIT compilation of jQuery.each – and therefore isArraylike – in iOS. <add> // Convince JSC to use one of its optimizing compilers <add> // by providing code which can be LICM'd into nothing. <add> for ( i = 0; i < 1000; i++ ) { <add> jQuery.each( [] ); <add> } <add> <add> i = 0; <add> jQuery.each( { 1: "1", 2: "2", 3: "3" }, function( index ) { <add> equal( ++i, index, "Iteration over object with solely " + <add> "numeric indices (gh-2145 JIT iOS 8 bug)" ); <add> }); <add> equal( i, 3, "Iteration over object with solely " + <add> "numeric indices (gh-2145 JIT iOS 8 bug)" ); <add>}); <add> <ide> test("jQuery.makeArray", function(){ <ide> expect(15); <ide>
2
Text
Text
add formatted string literals example
6361c48b99d2b6858a821e523fc3bf1303455cd7
<ide><path>guide/english/python/converting-integer-to-string-in-python/index.md <ide> print("Hello, I am " + str(age) + " years old") <ide> ``` <ide> <a href='https://repl.it/Jz8Q/0' target='_blank' rel='nofollow'>Run code on repl.it</a> <ide> <add>Formatted string literals or "f-strings": <add> <add>Python 3.6 (and later) allows strings to be [formatted with minimal syntax](https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals). <add> <add>```py <add>name = "Xochitl" <add>age = 45 <add> <add>f'Hello, my name is {name}, and I am {age} years young.' <add> <add># Output <add># 'Hello, my name is Xochitl, and I am 45 years young.' <add>``` <add> <ide> Print `1 2 3 4 5 6 7 8 9 10` using a single string <ide> ```py <ide> result = "" <ide> print(result) <ide> <ide> <ide> #### More Information: <del><a href='https://docs.python.org/3/library/stdtypes.html#str' target='_blank' rel='nofollow'>Official Python documentation for `str()`</a> <add>- <a href='https://docs.python.org/3/library/stdtypes.html#str' target='_blank' rel='nofollow'>Official Python documentation for `str()`</a> <add> <add>- Official Python documentation for <a href='https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals' target='_blank' rel='nofollow'>_formatted string literals_ or _f-strings_.</a> <ide> <ide> <ide>
1
Java
Java
operatorswitchmap accidental main method
7b0b75cd80928d2ba022e8a3ad7625ae5816a6f0
<ide><path>src/main/java/io/reactivex/internal/operators/OperatorSwitchMap.java <ide> <ide> import org.reactivestreams.*; <ide> <del>import io.reactivex.Observable; <ide> import io.reactivex.Observable.Operator; <ide> import io.reactivex.internal.queue.*; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> public void cancel() { <ide> } <ide> } <ide> } <del> <del> public static void main(String[] args) { <del> Observable.range(1, 10).switchMap(Observable::just).subscribe(System.out::println); <del> } <ide> }
1
PHP
PHP
add the registry alias to debug table debug info
4911a538dbb8316d35408c8a166feada74c5d546
<ide><path>src/ORM/Table.php <ide> public function __debugInfo() <ide> { <ide> $conn = $this->connection(); <ide> return [ <add> 'registryAlias' => $this->registryAlias(), <ide> 'table' => $this->table(), <ide> 'alias' => $this->alias(), <ide> 'entityClass' => $this->entityClass(), <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testDebugInfo() <ide> $articles->addBehavior('Timestamp'); <ide> $result = $articles->__debugInfo(); <ide> $expected = [ <add> 'registryAlias' => 'articles', <ide> 'table' => 'articles', <ide> 'alias' => 'articles', <ide> 'entityClass' => 'TestApp\Model\Entity\Article', <ide> public function testDebugInfo() <ide> 'connectionName' => 'test' <ide> ]; <ide> $this->assertEquals($expected, $result); <add> <add> $articles = TableRegistry::get('Foo.Articles'); <add> $result = $articles->__debugInfo(); <add> $expected = [ <add> 'registryAlias' => 'Foo.Articles', <add> 'table' => 'articles', <add> 'alias' => 'Articles', <add> 'entityClass' => '\Cake\ORM\Entity', <add> 'associations' => [], <add> 'behaviors' => [], <add> 'defaultConnection' => 'default', <add> 'connectionName' => 'test' <add> ]; <add> $this->assertEquals($expected, $result); <ide> } <ide> <ide> /**
2
Javascript
Javascript
remove erroneous assert message from test
b9d63ab1b7b82fe959c616ee16a8c6497c824114
<ide><path>test/parallel/test-process-external-stdio-close-spawn.js <ide> if (process.argv[2] === 'child') { <ide> }); <ide> <ide> child.on('close', common.mustCall((exitCode, signal) => { <del> assert.strictEqual(exitCode, 0, 'exit successfully'); <add> assert.strictEqual(exitCode, 0); <ide> assert.strictEqual(signal, null); <ide> })); <ide>
1
Text
Text
add changelog for v1.11.1
ca0c1becea921300599b44dc5b4f2d6e463309ec
<ide><path>CHANGELOG.md <ide> information on the list of deprecated flags and APIs please have a look at <ide> https://docs.docker.com/engine/deprecated/ where target removal dates can also <ide> be found. <ide> <add>## 1.11.1 (2016-04-26) <add> <add>### Distribution <add> <add>- Fix schema2 manifest media type to be of type `application/vnd.docker.container.image.v1+json` ([#21949](https://github.com/docker/docker/pull/21949)) <add> <add>### Documentation <add> <add>+ Add missing API documentation for changes introduced with 1.11.0 ([#22048](https://github.com/docker/docker/pull/22048)) <add> <add>### Builder <add> <add>* Append label passed to `docker build` as arguments as an implicit `LABEL` command at the end of the processed `Dockerfile` ([#22184](https://github.com/docker/docker/pull/22184)) <add> <add>### Networking <add> <add>- Fix a panic that would occur when forwarding DNS query ([#22261](https://github.com/docker/docker/pull/22261)) <add>- Fix an issue where OS threads could end up within an incorrect network namespace when using user defined networks ([#22261](https://github.com/docker/docker/pull/22261)) <add> <add>### Runtime <add> <add>- Fix a bug preventing labels configuration to be reloaded via the config file ([#22299](https://github.com/docker/docker/pull/22299)) <add>- Fix a regression where container mounting `/var/run` would prevent other containers from being removed ([#22256](https://github.com/docker/docker/pull/22256)) <add>- Fix an issue where it would be impossible to update both `memory-swap` and `memory` value together ([#22255](https://github.com/docker/docker/pull/22255)) <add>- Fix a regression from 1.11.0 where the `/auth` endpoint would not initialize `serveraddress` if it is not provided ([#22254](https://github.com/docker/docker/pull/22254)) <add>- Add missing cleanup of container temporary files when cancelling a schedule restart ([#22237](https://github.com/docker/docker/pull/22237)) <add>- Removed scary error message when no restart policy is specified ([#21993](https://github.com/docker/docker/pull/21993)) <add>- Fix a panic that would occur when the plugins were activated via the json spec ([#22191](https://github.com/docker/docker/pull/22191)) <add>- Fix restart backoff logic to correctly reset delay if container ran for at least 10secs ([#22125](https://github.com/docker/docker/pull/22125)) <add>- Remove error message when a container restart get cancelled ([#22123](https://github.com/docker/docker/pull/22123)) <add>- Fix an issue where `docker` would not correcly clean up after `docker exec` ([#22121](https://github.com/docker/docker/pull/22121)) <add>- Fix a panic that could occur when servicing concurrent `docker stats` commands ([#22120](https://github.com/docker/docker/pull/22120))` <add>- Revert deprecation of non-existing host directories auto-creation ([#22065](https://github.com/docker/docker/pull/22065)) <add>- Hide misleading rpc error on daemon shutdown ([#22058](https://github.com/docker/docker/pull/22058)) <add> <ide> ## 1.11.0 (2016-04-13) <ide> <ide> **IMPORTANT**: With Docker 1.11, a Linux docker installation is now made of 4 binaries (`docker`, [`docker-containerd`](https://github.com/docker/containerd), [`docker-containerd-shim`](https://github.com/docker/containerd) and [`docker-runc`](https://github.com/opencontainers/runc)). If you have scripts relying on docker being a single static binaries, please make sure to update them. Interaction with the daemon stay the same otherwise, the usage of the other binaries should be transparent. A Windows docker installation remains a single binary, `docker.exe`.
1
Ruby
Ruby
use localized monkey-patching
bd352bcf35fd45f811e5bd2dbe7f918124e591a2
<ide><path>Library/Homebrew/dev-cmd/extract.rb <ide> require "formulary" <ide> require "tap" <ide> <del># rubocop:disable Style/MethodMissingSuper <del>class BottleSpecification <del> def method_missing(*); end <add>def with_monkey_patch <add> BottleSpecification.class_eval do <add> if method_defined?(:method_missing) <add> alias_method :old_method_missing, :method_missing <add> end <add> define_method(:method_missing) { |*| } <add> end <ide> <del> def respond_to_missing?(*) <del> true <add> Module.class_eval do <add> if method_defined?(:method_missing) <add> alias_method :old_method_missing, :method_missing <add> end <add> define_method(:method_missing) { |*| } <ide> end <del>end <ide> <del>class Module <del> def method_missing(*); end <add> Resource.class_eval do <add> if method_defined?(:method_missing) <add> alias_method :old_method_missing, :method_missing <add> end <add> define_method(:method_missing) { |*| } <add> end <ide> <del> def respond_to_missing?(*) <del> true <add> yield <add>ensure <add> BottleSpecification.class_eval do <add> if method_defined?(:old_method_missing) <add> alias_method :method_missing, :old_method_missing <add> undef :old_method_missing <add> end <ide> end <del>end <ide> <del>class Resource <del> def method_missing(*); end <add> Module.class_eval do <add> if method_defined?(:old_method_missing) <add> alias_method :method_missing, :old_method_missing <add> undef :old_method_missing <add> end <add> end <ide> <del> def respond_to_missing?(*) <del> true <add> Resource.class_eval do <add> if method_defined?(:old_method_missing) <add> alias_method :method_missing, :old_method_missing <add> undef :old_method_missing <add> end <ide> end <ide> end <ide> <ide> def parse_string_spec(spec, tags) <ide> prepend Compat <ide> end <ide> <del># rubocop:enable Style/MethodMissingSuper <ide> module Homebrew <ide> module_function <ide> <ide> def formula_at_revision(repo, name, file, rev) <ide> contents = Git.last_revision_of_file(repo, file, before_commit: rev) <ide> contents.gsub!("@url=", "url ") <ide> contents.gsub!("require 'brewkit'", "require 'formula'") <del> Formulary.from_contents(name, file, contents) <add> with_monkey_patch { Formulary.from_contents(name, file, contents) } <ide> end <ide> end
1
Javascript
Javascript
add jsdoc marker to ensure it is included in docs
d307e77ff3a3c4170011fe88dbf562a69a31ccd2
<ide><path>src/Angular.js <ide> function reloadWithDebugInfo() { <ide> window.location.reload(); <ide> } <ide> <del>/* <add>/** <add> * @ngdoc function <ide> * @name angular.getTestability <ide> * @module ng <ide> * @description
1
Javascript
Javascript
fix permanent deoptimizations
d5925af8d7e8d689603208094a85972aacc53f49
<ide><path>lib/internal/util.js <ide> function getSignalsToNamesMapping() { <ide> return signalsToNamesMapping; <ide> <ide> signalsToNamesMapping = Object.create(null); <del> for (const key in signals) { <add> for (var key in signals) { <ide> signalsToNamesMapping[signals[key]] = key; <ide> } <ide> <ide><path>lib/util.js <ide> function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { <ide> } <ide> visibleLength++; <ide> } <del> const remaining = value.length - index; <add> var remaining = value.length - index; <ide> if (remaining > 0) { <ide> output.push(`... ${remaining} more item${remaining > 1 ? 's' : ''}`); <ide> }
2
Go
Go
convert parse errors to more informative format
64466b0cd9ff36dc3f123a3a68eae438ac9e8e60
<ide><path>builder/remotecontext/detect.go <ide> import ( <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/builder/dockerignore" <add> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/urlutil" <ide> "github.com/moby/buildkit/frontend/dockerfile/parser" <ide> func Detect(config backend.BuildConfig) (remote builder.Source, dockerfile *pars <ide> case remoteURL == ClientSessionRemote: <ide> res, err := parser.Parse(config.Source) <ide> if err != nil { <del> return nil, nil, err <add> return nil, nil, errdefs.InvalidParameter(err) <ide> } <add> <ide> return nil, res, nil <ide> case urlutil.IsGitURL(remoteURL): <ide> remote, dockerfile, err = newGitRemote(remoteURL, dockerfilePath) <ide> func newURLRemote(url string, dockerfilePath string, progressReader func(in io.R <ide> switch contentType { <ide> case mimeTypes.TextPlain: <ide> res, err := parser.Parse(progressReader(content)) <del> return nil, res, err <add> return nil, res, errdefs.InvalidParameter(err) <ide> default: <ide> source, err := FromArchive(progressReader(content)) <ide> if err != nil { <ide> func readAndParseDockerfile(name string, rc io.Reader) (*parser.Result, error) { <ide> br := bufio.NewReader(rc) <ide> if _, err := br.Peek(1); err != nil { <ide> if err == io.EOF { <del> return nil, errors.Errorf("the Dockerfile (%s) cannot be empty", name) <add> return nil, errdefs.InvalidParameter(errors.Errorf("the Dockerfile (%s) cannot be empty", name)) <ide> } <ide> return nil, errors.Wrap(err, "unexpected error reading Dockerfile") <ide> } <del> return parser.Parse(br) <add> <add> dockerfile, err := parser.Parse(br) <add> if err != nil { <add> return nil, errdefs.InvalidParameter(errors.Wrapf(err, "failed to parse %s", name)) <add> } <add> <add> return dockerfile, nil <ide> } <ide> <ide> func openAt(remote builder.Source, path string) (driver.File, error) {
1
Text
Text
update changelog for
2e43eefa94b5f98ab4b082dde1dbf34c5d7eedff
<ide><path>activerecord/CHANGELOG.md <add>* Use advisory locking to raise a ConcurrentMigrationError instead of <add> attempting to migrate when another migration is currently running. <add> <add> *Sam Davies* <add> <ide> * Added `ActiveRecord::Relation#left_outer_joins`. <ide> <ide> Example:
1
Go
Go
convert libnetwork stats directly to api types
d36376f86c8944f6955f537a1a12f4072f8d7403
<ide><path>daemon/daemon.go <ide> import ( <ide> "github.com/docker/go-connections/nat" <ide> "github.com/docker/libnetwork" <ide> nwconfig "github.com/docker/libnetwork/config" <del> lntypes "github.com/docker/libnetwork/types" <ide> "github.com/docker/libtrust" <del> "github.com/opencontainers/runc/libcontainer" <ide> "golang.org/x/net/context" <ide> ) <ide> <ide> func (daemon *Daemon) GetContainerStats(container *container.Container) (*types. <ide> return nil, err <ide> } <ide> <del> // Retrieve the nw statistics from libnetwork and inject them in the Stats <del> var nwStats []*libcontainer.NetworkInterface <del> if nwStats, err = daemon.getNetworkStats(container); err != nil { <add> if stats.Networks, err = daemon.getNetworkStats(container); err != nil { <ide> return nil, err <ide> } <ide> <del> stats.Networks = make(map[string]types.NetworkStats) <del> for _, iface := range nwStats { <del> // For API Version >= 1.21, the original data of network will <del> // be returned. <del> stats.Networks[iface.Name] = types.NetworkStats{ <del> RxBytes: iface.RxBytes, <del> RxPackets: iface.RxPackets, <del> RxErrors: iface.RxErrors, <del> RxDropped: iface.RxDropped, <del> TxBytes: iface.TxBytes, <del> TxPackets: iface.TxPackets, <del> TxErrors: iface.TxErrors, <del> TxDropped: iface.TxDropped, <del> } <del> } <del> <ide> return stats, nil <ide> } <ide> <del>func (daemon *Daemon) getNetworkStats(c *container.Container) ([]*libcontainer.NetworkInterface, error) { <del> var list []*libcontainer.NetworkInterface <del> <add>func (daemon *Daemon) getNetworkStats(c *container.Container) (map[string]types.NetworkStats, error) { <ide> sb, err := daemon.netController.SandboxByID(c.NetworkSettings.SandboxID) <ide> if err != nil { <del> return list, err <add> return nil, err <ide> } <ide> <del> stats, err := sb.Statistics() <add> lnstats, err := sb.Statistics() <ide> if err != nil { <del> return list, err <add> return nil, err <ide> } <ide> <del> // Convert libnetwork nw stats into libcontainer nw stats <del> for ifName, ifStats := range stats { <del> list = append(list, convertLnNetworkStats(ifName, ifStats)) <add> stats := make(map[string]types.NetworkStats) <add> // Convert libnetwork nw stats into engine-api stats <add> for ifName, ifStats := range lnstats { <add> stats[ifName] = types.NetworkStats{ <add> RxBytes: ifStats.RxBytes, <add> RxPackets: ifStats.RxPackets, <add> RxErrors: ifStats.RxErrors, <add> RxDropped: ifStats.RxDropped, <add> TxBytes: ifStats.TxBytes, <add> TxPackets: ifStats.TxPackets, <add> TxErrors: ifStats.TxErrors, <add> TxDropped: ifStats.TxDropped, <add> } <ide> } <ide> <del> return list, nil <add> return stats, nil <ide> } <ide> <ide> // newBaseContainer creates a new container with its initial <ide> func (daemon *Daemon) reloadClusterDiscovery(config *Config) error { <ide> return nil <ide> } <ide> <del>func convertLnNetworkStats(name string, stats *lntypes.InterfaceStatistics) *libcontainer.NetworkInterface { <del> n := &libcontainer.NetworkInterface{Name: name} <del> n.RxBytes = stats.RxBytes <del> n.RxPackets = stats.RxPackets <del> n.RxErrors = stats.RxErrors <del> n.RxDropped = stats.RxDropped <del> n.TxBytes = stats.TxBytes <del> n.TxPackets = stats.TxPackets <del> n.TxErrors = stats.TxErrors <del> n.TxDropped = stats.TxDropped <del> return n <del>} <del> <ide> func validateID(id string) error { <ide> if id == "" { <ide> return fmt.Errorf("Invalid empty id") <ide><path>daemon/stats_freebsd.go <del>package daemon <del> <del>import ( <del> "github.com/docker/engine-api/types" <del> "github.com/opencontainers/runc/libcontainer" <del>) <del> <del>// convertStatsToAPITypes converts the libcontainer.Stats to the api specific <del>// structs. This is done to preserve API compatibility and versioning. <del>func convertStatsToAPITypes(ls *libcontainer.Stats) *types.StatsJSON { <del> // TODO FreeBSD. Refactor accordingly to fill in stats. <del> s := &types.StatsJSON{} <del> return s <del>}
2
PHP
PHP
fix other uses of deprecated database features
e441a345d886097094385ebe686350f85dc7d7d8
<ide><path>src/ORM/Association/Loader/SelectLoader.php <ide> protected function _buildSubquery($query) <ide> $filterQuery->mapReduce(null, null, true); <ide> $filterQuery->formatResults(null, true); <ide> $filterQuery->contain([], true); <del> $filterQuery->valueBinder(new ValueBinder()); <add> $filterQuery->setValueBinder(new ValueBinder()); <ide> <ide> if (!$filterQuery->clause('limit')) { <ide> $filterQuery->limit(null); <ide><path>src/ORM/Behavior/TreeBehavior.php <ide> protected function _unmarkInternalTree() <ide> function ($exp) use ($config) { <ide> /* @var \Cake\Database\Expression\QueryExpression $exp */ <ide> $leftInverse = clone $exp; <del> $leftInverse->type('*')->add('-1'); <add> $leftInverse->setConjunction('*')->add('-1'); <ide> $rightInverse = clone $leftInverse; <ide> <ide> return $exp <ide><path>src/ORM/LazyEagerLoader.php <ide> protected function _getQuery($objects, $contain, $source) <ide> return $exp->in($source->aliasField($primaryKey), $keys->toList()); <ide> } <ide> <del> $types = array_intersect_key($q->defaultTypes(), array_flip($primaryKey)); <add> $types = array_intersect_key($q->getDefaultTypes(), array_flip($primaryKey)); <ide> $primaryKey = array_map([$source, 'aliasField'], $primaryKey); <ide> <ide> return new TupleComparison($primaryKey, $keys->toList(), $types, 'IN'); <ide><path>src/TestSuite/Fixture/TestFixture.php <ide> protected function _schemaFromImport() <ide> $this->table = $import['table']; <ide> <ide> $db = ConnectionManager::get($import['connection'], false); <del> $schemaCollection = $db->schemaCollection(); <add> $schemaCollection = $db->getSchemaCollection(); <ide> $table = $schemaCollection->describe($import['table']); <ide> $this->_schema = $table; <ide> } <ide> protected function _schemaFromImport() <ide> protected function _schemaFromReflection() <ide> { <ide> $db = ConnectionManager::get($this->connection()); <del> $schemaCollection = $db->schemaCollection(); <add> $schemaCollection = $db->getSchemaCollection(); <ide> $tables = $schemaCollection->listTables(); <ide> <ide> if (!in_array($this->table, $tables)) { <ide><path>tests/TestCase/DatabaseSuite.php <ide> public function run(TestResult $result = null) <ide> { <ide> $permutations = [ <ide> 'Identifier Quoting' => function () { <del> ConnectionManager::get('test')->driver()->autoQuoting(true); <add> ConnectionManager::get('test')->getDriver()->enableAutoQuoting(true); <ide> }, <ide> 'No identifier quoting' => function () { <del> ConnectionManager::get('test')->driver()->autoQuoting(false); <add> ConnectionManager::get('test')->getDriver()->enableAutoQuoting(false); <ide> } <ide> ]; <ide> <ide><path>tests/TestCase/ORM/Association/BelongsToTest.php <ide> public function testAttachTo() <ide> <ide> $this->assertEquals( <ide> 'integer', <del> $query->typeMap()->type('Companies__id'), <add> $query->getTypeMap()->type('Companies__id'), <ide> 'Associations should map types.' <ide> ); <ide> } <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function setUp() <ide> 'Articles__title' => 'string', <ide> 'Articles__author_id' => 'integer', <ide> ]); <del> $this->autoQuote = $connection->driver()->autoQuoting(); <add> $this->autoQuote = $connection->getDriver()->isAutoQuotingEnabled(); <ide> } <ide> <ide> /** <ide> public function testEagerLoaderWithOverrides() <ide> 'Articles.id !=' => 3, <ide> 'Articles.author_id IN' => $keys <ide> ], <del> $query->typeMap() <add> $query->getTypeMap() <ide> ); <ide> $this->assertWhereClause($expected, $query); <ide> <ide> public function testEagerLoaderWithQueryBuilder() <ide> 'type' => 'INNER', <ide> 'alias' => null, <ide> 'table' => 'comments', <del> 'conditions' => new QueryExpression([], $query->typeMap()), <add> 'conditions' => new QueryExpression([], $query->getTypeMap()), <ide> ] <ide> ]; <ide> $this->assertJoin($expected, $query); <ide> public function testEagerLoaderWithQueryBuilder() <ide> 'Articles.author_id IN' => $keys, <ide> 'comments.id' => 1, <ide> ], <del> $query->typeMap() <add> $query->getTypeMap() <ide> ); <ide> $this->assertWhereClause($expected, $query); <ide> } <ide> protected function assertJoin($expected, $query) <ide> protected function assertWhereClause($expected, $query) <ide> { <ide> if ($this->autoQuote) { <del> $quoter = new IdentifierQuoter($query->connection()->driver()); <add> $quoter = new IdentifierQuoter($query->getConnection()->getDriver()); <ide> $expected->traverse([$quoter, 'quoteExpression']); <ide> } <ide> $this->assertEquals($expected, $query->clause('where')); <ide> protected function assertWhereClause($expected, $query) <ide> protected function assertOrderClause($expected, $query) <ide> { <ide> if ($this->autoQuote) { <del> $quoter = new IdentifierQuoter($query->connection()->driver()); <add> $quoter = new IdentifierQuoter($query->getConnection()->getDriver()); <ide> $quoter->quoteExpression($expected); <ide> } <ide> $this->assertEquals($expected, $query->clause('order')); <ide><path>tests/TestCase/ORM/CompositeKeysTest.php <ide> public function testLoadIntoMany() <ide> */ <ide> public function testNotMatchingBelongsToMany() <ide> { <del> $driver = $this->connection->driver(); <add> $driver = $this->connection->getDriver(); <ide> <ide> if ($driver instanceof Sqlserver) { <ide> $this->markTestSkipped('Sqlserver does not support the requirements of this test.'); <ide> public function testNotMatchingBelongsToMany() <ide> public function skipIfSqlite() <ide> { <ide> $this->skipIf( <del> $this->connection->driver() instanceof Sqlite, <add> $this->connection->getDriver() instanceof Sqlite, <ide> 'SQLite does not support the requirements of this test.' <ide> ); <ide> } <ide><path>tests/TestCase/ORM/EagerLoaderTest.php <ide> public function testContainToJoinsOneLevel() <ide> ->setConstructorArgs([$this->connection, $this->table]) <ide> ->getMock(); <ide> <del> $query->typeMap($this->clientsTypeMap); <add> $query->setTypeMap($this->clientsTypeMap); <ide> <ide> $query->expects($this->at(0))->method('join') <ide> ->with(['clients' => [ <ide> 'table' => 'clients', <ide> 'type' => 'LEFT', <ide> 'conditions' => new QueryExpression([ <ide> ['clients.id' => new IdentifierExpression('foo.client_id')], <del> ], new TypeMap($this->clientsTypeMap->defaults())) <add> ], new TypeMap($this->clientsTypeMap->getDefaults())) <ide> ]]) <ide> ->will($this->returnValue($query)); <ide> <ide> public function testClearContain() <ide> */ <ide> protected function _quoteArray($elements) <ide> { <del> if ($this->connection->driver()->autoQuoting()) { <add> if ($this->connection->getDriver()->isAutoQuotingEnabled()) { <ide> $quoter = function ($e) { <del> return $this->connection->driver()->quoteIdentifier($e); <add> return $this->connection->getDriver()->quoteIdentifier($e); <ide> }; <ide> <ide> return array_combine( <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testDeepHasManyEitherStrategy() <ide> $tags = TableRegistry::get('Tags'); <ide> <ide> $this->skipIf( <del> $tags->connection()->driver() instanceof \Cake\Database\Driver\Sqlserver, <add> $tags->connection()->getDriver() instanceof \Cake\Database\Driver\Sqlserver, <ide> 'SQL server is temporarily weird in this test, will investigate later' <ide> ); <ide> $tags = TableRegistry::get('Tags'); <ide> public function testSubqueryInSelectExpression() <ide> $ratio = $table->find() <ide> ->select(function ($query) use ($table) { <ide> $allCommentsCount = $table->find()->select($query->func()->count('*')); <del> $countToFloat = $query->newExpr([$query->func()->count('*'), '1.0'])->type('*'); <add> $countToFloat = $query->newExpr([$query->func()->count('*'), '1.0'])->setConjunction('*'); <ide> <ide> return [ <ide> 'ratio' => $query <ide> ->newExpr($countToFloat) <ide> ->add($allCommentsCount) <del> ->type('/') <add> ->setConjunction('/') <ide> ]; <ide> }) <ide> ->where(['user_id' => 1]) <ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function testFirstUnbuffered() <ide> $query->select(['id']); <ide> <ide> $first = $query->hydrate(false) <del> ->bufferResults(false)->first(); <add> ->enableBufferedResults(false)->first(); <ide> <ide> $this->assertEquals(['id' => 1], $first); <ide> } <ide> public function testUpdate() <ide> */ <ide> public function testUpdateWithTableExpression() <ide> { <del> $this->skipIf(!$this->connection->driver() instanceof \Cake\Database\Driver\Mysql); <add> $this->skipIf(!$this->connection->getDriver() instanceof \Cake\Database\Driver\Mysql); <ide> $table = TableRegistry::get('articles'); <ide> <ide> $query = $table->query(); <ide> public function testInsert() <ide> <ide> $this->assertInstanceOf('Cake\Database\StatementInterface', $result); <ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT <del> if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) { <add> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) { <ide> $this->assertEquals(2, $result->rowCount()); <ide> } else { <ide> $this->assertEquals(-1, $result->rowCount()); <ide> public function testDebugInfo() <ide> $table->hasMany('articles'); <ide> $query = $table->find() <ide> ->where(['id > ' => 1]) <del> ->bufferResults(false) <add> ->enableBufferedResults(false) <ide> ->hydrate(false) <ide> ->matching('articles') <ide> ->applyOptions(['foo' => 'bar']) <ide> public function testDebugInfo() <ide> $expected = [ <ide> '(help)' => 'This is a Query object, to get the results execute or iterate it.', <ide> 'sql' => $query->sql(), <del> 'params' => $query->valueBinder()->bindings(), <add> 'params' => $query->getValueBinder()->bindings(), <ide> 'defaultTypes' => [ <ide> 'authors__id' => 'integer', <ide> 'authors.id' => 'integer', <ide> public function testCleanCopyRetainsBindings() <ide> ->bind(':end', 2); <ide> $copy = $query->cleanCopy(); <ide> <del> $this->assertNotEmpty($copy->valueBinder()->bindings()); <add> $this->assertNotEmpty($copy->getValueBinder()->bindings()); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/ORM/ResultSetTest.php <ide> public function testRewind() <ide> */ <ide> public function testRewindStreaming() <ide> { <del> $query = $this->table->find('all')->bufferResults(false); <add> $query = $this->table->find('all')->enableBufferedResults(false); <ide> $results = $query->all(); <ide> $first = $second = []; <ide> foreach ($results as $result) { <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testDisplaySet() <ide> */ <ide> public function testSchema() <ide> { <del> $schema = $this->connection->schemaCollection()->describe('users'); <add> $schema = $this->connection->getSchemaCollection()->describe('users'); <ide> $table = new Table([ <ide> 'table' => 'users', <ide> 'connection' => $this->connection, <ide> public function testSchema() <ide> */ <ide> public function testSchemaInitialize() <ide> { <del> $schema = $this->connection->schemaCollection()->describe('users'); <add> $schema = $this->connection->getSchemaCollection()->describe('users'); <ide> $table = $this->getMockBuilder('Cake\ORM\Table') <ide> ->setMethods(['_initializeSchema']) <ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]]) <ide> public function testAtomicSave() <ide> ->setMethods(['begin', 'commit', 'inTransaction']) <ide> ->setConstructorArgs([$config]) <ide> ->getMock(); <del> $connection->driver($this->connection->driver()); <add> $connection->setDriver($this->connection->getDriver()); <ide> <ide> $table = $this->getMockBuilder('\Cake\ORM\Table') <ide> ->setMethods(['getConnection']) <ide> public function testAtomicSaveRollback() <ide> ->setMethods(['begin', 'rollback']) <ide> ->setConstructorArgs([ConnectionManager::config('test')]) <ide> ->getMock(); <del> $connection->driver(ConnectionManager::get('test')->driver()); <add> $connection->setDriver(ConnectionManager::get('test')->getDriver()); <ide> $table = $this->getMockBuilder('\Cake\ORM\Table') <ide> ->setMethods(['query', 'getConnection']) <ide> ->setConstructorArgs([['table' => 'users']]) <ide> public function testAtomicSaveRollbackOnFailure() <ide> ->setMethods(['begin', 'rollback']) <ide> ->setConstructorArgs([ConnectionManager::config('test')]) <ide> ->getMock(); <del> $connection->driver(ConnectionManager::get('test')->driver()); <add> $connection->setDriver(ConnectionManager::get('test')->getDriver()); <ide> $table = $this->getMockBuilder('\Cake\ORM\Table') <ide> ->setMethods(['query', 'getConnection', 'exists']) <ide> ->setConstructorArgs([['table' => 'users']]) <ide> public function testMagicFindAllOr() <ide> $this->assertInstanceOf('Cake\ORM\Query', $result); <ide> $this->assertNull($result->clause('limit')); <ide> $expected = new QueryExpression(); <del> $expected->typeMap()->defaults($this->usersTypeMap->toArray()); <add> $expected->getTypeMap()->setDefaults($this->usersTypeMap->toArray()); <ide> $expected->add( <ide> ['or' => ['Users.author_id' => 1, 'Users.published' => 'Y']] <ide> ); <ide> public function getSaveOptionsBuilder() <ide> public function skipIfSqlServer() <ide> { <ide> $this->skipIf( <del> $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver, <add> $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver, <ide> 'SQLServer does not support the requirements of this test.' <ide> ); <ide> } <ide><path>tests/TestCase/Shell/SchemaCacheShellTest.php <ide> public function testClearEnablesMetadataCache() <ide> <ide> $this->shell->params['connection'] = 'test'; <ide> $this->shell->clear(); <del> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $ds->schemaCollection()); <add> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $ds->getSchemaCollection()); <ide> } <ide> <ide> /** <ide> public function testBuildEnablesMetadataCache() <ide> <ide> $this->shell->params['connection'] = 'test'; <ide> $this->shell->build(); <del> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $ds->schemaCollection()); <add> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $ds->getSchemaCollection()); <ide> } <ide> <ide> /**
14
Text
Text
add title text to image chart
43f64a4204e9d78f1aff2514c824f1795be06a49
<ide><path>guide/english/chef/index.md <ide> Chef enables programmers and system administrators to work together. Instead of <ide> <p>The client will then check in every now and again to make sure that no changes have occurred, and nothing needs to change. If it does, then the client deals with it. Patches and updates can be rolled out over your entire infrastructure by changing the recipe. There is no need to interact with each machine individually.</p> <ide> <ide> #### Chef Configuration <del>![Image Title](https://regmedia.co.uk/2015/10/07/chef_configuration_management.jpg) <add>![Image Title](https://regmedia.co.uk/2015/10/07/chef_configuration_management.jpg "Chef Configuration process chart") <ide> <ide> <ide> #### More Information:
1
Javascript
Javascript
switch assertequal arguments
24950985df4e55293efecd393d09d18abd94ed05
<ide><path>test/sequential/test-inspector-debug-end.js <ide> async function testNoServerNoCrash() { <ide> const instance = new NodeInstance([], <ide> `process._debugEnd(); <ide> process.exit(42);`); <del> strictEqual(42, (await instance.expectShutdown()).exitCode); <add> strictEqual((await instance.expectShutdown()).exitCode, 42); <ide> } <ide> <ide> async function testNoSessionNoCrash() { <ide> console.log('Test there\'s no crash stopping server without connecting'); <ide> const instance = new NodeInstance('--inspect=0', <ide> 'process._debugEnd();process.exit(42);'); <del> strictEqual(42, (await instance.expectShutdown()).exitCode); <add> strictEqual((await instance.expectShutdown()).exitCode, 42); <ide> } <ide> <ide> async function testSessionNoCrash() { <ide> async function testSessionNoCrash() { <ide> const session = await instance.connectInspectorSession(); <ide> await session.send({ 'method': 'Runtime.runIfWaitingForDebugger' }); <ide> await session.waitForServerDisconnect(); <del> strictEqual(42, (await instance.expectShutdown()).exitCode); <add> strictEqual((await instance.expectShutdown()).exitCode, 42); <ide> } <ide> <ide> async function runTest() {
1
Java
Java
generate module definition on demand
30a5eb51f8efea5cb5ccc75edbefc9575eadba3b
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java <ide> public void stopProfiler(String title, String filename) { <ide> private String buildModulesConfigJSONProperty( <ide> NativeModuleRegistry nativeModuleRegistry, <ide> JavaScriptModulesConfig jsModulesConfig) { <del> // TODO(5300733): Serialize config using single json generator <ide> JsonFactory jsonFactory = new JsonFactory(); <ide> StringWriter writer = new StringWriter(); <ide> try { <ide> JsonGenerator jg = jsonFactory.createGenerator(writer); <ide> jg.writeStartObject(); <ide> jg.writeFieldName("remoteModuleConfig"); <del> jg.writeRawValue(nativeModuleRegistry.moduleDescriptions()); <add> nativeModuleRegistry.writeModuleDescriptions(jg); <ide> jg.writeFieldName("localModulesConfig"); <del> jg.writeRawValue(jsModulesConfig.moduleDescriptions()); <add> jsModulesConfig.writeModuleDescriptions(jg); <ide> jg.writeEndObject(); <ide> jg.close(); <ide> } catch (IOException ioe) { <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModulesConfig.java <ide> package com.facebook.react.bridge; <ide> <ide> import java.io.IOException; <del>import java.io.StringWriter; <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> <del>import com.fasterxml.jackson.core.JsonFactory; <ide> import com.fasterxml.jackson.core.JsonGenerator; <ide> <ide> /** <ide> private JavaScriptModulesConfig(List<JavaScriptModuleRegistration> modules) { <ide> return mModules; <ide> } <ide> <del> /*package*/ String moduleDescriptions() { <del> JsonFactory jsonFactory = new JsonFactory(); <del> StringWriter writer = new StringWriter(); <del> try { <del> JsonGenerator jg = jsonFactory.createGenerator(writer); <del> jg.writeStartObject(); <del> for (JavaScriptModuleRegistration registration : mModules) { <del> jg.writeObjectFieldStart(registration.getName()); <del> appendJSModuleToJSONObject(jg, registration); <del> jg.writeEndObject(); <del> } <add> /*package*/ void writeModuleDescriptions(JsonGenerator jg) throws IOException { <add> jg.writeStartObject(); <add> for (JavaScriptModuleRegistration registration : mModules) { <add> jg.writeObjectFieldStart(registration.getName()); <add> appendJSModuleToJSONObject(jg, registration); <ide> jg.writeEndObject(); <del> jg.close(); <del> } catch (IOException ioe) { <del> throw new RuntimeException("Unable to serialize JavaScript module declaration", ioe); <ide> } <del> return writer.getBuffer().toString(); <add> jg.writeEndObject(); <ide> } <ide> <ide> private void appendJSModuleToJSONObject( <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleRegistry.java <ide> package com.facebook.react.bridge; <ide> <ide> import java.io.IOException; <del>import java.io.StringWriter; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.HashMap; <add>import java.util.List; <ide> import java.util.Map; <ide> <ide> import com.facebook.react.common.MapBuilder; <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.systrace.Systrace; <ide> <del>import com.fasterxml.jackson.core.JsonFactory; <ide> import com.fasterxml.jackson.core.JsonGenerator; <ide> <ide> /** <ide> * A set of Java APIs to expose to a particular JavaScript instance. <ide> */ <ide> public class NativeModuleRegistry { <ide> <del> private final ArrayList<ModuleDefinition> mModuleTable; <add> private final List<ModuleDefinition> mModuleTable; <ide> private final Map<Class<? extends NativeModule>, NativeModule> mModuleInstances; <del> private final String mModuleDescriptions; <ide> private final ArrayList<OnBatchCompleteListener> mBatchCompleteListenerModules; <ide> <ide> private NativeModuleRegistry( <del> ArrayList<ModuleDefinition> moduleTable, <del> Map<Class<? extends NativeModule>, NativeModule> moduleInstances, <del> String moduleDescriptions) { <add> List<ModuleDefinition> moduleTable, <add> Map<Class<? extends NativeModule>, NativeModule> moduleInstances) { <ide> mModuleTable = moduleTable; <ide> mModuleInstances = moduleInstances; <del> mModuleDescriptions = moduleDescriptions; <ide> <ide> mBatchCompleteListenerModules = new ArrayList<OnBatchCompleteListener>(mModuleTable.size()); <ide> for (int i = 0; i < mModuleTable.size(); i++) { <ide> private NativeModuleRegistry( <ide> definition.call(catalystInstance, methodId, parameters); <ide> } <ide> <del> /* package */ String moduleDescriptions() { <del> return mModuleDescriptions; <add> /* package */ void writeModuleDescriptions(JsonGenerator jg) throws IOException { <add> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateJSON"); <add> try { <add> jg.writeStartObject(); <add> for (ModuleDefinition moduleDef : mModuleTable) { <add> jg.writeObjectFieldStart(moduleDef.name); <add> jg.writeNumberField("moduleID", moduleDef.id); <add> jg.writeObjectFieldStart("methods"); <add> for (int i = 0; i < moduleDef.methods.size(); i++) { <add> MethodRegistration method = moduleDef.methods.get(i); <add> jg.writeObjectFieldStart(method.name); <add> jg.writeNumberField("methodID", i); <add> jg.writeStringField("type", method.method.getType()); <add> jg.writeEndObject(); <add> } <add> jg.writeEndObject(); <add> moduleDef.target.writeConstantsField(jg, "constants"); <add> jg.writeEndObject(); <add> } <add> jg.writeEndObject(); <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> } <ide> } <ide> <ide> /* package */ void notifyCatalystInstanceDestroy() { <ide> public Builder add(NativeModule module) { <ide> } <ide> <ide> public NativeModuleRegistry build() { <del> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateJSON"); <del> ArrayList<ModuleDefinition> moduleTable = new ArrayList<>(); <del> Map<Class<? extends NativeModule>, NativeModule> moduleInstances = MapBuilder.newHashMap(); <del> String moduleDefinitionJson; <del> try { <del> JsonFactory jsonFactory = new JsonFactory(); <del> StringWriter writer = new StringWriter(); <del> try { <del> JsonGenerator jg = jsonFactory.createGenerator(writer); <del> jg.writeStartObject(); <del> int idx = 0; <del> for (NativeModule module : mModules.values()) { <del> ModuleDefinition moduleDef = new ModuleDefinition(idx++, module.getName(), module); <del> moduleTable.add(moduleDef); <del> moduleInstances.put(module.getClass(), module); <del> jg.writeObjectFieldStart(moduleDef.name); <del> jg.writeNumberField("moduleID", moduleDef.id); <del> jg.writeObjectFieldStart("methods"); <del> for (int i = 0; i < moduleDef.methods.size(); i++) { <del> MethodRegistration method = moduleDef.methods.get(i); <del> jg.writeObjectFieldStart(method.name); <del> jg.writeNumberField("methodID", i); <del> jg.writeStringField("type", method.method.getType()); <del> jg.writeEndObject(); <del> } <del> jg.writeEndObject(); <del> moduleDef.target.writeConstantsField(jg, "constants"); <del> jg.writeEndObject(); <del> } <del> jg.writeEndObject(); <del> jg.close(); <del> } catch (IOException ioe) { <del> throw new RuntimeException("Unable to serialize Java module configuration", ioe); <del> } <del> moduleDefinitionJson = writer.getBuffer().toString(); <del> } finally { <del> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> List<ModuleDefinition> moduleTable = new ArrayList<>(); <add> Map<Class<? extends NativeModule>, NativeModule> moduleInstances = new HashMap<>(); <add> <add> int idx = 0; <add> for (NativeModule module : mModules.values()) { <add> ModuleDefinition moduleDef = new ModuleDefinition(idx++, module.getName(), module); <add> moduleTable.add(moduleDef); <add> moduleInstances.put(module.getClass(), module); <ide> } <del> return new NativeModuleRegistry(moduleTable, moduleInstances, moduleDefinitionJson); <add> return new NativeModuleRegistry(moduleTable, moduleInstances); <ide> } <ide> } <ide> }
3
PHP
PHP
improve doc block and signature
b55ee6710592af2748bee4fdbaf277d7e578f8e0
<ide><path>src/TestSuite/EmailTrait.php <ide> public function assertMailContainsHtml($contents, $message = null) <ide> } <ide> <ide> /** <del> * Asserts an email contains expected text contents <add> * Asserts an email contains an expected text content <ide> * <del> * @param int $contents Contents <del> * @param string $message Message <add> * @param string $expectedText Expected text. <add> * @param string $message Message to display if assertion fails. <ide> * @return void <ide> */ <del> public function assertMailContainsText($contents, $message = null) <add> public function assertMailContainsText($expectedText, $message = null) <ide> { <del> $this->assertThat($contents, new MailContainsText(), $message); <add> $this->assertThat($expectedText, new MailContainsText(), $message); <ide> } <ide> <ide> /**
1
Mixed
Ruby
fix validation callbacks on multiple context
470d0e459f2d1cb8e6d5c0a8a2fe3282ca65690e
<ide><path>activemodel/CHANGELOG.md <add>* Fix to working before/after validation callbacks on multiple contexts. <add> <add> *Yoshiyuki Hirano* <add> <ide> ## Rails 5.2.0.beta2 (November 28, 2017) ## <ide> <ide> * No changes. <ide><path>activemodel/lib/active_model/validations/callbacks.rb <ide> module ClassMethods <ide> # person.valid? # => true <ide> # person.name # => "bob" <ide> def before_validation(*args, &block) <del> options = args.last <del> if options.is_a?(Hash) && options[:on] <del> options[:if] = Array(options[:if]) <del> options[:on] = Array(options[:on]) <add> options = args.extract_options! <add> options[:if] = Array(options[:if]) <add> <add> if options.key?(:on) <ide> options[:if].unshift ->(o) { <del> options[:on].include? o.validation_context <add> !(Array(options[:on]) & Array(o.validation_context)).empty? <ide> } <ide> end <add> <add> args << options <ide> set_callback(:validation, :before, *args, &block) <ide> end <ide> <ide> def after_validation(*args, &block) <ide> options = args.extract_options! <ide> options[:prepend] = true <ide> options[:if] = Array(options[:if]) <del> if options[:on] <del> options[:on] = Array(options[:on]) <add> <add> if options.key?(:on) <ide> options[:if].unshift ->(o) { <del> options[:on].include? o.validation_context <add> !(Array(options[:on]) & Array(o.validation_context)).empty? <ide> } <ide> end <del> set_callback(:validation, :after, *(args << options), &block) <add> <add> args << options <add> set_callback(:validation, :after, *args, &block) <ide> end <ide> end <ide> <ide><path>activemodel/test/cases/validations/callbacks_test.rb <ide> def set_before_validation_marker; history << "before_validation_marker"; end <ide> def set_after_validation_marker; history << "after_validation_marker" ; end <ide> end <ide> <add>class DogValidatorWithOnMultipleCondition < Dog <add> before_validation :set_before_validation_marker_on_context_a, on: :context_a <add> before_validation :set_before_validation_marker_on_context_b, on: :context_b <add> after_validation :set_after_validation_marker_on_context_a, on: :context_a <add> after_validation :set_after_validation_marker_on_context_b, on: :context_b <add> <add> def set_before_validation_marker_on_context_a; history << "before_validation_marker on context_a"; end <add> def set_before_validation_marker_on_context_b; history << "before_validation_marker on context_b"; end <add> def set_after_validation_marker_on_context_a; history << "after_validation_marker on context_a" ; end <add> def set_after_validation_marker_on_context_b; history << "after_validation_marker on context_b" ; end <add>end <add> <ide> class DogValidatorWithIfCondition < Dog <ide> before_validation :set_before_validation_marker1, if: -> { true } <ide> before_validation :set_before_validation_marker2, if: -> { false } <ide> def test_on_condition_is_respected_for_validation_without_context <ide> assert_equal [], d.history <ide> end <ide> <add> def test_on_multiple_condition_is_respected_for_validation_with_matching_context <add> d = DogValidatorWithOnMultipleCondition.new <add> d.valid?(:context_a) <add> assert_equal ["before_validation_marker on context_a", "after_validation_marker on context_a"], d.history <add> <add> d = DogValidatorWithOnMultipleCondition.new <add> d.valid?(:context_b) <add> assert_equal ["before_validation_marker on context_b", "after_validation_marker on context_b"], d.history <add> <add> d = DogValidatorWithOnMultipleCondition.new <add> d.valid?([:context_a, :context_b]) <add> assert_equal([ <add> "before_validation_marker on context_a", <add> "before_validation_marker on context_b", <add> "after_validation_marker on context_a", <add> "after_validation_marker on context_b" <add> ], d.history) <add> end <add> <add> def test_on_multiple_condition_is_respected_for_validation_without_matching_context <add> d = DogValidatorWithOnMultipleCondition.new <add> d.valid?(:save) <add> assert_equal [], d.history <add> end <add> <add> def test_on_multiple_condition_is_respected_for_validation_without_context <add> d = DogValidatorWithOnMultipleCondition.new <add> d.valid? <add> assert_equal [], d.history <add> end <add> <ide> def test_before_validation_and_after_validation_callbacks_should_be_called <ide> d = DogWithMethodCallbacks.new <ide> d.valid?
3
Javascript
Javascript
improve error logging for inspector test
bfb4f4224d9f8f87944d611dd569d1d3579f5523
<ide><path>test/inspector/inspector-helper.js <ide> function parseWSFrame(buffer, handler) { <ide> } <ide> if (buffer.length < bodyOffset + dataLen) <ide> return 0; <del> const message = JSON.parse( <del> buffer.slice(bodyOffset, bodyOffset + dataLen).toString('utf8')); <add> const jsonPayload = <add> buffer.slice(bodyOffset, bodyOffset + dataLen).toString('utf8'); <add> let message; <add> try { <add> message = JSON.parse(jsonPayload); <add> } catch (e) { <add> console.error(`JSON.parse() failed for: ${jsonPayload}`); <add> throw e; <add> } <ide> if (DEBUG) <ide> console.log('[received]', JSON.stringify(message)); <ide> handler(message);
1
Javascript
Javascript
make "unexpected batch number" a warning
abcd5673251b3e17fc42ea9c93a2c6bd4068855e
<ide><path>src/renderers/shared/stack/reconciler/ReactReconciler.js <ide> var ReactRef = require('ReactRef'); <ide> var ReactInstrumentation = require('ReactInstrumentation'); <ide> <del>var invariant = require('invariant'); <add>var warning = require('warning'); <ide> <ide> /** <ide> * Helper to call ReactRef.attachRefs with this composite component, split out <ide> var ReactReconciler = { <ide> if (internalInstance._updateBatchNumber !== updateBatchNumber) { <ide> // The component's enqueued batch number should always be the current <ide> // batch or the following one. <del> invariant( <add> warning( <ide> internalInstance._updateBatchNumber == null || <ide> internalInstance._updateBatchNumber === updateBatchNumber + 1, <ide> 'performUpdateIfNecessary: Unexpected batch number (current %s, ' +
1
Python
Python
apply suggestions from code review
e6bea5f79c127a53a9252d8d3f51108815c60267
<ide><path>numpy/lib/function_base.py <ide> def unwrap(p, discont=None, axis=-1, *, period=2*pi): <ide> If the discontinuity in `p` is smaller than ``period/2``, <ide> but larger than `discont`, no unwrapping is done because taking <ide> the complement would only make the discontinuity larger. <del> <ide> Examples <ide> -------- <ide> >>> phase = np.linspace(0, np.pi, num=5) <ide> def unwrap(p, discont=None, axis=-1, *, period=2*pi): <ide> >>> phase_deg = np.mod(np.linspace(0,720,19), 360) - 180 <ide> >>> unwrap(phase_deg, period=360) <ide> array([-180., -140., -100., -60., -20., 20., 60., 100., 140., <del> 180., 220., 260., 300., 340., 380., 420., 460., 500., <del> 540.]) <add> 180., 220., 260., 300., 340., 380., 420., 460., 500., <add> 540.]) <ide> """ <ide> p = asarray(p) <ide> nd = p.ndim
1
Javascript
Javascript
change fixtures.readsync to fixtures.readkey
f212fee2a3709abb267796e8e4a3fb5d85d438b1
<ide><path>test/parallel/test-tls-getprotocol.js <ide> const clientConfigs = [ <ide> <ide> const serverConfig = { <ide> secureProtocol: 'TLS_method', <del> key: fixtures.readSync('/keys/agent2-key.pem'), <del> cert: fixtures.readSync('/keys/agent2-cert.pem') <add> key: fixtures.readKey('agent2-key.pem'), <add> cert: fixtures.readKey('agent2-cert.pem') <ide> }; <ide> <ide> const server = tls.createServer(serverConfig, common.mustCall(function() { <ide><path>test/parallel/test-tls-keylog-tlsv13.js <ide> const tls = require('tls'); <ide> const fixtures = require('../common/fixtures'); <ide> <ide> const server = tls.createServer({ <del> key: fixtures.readSync('/keys/agent2-key.pem'), <del> cert: fixtures.readSync('/keys/agent2-cert.pem'), <add> key: fixtures.readKey('agent2-key.pem'), <add> cert: fixtures.readKey('agent2-cert.pem'), <ide> // Amount of keylog events depends on negotiated protocol <ide> // version, so force a specific one: <ide> minVersion: 'TLSv1.3',
2
Go
Go
join memory and cpu cgroup in systemd too
4ddfffcab3edf3d05ee8319e87410fe747979a04
<ide><path>pkg/cgroups/apply_systemd.go <ide> func systemdApply(c *Cgroup, pid int) (ActiveCgroup, error) { <ide> })}) <ide> } <ide> <add> // Always enable accounting, this gets us the same behaviour as the raw implementation, <add> // plus the kernel has some problems with joining the memory cgroup at a later time. <add> properties = append(properties, <add> systemd1.Property{"MemoryAccounting", dbus.MakeVariant(true)}, <add> systemd1.Property{"CPUAccounting", dbus.MakeVariant(true)}) <add> <ide> if c.Memory != 0 { <ide> properties = append(properties, <ide> systemd1.Property{"MemoryLimit", dbus.MakeVariant(uint64(c.Memory))})
1
Javascript
Javascript
improve assert benchmarks
5442c28b651a79c2269bf2b931e81cd553171656
<ide><path>benchmark/assert/deepequal-buffer.js <ide> const common = require('../common.js'); <ide> const assert = require('assert'); <ide> <ide> const bench = common.createBenchmark(main, { <del> n: [1e5], <del> len: [1e2, 1e4], <add> n: [2e4], <add> len: [1e2, 1e3], <add> strict: [0, 1], <ide> method: [ <ide> 'deepEqual', <del> 'deepStrictEqual', <del> 'notDeepEqual', <del> 'notDeepStrictEqual' <add> 'notDeepEqual' <ide> ] <ide> }); <ide> <del>function main({ len, n, method }) { <add>function main({ len, n, method, strict }) { <ide> if (!method) <ide> method = 'deepEqual'; <ide> const data = Buffer.allocUnsafe(len + 1); <ide> function main({ len, n, method }) { <ide> data.copy(expected); <ide> data.copy(expectedWrong); <ide> <add> if (strict) { <add> method = method.replace('eep', 'eepStrict'); <add> } <ide> const fn = assert[method]; <ide> const value2 = method.includes('not') ? expectedWrong : expected; <ide> <ide><path>benchmark/assert/deepequal-map.js <ide> const { deepEqual, deepStrictEqual, notDeepEqual, notDeepStrictEqual } = <ide> const bench = common.createBenchmark(main, { <ide> n: [5e2], <ide> len: [5e2], <add> strict: [0, 1], <ide> method: [ <ide> 'deepEqual_primitiveOnly', <del> 'deepStrictEqual_primitiveOnly', <ide> 'deepEqual_objectOnly', <del> 'deepStrictEqual_objectOnly', <ide> 'deepEqual_mixed', <del> 'deepStrictEqual_mixed', <del> 'deepEqual_looseMatches', <ide> 'notDeepEqual_primitiveOnly', <del> 'notDeepStrictEqual_primitiveOnly', <ide> 'notDeepEqual_objectOnly', <del> 'notDeepStrictEqual_objectOnly', <del> 'notDeepEqual_mixed', <del> 'notDeepStrictEqual_mixed', <del> 'notDeepEqual_looseMatches', <add> 'notDeepEqual_mixed' <ide> ] <ide> }); <ide> <ide> function benchmark(method, n, values, values2) { <ide> bench.end(n); <ide> } <ide> <del>function main({ n, len, method }) { <add>function main({ n, len, method, strict }) { <ide> const array = Array(len).fill(1); <ide> var values, values2; <ide> <ide> function main({ n, len, method }) { <ide> // Empty string falls through to next line as default, mostly for tests. <ide> case 'deepEqual_primitiveOnly': <ide> values = array.map((_, i) => [`str_${i}`, 123]); <del> benchmark(deepEqual, n, values); <del> break; <del> case 'deepStrictEqual_primitiveOnly': <del> values = array.map((_, i) => [`str_${i}`, 123]); <del> benchmark(deepStrictEqual, n, values); <add> benchmark(strict ? deepStrictEqual : deepEqual, n, values); <ide> break; <ide> case 'deepEqual_objectOnly': <ide> values = array.map((_, i) => [[`str_${i}`, 1], 123]); <del> benchmark(deepEqual, n, values); <del> break; <del> case 'deepStrictEqual_objectOnly': <del> values = array.map((_, i) => [[`str_${i}`, 1], 123]); <del> benchmark(deepStrictEqual, n, values); <add> benchmark(strict ? deepStrictEqual : deepEqual, n, values); <ide> break; <ide> case 'deepEqual_mixed': <ide> values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]); <del> benchmark(deepEqual, n, values); <del> break; <del> case 'deepStrictEqual_mixed': <del> values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]); <del> benchmark(deepStrictEqual, n, values); <del> break; <del> case 'deepEqual_looseMatches': <del> values = array.map((_, i) => [i, i]); <del> values2 = values.slice().map((v) => [String(v[0]), String(v[1])]); <del> benchmark(deepEqual, n, values, values2); <add> benchmark(strict ? deepStrictEqual : deepEqual, n, values); <ide> break; <ide> case 'notDeepEqual_primitiveOnly': <ide> values = array.map((_, i) => [`str_${i}`, 123]); <ide> values2 = values.slice(0); <ide> values2[Math.floor(len / 2)] = ['w00t', 123]; <del> benchmark(notDeepEqual, n, values, values2); <del> break; <del> case 'notDeepStrictEqual_primitiveOnly': <del> values = array.map((_, i) => [`str_${i}`, 123]); <del> values2 = values.slice(0); <del> values2[Math.floor(len / 2)] = ['w00t', 123]; <del> benchmark(notDeepStrictEqual, n, values, values2); <add> benchmark(strict ? notDeepStrictEqual : notDeepEqual, n, values, values2); <ide> break; <ide> case 'notDeepEqual_objectOnly': <ide> values = array.map((_, i) => [[`str_${i}`, 1], 123]); <ide> values2 = values.slice(0); <ide> values2[Math.floor(len / 2)] = [['w00t'], 123]; <del> benchmark(notDeepEqual, n, values, values2); <del> break; <del> case 'notDeepStrictEqual_objectOnly': <del> values = array.map((_, i) => [[`str_${i}`, 1], 123]); <del> values2 = values.slice(0); <del> values2[Math.floor(len / 2)] = [['w00t'], 123]; <del> benchmark(notDeepStrictEqual, n, values, values2); <add> benchmark(strict ? notDeepStrictEqual : notDeepEqual, n, values, values2); <ide> break; <ide> case 'notDeepEqual_mixed': <ide> values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]); <ide> values2 = values.slice(0); <ide> values2[0] = ['w00t', 123]; <del> benchmark(notDeepEqual, n, values, values2); <del> break; <del> case 'notDeepStrictEqual_mixed': <del> values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]); <del> values2 = values.slice(0); <del> values2[0] = ['w00t', 123]; <del> benchmark(notDeepStrictEqual, n, values, values2); <del> break; <del> case 'notDeepEqual_looseMatches': <del> values = array.map((_, i) => [i, i]); <del> values2 = values.slice().map((v) => [String(v[0]), String(v[1])]); <del> values2[len - 1] = [String(len + 1), String(len + 1)]; <del> benchmark(notDeepEqual, n, values, values2); <add> benchmark(strict ? notDeepStrictEqual : notDeepEqual, n, values, values2); <ide> break; <ide> default: <ide> throw new Error(`Unsupported method ${method}`); <ide><path>benchmark/assert/deepequal-object.js <ide> const common = require('../common.js'); <ide> const assert = require('assert'); <ide> <ide> const bench = common.createBenchmark(main, { <del> n: [1e6], <del> size: [1e2, 1e3, 1e4], <add> n: [5e3], <add> size: [1e2, 1e3, 5e4], <add> strict: [0, 1], <ide> method: [ <ide> 'deepEqual', <del> 'deepStrictEqual', <del> 'notDeepEqual', <del> 'notDeepStrictEqual' <add> 'notDeepEqual' <ide> ] <ide> }); <ide> <ide> function createObj(source, add = '') { <ide> nope: { <ide> bar: `123${add}`, <ide> a: [1, 2, 3], <del> baz: n <add> baz: n, <add> c: {}, <add> b: [] <ide> } <ide> })); <ide> } <ide> <del>function main({ size, n, method }) { <add>function main({ size, n, method, strict }) { <ide> // TODO: Fix this "hack". `n` should not be manipulated. <del> n = n / size; <add> n = Math.min(Math.ceil(n / size), 20); <ide> <ide> if (!method) <ide> method = 'deepEqual'; <ide> function main({ size, n, method }) { <ide> const expected = createObj(source); <ide> const expectedWrong = createObj(source, '4'); <ide> <add> if (strict) { <add> method = method.replace('eep', 'eepStrict'); <add> } <ide> const fn = assert[method]; <ide> const value2 = method.includes('not') ? expectedWrong : expected; <ide> <ide><path>benchmark/assert/deepequal-prims-and-objs-big-array-set.js <ide> const { deepEqual, deepStrictEqual, notDeepEqual, notDeepStrictEqual } = <ide> require('assert'); <ide> <ide> const primValues = { <del> 'null': null, <del> 'undefined': undefined, <ide> 'string': 'a', <ide> 'number': 1, <del> 'boolean': true, <ide> 'object': { 0: 'a' }, <del> 'array': [1, 2, 3], <del> 'new-array': new Array([1, 2, 3]) <add> 'array': [1, 2, 3] <ide> }; <ide> <ide> const bench = common.createBenchmark(main, { <ide> primitive: Object.keys(primValues), <ide> n: [25], <del> len: [1e5], <add> len: [2e4], <add> strict: [0, 1], <ide> method: [ <ide> 'deepEqual_Array', <del> 'deepStrictEqual_Array', <ide> 'notDeepEqual_Array', <del> 'notDeepStrictEqual_Array', <ide> 'deepEqual_Set', <del> 'deepStrictEqual_Set', <del> 'notDeepEqual_Set', <del> 'notDeepStrictEqual_Set' <add> 'notDeepEqual_Set' <ide> ] <ide> }); <ide> <ide> function run(fn, n, actual, expected) { <ide> bench.end(n); <ide> } <ide> <del>function main({ n, len, primitive, method }) { <add>function main({ n, len, primitive, method, strict }) { <ide> const prim = primValues[primitive]; <ide> const actual = []; <ide> const expected = []; <ide> function main({ n, len, primitive, method }) { <ide> // Empty string falls through to next line as default, mostly for tests. <ide> case '': <ide> case 'deepEqual_Array': <del> run(deepEqual, n, actual, expected); <del> break; <del> case 'deepStrictEqual_Array': <del> run(deepStrictEqual, n, actual, expected); <add> run(strict ? deepStrictEqual : deepEqual, n, actual, expected); <ide> break; <ide> case 'notDeepEqual_Array': <del> run(notDeepEqual, n, actual, expectedWrong); <del> break; <del> case 'notDeepStrictEqual_Array': <del> run(notDeepStrictEqual, n, actual, expectedWrong); <add> run(strict ? notDeepStrictEqual : notDeepEqual, n, actual, expectedWrong); <ide> break; <ide> case 'deepEqual_Set': <del> run(deepEqual, n, actualSet, expectedSet); <del> break; <del> case 'deepStrictEqual_Set': <del> run(deepStrictEqual, n, actualSet, expectedSet); <add> run(strict ? deepStrictEqual : deepEqual, n, actualSet, expectedSet); <ide> break; <ide> case 'notDeepEqual_Set': <del> run(notDeepEqual, n, actualSet, expectedWrongSet); <del> break; <del> case 'notDeepStrictEqual_Set': <del> run(notDeepStrictEqual, n, actualSet, expectedWrongSet); <add> run(strict ? notDeepStrictEqual : notDeepEqual, <add> n, actualSet, expectedWrongSet); <ide> break; <ide> default: <ide> throw new Error(`Unsupported method "${method}"`); <ide><path>benchmark/assert/deepequal-prims-and-objs-big-loop.js <ide> const common = require('../common.js'); <ide> const assert = require('assert'); <ide> <ide> const primValues = { <del> 'null': null, <del> 'undefined': undefined, <ide> 'string': 'a', <ide> 'number': 1, <del> 'boolean': true, <ide> 'object': { 0: 'a' }, <del> 'array': [1, 2, 3], <del> 'new-array': new Array([1, 2, 3]) <add> 'array': [1, 2, 3] <ide> }; <ide> <ide> const bench = common.createBenchmark(main, { <ide> primitive: Object.keys(primValues), <del> n: [1e6], <add> n: [2e4], <add> strict: [0, 1], <ide> method: [ <ide> 'deepEqual', <del> 'deepStrictEqual', <ide> 'notDeepEqual', <del> 'notDeepStrictEqual' <ide> ] <ide> }); <ide> <del>function main({ n, primitive, method }) { <add>function main({ n, primitive, method, strict }) { <ide> if (!method) <ide> method = 'deepEqual'; <ide> const prim = primValues[primitive]; <ide> const actual = prim; <ide> const expected = prim; <ide> const expectedWrong = 'b'; <ide> <add> if (strict) { <add> method = method.replace('eep', 'eepStrict'); <add> } <ide> const fn = assert[method]; <ide> const value2 = method.includes('not') ? expectedWrong : expected; <ide> <ide><path>benchmark/assert/deepequal-set.js <ide> const { deepEqual, deepStrictEqual, notDeepEqual, notDeepStrictEqual } = <ide> const bench = common.createBenchmark(main, { <ide> n: [5e2], <ide> len: [5e2], <add> strict: [0, 1], <ide> method: [ <ide> 'deepEqual_primitiveOnly', <del> 'deepStrictEqual_primitiveOnly', <ide> 'deepEqual_objectOnly', <del> 'deepStrictEqual_objectOnly', <ide> 'deepEqual_mixed', <del> 'deepStrictEqual_mixed', <del> 'deepEqual_looseMatches', <ide> 'notDeepEqual_primitiveOnly', <del> 'notDeepStrictEqual_primitiveOnly', <ide> 'notDeepEqual_objectOnly', <del> 'notDeepStrictEqual_objectOnly', <del> 'notDeepEqual_mixed', <del> 'notDeepStrictEqual_mixed', <del> 'notDeepEqual_looseMatches', <add> 'notDeepEqual_mixed' <ide> ] <ide> }); <ide> <ide> function benchmark(method, n, values, values2) { <ide> bench.end(n); <ide> } <ide> <del>function main({ n, len, method }) { <add>function main({ n, len, method, strict }) { <ide> const array = Array(len).fill(1); <ide> <ide> var values, values2; <ide> function main({ n, len, method }) { <ide> // Empty string falls through to next line as default, mostly for tests. <ide> case 'deepEqual_primitiveOnly': <ide> values = array.map((_, i) => `str_${i}`); <del> benchmark(deepEqual, n, values); <del> break; <del> case 'deepStrictEqual_primitiveOnly': <del> values = array.map((_, i) => `str_${i}`); <del> benchmark(deepStrictEqual, n, values); <add> benchmark(strict ? deepStrictEqual : deepEqual, n, values); <ide> break; <ide> case 'deepEqual_objectOnly': <ide> values = array.map((_, i) => [`str_${i}`, null]); <del> benchmark(deepEqual, n, values); <del> break; <del> case 'deepStrictEqual_objectOnly': <del> values = array.map((_, i) => [`str_${i}`, null]); <del> benchmark(deepStrictEqual, n, values); <add> benchmark(strict ? deepStrictEqual : deepEqual, n, values); <ide> break; <ide> case 'deepEqual_mixed': <ide> values = array.map((_, i) => { <ide> return i % 2 ? [`str_${i}`, null] : `str_${i}`; <ide> }); <del> benchmark(deepEqual, n, values); <del> break; <del> case 'deepStrictEqual_mixed': <del> values = array.map((_, i) => { <del> return i % 2 ? [`str_${i}`, null] : `str_${i}`; <del> }); <del> benchmark(deepStrictEqual, n, values); <del> break; <del> case 'deepEqual_looseMatches': <del> values = array.map((_, i) => i); <del> values2 = values.slice().map((v) => String(v)); <del> benchmark(deepEqual, n, values, values2); <add> benchmark(strict ? deepStrictEqual : deepEqual, n, values); <ide> break; <ide> case 'notDeepEqual_primitiveOnly': <ide> values = array.map((_, i) => `str_${i}`); <ide> values2 = values.slice(0); <ide> values2[Math.floor(len / 2)] = 'w00t'; <del> benchmark(notDeepEqual, n, values, values2); <del> break; <del> case 'notDeepStrictEqual_primitiveOnly': <del> values = array.map((_, i) => `str_${i}`); <del> values2 = values.slice(0); <del> values2[Math.floor(len / 2)] = 'w00t'; <del> benchmark(notDeepStrictEqual, n, values, values2); <add> benchmark(strict ? notDeepStrictEqual : notDeepEqual, n, values, values2); <ide> break; <ide> case 'notDeepEqual_objectOnly': <ide> values = array.map((_, i) => [`str_${i}`, null]); <ide> values2 = values.slice(0); <ide> values2[Math.floor(len / 2)] = ['w00t']; <del> benchmark(notDeepEqual, n, values, values2); <del> break; <del> case 'notDeepStrictEqual_objectOnly': <del> values = array.map((_, i) => [`str_${i}`, null]); <del> values2 = values.slice(0); <del> values2[Math.floor(len / 2)] = ['w00t']; <del> benchmark(notDeepStrictEqual, n, values, values2); <add> benchmark(strict ? notDeepStrictEqual : notDeepEqual, n, values, values2); <ide> break; <ide> case 'notDeepEqual_mixed': <ide> values = array.map((_, i) => { <ide> return i % 2 ? [`str_${i}`, null] : `str_${i}`; <ide> }); <ide> values2 = values.slice(); <ide> values2[0] = 'w00t'; <del> benchmark(notDeepEqual, n, values, values2); <del> break; <del> case 'notDeepStrictEqual_mixed': <del> values = array.map((_, i) => { <del> return i % 2 ? [`str_${i}`, null] : `str_${i}`; <del> }); <del> values2 = values.slice(); <del> values2[0] = 'w00t'; <del> benchmark(notDeepStrictEqual, n, values, values2); <del> break; <del> case 'notDeepEqual_looseMatches': <del> values = array.map((_, i) => i); <del> values2 = values.slice().map((v) => String(v)); <del> values2[len - 1] = String(len + 1); <del> benchmark(notDeepEqual, n, values, values2); <add> benchmark(strict ? notDeepStrictEqual : notDeepEqual, n, values, values2); <ide> break; <ide> default: <ide> throw new Error(`Unsupported method "${method}"`); <ide><path>benchmark/assert/deepequal-typedarrays.js <ide> const bench = common.createBenchmark(main, { <ide> type: [ <ide> 'Int8Array', <ide> 'Uint8Array', <del> 'Int16Array', <del> 'Uint16Array', <del> 'Int32Array', <del> 'Uint32Array', <ide> 'Float32Array', <ide> 'Float64Array', <ide> 'Uint8ClampedArray', <ide> ], <del> n: [1], <add> n: [5e2], <add> strict: [0, 1], <ide> method: [ <ide> 'deepEqual', <del> 'deepStrictEqual', <ide> 'notDeepEqual', <del> 'notDeepStrictEqual' <ide> ], <del> len: [1e6] <add> len: [1e2, 5e3] <ide> }); <ide> <del>function main({ type, n, len, method }) { <add>function main({ type, n, len, method, strict }) { <ide> if (!method) <ide> method = 'deepEqual'; <ide> const clazz = global[type]; <ide> const actual = new clazz(len); <ide> const expected = new clazz(len); <del> const expectedWrong = Buffer.alloc(len); <add> const expectedWrong = new clazz(len); <ide> const wrongIndex = Math.floor(len / 2); <ide> expectedWrong[wrongIndex] = 123; <ide> <add> if (strict) { <add> method = method.replace('eep', 'eepStrict'); <add> } <ide> const fn = assert[method]; <ide> const value2 = method.includes('not') ? expectedWrong : expected; <ide> <ide> bench.start(); <ide> for (var i = 0; i < n; ++i) { <add> actual[0] = i; <add> value2[0] = i; <ide> fn(actual, value2); <ide> } <ide> bench.end(n); <ide><path>benchmark/assert/ok.js <ide> const common = require('../common.js'); <ide> const assert = require('assert'); <ide> <ide> const bench = common.createBenchmark(main, { <del> n: [1e9] <add> n: [1e5] <ide> }); <ide> <ide> function main({ n }) { <ide><path>benchmark/assert/throws.js <ide> const common = require('../common.js'); <ide> const { throws, doesNotThrow } = require('assert'); <ide> <ide> const bench = common.createBenchmark(main, { <del> n: [1e6], <add> n: [1e4], <ide> method: [ <ide> 'doesNotThrow', <del> 'throws', <ide> 'throws_TypeError', <ide> 'throws_RegExp' <ide> ] <ide> function main({ n, method }) { <ide> } <ide> bench.end(n); <ide> break; <del> case 'throws': <del> bench.start(); <del> for (i = 0; i < n; ++i) { <del> throws(throwError); <del> } <del> bench.end(n); <del> break; <ide> case 'throws_TypeError': <ide> bench.start(); <ide> for (i = 0; i < n; ++i) { <ide><path>test/parallel/test-benchmark-assert.js <ide> const runBenchmark = require('../common/benchmark'); <ide> runBenchmark( <ide> 'assert', <ide> [ <add> 'strict=1', <ide> 'len=1', <ide> 'method=', <ide> 'n=1',
10
Javascript
Javascript
add mustcall to openssl-client-cert-engine
c903c99d4bac9e13a34e97a4a98bd290925fda68
<ide><path>test/addons/openssl-client-cert-engine/test.js <ide> const serverOptions = { <ide> rejectUnauthorized: true <ide> }; <ide> <del>const server = https.createServer(serverOptions, (req, res) => { <add>const server = https.createServer(serverOptions, common.mustCall((req, res) => { <ide> res.writeHead(200); <ide> res.end('hello world'); <del>}).listen(0, common.localhostIPv4, () => { <add>})).listen(0, common.localhostIPv4, common.mustCall(() => { <ide> const clientOptions = { <ide> method: 'GET', <ide> host: common.localhostIPv4, <ide> const server = https.createServer(serverOptions, (req, res) => { <ide> })); <ide> <ide> req.end(); <del>}); <add>}));
1
Javascript
Javascript
reduce scope of imports
fe3931b0775a91b1661df8ca708c572d571f4b73
<ide><path>src/controllers/controller.bar.js <ide> <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import elements from '../elements'; <add>import Rectangle from '../elements/element.rectangle'; <ide> import helpers from '../helpers'; <ide> <ide> const valueOrDefault = helpers.valueOrDefault; <ide> function isFloatBar(custom) { <ide> <ide> export default DatasetController.extend({ <ide> <del> dataElementType: elements.Rectangle, <add> dataElementType: Rectangle, <ide> <ide> /** <ide> * @private <ide><path>src/controllers/controller.bubble.js <ide> <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import elements from '../elements'; <add>import Point from '../elements/element.point'; <ide> import helpers from '../helpers'; <ide> <ide> const resolve = helpers.options.resolve; <ide> export default DatasetController.extend({ <ide> /** <ide> * @protected <ide> */ <del> dataElementType: elements.Point, <add> dataElementType: Point, <ide> <ide> /** <ide> * @private <ide><path>src/controllers/controller.doughnut.js <ide> <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import elements from '../elements'; <add>import Arc from '../elements/element.arc'; <ide> import helpers from '../helpers'; <ide> <ide> const valueOrDefault = helpers.valueOrDefault; <ide> defaults._set('doughnut', { <ide> <ide> export default DatasetController.extend({ <ide> <del> dataElementType: elements.Arc, <add> dataElementType: Arc, <ide> <ide> linkScales: helpers.noop, <ide> <ide><path>src/controllers/controller.line.js <ide> <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import elements from '../elements'; <add>import Line from '../elements/element.line'; <add>import Point from '../elements/element.point'; <ide> import helpers from '../helpers'; <ide> <ide> const valueOrDefault = helpers.valueOrDefault; <ide> defaults._set('line', { <ide> <ide> export default DatasetController.extend({ <ide> <del> datasetElementType: elements.Line, <add> datasetElementType: Line, <ide> <del> dataElementType: elements.Point, <add> dataElementType: Point, <ide> <ide> /** <ide> * @private <ide><path>src/controllers/controller.polarArea.js <ide> <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import elements from '../elements'; <add>import Arc from '../elements/element.arc'; <ide> import helpers from '../helpers'; <ide> <ide> const resolve = helpers.options.resolve; <ide> function getStartAngleRadians(deg) { <ide> <ide> export default DatasetController.extend({ <ide> <del> dataElementType: elements.Arc, <add> dataElementType: Arc, <ide> <ide> /** <ide> * @private <ide><path>src/controllers/controller.radar.js <ide> <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import elements from '../elements'; <add>import Line from '../elements/element.line'; <add>import Point from '../elements/element.point'; <ide> import helpers from '../helpers'; <ide> <ide> const valueOrDefault = helpers.valueOrDefault; <ide> defaults._set('radar', { <ide> }); <ide> <ide> export default DatasetController.extend({ <del> datasetElementType: elements.Line, <add> datasetElementType: Line, <ide> <del> dataElementType: elements.Point, <add> dataElementType: Point, <ide> <ide> /** <ide> * @private <ide><path>src/core/core.plugins.js <ide> 'use strict'; <ide> <ide> import defaults from './core.defaults'; <del>import helpers from '../helpers/'; <add>import {clone} from '../helpers/helpers.core'; <ide> <ide> defaults._set('plugins', {}); <ide> <ide> export default { <ide> } <ide> <ide> if (opts === true) { <del> opts = helpers.clone(defaults.plugins[id]); <add> opts = clone(defaults.plugins[id]); <ide> } <ide> <ide> plugins.push(plugin); <ide><path>src/core/core.scaleService.js <ide> 'use strict'; <ide> <ide> import defaults from './core.defaults'; <del>import helpers from '../helpers'; <add>import {clone, each, extend, merge} from '../helpers/helpers.core'; <ide> import layouts from './core.layouts'; <ide> <ide> export default { <ide> export default { <ide> defaults: {}, <ide> registerScaleType: function(type, scaleConstructor, scaleDefaults) { <ide> this.constructors[type] = scaleConstructor; <del> this.defaults[type] = helpers.clone(scaleDefaults); <add> this.defaults[type] = clone(scaleDefaults); <ide> }, <ide> getScaleConstructor: function(type) { <ide> return Object.prototype.hasOwnProperty.call(this.constructors, type) ? this.constructors[type] : undefined; <ide> }, <ide> getScaleDefaults: function(type) { <ide> // Return the scale defaults merged with the global settings so that we always use the latest ones <del> return Object.prototype.hasOwnProperty.call(this.defaults, type) ? helpers.merge({}, [defaults.scale, this.defaults[type]]) : {}; <add> return Object.prototype.hasOwnProperty.call(this.defaults, type) ? merge({}, [defaults.scale, this.defaults[type]]) : {}; <ide> }, <ide> updateScaleDefaults: function(type, additions) { <ide> var me = this; <ide> if (Object.prototype.hasOwnProperty.call(me.defaults, type)) { <del> me.defaults[type] = helpers.extend(me.defaults[type], additions); <add> me.defaults[type] = extend(me.defaults[type], additions); <ide> } <ide> }, <ide> addScalesToLayout: function(chart) { <ide> // Adds each scale to the chart.boxes array to be sized accordingly <del> helpers.each(chart.scales, function(scale) { <add> each(chart.scales, function(scale) { <ide> // Set ILayoutItem parameters for backwards compatibility <ide> scale.fullWidth = scale.options.fullWidth; <ide> scale.position = scale.options.position;
8
Javascript
Javascript
get camera values from matrix world
dd184263c3225e65c5b342be05d5da5c26fdc8da
<ide><path>editor/js/Sidebar.Object.js <ide> Sidebar.Object = function ( editor ) { <ide> <ide> if ( editor.selected.isCamera === true && cameraTransitioning === false ) { <ide> <add> editor.selected.updateMatrixWorld( true ); <ide> editor.currentCamera = transitionCamera; <ide> transitionCamera.copy( editor.selected ); <ide> cameraViewButton.dom.setAttribute( 'viewset', '' ); <ide> Sidebar.Object = function ( editor ) { <ide> <ide> function getCameraData( camera ) { <ide> <add> var position = new THREE.Vector3(); <add> var quaternion = new THREE.Quaternion(); <add> var scale = new THREE.Vector3(); <add> camera.matrixWorld.decompose( position, quaternion, scale ); <ide> return { <del> position: camera.position.clone(), <del> quaternion: camera.quaternion.clone(), <add> position: position, <add> quaternion: quaternion, <ide> fov: camera.fov, <ide> near: camera.near, <ide> far: camera.far,
1
Python
Python
use a consistent method name
f5ad09c1a82bd48e6821b03b4dcd60bdd492f27d
<ide><path>libcloud/compute/drivers/gce.py <ide> def set_named_ports(self, named_ports): <ide> return self.driver.ex_instancegroup_set_named_ports( <ide> instancegroup=self.instance_group, named_ports=named_ports) <ide> <del> def set_autoHealingPolicies(self, healthcheck, initialdelaysec): <add> def set_autohealingpolicies(self, healthcheck, initialdelaysec): <ide> """ <ide> Sets the autohealing policies for the instance for the instance group <ide> controlled by this manager.
1
Ruby
Ruby
unify environment variables
fb0052068f3f948e0103066bb6a80099c13cc600
<ide><path>Library/Homebrew/env_config.rb <add># frozen_string_literal: true <add> <add>module Homebrew <add> module EnvConfig <add> module_function <add> <add> ENVS = { <add> HOMEBREW_ARCH: { <add> description: "Linux only: Homebrew will pass the set value to type name to the compiler's `-march` option.", <add> default: "native", <add> }, <add> HOMEBREW_ARTIFACT_DOMAIN: { <add> description: "Instructs Homebrew to prefix all download URLs, including those for bottles, with this " \ <add> "variable. For example, `HOMEBREW_ARTIFACT_DOMAIN=http://localhost:8080` will cause a " \ <add> "formula with the URL `https://example.com/foo.tar.gz` to instead download from " \ <add> "`http://localhost:8080/example.com/foo.tar.gz`.", <add> }, <add> HOMEBREW_AUTO_UPDATE_SECS: { <add> description: "Homebrew will only check for autoupdates once per this seconds interval.", <add> default: 300, <add> }, <add> HOMEBREW_BAT: { <add> description: "Homebrew will use `bat` for the `brew cat` command.", <add> boolean: true, <add> }, <add> HOMEBREW_BINTRAY_KEY: { <add> description: "Homebrew uses this API key when accessing the Bintray API (where bottles are stored).", <add> }, <add> HOMEBREW_BINTRAY_USER: { <add> description: "Homebrew uses this username when accessing the Bintray API (where bottles are stored).", <add> }, <add> HOMEBREW_BOTTLE_DOMAIN: { <add> description: "Instructs Homebrew to use the specified URL as its download mirror for bottles. " \ <add> "For example, `HOMEBREW_BOTTLE_DOMAIN=http://localhost:8080` will cause all bottles to " \ <add> "download from the prefix `http://localhost:8080/`.", <add> default_text: "macOS: `https://homebrew.bintray.com/`, Linux: `https://linuxbrew.bintray.com/`.", <add> default: HOMEBREW_BOTTLE_DEFAULT_DOMAIN, <add> }, <add> HOMEBREW_BREW_GIT_REMOTE: { <add> description: "Instructs Homebrew to use the specified URL as its Homebrew/brew `git`(1) remote.", <add> default: HOMEBREW_BREW_DEFAULT_GIT_REMOTE, <add> }, <add> HOMEBREW_BROWSER: { <add> description: "Homebrew uses this setting as the browser when opening project homepages.", <add> default_text: "`$BROWSER` or the OS's default browser.", <add> }, <add> HOMEBREW_CACHE: { <add> description: "Instructs Homebrew to use the specified directory as the download cache.", <add> default_text: "macOS: `$HOME/Library/Caches/Homebrew`, " \ <add> "Linux: `$XDG_CACHE_HOME/Homebrew` or `$HOME/.cache/Homebrew`.", <add> default: HOMEBREW_DEFAULT_CACHE, <add> }, <add> HOMEBREW_COLOR: { <add> description: "Homebrew force colour output on non-TTY outputs.", <add> boolean: true, <add> }, <add> HOMEBREW_CORE_GIT_REMOTE: { <add> description: "instructs Homebrew to use the specified URL as its Homebrew/homebrew-core `git`(1) remote.", <add> default_text: "macOS: `https://github.com/Homebrew/homebrew-core`, " \ <add> "Linux: `https://github.com/Homebrew/linuxbrew-core`.", <add> default: HOMEBREW_CORE_DEFAULT_GIT_REMOTE, <add> }, <add> HOMEBREW_CURLRC: { <add> description: "Homebrew will not pass `--disable` when invoking `curl`(1), which disables the " \ <add> "use of `curlrc`.", <add> boolean: true, <add> }, <add> HOMEBREW_CURL_RETRIES: { <add> description: "Homebrew will pass the given retry count to `--retry` when invoking `curl`(1).", <add> default: 3, <add> }, <add> HOMEBREW_CURL_VERBOSE: { <add> description: "Homebrew will pass `--verbose` when invoking `curl`(1).", <add> boolean: true, <add> }, <add> HOMEBREW_DEVELOPER: { <add> description: "Homebrew will tweak behaviour to be more relevant for Homebrew developers (active or " \ <add> "budding), e.g. turning warnings into errors.", <add> boolean: true, <add> }, <add> HOMEBREW_DISABLE_LOAD_FORMULA: { <add> description: "Homebrew will refuse to load formulae. This is useful when formulae are not trusted (such " \ <add> "as in pull requests).", <add> boolean: true, <add> }, <add> HOMEBREW_DISPLAY: { <add> description: "Homebrew will use this X11 display when opening a page in a browser, for example with " \ <add> "`brew home`. Primarily useful on Linux.", <add> default_text: "`$DISPLAY`.", <add> }, <add> HOMEBREW_DISPLAY_INSTALL_TIMES: { <add> description: "Homebrew will print install times for each formula at the end of the run.", <add> boolean: true, <add> }, <add> HOMEBREW_EDITOR: { <add> description: "Homebrew will use this editor when editing a single formula, or several formulae in the " \ <add> "same directory.\n\n *Note:* `brew edit` will open all of Homebrew as discontinuous files " \ <add> "and directories. Visual Studio Code can handle this correctly in project mode, but many " \ <add> "editors will do strange things in this case.", <add> default_text: "`$EDITOR` or `$VISUAL`.", <add> }, <add> HOMEBREW_FAIL_LOG_LINES: { <add> description: "Homebrew will output this many lines of output on formula `system` failures.", <add> default: 15, <add> }, <add> HOMEBREW_FORCE_BREWED_CURL: { <add> description: "Homebrew will always use a Homebrew-installed `curl`(1) rather than the system version. " \ <add> "Automatically set if the system version of `curl` is too old.", <add> }, <add> HOMEBREW_FORCE_BREWED_GIT: { <add> description: "Homebrew will always use a Homebrew-installed `git`(1) rather than the system version. " \ <add> "Automatically set if the system version of `git` is too old.", <add> }, <add> HOMEBREW_FORCE_HOMEBREW_ON_LINUX: { <add> description: "Homebrew running on Linux will use URLs for Homebrew on macOS. This is useful when merging" \ <add> "pull requests on Linux for macOS.", <add> boolean: true, <add> }, <add> HOMEBREW_FORCE_VENDOR_RUBY: { <add> description: "Homebrew will always use its vendored, relocatable Ruby version even if the system version " \ <add> "of Ruby is new enough.", <add> boolean: true, <add> }, <add> HOMEBREW_GITHUB_API_PASSWORD: { <add> description: "GitHub password for authentication with the GitHub API, used by Homebrew for features" \ <add> "such as `brew search`. We strongly recommend using `HOMEBREW_GITHUB_API_TOKEN` instead.", <add> }, <add> HOMEBREW_GITHUB_API_TOKEN: { <add> description: "A personal access token for the GitHub API, used by Homebrew for features such as " \ <add> "`brew search`. You can create one at <https://github.com/settings/tokens>. If set, " \ <add> "GitHub will allow you a greater number of API requests. For more information, see: " \ <add> "<https://developer.github.com/v3/#rate-limiting>\n\n *Note:* Homebrew doesn't " \ <add> "require permissions for any of the scopes.", <add> }, <add> HOMEBREW_GITHUB_API_USERNAME: { <add> description: "GitHub username for authentication with the GitHub API, used by Homebrew for features " \ <add> "such as `brew search`. We strongly recommend using `HOMEBREW_GITHUB_API_TOKEN` instead.", <add> }, <add> HOMEBREW_GIT_EMAIL: { <add> description: "Homebrew will set the Git author and committer name to this value.", <add> }, <add> HOMEBREW_GIT_NAME: { <add> description: "Homebrew will set the Git author and committer email to this value.", <add> }, <add> HOMEBREW_INSTALL_BADGE: { <add> description: "Text printed before the installation summary of each successful build.", <add> default_text: 'The "Beer Mug" emoji.', <add> default: "🍺", <add> }, <add> HOMEBREW_LOGS: { <add> description: "IHomebrew will use the specified directory to store log files.", <add> default_text: "macOS: `$HOME/Library/Logs/Homebrew`, "\ <add> "Linux: `$XDG_CACHE_HOME/Homebrew/Logs` or `$HOME/.cache/Homebrew/Logs`.", <add> default: HOMEBREW_DEFAULT_LOGS, <add> }, <add> HOMEBREW_MAKE_JOBS: { <add> description: "Instructs Homebrew to use the value of `HOMEBREW_MAKE_JOBS` as the number of " \ <add> "parallel jobs to run when building with `make`(1).", <add> default_text: "The number of available CPU cores.", <add> default: lambda { <add> require "os" <add> require "hardware" <add> Hardware::CPU.cores <add> }, <add> }, <add> HOMEBREW_NO_ANALYTICS: { <add> description: "Homebrew will not send analytics. See: <https://docs.brew.sh/Analytics>.", <add> boolean: true, <add> }, <add> HOMEBREW_NO_AUTO_UPDATE: { <add> description: "Homebrew will not auto-update before running `brew install`, `brew upgrade` or `brew tap`.", <add> boolean: true, <add> }, <add> HOMEBREW_NO_BOTTLE_SOURCE_FALLBACK: { <add> description: "Homebrew will fail on the failure of installation from a bottle rather than " \ <add> "falling back to building from source.", <add> boolean: true, <add> }, <add> HOMEBREW_NO_COLOR: { <add> description: "Homebrew will not print text with colour added.", <add> default_text: "`$NO_COLOR`.", <add> boolean: true, <add> }, <add> HOMEBREW_NO_COMPAT: { <add> description: "Homebrew disables all use of legacy compatibility code.", <add> boolean: true, <add> }, <add> HOMEBREW_NO_EMOJI: { <add> description: "Homebrew will not print the `HOMEBREW_INSTALL_BADGE` on a successful build." \ <add> "\n\n *Note:* Homebrew will only try to print emoji on OS X Lion or newer.", <add> boolean: true, <add> }, <add> HOMEBREW_NO_GITHUB_API: { <add> description: "Homebrew will not use the GitHub API, e.g. for searches or fetching relevant issues " \ <add> "on a failed install.", <add> boolean: true, <add> }, <add> HOMEBREW_NO_INSECURE_REDIRECT: { <add> description: "Homebrew will not permit redirects from secure HTTPS to insecure HTTP." \ <add> "\n\n *Note:* While ensuring your downloads are fully secure, this is likely to cause " \ <add> "from-source SourceForge, some GNU & GNOME based formulae to fail to download.", <add> boolean: true, <add> }, <add> HOMEBREW_NO_INSTALL_CLEANUP: { <add> description: "`brew install`, `brew upgrade` and `brew reinstall` will never automatically cleanup " \ <add> "installed/upgraded/reinstalled formulae or all formulae every 30 days.", <add> boolean: true, <add> }, <add> HOMEBREW_PRY: { <add> description: "Homebrew will use Pry for the `brew irb` command.", <add> boolean: true, <add> }, <add> HOMEBREW_SKIP_OR_LATER_BOTTLES: { <add> description: "Along with `HOMEBREW_DEVELOPER` Homebrew will not use bottles from older versions of macOS. " \ <add> "This is useful in Homebrew development on new macOS versions.", <add> boolean: true, <add> }, <add> HOMEBREW_SVN: { <add> description: "Forces Homebrew to use a particular `svn` binary. Otherwise, a Homebrew-built Subversion " \ <add> "if installed, or the system-provided binary.", <add> }, <add> HOMEBREW_TEMP: { <add> description: "Instructs Homebrew to use `HOMEBREW_TEMP` as the temporary directory for building " \ <add> "packages. This may be needed if your system temp directory and Homebrew prefix are on " \ <add> "different volumes, as macOS has trouble moving symlinks across volumes when the target" \ <add> "does not yet exist. This issue typically occurs when using FileVault or custom SSD" \ <add> "configurations.", <add> default_text: "macOS: `/private/tmp`, Linux: `/tmp`.", <add> default: HOMEBREW_DEFAULT_TEMP, <add> }, <add> HOMEBREW_UPDATE_TO_TAG: { <add> description: "Instructs Homebrew to always use the latest stable tag (even if developer commands " \ <add> "have been run).", <add> boolean: true, <add> }, <add> HOMEBREW_VERBOSE: { <add> description: "Homebrew always assumes `--verbose` when running commands.", <add> boolean: true, <add> }, <add> HOMEBREW_VERBOSE_USING_DOTS: { <add> boolean: true, <add> description: "Homebrew's verbose output will print a `.` no more than once a minute. This can be " \ <add> "useful to avoid long-running Homebrew commands being killed due to no output.", <add> }, <add> all_proxy: { <add> description: "Sets the SOCKS5 proxy to be used by `curl`(1), `git`(1) and `svn`(1) when downloading " \ <add> "through Homebrew.", <add> }, <add> ftp_proxy: { <add> description: "Sets the FTP proxy to be used by `curl`(1), `git`(1) and `svn`(1) when downloading " \ <add> "through Homebrew.", <add> }, <add> http_proxy: { <add> description: "Sets the HTTP proxy to be used by `curl`(1), `git`(1) and `svn`(1) when downloading " \ <add> "through Homebrew.", <add> }, <add> https_proxy: { <add> description: "Sets the HTTPS proxy to be used by `curl`(1), `git`(1) and `svn`(1) when downloading " \ <add> "through Homebrew.", <add> }, <add> no_proxy: { <add> description: "Sets the comma-separated list of hostnames and domain names that should be excluded " \ <add> "from proxying by `curl`(1), `git`(1) and `svn`(1) when downloading through Homebrew.", <add> }, <add> }.freeze <add> <add> def env_method_name(env, hash) <add> method_name = env.to_s <add> .sub(/^HOMEBREW_/, "") <add> .downcase <add> method_name = "#{method_name}?" if hash[:boolean] <add> method_name <add> end <add> <add> ENVS.each do |env, hash| <add> method_name = env_method_name(env, hash) <add> env = env.to_s <add> <add> if hash[:boolean] <add> define_method(method_name) do <add> ENV[env].present? <add> end <add> elsif hash[:default].present? <add> # Needs a custom implementation. <add> next if env == "HOMEBREW_MAKE_JOBS" <add> <add> define_method(method_name) do <add> ENV[env].presence || hash.fetch(:default).to_s <add> end <add> else <add> define_method(method_name) do <add> ENV[env].presence <add> end <add> end <add> end <add> <add> # Needs a custom implementation. <add> def make_jobs <add> jobs = ENV["HOMEBREW_MAKE_JOBS"].to_i <add> return jobs.to_s if jobs.positive? <add> <add> ENVS.fetch(:HOMEBREW_MAKE_JOBS) <add> .fetch(:default) <add> .call <add> .to_s <add> end <add> end <add>end
1
Text
Text
add mutt data to inthewild.md
925153f5a5442e3825b741fb510375f4b2fa1fc0
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Modernizing Medicine](https://www.modmed.com/) [[@kehv1n](https://github.com/kehv1n), [@dalupus](https://github.com/dalupus)] <ide> 1. [Movember](https://movember.com) <ide> 1. [Multiply](https://www.multiply.com) [[@nrhvyc](https://github.com/nrhvyc)] <add>1. [Mutt Data](https://muttdata.ai/) [[@plorenzatto](https://github.com/plorenzatto)] <ide> 1. [NEXT Trucking](https://www.nexttrucking.com/) [[@earthmancash2](https://github.com/earthmancash2), [@kppullin](https://github.com/kppullin)] <ide> 1. [National Bank of Canada](https://nbc.ca) [[@brilhana](https://github.com/brilhana)] <ide> 1. [Nav, Inc.](https://nav.com/) [[@tigerjz32](https://github.com/tigerjz32)]
1
Javascript
Javascript
fix invalid ping response throwing error in client
71ae456a7ca706ce8eaa006486d8bebf0beff7af
<ide><path>packages/next/client/on-demand-entries-client.js <ide> export default async ({ assetPrefix }) => { <ide> } <ide> <ide> evtSource.onmessage = event => { <del> const payload = JSON.parse(event.data) <del> if (payload.invalid) { <del> // Payload can be invalid even if the page does not exist. <del> // So, we need to make sure it exists before reloading. <del> fetch(location.href, { <del> credentials: 'same-origin' <del> }).then(pageRes => { <del> if (pageRes.status === 200) { <del> location.reload() <del> } <del> }) <del> } <add> try { <add> const payload = JSON.parse(event.data) <add> if (payload.invalid) { <add> // Payload can be invalid even if the page does not exist. <add> // So, we need to make sure it exists before reloading. <add> fetch(location.href, { <add> credentials: 'same-origin' <add> }).then(pageRes => { <add> if (pageRes.status === 200) { <add> location.reload() <add> } <add> }) <add> } <add> } catch (_) { /* noop */ } <ide> } <ide> } <ide> <ide><path>packages/next/server/on-demand-entry-handler.js <ide> export default function onDemandEntryHandler (devMiddleware, multiCompiler, { <ide> <ide> const runPing = () => { <ide> const data = handlePing(query.page) <add> if (!data) return <ide> res.write('data: ' + JSON.stringify(data) + '\n\n') <ide> } <ide> const pingInterval = setInterval(() => runPing(), 5000)
2
PHP
PHP
remove casts that aren't needed now
03a051542cd0ebb2c075a38a47709ee5bfaab59f
<ide><path>src/View/Widget/MultiCheckboxWidget.php <ide> protected function _isSelected(string $key, $selected): bool <ide> } <ide> $isArray = is_array($selected); <ide> if (!$isArray) { <del> return (string)$key === (string)$selected; <add> return $key === (string)$selected; <ide> } <ide> $strict = !is_numeric($key); <ide> <del> return in_array((string)$key, $selected, $strict); <add> return in_array($key, $selected, $strict); <ide> } <ide> <ide> /** <ide> protected function _isDisabled(string $key, $disabled): bool <ide> } <ide> $strict = !is_numeric($key); <ide> <del> return in_array((string)$key, $disabled, $strict); <add> return in_array($key, $disabled, $strict); <ide> } <ide> <ide> /**
1
Python
Python
add test for initialization of bert2rnd
1e68c28670cc8d0e8d20ca9fadc697f03908015b
<ide><path>examples/run_summarization.py <add># coding=utf-8 <add># Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. <add># Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. <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>""" Finetuning seq2seq models for abstractive summarization. <add> <add>The finetuning method for abstractive summarization is inspired by [1]. We <add>concatenate the document and summary, mask words of the summary at random and <add>maximizing the likelihood of masked words. <add> <add>[1] Dong Li, Nan Yang, Wenhui Wang, Furu Wei, Xiaodong Liu, Yu Wang, Jianfeng <add>Gao, Ming Zhou, and Hsiao-Wuen Hon. “Unified Language Model Pre-Training for <add>Natural Language Understanding and Generation.” (May 2019) ArXiv:1905.03197 <add>""" <add> <add>import logging <add>import random <add> <add>import numpy as np <add>import torch <add> <add>logger = logging.getLogger(__name__) <add> <add> <add>def set_seed(args): <add> random.seed(args.seed) <add> np.random.seed(args.seed) <add> torch.manual_seed(args.seed) <add> if args.n_gpu > 0: <add> torch.cuda.manual_seed_all(args.seed) <add> <add> <add>def train(args, train_dataset, model, tokenizer): <add> raise NotImplementedError <add> <add> <add>def evaluate(args, model, tokenizer, prefix=""): <add> raise NotImplementedError <ide><path>transformers/tests/modeling_bert_test.py <ide> def create_and_check_bert2rnd(self, config, input_ids, token_type_ids, input_mas <ide> config.num_choices = self.num_choices <ide> model = Bert2Rnd(config=config) <ide> model.eval() <del> bert2bert_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <del> bert2bert_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <del> bert2bert_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <del> _ = model(bert2bert_inputs_ids, <del> attention_mask=bert2bert_input_mask, <del> token_type_ids=bert2bert_token_type_ids) <add> bert2rnd_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <add> bert2rnd_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <add> bert2rnd_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <add> _ = model(bert2rnd_inputs_ids, <add> attention_mask=bert2rnd_input_mask, <add> token_type_ids=bert2rnd_token_type_ids) <ide> <ide> def prepare_config_and_inputs_for_common(self): <ide> config_and_inputs = self.prepare_config_and_inputs()
2
Text
Text
fix capitalization, markdown syntax link in docs
14fad0d6902550cd61fc07370759ef785effa207
<ide><path>docs/topics/documenting-your-api.md <ide> The built-in API documentation includes: <ide> ### Installation <ide> <ide> The `coreapi` library is required as a dependency for the API docs. Make sure <del>to install the latest version. The `pygments` and `markdown` libraries <add>to install the latest version. The `Pygments` and `Markdown` libraries <ide> are optional but recommended. <ide> <ide> To install the API documentation, you'll need to include it in your project's URLconf: <ide> When working with viewsets, an appropriate suffix is appended to each generated <ide> <ide> The description in the browsable API is generated from the docstring of the view or viewset. <ide> <del>If the python `markdown` library is installed, then [markdown syntax][markdown] may be used in the docstring, and will be converted to HTML in the browsable API. For example: <add>If the python `Markdown` library is installed, then [markdown syntax][markdown] may be used in the docstring, and will be converted to HTML in the browsable API. For example: <ide> <ide> class AccountListView(views.APIView): <ide> """ <ide> To implement a hypermedia API you'll need to decide on an appropriate media type <ide> [open-api]: https://openapis.org/ <ide> [rest-framework-docs]: https://github.com/marcgibbons/django-rest-framework-docs <ide> [apiary]: https://apiary.io/ <del>[markdown]: https://daringfireball.net/projects/markdown/ <add>[markdown]: https://daringfireball.net/projects/markdown/syntax <ide> [hypermedia-docs]: rest-hypermedia-hateoas.md <ide> [image-drf-docs]: ../img/drfdocs.png <ide> [image-django-rest-swagger]: ../img/django-rest-swagger.png
1
Mixed
Ruby
reset cache_versions on relation
a237867e8fada034d977b4b7e04e012470c14a5b
<ide><path>activerecord/CHANGELOG.md <add>* Resolve issue where a relation cache_version could be left stale. <add> <add> Previously, when `reset` was called on a relation object it did not reset the cache_versions <add> ivar. This led to a confusing situation where despite having the correct data the relation <add> still reported a stale cache_version. <add> <add> Usage: <add> <add> ```ruby <add> developers = Developer.all <add> developers.cache_version <add> <add> Developer.update_all(updated_at: Time.now.utc + 1.second) <add> <add> developers.cache_version # Stale cache_version <add> developers.reset <add> developers.cache_version # Returns the current correct cache_version <add> ``` <add> <add> Fixes #45341. <add> <add> *Austen Madden* <add> <ide> * Add support for exclusion constraints (PostgreSQL-only). <ide> <ide> ```ruby <ide><path>activerecord/lib/active_record/relation.rb <ide> def reset <ide> @to_sql = @arel = @loaded = @should_eager_load = nil <ide> @offsets = @take = nil <ide> @cache_keys = nil <add> @cache_versions = nil <ide> @records = nil <ide> self <ide> end <ide><path>activerecord/test/cases/collection_cache_key_test.rb <ide> class CollectionCacheKeyTest < ActiveRecord::TestCase <ide> end <ide> end <ide> <add> test "reset will reset cache_version" do <add> with_collection_cache_versioning do <add> developers = Developer.all <add> <add> assert_equal Developer.all.cache_version, developers.cache_version <add> <add> Developer.update_all(updated_at: Time.now.utc + 1.second) <add> developers.reset <add> <add> assert_equal Developer.all.cache_version, developers.cache_version <add> end <add> end <add> <ide> test "cache_key_with_version contains key and version regardless of collection_cache_versioning setting" do <ide> key_with_version_1 = Developer.all.cache_key_with_version <ide> assert_match(/\Adevelopers\/query-(\h+)-(\d+)-(\d+)\z/, key_with_version_1)
3
Javascript
Javascript
enable coverage logging from the worker
ef5a02c16485707acdfd38f612c16513beeb4a6a
<ide><path>src/environment/__tests__/ReactWebWorker-test.js <ide> describe('ReactWebWorker', function() { <ide> var data = JSON.parse(e.data); <ide> if (data.type == 'error') { <ide> error = data.message + "\n" + data.stack; <add> } else if (data.type == 'log') { <add> console.log(data.message); <ide> } else { <ide> expect(data.type).toBe('done'); <ide> done = true; <ide> describe('ReactWebWorker', function() { <ide> }); <ide> runs(function() { <ide> if (error) { <del> console.log(error); <add> console.error(error); <ide> throw new Error(error); <ide> } <ide> }); <ide><path>src/test/worker.js <ide> /* jshint worker: true */ <ide> "use strict"; <ide> <add>if (typeof console == 'undefined') { <add> this.console = { <add> error: function(e){ <add> postMessage(JSON.stringify({ <add> type: 'error', <add> message: e.message, <add> stack: e.stack <add> })); <add> }, <add> log: function(message){ <add> postMessage(JSON.stringify({ <add> type: 'log', <add> message: message <add> })); <add> } <add> } <add>} <add> <add>console.log('worker BEGIN'); <add> <ide> // The UMD wrapper tries to store on `global` if `window` isn't available <ide> var global = {}; <ide> importScripts("phantomjs-shims.js"); <ide> <ide> try { <ide> importScripts("../../build/react.js"); <ide> } catch (e) { <del> postMessage(JSON.stringify({ <del> type: 'error', <del> message: e.message, <del> stack: e.stack <del> })); <add> console.error(e); <ide> } <ide> <ide> postMessage(JSON.stringify({ <ide> type: 'done' <ide> })); <add> <add>console.log('worker END');
2
Text
Text
add changelog entry for
58a6a246cc8e78e15d083df041aea54d61a6b62a
<ide><path>activesupport/CHANGELOG.md <ide> ## Rails 5.0.0.beta1 (December 18, 2015) ## <ide> <add>* Add petabyte and exabyte numberic conversion. <add> <add> *Akshay Vishnoi* <add> <ide> * Add thread_m/cattr_accessor/reader/writer suite of methods for declaring class and module variables that live per-thread. <ide> This makes it easy to declare per-thread globals that are encapsulated. Note: This is a sharp edge. A wild proliferation <ide> of globals is A Bad Thing. But like other sharp tools, when it's right, it's right.
1
PHP
PHP
remove reference from the signature
6b8a79be6d74aba787d279beaa77a8400c26d69f
<ide><path>lib/Cake/Model/Datasource/DboSource.php <ide> public function prepareFields(Model $Model, $queryData) { <ide> /** <ide> * Builds an SQL statement. <ide> * <add> * This is merely a convenient wrapper to DboSource::buildStatement(). <add> * <ide> * @param Model $Model <ide> * @param array $queryData <ide> * @return string String containing an SQL statement. <add> * @see DboSource::buildStatement() <ide> */ <del> public function buildAssociationQuery(Model $Model, &$queryData) { <add> public function buildAssociationQuery(Model $Model, $queryData) { <ide> $queryData = $this->_scrubQueryData($queryData); <ide> <ide> return $this->buildStatement(
1
Javascript
Javascript
adopt standard parallels per usgs
ef084aaf615608441f136a270dafaa2f9b570f5a
<ide><path>d3.js <del>d3 = {version: "0.8.0"}; // semver <add>d3 = {version: "0.8.1"}; // semver <ide> if (!Date.now) Date.now = function() { <ide> return +new Date(); <ide> }; <ide> d3.geo.albers = function() { <ide> return reload(); <ide> }; <ide> <del>// A composite projection for the United States, 960x500. <add>// A composite projection for the United States, 960x500. The set of standard <add>// parallels for each region comes from USGS, which is published here: <add>// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers <ide> // TODO allow the composite projection to be rescaled? <ide> d3.geo.albersUsa = function() { <ide> var lower48 = d3.geo.albers(); <ide> d3.geo.albersUsa = function() { <ide> <ide> var hawaii = d3.geo.albers() <ide> .origin([-160, 20]) <del> .parallels([10, 30]) <add> .parallels([8, 18]) <ide> .translate([290, 450]); <ide> <ide> var puertoRico = d3.geo.albers() <ide> .origin([-60, 10]) <del> .parallels([0, 20]) <add> .parallels([8, 18]) <ide> .scale([1500]) <ide> .translate([1060, 680]); <ide> <ide><path>d3.min.js <del>(function(){var p=null;d3={version:"0.8.0"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function d(){}d.prototype=a;return new d};function z(a){return Array.prototype.slice.call(a)}function C(a,d){d=z(arguments);d[0]=this;a.apply(this,d);return this}d3.range=function(a,d,f){if(arguments.length==1){d=a;a=0}if(f==p)f=1;if((d-a)/f==Infinity)throw Error("infinite range");var g=[],b=-1,c;if(f<0)for(;(c=a+f*++b)>d;)g.push(c);else for(;(c=a+f*++b)<d;)g.push(c);return g}; <add>(function(){var p=null;d3={version:"0.8.1"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function d(){}d.prototype=a;return new d};function z(a){return Array.prototype.slice.call(a)}function C(a,d){d=z(arguments);d[0]=this;a.apply(this,d);return this}d3.range=function(a,d,f){if(arguments.length==1){d=a;a=0}if(f==p)f=1;if((d-a)/f==Infinity)throw Error("infinite range");var g=[],b=-1,c;if(f<0)for(;(c=a+f*++b)>d;)g.push(c);else for(;(c=a+f*++b)<d;)g.push(c);return g}; <ide> d3.json=function(a,d){var f=new XMLHttpRequest;f.overrideMimeType("application/json");f.open("GET",a,true);f.onreadystatechange=function(){if(f.readyState==4)d(f.status<300&&f.responseText?JSON.parse(f.responseText):p)};f.send(p)}; <ide> d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var d=a.indexOf(":");return d<0?a:{space:d3.ns.prefix[a.substring(0,d)],local:a.substring(d+1)}}};d3.dispatch=function(){for(var a={},d,f=0,g=arguments.length;f<g;f++){d=arguments[f];a[d]=E(d)}return a}; <ide> function E(){var a={},d=[];a.add=function(f){for(var g=0;g<d.length;g++)if(d[g].e==f)return a;d.push({e:f,on:true});return a};a.remove=function(f){for(var g=0;g<d.length;g++){var b=d[g];if(b.e==f){b.on=false;d=d.slice(0,g).concat(d.slice(g+1));break}}return a};a.dispatch=function(){for(var f=d,g=0,b=f.length;g<b;g++){var c=f[g];c.on&&c.e.apply(this,arguments)}};return a} <ide> d3.svg.line=function(){function a(g){return g.y}function d(g){return g.x}functio <ide> d3.svg.area=function(){function a(b){return b.y1}function d(b){return b.x}function f(b){var c=[],i=0,h=b[0];for(c.push("M",d.call(this,h,i),","+g+"V",a.call(this,h,i));h=b[++i];)c.push("L",d.call(this,h,i),",",a.call(this,h,i));c.push("V"+g+"Z");return c.join("")}var g=0;f.x=function(b){d=b;return f};f.y0=function(b){g=b;return f};f.y1=function(b){a=b;return f};return f};d3.geo={}; <ide> d3.geo.albers=function(){function a(l){var k=h*(Z*l[0]-i);l=Math.sqrt(e-2*h*Math.sin(Z*l[1]))/h;return[b*l*Math.sin(k)+c[0],b*(l*Math.cos(k)-j)+c[1]]}function d(){var l=Z*g[0],k=Z*g[1],m=Z*f[1],o=Math.sin(l);l=Math.cos(l);i=Z*f[0];h=0.5*(o+Math.sin(k));e=l*l+2*h*o;j=Math.sqrt(e-2*h*Math.sin(m))/h;return a}var f=[-98,38],g=[29.5,45.5],b=1E3,c=[480,250],i,h,e,j;a.origin=function(l){if(!arguments.length)return f;f=[+l[0],+l[1]];return d()};a.parallels=function(l){if(!arguments.length)return g;g=[+l[0], <ide> +l[1]];return d()};a.scale=function(l){if(!arguments.length)return b;b=+l;return a};a.translate=function(l){if(!arguments.length)return c;c=[+l[0],+l[1]];return a};return d()}; <del>d3.geo.albersUsa=function(){var a=d3.geo.albers(),d=d3.geo.albers().origin([-160,60]).parallels([55,65]).scale([600]).translate([80,420]),f=d3.geo.albers().origin([-160,20]).parallels([10,30]).translate([290,450]),g=d3.geo.albers().origin([-60,10]).parallels([0,20]).scale([1500]).translate([1060,680]);return function(b){var c=b[0],i=b[1];return(i<25?c<-100?f:g:i>50?d:a)(b)}};var Z=Math.PI/180; <add>d3.geo.albersUsa=function(){var a=d3.geo.albers(),d=d3.geo.albers().origin([-160,60]).parallels([55,65]).scale([600]).translate([80,420]),f=d3.geo.albers().origin([-160,20]).parallels([8,18]).translate([290,450]),g=d3.geo.albers().origin([-60,10]).parallels([8,18]).scale([1500]).translate([1060,680]);return function(b){var c=b[0],i=b[1];return(i<25?c<-100?f:g:i>50?d:a)(b)}};var Z=Math.PI/180; <ide> d3.geo.path=function(){function a(e){if(typeof g=="function")b=$(g.apply(this,arguments));return f(i,e)}function d(e){return c(e).join(",")}function f(e,j){return j&&j.type in e?e[j.type](j):""}var g=4.5,b=$(g),c=d3.geo.albersUsa(),i={FeatureCollection:function(e){var j=[];e=e.features;for(var l=-1,k=e.length;++l<k;)j.push(f(i,e[l]));return j.join("")},Feature:function(e){return f(h,e.geometry)}},h={Point:function(e){return"M"+d(e.coordinates)+b},MultiPoint:function(e){var j=[];e=e.coordinates;for(var l= <ide> -1,k=e.length;++l<k;)j.push("M",d(e[l]),b);return j.join("")},LineString:function(e){var j=["M"];e=e.coordinates;for(var l=-1,k=e.length;++l<k;)j.push(d(e[l]),"L");j.pop();return j.join("")},MultiLineString:function(e){var j=[];e=e.coordinates;for(var l=-1,k=e.length,m,o,q;++l<k;){m=e[l];o=-1;q=m.length;for(j.push("M");++o<q;)j.push(d(m[o]),"L");j.pop()}return j.join("")},Polygon:function(e){var j=[];e=e.coordinates;for(var l=-1,k=e.length,m,o,q;++l<k;){m=e[l];o=-1;q=m.length;for(j.push("M");++o< <ide> q;)j.push(d(m[o]),"L");j[j.length-1]="Z"}return j.join("")},MultiPolygon:function(e){var j=[];e=e.coordinates;for(var l=-1,k=e.length,m,o,q,t,n,r;++l<k;){m=e[l];o=-1;for(q=m.length;++o<q;){t=m[o];n=-1;r=t.length-1;for(j.push("M");++n<r;)j.push(d(t[n]),"L");j[j.length-1]="Z"}}return j.join("")},GeometryCollection:function(e){var j=[];e=e.geometries;for(var l=-1,k=e.length;++l<k;)j.push(f(h,e[l]));return j.join("")}};a.projection=function(e){c=e;return a};a.pointRadius=function(e){if(typeof e=="function")g= <ide><path>src/core/core.js <del>d3 = {version: "0.8.0"}; // semver <add>d3 = {version: "0.8.1"}; // semver <ide><path>src/geo/albers.js <ide> d3.geo.albers = function() { <ide> return reload(); <ide> }; <ide> <del>// A composite projection for the United States, 960x500. <add>// A composite projection for the United States, 960x500. The set of standard <add>// parallels for each region comes from USGS, which is published here: <add>// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers <ide> // TODO allow the composite projection to be rescaled? <ide> d3.geo.albersUsa = function() { <ide> var lower48 = d3.geo.albers(); <ide> d3.geo.albersUsa = function() { <ide> <ide> var hawaii = d3.geo.albers() <ide> .origin([-160, 20]) <del> .parallels([10, 30]) <add> .parallels([8, 18]) <ide> .translate([290, 450]); <ide> <ide> var puertoRico = d3.geo.albers() <ide> .origin([-60, 10]) <del> .parallels([0, 20]) <add> .parallels([8, 18]) <ide> .scale([1500]) <ide> .translate([1060, 680]); <ide>
4
Javascript
Javascript
use fewer global variables in hooks
f523b2e0d369e3f42938b56784f9ce1990838753
<ide><path>packages/react-reconciler/src/ReactFiberHooks.js <ide> import type { <ide> ReactContext, <ide> ReactEventResponderListener, <ide> } from 'shared/ReactTypes'; <del>import type {SideEffectTag} from 'shared/ReactSideEffectTags'; <ide> import type {Fiber} from './ReactFiber'; <ide> import type {ExpirationTime} from './ReactFiberExpirationTime'; <ide> import type {HookEffectTag} from './ReactHookEffectTags'; <ide> type Dispatch<A> = A => void; <ide> let renderExpirationTime: ExpirationTime = NoWork; <ide> // The work-in-progress fiber. I've named it differently to distinguish it from <ide> // the work-in-progress hook. <del>let currentlyRenderingFiber: Fiber | null = null; <add>let currentlyRenderingFiber: Fiber = (null: any); <ide> <ide> // Hooks are stored as a linked list on the fiber's memoizedState field. The <ide> // current hook list is the list that belongs to the current fiber. The <ide> // work-in-progress hook list is a new list that will be added to the <ide> // work-in-progress fiber. <ide> let currentHook: Hook | null = null; <del>let nextCurrentHook: Hook | null = null; <del>let firstWorkInProgressHook: Hook | null = null; <ide> let workInProgressHook: Hook | null = null; <del>let nextWorkInProgressHook: Hook | null = null; <del> <del>let remainingExpirationTime: ExpirationTime = NoWork; <del>let componentUpdateQueue: FunctionComponentUpdateQueue | null = null; <del>let sideEffectTag: SideEffectTag = 0; <ide> <ide> // Updates scheduled during render will trigger an immediate re-render at the <ide> // end of the current pass. We can't store these updates on the normal queue, <ide> let renderPhaseUpdates: Map< <ide> UpdateQueue<any, any>, <ide> Update<any, any>, <ide> > | null = null; <del>// Counter to prevent infinite loops. <del>let numberOfReRenders: number = 0; <add> <ide> const RE_RENDER_LIMIT = 25; <ide> <ide> // In DEV, this is the name of the currently executing primitive hook <ide> function checkDepsAreArrayDev(deps: mixed) { <ide> <ide> function warnOnHookMismatchInDev(currentHookName: HookType) { <ide> if (__DEV__) { <del> const componentName = getComponentName( <del> ((currentlyRenderingFiber: any): Fiber).type, <del> ); <add> const componentName = getComponentName(currentlyRenderingFiber.type); <ide> if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { <ide> didWarnAboutMismatchedHooksForComponent.add(componentName); <ide> <ide> export function renderWithHooks( <ide> ): any { <ide> renderExpirationTime = nextRenderExpirationTime; <ide> currentlyRenderingFiber = workInProgress; <del> nextCurrentHook = current !== null ? current.memoizedState : null; <ide> <ide> if (__DEV__) { <ide> hookTypesDev = <ide> export function renderWithHooks( <ide> current !== null && current.type !== workInProgress.type; <ide> } <ide> <add> workInProgress.memoizedState = null; <add> workInProgress.updateQueue = null; <add> workInProgress.expirationTime = NoWork; <add> <ide> // The following should have already been reset <ide> // currentHook = null; <ide> // workInProgressHook = null; <ide> <del> // remainingExpirationTime = NoWork; <del> // componentUpdateQueue = null; <del> <ide> // didScheduleRenderPhaseUpdate = false; <ide> // renderPhaseUpdates = null; <del> // numberOfReRenders = 0; <del> // sideEffectTag = 0; <ide> <ide> // TODO Warn if no hooks are used at all during mount, then some are used during update. <del> // Currently we will identify the update render as a mount because nextCurrentHook === null. <add> // Currently we will identify the update render as a mount because memoizedState === null. <ide> // This is tricky because it's valid for certain types of components (e.g. React.lazy) <ide> <del> // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used. <add> // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. <ide> // Non-stateful hooks (e.g. context) don't get added to memoizedState, <del> // so nextCurrentHook would be null during updates and mounts. <add> // so memoizedState would be null during updates and mounts. <ide> if (__DEV__) { <del> if (nextCurrentHook !== null) { <add> if (current !== null && current.memoizedState !== null) { <ide> ReactCurrentDispatcher.current = HooksDispatcherOnUpdateInDEV; <ide> } else if (hookTypesDev !== null) { <ide> // This dispatcher handles an edge case where a component is updating, <ide> export function renderWithHooks( <ide> } <ide> } else { <ide> ReactCurrentDispatcher.current = <del> nextCurrentHook === null <add> current === null || current.memoizedState === null <ide> ? HooksDispatcherOnMount <ide> : HooksDispatcherOnUpdate; <ide> } <ide> <ide> let children = Component(props, refOrContext); <ide> <ide> if (didScheduleRenderPhaseUpdate) { <add> // Counter to prevent infinite loops. <add> let numberOfReRenders: number = 0; <ide> do { <ide> didScheduleRenderPhaseUpdate = false; <add> <add> invariant( <add> numberOfReRenders < RE_RENDER_LIMIT, <add> 'Too many re-renders. React limits the number of renders to prevent ' + <add> 'an infinite loop.', <add> ); <add> <ide> numberOfReRenders += 1; <ide> if (__DEV__) { <ide> // Even when hot reloading, allow dependencies to stabilize <ide> export function renderWithHooks( <ide> } <ide> <ide> // Start over from the beginning of the list <del> nextCurrentHook = current !== null ? current.memoizedState : null; <del> nextWorkInProgressHook = firstWorkInProgressHook; <del> <ide> currentHook = null; <ide> workInProgressHook = null; <del> componentUpdateQueue = null; <add> <add> workInProgress.updateQueue = null; <ide> <ide> if (__DEV__) { <ide> // Also validate hook order for cascading updates. <ide> export function renderWithHooks( <ide> } while (didScheduleRenderPhaseUpdate); <ide> <ide> renderPhaseUpdates = null; <del> numberOfReRenders = 0; <ide> } <ide> <ide> // We can assume the previous dispatcher is always this one, since we set it <ide> // at the beginning of the render phase and there's no re-entrancy. <ide> ReactCurrentDispatcher.current = ContextOnlyDispatcher; <ide> <del> const renderedWork: Fiber = (currentlyRenderingFiber: any); <del> <del> renderedWork.memoizedState = firstWorkInProgressHook; <del> renderedWork.expirationTime = remainingExpirationTime; <del> renderedWork.updateQueue = (componentUpdateQueue: any); <del> renderedWork.effectTag |= sideEffectTag; <del> <ide> if (__DEV__) { <del> renderedWork._debugHookTypes = hookTypesDev; <add> workInProgress._debugHookTypes = hookTypesDev; <ide> } <ide> <ide> // This check uses currentHook so that it works the same in DEV and prod bundles. <ide> export function renderWithHooks( <ide> currentHook !== null && currentHook.next !== null; <ide> <ide> renderExpirationTime = NoWork; <del> currentlyRenderingFiber = null; <add> currentlyRenderingFiber = (null: any); <ide> <ide> currentHook = null; <del> nextCurrentHook = null; <del> firstWorkInProgressHook = null; <ide> workInProgressHook = null; <del> nextWorkInProgressHook = null; <ide> <ide> if (__DEV__) { <ide> currentHookNameInDev = null; <ide> hookTypesDev = null; <ide> hookTypesUpdateIndexDev = -1; <ide> } <ide> <del> remainingExpirationTime = NoWork; <del> componentUpdateQueue = null; <del> sideEffectTag = 0; <del> <ide> // These were reset above <ide> // didScheduleRenderPhaseUpdate = false; <ide> // renderPhaseUpdates = null; <del> // numberOfReRenders = 0; <ide> <ide> invariant( <ide> !didRenderTooFewHooks, <ide> export function resetHooks(): void { <ide> // component is a module-style component. <ide> <ide> renderExpirationTime = NoWork; <del> currentlyRenderingFiber = null; <add> currentlyRenderingFiber = (null: any); <ide> <ide> currentHook = null; <del> nextCurrentHook = null; <del> firstWorkInProgressHook = null; <ide> workInProgressHook = null; <del> nextWorkInProgressHook = null; <ide> <ide> if (__DEV__) { <ide> hookTypesDev = null; <ide> export function resetHooks(): void { <ide> currentHookNameInDev = null; <ide> } <ide> <del> remainingExpirationTime = NoWork; <del> componentUpdateQueue = null; <del> sideEffectTag = 0; <del> <ide> didScheduleRenderPhaseUpdate = false; <ide> renderPhaseUpdates = null; <del> numberOfReRenders = 0; <ide> } <ide> <ide> function mountWorkInProgressHook(): Hook { <ide> function mountWorkInProgressHook(): Hook { <ide> <ide> if (workInProgressHook === null) { <ide> // This is the first hook in the list <del> firstWorkInProgressHook = workInProgressHook = hook; <add> currentlyRenderingFiber.memoizedState = workInProgressHook = hook; <ide> } else { <ide> // Append to the end of the list <ide> workInProgressHook = workInProgressHook.next = hook; <ide> function updateWorkInProgressHook(): Hook { <ide> // clone, or a work-in-progress hook from a previous render pass that we can <ide> // use as a base. When we reach the end of the base list, we must switch to <ide> // the dispatcher used for mounts. <add> let nextCurrentHook: null | Hook; <add> if (currentHook === null) { <add> let current = currentlyRenderingFiber.alternate; <add> if (current !== null) { <add> nextCurrentHook = current.memoizedState; <add> } else { <add> nextCurrentHook = null; <add> } <add> } else { <add> nextCurrentHook = currentHook.next; <add> } <add> <add> let nextWorkInProgressHook: null | Hook; <add> if (workInProgressHook === null) { <add> nextWorkInProgressHook = currentlyRenderingFiber.memoizedState; <add> } else { <add> nextWorkInProgressHook = workInProgressHook.next; <add> } <add> <ide> if (nextWorkInProgressHook !== null) { <ide> // There's already a work-in-progress. Reuse it. <ide> workInProgressHook = nextWorkInProgressHook; <ide> nextWorkInProgressHook = workInProgressHook.next; <ide> <ide> currentHook = nextCurrentHook; <del> nextCurrentHook = currentHook !== null ? currentHook.next : null; <ide> } else { <ide> // Clone from the current hook. <add> <ide> invariant( <ide> nextCurrentHook !== null, <ide> 'Rendered more hooks than during the previous render.', <ide> function updateWorkInProgressHook(): Hook { <ide> <ide> if (workInProgressHook === null) { <ide> // This is the first hook in the list. <del> workInProgressHook = firstWorkInProgressHook = newHook; <add> currentlyRenderingFiber.memoizedState = workInProgressHook = newHook; <ide> } else { <ide> // Append to the end of the list. <ide> workInProgressHook = workInProgressHook.next = newHook; <ide> } <del> nextCurrentHook = currentHook.next; <ide> } <ide> return workInProgressHook; <ide> } <ide> function mountReducer<S, I, A>( <ide> }); <ide> const dispatch: Dispatch<A> = (queue.dispatch = (dispatchAction.bind( <ide> null, <del> // Flow doesn't know this is non-null, but we do. <del> ((currentlyRenderingFiber: any): Fiber), <add> currentlyRenderingFiber, <ide> queue, <ide> ): any)); <ide> return [hook.memoizedState, dispatch]; <ide> function updateReducer<S, I, A>( <ide> <ide> queue.lastRenderedReducer = reducer; <ide> <del> if (numberOfReRenders > 0) { <add> if (renderPhaseUpdates !== null) { <ide> // This is a re-render. Apply the new render phase updates to the previous <ide> // work-in-progress hook. <ide> const dispatch: Dispatch<A> = (queue.dispatch: any); <del> if (renderPhaseUpdates !== null) { <del> // Render phase updates are stored in a map of queue -> linked list <del> const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); <del> if (firstRenderPhaseUpdate !== undefined) { <del> renderPhaseUpdates.delete(queue); <del> let newState = hook.memoizedState; <del> let update = firstRenderPhaseUpdate; <del> do { <del> // Process this render phase update. We don't have to check the <del> // priority because it will always be the same as the current <del> // render's. <del> const action = update.action; <del> newState = reducer(newState, action); <del> update = update.next; <del> } while (update !== null); <del> <del> // Mark that the fiber performed work, but only if the new state is <del> // different from the current state. <del> if (!is(newState, hook.memoizedState)) { <del> markWorkInProgressReceivedUpdate(); <del> } <add> // Render phase updates are stored in a map of queue -> linked list <add> const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); <add> if (firstRenderPhaseUpdate !== undefined) { <add> renderPhaseUpdates.delete(queue); <add> let newState = hook.memoizedState; <add> let update = firstRenderPhaseUpdate; <add> do { <add> // Process this render phase update. We don't have to check the <add> // priority because it will always be the same as the current <add> // render's. <add> const action = update.action; <add> newState = reducer(newState, action); <add> update = update.next; <add> } while (update !== null); <add> <add> // Mark that the fiber performed work, but only if the new state is <add> // different from the current state. <add> if (!is(newState, hook.memoizedState)) { <add> markWorkInProgressReceivedUpdate(); <add> } <ide> <del> hook.memoizedState = newState; <del> // Don't persist the state accumulated from the render phase updates to <del> // the base state unless the queue is empty. <del> // TODO: Not sure if this is the desired semantics, but it's what we <del> // do for gDSFP. I can't remember why. <del> if (hook.baseUpdate === queue.last) { <del> hook.baseState = newState; <del> } <add> hook.memoizedState = newState; <add> // Don't persist the state accumulated from the render phase updates to <add> // the base state unless the queue is empty. <add> // TODO: Not sure if this is the desired semantics, but it's what we <add> // do for gDSFP. I can't remember why. <add> if (hook.baseUpdate === queue.last) { <add> hook.baseState = newState; <add> } <ide> <del> queue.lastRenderedState = newState; <add> queue.lastRenderedState = newState; <ide> <del> return [newState, dispatch]; <del> } <add> return [newState, dispatch]; <ide> } <ide> return [hook.memoizedState, dispatch]; <ide> } <ide> function updateReducer<S, I, A>( <ide> newBaseState = newState; <ide> } <ide> // Update the remaining priority in the queue. <del> if (updateExpirationTime > remainingExpirationTime) { <del> remainingExpirationTime = updateExpirationTime; <del> markUnprocessedUpdateTime(remainingExpirationTime); <add> if (updateExpirationTime > currentlyRenderingFiber.expirationTime) { <add> currentlyRenderingFiber.expirationTime = updateExpirationTime; <add> markUnprocessedUpdateTime(updateExpirationTime); <ide> } <ide> } else { <ide> // This update does have sufficient priority. <ide> function mountState<S>( <ide> BasicStateAction<S>, <ide> > = (queue.dispatch = (dispatchAction.bind( <ide> null, <del> // Flow doesn't know this is non-null, but we do. <del> ((currentlyRenderingFiber: any): Fiber), <add> currentlyRenderingFiber, <ide> queue, <ide> ): any)); <ide> return [hook.memoizedState, dispatch]; <ide> function pushEffect(tag, create, destroy, deps) { <ide> // Circular <ide> next: (null: any), <ide> }; <add> let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any); <ide> if (componentUpdateQueue === null) { <ide> componentUpdateQueue = createFunctionComponentUpdateQueue(); <add> currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any); <ide> componentUpdateQueue.lastEffect = effect.next = effect; <ide> } else { <ide> const lastEffect = componentUpdateQueue.lastEffect; <ide> function updateRef<T>(initialValue: T): {current: T} { <ide> function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps): void { <ide> const hook = mountWorkInProgressHook(); <ide> const nextDeps = deps === undefined ? null : deps; <del> sideEffectTag |= fiberEffectTag; <add> currentlyRenderingFiber.effectTag |= fiberEffectTag; <ide> hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps); <ide> } <ide> <ide> function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps): void { <ide> } <ide> } <ide> <del> sideEffectTag |= fiberEffectTag; <add> currentlyRenderingFiber.effectTag |= fiberEffectTag; <add> <ide> hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps); <ide> } <ide> <ide> function mountEffect( <ide> if (__DEV__) { <ide> // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests <ide> if ('undefined' !== typeof jest) { <del> warnIfNotCurrentlyActingEffectsInDEV( <del> ((currentlyRenderingFiber: any): Fiber), <del> ); <add> warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber); <ide> } <ide> } <ide> return mountEffectImpl( <ide> function updateEffect( <ide> if (__DEV__) { <ide> // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests <ide> if ('undefined' !== typeof jest) { <del> warnIfNotCurrentlyActingEffectsInDEV( <del> ((currentlyRenderingFiber: any): Fiber), <del> ); <add> warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber); <ide> } <ide> } <ide> return updateEffectImpl( <ide> function dispatchAction<S, A>( <ide> queue: UpdateQueue<S, A>, <ide> action: A, <ide> ) { <del> invariant( <del> numberOfReRenders < RE_RENDER_LIMIT, <del> 'Too many re-renders. React limits the number of renders to prevent ' + <del> 'an infinite loop.', <del> ); <del> <ide> if (__DEV__) { <ide> warning( <ide> typeof arguments[3] !== 'function', <ide><path>packages/react-reconciler/src/ReactFiberThrow.js <ide> function throwException( <ide> // This is a thenable. <ide> const thenable: Thenable = (value: any); <ide> <add> if ((sourceFiber.mode & BlockingMode) === NoMode) { <add> // Reset the memoizedState to what it was before we attempted <add> // to render it. <add> let currentSource = sourceFiber.alternate; <add> if (currentSource) { <add> sourceFiber.memoizedState = currentSource.memoizedState; <add> sourceFiber.expirationTime = currentSource.expirationTime; <add> } else { <add> sourceFiber.memoizedState = null; <add> } <add> } <add> <ide> checkForWrongSuspensePriorityInDEV(sourceFiber); <ide> <ide> let hasInvisibleParentBoundary = hasSuspenseContext( <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.internal.js <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> ); <ide> }); <ide> <add> it('does not call lifecycles of a suspended component (hooks)', async () => { <add> function TextWithLifecycle(props) { <add> React.useLayoutEffect( <add> () => { <add> Scheduler.unstable_yieldValue(`Layout Effect [${props.text}]`); <add> return () => { <add> Scheduler.unstable_yieldValue( <add> `Destroy Layout Effect [${props.text}]`, <add> ); <add> }; <add> }, <add> [props.text], <add> ); <add> React.useEffect( <add> () => { <add> Scheduler.unstable_yieldValue(`Effect [${props.text}]`); <add> return () => { <add> Scheduler.unstable_yieldValue(`Destroy Effect [${props.text}]`); <add> }; <add> }, <add> [props.text], <add> ); <add> return <Text {...props} />; <add> } <add> <add> function AsyncTextWithLifecycle(props) { <add> React.useLayoutEffect( <add> () => { <add> Scheduler.unstable_yieldValue(`Layout Effect [${props.text}]`); <add> return () => { <add> Scheduler.unstable_yieldValue( <add> `Destroy Layout Effect [${props.text}]`, <add> ); <add> }; <add> }, <add> [props.text], <add> ); <add> React.useEffect( <add> () => { <add> Scheduler.unstable_yieldValue(`Effect [${props.text}]`); <add> return () => { <add> Scheduler.unstable_yieldValue(`Destroy Effect [${props.text}]`); <add> }; <add> }, <add> [props.text], <add> ); <add> const text = props.text; <add> const ms = props.ms; <add> try { <add> TextResource.read([text, ms]); <add> Scheduler.unstable_yieldValue(text); <add> return <span prop={text} />; <add> } catch (promise) { <add> if (typeof promise.then === 'function') { <add> Scheduler.unstable_yieldValue(`Suspend! [${text}]`); <add> } else { <add> Scheduler.unstable_yieldValue(`Error! [${text}]`); <add> } <add> throw promise; <add> } <add> } <add> <add> function App({text}) { <add> return ( <add> <Suspense fallback={<TextWithLifecycle text="Loading..." />}> <add> <TextWithLifecycle text="A" /> <add> <AsyncTextWithLifecycle ms={100} text={text} /> <add> <TextWithLifecycle text="C" /> <add> </Suspense> <add> ); <add> } <add> <add> ReactNoop.renderLegacySyncRoot(<App text="B" />, () => <add> Scheduler.unstable_yieldValue('Commit root'), <add> ); <add> expect(Scheduler).toHaveYielded([ <add> 'A', <add> 'Suspend! [B]', <add> 'C', <add> 'Loading...', <add> <add> 'Layout Effect [A]', <add> // B's effect should not fire because it suspended <add> // 'Layout Effect [B]', <add> 'Layout Effect [C]', <add> 'Layout Effect [Loading...]', <add> 'Commit root', <add> ]); <add> <add> // Flush passive effects. <add> expect(Scheduler).toFlushAndYield([ <add> 'Effect [A]', <add> // B's effect should not fire because it suspended <add> // 'Effect [B]', <add> 'Effect [C]', <add> 'Effect [Loading...]', <add> ]); <add> <add> expect(ReactNoop).toMatchRenderedOutput( <add> <> <add> <span hidden={true} prop="A" /> <add> <span hidden={true} prop="C" /> <add> <span prop="Loading..." /> <add> </>, <add> ); <add> <add> Scheduler.unstable_advanceTime(500); <add> await advanceTimers(500); <add> <add> expect(Scheduler).toHaveYielded(['Promise resolved [B]']); <add> <add> expect(Scheduler).toFlushAndYield([ <add> 'B', <add> 'Destroy Layout Effect [Loading...]', <add> 'Destroy Effect [Loading...]', <add> 'Layout Effect [B]', <add> 'Effect [B]', <add> ]); <add> <add> // Update <add> ReactNoop.renderLegacySyncRoot(<App text="B2" />, () => <add> Scheduler.unstable_yieldValue('Commit root'), <add> ); <add> <add> expect(Scheduler).toHaveYielded([ <add> 'A', <add> 'Suspend! [B2]', <add> 'C', <add> 'Loading...', <add> <add> // B2's effect should not fire because it suspended <add> // 'Layout Effect [B2]', <add> 'Layout Effect [Loading...]', <add> 'Commit root', <add> ]); <add> <add> // Flush passive effects. <add> expect(Scheduler).toFlushAndYield([ <add> // B2's effect should not fire because it suspended <add> // 'Effect [B2]', <add> 'Effect [Loading...]', <add> ]); <add> <add> Scheduler.unstable_advanceTime(500); <add> await advanceTimers(500); <add> <add> expect(Scheduler).toHaveYielded(['Promise resolved [B2]']); <add> <add> expect(Scheduler).toFlushAndYield([ <add> 'B2', <add> 'Destroy Layout Effect [Loading...]', <add> 'Destroy Effect [Loading...]', <add> 'Destroy Layout Effect [B]', <add> 'Layout Effect [B2]', <add> 'Destroy Effect [B]', <add> 'Effect [B2]', <add> ]); <add> }); <add> <ide> it('suspends for longer if something took a long (CPU bound) time to render', async () => { <ide> function Foo({renderContent}) { <ide> Scheduler.unstable_yieldValue('Foo');
3
Javascript
Javascript
convert _app.js to functional components
ea0d916b50fdf7faa0534446a4bf672bedb0e344
<ide><path>examples/with-app-layout/pages/_app.js <ide> import React from 'react' <del>import App from 'next/app' <ide> <del>class Layout extends React.Component { <del> render() { <del> const { children } = this.props <del> return <div className="layout">{children}</div> <del> } <del>} <add>const Layout = ({ children }) => <div className="layout">{children}</div> <ide> <del>export default class MyApp extends App { <del> render() { <del> const { Component, pageProps } = this.props <del> return ( <del> <Layout> <del> <Component {...pageProps} /> <del> </Layout> <del> ) <del> } <del>} <add>export default ({ Component, pageProps }) => ( <add> <Layout> <add> <Component {...pageProps} /> <add> </Layout> <add>)
1
Javascript
Javascript
remove redundant boolean check of request variable
2471713608f618b467fd11af0a6dc4bec22a3b4d
<ide><path>lib/DelegatedModuleFactoryPlugin.js <ide> class DelegatedModuleFactoryPlugin { <ide> module => { <ide> const request = module.libIdent(this.options); <ide> if (request) { <del> if (request && request in this.options.content) { <add> if (request in this.options.content) { <ide> const resolved = this.options.content[request]; <ide> return new DelegatedModule( <ide> this.options.source,
1
Javascript
Javascript
increase coverage of internal/stream/end-of-stream
7d2494d867f38d5d56f955cb7126e49f3348b96c
<ide><path>test/parallel/test-stream-finished.js <ide> const { promisify } = require('util'); <ide> rs.push(null); <ide> rs.resume(); <ide> } <add> <add>// Test that calling returned function removes listeners <add>{ <add> const ws = new Writable({ <add> write(data, env, cb) { <add> cb(); <add> } <add> }); <add> const removeListener = finished(ws, common.mustNotCall()); <add> removeListener(); <add> ws.end(); <add>} <add> <add>{ <add> const rs = new Readable(); <add> const removeListeners = finished(rs, common.mustNotCall()); <add> removeListeners(); <add> <add> rs.emit('close'); <add> rs.push(null); <add> rs.resume(); <add>}
1
Javascript
Javascript
update deployment used for e2e test
0f724a67feb3e80a5cbacbe152d170f73db432fe
<ide><path>test/e2e/app-dir/app/app/very-large-data-fetch/page.js <ide> export default async function Home() { <ide> const res = await fetch( <del> `https://data-api-endpoint-nmw78dd69-ijjk-testing.vercel.app/api/data?amount=128000` <add> `https://next-data-api-endpoint.vercel.app/api/data?amount=128000` <ide> ) <ide> const resClone = res.clone() <ide> const json = await resClone.json()
1
Python
Python
add test for #629
28051478f847c7d62a219484e6d2114adc7bf102
<ide><path>numpy/core/tests/test_scalarmath.py <ide> def test_basic(self): <ide> assert_array_equal(x[...],value) <ide> assert_array_equal(x[()],value) <ide> <add>class TestRepr(NumpyTestCase): <add> def check_float_repr(self): <add> from numpy import nan, inf <add> for t in [np.float32, np.float64, np.longdouble]: <add> finfo=np.finfo(t) <add> last_fraction_bit_idx = finfo.nexp + finfo.nmant <add> last_exponent_bit_idx = finfo.nexp <add> storage_bytes = np.dtype(t).itemsize*8 <add> for which in ['small denorm','small norm']: # could add some more types here <add> # Values from http://en.wikipedia.org/wiki/IEEE_754 <add> constr = array([0x00]*storage_bytes,dtype=np.uint8) <add> if which == 'small denorm': <add> byte = last_fraction_bit_idx // 8 <add> bytebit = 7-(last_fraction_bit_idx % 8) <add> constr[byte] = 1<<bytebit <add> elif which == 'small norm': <add> byte = last_exponent_bit_idx // 8 <add> bytebit = 7-(last_exponent_bit_idx % 8) <add> constr[byte] = 1<<bytebit <add> else: <add> raise ValueError('hmm') <add> val = constr.view(t)[0] <add> val_repr = repr(val) <add> val2 = t(eval(val_repr)) <add> if t == np.longdouble: <add> # Skip longdouble - the eval() statement goes <add> # through a Python float, which will lose <add> # precision <add> continue <add> assert_equal( val, val2 ) <add> <ide> if __name__ == "__main__": <ide> NumpyTest().run()
1
Javascript
Javascript
increase browser start and total run timeout times
8910a0dc8a1693b907d358e002d08a77101baa5a
<ide><path>testem.dist.js <ide> module.exports = { <ide> test_page: "dist/tests/index.html?hidepassed&hideskipped&timeout=60000", <ide> timeout: 540, <ide> reporter: FailureOnlyPerBrowserReporter, <del> browser_start_timeout: 600, <add> browser_start_timeout: 1200, <ide> parallel: 4, <ide> disable_watching: true, <ide> launchers: { <ide> BS_Chrome_Current: { <ide> exe: "node_modules/.bin/browserstack-launch", <del> args: ["--os", "Windows", "--osv", "10", "--b", "chrome", "--bv", "latest", "-t", "600", "--u", "<url>"], <add> args: ["--os", "Windows", "--osv", "10", "--b", "chrome", "--bv", "latest", "-t", "1200", "--u", "<url>"], <ide> protocol: "browser" <ide> }, <ide> BS_Firefox_Current: { <ide> exe: "node_modules/.bin/browserstack-launch", <del> args: ["--os", "Windows", "--osv", "10", "--b", "firefox", "--bv", "latest", "-t", "600", "--u", "<url>"], <add> args: ["--os", "Windows", "--osv", "10", "--b", "firefox", "--bv", "latest", "-t", "1200", "--u", "<url>"], <ide> protocol: "browser" <ide> }, <ide> BS_Safari_Current: { <ide> exe: "node_modules/.bin/browserstack-launch", <del> args: ["--os", "OS X", "--osv", "High Sierra", "--b", "safari", "--bv", "11", "-t", "600", "--u", "<url>"], <add> args: ["--os", "OS X", "--osv", "High Sierra", "--b", "safari", "--bv", "11", "-t", "1200", "--u", "<url>"], <ide> protocol: "browser" <ide> }, <ide> BS_Safari_Last: { <ide> exe: "node_modules/.bin/browserstack-launch", <del> args: ["--os", "OS X", "--osv", "Sierra", "--b", "safari", "--bv", "10.1", "-t", "600", "--u", "<url>"], <add> args: ["--os", "OS X", "--osv", "Sierra", "--b", "safari", "--bv", "10.1", "-t", "1200", "--u", "<url>"], <ide> protocol: "browser" <ide> }, <ide> BS_MS_Edge: { <ide> exe: "node_modules/.bin/browserstack-launch", <del> args: ["--os", "Windows", "--osv", "10", "--b", "edge", "--bv", "latest", "-t", "600", "--u", "<url>"], <add> args: ["--os", "Windows", "--osv", "10", "--b", "edge", "--bv", "latest", "-t", "1200", "--u", "<url>"], <ide> protocol: "browser" <ide> }, <ide> BS_IE_11: { <ide> exe: "node_modules/.bin/browserstack-launch", <del> args: ["--os", "Windows", "--osv", "10", "--b", "ie", "--bv", "11.0", "-t", "600", "--u", "<url>"], <add> args: ["--os", "Windows", "--osv", "10", "--b", "ie", "--bv", "11.0", "-t", "1200", "--u", "<url>"], <ide> protocol: "browser" <ide> } <ide> },
1
Ruby
Ruby
incorporate suggestions from code review
eebc161ea51aa74a93ce3394aeab72a35a57ed04
<ide><path>Library/Homebrew/cli/parser.rb <ide> def check_named_args(args) <ide> <ide> def process_option(*args) <ide> option, = @parser.make_switch(args) <del> @processed_options.reject! { |existing| option.long.first.present? && existing.second == option.long.first } <add> @processed_options.reject! { |existing| existing.second == option.long.first } if option.long.first.present? <ide> @processed_options << [option.short.first, option.long.first, option.arg, option.desc.first] <ide> end <ide> <ide><path>Library/Homebrew/cmd/options.rb <ide> def options <ide> puts_options Formula.to_a.sort, args: args <ide> elsif args.installed? <ide> puts_options Formula.installed.sort, args: args <del> elsif !args.command.nil? <add> elsif args.command.present? <ide> cmd_options = Commands.command_options(args.command) <add> odie "Unknown command: #{args.command}" if cmd_options.nil? <add> <ide> if args.compact? <ide> puts cmd_options.sort.map(&:first) * " " <ide> else <ide><path>Library/Homebrew/commands.rb <ide> def rebuild_commands_completion_list <ide> HOMEBREW_CACHE.mkpath <ide> <ide> cmds = commands(aliases: true).reject do |cmd| <del> # TODO: remove the cask check when `brew cask` is removed <add> # TODO: (2.8) remove the cask check when `brew cask` is removed <ide> cmd.start_with?("cask ") || Homebrew::Completions::COMPLETIONS_EXCLUSION_LIST.include?(cmd) <ide> end <ide> <ide> def rebuild_commands_completion_list <ide> end <ide> <ide> def command_options(command) <del> path = Commands.path(command) <del> return unless path <add> path = self.path(command) <add> return if path.blank? <ide> <ide> if cmd_parser = Homebrew::CLI::Parser.from_cmd_path(path) <ide> cmd_parser.processed_options.map do |short, long, _, desc| <ide> def command_options(command) <ide> end <ide> <ide> def named_args_type(command) <del> path = Commands.path(command) <del> return unless path <add> path = self.path(command) <add> return if path.blank? <ide> <ide> cmd_parser = Homebrew::CLI::Parser.from_cmd_path(path) <ide> return if cmd_parser.blank?
3
Javascript
Javascript
remove outdated comment
32fb7d93348c9d2d70bb4450913e22c68a7e76ca
<ide><path>lib/internal/util/inspect.js <ide> function getFunctionBase(value, constructor, tag) { <ide> } <ide> <ide> function formatError(err, constructor, tag, ctx) { <del> // TODO(BridgeAR): Always show the error code if present. <ide> let stack = err.stack || ErrorPrototype.toString(err); <ide> <ide> // A stack trace may contain arbitrary data. Only manipulate the output
1
PHP
PHP
shift things around
b17a5e347de088fc846f64c31557a7ca483c1531
<ide><path>lib/Cake/Routing/Route/Route.php <ide> public function match($url, $context = array()) { <ide> $url['prefix'] = $defaults['prefix']; <ide> } <ide> <del> // check that all the key names are in the url <del> $keyNames = array_flip($this->keys); <del> if (array_intersect_key($keyNames, $url) !== $keyNames) { <del> return false; <del> } <del> <ide> // Missing defaults is a fail. <ide> if (array_diff_key($defaults, $url) !== array()) { <ide> return false; <ide> public function match($url, $context = array()) { <ide> return false; <ide> } <ide> <add> // check that all the key names are in the url <add> $keyNames = array_flip($this->keys); <add> if (array_intersect_key($keyNames, $url) !== $keyNames) { <add> return false; <add> } <add> <ide> $prefixes = Router::prefixes(); <ide> $pass = array(); <ide> $query = array();
1
Java
Java
remove inefficiency in httpstatus.series()
97cc89630dce6e65dbe3f80e3d777f897c944667
<ide><path>spring-web/src/main/java/org/springframework/http/HttpStatus.java <ide> public enum HttpStatus { <ide> * {@code 100 Continue}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.2.1">HTTP/1.1: Semantics and Content, section 6.2.1</a> <ide> */ <del> CONTINUE(100, "Continue"), <add> CONTINUE(100, Series.INFORMATIONAL, "Continue"), <ide> /** <ide> * {@code 101 Switching Protocols}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.2.2">HTTP/1.1: Semantics and Content, section 6.2.2</a> <ide> */ <del> SWITCHING_PROTOCOLS(101, "Switching Protocols"), <add> SWITCHING_PROTOCOLS(101, Series.INFORMATIONAL, "Switching Protocols"), <ide> /** <ide> * {@code 102 Processing}. <ide> * @see <a href="https://tools.ietf.org/html/rfc2518#section-10.1">WebDAV</a> <ide> */ <del> PROCESSING(102, "Processing"), <add> PROCESSING(102, Series.INFORMATIONAL, "Processing"), <ide> /** <ide> * {@code 103 Checkpoint}. <ide> * @see <a href="https://code.google.com/p/gears/wiki/ResumableHttpRequestsProposal">A proposal for supporting <ide> * resumable POST/PUT HTTP requests in HTTP/1.0</a> <ide> */ <del> CHECKPOINT(103, "Checkpoint"), <add> CHECKPOINT(103, Series.INFORMATIONAL, "Checkpoint"), <ide> <ide> // 2xx Success <ide> <ide> /** <ide> * {@code 200 OK}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.3.1">HTTP/1.1: Semantics and Content, section 6.3.1</a> <ide> */ <del> OK(200, "OK"), <add> OK(200, Series.SUCCESSFUL, "OK"), <ide> /** <ide> * {@code 201 Created}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.3.2">HTTP/1.1: Semantics and Content, section 6.3.2</a> <ide> */ <del> CREATED(201, "Created"), <add> CREATED(201, Series.SUCCESSFUL, "Created"), <ide> /** <ide> * {@code 202 Accepted}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.3.3">HTTP/1.1: Semantics and Content, section 6.3.3</a> <ide> */ <del> ACCEPTED(202, "Accepted"), <add> ACCEPTED(202, Series.SUCCESSFUL, "Accepted"), <ide> /** <ide> * {@code 203 Non-Authoritative Information}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.3.4">HTTP/1.1: Semantics and Content, section 6.3.4</a> <ide> */ <del> NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"), <add> NON_AUTHORITATIVE_INFORMATION(203, Series.SUCCESSFUL, "Non-Authoritative Information"), <ide> /** <ide> * {@code 204 No Content}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.3.5">HTTP/1.1: Semantics and Content, section 6.3.5</a> <ide> */ <del> NO_CONTENT(204, "No Content"), <add> NO_CONTENT(204, Series.SUCCESSFUL, "No Content"), <ide> /** <ide> * {@code 205 Reset Content}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.3.6">HTTP/1.1: Semantics and Content, section 6.3.6</a> <ide> */ <del> RESET_CONTENT(205, "Reset Content"), <add> RESET_CONTENT(205, Series.SUCCESSFUL, "Reset Content"), <ide> /** <ide> * {@code 206 Partial Content}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7233#section-4.1">HTTP/1.1: Range Requests, section 4.1</a> <ide> */ <del> PARTIAL_CONTENT(206, "Partial Content"), <add> PARTIAL_CONTENT(206, Series.SUCCESSFUL, "Partial Content"), <ide> /** <ide> * {@code 207 Multi-Status}. <ide> * @see <a href="https://tools.ietf.org/html/rfc4918#section-13">WebDAV</a> <ide> */ <del> MULTI_STATUS(207, "Multi-Status"), <add> MULTI_STATUS(207, Series.SUCCESSFUL, "Multi-Status"), <ide> /** <ide> * {@code 208 Already Reported}. <ide> * @see <a href="https://tools.ietf.org/html/rfc5842#section-7.1">WebDAV Binding Extensions</a> <ide> */ <del> ALREADY_REPORTED(208, "Already Reported"), <add> ALREADY_REPORTED(208, Series.SUCCESSFUL, "Already Reported"), <ide> /** <ide> * {@code 226 IM Used}. <ide> * @see <a href="https://tools.ietf.org/html/rfc3229#section-10.4.1">Delta encoding in HTTP</a> <ide> */ <del> IM_USED(226, "IM Used"), <add> IM_USED(226, Series.SUCCESSFUL, "IM Used"), <ide> <ide> // 3xx Redirection <ide> <ide> /** <ide> * {@code 300 Multiple Choices}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.4.1">HTTP/1.1: Semantics and Content, section 6.4.1</a> <ide> */ <del> MULTIPLE_CHOICES(300, "Multiple Choices"), <add> MULTIPLE_CHOICES(300, Series.REDIRECTION, "Multiple Choices"), <ide> /** <ide> * {@code 301 Moved Permanently}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.4.2">HTTP/1.1: Semantics and Content, section 6.4.2</a> <ide> */ <del> MOVED_PERMANENTLY(301, "Moved Permanently"), <add> MOVED_PERMANENTLY(301, Series.REDIRECTION, "Moved Permanently"), <ide> /** <ide> * {@code 302 Found}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.4.3">HTTP/1.1: Semantics and Content, section 6.4.3</a> <ide> */ <del> FOUND(302, "Found"), <add> FOUND(302, Series.REDIRECTION, "Found"), <ide> /** <ide> * {@code 302 Moved Temporarily}. <ide> * @see <a href="https://tools.ietf.org/html/rfc1945#section-9.3">HTTP/1.0, section 9.3</a> <ide> * @deprecated in favor of {@link #FOUND} which will be returned from {@code HttpStatus.valueOf(302)} <ide> */ <ide> @Deprecated <del> MOVED_TEMPORARILY(302, "Moved Temporarily"), <add> MOVED_TEMPORARILY(302, Series.REDIRECTION, "Moved Temporarily"), <ide> /** <ide> * {@code 303 See Other}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.4.4">HTTP/1.1: Semantics and Content, section 6.4.4</a> <ide> */ <del> SEE_OTHER(303, "See Other"), <add> SEE_OTHER(303, Series.REDIRECTION, "See Other"), <ide> /** <ide> * {@code 304 Not Modified}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7232#section-4.1">HTTP/1.1: Conditional Requests, section 4.1</a> <ide> */ <del> NOT_MODIFIED(304, "Not Modified"), <add> NOT_MODIFIED(304, Series.REDIRECTION, "Not Modified"), <ide> /** <ide> * {@code 305 Use Proxy}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.4.5">HTTP/1.1: Semantics and Content, section 6.4.5</a> <ide> * @deprecated due to security concerns regarding in-band configuration of a proxy <ide> */ <ide> @Deprecated <del> USE_PROXY(305, "Use Proxy"), <add> USE_PROXY(305, Series.REDIRECTION, "Use Proxy"), <ide> /** <ide> * {@code 307 Temporary Redirect}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.4.7">HTTP/1.1: Semantics and Content, section 6.4.7</a> <ide> */ <del> TEMPORARY_REDIRECT(307, "Temporary Redirect"), <add> TEMPORARY_REDIRECT(307, Series.REDIRECTION, "Temporary Redirect"), <ide> /** <ide> * {@code 308 Permanent Redirect}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7238">RFC 7238</a> <ide> */ <del> PERMANENT_REDIRECT(308, "Permanent Redirect"), <add> PERMANENT_REDIRECT(308, Series.REDIRECTION, "Permanent Redirect"), <ide> <ide> // --- 4xx Client Error --- <ide> <ide> /** <ide> * {@code 400 Bad Request}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.1">HTTP/1.1: Semantics and Content, section 6.5.1</a> <ide> */ <del> BAD_REQUEST(400, "Bad Request"), <add> BAD_REQUEST(400, Series.CLIENT_ERROR, "Bad Request"), <ide> /** <ide> * {@code 401 Unauthorized}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7235#section-3.1">HTTP/1.1: Authentication, section 3.1</a> <ide> */ <del> UNAUTHORIZED(401, "Unauthorized"), <add> UNAUTHORIZED(401, Series.CLIENT_ERROR, "Unauthorized"), <ide> /** <ide> * {@code 402 Payment Required}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.2">HTTP/1.1: Semantics and Content, section 6.5.2</a> <ide> */ <del> PAYMENT_REQUIRED(402, "Payment Required"), <add> PAYMENT_REQUIRED(402, Series.CLIENT_ERROR, "Payment Required"), <ide> /** <ide> * {@code 403 Forbidden}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.3">HTTP/1.1: Semantics and Content, section 6.5.3</a> <ide> */ <del> FORBIDDEN(403, "Forbidden"), <add> FORBIDDEN(403, Series.CLIENT_ERROR, "Forbidden"), <ide> /** <ide> * {@code 404 Not Found}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.4">HTTP/1.1: Semantics and Content, section 6.5.4</a> <ide> */ <del> NOT_FOUND(404, "Not Found"), <add> NOT_FOUND(404, Series.CLIENT_ERROR, "Not Found"), <ide> /** <ide> * {@code 405 Method Not Allowed}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.5">HTTP/1.1: Semantics and Content, section 6.5.5</a> <ide> */ <del> METHOD_NOT_ALLOWED(405, "Method Not Allowed"), <add> METHOD_NOT_ALLOWED(405, Series.CLIENT_ERROR, "Method Not Allowed"), <ide> /** <ide> * {@code 406 Not Acceptable}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.6">HTTP/1.1: Semantics and Content, section 6.5.6</a> <ide> */ <del> NOT_ACCEPTABLE(406, "Not Acceptable"), <add> NOT_ACCEPTABLE(406, Series.CLIENT_ERROR, "Not Acceptable"), <ide> /** <ide> * {@code 407 Proxy Authentication Required}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7235#section-3.2">HTTP/1.1: Authentication, section 3.2</a> <ide> */ <del> PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"), <add> PROXY_AUTHENTICATION_REQUIRED(407, Series.CLIENT_ERROR, "Proxy Authentication Required"), <ide> /** <ide> * {@code 408 Request Timeout}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.7">HTTP/1.1: Semantics and Content, section 6.5.7</a> <ide> */ <del> REQUEST_TIMEOUT(408, "Request Timeout"), <add> REQUEST_TIMEOUT(408, Series.CLIENT_ERROR, "Request Timeout"), <ide> /** <ide> * {@code 409 Conflict}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.8">HTTP/1.1: Semantics and Content, section 6.5.8</a> <ide> */ <del> CONFLICT(409, "Conflict"), <add> CONFLICT(409, Series.CLIENT_ERROR, "Conflict"), <ide> /** <ide> * {@code 410 Gone}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.9"> <ide> * HTTP/1.1: Semantics and Content, section 6.5.9</a> <ide> */ <del> GONE(410, "Gone"), <add> GONE(410, Series.CLIENT_ERROR, "Gone"), <ide> /** <ide> * {@code 411 Length Required}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.10"> <ide> * HTTP/1.1: Semantics and Content, section 6.5.10</a> <ide> */ <del> LENGTH_REQUIRED(411, "Length Required"), <add> LENGTH_REQUIRED(411, Series.CLIENT_ERROR, "Length Required"), <ide> /** <ide> * {@code 412 Precondition failed}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7232#section-4.2"> <ide> * HTTP/1.1: Conditional Requests, section 4.2</a> <ide> */ <del> PRECONDITION_FAILED(412, "Precondition Failed"), <add> PRECONDITION_FAILED(412, Series.CLIENT_ERROR, "Precondition Failed"), <ide> /** <ide> * {@code 413 Payload Too Large}. <ide> * @since 4.1 <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.11"> <ide> * HTTP/1.1: Semantics and Content, section 6.5.11</a> <ide> */ <del> PAYLOAD_TOO_LARGE(413, "Payload Too Large"), <add> PAYLOAD_TOO_LARGE(413, Series.CLIENT_ERROR, "Payload Too Large"), <ide> /** <ide> * {@code 413 Request Entity Too Large}. <ide> * @see <a href="https://tools.ietf.org/html/rfc2616#section-10.4.14">HTTP/1.1, section 10.4.14</a> <ide> * @deprecated in favor of {@link #PAYLOAD_TOO_LARGE} which will be <ide> * returned from {@code HttpStatus.valueOf(413)} <ide> */ <ide> @Deprecated <del> REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"), <add> REQUEST_ENTITY_TOO_LARGE(413, Series.CLIENT_ERROR, "Request Entity Too Large"), <ide> /** <ide> * {@code 414 URI Too Long}. <ide> * @since 4.1 <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.12"> <ide> * HTTP/1.1: Semantics and Content, section 6.5.12</a> <ide> */ <del> URI_TOO_LONG(414, "URI Too Long"), <add> URI_TOO_LONG(414, Series.CLIENT_ERROR, "URI Too Long"), <ide> /** <ide> * {@code 414 Request-URI Too Long}. <ide> * @see <a href="https://tools.ietf.org/html/rfc2616#section-10.4.15">HTTP/1.1, section 10.4.15</a> <ide> * @deprecated in favor of {@link #URI_TOO_LONG} which will be returned from {@code HttpStatus.valueOf(414)} <ide> */ <ide> @Deprecated <del> REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"), <add> REQUEST_URI_TOO_LONG(414, Series.CLIENT_ERROR, "Request-URI Too Long"), <ide> /** <ide> * {@code 415 Unsupported Media Type}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.13"> <ide> * HTTP/1.1: Semantics and Content, section 6.5.13</a> <ide> */ <del> UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), <add> UNSUPPORTED_MEDIA_TYPE(415, Series.CLIENT_ERROR, "Unsupported Media Type"), <ide> /** <ide> * {@code 416 Requested Range Not Satisfiable}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7233#section-4.4">HTTP/1.1: Range Requests, section 4.4</a> <ide> */ <del> REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested range not satisfiable"), <add> REQUESTED_RANGE_NOT_SATISFIABLE(416, Series.CLIENT_ERROR, "Requested range not satisfiable"), <ide> /** <ide> * {@code 417 Expectation Failed}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.5.14"> <ide> * HTTP/1.1: Semantics and Content, section 6.5.14</a> <ide> */ <del> EXPECTATION_FAILED(417, "Expectation Failed"), <add> EXPECTATION_FAILED(417, Series.CLIENT_ERROR, "Expectation Failed"), <ide> /** <ide> * {@code 418 I'm a teapot}. <ide> * @see <a href="https://tools.ietf.org/html/rfc2324#section-2.3.2">HTCPCP/1.0</a> <ide> */ <del> I_AM_A_TEAPOT(418, "I'm a teapot"), <add> I_AM_A_TEAPOT(418, Series.CLIENT_ERROR, "I'm a teapot"), <ide> /** <ide> * @deprecated See <ide> * <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt"> <ide> * WebDAV Draft Changes</a> <ide> */ <ide> @Deprecated <del> INSUFFICIENT_SPACE_ON_RESOURCE(419, "Insufficient Space On Resource"), <add> INSUFFICIENT_SPACE_ON_RESOURCE(419, Series.CLIENT_ERROR, "Insufficient Space On Resource"), <ide> /** <ide> * @deprecated See <ide> * <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt"> <ide> * WebDAV Draft Changes</a> <ide> */ <ide> @Deprecated <del> METHOD_FAILURE(420, "Method Failure"), <add> METHOD_FAILURE(420, Series.CLIENT_ERROR, "Method Failure"), <ide> /** <ide> * @deprecated <ide> * See <a href="https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt"> <ide> * WebDAV Draft Changes</a> <ide> */ <ide> @Deprecated <del> DESTINATION_LOCKED(421, "Destination Locked"), <add> DESTINATION_LOCKED(421, Series.CLIENT_ERROR, "Destination Locked"), <ide> /** <ide> * {@code 422 Unprocessable Entity}. <ide> * @see <a href="https://tools.ietf.org/html/rfc4918#section-11.2">WebDAV</a> <ide> */ <del> UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"), <add> UNPROCESSABLE_ENTITY(422, Series.CLIENT_ERROR, "Unprocessable Entity"), <ide> /** <ide> * {@code 423 Locked}. <ide> * @see <a href="https://tools.ietf.org/html/rfc4918#section-11.3">WebDAV</a> <ide> */ <del> LOCKED(423, "Locked"), <add> LOCKED(423, Series.CLIENT_ERROR, "Locked"), <ide> /** <ide> * {@code 424 Failed Dependency}. <ide> * @see <a href="https://tools.ietf.org/html/rfc4918#section-11.4">WebDAV</a> <ide> */ <del> FAILED_DEPENDENCY(424, "Failed Dependency"), <add> FAILED_DEPENDENCY(424, Series.CLIENT_ERROR, "Failed Dependency"), <ide> /** <ide> * {@code 425 Too Early}. <ide> * @since 5.2 <ide> * @see <a href="https://tools.ietf.org/html/rfc8470">RFC 8470</a> <ide> */ <del> TOO_EARLY(425, "Too Early"), <add> TOO_EARLY(425, Series.CLIENT_ERROR, "Too Early"), <ide> /** <ide> * {@code 426 Upgrade Required}. <ide> * @see <a href="https://tools.ietf.org/html/rfc2817#section-6">Upgrading to TLS Within HTTP/1.1</a> <ide> */ <del> UPGRADE_REQUIRED(426, "Upgrade Required"), <add> UPGRADE_REQUIRED(426, Series.CLIENT_ERROR, "Upgrade Required"), <ide> /** <ide> * {@code 428 Precondition Required}. <ide> * @see <a href="https://tools.ietf.org/html/rfc6585#section-3">Additional HTTP Status Codes</a> <ide> */ <del> PRECONDITION_REQUIRED(428, "Precondition Required"), <add> PRECONDITION_REQUIRED(428, Series.CLIENT_ERROR, "Precondition Required"), <ide> /** <ide> * {@code 429 Too Many Requests}. <ide> * @see <a href="https://tools.ietf.org/html/rfc6585#section-4">Additional HTTP Status Codes</a> <ide> */ <del> TOO_MANY_REQUESTS(429, "Too Many Requests"), <add> TOO_MANY_REQUESTS(429, Series.CLIENT_ERROR, "Too Many Requests"), <ide> /** <ide> * {@code 431 Request Header Fields Too Large}. <ide> * @see <a href="https://tools.ietf.org/html/rfc6585#section-5">Additional HTTP Status Codes</a> <ide> */ <del> REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"), <add> REQUEST_HEADER_FIELDS_TOO_LARGE(431, Series.CLIENT_ERROR, "Request Header Fields Too Large"), <ide> /** <ide> * {@code 451 Unavailable For Legal Reasons}. <ide> * @see <a href="https://tools.ietf.org/html/draft-ietf-httpbis-legally-restricted-status-04"> <ide> * An HTTP Status Code to Report Legal Obstacles</a> <ide> * @since 4.3 <ide> */ <del> UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"), <add> UNAVAILABLE_FOR_LEGAL_REASONS(451, Series.CLIENT_ERROR, "Unavailable For Legal Reasons"), <ide> <ide> // --- 5xx Server Error --- <ide> <ide> /** <ide> * {@code 500 Internal Server Error}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.6.1">HTTP/1.1: Semantics and Content, section 6.6.1</a> <ide> */ <del> INTERNAL_SERVER_ERROR(500, "Internal Server Error"), <add> INTERNAL_SERVER_ERROR(500, Series.SERVER_ERROR, "Internal Server Error"), <ide> /** <ide> * {@code 501 Not Implemented}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.6.2">HTTP/1.1: Semantics and Content, section 6.6.2</a> <ide> */ <del> NOT_IMPLEMENTED(501, "Not Implemented"), <add> NOT_IMPLEMENTED(501, Series.SERVER_ERROR, "Not Implemented"), <ide> /** <ide> * {@code 502 Bad Gateway}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.6.3">HTTP/1.1: Semantics and Content, section 6.6.3</a> <ide> */ <del> BAD_GATEWAY(502, "Bad Gateway"), <add> BAD_GATEWAY(502, Series.SERVER_ERROR, "Bad Gateway"), <ide> /** <ide> * {@code 503 Service Unavailable}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.6.4">HTTP/1.1: Semantics and Content, section 6.6.4</a> <ide> */ <del> SERVICE_UNAVAILABLE(503, "Service Unavailable"), <add> SERVICE_UNAVAILABLE(503, Series.SERVER_ERROR, "Service Unavailable"), <ide> /** <ide> * {@code 504 Gateway Timeout}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.6.5">HTTP/1.1: Semantics and Content, section 6.6.5</a> <ide> */ <del> GATEWAY_TIMEOUT(504, "Gateway Timeout"), <add> GATEWAY_TIMEOUT(504, Series.SERVER_ERROR, "Gateway Timeout"), <ide> /** <ide> * {@code 505 HTTP Version Not Supported}. <ide> * @see <a href="https://tools.ietf.org/html/rfc7231#section-6.6.6">HTTP/1.1: Semantics and Content, section 6.6.6</a> <ide> */ <del> HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version not supported"), <add> HTTP_VERSION_NOT_SUPPORTED(505, Series.SERVER_ERROR, "HTTP Version not supported"), <ide> /** <ide> * {@code 506 Variant Also Negotiates} <ide> * @see <a href="https://tools.ietf.org/html/rfc2295#section-8.1">Transparent Content Negotiation</a> <ide> */ <del> VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates"), <add> VARIANT_ALSO_NEGOTIATES(506, Series.SERVER_ERROR, "Variant Also Negotiates"), <ide> /** <ide> * {@code 507 Insufficient Storage} <ide> * @see <a href="https://tools.ietf.org/html/rfc4918#section-11.5">WebDAV</a> <ide> */ <del> INSUFFICIENT_STORAGE(507, "Insufficient Storage"), <add> INSUFFICIENT_STORAGE(507, Series.SERVER_ERROR, "Insufficient Storage"), <ide> /** <ide> * {@code 508 Loop Detected} <ide> * @see <a href="https://tools.ietf.org/html/rfc5842#section-7.2">WebDAV Binding Extensions</a> <ide> */ <del> LOOP_DETECTED(508, "Loop Detected"), <add> LOOP_DETECTED(508, Series.SERVER_ERROR, "Loop Detected"), <ide> /** <ide> * {@code 509 Bandwidth Limit Exceeded} <ide> */ <del> BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded"), <add> BANDWIDTH_LIMIT_EXCEEDED(509, Series.SERVER_ERROR, "Bandwidth Limit Exceeded"), <ide> /** <ide> * {@code 510 Not Extended} <ide> * @see <a href="https://tools.ietf.org/html/rfc2774#section-7">HTTP Extension Framework</a> <ide> */ <del> NOT_EXTENDED(510, "Not Extended"), <add> NOT_EXTENDED(510, Series.SERVER_ERROR, "Not Extended"), <ide> /** <ide> * {@code 511 Network Authentication Required}. <ide> * @see <a href="https://tools.ietf.org/html/rfc6585#section-6">Additional HTTP Status Codes</a> <ide> */ <del> NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required"); <add> NETWORK_AUTHENTICATION_REQUIRED(511, Series.SERVER_ERROR, "Network Authentication Required"); <ide> <ide> <ide> private final int value; <ide> <ide> private final String reasonPhrase; <ide> <add> private final Series series; <ide> <del> HttpStatus(int value, String reasonPhrase) { <add> HttpStatus(int value, Series series, String reasonPhrase) { <ide> this.value = value; <ide> this.reasonPhrase = reasonPhrase; <add> this.series = series; <ide> } <ide> <ide> <ide> public String getReasonPhrase() { <ide> * @see HttpStatus.Series <ide> */ <ide> public Series series() { <del> return Series.valueOf(this); <add> return this.series; <ide> } <ide> <ide> /** <ide> public int value() { <ide> * Return the enum constant of this type with the corresponding series. <ide> * @param status a standard HTTP status enum value <ide> * @return the enum constant of this type with the corresponding series <del> * @throws IllegalArgumentException if this enum has no corresponding constant <ide> */ <ide> public static Series valueOf(HttpStatus status) { <del> return valueOf(status.value); <add> return status.series; <ide> } <ide> <ide> /** <ide><path>spring-web/src/test/java/org/springframework/http/HttpStatusTests.java <ide> public void fromEnumToMap() { <ide> } <ide> } <ide> <add> @Test <add> public void allStatusSeriesShouldMatchExpectations() { <add> // a series of a status is manually set, make sure it is the correct one <add> for (HttpStatus status : HttpStatus.values()) { <add> HttpStatus.Series expectedSeries = HttpStatus.Series.valueOf(status.value()); <add> assertThat(expectedSeries).isEqualTo(status.series()); <add> } <add> } <ide> }
2
Text
Text
add table of contents to readme (#735)
d6439d172b70e866becfa380af244bba9950fb6e
<ide><path>README.md <ide> <ide> Next.js is a minimalistic framework for server-rendered React applications. <ide> <del>**NOTE! the README on the `master` branch might not match that of the [latest stable release](https://github.com/zeit/next.js/releases/latest)! ** <add>_**NOTE! the README on the `master` branch might not match that of the [latest stable release](https://github.com/zeit/next.js/releases/latest)!**_ <add> <add><!-- START doctoc generated TOC please keep comment here to allow auto update --> <add><!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <add><!-- https://github.com/thlorenz/doctoc --> <add> <add>- [How to use](#how-to-use) <add> - [Setup](#setup) <add> - [Automatic code splitting](#automatic-code-splitting) <add> - [CSS](#css) <add> - [Built-in CSS support](#built-in-css-support) <add> - [CSS-in-JS](#css-in-js) <add> - [Static file serving (e.g.: images)](#static-file-serving-eg-images) <add> - [Populating `<head>`](#populating-head) <add> - [Fetching data and component lifecycle](#fetching-data-and-component-lifecycle) <add> - [Routing](#routing) <add> - [With `<Link>`](#with-link) <add> - [Imperatively](#imperatively) <add> - [Router Events](#router-events) <add> - [Prefetching Pages](#prefetching-pages) <add> - [With `<Link>`](#with-link-1) <add> - [Imperatively](#imperatively-1) <add> - [Custom server and routing](#custom-server-and-routing) <add> - [Custom `<Document>`](#custom-document) <add> - [Custom error handling](#custom-error-handling) <add> - [Custom configuration](#custom-configuration) <add> - [Customizing webpack config](#customizing-webpack-config) <add> - [Customizing babel config](#customizing-babel-config) <add>- [Production deployment](#production-deployment) <add>- [FAQ](#faq) <add>- [Roadmap](#roadmap) <add>- [Authors](#authors) <add> <add><!-- END doctoc generated TOC please keep comment here to allow auto update --> <ide> <ide> ## How to use <ide> <add>### Setup <add> <ide> Install it: <ide> <ide> ```bash
1
PHP
PHP
fix cs issues
8351c8f912ace3523f98d97c83a7695ef0c73d1a
<ide><path>tests/Notifications/NotificationSlackChannelTest.php <ide> public function testCorrectPayloadWithAttachmentFieldBuilderIsSentToSlack() <ide> [ <ide> 'title' => 'Special powers', <ide> 'value' => 'Zonda', <del> 'short' => false <add> 'short' => false, <ide> ] <ide> ], <ide> ], <ide> public function toSlack($notifiable) <ide> $attachment->title('Laravel', 'https://laravel.com') <ide> ->content('Attachment Content') <ide> ->field('Project', 'Laravel') <del> ->field(function($attachmentField) { <add> ->field(function ($attachmentField) { <ide> $attachmentField <ide> ->title('Special powers') <ide> ->content('Zonda')
1
Ruby
Ruby
use a case statement
230161c1deb4bee497c12e7dfe87f41a236b2d44
<ide><path>Library/Homebrew/extend/ENV/super.rb <ide> def universal_binary <ide> end <ide> <ide> def cxx11 <del> if self['HOMEBREW_CC'] == 'clang' <add> case self["HOMEBREW_CC"] <add> when "clang" <ide> append 'HOMEBREW_CCCFG', "x", '' <ide> append 'HOMEBREW_CCCFG', "g", '' <del> elsif self['HOMEBREW_CC'] =~ /gcc-4\.(8|9)/ <add> when /gcc-4\.(8|9)/ <ide> append 'HOMEBREW_CCCFG', "x", '' <ide> else <ide> raise "The selected compiler doesn't support C++11: #{self['HOMEBREW_CC']}"
1
Java
Java
fix failing test (after previous commit)
53e8ebe6a66e71f2565c496861a0baa0db80359e
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultPathSegmentContainer.java <ide> private static void parseParamValues(String input, Charset charset, MultiValueMa <ide> } <ide> <ide> static PathSegmentContainer subPath(PathSegmentContainer container, int fromIndex, int toIndex) { <add> if (fromIndex == toIndex) { <add> return EMPTY_PATH; <add> } <ide> List<PathSegment> segments = container.pathSegments(); <ide> if (fromIndex == 0 && toIndex == segments.size()) { <ide> return container; <ide> } <add> <ide> Assert.isTrue(fromIndex < toIndex, "fromIndex: " + fromIndex + " should be < toIndex " + toIndex); <ide> Assert.isTrue(fromIndex >= 0 && fromIndex < segments.size(), "Invalid fromIndex: " + fromIndex); <ide> Assert.isTrue(toIndex >= 0 && toIndex <= segments.size(), "Invalid toIndex: " + toIndex); <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/DefaultRequestPathTests.java <ide> public void requestPath() throws Exception { <ide> // no context path <ide> testRequestPath("/a/b/c", "", "/a/b/c", false, true, false); <ide> <add> // context path only <add> testRequestPath("/a/b", "/a/b", "", false, true, false); <add> <ide> // empty path <ide> testRequestPath("", "", "", true, false, false); <ide> testRequestPath("", "/", "", true, false, false);
2
Javascript
Javascript
unify ga and add to donation
78df3067078b29e868ca5fbe40e01101cd60982d
<ide><path>client/src/client-only-routes/ShowCertification.js <ide> import { <ide> showCert, <ide> userFetchStateSelector, <ide> usernameSelector, <del> isDonatingSelector <add> isDonatingSelector, <add> executeGA <ide> } from '../redux'; <ide> import validCertNames from '../../utils/validCertNames'; <ide> import { createFlashMessage } from '../components/Flash/redux'; <ide> const propTypes = { <ide> certDashedName: PropTypes.string, <ide> certName: PropTypes.string, <ide> createFlashMessage: PropTypes.func.isRequired, <add> executeGA: PropTypes.func, <ide> fetchState: PropTypes.shape({ <ide> pending: PropTypes.bool, <ide> complete: PropTypes.bool, <ide> const mapStateToProps = (state, { certName }) => { <ide> }; <ide> <ide> const mapDispatchToProps = dispatch => <del> bindActionCreators({ createFlashMessage, showCert }, dispatch); <add> bindActionCreators({ createFlashMessage, showCert, executeGA }, dispatch); <ide> <ide> class ShowCertification extends Component { <ide> constructor(...args) { <ide> super(...args); <ide> <ide> this.state = { <del> closeBtn: false, <del> donationClosed: false <add> isDonationSubmitted: false, <add> isDonationDisplayed: false, <add> isDonationClosed: false <ide> }; <ide> <ide> this.hideDonationSection = this.hideDonationSection.bind(this); <del> this.showDonationCloseBtn = this.showDonationCloseBtn.bind(this); <add> this.handleProcessing = this.handleProcessing.bind(this); <ide> } <ide> <ide> componentDidMount() { <ide> class ShowCertification extends Component { <ide> return null; <ide> } <ide> <add> shouldComponentUpdate(nextProps) { <add> const { <add> userFetchState: { complete: userComplete }, <add> signedInUserName, <add> isDonating, <add> cert: { username = '' }, <add> executeGA <add> } = nextProps; <add> const { isDonationDisplayed } = this.state; <add> <add> if ( <add> !isDonationDisplayed && <add> userComplete && <add> signedInUserName === username && <add> !isDonating <add> ) { <add> this.setState({ <add> isDonationDisplayed: true <add> }); <add> <add> executeGA({ <add> type: 'event', <add> data: { <add> category: 'Donation', <add> action: 'Displayed Certificate Donation', <add> nonInteraction: true <add> } <add> }); <add> } <add> return true; <add> } <add> <ide> hideDonationSection() { <del> this.setState({ donationClosed: true }); <add> this.setState({ isDonationDisplayed: false, isDonationClosed: true }); <ide> } <ide> <del> showDonationCloseBtn() { <del> this.setState({ closeBtn: true }); <add> handleProcessing(duration, amount) { <add> this.props.executeGA({ <add> type: 'event', <add> data: { <add> category: 'donation', <add> action: 'certificate stripe form submission', <add> label: duration, <add> value: amount <add> } <add> }); <add> this.setState({ isDonationSubmitted: true }); <ide> } <ide> <ide> render() { <ide> class ShowCertification extends Component { <ide> fetchState, <ide> validCertName, <ide> createFlashMessage, <del> certName, <del> signedInUserName, <del> isDonating, <del> userFetchState <add> certName <ide> } = this.props; <ide> <del> const { donationClosed, closeBtn } = this.state; <add> const { <add> isDonationSubmitted, <add> isDonationDisplayed, <add> isDonationClosed <add> } = this.state; <ide> <ide> if (!validCertName) { <ide> createFlashMessage(standardErrorMessage); <ide> return <RedirectHome />; <ide> } <ide> <ide> const { pending, complete, errored } = fetchState; <del> const { complete: userComplete } = userFetchState; <ide> <ide> if (pending) { <ide> return <Loader fullScreen={true} />; <ide> class ShowCertification extends Component { <ide> completionTime <ide> } = cert; <ide> <del> let conditionalDonationSection = ''; <del> <ide> const donationCloseBtn = ( <ide> <div> <ide> <Button <ide> class ShowCertification extends Component { <ide> </div> <ide> ); <ide> <del> if ( <del> userComplete && <del> signedInUserName === username && <del> !isDonating && <del> !donationClosed <del> ) { <del> conditionalDonationSection = ( <del> <Grid className='donation-section'> <del> {!closeBtn && ( <del> <Row> <del> <Col sm={10} smOffset={1} xs={12}> <del> <p> <del> Only you can see this message. Congratulations on earning this <del> certification. It’s no easy task. Running freeCodeCamp isn’t <del> easy either. Nor is it cheap. Help us help you and many other <del> people around the world. Make a tax-deductible supporting <del> donation to our nonprofit today. <del> </p> <del> </Col> <del> </Row> <del> )} <del> <MinimalDonateForm <del> showCloseBtn={this.showDonationCloseBtn} <del> defaultTheme='light' <del> /> <add> let donationSection = ( <add> <Grid className='donation-section'> <add> {!isDonationSubmitted && ( <ide> <Row> <del> <Col sm={4} smOffset={4} xs={6} xsOffset={3}> <del> {closeBtn ? donationCloseBtn : ''} <add> <Col sm={10} smOffset={1} xs={12}> <add> <p> <add> Only you can see this message. Congratulations on earning this <add> certification. It’s no easy task. Running freeCodeCamp isn’t <add> easy either. Nor is it cheap. Help us help you and many other <add> people around the world. Make a tax-deductible supporting <add> donation to our nonprofit today. <add> </p> <ide> </Col> <ide> </Row> <del> </Grid> <del> ); <del> } <add> )} <add> <MinimalDonateForm <add> handleProcessing={this.handleProcessing} <add> defaultTheme='light' <add> /> <add> <Row> <add> <Col sm={4} smOffset={4} xs={6} xsOffset={3}> <add> {isDonationSubmitted && donationCloseBtn} <add> </Col> <add> </Row> <add> </Grid> <add> ); <ide> <ide> return ( <ide> <div className='certificate-outer-wrapper'> <del> {conditionalDonationSection} <add> {isDonationDisplayed && !isDonationClosed ? donationSection : ''} <ide> <Grid className='certificate-wrapper certification-namespace'> <ide> <Row> <ide> <header> <ide><path>client/src/components/Donation/DonateForm.js <ide> const numToCommas = num => <ide> num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); <ide> <ide> const propTypes = { <add> handleProcessing: PropTypes.func, <ide> isDonating: PropTypes.bool, <ide> isSignedIn: PropTypes.bool, <ide> navigate: PropTypes.func.isRequired, <ide> class DonateForm extends Component { <ide> } <ide> <ide> renderDonationOptions() { <del> const { stripe } = this.props; <add> const { stripe, handleProcessing } = this.props; <ide> const { donationAmount, donationDuration, paymentType } = this.state; <ide> return ( <ide> <div> <ide> class DonateForm extends Component { <ide> donationAmount={donationAmount} <ide> donationDuration={donationDuration} <ide> getDonationButtonLabel={this.getDonationButtonLabel} <add> handleProcessing={handleProcessing} <ide> hideAmountOptionsCB={this.hideAmountOptionsCB} <ide> /> <ide> </Elements> <ide><path>client/src/components/Donation/DonateFormChildViewForHOC.js <ide> const propTypes = { <ide> donationDuration: PropTypes.string.isRequired, <ide> email: PropTypes.string, <ide> getDonationButtonLabel: PropTypes.func.isRequired, <add> handleProcessing: PropTypes.func, <ide> isSignedIn: PropTypes.bool, <ide> showCloseBtn: PropTypes.func, <ide> stripe: PropTypes.shape({ <ide> class DonateFormChildViewForHOC extends Component { <ide> <ide> // change the donation modal button label to close <ide> // or display the close button for the cert donation section <del> if (this.props.showCloseBtn) { <del> this.props.showCloseBtn(); <add> if (this.props.handleProcessing) { <add> this.props.handleProcessing( <add> this.state.donationDuration, <add> Math.round(this.state.donationAmount / 100) <add> ); <ide> } <ide> <ide> return postChargeStripe(yearEndGift, { <ide><path>client/src/components/Donation/DonationModal.js <ide> import Heart from '../../assets/icons/Heart'; <ide> import Cup from '../../assets/icons/Cup'; <ide> import MinimalDonateForm from './MinimalDonateForm'; <ide> <del>import ga from '../../analytics'; <ide> import { <ide> closeDonationModal, <ide> isDonationModalOpenSelector, <del> isBlockDonationModalSelector <add> isBlockDonationModalSelector, <add> executeGA <ide> } from '../../redux'; <ide> <ide> import { challengeMetaSelector } from '../../templates/Challenges/redux'; <ide> const mapStateToProps = createSelector( <ide> const mapDispatchToProps = dispatch => <ide> bindActionCreators( <ide> { <del> closeDonationModal <add> closeDonationModal, <add> executeGA <ide> }, <ide> dispatch <ide> ); <ide> const propTypes = { <ide> activeDonors: PropTypes.number, <ide> block: PropTypes.string, <ide> closeDonationModal: PropTypes.func.isRequired, <add> executeGA: PropTypes.func, <ide> isBlockDonation: PropTypes.bool, <ide> show: PropTypes.bool <ide> }; <ide> <del>function DonateModal({ show, block, isBlockDonation, closeDonationModal }) { <add>function DonateModal({ <add> show, <add> block, <add> isBlockDonation, <add> closeDonationModal, <add> executeGA <add>}) { <ide> const [closeLabel, setCloseLabel] = React.useState(false); <del> const showCloseBtn = () => { <add> const handleProcessing = (duration, amount) => { <add> executeGA({ <add> type: 'event', <add> data: { <add> category: 'donation', <add> action: 'Modal strip form submission', <add> label: duration, <add> value: amount <add> } <add> }); <ide> setCloseLabel(true); <ide> }; <ide> <ide> if (show) { <del> ga.modalview('/donation-modal'); <add> executeGA({ type: 'modal', data: '/donation-modal' }); <add> executeGA({ <add> type: 'event', <add> data: { <add> category: 'Donation', <add> action: `Displayed ${ <add> isBlockDonation ? 'block' : 'progress' <add> } donation modal`, <add> nonInteraction: true <add> } <add> }); <ide> } <ide> <ide> const donationText = ( <ide> function DonateModal({ show, block, isBlockDonation, closeDonationModal }) { <ide> <Modal.Body> <ide> {isBlockDonation ? blockDonationText : progressDonationText} <ide> <Spacer /> <del> <MinimalDonateForm showCloseBtn={showCloseBtn} /> <add> <MinimalDonateForm handleProcessing={handleProcessing} /> <ide> <Spacer /> <ide> <Row> <ide> <Col sm={4} smOffset={4} xs={8} xsOffset={2}> <ide><path>client/src/components/Donation/MinimalDonateForm.js <ide> import './Donation.css'; <ide> <ide> const propTypes = { <ide> defaultTheme: PropTypes.string, <add> handleProcessing: PropTypes.func, <ide> isDonating: PropTypes.bool, <del> showCloseBtn: PropTypes.func, <ide> stripe: PropTypes.shape({ <ide> createToken: PropTypes.func.isRequired <ide> }) <ide> class MinimalDonateForm extends Component { <ide> <ide> render() { <ide> const { donationAmount, donationDuration, stripe } = this.state; <del> const { showCloseBtn, defaultTheme } = this.props; <add> const { handleProcessing, defaultTheme } = this.props; <ide> <ide> return ( <ide> <Row> <ide> class MinimalDonateForm extends Component { <ide> getDonationButtonLabel={() => <ide> `Confirm your donation of $5 per month` <ide> } <del> showCloseBtn={showCloseBtn} <add> handleProcessing={handleProcessing} <ide> /> <ide> </Elements> <ide> </StripeProvider> <ide><path>client/src/components/Map/components/Block.js <ide> import { connect } from 'react-redux'; <ide> import { createSelector } from 'reselect'; <ide> import { Link } from 'gatsby'; <ide> <del>import ga from '../../../analytics'; <ide> import { makeExpandedBlockSelector, toggleBlock } from '../redux'; <del>import { completedChallengesSelector } from '../../../redux'; <add>import { completedChallengesSelector, executeGA } from '../../../redux'; <ide> import Caret from '../../../assets/icons/Caret'; <ide> import { blockNameify } from '../../../../utils/blockNameify'; <ide> import GreenPass from '../../../assets/icons/GreenPass'; <ide> const mapStateToProps = (state, ownProps) => { <ide> }; <ide> <ide> const mapDispatchToProps = dispatch => <del> bindActionCreators({ toggleBlock }, dispatch); <add> bindActionCreators({ toggleBlock, executeGA }, dispatch); <ide> <ide> const propTypes = { <ide> blockDashedName: PropTypes.string, <ide> challenges: PropTypes.array, <ide> completedChallenges: PropTypes.arrayOf(PropTypes.string), <add> executeGA: PropTypes.func, <ide> intro: PropTypes.shape({ <ide> fields: PropTypes.shape({ slug: PropTypes.string.isRequired }), <ide> frontmatter: PropTypes.shape({ <ide> export class Block extends Component { <ide> } <ide> <ide> handleBlockClick() { <del> const { blockDashedName, toggleBlock } = this.props; <del> ga.event({ <del> category: 'Map Block Click', <del> action: blockDashedName <add> const { blockDashedName, toggleBlock, executeGA } = this.props; <add> executeGA({ <add> type: 'event', <add> data: { <add> category: 'Map Block Click', <add> action: blockDashedName <add> } <ide> }); <ide> return toggleBlock(blockDashedName); <ide> } <ide> <ide> handleChallengeClick(slug) { <ide> return () => { <del> return ga.event({ <del> category: 'Map Challenge Click', <del> action: slug <add> return this.props.executeGA({ <add> type: 'event', <add> data: { <add> category: 'Map Challenge Click', <add> action: slug <add> } <ide> }); <ide> }; <ide> } <ide><path>client/src/components/Map/components/Block.test.js <ide> test('<Block expanded snapshot', () => { <ide> test('<Block /> should handle toggle clicks correctly', async () => { <ide> const toggleSpy = jest.fn(); <ide> const toggleMapSpy = jest.fn(); <add> const executeGA = jest.fn(); <ide> <ide> const props = { <ide> blockDashedName: 'block-a', <ide> challenges: mockChallengeNodes.filter(node => node.block === 'block-a'), <ide> completedChallenges: mockCompleted, <ide> intro: mockIntroNodes[0], <ide> isExpanded: false, <add> executeGA: executeGA, <ide> toggleBlock: toggleSpy, <ide> toggleMapModal: toggleMapSpy <ide> }; <ide><path>client/src/components/YearEndGift/YearEndDonationForm.js <ide> const numToCommas = num => <ide> num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); <ide> <ide> const propTypes = { <del> showCloseBtn: PropTypes.func, <add> handleProcessing: PropTypes.func, <ide> defaultTheme: PropTypes.string, <ide> isDonating: PropTypes.bool, <add> executeGA: PropTypes.func, <ide> stripe: PropTypes.shape({ <ide> createToken: PropTypes.func.isRequired <ide> }) <ide> class YearEndDonationForm extends Component { <ide> this.handleSelectAmount = this.handleSelectAmount.bind(this); <ide> this.handleChange = this.handleChange.bind(this); <ide> this.handleClick = this.handleClick.bind(this); <add> this.handlePaypalSubmission = this.handlePaypalSubmission.bind(this); <ide> } <ide> <ide> componentDidMount() { <ide> class YearEndDonationForm extends Component { <ide> <ide> renderDonationOptions() { <ide> const { donationAmount, stripe } = this.state; <del> <del> const { showCloseBtn, defaultTheme } = this.props; <add> const { handleProcessing, defaultTheme } = this.props; <ide> return ( <ide> <div> <ide> <StripeProvider stripe={stripe}> <ide> <Elements> <ide> <DonateFormChildViewForHOC <del> showCloseBtn={showCloseBtn} <add> handleProcessing={handleProcessing} <ide> defaultTheme={defaultTheme} <ide> donationAmount={donationAmount} <ide> donationDuration='onetime' <ide> class YearEndDonationForm extends Component { <ide> ); <ide> } <ide> <add> handlePaypalSubmission() { <add> this.props.executeGA({ <add> type: 'event', <add> data: { <add> category: 'donation', <add> action: 'year end gift paypal button click' <add> } <add> }); <add> } <add> <ide> renderPayPalDonations() { <ide> return ( <ide> <form <ide> action='https://www.paypal.com/cgi-bin/webscr' <ide> method='post' <ide> target='_top' <add> onSubmit={this.handlePaypalSubmission} <ide> > <ide> <input type='hidden' name='cmd' value='_s-xclick' /> <ide> <input type='hidden' name='hosted_button_id' value='9C73W6CWSLNPW' /> <ide><path>client/src/components/layouts/Certification.js <ide> import React, { Fragment, Component } from 'react'; <ide> import PropTypes from 'prop-types'; <ide> import { connect } from 'react-redux'; <ide> <del>import ga from '../../analytics'; <del>import { fetchUser, isSignedInSelector } from '../../redux'; <add>import { fetchUser, isSignedInSelector, executeGA } from '../../redux'; <ide> import { createSelector } from 'reselect'; <ide> <ide> const mapStateToProps = createSelector( <ide> const mapStateToProps = createSelector( <ide> }) <ide> ); <ide> <del>const mapDispatchToProps = { fetchUser }; <add>const mapDispatchToProps = { fetchUser, executeGA }; <ide> <ide> class CertificationLayout extends Component { <ide> componentDidMount() { <ide> const { isSignedIn, fetchUser, pathname } = this.props; <ide> if (!isSignedIn) { <ide> fetchUser(); <ide> } <del> ga.pageview(pathname); <add> this.props.executeGA({ type: 'page', data: pathname }); <ide> } <ide> render() { <ide> return <Fragment>{this.props.children}</Fragment>; <ide> class CertificationLayout extends Component { <ide> CertificationLayout.displayName = 'CertificationLayout'; <ide> CertificationLayout.propTypes = { <ide> children: PropTypes.any, <add> executeGA: PropTypes.func, <ide> fetchUser: PropTypes.func.isRequired, <ide> isSignedIn: PropTypes.bool, <ide> pathname: PropTypes.string.isRequired <ide><path>client/src/components/layouts/Default.js <ide> import { createSelector } from 'reselect'; <ide> import Helmet from 'react-helmet'; <ide> import fontawesome from '@fortawesome/fontawesome'; <ide> <del>import ga from '../../analytics'; <ide> import { <ide> fetchUser, <ide> isSignedInSelector, <ide> onlineStatusChange, <ide> isOnlineSelector, <del> userSelector <add> userSelector, <add> executeGA <ide> } from '../../redux'; <ide> import { flashMessageSelector, removeFlashMessage } from '../Flash/redux'; <ide> <ide> const metaKeywords = [ <ide> <ide> const propTypes = { <ide> children: PropTypes.node.isRequired, <add> executeGA: PropTypes.func, <ide> fetchUser: PropTypes.func.isRequired, <ide> flashMessage: PropTypes.shape({ <ide> id: PropTypes.string, <ide> const mapStateToProps = createSelector( <ide> <ide> const mapDispatchToProps = dispatch => <ide> bindActionCreators( <del> { fetchUser, removeFlashMessage, onlineStatusChange }, <add> { fetchUser, removeFlashMessage, onlineStatusChange, executeGA }, <ide> dispatch <ide> ); <ide> <ide> class DefaultLayout extends Component { <ide> componentDidMount() { <del> const { isSignedIn, fetchUser, pathname } = this.props; <add> const { isSignedIn, fetchUser, pathname, executeGA } = this.props; <ide> if (!isSignedIn) { <ide> fetchUser(); <ide> } <del> ga.pageview(pathname); <add> executeGA({ type: 'page', data: pathname }); <ide> <ide> window.addEventListener('online', this.updateOnlineStatus); <ide> window.addEventListener('offline', this.updateOnlineStatus); <ide> } <ide> <ide> componentDidUpdate(prevProps) { <del> const { pathname } = this.props; <add> const { pathname, executeGA } = this.props; <ide> const { pathname: prevPathname } = prevProps; <ide> if (pathname !== prevPathname) { <del> ga.pageview(pathname); <add> executeGA({ type: 'page', data: pathname }); <ide> } <ide> } <ide> <ide><path>client/src/pages/donate.js <ide> import React, { Component, Fragment } from 'react'; <ide> import Helmet from 'react-helmet'; <ide> import PropTypes from 'prop-types'; <add>import { bindActionCreators } from 'redux'; <ide> import { connect } from 'react-redux'; <ide> import { createSelector } from 'reselect'; <ide> import { Grid, Row, Col } from '@freecodecamp/react-bootstrap'; <ide> import { stripePublicKey } from '../../config/env.json'; <ide> import { Spacer, Loader } from '../components/helpers'; <ide> import DonateForm from '../components/Donation/DonateForm'; <ide> import DonateText from '../components/Donation/DonateText'; <del>import { signInLoadingSelector, userSelector } from '../redux'; <add>import { signInLoadingSelector, userSelector, executeGA } from '../redux'; <ide> import { stripeScriptLoader } from '../utils/scriptLoaders'; <ide> <ide> const propTypes = { <add> executeGA: PropTypes.func, <ide> isDonating: PropTypes.bool, <ide> showLoading: PropTypes.bool.isRequired <ide> }; <ide> const mapStateToProps = createSelector( <ide> }) <ide> ); <ide> <add>const mapDispatchToProps = dispatch => <add> bindActionCreators( <add> { <add> executeGA <add> }, <add> dispatch <add> ); <add> <ide> export class DonatePage extends Component { <ide> constructor(...props) { <ide> super(...props); <ide> this.state = { <ide> stripe: null, <ide> enableSettings: false <ide> }; <del> <add> this.handleProcessing = this.handleProcessing.bind(this); <ide> this.handleStripeLoad = this.handleStripeLoad.bind(this); <ide> } <ide> <ide> componentDidMount() { <add> this.props.executeGA({ <add> type: 'event', <add> data: { <add> category: 'Donation', <add> action: `Displayed donate page`, <add> nonInteraction: true <add> } <add> }); <ide> if (window.Stripe) { <ide> this.handleStripeLoad(); <ide> } else if (document.querySelector('#stripe-js')) { <ide> export class DonatePage extends Component { <ide> } <ide> } <ide> <add> handleProcessing(duration, amount) { <add> this.props.executeGA({ <add> type: 'event', <add> data: { <add> category: 'donation', <add> action: 'donate page stripe form submission', <add> label: duration, <add> value: amount <add> } <add> }); <add> } <add> <ide> handleStripeLoad() { <ide> // Create Stripe instance once Stripe.js loads <ide> console.info('stripe has loaded'); <ide> export class DonatePage extends Component { <ide> <Col md={6}> <ide> <DonateForm <ide> enableDonationSettingsPage={this.enableDonationSettingsPage} <add> handleProcessing={this.handleProcessing} <ide> stripe={stripe} <ide> /> <ide> </Col> <ide> export class DonatePage extends Component { <ide> DonatePage.displayName = 'DonatePage'; <ide> DonatePage.propTypes = propTypes; <ide> <del>export default connect(mapStateToProps)(DonatePage); <add>export default connect( <add> mapStateToProps, <add> mapDispatchToProps <add>)(DonatePage); <ide><path>client/src/pages/year-end-gift.js <del>import React from 'react'; <add>import React, { useEffect } from 'react'; <ide> import Helmet from 'react-helmet'; <ide> import { Grid } from '@freecodecamp/react-bootstrap'; <add>import { connect } from 'react-redux'; <add>import { executeGA } from '../redux'; <add>import { bindActionCreators } from 'redux'; <add>import PropTypes from 'prop-types'; <ide> <ide> import { Spacer, FullWidthRow } from '../components/helpers'; <ide> import YearEndDonationForm from '../components/YearEndGift/YearEndDonationForm'; <ide> <del>function YearEndGiftPage() { <add>const mapDispatchToProps = dispatch => <add> bindActionCreators( <add> { <add> executeGA <add> }, <add> dispatch <add> ); <add> <add>const propTypes = { <add> executeGA: PropTypes.func <add>}; <add> <add>function YearEndGiftPage({ executeGA }) { <add> useEffect(() => { <add> executeGA({ <add> type: 'event', <add> data: { <add> category: 'Donation', <add> action: `Displayed year end gift page`, <add> nonInteraction: true <add> } <add> }); <add> }, [executeGA]); <add> const handleProcessing = (duration, amount) => { <add> executeGA({ <add> type: 'event', <add> data: { <add> category: 'donation', <add> action: 'year-end-gift strip form submission', <add> label: duration, <add> value: amount <add> } <add> }); <add> }; <ide> return ( <ide> <> <ide> <Helmet title='Support our nonprofit | freeCodeCamp.org' /> <ide> <Grid> <ide> <main> <ide> <Spacer /> <ide> <FullWidthRow> <del> <YearEndDonationForm defaultTheme='light' /> <add> <YearEndDonationForm <add> defaultTheme='light' <add> executeGA={executeGA} <add> handleProcessing={handleProcessing} <add> /> <ide> </FullWidthRow> <ide> <Spacer /> <ide> <Spacer /> <ide> function YearEndGiftPage() { <ide> } <ide> <ide> YearEndGiftPage.displayName = 'YearEndGiftPage'; <add>YearEndGiftPage.propTypes = propTypes; <ide> <del>export default YearEndGiftPage; <add>export default connect( <add> null, <add> mapDispatchToProps <add>)(YearEndGiftPage); <ide><path>client/src/redux/ga-saga.js <add>import { takeEvery } from 'redux-saga/effects'; <add>import ga from '../analytics'; <add> <add>function* callGaType({ payload: { type, data } }) { <add> const GaTypes = { event: ga.event, page: ga.pageview, modal: ga.modalview }; <add> GaTypes[type](data); <add>} <add> <add>export function createGaSaga(types) { <add> return [takeEvery(types.executeGA, callGaType)]; <add>} <ide><path>client/src/redux/index.js <ide> import { createReportUserSaga } from './report-user-saga'; <ide> import { createShowCertSaga } from './show-cert-saga'; <ide> import { createNightModeSaga } from './night-mode-saga'; <ide> import { createDonationSaga } from './donation-saga'; <add>import { createGaSaga } from './ga-saga'; <ide> <ide> import hardGoToEpic from './hard-go-to-epic'; <ide> import failedUpdatesEpic from './failed-updates-epic'; <ide> export const types = createTypes( <ide> 'onlineStatusChange', <ide> 'resetUserData', <ide> 'tryToShowDonationModal', <add> 'executeGA', <ide> 'submitComplete', <ide> 'updateComplete', <ide> 'updateCurrentChallengeId', <ide> export const sagas = [ <ide> ...createAcceptTermsSaga(types), <ide> ...createAppMountSaga(types), <ide> ...createDonationSaga(types), <add> ...createGaSaga(types), <ide> ...createFetchUserSaga(types), <ide> ...createShowCertSaga(types), <ide> ...createReportUserSaga(types), <ide> export const appMount = createAction(types.appMount); <ide> export const tryToShowDonationModal = createAction( <ide> types.tryToShowDonationModal <ide> ); <add> <add>export const executeGA = createAction(types.executeGA); <add> <ide> export const allowBlockDonationRequests = createAction( <ide> types.allowBlockDonationRequests <ide> ); <ide><path>client/src/templates/Challenges/components/CompletionModal.js <ide> import { createSelector } from 'reselect'; <ide> import { Button, Modal } from '@freecodecamp/react-bootstrap'; <ide> import { useStaticQuery, graphql } from 'gatsby'; <ide> <del>import ga from '../../../analytics'; <ide> import Login from '../../../components/Header/components/Login'; <ide> import CompletionModalBody from './CompletionModalBody'; <del> <ide> import { dasherize } from '../../../../../utils/slugs'; <ide> <ide> import './completion-modal.css'; <ide> import { <ide> lastBlockChalSubmitted <ide> } from '../redux'; <ide> <del>import { isSignedInSelector } from '../../../redux'; <add>import { isSignedInSelector, executeGA } from '../../../redux'; <ide> <ide> const mapStateToProps = createSelector( <ide> challengeFilesSelector, <ide> const mapDispatchToProps = function(dispatch) { <ide> }, <ide> lastBlockChalSubmitted: () => { <ide> dispatch(lastBlockChalSubmitted()); <del> } <add> }, <add> executeGA <ide> }; <ide> return () => dispatchers; <ide> }; <ide> const propTypes = { <ide> close: PropTypes.func.isRequired, <ide> completedChallengesIds: PropTypes.array, <ide> currentBlockIds: PropTypes.array, <add> executeGA: PropTypes.func, <ide> files: PropTypes.object.isRequired, <ide> id: PropTypes.string, <ide> isOpen: PropTypes.bool, <ide> export class CompletionModalInner extends Component { <ide> const { completedPercent } = this.state; <ide> <ide> if (isOpen) { <del> ga.modalview('/completion-modal'); <add> executeGA({ type: 'modal', data: '/completion-modal' }); <ide> } <ide> const dashedName = dasherize(title); <ide> return ( <ide><path>client/src/templates/Challenges/components/HelpModal.js <ide> import { bindActionCreators } from 'redux'; <ide> import { connect } from 'react-redux'; <ide> import { Button, Modal } from '@freecodecamp/react-bootstrap'; <ide> <del>import ga from '../../../analytics'; <ide> import { createQuestion, closeModal, isHelpModalOpenSelector } from '../redux'; <add>import { executeGA } from '../../../redux'; <ide> <ide> import './help-modal.css'; <ide> <ide> const mapStateToProps = state => ({ isOpen: isHelpModalOpenSelector(state) }); <ide> const mapDispatchToProps = dispatch => <ide> bindActionCreators( <del> { createQuestion, closeHelpModal: () => closeModal('help') }, <add> { createQuestion, executeGA, closeHelpModal: () => closeModal('help') }, <ide> dispatch <ide> ); <ide> <ide> const propTypes = { <ide> closeHelpModal: PropTypes.func.isRequired, <ide> createQuestion: PropTypes.func.isRequired, <add> executeGA: PropTypes.func, <ide> isOpen: PropTypes.bool <ide> }; <ide> <ide> const RSA = <ide> <ide> export class HelpModal extends Component { <ide> render() { <del> const { isOpen, closeHelpModal, createQuestion } = this.props; <add> const { isOpen, closeHelpModal, createQuestion, executeGA } = this.props; <ide> if (isOpen) { <del> ga.modalview('/help-modal'); <add> executeGA({ type: 'modal', data: '/help-modal' }); <ide> } <ide> return ( <ide> <Modal dialogClassName='help-modal' onHide={closeHelpModal} show={isOpen}> <ide><path>client/src/templates/Challenges/components/ResetModal.js <ide> import { connect } from 'react-redux'; <ide> import { createSelector } from 'reselect'; <ide> import { Button, Modal } from '@freecodecamp/react-bootstrap'; <ide> <del>import ga from '../../../analytics'; <ide> import { isResetModalOpenSelector, closeModal, resetChallenge } from '../redux'; <add>import { executeGA } from '../../../redux'; <ide> <ide> import './reset-modal.css'; <ide> <ide> const propTypes = { <ide> close: PropTypes.func.isRequired, <add> executeGA: PropTypes.func, <ide> isOpen: PropTypes.bool.isRequired, <ide> reset: PropTypes.func.isRequired <ide> }; <ide> const mapStateToProps = createSelector( <ide> <ide> const mapDispatchToProps = dispatch => <ide> bindActionCreators( <del> { close: () => closeModal('reset'), reset: () => resetChallenge() }, <add> { <add> close: () => closeModal('reset'), <add> executeGA, <add> reset: () => resetChallenge() <add> }, <ide> dispatch <ide> ); <ide> <ide> function withActions(...fns) { <ide> <ide> function ResetModal({ reset, close, isOpen }) { <ide> if (isOpen) { <del> ga.modalview('/reset-modal'); <add> executeGA({ type: 'modal', data: '/reset-modal' }); <ide> } <ide> return ( <ide> <Modal <ide><path>client/src/templates/Challenges/components/VideoModal.js <ide> import { bindActionCreators } from 'redux'; <ide> import { connect } from 'react-redux'; <ide> import { Modal } from '@freecodecamp/react-bootstrap'; <ide> <del>import ga from '../../../analytics'; <ide> import { closeModal, isVideoModalOpenSelector } from '../redux'; <add>import { executeGA } from '../../../redux'; <ide> <ide> import './video-modal.css'; <ide> <ide> const mapStateToProps = state => ({ isOpen: isVideoModalOpenSelector(state) }); <ide> const mapDispatchToProps = dispatch => <del> bindActionCreators({ closeVideoModal: () => closeModal('video') }, dispatch); <add> bindActionCreators( <add> { closeVideoModal: () => closeModal('video'), executeGA }, <add> dispatch <add> ); <ide> <ide> const propTypes = { <ide> closeVideoModal: PropTypes.func.isRequired, <add> executeGA: propTypes.func, <ide> isOpen: PropTypes.bool, <ide> videoUrl: PropTypes.string <ide> }; <ide> <ide> export class VideoModal extends Component { <ide> render() { <del> const { isOpen, closeVideoModal, videoUrl } = this.props; <add> const { isOpen, closeVideoModal, videoUrl, executeGA } = this.props; <ide> if (isOpen) { <del> ga.modalview('/video-modal'); <add> executeGA({ type: 'modal', data: '/completion-modal' }); <ide> } <ide> return ( <ide> <Modal
18
Javascript
Javascript
fix touch events
07cd9800e8cbd1b7822ead6b249d015650ef80c8
<ide><path>src/js/component.js <ide> vjs.Component = vjs.CoreObject.extend({ <ide> this.ready(ready); <ide> // Don't want to trigger ready here or it will before init is actually <ide> // finished for all children that run this constructor <add> <add> <add> var touchmove = false; <add> this.on('touchstart', function() { <add> touchmove = false; <add> }); <add> this.on('touchmove', vjs.bind(this, function() { <add> if (this.listenToTouchMove) { <add> this.player_.reportUserActivity(); <add> } <add> touchmove = true; <add> })); <add> this.on('touchend', vjs.bind(this, function(event) { <add> if (!touchmove && !didSomething) { <add> this.player_.reportUserActivity(); <add> } <add> })); <ide> } <ide> }); <ide> <ide><path>src/js/control-bar/control-bar.js <ide> vjs.ControlBar.prototype.options_ = { <ide> } <ide> }; <ide> <add>vjs.ControlBar.prototype.listenToTouchMove = true; <add> <ide> vjs.ControlBar.prototype.createEl = function(){ <ide> return vjs.createEl('div', { <ide> className: 'vjs-control-bar' <ide><path>src/js/control-bar/progress-control.js <ide> vjs.ProgressControl.prototype.options_ = { <ide> } <ide> }; <ide> <add>vjs.ProgressControl.prototype.listenToTouchMove = true; <add> <ide> vjs.ProgressControl.prototype.createEl = function(){ <ide> return vjs.Component.prototype.createEl.call(this, 'div', { <ide> className: 'vjs-progress-control vjs-control' <ide><path>src/js/media/media.js <ide> vjs.MediaTechController.prototype.addControlsListeners = function(){ <ide> this.on('touchstart', function(event) { <ide> // Stop the mouse events from also happening <ide> event.preventDefault(); <del> event.stopPropagation(); <del> // Record if the user was active now so we don't have to keep polling it <del> userWasActive = this.player_.userActive(); <ide> }); <ide> <del> preventBubble = function(event){ <del> event.stopPropagation(); <del> if (userWasActive) { <del> this.player_.reportUserActivity(); <del> } <del> }; <del> <del> // Treat all touch events the same for consistency <del> this.on('touchmove', preventBubble); <del> this.on('touchleave', preventBubble); <del> this.on('touchcancel', preventBubble); <del> this.on('touchend', preventBubble); <del> <ide> // Turn on component tap events <ide> this.emitTapEvents(); <ide> <ide><path>src/js/player.js <ide> vjs.Player.prototype.listenForUserActivity = function(){ <ide> this.on('keydown', onMouseActivity); <ide> this.on('keyup', onMouseActivity); <ide> <del> // Consider any touch events that bubble up to be activity <del> // Certain touches on the tech will be blocked from bubbling because they <del> // toggle controls <del> this.on('touchstart', onMouseDown); <del> this.on('touchmove', onMouseActivity); <del> this.on('touchend', onMouseUp); <del> this.on('touchcancel', onMouseUp); <del> <ide> // Run an interval every 250 milliseconds instead of stuffing everything into <ide> // the mousemove/touchmove function itself, to prevent performance degradation. <ide> // `this.reportUserActivity` simply sets this.userActivity_ to true, which <ide><path>src/js/slider.js <ide> vjs.Slider.prototype.createEl = function(type, props) { <ide> return vjs.Component.prototype.createEl.call(this, type, props); <ide> }; <ide> <add>vjs.Slider.prototype.listenToTouchMove = true; <add> <ide> vjs.Slider.prototype.onMouseDown = function(event){ <ide> event.preventDefault(); <ide> vjs.blockTextSelection(); <ide> vjs.SliderHandle.prototype.createEl = function(type, props) { <ide> <ide> return vjs.Component.prototype.createEl.call(this, 'div', props); <ide> }; <add> <add>vjs.SliderHandle.prototype.listenToTouchMove = true;
6
Python
Python
fix a typo in a comment
413735b239239bc8ff38ee893e8448daf9b2bff6
<ide><path>django/utils/http.py <ide> def urlunquote_plus(quoted_url): <ide> def urlencode(query, doseq=0): <ide> """ <ide> A version of Python's urllib.urlencode() function that can operate on <del> unicode strings. The parameters are first case to UTF-8 encoded strings and <add> unicode strings. The parameters are first cast to UTF-8 encoded strings and <ide> then encoded as per normal. <ide> """ <ide> if isinstance(query, MultiValueDict):
1
Javascript
Javascript
improve code in test-http-bind-twice.js
80f19b043dda93135d69459def5944e60518c690
<ide><path>test/parallel/test-http-bind-twice.js <ide> 'use strict'; <ide> const common = require('../common'); <del>var assert = require('assert'); <del>var http = require('http'); <add>const assert = require('assert'); <add>const http = require('http'); <ide> <del>var server1 = http.createServer(common.fail); <add>const server1 = http.createServer(common.fail); <ide> server1.listen(0, '127.0.0.1', common.mustCall(function() { <del> var server2 = http.createServer(common.fail); <add> const server2 = http.createServer(common.fail); <ide> server2.listen(this.address().port, '127.0.0.1', common.fail); <ide> <ide> server2.on('error', common.mustCall(function(e) { <del> assert.equal(e.code, 'EADDRINUSE'); <add> assert.strictEqual(e.code, 'EADDRINUSE'); <ide> server1.close(); <ide> })); <ide> }));
1
PHP
PHP
remove bad test
d4631a6eaddaf8bf8d7e24262631030efe32b7c2
<ide><path>lib/Cake/Test/Case/Cache/Engine/MemcacheEngineTest.php <ide> public function testMultipleServers() { <ide> $Memcache = new MemcacheEngine(); <ide> $Memcache->init(array('engine' => 'Memcache', 'servers' => $servers)); <ide> <del> $servers = array_keys($Memcache->__Memcache->getExtendedStats()); <ide> $settings = $Memcache->settings(); <ide> $this->assertEquals($settings['servers'], $servers); <ide> Cache::drop('dual_server');
1
Javascript
Javascript
fix asset resolver url handling
28d5d6baf1e6ac52e8672a653f56c3898e4e11d2
<ide><path>Libraries/Image/AssetSourceResolver.js <ide> class AssetSourceResolver { <ide> } <ide> <ide> isLoadedFromFileSystem(): boolean { <del> return !!this.jsbundleUrl; <add> return !!(this.jsbundleUrl && this.jsbundleUrl.startsWith('file://')); <ide> } <ide> <ide> canLoadFromEmbeddedBundledLocation(): boolean { <ide><path>Libraries/Image/resolveAssetSource.js <ide> function _coerceLocalScriptURL(scriptURL: ?string): ?string { <ide> return null; <ide> } <ide> scriptURL = scriptURL.substring(0, scriptURL.lastIndexOf('/') + 1); <del> if (!scriptURL.startsWith('file://')) { <add> if (!scriptURL.includes('://')) { <ide> // Add file protocol in case we have an absolute file path and not a URL. <ide> // This shouldn't really be necessary. scriptURL should be a URL. <ide> scriptURL = 'file://' + scriptURL;
2
Text
Text
fix some translation errors
d6706f5d06080158e79e92064ff65a3e3ae6ce8b
<ide><path>threejs/lessons/fr/threejs-materials.md <del>Title: Les Materials de Three.js <del>Description: Les Materials dans Three.js <del>TOC: Materials <add>Title: Les Matériaux dans Three.js <add>Description: Les Matériaux dans Three.js <add>TOC: Matériaux <ide> <ide> Cet article fait partie d'une série consacrée à Three.js. <ide> Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
1
Go
Go
use local random instance
25fab69f7dcf72dabfeb60f61f50f175692f0b03
<ide><path>pkg/namesgenerator/names-generator.go <ide> var ( <ide> // Ada Yonath - an Israeli crystallographer, the first woman from the Middle East to win a Nobel prize in the sciences. https://en.wikipedia.org/wiki/Ada_Yonath <ide> "yonath", <ide> } <add> <add> rnd = rand.New(rand.NewSource(time.Now().UnixNano())) <ide> ) <ide> <ide> func GetRandomName(retry int) string { <del> rand.Seed(time.Now().UnixNano()) <del> <ide> begin: <del> name := fmt.Sprintf("%s_%s", left[rand.Intn(len(left))], right[rand.Intn(len(right))]) <add> name := fmt.Sprintf("%s_%s", left[rnd.Intn(len(left))], right[rnd.Intn(len(right))]) <ide> if name == "boring_wozniak" /* Steve Wozniak is not boring */ { <ide> goto begin <ide> } <ide> <ide> if retry > 0 { <del> name = fmt.Sprintf("%s%d", name, rand.Intn(10)) <add> name = fmt.Sprintf("%s%d", name, rnd.Intn(10)) <ide> } <ide> return name <ide> }
1
Python
Python
drop u'' prefix for python 3.x compatibility
5829eb7a5b0d45fe668d7ce1ad394a7b5966c70d
<ide><path>rest_framework/tests/test_fields.py <ide> def test_choices_not_required(self): <ide> def test_invalid_choice_model(self): <ide> s = ChoiceFieldModelSerializer(data={'choice' : 'wrong_value'}) <ide> self.assertFalse(s.is_valid()) <del> self.assertEqual(s.errors, {'choice': [u'Select a valid choice. wrong_value is not one of the available choices.']}) <add> self.assertEqual(s.errors, {'choice': ['Select a valid choice. wrong_value is not one of the available choices.']}) <ide> self.assertEqual(s.data['choice'], '') <ide> <ide> def test_empty_choice_model(self):
1
Javascript
Javascript
fix kupdatetimer timer refresh
0812ebda88798e103498e78c8ae95497e0a4bad1
<ide><path>lib/internal/http2/core.js <ide> class Http2Stream extends Duplex { <ide> if (this.destroyed) <ide> return; <ide> if (this[kTimeout]) <del> _unrefActive([kTimeout]); <add> _unrefActive(this[kTimeout]); <ide> if (this[kSession]) <ide> this[kSession][kUpdateTimer](); <ide> }
1
Text
Text
fix changelog indent [ci skip]
08d9c7532c7081d6b5964b8edf802fab72224cd7
<ide><path>actionpack/CHANGELOG.md <del>* Alias the `ActionDispatch::Request#uuid` method to `ActionDispatch::Request#request_id`. <add>* Alias the `ActionDispatch::Request#uuid` method to `ActionDispatch::Request#request_id`. <ide> Due to implementation, `config.log_tags = [:request_id]` also works in substitute <ide> for `config.log_tags = [:uuid]`. <ide> <ide> <ide> * Explicitly ignored wildcard verbs when searching for HEAD routes before fallback <ide> <del> Fixes an issue where a mounted rack app at root would intercept the HEAD <add> Fixes an issue where a mounted rack app at root would intercept the HEAD <ide> request causing an incorrect behavior during the fall back to GET requests. <ide> <ide> Example:
1
Python
Python
add backfill option to not pickle the dag
727786a3a27698eb2f9154cd35e6ad57b3b72027
<ide><path>airflow/bin/cli.py <ide> def backfill(args): <ide> mark_success=args.mark_success, <ide> include_adhoc=args.include_adhoc, <ide> local=args.local, <add> donot_pickle=args.donot_pickle, <ide> ignore_dependencies=args.ignore_dependencies) <ide> <ide> <ide> def get_parser(): <ide> parser_backfill.add_argument( <ide> "-l", "--local", <ide> help="Run the task using the LocalExecutor", action="store_true") <add> parser_backfill.add_argument( <add> "-x", "--donot_pickle", <add> help=( <add> "Do not attempt to pickle the DAG object to send over " <add> "to the workers, just tell the workers to run their version " <add> "of the code."), <add> action="store_true") <ide> parser_backfill.add_argument( <ide> "-a", "--include_adhoc", <ide> help="Include dags with the adhoc parameter.", action="store_true")
1
Text
Text
fix headings for changelog_v10.md
db2ac1dbd94cd8a7628ddd609c5238aa2ad3d52e
<ide><path>doc/changelogs/CHANGELOG_V10.md <ide> <ide> <table> <ide> <tr> <del><th>Current</th> <add><th>LTS 'Dubnium'</th> <add><th title="Previously called 'Stable'">Current</th> <ide> </tr> <ide> <tr> <del><td> <add><td valign="top"> <ide> <a href="#10.13.0">10.13.0</a><br/> <add></td> <add><td valign="top"> <ide> <a href="#10.12.0">10.12.0</a><br/> <ide> <a href="#10.11.0">10.11.0</a><br/> <ide> <a href="#10.10.0">10.10.0</a><br/>
1
Text
Text
note synchronous part of child_process.spawn
25e5ae41688676a5fd29b2e2e7602168eee4ceb5
<ide><path>doc/api/child_process.md <ide> child registers an event handler for the [`'disconnect'`][] event <ide> or the [`'message'`][] event. This allows the child to exit <ide> normally without the process being held open by the open IPC channel.* <ide> <add>On UNIX-like operating systems, the [`child_process.spawn()`][] method <add>performs memory operations synchronously before decoupling the event loop <add>from the child. Applications with a large memory footprint may find frequent <add>[`child_process.spawn()`][] calls to be a bottleneck. For more information, <add>see [V8 issue 7381](https://bugs.chromium.org/p/v8/issues/detail?id=7381). <add> <ide> See also: [`child_process.exec()`][] and [`child_process.fork()`][]. <ide> <ide> ## Synchronous Process Creation
1
Text
Text
add french translation
bf72b7a71c8578206217c150abb6973afbffd97c
<ide><path>threejs/lessons/fr/threejs-scenegraph.md <ide> Cet article fait partie d'une série consacrée à Three.js. <ide> Le premier article s'intitule [Principes de base](threejs-fundamentals.html). <ide> Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là. <ide> <del>Le coeurs de Three.js est sans aucun doute son objet scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local. <add>Le coeurs de Three.js est sans aucun doute son graphique de scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local. <ide> <ide> <img src="resources/images/scenegraph-generic.svg" align="center"> <ide> <ide> objects.push(earthMesh); <ide> +moonOrbit.add(moonMesh); <ide> +objects.push(moonMesh); <ide> ``` <del>XXXXXXXXXXXXXXXX <ide> <del> <del>Again we added more invisible scene graph nodes. The first, an `Object3D` called `earthOrbit` <del>and added both the `earthMesh` and the `moonOrbit` to it, also new. We then added the `moonMesh` <del>to the `moonOrbit`. The new scene graph looks like this. <add>Ajoutons à nouveau d'autres noeuds à notre scène. D'abord, un `Object3D` appelé `earthOrbit` <add>ensuite ajoutons-lui un `earthMesh` et un `moonOrbit`. Finalement, ajoutons un `moonMesh` <add>au `moonOrbit`. Notre scène devrait ressembler à ceci : <ide> <ide> <img src="resources/images/scenegraph-sun-earth-moon.svg" align="center"> <ide> <del>and here's that <add>et à ça : <ide> <ide> {{{example url="../threejs-scenegraph-sun-earth-moon.html" }}} <ide> <del>You can see the moon follows the spirograph pattern shown at the top <del>of this article but we didn't have to manually compute it. We just <del>setup our scene graph to do it for us. <add>Vous pouvez voir que la lune suit le modèle de spirographe indiqué en haut de cet article, mais nous n'avons pas eu à le calculer manuellement. Nous venons de configurer notre graphe de scène pour le faire pour nous. <ide> <del>It is often useful to draw something to visualize the nodes in the scene graph. <del>Three.js has some helpful ummmm, helpers to ummm, ... help with this. <add>Il est souvent utile de dessiner quelque chose pour visualiser les nœuds dans le graphe de scène. <add>Three.js dispose pour cela de Helpers. <ide> <del>One is called an `AxesHelper`. It draws 3 lines representing the local <add>L'un d'entre eux s'appelle `AxesHelper`. Il dessine trois lignes représentant les axes <ide> <span style="color:red">X</span>, <del><span style="color:green">Y</span>, and <del><span style="color:blue">Z</span> axes. Let's add one to every node we <del>created. <add><span style="color:green">Y</span>, et <add><span style="color:blue">Z</span>. Ajoutons-en un à chacun de nos noeuds. <ide> <ide> ```js <ide> // add an AxesHelper to each node <ide> objects.forEach((node) => { <ide> }); <ide> ``` <ide> <del>On our case we want the axes to appear even though they are inside the spheres. <del>To do this we set their material's `depthTest` to false which means they will <del>not check to see if they are drawing behind something else. We also <del>set their `renderOrder` to 1 (the default is 0) so that they get drawn after <del>all the spheres. Otherwise a sphere might draw over them and cover them up. <add>Dans notre cas, nous voulons que les axes apparaissent même s'ils sont à l'intérieur des sphères. <add>Pour cela, nous définissons le `depthTest` de material à false, pour ne pas vérifier s'ils dessinent derrière quelque chose. Nous définissons également leur `renderOrder` sur 1 (la valeur par défaut est 0) afin qu'ils soient dessinés après toutes les sphères. Sinon, une sphère pourrait les recouvrir et les recouvrir. <ide> <ide> {{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}} <ide> <del>We can see the <del><span style="color:red">x (red)</span> and <del><span style="color:blue">z (blue)</span> axes. Since we are looking <del>straight down and each of our objects is only rotating around its <del>y axis we don't see much of the <span style="color:green">y (green)</span> axes. <add>Vous pouvez voir les axes <add><span style="color:red">x (rouge)</span> et <add><span style="color:blue">z (bleu)</span>. Comme nous regardons vers le bas et que chacun de nos objets tourne autour de son axe y, nous ne voyons pas bien l'axe <span style="color:green">y (verte)</span>. <ide> <del>It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh` <del>and the `solarSystem` are at the same position. Similarly the `earthMesh` and <del>`earthOrbit` are at the same position. Let's add some simple controls to allow us <del>to turn them on/off for each node. <del>While we're at it let's also add another helper called the `GridHelper`. It <del>makes a 2D grid on the X,Z plane. By default the grid is 10x10 units. <add>Il peut être difficile de voir certains d'entre eux car il y a 2 paires d'axes qui se chevauchent. Le `sunMesh` et le `solarSystem` sont tous les deux à la même position. De même, `earthMesh` et `earthOrbit` sont à la même position. Ajoutons quelques contrôles simples pour nous permettre de les activer/désactiver pour chaque nœud. Pendant que nous y sommes, ajoutons également un autre assistant appelé `GridHelper`. Il crée une grille 2D sur le plan X,Z. Par défaut, la grille est de 10x10 unités. <ide> <del>We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is <del>a UI library that is very popular with three.js projects. dat.GUI takes an <del>object and a property name on that object and based on the type of the property <del>automatically makes a UI to manipulate that property. <add>Nous allons également utiliser [dat.GUI](https://github.com/dataarts/dat.gui), une librairie d'interface utilisateur très populaire pour les projets Three.js. dat.GUI prend un objet et un nom de propriété sur cet objet et, en fonction du type de la propriété, crée automatiquement une interface utilisateur pour manipuler cette propriété. <ide> <del>We want to make both a `GridHelper` and an `AxesHelper` for each node. We need <del>a label for each node so we'll get rid of the old loop and switch to calling <del>some function to add the helpers for each node <add>Nous voulons créer à la fois un `GridHelper` et un `AxesHelper` pour chaque nœud. Nous avons besoin d'un label pour chaque nœud, nous allons donc nous débarrasser de l'ancienne boucle et faire appel à une fonction pour ajouter les helpers pour chaque nœud. <ide> <ide> ```js <ide> -// add an AxesHelper to each node <ide> some function to add the helpers for each node <ide> +makeAxisGrid(moonOrbit, 'moonOrbit'); <ide> +makeAxisGrid(moonMesh, 'moonMesh'); <ide> ``` <del> <del>`makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create <del>to make dat.GUI happy. Like it says above dat.GUI <del>will automagically make a UI that manipulates the named property <del>of some object. It will create a different UI depending on the type <del>of property. We want it to create a checkbox so we need to specify <del>a `bool` property. But, we want both the axes and the grid <del>to appear/disappear based on a single property so we'll make a class <del>that has a getter and setter for a property. That way we can let dat.GUI <del>think it's manipulating a single property but internally we can set <del>the visible property of both the `AxesHelper` and `GridHelper` for a node. <add>`makeAxisGrid` crée un `AxisGridHelper` qui est une classe que nous allons créer pour rendre dat.GUI heureux. Comme il est dit ci-dessus, dat.GUI créera automatiquement une interface utilisateur qui manipule la propriété nommée d'un objet. Cela créera une interface utilisateur différente selon le type de propriété. Nous voulons qu'il crée une case à cocher, nous devons donc spécifier une propriété bool. Mais, nous voulons que les axes et la grille apparaissent/disparaissent en fonction d'une seule propriété, nous allons donc créer une classe qui a un getter et un setter pour une propriété. De cette façon, nous pouvons laisser dat.GUI penser qu'il manipule une seule propriété, mais en interne, nous pouvons définir la propriété visible de `AxesHelper` et `GridHelper` pour un nœud. <ide> <ide> ```js <del>// Turns both axes and grid visible on/off <del>// dat.GUI requires a property that returns a bool <del>// to decide to make a checkbox so we make a setter <del>// and getter for `visible` which we can tell dat.GUI <del>// to look at. <add>// Activer/désactiver les axes et la grille dat.GUI <add>// nécessite une propriété qui renvoie un bool <add>// pour décider de faire une case à cocher <add>// afin que nous créions un setter et un getter pour `visible` <add>// que nous pouvons dire à dat.GUI de regarder. <ide> class AxisGridHelper { <ide> constructor(node, units = 10) { <ide> const axes = new THREE.AxesHelper(); <ide> class AxisGridHelper { <ide> } <ide> ``` <ide> <del>One thing to notice is we set the `renderOrder` of the `AxesHelper` <del>to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid. <del>Otherwise the grid might overwrite the axes. <add>Une chose à noter est que nous définissons le `renderOrder` de l'`AxesHelper` sur 2 et pour le `GridHelper` sur 1 afin que les axes soient dessinés après la grille. Sinon, la grille pourrait écraser les axes. <ide> <ide> {{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}} <ide> <del>Turn on the `solarSystem` and you'll see how the earth is exactly 10 <del>units out from the center just like we set above. You can see how the <del>earth is in the *local space* of the `solarSystem`. Similarly if you <del>turn on the `earthOrbit` you'll see how the moon is exactly 2 units <del>from the center of the *local space* of the `earthOrbit`. <add>Cliquez sur `solarSystem` et vous verrez que la terre est exactement à 10 unités du centre, comme nous l'avons défini ci-dessus. Vous pouvez voir que la terre est dans l'espace local du `solarSystem`. De même, si vous cliquez sur `earthOrbit`, vous verrez que la lune est exactement à 2 unités du centre de *l'espace local* de `earthOrbit`. <ide> <del>A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this <add>Un autre exemple de scène. Une automobile dans un jeu simple pourrait avoir un graphique de scène comme celui-ci <ide> <ide> <img src="resources/images/scenegraph-car.svg" align="center"> <ide> <del>If you move the car's body all the wheels will move with it. If you wanted the body <del>to bounce separate from the wheels you might parent the body and the wheels to a "frame" node <del>that represents the car's frame. <add>Si vous déplacez la carrosserie de la voiture, toutes les roues bougeront avec elle. Si vous vouliez que le corps rebondisse séparément des roues, vous pouvez lier le corps et les roues à un nœud "cadre" qui représente le cadre de la voiture. <ide> <del>Another example is a human in a game world. <add>Un autre exemple avec un humain dans un jeu vidéo. <ide> <ide> <img src="resources/images/scenegraph-human.svg" align="center"> <ide> <del>You can see the scene graph gets pretty complex for a human. In fact <del>that scene graph above is simplified. For example you might extend it <del>to cover every finger (at least another 28 nodes) and every toe <del>(yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more. <add>Vous pouvez voir que le graphique de la scène devient assez complexe pour un humain. En fait, le graphe ci-dessus est simplifié. Par exemple, vous pouvez l'étendre pour couvrir chaque doigt (au moins 28 autres nœuds) et chaque orteil (encore 28 nœuds) plus ceux pour le visage et la mâchoire, les yeux et peut-être plus. <add> <add>Faisons un graphe semi-complexe. On va faire un char. Il aura 6 roues et une tourelle. Il pourra suivre un chemin. Il y aura une sphère qui se déplacera et le char ciblera la sphère. <ide> <ide> Let's make one semi-complex scene graph. We'll make a tank. The tank will have <ide> 6 wheels and a turret. The tank will follow a path. There will be a sphere that <ide> moves around and the tank will target the sphere. <ide> <del>Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue, <del>the lights in gold, and the cameras in purple. One camera has not been added <del>to the scene graph. <add>Voici le graphique de la scène. Les maillages sont colorés en vert, les `Object3D` en bleu, les lumières en or et les caméras en violet. Une caméra n'a pas été ajoutée au graphique de la scène. <ide> <ide> <div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div> <ide> <del>Look in the code to see the setup of all of these nodes. <add>Regardez dans le code pour voir la configuration de tous ces nœuds. <ide> <del>For the target, the thing the tank is aiming at, there is a `targetOrbit` <del>(`Object3D`) which just rotates similar to the `earthOrbit` above. A <del>`targetElevation` (`Object3D`) which is a child of the `targetOrbit` provides an <del>offset from the `targetOrbit` and a base elevation. Childed to that is another <del>`Object3D` called `targetBob` which just bobs up and down relative to the <del>`targetElevation`. Finally there's the `targetMesh` which is just a cube we <del>rotate and change its colors <add>Pour la cible, la chose que le char vise, il y a une `targetOrbit` (Object3D) qui tourne juste de la même manière que la `earthOrbit` ci-dessus. Une `targetElevation` (Object3D) qui est un enfant de `targetOrbit` fournit un décalage par rapport à `targetOrbit` et une élévation de base. Un autre `Object3D` appelé `targetBob` qui monte et descend par rapport à la `targetElevation`. Enfin, il y a le `targetMesh` qui est juste un cube que nous faisons pivoter et changeons ses couleurs. <ide> <ide> ```js <del>// move target <add>// mettre en mouvement la cible <ide> targetOrbit.rotation.y = time * .27; <ide> targetBob.position.y = Math.sin(time * 2) * 4; <ide> targetMesh.rotation.x = time * 7; <ide> targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25); <ide> targetMaterial.color.setHSL(time * 10 % 1, 1, .25); <ide> ``` <ide> <del>For the tank there's an `Object3D` called `tank` which is used to move everything <del>below it around. The code uses a `SplineCurve` which it can ask for positions <del>along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It <del>asks for the current position where it puts the tank. It then asks for a <del>position slightly further down the curve and uses that to point the tank in that <del>direction using `Object3D.lookAt`. <add>Pour le char, il y a un `Object3D` appelé `tank` qui est utilisé pour déplacer tout ce qui se trouve en dessous. Le code utilise une `SplineCurve` à laquelle il peut demander des positions le long de cette courbe. 0.0 est le début de la courbe. 1,0 est la fin de la courbe. Il demande la position actuelle où il met le réservoir. Il demande ensuite une position légèrement plus bas dans la courbe et l'utilise pour pointer le réservoir dans cette direction à l'aide de `Object3D.lookAt`. <ide> <ide> ```js <ide> const tankPosition = new THREE.Vector2(); <ide> const tankTarget = new THREE.Vector2(); <ide> <ide> ... <ide> <del>// move tank <add>// mettre en mouvement le char <ide> const tankTime = time * .05; <ide> curve.getPointAt(tankTime % 1, tankPosition); <ide> curve.getPointAt((tankTime + 0.01) % 1, tankTarget); <ide> tank.position.set(tankPosition.x, 0, tankPosition.y); <ide> tank.lookAt(tankTarget.x, 0, tankTarget.y); <ide> ``` <ide> <del>The turret on top of the tank is moved automatically by being a child <del>of the tank. To point it at the target we just ask for the target's world position <del>and then again use `Object3D.lookAt` <add>La tourelle sur le dessus du char est déplacée automatiquement en tant qu'enfant du char. Pour le pointer sur la cible, nous demandons simplement la position de la cible, puis utilisons à nouveau `Object3D.lookAt`. <ide> <ide> ```js <ide> const targetPosition = new THREE.Vector3(); <ide> <ide> ... <ide> <del>// face turret at target <add>// tourelle face à la cible <ide> targetMesh.getWorldPosition(targetPosition); <ide> turretPivot.lookAt(targetPosition); <ide> ``` <del> <del>There's a `turretCamera` which is a child of the `turretMesh` so <del>it will move up and down and rotate with the turret. We make that <del>aim at the target. <add>Il y a une `tourretCamera` qui est un enfant de `turretMesh` donc il se déplacera de haut en bas et tournera avec la tourelle. On la fait viser la cible. <ide> <ide> ```js <del>// make the turretCamera look at target <add>// la turretCamera regarde la cible <ide> turretCamera.lookAt(targetPosition); <ide> ``` <del> <del>There is also a `targetCameraPivot` which is a child of `targetBob` so it floats <del>around with the target. We aim that back at the tank. Its purpose is to allow the <del>`targetCamera` to be offset from the target itself. If we instead made the camera <del>a child of `targetBob` and just aimed the camera itself it would be inside the <del>target. <add>Il y a aussi un `targetCameraPivot` qui est un enfant de `targetBob` donc il flotte <add>autour de la cible. Nous le pointons vers le char. Son but est de permettre à la <add>`targetCamera` d'être décalé par rapport à la cible elle-même. Si nous faisions de la caméra <add>un enfant de `targetBob`, elle serait à l'intérieur de la cible. <ide> <ide> ```js <del>// make the targetCameraPivot look at the tank <add>// faire en sorte que la cibleCameraPivot regarde le char <ide> tank.getWorldPosition(targetPosition); <ide> targetCameraPivot.lookAt(targetPosition); <ide> ``` <ide> <del>Finally we rotate all the wheels <add>Enfin on fait tourner toutes les roues <ide> <ide> ```js <ide> wheelMeshes.forEach((obj) => { <ide> obj.rotation.x = time * 3; <ide> }); <ide> ``` <ide> <del>For the cameras we setup an array of all 4 cameras at init time with descriptions. <add>Pour les caméras, nous avons configuré un ensemble de 4 caméras au moment de l'initialisation avec des descriptions. <ide> <ide> ```js <ide> const cameras = [ <ide> const cameras = [ <ide> const infoElem = document.querySelector('#info'); <ide> ``` <ide> <del>and cycle through our cameras at render time. <add>et nous parcourons chaque camera au moment du rendu <ide> <ide> ```js <ide> const camera = cameras[time * .25 % cameras.length | 0]; <ide> infoElem.textContent = camera.desc; <ide> <ide> {{{example url="../threejs-scenegraph-tank.html"}}} <ide> <del>I hope this gives some idea of how scene graphs work and how you might use them. <del>Making `Object3D` nodes and parenting things to them is an important step to using <del>a 3D engine like three.js well. Often it might seem like some complex math is necessary <del>to make something move and rotate the way you want. For example without a scene graph <del>computing the motion of the moon or where to put the wheels of the car relative to its <del>body would be very complicated but using a scene graph it becomes much easier. <add>J'espère que cela donne une idée du fonctionnement des graphiques de scène et de la façon dont vous pouvez les utiliser. <add>Faire des nœuds « Object3D » et leur attacher des choses est une étape importante pour utiliser <add>un moteur 3D comme Three.js bien. Souvent, on pourrait penser que des mathématiques complexes soient nécessaires <add>pour faire bouger quelque chose et faire pivoter comme vous le souhaitez. Par exemple sans graphique de scène <add>calculer le mouvement de la lune, savoir où placer les roues de la voiture par rapport à son <add>corps serait très compliqué, mais en utilisant un graphique de scène, cela devient beaucoup plus facile. <ide> <del>[Next up we'll go over materials](threejs-materials.html). <add>[Passons maintenant en revue les materials](threejs-materials.html).
1
Javascript
Javascript
handle certificate challenges separately
2c78402837c501a131a9cc61000127e8255cc996
<ide><path>tools/challenge-md-parser/translation-parser/translation-parser.js <ide> exports.mergeChallenges = (engChal, transChal) => { <ide> title: ${engChal.title} <ide> localeTitle: ${transChal.localeTitle}` <ide> ); <del> const translatedTests = transChal.tests.map(({ text }, id) => ({ <del> text, <del> testString: engChal.tests[id].testString <del> })); <del> return { <add> <add> const translatedTests = <add> engChal.challengeType === 7 <add> ? transChal.tests.map(({ title }, i) => ({ <add> title, <add> id: engChal.tests[i].id <add> })) <add> : transChal.tests.map(({ text }, i) => ({ <add> text, <add> testString: engChal.tests[i].testString <add> })); <add> const challenge = { <ide> ...engChal, <ide> description: transChal.description, <ide> instructions: transChal.instructions, <ide> localeTitle: transChal.localeTitle, <ide> forumTopicId: transChal.forumTopicId, <ide> tests: translatedTests <ide> }; <add> // certificates do not have forumTopicIds <add> if (challenge.challengeType === 7) delete challenge.forumTopicId; <add> return challenge; <ide> }; <ide> <ide> // bare urls could be interpreted as comments, so we have to lookbehind for
1
Text
Text
fix typo in releases.md
c91e0ed3ad048deba9639e35570e5b6dcd7b7d39
<ide><path>doc/releases.md <ide> official release builds for Node.js, hosted on <https://nodejs.org/>. <ide> ## Who can make a release? <ide> <ide> Release authorization is given by the Node.js TSC. Once authorized, an <del>individual must be have the following: <add>individual must have the following: <ide> <ide> ### 1. Jenkins Release Access <ide>
1
Python
Python
move std, var, mean calls out of try block
08fb5807118423e314f324b9bcafdbaab9316f4d
<ide><path>numpy/core/fromnumeric.py <ide> def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue): <ide> if type(a) is not mu.ndarray: <ide> try: <ide> mean = a.mean <del> return mean(axis=axis, dtype=dtype, out=out, **kwargs) <ide> except AttributeError: <ide> pass <add> else: <add> return mean(axis=axis, dtype=dtype, out=out, **kwargs) <ide> <ide> return _methods._mean(a, axis=axis, dtype=dtype, <del> out=out, **kwargs) <add> out=out, **kwargs) <ide> <ide> <ide> def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): <ide> def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): <ide> if type(a) is not mu.ndarray: <ide> try: <ide> std = a.std <del> return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs) <ide> except AttributeError: <ide> pass <add> else: <add> return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs) <ide> <ide> return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof, <del> **kwargs) <add> **kwargs) <ide> <ide> <ide> def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): <ide> def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): <ide> if type(a) is not mu.ndarray: <ide> try: <ide> var = a.var <del> return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs) <add> <ide> except AttributeError: <ide> pass <add> else: <add> return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs) <ide> <ide> return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, <ide> **kwargs)
1