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
|
---|---|---|---|---|---|
Ruby | Ruby | implement x11requirement for linux | 804393efc466e72ea07b3e38b09d39a5a64d1b78 | <ide><path>Library/Homebrew/extend/os/mac/requirements/x11_requirement.rb
<add>require "requirement"
<add>
<add>class XQuartzRequirement < Requirement
<add> include Comparable
<add>
<add> fatal true
<add> cask "xquartz"
<add> download "https://xquartz.macosforge.org"
<add>
<add> env { ENV.x11 }
<add>
<add> def initialize(name = "x11", tags = [])
<add> @name = name
<add> # no-op on version specified as a tag argument
<add> tags.shift if /(\d\.)+\d/ =~ tags.first
<add> super(tags)
<add> end
<add>
<add> def min_version
<add> MacOS::XQuartz.minimum_version
<add> end
<add>
<add> satisfy build_env: false do
<add> next false unless MacOS::XQuartz.installed?
<add> min_version <= MacOS::XQuartz.version
<add> end
<add>
<add> def message
<add> "XQuartz #{min_version} (or newer) is required to install this formula. #{super}"
<add> end
<add>
<add> def <=>(other)
<add> return unless other.is_a? X11Requirement
<add> 0
<add> end
<add>
<add> def inspect
<add> "#<#{self.class.name}: #{name.inspect} #{tags.inspect}>"
<add> end
<add>end
<add>
<add>X11Requirement = XQuartzRequirement
<ide><path>Library/Homebrew/extend/os/requirements/x11_requirement.rb
<add>require "extend/os/mac/requirements/x11_requirement" if OS.mac?
<ide><path>Library/Homebrew/requirements/x11_requirement.rb
<ide> class X11Requirement < Requirement
<ide> include Comparable
<ide>
<ide> fatal true
<del> cask "xquartz"
<del> download "https://xquartz.macosforge.org"
<ide>
<ide> env { ENV.x11 }
<ide>
<ide> def initialize(name = "x11", tags = [])
<ide> end
<ide>
<ide> def min_version
<del> # TODO: remove in https://github.com/Homebrew/brew/pull/3483
<del> return Version::NULL unless OS.mac?
<add> "1.12.2"
<add> end
<ide>
<del> MacOS::XQuartz.minimum_version
<add> def min_xdpyinfo_version
<add> "1.3.0"
<ide> end
<ide>
<ide> satisfy build_env: false do
<del> # TODO: remove in https://github.com/Homebrew/brew/pull/3483
<del> next false unless OS.mac?
<del>
<del> next false unless MacOS::XQuartz.installed?
<del> min_version <= MacOS::XQuartz.version
<add> if which_xorg = which("Xorg")
<add> version = Utils.popen_read which_xorg, "-version", err: :out
<add> next false unless $CHILD_STATUS.success?
<add> version = version[/X Server (\d+\.\d+\.\d+)/, 1]
<add> next false unless version
<add> Version.new(version) >= min_version
<add> elsif which_xdpyinfo = which("xdpyinfo")
<add> version = Utils.popen_read which_xdpyinfo, "-version"
<add> next false unless $CHILD_STATUS.success?
<add> version = version[/^xdpyinfo (\d+\.\d+\.\d+)/, 1]
<add> next false unless version
<add> Version.new(version) >= min_xdpyinfo_version
<add> else
<add> false
<add> end
<ide> end
<ide>
<ide> def message
<del> s = "XQuartz #{min_version} (or newer) is required to install this formula."
<del> s += super
<del> s
<add> "X11 is required to install this formula, either Xorg #{min_version} or xdpyinfo #{min_xdpyinfo_version}, or newer. #{super}"
<ide> end
<ide>
<ide> def <=>(other)
<ide> def inspect
<ide> "#<#{self.class.name}: #{name.inspect} #{tags.inspect}>"
<ide> end
<ide> end
<add>
<add>require "extend/os/requirements/x11_requirement" | 3 |
Ruby | Ruby | add inline patch checks to patches cop | afb844538048055d3a5ce42ce051a21fb3ff8cf2 | <ide><path>Library/Homebrew/rubocops/patches.rb
<ide> module Cop
<ide> module FormulaAudit
<ide> # This cop audits patches in Formulae.
<ide> class Patches < FormulaCop
<del> def audit_formula(_node, _class_node, _parent_class_node, body)
<add> def audit_formula(node, _class_node, _parent_class_node, body)
<add> @full_source_content = source_buffer(node).source
<add>
<ide> external_patches = find_all_blocks(body, :patch)
<ide> external_patches.each do |patch_block|
<ide> url_node = find_every_method_call_by_name(patch_block, :url).first
<ide> url_string = parameters(url_node).first
<ide> patch_problems(url_string)
<ide> end
<ide>
<add> inline_patches = find_method_calls_by_name(body, :patch)
<add> inline_patches.each { |patch| inline_patch_problems(patch) }
<add>
<add> if inline_patches.empty? && patch_end?
<add> offending_patch_end_node(node)
<add> problem "patch is missing 'DATA'"
<add> end
<add>
<ide> patches_node = find_method_def(body, :patches)
<ide> return if patches_node.nil?
<ide>
<ide> def patch_problems(patch)
<ide> #{patch_url}
<ide> EOS
<ide> end
<add>
<add> def inline_patch_problems(patch)
<add> return unless patch_data?(patch) && !patch_end?
<add>
<add> offending_node(patch)
<add> problem "patch is missing '__END__'"
<add> end
<add>
<add> def_node_search :patch_data?, <<~AST
<add> (send nil? :patch (:sym :DATA))
<add> AST
<add>
<add> def patch_end?
<add> /^__END__$/.match?(@full_source_content)
<add> end
<add>
<add> def offending_patch_end_node(node)
<add> @offensive_node = node
<add> @source_buf = source_buffer(node)
<add> @line_no = node.loc.last_line + 1
<add> @column = 0
<add> @length = 7 # "__END__".size
<add> @offense_source_range = source_range(@source_buf, @line_no, @column, @length)
<add> end
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | add server integration tests for new context | c040bcbea8e4393fbab549cc195162ac183625ed | <add><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationLegacyContext-test.js
<del><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationContext-test.js
<ide> describe('ReactDOMServerIntegration', () => {
<ide> resetModules();
<ide> });
<ide>
<del> describe('context', function() {
<add> describe('legacy context', function() {
<ide> let PurpleContext, RedContext;
<ide> beforeEach(() => {
<ide> class Parent extends React.Component {
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationNewContext-test.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>'use strict';
<add>
<add>const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');
<add>
<add>let React;
<add>let ReactDOM;
<add>let ReactDOMServer;
<add>
<add>function initModules() {
<add> // Reset warning cache.
<add> jest.resetModuleRegistry();
<add> React = require('react');
<add> ReactDOM = require('react-dom');
<add> ReactDOMServer = require('react-dom/server');
<add>
<add> // Make them available to the helpers.
<add> return {
<add> ReactDOM,
<add> ReactDOMServer,
<add> };
<add>}
<add>
<add>const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules);
<add>
<add>describe('ReactDOMServerIntegration', () => {
<add> beforeEach(() => {
<add> resetModules();
<add> });
<add>
<add> describe('context', function() {
<add> let PurpleContext, RedContext, Consumer;
<add> beforeEach(() => {
<add> let Context = React.createContext('none');
<add>
<add> class Parent extends React.Component {
<add> render() {
<add> return (
<add> <Context.Provider value={this.props.text}>
<add> {this.props.children}
<add> </Context.Provider>
<add> );
<add> }
<add> }
<add> Consumer = Context.Consumer;
<add> PurpleContext = props => <Parent text="purple">{props.children}</Parent>;
<add> RedContext = props => <Parent text="red">{props.children}</Parent>;
<add> });
<add>
<add> itRenders('class child with context', async render => {
<add> class ClassChildWithContext extends React.Component {
<add> render() {
<add> return (
<add> <div>
<add> <Consumer>{text => text}</Consumer>
<add> </div>
<add> );
<add> }
<add> }
<add>
<add> const e = await render(
<add> <PurpleContext>
<add> <ClassChildWithContext />
<add> </PurpleContext>,
<add> );
<add> expect(e.textContent).toBe('purple');
<add> });
<add>
<add> itRenders('stateless child with context', async render => {
<add> function StatelessChildWithContext(props) {
<add> return <Consumer>{text => text}</Consumer>;
<add> }
<add>
<add> const e = await render(
<add> <PurpleContext>
<add> <StatelessChildWithContext />
<add> </PurpleContext>,
<add> );
<add> expect(e.textContent).toBe('purple');
<add> });
<add>
<add> itRenders('class child with default context', async render => {
<add> class ClassChildWithWrongContext extends React.Component {
<add> render() {
<add> return (
<add> <div id="classWrongChild">
<add> <Consumer>{text => text}</Consumer>
<add> </div>
<add> );
<add> }
<add> }
<add>
<add> const e = await render(<ClassChildWithWrongContext />);
<add> expect(e.textContent).toBe('none');
<add> });
<add>
<add> itRenders('stateless child with wrong context', async render => {
<add> function StatelessChildWithWrongContext(props) {
<add> return (
<add> <div id="statelessWrongChild">
<add> <Consumer>{text => text}</Consumer>
<add> </div>
<add> );
<add> }
<add>
<add> const e = await render(<StatelessChildWithWrongContext />);
<add> expect(e.textContent).toBe('none');
<add> });
<add>
<add> itRenders('with context passed through to a grandchild', async render => {
<add> function Grandchild(props) {
<add> return (
<add> <div>
<add> <Consumer>{text => text}</Consumer>
<add> </div>
<add> );
<add> }
<add>
<add> const Child = props => <Grandchild />;
<add>
<add> const e = await render(
<add> <PurpleContext>
<add> <Child />
<add> </PurpleContext>,
<add> );
<add> expect(e.textContent).toBe('purple');
<add> });
<add>
<add> itRenders('a child context overriding a parent context', async render => {
<add> const Grandchild = props => {
<add> return (
<add> <div>
<add> <Consumer>{text => text}</Consumer>
<add> </div>
<add> );
<add> };
<add>
<add> const e = await render(
<add> <PurpleContext>
<add> <RedContext>
<add> <Grandchild />
<add> </RedContext>
<add> </PurpleContext>,
<add> );
<add> expect(e.textContent).toBe('red');
<add> });
<add>
<add> itRenders('multiple contexts', async render => {
<add> const Theme = React.createContext('dark');
<add> const Language = React.createContext('french');
<add> class Parent extends React.Component {
<add> render() {
<add> return (
<add> <Theme.Provider value="light">
<add> <Child />
<add> </Theme.Provider>
<add> );
<add> }
<add> }
<add>
<add> function Child() {
<add> return (
<add> <Language.Provider value="english">
<add> <Grandchild />
<add> </Language.Provider>
<add> );
<add> }
<add>
<add> const Grandchild = props => {
<add> return (
<add> <div>
<add> <Theme.Consumer>
<add> {theme => <div id="theme">{theme}</div>}
<add> </Theme.Consumer>
<add> <Language.Consumer>
<add> {language => <div id="language">{language}</div>}
<add> </Language.Consumer>
<add> </div>
<add> );
<add> };
<add>
<add> const e = await render(<Parent />);
<add> expect(e.querySelector('#theme').textContent).toBe('light');
<add> expect(e.querySelector('#language').textContent).toBe('english');
<add> });
<add> });
<add>}); | 2 |
Javascript | Javascript | add more tests for error boundaries | bd3c90ac6f9b601e0c0b53ae38b0e8d4bbc5ac03 | <ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactErrorBoundaries-test.js
<ide> describe('ReactErrorBoundaries', () => {
<ide> var BrokenComponentWillUnmount;
<ide> var BrokenRenderErrorBoundary;
<ide> var BrokenComponentWillMountErrorBoundary;
<add> var BrokenComponentDidMountErrorBoundary;
<ide> var BrokenRender;
<ide> var ErrorBoundary;
<ide> var ErrorMessage;
<ide> describe('ReactErrorBoundaries', () => {
<ide> }
<ide> };
<ide>
<add> BrokenComponentDidMountErrorBoundary = class extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {error: null};
<add> log.push('BrokenComponentDidMountErrorBoundary constructor');
<add> }
<add> render() {
<add> if (this.state.error) {
<add> log.push('BrokenComponentDidMountErrorBoundary render error');
<add> return <div>Caught an error: {this.state.error.message}.</div>;
<add> }
<add> log.push('BrokenComponentDidMountErrorBoundary render success');
<add> return <div>{this.props.children}</div>;
<add> }
<add> componentWillMount() {
<add> log.push('BrokenComponentDidMountErrorBoundary componentWillMount');
<add> }
<add> componentDidMount() {
<add> log.push('BrokenComponentDidMountErrorBoundary componentDidMount [!]');
<add> throw new Error('Hello');
<add> }
<add> componentWillUnmount() {
<add> log.push('BrokenComponentDidMountErrorBoundary componentWillUnmount');
<add> }
<add> unstable_handleError(error) {
<add> log.push('BrokenComponentDidMountErrorBoundary unstable_handleError');
<add> this.setState({error});
<add> }
<add> };
<add>
<ide> BrokenRenderErrorBoundary = class extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> describe('ReactErrorBoundaries', () => {
<ide> };
<ide>
<ide> ErrorBoundary = class extends React.Component {
<del> constructor() {
<del> super();
<add> constructor(props) {
<add> super(props);
<ide> this.state = {error: null};
<del> log.push('ErrorBoundary constructor');
<add> log.push(`${this.props.logName} constructor`);
<ide> }
<ide> render() {
<ide> if (this.state.error && !this.props.forceRetry) {
<del> log.push('ErrorBoundary render error');
<add> log.push(`${this.props.logName} render error`);
<ide> return this.props.renderError(this.state.error, this.props);
<ide> }
<del> log.push('ErrorBoundary render success');
<add> log.push(`${this.props.logName} render success`);
<ide> return <div>{this.props.children}</div>;
<ide> }
<ide> unstable_handleError(error) {
<del> log.push('ErrorBoundary unstable_handleError');
<add> log.push(`${this.props.logName} unstable_handleError`);
<ide> this.setState({error});
<ide> }
<ide> componentWillMount() {
<del> log.push('ErrorBoundary componentWillMount');
<add> log.push(`${this.props.logName} componentWillMount`);
<ide> }
<ide> componentDidMount() {
<del> log.push('ErrorBoundary componentDidMount');
<add> log.push(`${this.props.logName} componentDidMount`);
<ide> }
<ide> componentWillReceiveProps() {
<del> log.push('ErrorBoundary componentWillReceiveProps');
<add> log.push(`${this.props.logName} componentWillReceiveProps`);
<ide> }
<ide> componentWillUpdate() {
<del> log.push('ErrorBoundary componentWillUpdate');
<add> log.push(`${this.props.logName} componentWillUpdate`);
<ide> }
<ide> componentDidUpdate() {
<del> log.push('ErrorBoundary componentDidUpdate');
<add> log.push(`${this.props.logName} componentDidUpdate`);
<ide> }
<ide> componentWillUnmount() {
<del> log.push('ErrorBoundary componentWillUnmount');
<add> log.push(`${this.props.logName} componentWillUnmount`);
<ide> }
<ide> };
<ide> ErrorBoundary.defaultProps = {
<add> logName: 'ErrorBoundary',
<ide> renderError(error, props) {
<ide> return (
<ide> <div ref={props.errorMessageRef}>
<ide> describe('ReactErrorBoundaries', () => {
<ide> };
<ide> });
<ide>
<del> if (ReactDOMFeatureFlags.useFiber) {
<del> // This test implements a new feature in Fiber.
<del> it('catches errors originating downstream', () => {
<del> var fail = false;
<del> class Stateful extends React.Component {
<del> state = {shouldThrow: false};
<del>
<del> render() {
<del> if (fail) {
<del> log.push('Stateful render [!]');
<del> throw new Error('Hello');
<del> }
<del> return <div>{this.props.children}</div>;
<del> }
<del> }
<del>
<del> var statefulInst;
<del> var container = document.createElement('div');
<del> ReactDOM.render(
<del> <ErrorBoundary>
<del> <Stateful ref={inst => statefulInst = inst} />
<del> </ErrorBoundary>,
<del> container
<del> );
<del>
<del> log.length = 0;
<del> expect(() => {
<del> fail = true;
<del> statefulInst.forceUpdate();
<del> }).not.toThrow();
<del>
<del> expect(log).toEqual([
<del> 'Stateful render [!]',
<del> 'ErrorBoundary unstable_handleError',
<del> 'ErrorBoundary componentWillUpdate',
<del> 'ErrorBoundary render error',
<del> 'ErrorBoundary componentDidUpdate',
<del> ]);
<del>
<del> log.length = 0;
<del> ReactDOM.unmountComponentAtNode(container);
<del> expect(log).toEqual([
<del> 'ErrorBoundary componentWillUnmount',
<del> ]);
<del> });
<del> }
<del>
<ide> it('renders an error state if child throws in render', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(
<ide> describe('ReactErrorBoundaries', () => {
<ide> ]);
<ide> });
<ide>
<del> if (ReactDOMFeatureFlags.useFiber) {
<del> // This test implements a new feature in Fiber.
<del> it('catches errors in componentDidMount', () => {
<del> var container = document.createElement('div');
<del> ReactDOM.render(
<del> <ErrorBoundary>
<del> <BrokenComponentWillUnmount>
<del> <Normal />
<del> </BrokenComponentWillUnmount>
<del> <BrokenComponentDidMount />
<del> <Normal logName="LastChild" />
<del> </ErrorBoundary>,
<del> container
<del> );
<del> expect(log).toEqual([
<del> 'ErrorBoundary constructor',
<del> 'ErrorBoundary componentWillMount',
<del> 'ErrorBoundary render success',
<del> 'BrokenComponentWillUnmount constructor',
<del> 'BrokenComponentWillUnmount componentWillMount',
<del> 'BrokenComponentWillUnmount render',
<del> 'Normal constructor',
<del> 'Normal componentWillMount',
<del> 'Normal render',
<del> 'BrokenComponentDidMount constructor',
<del> 'BrokenComponentDidMount componentWillMount',
<del> 'BrokenComponentDidMount render',
<del> 'LastChild constructor',
<del> 'LastChild componentWillMount',
<del> 'LastChild render',
<del> // Start flushing didMount queue
<del> 'Normal componentDidMount',
<del> 'BrokenComponentWillUnmount componentDidMount',
<del> 'BrokenComponentDidMount componentDidMount [!]',
<del> // Continue despite the error
<del> 'LastChild componentDidMount',
<del> 'ErrorBoundary componentDidMount',
<del> // Now we are ready to handle the error
<del> 'ErrorBoundary unstable_handleError',
<del> 'ErrorBoundary componentWillUpdate',
<del> 'ErrorBoundary render error',
<del> // Safely unmount every child
<del> 'BrokenComponentWillUnmount componentWillUnmount [!]',
<del> // Continue unmounting safely despite any errors
<del> 'Normal componentWillUnmount',
<del> 'BrokenComponentDidMount componentWillUnmount',
<del> 'LastChild componentWillUnmount',
<del> // The update has finished
<del> 'ErrorBoundary componentDidUpdate',
<del> ]);
<del>
<del> log.length = 0;
<del> ReactDOM.unmountComponentAtNode(container);
<del> expect(log).toEqual([
<del> 'ErrorBoundary componentWillUnmount',
<del> ]);
<del> });
<del> }
<del>
<ide> it('propagates errors on retry on mounting', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(
<ide> describe('ReactErrorBoundaries', () => {
<ide> ]);
<ide> });
<ide>
<del> if (ReactDOMFeatureFlags.useFiber) {
<del> // This test implements a new feature in Fiber.
<del> it('catches errors in componentDidUpdate', () => {
<del> var container = document.createElement('div');
<del> ReactDOM.render(
<del> <ErrorBoundary>
<del> <BrokenComponentDidUpdate />
<del> </ErrorBoundary>,
<del> container
<del> );
<del>
<del> log.length = 0;
<del> ReactDOM.render(
<del> <ErrorBoundary>
<del> <BrokenComponentDidUpdate />
<del> </ErrorBoundary>,
<del> container
<del> );
<del> expect(log).toEqual([
<del> 'ErrorBoundary componentWillReceiveProps',
<del> 'ErrorBoundary componentWillUpdate',
<del> 'ErrorBoundary render success',
<del> 'BrokenComponentDidUpdate componentWillReceiveProps',
<del> 'BrokenComponentDidUpdate componentWillUpdate',
<del> 'BrokenComponentDidUpdate render',
<del> // All lifecycles run
<del> 'BrokenComponentDidUpdate componentDidUpdate [!]',
<del> 'ErrorBoundary componentDidUpdate',
<del> // Then, error is handled
<del> 'ErrorBoundary unstable_handleError',
<del> 'ErrorBoundary componentWillUpdate',
<del> 'ErrorBoundary render error',
<del> 'BrokenComponentDidUpdate componentWillUnmount',
<del> 'ErrorBoundary componentDidUpdate',
<del> ]);
<del>
<del> log.length = 0;
<del> ReactDOM.unmountComponentAtNode(container);
<del> expect(log).toEqual([
<del> 'ErrorBoundary componentWillUnmount',
<del> ]);
<del> });
<del> }
<del>
<ide> it('recovers from componentWillUnmount errors on update', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(
<ide> describe('ReactErrorBoundaries', () => {
<ide> ]);
<ide> });
<ide>
<add> it('picks the right boundary when handling unmounting errors', () => {
<add> function renderInnerError(error, props) {
<add> return <div>Caught an inner error: {error.message}.</div>;
<add> }
<add> function renderOuterError(error, props) {
<add> return <div>Caught an outer error: {error.message}.</div>;
<add> }
<add>
<add> var container = document.createElement('div');
<add> ReactDOM.render(
<add> <ErrorBoundary logName="OuterErrorBoundary" renderError={renderOuterError}>
<add> <ErrorBoundary logName="InnerErrorBoundary" renderError={renderInnerError}>
<add> <BrokenComponentWillUnmount />
<add> </ErrorBoundary>
<add> </ErrorBoundary>,
<add> container
<add> );
<add>
<add> log.length = 0;
<add> ReactDOM.render(
<add> <ErrorBoundary logName="OuterErrorBoundary" renderError={renderOuterError}>
<add> <ErrorBoundary logName="InnerErrorBoundary" renderError={renderInnerError} />
<add> </ErrorBoundary>,
<add> container
<add> );
<add> expect(container.textContent).toBe('Caught an inner error: Hello.');
<add> expect(log).toEqual([
<add> // Update outer boundary
<add> 'OuterErrorBoundary componentWillReceiveProps',
<add> 'OuterErrorBoundary componentWillUpdate',
<add> 'OuterErrorBoundary render success',
<add> // Update inner boundary
<add> 'InnerErrorBoundary componentWillReceiveProps',
<add> 'InnerErrorBoundary componentWillUpdate',
<add> 'InnerErrorBoundary render success',
<add> // Try unmounting child
<add> 'BrokenComponentWillUnmount componentWillUnmount [!]',
<add> ...(ReactDOMFeatureFlags.useFiber ? [
<add> // Fiber proceeds with lifecycles despite errors
<add> // Inner and outer boundaries have updated in this phase
<add> 'InnerErrorBoundary componentDidUpdate',
<add> 'OuterErrorBoundary componentDidUpdate',
<add> // Now that commit phase is done, Fiber handles errors
<add> // Only inner boundary receives the error:
<add> 'InnerErrorBoundary unstable_handleError',
<add> 'InnerErrorBoundary componentWillUpdate',
<add> // Render an error now
<add> 'InnerErrorBoundary render error',
<add> // In Fiber, this was a local update to the
<add> // inner boundary so only its hook fires
<add> 'InnerErrorBoundary componentDidUpdate',
<add> ] : [
<add> // Stack will handle error immediately
<add> 'InnerErrorBoundary unstable_handleError',
<add> 'InnerErrorBoundary render error',
<add> // In stack, this was a part of the update to the
<add> // outer boundary so both lifecycles fire
<add> 'InnerErrorBoundary componentDidUpdate',
<add> 'OuterErrorBoundary componentDidUpdate',
<add> ]),
<add> ]);
<add>
<add> log.length = 0;
<add> ReactDOM.unmountComponentAtNode(container);
<add> expect(log).toEqual([
<add> 'OuterErrorBoundary componentWillUnmount',
<add> 'InnerErrorBoundary componentWillUnmount',
<add> ]);
<add> });
<add>
<ide> it('can recover from error state', () => {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(
<ide> describe('ReactErrorBoundaries', () => {
<ide> 'ErrorBoundary componentWillUnmount',
<ide> ]);
<ide> });
<add>
<add> // The tests below implement new features in Fiber.
<add> if (ReactDOMFeatureFlags.useFiber) {
<add> it('catches errors originating downstream', () => {
<add> var fail = false;
<add> class Stateful extends React.Component {
<add> state = {shouldThrow: false};
<add>
<add> render() {
<add> if (fail) {
<add> log.push('Stateful render [!]');
<add> throw new Error('Hello');
<add> }
<add> return <div>{this.props.children}</div>;
<add> }
<add> }
<add>
<add> var statefulInst;
<add> var container = document.createElement('div');
<add> ReactDOM.render(
<add> <ErrorBoundary>
<add> <Stateful ref={inst => statefulInst = inst} />
<add> </ErrorBoundary>,
<add> container
<add> );
<add>
<add> log.length = 0;
<add> expect(() => {
<add> fail = true;
<add> statefulInst.forceUpdate();
<add> }).not.toThrow();
<add>
<add> expect(log).toEqual([
<add> 'Stateful render [!]',
<add> 'ErrorBoundary unstable_handleError',
<add> 'ErrorBoundary componentWillUpdate',
<add> 'ErrorBoundary render error',
<add> 'ErrorBoundary componentDidUpdate',
<add> ]);
<add>
<add> log.length = 0;
<add> ReactDOM.unmountComponentAtNode(container);
<add> expect(log).toEqual([
<add> 'ErrorBoundary componentWillUnmount',
<add> ]);
<add> });
<add>
<add> it('catches errors in componentDidMount', () => {
<add> var container = document.createElement('div');
<add> ReactDOM.render(
<add> <ErrorBoundary>
<add> <BrokenComponentWillUnmount>
<add> <Normal />
<add> </BrokenComponentWillUnmount>
<add> <BrokenComponentDidMount />
<add> <Normal logName="LastChild" />
<add> </ErrorBoundary>,
<add> container
<add> );
<add> expect(log).toEqual([
<add> 'ErrorBoundary constructor',
<add> 'ErrorBoundary componentWillMount',
<add> 'ErrorBoundary render success',
<add> 'BrokenComponentWillUnmount constructor',
<add> 'BrokenComponentWillUnmount componentWillMount',
<add> 'BrokenComponentWillUnmount render',
<add> 'Normal constructor',
<add> 'Normal componentWillMount',
<add> 'Normal render',
<add> 'BrokenComponentDidMount constructor',
<add> 'BrokenComponentDidMount componentWillMount',
<add> 'BrokenComponentDidMount render',
<add> 'LastChild constructor',
<add> 'LastChild componentWillMount',
<add> 'LastChild render',
<add> // Start flushing didMount queue
<add> 'Normal componentDidMount',
<add> 'BrokenComponentWillUnmount componentDidMount',
<add> 'BrokenComponentDidMount componentDidMount [!]',
<add> // Continue despite the error
<add> 'LastChild componentDidMount',
<add> 'ErrorBoundary componentDidMount',
<add> // Now we are ready to handle the error
<add> 'ErrorBoundary unstable_handleError',
<add> 'ErrorBoundary componentWillUpdate',
<add> 'ErrorBoundary render error',
<add> // Safely unmount every child
<add> 'BrokenComponentWillUnmount componentWillUnmount [!]',
<add> // Continue unmounting safely despite any errors
<add> 'Normal componentWillUnmount',
<add> 'BrokenComponentDidMount componentWillUnmount',
<add> 'LastChild componentWillUnmount',
<add> // The update has finished
<add> 'ErrorBoundary componentDidUpdate',
<add> ]);
<add>
<add> log.length = 0;
<add> ReactDOM.unmountComponentAtNode(container);
<add> expect(log).toEqual([
<add> 'ErrorBoundary componentWillUnmount',
<add> ]);
<add> });
<add>
<add> it('propagates errors inside boundary during componentDidMount', () => {
<add> var container = document.createElement('div');
<add> ReactDOM.render(
<add> <ErrorBoundary>
<add> <BrokenComponentDidMountErrorBoundary
<add> renderError={error => (
<add> <div>
<add> We should never catch our own error: {error.message}.
<add> </div>
<add> )} />
<add> </ErrorBoundary>,
<add> container
<add> );
<add> expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
<add> expect(log).toEqual([
<add> 'ErrorBoundary constructor',
<add> 'ErrorBoundary componentWillMount',
<add> 'ErrorBoundary render success',
<add> 'BrokenComponentDidMountErrorBoundary constructor',
<add> 'BrokenComponentDidMountErrorBoundary componentWillMount',
<add> 'BrokenComponentDidMountErrorBoundary render success',
<add> 'BrokenComponentDidMountErrorBoundary componentDidMount [!]',
<add> // Fiber proceeds with the hooks
<add> 'ErrorBoundary componentDidMount',
<add> // The error propagates to the higher boundary
<add> 'ErrorBoundary unstable_handleError',
<add> // Fiber retries from the root
<add> 'ErrorBoundary componentWillUpdate',
<add> 'ErrorBoundary render error',
<add> 'BrokenComponentDidMountErrorBoundary componentWillUnmount',
<add> 'ErrorBoundary componentDidUpdate',
<add> ]);
<add>
<add> log.length = 0;
<add> ReactDOM.unmountComponentAtNode(container);
<add> expect(log).toEqual([
<add> 'ErrorBoundary componentWillUnmount',
<add> ]);
<add> });
<add>
<add> it('catches errors in componentDidUpdate', () => {
<add> var container = document.createElement('div');
<add> ReactDOM.render(
<add> <ErrorBoundary>
<add> <BrokenComponentDidUpdate />
<add> </ErrorBoundary>,
<add> container
<add> );
<add>
<add> log.length = 0;
<add> ReactDOM.render(
<add> <ErrorBoundary>
<add> <BrokenComponentDidUpdate />
<add> </ErrorBoundary>,
<add> container
<add> );
<add> expect(log).toEqual([
<add> 'ErrorBoundary componentWillReceiveProps',
<add> 'ErrorBoundary componentWillUpdate',
<add> 'ErrorBoundary render success',
<add> 'BrokenComponentDidUpdate componentWillReceiveProps',
<add> 'BrokenComponentDidUpdate componentWillUpdate',
<add> 'BrokenComponentDidUpdate render',
<add> // All lifecycles run
<add> 'BrokenComponentDidUpdate componentDidUpdate [!]',
<add> 'ErrorBoundary componentDidUpdate',
<add> // Then, error is handled
<add> 'ErrorBoundary unstable_handleError',
<add> 'ErrorBoundary componentWillUpdate',
<add> 'ErrorBoundary render error',
<add> 'BrokenComponentDidUpdate componentWillUnmount',
<add> 'ErrorBoundary componentDidUpdate',
<add> ]);
<add>
<add> log.length = 0;
<add> ReactDOM.unmountComponentAtNode(container);
<add> expect(log).toEqual([
<add> 'ErrorBoundary componentWillUnmount',
<add> ]);
<add> });
<add> }
<add>
<ide> }); | 1 |
Javascript | Javascript | remove unused fast path in internal debuglog | 49ba2104c495935bc83390dc8c4cd82bd4c24db9 | <ide><path>lib/internal/util/debuglog.js
<ide> function debuglog(set, cb) {
<ide> if (typeof cb === 'function')
<ide> cb(debug);
<ide> switch (args.length) {
<del> case 0: return debug();
<ide> case 1: return debug(args[0]);
<ide> case 2: return debug(args[0], args[1]);
<ide> default: return debug(...new SafeArrayIterator(args));
<ide> function debuglog(set, cb) {
<ide> };
<ide> const logger = (...args) => {
<ide> switch (args.length) {
<del> case 0: return debug();
<ide> case 1: return debug(args[0]);
<ide> case 2: return debug(args[0], args[1]);
<ide> default: return debug(...new SafeArrayIterator(args)); | 1 |
Text | Text | fix links in socket.connecting | ffc708daad2c512bfe5bc28af07d237bfeaaf89b | <ide><path>doc/api/net.md
<ide> The `connectListener` parameter will be added as a listener for the
<ide> ### socket.connect(path[, connectListener])
<ide> ### socket.connect(port[, host][, connectListener])
<ide>
<del>As [`socket.connect(options\[, connectListener\])`][`socket.connect(options, connectListener)`],
<add>As [`socket.connect(options[, connectListener])`][`socket.connect(options, connectListener)`],
<ide> with options either as either `{port: port, host: host}` or `{path: path}`.
<ide>
<ide> ### socket.connecting
<ide>
<del>If `true` - [`socket.connect(options\[, connectListener\])`][] was called and
<add>If `true` - [`socket.connect(options[, connectListener])`][`socket.connect(options, connectListener)`] was called and
<ide> haven't yet finished. Will be set to `false` before emitting `connect` event
<del>and/or calling [`socket.connect(options\[, connectListener\])`][]'s callback.
<add>and/or calling [`socket.connect(options[, connectListener])`][`socket.connect(options, connectListener)`]'s callback.
<ide>
<ide> ### socket.destroy()
<ide> | 1 |
PHP | PHP | add test for view component class | 33461dcbb77702d444ec0e04a55c2e7ff97521b1 | <ide><path>tests/View/ViewComponentTest.php
<ide> public function testDataExposure()
<ide> $this->assertEquals('world', $variables['hello']());
<ide> $this->assertEquals('taylor', $variables['hello']('taylor'));
<ide> }
<add>
<add> public function testPublicMethodsWithNoArgsAreEagerlyInvokedAndNotCached()
<add> {
<add> $component = new TestSampleViewComponent;
<add>
<add> $this->assertEquals(0, $component->counter);
<add> $variables = $component->data();
<add> $this->assertEquals(1, $component->counter);
<add>
<add> $this->assertEquals('noArgs val', $variables['noArgs']);
<add> $this->assertEquals(0, $variables['counter']);
<add>
<add> // make sure non-public members are not invoked nor counted.
<add> $this->assertEquals(1, $component->counter);
<add> $this->assertArrayHasKey('publicHello', $variables);
<add> $this->assertArrayNotHasKey('protectedHello', $variables);
<add> $this->assertArrayNotHasKey('privateHello', $variables);
<add>
<add> $this->assertArrayNotHasKey('protectedCounter', $variables);
<add> $this->assertArrayNotHasKey('privateCounter', $variables);
<add>
<add> // test each time we invoke data(), the non-argument methods are invoked
<add> $this->assertEquals(1, $component->counter);
<add> $component->data();
<add> $this->assertEquals(2, $component->counter);
<add> $component->data();
<add> $this->assertEquals(3, $component->counter);
<add> }
<ide> }
<ide>
<ide> class TestViewComponent extends Component
<ide> public function hello($string = 'world')
<ide> return $string;
<ide> }
<ide> }
<add>
<add>class TestSampleViewComponent extends Component
<add>{
<add> public $counter = 0;
<add>
<add> protected $protectedCounter = 0;
<add>
<add> private $privateCounter = 0;
<add>
<add> public function render()
<add> {
<add> return 'test';
<add> }
<add>
<add> public function publicHello($string = 'world')
<add> {
<add> $this->counter = 100;
<add>
<add> return $string;
<add> }
<add>
<add> public function noArgs()
<add> {
<add> $this->counter++;
<add>
<add> return 'noArgs val';
<add> }
<add>
<add> protected function protectedHello()
<add> {
<add> $this->counter++;
<add> }
<add>
<add> private function privateHello()
<add> {
<add> $this->counter++;
<add> }
<add>} | 1 |
Python | Python | improve add_newdocs performance | 66174b8aa5644b11054b72761e89e22fd8a18eae | <ide><path>numpy/lib/function_base.py
<ide> def add_newdoc(place, obj, doc):
<ide> that the docstrings were changed.
<ide> """
<ide> try:
<del> new = {}
<del> exec('from %s import %s' % (place, obj), new)
<add> new = getattr(__import__(place, globals(), {}, [obj]), obj)
<ide> if isinstance(doc, str):
<del> add_docstring(new[obj], doc.strip())
<add> add_docstring(new, doc.strip())
<ide> elif isinstance(doc, tuple):
<del> add_docstring(getattr(new[obj], doc[0]), doc[1].strip())
<add> add_docstring(getattr(new, doc[0]), doc[1].strip())
<ide> elif isinstance(doc, list):
<ide> for val in doc:
<del> add_docstring(getattr(new[obj], val[0]), val[1].strip())
<add> add_docstring(getattr(new, val[0]), val[1].strip())
<ide> except:
<ide> pass
<ide>
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def mean(self, axis=None, dtype=None, out=None):
<ide> a = MySubClass([1,2,3])
<ide> assert_equal(np.median(a), -7)
<ide>
<add>
<ide> class TestAdd_newdoc_ufunc(TestCase):
<ide>
<ide> def test_ufunc_arg(self):
<ide> def test_string_arg(self):
<ide> assert_raises(TypeError, add_newdoc_ufunc, np.add, 3)
<ide>
<ide>
<add>class TestAdd_newdoc(TestCase):
<add> def test_add_doc(self):
<add> # test np.add_newdoc
<add> tgt = "Current flat index into the array."
<add> self.assertEqual(np.core.flatiter.index.__doc__[:len(tgt)], tgt)
<add> self.assertTrue(len(np.core.ufunc.identity.__doc__) > 300)
<add> self.assertTrue(len(np.lib.index_tricks.mgrid.__doc__) > 300)
<add>
<add>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 2 |
Python | Python | ignore unknown events | a77a42ea5cab5d5f34901e53cffd989d40bb46a8 | <ide><path>celery/events/state.py
<ide> def __init__(self, callback=None,
<ide> self.tasks = LRUCache(limit=max_tasks_in_memory)
<ide> self.event_callback = callback
<ide> self._mutex = threading.Lock()
<add> self.handlers = {'task': self.task_event,
<add> 'worker': self.worker_event}
<add> self._get_handler = self.handlers.__getitem__
<ide>
<ide> def freeze_while(self, fun, *args, **kwargs):
<ide> clear_after = kwargs.pop('clear_after', False)
<ide> def event(self, event):
<ide> with self._mutex:
<ide> return self._dispatch_event(event)
<ide>
<del> def _dispatch_event(self, event):
<add> def _dispatch_event(self, event, kwdict=kwdict):
<ide> self.event_count += 1
<ide> event = kwdict(event)
<ide> group, _, subject = event['type'].partition('-')
<del> getattr(self, group + '_event')(subject, event)
<add> try:
<add> self._get_handler(group)(subject, event)
<add> except KeyError:
<add> pass
<ide> if self.event_callback:
<ide> self.event_callback(self, event)
<ide> | 1 |
Javascript | Javascript | make use of declared but unused variables | 03c572551de92ef11f649dbeb305f7c747c68f52 | <ide><path>src/ng/directive/ngModel.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> };
<ide> ngModelSet = function($scope, newValue) {
<ide> if (isFunction(parsedNgModel($scope))) {
<del> invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
<add> invokeModelSetter($scope, {$$$p: newValue});
<ide> } else {
<del> parsedNgModelAssign($scope, ctrl.$modelValue);
<add> parsedNgModelAssign($scope, newValue);
<ide> }
<ide> };
<ide> } else if (!parsedNgModel.assign) {
<ide><path>src/ng/directive/ngOptions.js
<ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
<ide> var value = optionValues[key];
<ide>
<del> var locals = getLocals(optionValues[key], key);
<del> var selectValue = getTrackByValueFn(optionValues[key], locals);
<add> var locals = getLocals(value, key);
<add> var selectValue = getTrackByValueFn(value, locals);
<ide> watchedArray.push(selectValue);
<ide>
<ide> // Only need to watch the displayFn if there is a specific label expression | 2 |
PHP | PHP | add language to str_slug helper | deefa1f96df1f21de36e40ebe1ef61b997d8e098 | <ide><path>src/Illuminate/Support/helpers.php
<ide> function str_singular($value)
<ide> *
<ide> * @param string $title
<ide> * @param string $separator
<add> * @param string $language
<ide> * @return string
<ide> */
<del> function str_slug($title, $separator = '-')
<add> function str_slug($title, $separator = '-', $language = 'en')
<ide> {
<del> return Str::slug($title, $separator);
<add> return Str::slug($title, $separator, $language);
<ide> }
<ide> }
<ide> | 1 |
Python | Python | set version to v2.3.0 | 7ff447c5a0198600bfb8f4a43b042a6ed8276126 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "2.3.0.dev1"
<add>__version__ = "2.3.0"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Ruby | Ruby | add configurable selenium driver for capybara | 4f08bc0808ab93f70a029f15ac094d61fc5ba121 | <ide><path>actionpack/lib/system_testing/driver_adapters.rb
<ide> module DriverAdapters
<ide> extend ActiveSupport::Autoload
<ide>
<ide> autoload :CapybaraRackTestDriver
<add> autoload :CapybaraSeleniumDriver
<ide>
<ide> class << self
<ide> def lookup(name)
<ide><path>actionpack/lib/system_testing/driver_adapters/capybara_selenium_driver.rb
<add>require 'rack/handler/puma'
<add>require 'selenium-webdriver'
<add>
<add>module SystemTesting
<add> module DriverAdapters
<add> class CapybaraSeleniumDriver
<add> attr_reader :browser, :server, :port, :screen_size
<add>
<add> def initialize(browser: :chrome, server: :puma, port: 28100, screen_size: [1400,1400])
<add> @browser = browser
<add> @server = server
<add> @port = port
<add> @screen_size = screen_size
<add> end
<add>
<add> def call
<add> registration
<add> setup
<add> end
<add>
<add> private
<add> def registration
<add> register_browser_driver
<add> register_server
<add> end
<add>
<add> def setup
<add> set_server
<add> set_driver
<add> set_port
<add> end
<add>
<add> def register_browser_driver
<add> Capybara.register_driver @browser do |app|
<add> Capybara::Selenium::Driver.new(app, browser: @browser).tap do |driver|
<add> driver.browser.manage.window.size = Selenium::WebDriver::Dimension.new(*@screen_size)
<add> end
<add> end
<add> end
<add>
<add> def register_server
<add> Capybara.register_server @server do |app, port, host|
<add> case @server
<add> when :puma
<add> register_puma(app, port)
<add> when :webrick
<add> register_webrick(app, port, host)
<add> else
<add> register_default(app, port)
<add> end
<add> end
<add> end
<add>
<add> def register_default(app, port)
<add> Capybara.run_default_server(app, port)
<add> end
<add>
<add> def register_puma(app, port)
<add> ::Rack::Handler::Puma.run(app, Port: port, Threads: '0:4')
<add> end
<add>
<add> def register_webrick(app, port, host)
<add> Rack::Handler::WEBrick.run(app, Host: host, Port: port, AccessLog: [], Logger: WEBrick::Log::new(nil, 0))
<add> end
<add>
<add> def set_server
<add> Capybara.server = @server
<add> end
<add>
<add> def set_driver
<add> Capybara.default_driver = @browser.to_sym
<add> end
<add>
<add> def set_port
<add> Capybara.server_port = @port
<add> end
<add> end
<add> end
<add>end | 2 |
Text | Text | add documentation for wildcard | 4a37cd131893fb67fcbba45ef57ee4b4015ef043 | <ide><path>guide/english/bash/bash-rm/index.md
<ide> rm <file name or file path>
<ide> rm -R <folder name or folder path>
<ide> ```
<ide>
<del>You will be prompted with **'rm: remove regular file ‘hello’?'** and will need to respond **'y'** before the file can be deleted. Use this command with caution because 'rm' is a permanent action.
<add>**Delete Files of a certain type**
<add>
<add>```bash
<add>rm -R *file_extension
<add>```
<add>- `*` accounts for the part to ignore, `file_extension` is the type to remove
<add>Example:
<add>```bash
<add>rm -R *.txt
<add>```
<add>Removes all file ending with .txt
<ide>
<ide> There are few commonly used arguments:
<ide> | 1 |
Text | Text | add a note about font-family in syntax themes | c5a15fb50e36c6074208b0fcbef52d2ce23970e2 | <ide><path>docs/creating-a-theme.md
<ide> window in dev mode. To open a Dev Mode Atom window run `atom --dev .` in the
<ide> terminal, use `cmd-shift-o` or use the _View > Developer > Open in Dev Mode_
<ide> menu. When you edit your theme, changes will instantly be reflected!
<ide>
<add>> Note: It's advised to _not_ specify a `font-family` in your syntax theme because it will override the Font Family field in Atom's settings. If you still like to recommend a font that goes well with your theme, we recommend you do so in your README.
<add>
<ide> ## Creating an Interface Theme
<ide>
<ide> Interface themes **must** provide a `ui-variables.less` file which contains all | 1 |
Javascript | Javascript | return needed objects | 706fac34a0d7c96a5e51ff453a9885ef631a31b9 | <ide><path>script/lib/update-dependency/check-npm.js
<ide> module.exports = async function(cwd) {
<ide> ignoreDev: true,
<ide> skipUnused: true
<ide> });
<del> const outdatedPackages = currentState.get('packages').filter(p => {
<del> if (p.packageJson && p.latest) {
<del> return p.latest > p.installed;
<del> }
<del> });
<add> const outdatedPackages = currentState
<add> .get('packages')
<add> .filter(p => {
<add> if (p.packageJson && p.latest && p.installed) {
<add> return p.latest > p.installed;
<add> }
<add> })
<add> .map(({ packageJson, installed, moduleName, latest }) => ({
<add> packageJson,
<add> installed,
<add> moduleName,
<add> latest,
<add> isCorePackage: false
<add> }));
<ide>
<ide> console.log(`${outdatedPackages.length} outdated package(s) found`);
<ide> | 1 |
Text | Text | add missing import in css docs | 9a548b649f541d2e0631102b2a4dc40edff7b1e6 | <ide><path>docs/basic-features/built-in-css-support.md
<ide> For importing CSS required by a third party component, you can do so in your com
<ide> // components/ExampleDialog.js
<ide> import { useState } from 'react'
<ide> import { Dialog } from '@reach/dialog'
<add>import VisuallyHidden from '@reach/visually-hidden'
<ide> import '@reach/dialog/styles.css'
<ide>
<ide> function ExampleDialog(props) { | 1 |
PHP | PHP | fix yoda condition in file test | b93f373f1627560dc001b1e52c2941e4ce9920e4 | <ide><path>lib/Cake/Test/Case/Utility/FileTest.php
<ide> public function testMime() {
<ide> $path = CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif';
<ide> $file = new File($path);
<ide> $expected = 'image/gif';
<del> if (function_exists('mime_content_type') && false === mime_content_type($file->pwd())) {
<add> if (function_exists('mime_content_type') && mime_content_type($file->pwd()) === false) {
<ide> $expected = false;
<ide> }
<ide> $this->assertEquals($expected, $file->mime()); | 1 |
Javascript | Javascript | create new array in defaults | 1de9e168589b383583086a1a776bbfd947335819 | <ide><path>lib/config/defaults.js
<ide> const applyResolveDefaults = (
<ide> F(resolve, "mainFields", () =>
<ide> webTarget ? ["browser", "module", "main"] : ["module", "main"]
<ide> );
<del> D(resolve, "roots", [context]);
<add> F(resolve, "roots", () => [context]);
<ide> F(resolve.byDependency, "commonjs", () => ({}));
<ide> F(resolve.byDependency.commonjs, "conditionNames", () => [
<ide> "require", | 1 |
Javascript | Javascript | remove unused bundle flag | c539be05155eb6f4f6d19fbb9243dc335eb38aba | <ide><path>scripts/rollup/build.js
<ide> function getPlugins(
<ide> hasteName,
<ide> moduleType,
<ide> manglePropertiesOnProd,
<del> useFiber,
<ide> modulesToStub
<ide> ) {
<ide> const plugins = [
<ide> function createBundle(bundle, bundleType) {
<ide> bundle.hasteName,
<ide> bundle.moduleType,
<ide> bundle.manglePropertiesOnProd,
<del> bundle.useFiber,
<ide> bundle.modulesToStub
<ide> ),
<ide> })
<ide><path>scripts/rollup/bundles.js
<ide> const bundles = [
<ide> 'src/ReactVersion.js',
<ide> 'src/shared/**/*.js',
<ide> ],
<del> useFiber: true,
<ide> },
<ide>
<ide> /******* React Native RT *******/
<ide> const bundles = [
<ide> 'src/ReactVersion.js',
<ide> 'src/shared/**/*.js',
<ide> ],
<del> useFiber: true,
<ide> },
<ide>
<ide> /******* React Native CS *******/
<ide> const bundles = [
<ide> 'src/ReactVersion.js',
<ide> 'src/shared/**/*.js',
<ide> ],
<del> useFiber: true,
<ide> },
<ide>
<ide> /******* React Test Renderer *******/ | 2 |
Java | Java | fix broken test in enableschedulingtests | 08f3a7982192e3f1aee9f31c61fb98022fc3b0ac | <ide><path>spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * Tests use of @EnableScheduling on @Configuration classes.
<ide> *
<ide> * @author Chris Beams
<add> * @author Sam Brannen
<ide> * @since 3.1
<ide> */
<ide> public class EnableSchedulingTests {
<ide> public void withExplicitSchedulerAmbiguity_andSchedulingEnabled() {
<ide> assertThat(ex.getMessage(), startsWith("More than one TaskScheduler"));
<ide> throw ex;
<ide> }
<add> finally {
<add> ctx.close();
<add> }
<ide> }
<ide>
<ide> @EnableScheduling @Configuration
<ide> public void withAmbiguousTaskSchedulers_butNoActualTasks() {
<ide> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
<ide> ctx.register(SchedulingEnabled_withAmbiguousTaskSchedulers_butNoActualTasks.class);
<ide> ctx.refresh();
<add> ctx.close();
<ide> }
<ide>
<ide>
<ide> public void withAmbiguousTaskSchedulers_andSingleTask() {
<ide> try {
<ide> ctx.refresh();
<ide> } catch (IllegalStateException ex) {
<del> assertThat(ex.getMessage(), startsWith("More than one TaskScheduler and/or"));
<add> assertThat(ex.getMessage(), startsWith("More than one TaskScheduler exists within the context"));
<ide> throw ex;
<ide> }
<add> finally {
<add> ctx.close();
<add> }
<ide> }
<ide>
<ide> | 1 |
Text | Text | simplify major release preparation | 18ff5832501b66b45a16ffcbddebd38c93bd4bcb | <ide><path>doc/guides/releases.md
<ide> announced immediately following the release of 12.0.0).
<ide>
<ide> ### Release branch
<ide>
<del>Approximately three months before a major release, new `vN.x` and
<add>Approximately two months before a major release, new `vN.x` and
<ide> `vN.x-staging` branches (where `N` indicates the major release) should be
<del>created as forks of the `master` branch. Up until one month before the release
<del>date, these must be kept in sync with `master` and must not be considered to
<del>be stable branches (e.g. they may be force pushed).
<add>created as forks of the `master` branch. Up until one week before the release
<add>date, these must be kept in sync with `master`.
<ide>
<ide> The `vN.x` and `vN.x-staging` branches must be kept in sync with one another
<del>up until the date of release.
<add>up until the date of the release.
<ide>
<del>One month or less before the release date, commits must be cherry-picked into
<del>the two branches. To land `SEMVER-MAJOR` at this time requires no objections
<del>from the TSC.
<add>The TSC should be informed of any `SEMVER-MAJOR` commits that land within one
<add>month of the release.
<ide>
<ide> ### Create release labels
<ide>
<ide> labels of previous releases.
<ide>
<ide> ### Release proposal
<ide>
<del>A draft release proposal should be created two months before the release. A
<add>A draft release proposal should be created 6 weeks before the release. A
<ide> separate `vN.x-proposal` branch should be created that tracks the `vN.x`
<ide> branch. This branch will contain the draft release commit (with the draft
<ide> changelog). | 1 |
Text | Text | update info about wq.db.rest router | e9b6b47872ffbd6572c39af9b2198575ccd3dde4 | <ide><path>docs/api-guide/routers.md
<ide> The following third party packages are also available.
<ide>
<ide> The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
<ide>
<del>## wq.db
<add>## ModelRouter (wq.db.rest)
<ide>
<del>The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `app.router.register_model` is a model class. Reasonable defaults for a url prefix and viewset will be inferred from the model and global configuration.
<add>The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `rest.router.register_model` is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.
<ide>
<del> from wq.db.rest import app
<add> from wq.db import rest
<ide> from myapp.models import MyModel
<ide>
<del> app.router.register_model(MyModel)
<add> rest.router.register_model(MyModel)
<ide>
<ide> ## DRF-extensions
<ide>
<ide> The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions
<ide> [route-decorators]: viewsets.md#marking-extra-actions-for-routing
<ide> [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
<ide> [wq.db]: http://wq.io/wq.db
<del>[wq.db-router]: http://wq.io/docs/app.py
<add>[wq.db-router]: http://wq.io/docs/router
<ide> [drf-extensions]: http://chibisov.github.io/drf-extensions/docs/
<ide> [drf-extensions-routers]: http://chibisov.github.io/drf-extensions/docs/#routers
<ide> [drf-extensions-nested-viewsets]: http://chibisov.github.io/drf-extensions/docs/#nested-routes | 1 |
Python | Python | update example in np.nonzero docstring | 6aed49135b26fe23620b15cab6c3b99c56545867 | <ide><path>numpy/core/fromnumeric.py
<ide> def nonzero(a):
<ide> [0, 2, 0],
<ide> [1, 1, 0]])
<ide> >>> np.nonzero(x)
<del> (array([0, 1, 2, 2], dtype=int64), array([0, 1, 0, 1], dtype=int64))
<add> (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
<ide>
<ide> >>> x[np.nonzero(x)]
<del> array([ 1., 1., 1.])
<add> array([1, 2, 1, 1])
<ide> >>> np.transpose(np.nonzero(x))
<ide> array([[0, 0],
<ide> [1, 1],
<del> [2, 2]])
<add> [2, 0],
<add> [2, 1])
<ide>
<ide> A common use for ``nonzero`` is to find the indices of an array, where
<ide> a condition is True. Given an array `a`, the condition `a` > 3 is a | 1 |
Javascript | Javascript | bind methods from the prototype chain in console | 04a291abec3b86ed902c5e9919b2a8adf1e07d14 | <ide><path>lib/console.js
<ide> function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
<ide> var keys = Object.keys(Console.prototype);
<ide> for (var v = 0; v < keys.length; v++) {
<ide> var k = keys[v];
<del> this[k] = Console.prototype[k].bind(this);
<add> // We have to bind the methods grabbed from the instance instead of from
<add> // the prototype so that users extending the Console can override them
<add> // from the prototype chain of the subclass.
<add> this[k] = this[k].bind(this);
<ide> }
<ide> }
<ide>
<ide><path>test/parallel/test-console-instance.js
<ide> out.write = err.write = (d) => {};
<ide> {
<ide> class MyConsole extends Console {
<ide> hello() {}
<add> // See if the methods on Console.prototype are overridable.
<add> log() { return 'overridden'; }
<ide> }
<ide> const myConsole = new MyConsole(process.stdout);
<ide> assert.strictEqual(typeof myConsole.hello, 'function');
<ide> assert.ok(myConsole instanceof Console);
<add> assert.strictEqual(myConsole.log(), 'overridden');
<add>
<add> const log = myConsole.log;
<add> assert.strictEqual(log(), 'overridden');
<ide> }
<ide>
<ide> // Instance that does not ignore the stream errors. | 2 |
Text | Text | fix typo in zlib.md | 1fcd088fd9648bcbab9789d8f00ce3208647a683 | <ide><path>doc/api/zlib.md
<ide> http.createServer((request, response) => {
<ide> }).listen(1337);
<ide> ```
<ide>
<del>By default, the `zlib` methods with throw an error when decompressing
<add>By default, the `zlib` methods will throw an error when decompressing
<ide> truncated data. However, if it is known that the data is incomplete, or
<ide> the desire is to inspect only the beginning of a compressed file, it is
<ide> possible to suppress the default error handling by changing the flushing | 1 |
Java | Java | change domstorageenabled default value to true | 829019400aca367656dd18110d2e7dd845b9d043 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/webview/ReactWebViewManager.java
<ide> public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermiss
<ide> mWebViewConfig.configWebView(webView);
<ide> webView.getSettings().setBuiltInZoomControls(true);
<ide> webView.getSettings().setDisplayZoomControls(false);
<add> webView.getSettings().setDomStorageEnabled(true);
<ide>
<ide> // Fixes broken full-screen modals/galleries due to body height being 0.
<ide> webView.setLayoutParams( | 1 |
Python | Python | add keras resnet code | 310219595b048b3b0c798d5439ce0e79ca3dd236 | <ide><path>official/resnet/imagenet_main.py
<ide> def parse_record(raw_record, is_training, dtype):
<ide>
<ide> def input_fn(is_training, data_dir, batch_size, num_epochs=1,
<ide> dtype=tf.float32, datasets_num_private_threads=None,
<del> num_parallel_batches=1):
<add> num_parallel_batches=1, parse_record_fn=parse_record):
<ide> """Input function which provides batches for train or eval.
<ide>
<ide> Args:
<ide> def input_fn(is_training, data_dir, batch_size, num_epochs=1,
<ide> is_training=is_training,
<ide> batch_size=batch_size,
<ide> shuffle_buffer=_SHUFFLE_BUFFER,
<del> parse_record_fn=parse_record,
<add> parse_record_fn=parse_record_fn,
<ide> num_epochs=num_epochs,
<ide> dtype=dtype,
<ide> datasets_num_private_threads=datasets_num_private_threads, | 1 |
Ruby | Ruby | change merge to merge! in as on new hashes | 187969069a1d76b93088ec8f574b8c80252dbb51 | <ide><path>activesupport/lib/active_support/xml_mini/libxmlsax.rb
<ide> def on_end_document
<ide> end
<ide>
<ide> def on_start_element(name, attrs = {})
<del> new_hash = { CONTENT_KEY => '' }.merge(attrs)
<add> new_hash = { CONTENT_KEY => '' }.merge!(attrs)
<ide> new_hash[HASH_SIZE_KEY] = new_hash.size + 1
<ide>
<ide> case current_hash[name]
<ide><path>activesupport/lib/active_support/xml_mini/nokogirisax.rb
<ide> def error(error_message)
<ide> end
<ide>
<ide> def start_element(name, attrs = [])
<del> new_hash = { CONTENT_KEY => '' }.merge(Hash[attrs])
<add> new_hash = { CONTENT_KEY => '' }.merge!(Hash[attrs])
<ide> new_hash[HASH_SIZE_KEY] = new_hash.size + 1
<ide>
<ide> case current_hash[name] | 2 |
Go | Go | fix typo in comments and log | d69747e19e862dc302694f4d02b5a29c14aa5b78 | <ide><path>libnetwork/controller.go
<ide> type NetworkController interface {
<ide> // Sandboxes returns the list of Sandbox(s) managed by this controller.
<ide> Sandboxes() []Sandbox
<ide>
<del> // WlakSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
<add> // WalkSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
<ide> WalkSandboxes(walker SandboxWalker)
<ide>
<ide> // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
<ide><path>libnetwork/default_gateway.go
<ide> const (
<ide> var procGwNetwork = make(chan (bool), 1)
<ide>
<ide> /*
<del> libnetwork creates a bridge network "docker_gw_bridge" for provding
<add> libnetwork creates a bridge network "docker_gw_bridge" for providing
<ide> default gateway for the containers if none of the container's endpoints
<ide> have GW set by the driver. ICC is set to false for the GW_bridge network.
<ide>
<ide> var procGwNetwork = make(chan (bool), 1)
<ide>
<ide> func (sb *sandbox) setupDefaultGW() error {
<ide>
<del> // check if the conitainer already has a GW endpoint
<add> // check if the container already has a GW endpoint
<ide> if ep := sb.getEndpointInGWNetwork(); ep != nil {
<ide> return nil
<ide> }
<ide><path>libnetwork/drivers/bridge/bridge.go
<ide> func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo d
<ide> }
<ide> d.Unlock()
<ide>
<del> // Parse and validate the config. It should not conflict with existing networks' config
<add> // Parse and validate the config. It should not be conflict with existing networks' config
<ide> config, err := parseNetworkOptions(id, option)
<ide> if err != nil {
<ide> return err
<ide><path>libnetwork/network.go
<ide> func (n *network) requestPoolHelper(ipam ipamapi.Ipam, addressSpace, preferredPo
<ide> }()
<ide>
<ide> // If this is a preferred pool request and the network
<del> // is local scope and there is a overlap, we fail the
<add> // is local scope and there is an overlap, we fail the
<ide> // network creation right here. The pool will be
<ide> // released in the defer.
<ide> if preferredPool != "" {
<ide><path>libnetwork/service_linux.go
<ide> func (sb *sandbox) addLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*P
<ide>
<ide> i, err := ipvs.New(sb.Key())
<ide> if err != nil {
<del> logrus.Errorf("Failed to create a ipvs handle for sbox %s: %v", sb.Key(), err)
<add> logrus.Errorf("Failed to create an ipvs handle for sbox %s: %v", sb.Key(), err)
<ide> return
<ide> }
<ide> defer i.Close()
<ide> func (sb *sandbox) rmLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*Po
<ide>
<ide> i, err := ipvs.New(sb.Key())
<ide> if err != nil {
<del> logrus.Errorf("Failed to create a ipvs handle for sbox %s: %v", sb.Key(), err)
<add> logrus.Errorf("Failed to create an ipvs handle for sbox %s: %v", sb.Key(), err)
<ide> return
<ide> }
<ide> defer i.Close() | 5 |
Text | Text | add docs on how to configure active storage | cc488b40d2bde10083984df5bb85417e0c2f7c0c | <ide><path>guides/source/configuring.md
<ide> main application.
<ide> You can set this as nil to not mount Action Cable as part of your
<ide> normal Rails server.
<ide>
<add>
<add>### Configuring Active Storage
<add>
<add>`config.active_storage` provides the following configuration options:
<add>
<add>* `config.active_storage.analyzers` accepts an array of classes indicating the analyzers available for Active Storage blobs. The default is `[ActiveStorage::Analyzer::ImageAnalyzer, ActiveStorage::Analyzer::VideoAnalyzer]`. The former can extract width and height of an image blob; the latter can extract width, height, duration, angle, and aspect ratio of a video blob.
<add>
<add>* `config.active_storage.previewers` accepts an array of classes indicating the image previewers available in Active Storage blobs. The default is `[ActiveStorage::Previewer::PDFPreviewer, ActiveStorage::Previewer::VideoPreviewer]`. The former can generate a thumbnail from the first page of a PDF blob; the latter from the relevant frame of a video blob.
<add>
<add>* `config.active_storage.paths` accepts a hash of options indicating the locations of previewer/analyzer commands. The default is `{}`, meaning the commands will be looked for in the default path. Can include any of these options:
<add> * `:ffprobe` - The location of the ffprobe executable.
<add> * `:mutool` - The location of the mutool executable.
<add> * `:ffmpeg` - The location of the ffmpeg executable.
<add>
<add> ```ruby
<add> config.active_storage.paths[:ffprobe] = '/usr/local/bin/ffprobe'
<add> ```
<add>
<add>* `config.active_storage.variable_content_types` accepts an array of strings indicating the content types that Active Storage can transform through ImageMagick. The default is `%w(image/png image/gif image/jpg image/jpeg image/vnd.adobe.photoshop)`.
<add>
<add>* `config.active_storage.content_types_to_serve_as_binary` accepts an array of strings indicating the content types that Active Storage will always serve as an attachment, rather than inline. The default is `%w(text/html
<add>text/javascript image/svg+xml application/postscript application/x-shockwave-flash text/xml application/xml application/xhtml+xml)`.
<add>
<add>* `config.active_storage.queue` can be used to set the name of the Active Job queue used to perform jobs like analyzing the content of a blob or purging a blog.
<add>
<add> ```ruby
<add> config.active_job.queue = :low_priority
<add> ```
<add>
<add>* `config.active_storage.logger` can be used to set the logger used by Active Storage. Accepts a logger conforming to the interface of Log4r or the default Ruby Logger class.
<add>
<add> ```ruby
<add> config.active_job.logger = ActiveSupport::Logger.new(STDOUT)
<add> ```
<add>
<ide> ### Configuring a Database
<ide>
<ide> Just about every Rails application will interact with a database. You can connect to the database by setting an environment variable `ENV['DATABASE_URL']` or by using a configuration file called `config/database.yml`. | 1 |
Python | Python | set the __name__ of generated methods | e8c387cb8a105b9209474b6abf5c8feb0e92d830 | <ide><path>numpy/lib/mixins.py
<ide> def _disables_array_ufunc(obj):
<ide> return False
<ide>
<ide>
<del>def _binary_method(ufunc):
<add>def _binary_method(ufunc, name):
<ide> """Implement a forward binary method with a ufunc, e.g., __add__."""
<ide> def func(self, other):
<ide> if _disables_array_ufunc(other):
<ide> return NotImplemented
<ide> return ufunc(self, other)
<add> func.__name__ = '__{}__'.format(name)
<ide> return func
<ide>
<ide>
<del>def _reflected_binary_method(ufunc):
<add>def _reflected_binary_method(ufunc, name):
<ide> """Implement a reflected binary method with a ufunc, e.g., __radd__."""
<ide> def func(self, other):
<ide> if _disables_array_ufunc(other):
<ide> return NotImplemented
<ide> return ufunc(other, self)
<add> func.__name__ = '__r{}__'.format(name)
<ide> return func
<ide>
<ide>
<del>def _inplace_binary_method(ufunc):
<add>def _inplace_binary_method(ufunc, name):
<ide> """Implement an in-place binary method with a ufunc, e.g., __iadd__."""
<ide> def func(self, other):
<ide> return ufunc(self, other, out=(self,))
<add> func.__name__ = '__i{}__'.format(name)
<ide> return func
<ide>
<ide>
<del>def _numeric_methods(ufunc):
<add>def _numeric_methods(ufunc, name):
<ide> """Implement forward, reflected and inplace binary methods with a ufunc."""
<del> return (_binary_method(ufunc),
<del> _reflected_binary_method(ufunc),
<del> _inplace_binary_method(ufunc))
<add> return (_binary_method(ufunc, name),
<add> _reflected_binary_method(ufunc, name),
<add> _inplace_binary_method(ufunc, name))
<ide>
<ide>
<del>def _unary_method(ufunc):
<add>def _unary_method(ufunc, name):
<ide> """Implement a unary special method with a ufunc."""
<ide> def func(self):
<ide> return ufunc(self)
<add> func.__name__ = '__{}__'.format(name)
<ide> return func
<ide>
<ide>
<ide> def __repr__(self):
<ide> # overrides NEP.
<ide>
<ide> # comparisons don't have reflected and in-place versions
<del> __lt__ = _binary_method(um.less)
<del> __le__ = _binary_method(um.less_equal)
<del> __eq__ = _binary_method(um.equal)
<del> __ne__ = _binary_method(um.not_equal)
<del> __gt__ = _binary_method(um.greater)
<del> __ge__ = _binary_method(um.greater_equal)
<add> __lt__ = _binary_method(um.less, 'lt')
<add> __le__ = _binary_method(um.less_equal, 'le')
<add> __eq__ = _binary_method(um.equal, 'eq')
<add> __ne__ = _binary_method(um.not_equal, 'ne')
<add> __gt__ = _binary_method(um.greater, 'gt')
<add> __ge__ = _binary_method(um.greater_equal, 'ge')
<ide>
<ide> # numeric methods
<del> __add__, __radd__, __iadd__ = _numeric_methods(um.add)
<del> __sub__, __rsub__, __isub__ = _numeric_methods(um.subtract)
<del> __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply)
<add> __add__, __radd__, __iadd__ = _numeric_methods(um.add, 'add')
<add> __sub__, __rsub__, __isub__ = _numeric_methods(um.subtract, 'sub')
<add> __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul')
<ide> if sys.version_info.major < 3:
<ide> # Python 3 uses only __truediv__ and __floordiv__
<del> __div__, __rdiv__, __idiv__ = _numeric_methods(um.divide)
<del> __truediv__, __rtruediv__, __itruediv__ = _numeric_methods(um.true_divide)
<add> __div__, __rdiv__, __idiv__ = _numeric_methods(um.divide, 'div')
<add> __truediv__, __rtruediv__, __itruediv__ = _numeric_methods(
<add> um.true_divide, 'truediv')
<ide> __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods(
<del> um.floor_divide)
<del> __mod__, __rmod__, __imod__ = _numeric_methods(um.mod)
<add> um.floor_divide, 'floordiv')
<add> __mod__, __rmod__, __imod__ = _numeric_methods(um.mod, 'mod')
<ide> # TODO: handle the optional third argument for __pow__?
<del> __pow__, __rpow__, __ipow__ = _numeric_methods(um.power)
<del> __lshift__, __rlshift__, __ilshift__ = _numeric_methods(um.left_shift)
<del> __rshift__, __rrshift__, __irshift__ = _numeric_methods(um.right_shift)
<del> __and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and)
<del> __xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor)
<del> __or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or)
<add> __pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow')
<add> __lshift__, __rlshift__, __ilshift__ = _numeric_methods(
<add> um.left_shift, 'lshift')
<add> __rshift__, __rrshift__, __irshift__ = _numeric_methods(
<add> um.right_shift, 'rshift')
<add> __and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and, 'and')
<add> __xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor, 'xor')
<add> __or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or, 'or')
<ide>
<ide> # unary methods
<del> __neg__ = _unary_method(um.negative)
<del> __abs__ = _unary_method(um.absolute)
<del> __invert__ = _unary_method(um.invert)
<add> __neg__ = _unary_method(um.negative, 'neg')
<add> __abs__ = _unary_method(um.absolute, 'abs')
<add> __invert__ = _unary_method(um.invert, 'invert') | 1 |
Text | Text | add release date for 0.9.17 | 68ab0f9b02372d11d31412edce86080eaa43625b | <ide><path>CHANGELOG.md
<ide> <a name="0.9.17"><a/>
<del># <angular/> 0.9.17 vegetable-reanimation (in progress) #
<add># <angular/> 0.9.17 vegetable-reanimation (2011-06-30) #
<ide>
<ide> ### New Features
<ide> - New [ng:options] directive to better bind a model to `<select>` and `<option>` elements. | 1 |
Text | Text | fix sentence structure | ee986bf8a71269473c92796ee7fec6872f89e5d7 | <ide><path>guide/english/miscellaneous/how-to-start-when-you-are-stuck/index.md
<ide> ---
<ide> title: How to Start When You Are Stuck
<ide> ---
<del>You are a camper just like me, you get to an exercise and you get stuck ... just like anyone else. You have no idea how to start, you stare at your editor and you think you must have a problem, surely you are not developer material ... well you're wrong! Perhaps you are just like me? I'm a visual person, I like a drawing better than a text. Everytime the same problem put down in a schema makes more sense to me than if you gave me a text. So ... what do I do when I have problems solving/understanding an exercise? I start to draw. After I have my drawing in place if I need more to translate it to code I can also write it in pseudocode. After that transposing it to code should not be very hard.
<add>You are a camper just like me, you get to an exercise and you get stuck ... just like anyone else. You have no idea how to start, you stare at your editor and you think you must have a problem, surely you are not developer material ... well you're wrong! Perhaps you are just like me? I'm a visual person, I like a drawing better than a text. Everytime the same problem put down in a schema makes more sense to me than if you gave me a text. So ... what do I do when I have problems solving/understanding an exercise? I start to draw. After I have my drawing in place, if I need more to translate it to code, I can also write it in pseudocode. After that, transposing it to code should not be very hard.
<ide>
<del># So what are this flowcharts (the drawings) and pseudocode?
<add># So what are these flowcharts (the drawings) and pseudocode?
<ide>
<ide> During my first semester in college, we had a course about introduction to algorithms. This is where we first learned about this stuff. We learned that a good algorithm and good logical programing is developed using flowcharts and pseudocode.
<ide>
<del>A **flowchart** represents your program flow from top to bottom. Each command is represented on this. Depending on the nature of the command there are different shapes you can use. A few of them that I mostly use (you can google more on this, google is your friend when you know what to google for) are:
<add>A **flowchart** represents your program flow from top to bottom. Each command is represented on this. Depending on the nature of the command, there are different shapes you can use. A few of them that I mostly use (you can google more on this, google is your friend when you know what to google for) are:
<ide>
<ide> 
<ide>
<del>More information about this you can find here <a href='https://en.wikipedia.org/wiki/Flowchart' target='_blank' rel='nofollow'>https://en.wikipedia.org/wiki/Flowchart</a>.
<add>You can find more information about this here: <a href='https://en.wikipedia.org/wiki/Flowchart' target='_blank' rel='nofollow'>https://en.wikipedia.org/wiki/Flowchart</a>.
<ide>
<del>**Pseudocode** is an informal language that helps developers write algorithms. It is a text-based design tool and it uses a human readable language. It's a structured english text that describes an algorithm.
<add>**Pseudocode** is an informal language that helps developers write algorithms. It is a text-based design tool and it uses a human-readable language. It's a structured english text that describes an algorithm.
<ide>
<ide> Every Algorithm in Free Code Camp curriculum can be solved using pseudocode and after that translated using javascript in a functional javascript code. | 1 |
Python | Python | fix failing static tests on master | e9add79160e3a16bb348e30f4e83386a371dbc1e | <ide><path>airflow/providers/amazon/aws/hooks/base_aws.py
<ide> def _get_credentials(self, region_name: Optional[str]) -> Tuple[boto3.session.Se
<ide> return session, None
<ide>
<ide> def get_client_type(
<del> self, client_type: str, region_name: Optional[str] = None, config: Optional[Config] = None,
<add> self,
<add> client_type: str,
<add> region_name: Optional[str] = None,
<add> config: Optional[Config] = None,
<ide> ) -> boto3.client:
<ide> """Get the underlying boto3 client using boto3 session"""
<ide> session, endpoint_url = self._get_credentials(region_name)
<ide> def get_client_type(
<ide> return session.client(client_type, endpoint_url=endpoint_url, config=config, verify=self.verify)
<ide>
<ide> def get_resource_type(
<del> self, resource_type: str, region_name: Optional[str] = None, config: Optional[Config] = None,
<add> self,
<add> resource_type: str,
<add> region_name: Optional[str] = None,
<add> config: Optional[Config] = None,
<ide> ) -> boto3.resource:
<ide> """Get the underlying boto3 resource using boto3 session"""
<ide> session, endpoint_url = self._get_credentials(region_name) | 1 |
Text | Text | add jsbeautify-loader to readme | e5ae047334d187b5fe17318fbc5ef58f6e500419 | <ide><path>README.md
<ide> Please see [Using Loaders](https://webpack.github.io/docs/using-loaders.html) fo
<ide> * [`jscs`](https://github.com/unindented/jscs-loader): PreLoader for style checking.
<ide> * [`injectable`](https://github.com/jauco/webpack-injectable): Allow to inject dependencies into modules
<ide> * [`transform`](https://github.com/webpack/transform-loader): Use browserify transforms as loader.
<add>* [`jsbeautify`](https://github.com/tomaszczechowski/jsbeautify-loader): Autoformatting code.
<ide>
<ide> For the full list of loaders, see [list of loaders](https://webpack.github.io/docs/list-of-loaders.html).
<ide> | 1 |
Javascript | Javascript | add missing keyboardavoidingview documentation | 0a1d7280eb5f50fed6b44b1b5244dedc22739f01 | <ide><path>Libraries/Components/Keyboard/KeyboardAvoidingView.js
<ide> type LayoutEvent = {
<ide>
<ide> const viewRef = 'VIEW';
<ide>
<add>/**
<add> * It is a component to solve the common problem of views that need to move out of the way of the virtual keyboard.
<add> * It can automatically adjust either its position or bottom padding based on the position of the keyboard.
<add> */
<ide> const KeyboardAvoidingView = React.createClass({
<ide> mixins: [TimerMixin],
<ide>
<ide><path>website/server/extractDocs.js
<ide> const components = [
<ide> '../Libraries/Components/DatePicker/DatePickerIOS.ios.js',
<ide> '../Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js',
<ide> '../Libraries/Image/Image.ios.js',
<add> '../Libraries/Components/Keyboard/KeyboardAvoidingView.js',
<ide> '../Libraries/CustomComponents/ListView/ListView.js',
<ide> '../Libraries/Components/MapView/MapView.js',
<ide> '../Libraries/Modal/Modal.js', | 2 |
Text | Text | fix a typo of a prop name | 7567a92ca75081ee8a2025661127d048b7916627 | <ide><path>docs/CommunicationIOS.md
<ide> class ImageBrowserApp extends React.Component {
<ide> render() {
<ide> return (
<ide> <View>
<del> {this.props.imageList.map(this.renderImage)}
<add> {this.props.images.map(this.renderImage)}
<ide> </View>
<ide> );
<ide> } | 1 |
Ruby | Ruby | apply suggestions from code review | 5e99ecfbdb0a33fd4cb831232abfd824b5b5ecb7 | <ide><path>Library/Homebrew/env_config.rb
<ide> module EnvConfig
<ide> default: 15,
<ide> },
<ide> HOMEBREW_FORBIDDEN_LICENSES: {
<del> description: "Use this environment variable to define a blacklist of space separated licenses and Homebrew " \
<add> description: "Use this environment variable to define a denylist of space separated licenses and Homebrew " \
<ide> "will avoid installing the packages with those licenses.",
<ide> },
<ide> HOMEBREW_FORCE_BREWED_CURL: {
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def puts_requirement_messages
<ide> $stderr.puts @requirement_messages
<ide> end
<ide>
<del> def env_forbidden_licenses
<del> Homebrew::EnvConfig.forbidden_licenses.split(" ")
<del> end
<del>
<del> def forbidden_license_check(f)
<del> return if ENV["HOMEBREW_FORBIDDEN_LICENSES"].blank?
<del>
<del> forbidden_licenses = env_forbidden_licenses
<add> def forbidden_license_check
<add> forbidden_licenses = Homebrew::EnvConfig.forbidden_licenses.split(" ")
<add> return if forbidden_licenses.blank?
<ide>
<del> if forbidden_licenses.include? f.license
<add> if forbidden_licenses.include? formula.license
<ide> raise CannotInstallFormulaError, <<~EOS
<del> #{f.name} has a forbidden license #{f.license}.
<add> #{formula.name} has a forbidden license #{formula.license}.
<ide> EOS
<ide> end
<ide>
<del> fi = FormulaInstaller.new(f)
<del> fi.compute_dependencies.each do |dep, _|
<add> compute_dependencies.each do |dep, _|
<ide> dep_f = dep.to_formula
<ide> next unless forbidden_licenses.include? dep_f.license
<ide> | 2 |
Python | Python | catch possible warnings | 2d841a8edc7acc3054937912b150d7a23764c41c | <ide><path>numpy/ma/tests/test_core.py
<ide> def test_varstd_specialcases(self):
<ide> self.assertTrue(method(0) is masked)
<ide> self.assertTrue(method(-1) is masked)
<ide> # Using a masked array as explicit output
<del> _ = method(out=mout)
<add> warn_ctx = WarningManager()
<add> warn_ctx.__enter__()
<add> try:
<add> warnings.simplefilter('ignore')
<add> _ = method(out=mout)
<add> finally:
<add> warn_ctx.__exit__()
<ide> self.assertTrue(mout is not masked)
<ide> assert_equal(mout.mask, True)
<ide> # Using a ndarray as explicit output
<del> _ = method(out=nout)
<add> warn_ctx = WarningManager()
<add> warn_ctx.__enter__()
<add> try:
<add> warnings.simplefilter('ignore')
<add> _ = method(out=nout)
<add> finally:
<add> warn_ctx.__exit__()
<ide> self.assertTrue(np.isnan(nout))
<ide> #
<ide> x = array(arange(10), mask=True) | 1 |
Javascript | Javascript | do the work after waiting | e8a5864707e0f898e08d97e64acc614dd0fa2025 | <ide><path>spec/git-repository-async-spec.js
<ide> describe('GitRepositoryAsync-js', () => {
<ide>
<ide> const repo = project2.getRepositories()[0].async
<ide> waitsFor(() => !repo._isRefreshing())
<del>
<del> const buffer = project2.getBuffers()[0]
<del>
<del> waitsFor(() => buffer.loaded)
<ide> runs(() => {
<del> buffer.append('changes')
<del>
<del> const statusHandler = jasmine.createSpy('statusHandler')
<del> repo.onDidChangeStatus(statusHandler)
<del> buffer.save()
<add> const buffer = project2.getBuffers()[0]
<ide>
<del> waitsFor(() => statusHandler.callCount > 0)
<add> waitsFor(() => buffer.loaded)
<ide> runs(() => {
<del> expect(statusHandler.callCount).toBe(1)
<del> expect(statusHandler).toHaveBeenCalledWith({path: buffer.getPath(), pathStatus: 256})
<add> buffer.append('changes')
<add>
<add> const statusHandler = jasmine.createSpy('statusHandler')
<add> repo.onDidChangeStatus(statusHandler)
<add> buffer.save()
<add>
<add> waitsFor(() => statusHandler.callCount > 0)
<add> runs(() => {
<add> expect(statusHandler.callCount).toBeGreaterThan(0)
<add> expect(statusHandler).toHaveBeenCalledWith({path: buffer.getPath(), pathStatus: 256})
<add> })
<ide> })
<ide> })
<ide> }) | 1 |
Ruby | Ruby | change directory only for git commands | 25442f20ec639375849f8be65000c367dbc6c5b8 | <ide><path>Library/Contributions/cmds/brew-test-bot.rb
<ide> def write_html
<ide> def self.run test, command, output_on_success = false
<ide> step = new test, command
<ide> step.puts_command
<del> `#{step.command} &>#{step.log_file_path}`
<add>
<add> command = "#{step.command} &>#{step.log_file_path}"
<add> if command.start_with? 'git '
<add> Dir.chdir HOMEBREW_REPOSITORY { `#{command}` }
<add> else
<add> `#{command}`
<add> end
<add>
<ide> step.status = $?.success? ? :passed : :failed
<ide> step.puts_result
<ide> puts IO.read(step.log_file_path) if output_on_success
<ide> def write_root_html status
<ide> end
<ide> end
<ide>
<add> def git arguments
<add> Dir.chdir HOMEBREW_REPOSITORY do
<add> `git #{arguments}`
<add> end
<add> end
<add>
<ide> def download
<ide> def current_sha1
<del> `git rev-parse --short HEAD`.strip
<add> git('rev-parse --short HEAD').strip
<ide> end
<ide>
<ide> def current_branch
<del> `git symbolic-ref HEAD`.slice!("refs/heads/").strip
<add> git('symbolic-ref HEAD').slice!("refs/heads/").strip
<ide> end
<ide>
<ide> @category = __method__
<ide> if @url
<del> `git am --abort 2>/dev/null`
<add> git 'am --abort 2>/dev/null'
<ide> test "brew update" if current_branch == "master"
<ide> @start_sha1 = current_sha1
<ide> test "brew pull --clean #{@url}"
<ide> def current_branch
<ide>
<ide> return unless @url and @start_sha1 != end_sha1 and steps.last.status == :passed
<ide>
<del> `git diff #{@start_sha1}..#{end_sha1} --name-status`.each_line do |line|
<add> git("diff #{@start_sha1}..#{end_sha1} --name-status`.each_line") do |line|
<ide> status, filename = line.split
<ide> # Don't try and do anything to removed files.
<ide> if (status == 'A' or status == 'M')
<ide> def cleanup
<ide> test "git reset --hard origin/master"
<ide> test "git clean --force -dx"
<ide> else
<del> `git diff --exit-code HEAD 2>/dev/null`
<add> git('diff --exit-code HEAD 2>/dev/null')
<ide> odie "Uncommitted changes, aborting." unless $?.success?
<ide> test "git reset --hard #{@start_sha1}" if @start_sha1
<ide> end
<ide> def self.run url
<ide> odie 'This command requires at least one argument containing a pull request number or formula.'
<ide> end
<ide>
<del>Dir.chdir HOMEBREW_REPOSITORY
<del>
<ide> ARGV.named.each do|arg|
<ide> Test.run arg
<ide> end | 1 |
Python | Python | use open() instead of tf.gfile.fastgfile() | c6a4f783080c5310ce0e3244daa31af57df12def | <ide><path>im2txt/im2txt/data/build_mscoco_data.py
<ide> def _to_sequence_example(image, decoder, vocab):
<ide> Returns:
<ide> A SequenceExample proto.
<ide> """
<del> with tf.gfile.FastGFile(image.filename, "r") as f:
<add> with open(image.filename, "r") as f:
<ide> encoded_image = f.read()
<ide>
<ide> try:
<ide><path>inception/inception/data/build_image_data.py
<ide> def _process_image(filename, coder):
<ide> width: integer, image width in pixels.
<ide> """
<ide> # Read the image file.
<del> image_data = tf.gfile.FastGFile(filename, 'r').read()
<add> with open(filename, 'r') as f:
<add> image_data = f.read()
<ide>
<ide> # Convert any PNG to JPEG's for consistency.
<ide> if _is_png(filename):
<ide><path>inception/inception/data/build_imagenet_data.py
<ide> def _process_image(filename, coder):
<ide> width: integer, image width in pixels.
<ide> """
<ide> # Read the image file.
<del> image_data = tf.gfile.FastGFile(filename, 'r').read()
<add> with open(filename, 'r') as f:
<add> image_data = f.read()
<ide>
<ide> # Clean the dirty data.
<ide> if _is_png(filename): | 3 |
PHP | PHP | fix travis ci build | cab7114662b8e2d563058cd0126fe95bc4c38021 | <ide><path>src/View/Widget/WidgetRegistry.php
<ide> class WidgetRegistry {
<ide> public function __construct(StringTemplate $templates, View $view, $widgets = []) {
<ide> $this->_templates = $templates;
<ide> if (!empty($widgets)) {
<del> if (is_string($widgets)){
<add> if (is_string($widgets)) {
<ide> $loader = new PhpConfig();
<ide> $widgets = $loader->read($widgets);
<ide> } | 1 |
Javascript | Javascript | fix typo in deeplinking docs | d53d121956914f401bf4ea797cdf2361db3325cf | <ide><path>Libraries/Linking/Linking.js
<ide> const LinkingManager = Platform.OS === 'android' ?
<ide> * openURL:(NSURL *)url
<ide> * options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
<ide> * {
<del> * return [RCTLinkingManager application:app openURL:url options:options];
<add> * return [RCTLinkingManager application:application openURL:url options:options];
<ide> * }
<ide> * ```
<ide> * | 1 |
Ruby | Ruby | factorize methods that are easily reversible [] | 7204d3c63e0c412c638b885fb552ec50e7c1520a | <ide><path>activerecord/lib/active_record/migration/command_recorder.rb
<ide> def #{method}(*args, &block) # def create_table(*args, &block)
<ide>
<ide> private
<ide>
<del> def invert_transaction(args, &block)
<del> [:transaction, args, block]
<add> module StraightReversions
<add> private
<add> { transaction: :transaction,
<add> create_table: :drop_table,
<add> create_join_table: :drop_join_table,
<add> add_column: :remove_column,
<add> add_timestamps: :remove_timestamps,
<add> add_reference: :remove_reference,
<add> }.each do |cmd, inv|
<add> [[inv, cmd], [cmd, inv]].each do |method, inverse|
<add> class_eval <<-EOV, __FILE__, __LINE__ + 1
<add> def invert_#{method}(args, &block) # def invert_create_table(args, &block)
<add> [:#{inverse}, args, block] # [:drop_table, args, block]
<add> end # end
<add> EOV
<add> end
<add> end
<ide> end
<ide>
<del> def invert_create_table(args, &block)
<del> [:drop_table, args, block]
<del> end
<add> include StraightReversions
<ide>
<ide> def invert_drop_table(args, &block)
<ide> if args.size == 1 && block == nil
<ide> raise ActiveRecord::IrreversibleMigration, "To avoid mistakes, drop_table is only reversible if given options or a block (can be empty)."
<ide> end
<del> [:create_table, args, block]
<del> end
<del>
<del> def invert_create_join_table(args, &block)
<del> [:drop_join_table, args, block]
<del> end
<del>
<del> def invert_drop_join_table(args, &block)
<del> [:create_join_table, args, block]
<add> super
<ide> end
<ide>
<ide> def invert_rename_table(args)
<ide> [:rename_table, args.reverse]
<ide> end
<ide>
<del> def invert_add_column(args)
<del> [:remove_column, args]
<del> end
<del>
<ide> def invert_remove_column(args)
<ide> raise ActiveRecord::IrreversibleMigration, "remove_column is only reversible if given a type." if args.size <= 2
<del> [:add_column, args]
<add> super
<ide> end
<ide>
<ide> def invert_rename_index(args)
<ide> def invert_remove_index(args)
<ide> [:add_index, [table, options.delete(:column), options]]
<ide> end
<ide>
<del> def invert_remove_timestamps(args)
<del> [:add_timestamps, args]
<del> end
<del>
<del> def invert_add_timestamps(args)
<del> [:remove_timestamps, args]
<del> end
<del>
<del> def invert_add_reference(args)
<del> [:remove_reference, args]
<del> end
<ide> alias :invert_add_belongs_to :invert_add_reference
<del>
<del> def invert_remove_reference(args)
<del> [:add_reference, args]
<del> end
<ide> alias :invert_remove_belongs_to :invert_remove_reference
<ide>
<ide> # Forwards any missing method call to the \target.
<ide><path>activerecord/test/cases/migration/command_recorder_test.rb
<ide> def test_invert_rename_table
<ide>
<ide> def test_invert_add_column
<ide> remove = @recorder.inverse_of :add_column, [:table, :column, :type, {}]
<del> assert_equal [:remove_column, [:table, :column, :type, {}]], remove
<add> assert_equal [:remove_column, [:table, :column, :type, {}], nil], remove
<ide> end
<ide>
<ide> def test_invert_remove_column
<ide> add = @recorder.inverse_of :remove_column, [:table, :column, :type, {}]
<del> assert_equal [:add_column, [:table, :column, :type, {}]], add
<add> assert_equal [:add_column, [:table, :column, :type, {}], nil], add
<ide> end
<ide>
<ide> def test_invert_remove_column_without_type
<ide> def test_invert_rename_index
<ide>
<ide> def test_invert_add_timestamps
<ide> remove = @recorder.inverse_of :add_timestamps, [:table]
<del> assert_equal [:remove_timestamps, [:table]], remove
<add> assert_equal [:remove_timestamps, [:table], nil], remove
<ide> end
<ide>
<ide> def test_invert_remove_timestamps
<ide> add = @recorder.inverse_of :remove_timestamps, [:table]
<del> assert_equal [:add_timestamps, [:table]], add
<add> assert_equal [:add_timestamps, [:table], nil], add
<ide> end
<ide>
<ide> def test_invert_add_reference
<ide> remove = @recorder.inverse_of :add_reference, [:table, :taggable, { polymorphic: true }]
<del> assert_equal [:remove_reference, [:table, :taggable, { polymorphic: true }]], remove
<add> assert_equal [:remove_reference, [:table, :taggable, { polymorphic: true }], nil], remove
<ide> end
<ide>
<ide> def test_invert_add_belongs_to_alias
<ide> remove = @recorder.inverse_of :add_belongs_to, [:table, :user]
<del> assert_equal [:remove_reference, [:table, :user]], remove
<add> assert_equal [:remove_reference, [:table, :user], nil], remove
<ide> end
<ide>
<ide> def test_invert_remove_reference
<ide> add = @recorder.inverse_of :remove_reference, [:table, :taggable, { polymorphic: true }]
<del> assert_equal [:add_reference, [:table, :taggable, { polymorphic: true }]], add
<add> assert_equal [:add_reference, [:table, :taggable, { polymorphic: true }], nil], add
<ide> end
<ide>
<ide> def test_invert_remove_belongs_to_alias
<ide> add = @recorder.inverse_of :remove_belongs_to, [:table, :user]
<del> assert_equal [:add_reference, [:table, :user]], add
<add> assert_equal [:add_reference, [:table, :user], nil], add
<ide> end
<ide> end
<ide> end | 2 |
Mixed | Ruby | fix error when using `with_options` with lambda | db5d26c9d70fb72b8aa3ea98709224dd13800024 | <ide><path>activerecord/CHANGELOG.md
<add>* Fixed error when using `with_options` with lambda.
<add>
<add> Fixes #9805.
<add>
<add> *Lauro Caetano*
<add>
<ide> * Treat blank UUID values as `nil`.
<ide>
<ide> Example:
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> require 'models/speedometer'
<ide> require 'models/reference'
<ide> require 'models/job'
<add>require 'models/college'
<add>require 'models/student'
<ide>
<ide> class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
<ide> fixtures :authors, :posts, :comments
<ide> def test_anonymous_has_many
<ide> dev.developer_projects.map(&:project_id).sort
<ide> end
<ide>
<add> def test_has_many_build_with_options
<add> college = College.create(name: 'UFMT')
<add> student = Student.create(active: true, college_id: college.id, name: 'Sarah')
<add>
<add> assert_equal college.students, Student.where(active: true, college_id: college.id)
<add> end
<add>
<ide> def test_create_from_association_should_respect_default_scope
<ide> car = Car.create(:name => 'honda')
<ide> assert_equal 'honda', car.name
<ide><path>activerecord/test/models/college.rb
<ide> require_dependency 'models/arunit2_model'
<add>require 'active_support/core_ext/object/with_options'
<ide>
<ide> class College < ARUnit2Model
<ide> has_many :courses
<add>
<add> with_options dependent: :destroy do |assoc|
<add> assoc.has_many :students, -> { where(active: true) }
<add> end
<ide> end
<ide><path>activerecord/test/models/student.rb
<ide> class Student < ActiveRecord::Base
<ide> has_and_belongs_to_many :lessons
<add> belongs_to :college
<ide> end
<ide><path>activerecord/test/schema/schema.rb
<ide> def create_table(*args, &block)
<ide>
<ide> create_table :students, force: true do |t|
<ide> t.string :name
<add> t.boolean :active
<add> t.integer :college_id
<ide> end
<ide>
<ide> create_table :subscribers, force: true, id: false do |t|
<ide><path>activesupport/lib/active_support/option_merger.rb
<ide> def initialize(context, options)
<ide>
<ide> private
<ide> def method_missing(method, *arguments, &block)
<del> if arguments.last.is_a?(Proc)
<add> if arguments.first.is_a?(Proc)
<ide> proc = arguments.pop
<ide> arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
<ide> else | 6 |
Python | Python | blackify, troubleshoot tests | 8e3cfd83fb778b03c8bd1537a6d9437461c48584 | <ide><path>numpy/core/tests/test_cython.py
<del>
<ide> import os
<ide> import shutil
<ide> import subprocess
<ide> cython = None
<ide> else:
<ide> from distutils.version import LooseVersion
<add>
<ide> # Cython 0.29.14 is required for Python 3.8 and there are
<ide> # other fixes in the 0.29 series that are needed even for earlier
<ide> # Python versions.
<ide> def install_temp(request, tmp_path):
<ide> here = os.path.dirname(__file__)
<ide> ext_dir = os.path.join(here, "examples")
<ide>
<del> #assert False
<del> tmp_path = tmp_path._str # str(tmp_path)
<add> tmp_path = tmp_path._str
<ide> cytest = os.path.join(tmp_path, "cytest")
<ide>
<ide> shutil.copytree(ext_dir, cytest)
<ide> # build the examples and "install" them into a temporary directory
<del>
<del> build_dir = os.path.join(tmp_path, "examples")
<add>
<ide> install_log = os.path.join(tmp_path, "tmp_install_log.txt")
<del> subprocess.check_call([sys.executable, "setup.py", "build", "install",
<del> "--prefix", os.path.join(tmp_path, "installdir"),
<del> "--single-version-externally-managed",
<del> "--record", install_log,
<del> ],
<del> cwd=cytest,
<del> )
<add> subprocess.check_call(
<add> [
<add> sys.executable,
<add> "setup.py",
<add> "build",
<add> "install",
<add> "--prefix",
<add> os.path.join(tmp_path, "installdir"),
<add> "--single-version-externally-managed",
<add> "--record",
<add> install_log,
<add> ],
<add> cwd=cytest,
<add> )
<ide>
<ide> # In order to import the built module, we need its path to sys.path
<ide> # so parse that out of the record
<ide> with open(install_log) as fid:
<ide> for line in fid:
<del> if 'checks' in line:
<add> if "checks" in line:
<ide> sys.path.append(os.path.dirname(line))
<ide> break
<ide> else:
<ide> def test_is_timedelta64_object(install_temp):
<ide> assert not checks.is_td64(1)
<ide> assert not checks.is_td64(None)
<ide> assert not checks.is_td64("foo")
<del> assert not checks.is_td64(np.datetime64("now"))
<add> assert not checks.is_td64(np.datetime64("now", "s"))
<ide>
<ide>
<ide> def test_is_datetime64_object(install_temp):
<ide> import checks
<ide>
<del> assert checks.is_dt64(np.datetime64(1234))
<ide> assert checks.is_dt64(np.datetime64(1234, "ns"))
<ide> assert checks.is_dt64(np.datetime64("NaT", "ns"))
<ide>
<ide> def test_get_datetime64_unit(install_temp):
<ide>
<ide> dt64 = np.datetime64("2016-01-01", "ns")
<ide> result = checks.get_dt64_unit(dt64)
<del> expected = 11
<add> expected = 10
<ide> assert result == expected
<ide>
<ide> td64 = np.timedelta64(12345, "h")
<del> result = checks.get_dt64_unit(dt64)
<add> result = checks.get_dt64_unit(td64)
<ide> expected = 5
<ide> assert result == expected | 1 |
Text | Text | add focus for @kuychaco | 50b8d376499623ebe5f49688ad003333fc21610e | <ide><path>docs/focus/2018-03-05.md
<ide> - Finish "Remember me" within the credential dialog (@smashwilson) [#1327](https://github.com/atom/github/pull/1327)
<ide> - Write up `docs/vision` from meeting notes (@smashwilson)
<ide> - Kick-start our GPG pinentry handling (@smashwilson) [#846](https://github.com/atom/github/pull/846)
<add> - Build UI for adding co-authors, much like Desktop's UI/UX - desktop.github.com/features/co-authors/
<add>
<ide> - Teletype
<ide> - Tree-sitter
<ide> - Carrying over goals from previous weeks: | 1 |
Javascript | Javascript | assign deep defaults for custom config | 369ac488e09b836d3f83d7f35e3b8a9bf72f74be | <ide><path>packages/next-server/server/config.js
<ide> const defaultConfig = {
<ide> }
<ide> }
<ide>
<add>function assignDefaults (userConfig) {
<add> Object.keys(userConfig).forEach(key => {
<add> const maybeObject = userConfig[key]
<add> if ((!!maybeObject) && (maybeObject.constructor === Object)) {
<add> userConfig[key] = {
<add> ...(defaultConfig[key] || {}),
<add> ...userConfig[key]
<add> }
<add> }
<add> })
<add>
<add> return { ...defaultConfig, ...userConfig }
<add>}
<add>
<ide> function normalizeConfig (phase, config) {
<ide> if (typeof config === 'function') {
<ide> return config(phase, { defaultConfig })
<ide> function normalizeConfig (phase, config) {
<ide>
<ide> export default function loadConfig (phase, dir, customConfig) {
<ide> if (customConfig) {
<del> return { ...defaultConfig, configOrigin: 'server', ...customConfig }
<add> return assignDefaults({ configOrigin: 'server', ...customConfig })
<ide> }
<ide> const path = findUp.sync(CONFIG_FILE, {
<ide> cwd: dir
<ide> export default function loadConfig (phase, dir, customConfig) {
<ide> if (userConfig.target && !targets.includes(userConfig.target)) {
<ide> throw new Error(`Specified target is invalid. Provided: "${userConfig.target}" should be one of ${targets.join(', ')}`)
<ide> }
<del> if (userConfig.experimental) {
<del> userConfig.experimental = {
<del> ...defaultConfig.experimental,
<del> ...userConfig.experimental
<del> }
<del> }
<del> if (userConfig.onDemandEntries) {
<del> userConfig.onDemandEntries = {
<del> ...defaultConfig.onDemandEntries,
<del> ...userConfig.onDemandEntries
<del> }
<del> }
<del> return { ...defaultConfig, configOrigin: CONFIG_FILE, ...userConfig }
<add> return assignDefaults({ configOrigin: CONFIG_FILE, ...userConfig })
<ide> }
<ide>
<ide> return defaultConfig
<ide><path>test/isolated/config.test.js
<ide> describe('config', () => {
<ide> expect(config.defaultConfig).toBeDefined()
<ide> })
<ide>
<add> it('Should assign object defaults deeply to user config', () => {
<add> const config = loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn)
<add> expect(config.distDir).toEqual('.next')
<add> expect(config.onDemandEntries.maxInactiveAge).toBeDefined()
<add> })
<add>
<ide> it('Should pass the customConfig correctly', () => {
<ide> const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, { customConfig: true })
<ide> expect(config.customConfig).toBe(true)
<ide> describe('config', () => {
<ide> expect(config.webpack).toBe(null)
<ide> })
<ide>
<add> it('Should assign object defaults deeply to customConfig', () => {
<add> const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, { customConfig: true, onDemandEntries: { custom: true } })
<add> expect(config.customConfig).toBe(true)
<add> expect(config.onDemandEntries.maxInactiveAge).toBeDefined()
<add> })
<add>
<add> it('Should allow setting objects which do not have defaults', () => {
<add> const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, { bogusSetting: { custom: true } })
<add> expect(config.bogusSetting).toBeDefined()
<add> expect(config.bogusSetting.custom).toBe(true)
<add> })
<add>
<add> it('Should override defaults for arrays from user arrays', () => {
<add> const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, { pageExtensions: ['.bogus'] })
<add> expect(config.pageExtensions).toEqual(['.bogus'])
<add> })
<add>
<ide> it('Should throw when an invalid target is provided', () => {
<ide> try {
<ide> loadConfig(PHASE_DEVELOPMENT_SERVER, join(__dirname, '_resolvedata', 'invalid-target')) | 2 |
Python | Python | add decayexponent support to lights | d848e13d346c5087d09b579066e241268d0ca6d0 | <ide><path>utils/exporters/blender/addons/io_three/constants.py
<ide> WARNING = 'warning'
<ide> INFO = 'info'
<ide> DEBUG = 'debug'
<add>DISABLED = 'disabled'
<ide>
<ide> NONE = 'None'
<ide> MSGPACK = 'msgpack'
<ide> DISTANCE = 'distance'
<ide> ASPECT = 'aspect'
<ide> ANGLE = 'angle'
<add>DECAY = 'decayExponent'
<ide>
<ide> FOV = 'fov'
<ide> ASPECT = 'aspect'
<ide><path>utils/exporters/blender/addons/io_three/exporter/api/light.py
<ide> def intensity(lamp):
<ide> """
<ide> logger.debug("light.intensity(%s)", lamp)
<ide> return round(lamp.energy, 2)
<add>
<add># mapping enum values to decay exponent
<add>__FALLOFF_TO_EXP = {
<add> 'CONSTANT': 0,
<add> 'INVERSE_LINEAR': 1,
<add> 'INVERSE_SQUARE': 2,
<add> 'CUSTOM_CURVE': 0,
<add> 'LINEAR_QUADRATIC_WEIGHTED': 2
<add>}
<add>
<add>@_lamp
<add>def falloff(lamp):
<add> """
<add>
<add> :param lamp:
<add> :rtype: float
<add>
<add> """
<add> logger.debug("light.falloff(%s)", lamp)
<add> return __FALLOFF_TO_EXP[lamp.falloff_type]
<ide><path>utils/exporters/blender/addons/io_three/exporter/object.py
<ide> def _init_light(self):
<ide> # self[constants.DISTANCE] = api.light.distance(self.data)
<ide> self[constants.DISTANCE] = 0;
<ide>
<del> if self[constants.TYPE] == constants.SPOT_LIGHT:
<add> lightType = self[constants.TYPE]
<add> if lightType == constants.SPOT_LIGHT:
<ide> self[constants.ANGLE] = api.light.angle(self.data)
<add> self[constants.DECAY] = api.light.falloff(self.data)
<add> elif lightType == constants.POINT_LIGHT:
<add> self[constants.DECAY] = api.light.falloff(self.data)
<ide>
<ide> def _init_mesh(self):
<ide> """Initialize mesh attributes""" | 3 |
Javascript | Javascript | reduce usage of require('util') | b51a546488698660f00aa5221bbe908d6e01f4e0 | <ide><path>lib/internal/errors.js
<ide> function lazyInternalUtil() {
<ide> return internalUtil;
<ide> }
<ide>
<add>let internalUtilInspect = null;
<add>function lazyInternalUtilInspect() {
<add> if (!internalUtilInspect) {
<add> internalUtilInspect = require('internal/util/inspect');
<add> }
<add> return internalUtilInspect;
<add>}
<add>
<ide> let buffer;
<ide> function lazyBuffer() {
<ide> if (buffer === undefined)
<ide> function E(sym, val, def, ...otherClasses) {
<ide> function getMessage(key, args, self) {
<ide> const msg = messages.get(key);
<ide>
<del> if (util === undefined) util = require('util');
<ide> if (assert === undefined) assert = require('internal/assert');
<ide>
<ide> if (typeof msg === 'function') {
<ide> function getMessage(key, args, self) {
<ide> return msg;
<ide>
<ide> args.unshift(msg);
<del> return util.format.apply(null, args);
<add> return lazyInternalUtilInspect().format.apply(null, args);
<ide> }
<ide>
<ide> let uvBinding;
<ide> E('ERR_INVALID_ARG_TYPE',
<ide> return msg;
<ide> }, TypeError);
<ide> E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => {
<del> let inspected = util.inspect(value);
<add> let inspected = lazyInternalUtilInspect().inspect(value);
<ide> if (inspected.length > 128) {
<ide> inspected = `${inspected.slice(0, 128)}...`;
<ide> } | 1 |
PHP | PHP | fix newlines around psr2 | 2b40e56493c4c2488753b1a5faa4a35abf1f9cde | <ide><path>src/Auth/BasicAuthenticate.php
<ide> */
<ide> class BasicAuthenticate extends BaseAuthenticate
<ide> {
<del>
<ide> /**
<ide> * Authenticate a user using HTTP auth. Will use the configured User model and attempt a
<ide> * login using HTTP auth.
<ide><path>src/Auth/ControllerAuthorize.php
<ide> */
<ide> class ControllerAuthorize extends BaseAuthorize
<ide> {
<del>
<ide> /**
<ide> * Controller for the request.
<ide> *
<ide><path>src/Auth/DefaultPasswordHasher.php
<ide> */
<ide> class DefaultPasswordHasher extends AbstractPasswordHasher
<ide> {
<del>
<ide> /**
<ide> * Default config for this object.
<ide> *
<ide><path>src/Auth/DigestAuthenticate.php
<ide> */
<ide> class DigestAuthenticate extends BasicAuthenticate
<ide> {
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide><path>src/Auth/FallbackPasswordHasher.php
<ide> */
<ide> class FallbackPasswordHasher extends AbstractPasswordHasher
<ide> {
<del>
<ide> /**
<ide> * Default config for this object.
<ide> *
<ide><path>src/Auth/FormAuthenticate.php
<ide> */
<ide> class FormAuthenticate extends BaseAuthenticate
<ide> {
<del>
<ide> /**
<ide> * Checks the fields to ensure they are supplied.
<ide> *
<ide><path>src/Auth/PasswordHasherFactory.php
<ide> */
<ide> class PasswordHasherFactory
<ide> {
<del>
<ide> /**
<ide> * Returns password hasher object out of a hasher name or a configuration array
<ide> *
<ide><path>src/Auth/Storage/MemoryStorage.php
<ide> */
<ide> class MemoryStorage implements StorageInterface
<ide> {
<del>
<ide> /**
<ide> * User record.
<ide> *
<ide><path>src/Auth/WeakPasswordHasher.php
<ide> */
<ide> class WeakPasswordHasher extends AbstractPasswordHasher
<ide> {
<del>
<ide> /**
<ide> * Default config for this object.
<ide> *
<ide><path>src/Cache/Cache.php
<ide> */
<ide> class Cache
<ide> {
<del>
<ide> use StaticConfigTrait;
<ide>
<ide> /**
<ide><path>src/Cache/CacheRegistry.php
<ide> */
<ide> class CacheRegistry extends ObjectRegistry
<ide> {
<del>
<ide> /**
<ide> * Resolve a cache engine classname.
<ide> *
<ide><path>src/Cache/Engine/ApcuEngine.php
<ide> */
<ide> class ApcuEngine extends CacheEngine
<ide> {
<del>
<ide> /**
<ide> * Contains the compiled group names
<ide> * (prefixed with the global configuration prefix)
<ide><path>src/Cache/Engine/FileEngine.php
<ide> */
<ide> class FileEngine extends CacheEngine
<ide> {
<del>
<ide> /**
<ide> * Instance of SplFileObject class
<ide> *
<ide><path>src/Cache/Engine/MemcachedEngine.php
<ide> */
<ide> class MemcachedEngine extends CacheEngine
<ide> {
<del>
<ide> /**
<ide> * memcached wrapper.
<ide> *
<ide><path>src/Cache/Engine/NullEngine.php
<ide> */
<ide> class NullEngine extends CacheEngine
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Cache/Engine/RedisEngine.php
<ide> */
<ide> class RedisEngine extends CacheEngine
<ide> {
<del>
<ide> /**
<ide> * Redis wrapper.
<ide> *
<ide><path>src/Cache/Engine/WincacheEngine.php
<ide> */
<ide> class WincacheEngine extends CacheEngine
<ide> {
<del>
<ide> /**
<ide> * Contains the compiled group names
<ide> * (prefixed with the global configuration prefix)
<ide><path>src/Cache/Engine/XcacheEngine.php
<ide> */
<ide> class XcacheEngine extends CacheEngine
<ide> {
<del>
<ide> /**
<ide> * The default config used unless overridden by runtime configuration
<ide> *
<ide><path>src/Collection/Collection.php
<ide> */
<ide> class Collection extends IteratorIterator implements CollectionInterface, Serializable
<ide> {
<del>
<ide> use CollectionTrait;
<ide>
<ide> /**
<ide><path>src/Collection/CollectionInterface.php
<ide> */
<ide> interface CollectionInterface extends Iterator, JsonSerializable
<ide> {
<del>
<ide> /**
<ide> * Executes the passed callable for each of the elements in this collection
<ide> * and passes both the value and key for them on each step.
<ide><path>src/Collection/CollectionTrait.php
<ide> */
<ide> trait CollectionTrait
<ide> {
<del>
<ide> use ExtractTrait;
<ide>
<ide> /**
<ide><path>src/Collection/ExtractTrait.php
<ide> */
<ide> trait ExtractTrait
<ide> {
<del>
<ide> /**
<ide> * Returns a callable that can be used to extract a property or column from
<ide> * an array or object based on a dot separated path.
<ide><path>src/Collection/Iterator/BufferedIterator.php
<ide> */
<ide> class BufferedIterator extends Collection implements Countable, Serializable
<ide> {
<del>
<ide> /**
<ide> * The in-memory cache containing results from previous iterators
<ide> *
<ide><path>src/Collection/Iterator/ExtractIterator.php
<ide> */
<ide> class ExtractIterator extends Collection
<ide> {
<del>
<ide> /**
<ide> * A callable responsible for extracting a single value for each
<ide> * item in the collection.
<ide><path>src/Collection/Iterator/FilterIterator.php
<ide> */
<ide> class FilterIterator extends Collection
<ide> {
<del>
<ide> /**
<ide> * The callback used to filter the elements in this collection
<ide> *
<ide><path>src/Collection/Iterator/InsertIterator.php
<ide> */
<ide> class InsertIterator extends Collection
<ide> {
<del>
<ide> /**
<ide> * The collection from which to extract the values to be inserted
<ide> *
<ide><path>src/Collection/Iterator/MapReduce.php
<ide> */
<ide> class MapReduce implements IteratorAggregate
<ide> {
<del>
<ide> /**
<ide> * Holds the shuffled results that were emitted from the map
<ide> * phase
<ide><path>src/Collection/Iterator/NoChildrenIterator.php
<ide> */
<ide> class NoChildrenIterator extends Collection implements RecursiveIterator
<ide> {
<del>
<ide> /**
<ide> * Returns false as there are no children iterators in this collection
<ide> *
<ide><path>src/Collection/Iterator/ReplaceIterator.php
<ide> */
<ide> class ReplaceIterator extends Collection
<ide> {
<del>
<ide> /**
<ide> * The callback function to be used to transform values
<ide> *
<ide><path>src/Collection/Iterator/SortIterator.php
<ide> */
<ide> class SortIterator extends Collection
<ide> {
<del>
<ide> /**
<ide> * Wraps this iterator around the passed items so when iterated they are returned
<ide> * in order.
<ide><path>src/Collection/Iterator/StoppableIterator.php
<ide> */
<ide> class StoppableIterator extends Collection
<ide> {
<del>
<ide> /**
<ide> * The condition to evaluate for each item of the collection
<ide> *
<ide><path>src/Collection/Iterator/TreeIterator.php
<ide> */
<ide> class TreeIterator extends RecursiveIteratorIterator
<ide> {
<del>
<ide> use CollectionTrait;
<ide>
<ide> /**
<ide><path>src/Collection/Iterator/TreePrinter.php
<ide> */
<ide> class TreePrinter extends RecursiveIteratorIterator
<ide> {
<del>
<ide> use CollectionTrait;
<ide>
<ide> /**
<ide><path>src/Collection/Iterator/UnfoldIterator.php
<ide> */
<ide> class UnfoldIterator extends IteratorIterator implements RecursiveIterator
<ide> {
<del>
<ide> /**
<ide> * A function that is passed each element in this iterator and
<ide> * must return an array or Traversable object.
<ide><path>src/Collection/Iterator/ZipIterator.php
<ide> */
<ide> class ZipIterator extends MultipleIterator implements CollectionInterface, Serializable
<ide> {
<del>
<ide> use CollectionTrait;
<ide>
<ide> /**
<ide><path>src/Console/CommandFactory.php
<ide> */
<ide> class CommandFactory implements CommandFactoryInterface
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Console/ConsoleErrorHandler.php
<ide> */
<ide> class ConsoleErrorHandler extends BaseErrorHandler
<ide> {
<del>
<ide> /**
<ide> * Standard error stream.
<ide> *
<ide><path>src/Console/ConsoleInput.php
<ide> */
<ide> class ConsoleInput
<ide> {
<del>
<ide> /**
<ide> * Input value.
<ide> *
<ide><path>src/Console/ConsoleInputArgument.php
<ide> */
<ide> class ConsoleInputArgument
<ide> {
<del>
<ide> /**
<ide> * Name of the argument.
<ide> *
<ide><path>src/Console/ConsoleInputOption.php
<ide> */
<ide> class ConsoleInputOption
<ide> {
<del>
<ide> /**
<ide> * Name of the option
<ide> *
<ide><path>src/Console/ConsoleInputSubcommand.php
<ide> */
<ide> class ConsoleInputSubcommand
<ide> {
<del>
<ide> /**
<ide> * Name of the subcommand
<ide> *
<ide><path>src/Console/ConsoleIo.php
<ide> */
<ide> class ConsoleIo
<ide> {
<del>
<ide> /**
<ide> * The output stream
<ide> *
<ide><path>src/Console/ConsoleOptionParser.php
<ide> */
<ide> class ConsoleOptionParser
<ide> {
<del>
<ide> /**
<ide> * Description text - displays before options when help is generated
<ide> *
<ide><path>src/Console/ConsoleOutput.php
<ide> */
<ide> class ConsoleOutput
<ide> {
<del>
<ide> /**
<ide> * Raw output constant - no modification of output text.
<ide> *
<ide><path>src/Console/Exception/MissingShellException.php
<ide> */
<ide> class MissingShellException extends ConsoleException
<ide> {
<del>
<ide> protected $_messageTemplate = 'Shell class for "%s" could not be found. If you are trying to use a plugin shell, that was loaded via $this->addPlugin(), you may need to update bin/cake.php to match https://github.com/cakephp/app/tree/master/bin/cake.php';
<ide> }
<ide><path>src/Console/Exception/MissingShellMethodException.php
<ide> */
<ide> class MissingShellMethodException extends ConsoleException
<ide> {
<del>
<ide> protected $_messageTemplate = "Unknown command %1\$s %2\$s.\nFor usage try `cake %1\$s --help`";
<ide> }
<ide><path>src/Console/HelpFormatter.php
<ide> */
<ide> class HelpFormatter
<ide> {
<del>
<ide> /**
<ide> * The maximum number of arguments shown when generating usage.
<ide> *
<ide><path>src/Console/HelperRegistry.php
<ide> */
<ide> class HelperRegistry extends ObjectRegistry
<ide> {
<del>
<ide> /**
<ide> * Shell to use to set params to tasks.
<ide> *
<ide><path>src/Console/Shell.php
<ide> */
<ide> class Shell
<ide> {
<del>
<ide> use LocatorAwareTrait;
<ide> use LogTrait;
<ide> use MergeVariablesTrait;
<ide><path>src/Console/ShellDispatcher.php
<ide> */
<ide> class ShellDispatcher
<ide> {
<del>
<ide> /**
<ide> * Contains arguments parsed from the command line.
<ide> *
<ide><path>src/Console/TaskRegistry.php
<ide> */
<ide> class TaskRegistry extends ObjectRegistry
<ide> {
<del>
<ide> /**
<ide> * Shell to use to set params to tasks.
<ide> *
<ide><path>src/Controller/Component/AuthComponent.php
<ide> */
<ide> class AuthComponent extends Component
<ide> {
<del>
<ide> use EventDispatcherTrait;
<ide>
<ide> /**
<ide><path>src/Controller/Component/CsrfComponent.php
<ide> */
<ide> class CsrfComponent extends Component
<ide> {
<del>
<ide> /**
<ide> * Default config for the CSRF handling.
<ide> *
<ide><path>src/Controller/Component/FlashComponent.php
<ide> */
<ide> class FlashComponent extends Component
<ide> {
<del>
<ide> /**
<ide> * The Session object instance
<ide> *
<ide><path>src/Controller/Component/PaginatorComponent.php
<ide> */
<ide> class PaginatorComponent extends Component
<ide> {
<del>
<ide> /**
<ide> * Default pagination settings.
<ide> *
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> */
<ide> class RequestHandlerComponent extends Component
<ide> {
<del>
<ide> /**
<ide> * @var bool
<ide> * @deprecated 3.4.0 Unused. Will be removed in 4.0.0
<ide><path>src/Controller/Component/SecurityComponent.php
<ide> */
<ide> class SecurityComponent extends Component
<ide> {
<del>
<ide> /**
<ide> * Default message used for exceptions thrown
<ide> */
<ide><path>src/Controller/ComponentRegistry.php
<ide> */
<ide> class ComponentRegistry extends ObjectRegistry implements EventDispatcherInterface
<ide> {
<del>
<ide> use EventDispatcherTrait;
<ide>
<ide> /**
<ide><path>src/Controller/Controller.php
<ide> */
<ide> class Controller implements EventListenerInterface, EventDispatcherInterface
<ide> {
<del>
<ide> use EventDispatcherTrait;
<ide> use LocatorAwareTrait;
<ide> use LogTrait;
<ide><path>src/Controller/ErrorController.php
<ide> */
<ide> class ErrorController extends Controller
<ide> {
<del>
<ide> /**
<ide> * Initialization hook method.
<ide> *
<ide><path>src/Controller/Exception/MissingActionException.php
<ide> */
<ide> class MissingActionException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Controller/Exception/MissingComponentException.php
<ide> */
<ide> class MissingComponentException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'Component class %s could not be found.';
<ide> }
<ide><path>src/Core/App.php
<ide> */
<ide> class App
<ide> {
<del>
<ide> /**
<ide> * Return the class name namespaced. This method checks if the class is defined on the
<ide> * application/plugin, otherwise try to load from the CakePHP core
<ide><path>src/Core/BasePlugin.php
<ide> */
<ide> class BasePlugin implements PluginInterface
<ide> {
<del>
<ide> /**
<ide> * Do bootstrapping or not
<ide> *
<ide><path>src/Core/ClassLoader.php
<ide> */
<ide> class ClassLoader
<ide> {
<del>
<ide> /**
<ide> * An associative array where the key is a namespace prefix and the value
<ide> * is an array of base directories for classes in that namespace.
<ide><path>src/Core/Configure.php
<ide> */
<ide> class Configure
<ide> {
<del>
<ide> /**
<ide> * Array of values currently stored in Configure.
<ide> *
<ide><path>src/Core/Configure/ConfigEngineInterface.php
<ide> */
<ide> interface ConfigEngineInterface
<ide> {
<del>
<ide> /**
<ide> * Read a configuration file/storage key
<ide> *
<ide><path>src/Core/Configure/Engine/IniConfig.php
<ide> */
<ide> class IniConfig implements ConfigEngineInterface
<ide> {
<del>
<ide> use FileConfigTrait;
<ide>
<ide> /**
<ide><path>src/Core/Configure/Engine/JsonConfig.php
<ide> */
<ide> class JsonConfig implements ConfigEngineInterface
<ide> {
<del>
<ide> use FileConfigTrait;
<ide>
<ide> /**
<ide><path>src/Core/Configure/Engine/PhpConfig.php
<ide> */
<ide> class PhpConfig implements ConfigEngineInterface
<ide> {
<del>
<ide> use FileConfigTrait;
<ide>
<ide> /**
<ide><path>src/Core/Configure/FileConfigTrait.php
<ide> */
<ide> trait FileConfigTrait
<ide> {
<del>
<ide> /**
<ide> * The path this engine finds files on.
<ide> *
<ide><path>src/Core/ConventionsTrait.php
<ide> */
<ide> trait ConventionsTrait
<ide> {
<del>
<ide> /**
<ide> * Creates a fixture name
<ide> *
<ide><path>src/Core/Exception/Exception.php
<ide> */
<ide> class Exception extends RuntimeException
<ide> {
<del>
<ide> /**
<ide> * Array of attributes that are passed in from the constructor, and
<ide> * made available in the view when a development error is displayed.
<ide><path>src/Core/Exception/MissingPluginException.php
<ide> */
<ide> class MissingPluginException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'Plugin %s could not be found.';
<ide> }
<ide><path>src/Core/InstanceConfigTrait.php
<ide> */
<ide> trait InstanceConfigTrait
<ide> {
<del>
<ide> /**
<ide> * Runtime config
<ide> *
<ide><path>src/Core/ObjectRegistry.php
<ide> */
<ide> abstract class ObjectRegistry implements Countable, IteratorAggregate
<ide> {
<del>
<ide> /**
<ide> * Map of loaded objects.
<ide> *
<ide><path>src/Core/Plugin.php
<ide> */
<ide> class Plugin
<ide> {
<del>
<ide> /**
<ide> * Holds a list of all loaded plugins and their configuration
<ide> *
<ide><path>src/Core/Retry/CommandRetry.php
<ide> */
<ide> class CommandRetry
<ide> {
<del>
<ide> /**
<ide> * The strategy to follow should the executed action fail.
<ide> *
<ide><path>src/Core/StaticConfigTrait.php
<ide> */
<ide> trait StaticConfigTrait
<ide> {
<del>
<ide> /**
<ide> * Configuration sets.
<ide> *
<ide><path>src/Database/Connection.php
<ide> */
<ide> class Connection implements ConnectionInterface
<ide> {
<del>
<ide> use TypeConverterTrait;
<ide>
<ide> /**
<ide><path>src/Database/Dialect/MysqlDialectTrait.php
<ide> */
<ide> trait MysqlDialectTrait
<ide> {
<del>
<ide> use SqlDialectTrait;
<ide>
<ide> /**
<ide><path>src/Database/Dialect/PostgresDialectTrait.php
<ide> */
<ide> trait PostgresDialectTrait
<ide> {
<del>
<ide> use SqlDialectTrait;
<ide>
<ide> /**
<ide><path>src/Database/Dialect/SqliteDialectTrait.php
<ide> */
<ide> trait SqliteDialectTrait
<ide> {
<del>
<ide> use SqlDialectTrait;
<ide> use TupleComparisonTranslatorTrait;
<ide>
<ide><path>src/Database/Dialect/SqlserverDialectTrait.php
<ide> */
<ide> trait SqlserverDialectTrait
<ide> {
<del>
<ide> use SqlDialectTrait;
<ide> use TupleComparisonTranslatorTrait;
<ide>
<ide><path>src/Database/Dialect/TupleComparisonTranslatorTrait.php
<ide> */
<ide> trait TupleComparisonTranslatorTrait
<ide> {
<del>
<ide> /**
<ide> * Receives a TupleExpression and changes it so that it conforms to this
<ide> * SQL dialect.
<ide><path>src/Database/Driver/Mysql.php
<ide> */
<ide> class Mysql extends Driver
<ide> {
<del>
<ide> use MysqlDialectTrait;
<ide>
<ide> /**
<ide><path>src/Database/Driver/PDODriverTrait.php
<ide> */
<ide> trait PDODriverTrait
<ide> {
<del>
<ide> /**
<ide> * Instance of PDO.
<ide> *
<ide><path>src/Database/Driver/Postgres.php
<ide> */
<ide> class Postgres extends Driver
<ide> {
<del>
<ide> use PostgresDialectTrait;
<ide>
<ide> /**
<ide><path>src/Database/Driver/Sqlite.php
<ide> */
<ide> class Sqlite extends Driver
<ide> {
<del>
<ide> use SqliteDialectTrait;
<ide>
<ide> /**
<ide><path>src/Database/Driver/Sqlserver.php
<ide> */
<ide> class Sqlserver extends Driver
<ide> {
<del>
<ide> use SqlserverDialectTrait;
<ide>
<ide> /**
<ide><path>src/Database/Exception.php
<ide> */
<ide> class Exception extends CakeException
<ide> {
<del>
<ide> }
<ide><path>src/Database/Exception/MissingConnectionException.php
<ide> */
<ide> class MissingConnectionException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Database/Exception/MissingDriverException.php
<ide> */
<ide> class MissingDriverException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Database/Exception/MissingExtensionException.php
<ide> */
<ide> class MissingExtensionException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Database/Exception/NestedTransactionRollbackException.php
<ide> */
<ide> class NestedTransactionRollbackException extends Exception
<ide> {
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide><path>src/Database/Expression/BetweenExpression.php
<ide> */
<ide> class BetweenExpression implements ExpressionInterface, FieldInterface
<ide> {
<del>
<ide> use ExpressionTypeCasterTrait;
<ide> use FieldTrait;
<ide>
<ide><path>src/Database/Expression/CaseExpression.php
<ide> */
<ide> class CaseExpression implements ExpressionInterface
<ide> {
<del>
<ide> use ExpressionTypeCasterTrait;
<ide>
<ide> /**
<ide><path>src/Database/Expression/Comparison.php
<ide> */
<ide> class Comparison implements ExpressionInterface, FieldInterface
<ide> {
<del>
<ide> use ExpressionTypeCasterTrait;
<ide> use FieldTrait;
<ide>
<ide><path>src/Database/Expression/FieldInterface.php
<ide> */
<ide> interface FieldInterface
<ide> {
<del>
<ide> /**
<ide> * Sets the field name
<ide> *
<ide><path>src/Database/Expression/FieldTrait.php
<ide> */
<ide> trait FieldTrait
<ide> {
<del>
<ide> /**
<ide> * The field name or expression to be used in the left hand side of the operator
<ide> *
<ide><path>src/Database/Expression/FunctionExpression.php
<ide> */
<ide> class FunctionExpression extends QueryExpression implements TypedResultInterface
<ide> {
<del>
<ide> use ExpressionTypeCasterTrait;
<ide> use TypedResultTrait;
<ide>
<ide><path>src/Database/Expression/IdentifierExpression.php
<ide> */
<ide> class IdentifierExpression implements ExpressionInterface
<ide> {
<del>
<ide> /**
<ide> * Holds the identifier string
<ide> *
<ide><path>src/Database/Expression/OrderByExpression.php
<ide> */
<ide> class OrderByExpression extends QueryExpression
<ide> {
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide><path>src/Database/Expression/QueryExpression.php
<ide> */
<ide> class QueryExpression implements ExpressionInterface, Countable
<ide> {
<del>
<ide> use TypeMapTrait;
<ide>
<ide> /**
<ide><path>src/Database/Expression/TupleComparison.php
<ide> */
<ide> class TupleComparison extends Comparison
<ide> {
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide><path>src/Database/Expression/UnaryExpression.php
<ide> */
<ide> class UnaryExpression implements ExpressionInterface
<ide> {
<del>
<ide> /**
<ide> * Indicates that the operation is in pre-order
<ide> *
<ide><path>src/Database/Expression/ValuesExpression.php
<ide> */
<ide> class ValuesExpression implements ExpressionInterface
<ide> {
<del>
<ide> use ExpressionTypeCasterTrait;
<ide> use TypeMapTrait;
<ide>
<ide><path>src/Database/ExpressionInterface.php
<ide> */
<ide> interface ExpressionInterface
<ide> {
<del>
<ide> /**
<ide> * Converts the Node into a SQL string fragment.
<ide> *
<ide><path>src/Database/FieldTypeConverter.php
<ide> */
<ide> class FieldTypeConverter
<ide> {
<del>
<ide> /**
<ide> * An array containing the name of the fields and the Type objects
<ide> * each should use when converting them.
<ide><path>src/Database/FunctionsBuilder.php
<ide> */
<ide> class FunctionsBuilder
<ide> {
<del>
<ide> /**
<ide> * Returns a new instance of a FunctionExpression. This is used for generating
<ide> * arbitrary function calls in the final SQL string.
<ide><path>src/Database/IdentifierQuoter.php
<ide> */
<ide> class IdentifierQuoter
<ide> {
<del>
<ide> /**
<ide> * The driver instance used to do the identifier quoting
<ide> *
<ide><path>src/Database/Log/LoggedQuery.php
<ide> */
<ide> class LoggedQuery
<ide> {
<del>
<ide> /**
<ide> * Query string that was executed
<ide> *
<ide><path>src/Database/Log/LoggingStatement.php
<ide> */
<ide> class LoggingStatement extends StatementDecorator
<ide> {
<del>
<ide> /**
<ide> * Logger instance responsible for actually doing the logging task
<ide> *
<ide><path>src/Database/Log/QueryLogger.php
<ide> */
<ide> class QueryLogger
<ide> {
<del>
<ide> /**
<ide> * Writes a LoggedQuery into a log
<ide> *
<ide><path>src/Database/Query.php
<ide> */
<ide> class Query implements ExpressionInterface, IteratorAggregate
<ide> {
<del>
<ide> use TypeMapTrait;
<ide>
<ide> /**
<ide><path>src/Database/QueryCompiler.php
<ide> */
<ide> class QueryCompiler
<ide> {
<del>
<ide> /**
<ide> * List of sprintf templates that will be used for compiling the SQL for
<ide> * this query. There are some clauses that can be built as just as the
<ide><path>src/Database/Schema/BaseSchema.php
<ide> */
<ide> abstract class BaseSchema
<ide> {
<del>
<ide> /**
<ide> * The driver instance being used.
<ide> *
<ide><path>src/Database/Schema/CachedCollection.php
<ide> */
<ide> class CachedCollection extends Collection
<ide> {
<del>
<ide> /**
<ide> * The name of the cache config key to use for caching table metadata,
<ide> * of false if disabled.
<ide><path>src/Database/Schema/Collection.php
<ide> */
<ide> class Collection
<ide> {
<del>
<ide> /**
<ide> * Connection object
<ide> *
<ide><path>src/Database/Schema/PostgresSchema.php
<ide> */
<ide> class PostgresSchema extends BaseSchema
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Database/Schema/SqlGeneratorInterface.php
<ide> */
<ide> interface SqlGeneratorInterface
<ide> {
<del>
<ide> /**
<ide> * Generate the SQL to create the Table.
<ide> *
<ide><path>src/Database/Schema/SqliteSchema.php
<ide> */
<ide> class SqliteSchema extends BaseSchema
<ide> {
<del>
<ide> /**
<ide> * Array containing the foreign keys constraints names
<ide> * Necessary for composite foreign keys to be handled
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> */
<ide> class SqlserverSchema extends BaseSchema
<ide> {
<del>
<ide> const DEFAULT_SCHEMA_NAME = 'dbo';
<ide>
<ide> /**
<ide><path>src/Database/Schema/TableSchema.php
<ide> */
<ide> class TableSchema implements TableSchemaInterface, SqlGeneratorInterface
<ide> {
<del>
<ide> /**
<ide> * The name of the table
<ide> *
<ide><path>src/Database/Schema/TableSchemaAwareInterface.php
<ide> */
<ide> interface TableSchemaAwareInterface
<ide> {
<del>
<ide> /**
<ide> * Get and set the schema for this fixture.
<ide> *
<ide><path>src/Database/Schema/TableSchemaInterface.php
<ide> */
<ide> interface TableSchemaInterface extends SchemaInterface
<ide> {
<del>
<ide> /**
<ide> * Binary column type
<ide> *
<ide><path>src/Database/SchemaCache.php
<ide> */
<ide> class SchemaCache
<ide> {
<del>
<ide> /**
<ide> * Schema
<ide> *
<ide><path>src/Database/SqlDialectTrait.php
<ide> */
<ide> trait SqlDialectTrait
<ide> {
<del>
<ide> /**
<ide> * Quotes a database identifier (a column name, table name, etc..) to
<ide> * be used safely in queries without the risk of using reserved words
<ide><path>src/Database/SqliteCompiler.php
<ide> */
<ide> class SqliteCompiler extends QueryCompiler
<ide> {
<del>
<ide> /**
<ide> * SQLite does not support ORDER BY in UNION queries.
<ide> *
<ide><path>src/Database/SqlserverCompiler.php
<ide> */
<ide> class SqlserverCompiler extends QueryCompiler
<ide> {
<del>
<ide> /**
<ide> * SQLserver does not support ORDER BY in UNION queries.
<ide> *
<ide><path>src/Database/Statement/BufferResultsTrait.php
<ide> */
<ide> trait BufferResultsTrait
<ide> {
<del>
<ide> /**
<ide> * Whether or not to buffer results in php
<ide> *
<ide><path>src/Database/Statement/CallbackStatement.php
<ide> */
<ide> class CallbackStatement extends StatementDecorator
<ide> {
<del>
<ide> /**
<ide> * A callback function to be applied to results.
<ide> *
<ide><path>src/Database/Statement/MysqlStatement.php
<ide> */
<ide> class MysqlStatement extends PDOStatement
<ide> {
<del>
<ide> use BufferResultsTrait;
<ide>
<ide> /**
<ide><path>src/Database/Statement/PDOStatement.php
<ide> */
<ide> class PDOStatement extends StatementDecorator
<ide> {
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide><path>src/Database/Statement/SqliteStatement.php
<ide> */
<ide> class SqliteStatement extends StatementDecorator
<ide> {
<del>
<ide> use BufferResultsTrait;
<ide>
<ide> /**
<ide><path>src/Database/Statement/SqlserverStatement.php
<ide> */
<ide> class SqlserverStatement extends PDOStatement
<ide> {
<del>
<ide> /**
<ide> * The SQL Server PDO driver requires that binary parameters be bound with the SQLSRV_ENCODING_BINARY attribute.
<ide> * This overrides the PDOStatement::bindValue method in order to bind binary columns using the required attribute.
<ide><path>src/Database/Type.php
<ide> */
<ide> class Type implements TypeInterface
<ide> {
<del>
<ide> /**
<ide> * List of supported database types. A human readable
<ide> * identifier is used as key and a complete namespaced class name as value
<ide><path>src/Database/Type/BatchCastingInterface.php
<ide> */
<ide> interface BatchCastingInterface
<ide> {
<del>
<ide> /**
<ide> * Returns an array of the values converted to the PHP representation of
<ide> * this type.
<ide><path>src/Database/Type/DateType.php
<ide> */
<ide> class DateType extends DateTimeType
<ide> {
<del>
<ide> /**
<ide> * The class to use for representing date objects
<ide> *
<ide><path>src/Database/Type/ExpressionTypeCasterTrait.php
<ide> */
<ide> trait ExpressionTypeCasterTrait
<ide> {
<del>
<ide> /**
<ide> * Conditionally converts the passed value to an ExpressionInterface object
<ide> * if the type class implements the ExpressionTypeInterface. Otherwise,
<ide><path>src/Database/Type/ExpressionTypeInterface.php
<ide> */
<ide> interface ExpressionTypeInterface
<ide> {
<del>
<ide> /**
<ide> * Returns an ExpressionInterface object for the given value that can
<ide> * be used in queries.
<ide><path>src/Database/Type/OptionalConvertInterface.php
<ide> */
<ide> interface OptionalConvertInterface
<ide> {
<del>
<ide> /**
<ide> * Returns whether the cast to PHP is required to be invoked, since
<ide> * it is not a identity function.
<ide><path>src/Database/Type/StringType.php
<ide> */
<ide> class StringType extends Type implements OptionalConvertInterface, TypeInterface
<ide> {
<del>
<ide> /**
<ide> * Convert string data into the database format.
<ide> *
<ide><path>src/Database/Type/TimeType.php
<ide> */
<ide> class TimeType extends DateTimeType
<ide> {
<del>
<ide> /**
<ide> * Time format for DateTime object
<ide> *
<ide><path>src/Database/Type/UuidType.php
<ide> */
<ide> class UuidType extends StringType
<ide> {
<del>
<ide> /**
<ide> * Casts given value from a PHP type to one acceptable by database
<ide> *
<ide><path>src/Database/TypeConverterTrait.php
<ide> */
<ide> trait TypeConverterTrait
<ide> {
<del>
<ide> /**
<ide> * Converts a give value to a suitable database value based on type
<ide> * and return relevant internal statement type
<ide><path>src/Database/TypeInterface.php
<ide> */
<ide> interface TypeInterface
<ide> {
<del>
<ide> /**
<ide> * Casts given value from a PHP type to one acceptable by a database.
<ide> *
<ide><path>src/Database/TypeMap.php
<ide> */
<ide> class TypeMap
<ide> {
<del>
<ide> /**
<ide> * Associative array with the default fields and the related types this query might contain.
<ide> *
<ide><path>src/Database/TypeMapTrait.php
<ide> */
<ide> trait TypeMapTrait
<ide> {
<del>
<ide> /**
<ide> * @var \Cake\Database\TypeMap
<ide> */
<ide><path>src/Database/TypedResultInterface.php
<ide> */
<ide> interface TypedResultInterface
<ide> {
<del>
<ide> /**
<ide> * Sets the type of the value this object will generate.
<ide> * If called without arguments, returns the current known type
<ide><path>src/Database/TypedResultTrait.php
<ide> */
<ide> trait TypedResultTrait
<ide> {
<del>
<ide> /**
<ide> * The type name this expression will return when executed
<ide> *
<ide><path>src/Database/ValueBinder.php
<ide> */
<ide> class ValueBinder
<ide> {
<del>
<ide> /**
<ide> * Array containing a list of bound values to the conditions on this
<ide> * object. Each array entry is another array structure containing the actual
<ide><path>src/Datasource/ConnectionManager.php
<ide> */
<ide> class ConnectionManager
<ide> {
<del>
<ide> use StaticConfigTrait {
<ide> setConfig as protected _setConfig;
<ide> parseDsn as protected _parseDsn;
<ide><path>src/Datasource/ConnectionRegistry.php
<ide> */
<ide> class ConnectionRegistry extends ObjectRegistry
<ide> {
<del>
<ide> /**
<ide> * Resolve a datasource classname.
<ide> *
<ide><path>src/Datasource/EntityInterface.php
<ide> */
<ide> interface EntityInterface extends ArrayAccess, JsonSerializable
<ide> {
<del>
<ide> /**
<ide> * Sets one or multiple properties to the specified value
<ide> *
<ide><path>src/Datasource/EntityTrait.php
<ide> */
<ide> trait EntityTrait
<ide> {
<del>
<ide> /**
<ide> * Holds all properties and their values for this entity
<ide> *
<ide><path>src/Datasource/Exception/InvalidPrimaryKeyException.php
<ide> */
<ide> class InvalidPrimaryKeyException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Datasource/Exception/MissingDatasourceConfigException.php
<ide> */
<ide> class MissingDatasourceConfigException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'The datasource configuration "%s" was not found.';
<ide> }
<ide><path>src/Datasource/Exception/MissingDatasourceException.php
<ide> */
<ide> class MissingDatasourceException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'Datasource class %s could not be found. %s';
<ide> }
<ide><path>src/Datasource/Exception/MissingModelException.php
<ide> */
<ide> class MissingModelException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'Model class "%s" of type "%s" could not be found.';
<ide> }
<ide><path>src/Datasource/Exception/RecordNotFoundException.php
<ide> */
<ide> class RecordNotFoundException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Datasource/ModelAwareTrait.php
<ide> */
<ide> trait ModelAwareTrait
<ide> {
<del>
<ide> /**
<ide> * This object's primary model class name. Should be a plural form.
<ide> * CakePHP will not inflect the name.
<ide><path>src/Datasource/QueryCacher.php
<ide> */
<ide> class QueryCacher
<ide> {
<del>
<ide> /**
<ide> * The key or function to generate a key.
<ide> *
<ide><path>src/Datasource/QueryInterface.php
<ide> */
<ide> interface QueryInterface
<ide> {
<del>
<ide> const JOIN_TYPE_INNER = 'INNER';
<ide> const JOIN_TYPE_LEFT = 'LEFT';
<ide> const JOIN_TYPE_RIGHT = 'RIGHT';
<ide><path>src/Datasource/QueryTrait.php
<ide> */
<ide> trait QueryTrait
<ide> {
<del>
<ide> /**
<ide> * Instance of a table object this query is bound to
<ide> *
<ide><path>src/Datasource/RepositoryInterface.php
<ide> */
<ide> interface RepositoryInterface
<ide> {
<del>
<ide> /**
<ide> * Returns the table alias or sets a new one
<ide> *
<ide><path>src/Datasource/ResultSetDecorator.php
<ide> */
<ide> class ResultSetDecorator extends Collection implements ResultSetInterface
<ide> {
<del>
<ide> /**
<ide> * Make this object countable.
<ide> *
<ide><path>src/Datasource/RulesAwareTrait.php
<ide> */
<ide> trait RulesAwareTrait
<ide> {
<del>
<ide> /**
<ide> * The domain rules to be applied to entities saved by this table
<ide> *
<ide><path>src/Datasource/SchemaInterface.php
<ide> */
<ide> interface SchemaInterface
<ide> {
<del>
<ide> /**
<ide> * Get the name of the table.
<ide> *
<ide><path>src/Datasource/TableSchemaInterface.php
<ide> */
<ide> interface TableSchemaInterface
<ide> {
<del>
<ide> /**
<ide> * Get and set the schema for this fixture.
<ide> *
<ide><path>src/Error/BaseErrorHandler.php
<ide> */
<ide> abstract class BaseErrorHandler
<ide> {
<del>
<ide> /**
<ide> * Options to use for the Error handling.
<ide> *
<ide><path>src/Error/ExceptionRenderer.php
<ide> */
<ide> class ExceptionRenderer implements ExceptionRendererInterface
<ide> {
<del>
<ide> /**
<ide> * The exception being handled.
<ide> *
<ide><path>src/Error/FatalErrorException.php
<ide> */
<ide> class FatalErrorException extends Exception
<ide> {
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide><path>src/Error/PHP7ErrorException.php
<ide> */
<ide> class PHP7ErrorException extends Exception
<ide> {
<del>
<ide> /**
<ide> * The wrapped error object
<ide> *
<ide><path>src/Event/Decorator/AbstractDecorator.php
<ide> */
<ide> abstract class AbstractDecorator
<ide> {
<del>
<ide> /**
<ide> * Callable
<ide> *
<ide><path>src/Event/Decorator/ConditionDecorator.php
<ide> */
<ide> class ConditionDecorator extends AbstractDecorator
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Event/Decorator/SubjectFilterDecorator.php
<ide> */
<ide> class SubjectFilterDecorator extends AbstractDecorator
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Event/Event.php
<ide> */
<ide> class Event implements EventInterface
<ide> {
<del>
<ide> /**
<ide> * Name of the event
<ide> *
<ide><path>src/Event/EventDispatcherTrait.php
<ide> */
<ide> trait EventDispatcherTrait
<ide> {
<del>
<ide> /**
<ide> * Instance of the Cake\Event\EventManager this object is using
<ide> * to dispatch inner events.
<ide><path>src/Event/EventList.php
<ide> */
<ide> class EventList implements ArrayAccess, Countable
<ide> {
<del>
<ide> /**
<ide> * Events list
<ide> *
<ide><path>src/Event/EventListenerInterface.php
<ide> */
<ide> interface EventListenerInterface
<ide> {
<del>
<ide> /**
<ide> * Returns a list of events this object is implementing. When the class is registered
<ide> * in an event manager, each individual method will be associated with the respective event.
<ide><path>src/Event/EventManager.php
<ide> */
<ide> class EventManager implements EventManagerInterface
<ide> {
<del>
<ide> /**
<ide> * The default priority queue value for new, attached listeners
<ide> *
<ide><path>src/Event/EventManagerInterface.php
<ide> */
<ide> interface EventManagerInterface
<ide> {
<del>
<ide> /**
<ide> * Adds a new listener to an event.
<ide> *
<ide><path>src/Event/EventManagerTrait.php
<ide> */
<ide> trait EventManagerTrait
<ide> {
<del>
<ide> use EventDispatcherTrait;
<ide> }
<ide><path>src/Filesystem/File.php
<ide> */
<ide> class File
<ide> {
<del>
<ide> /**
<ide> * Folder object of the file
<ide> *
<ide><path>src/Filesystem/Folder.php
<ide> */
<ide> class Folder
<ide> {
<del>
<ide> /**
<ide> * Default scheme for Folder::copy
<ide> * Recursively merges subfolders with the same name
<ide><path>src/Form/Schema.php
<ide> */
<ide> class Schema
<ide> {
<del>
<ide> /**
<ide> * The fields in this schema.
<ide> *
<ide><path>src/Http/BaseApplication.php
<ide> abstract class BaseApplication implements
<ide> HttpApplicationInterface,
<ide> PluginApplicationInterface
<ide> {
<del>
<ide> use EventDispatcherTrait;
<ide>
<ide> /**
<ide><path>src/Http/Client/Adapter/Stream.php
<ide> */
<ide> class Stream implements AdapterInterface
<ide> {
<del>
<ide> /**
<ide> * Context resource used by the stream API.
<ide> *
<ide><path>src/Http/Client/Auth/Basic.php
<ide> */
<ide> class Basic
<ide> {
<del>
<ide> /**
<ide> * Add Authorization header to the request.
<ide> *
<ide><path>src/Http/Client/Auth/Digest.php
<ide> */
<ide> class Digest
<ide> {
<del>
<ide> /**
<ide> * Instance of Cake\Http\Client
<ide> *
<ide><path>src/Http/Client/Auth/Oauth.php
<ide> */
<ide> class Oauth
<ide> {
<del>
<ide> /**
<ide> * Add headers for Oauth authorization.
<ide> *
<ide><path>src/Http/Client/CookieCollection.php
<ide> */
<ide> class CookieCollection extends BaseCollection
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Client/FormData.php
<ide> */
<ide> class FormData implements Countable
<ide> {
<del>
<ide> /**
<ide> * Boundary marker.
<ide> *
<ide><path>src/Http/Client/FormDataPart.php
<ide> */
<ide> class FormDataPart
<ide> {
<del>
<ide> /**
<ide> * Name of the value.
<ide> *
<ide><path>src/Http/Client/Message.php
<ide> */
<ide> class Message
<ide> {
<del>
<ide> /**
<ide> * HTTP 200 code
<ide> *
<ide><path>src/Http/Cookie/Cookie.php
<ide> */
<ide> class Cookie implements CookieInterface
<ide> {
<del>
<ide> /**
<ide> * Cookie name
<ide> *
<ide><path>src/Http/Cookie/CookieCollection.php
<ide> */
<ide> class CookieCollection implements IteratorAggregate, Countable
<ide> {
<del>
<ide> /**
<ide> * Cookie objects
<ide> *
<ide><path>src/Http/Cookie/CookieInterface.php
<ide> */
<ide> interface CookieInterface
<ide> {
<del>
<ide> /**
<ide> * Expires attribute format.
<ide> *
<ide><path>src/Http/CorsBuilder.php
<ide> */
<ide> class CorsBuilder
<ide> {
<del>
<ide> /**
<ide> * The response object this builder is attached to.
<ide> *
<ide><path>src/Http/Exception/BadRequestException.php
<ide> */
<ide> class BadRequestException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/ConflictException.php
<ide> */
<ide> class ConflictException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/ForbiddenException.php
<ide> */
<ide> class ForbiddenException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/GoneException.php
<ide> */
<ide> class GoneException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/InternalErrorException.php
<ide> */
<ide> class InternalErrorException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide><path>src/Http/Exception/InvalidCsrfTokenException.php
<ide> */
<ide> class InvalidCsrfTokenException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/MethodNotAllowedException.php
<ide> */
<ide> class MethodNotAllowedException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/NotAcceptableException.php
<ide> */
<ide> class NotAcceptableException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/NotFoundException.php
<ide> */
<ide> class NotFoundException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/NotImplementedException.php
<ide> */
<ide> class NotImplementedException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/ServiceUnavailableException.php
<ide> */
<ide> class ServiceUnavailableException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/UnauthorizedException.php
<ide> */
<ide> class UnauthorizedException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Exception/UnavailableForLegalReasonsException.php
<ide> */
<ide> class UnavailableForLegalReasonsException extends HttpException
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Http/Response.php
<ide> */
<ide> class Response implements ResponseInterface
<ide> {
<del>
<ide> use MessageTrait;
<ide>
<ide> /**
<ide><path>src/Http/Server.php
<ide> */
<ide> class Server implements EventDispatcherInterface
<ide> {
<del>
<ide> /**
<ide> * Alias methods away so we can implement proxying methods.
<ide> */
<ide><path>src/Http/ServerRequest.php
<ide> */
<ide> class ServerRequest implements ArrayAccess, ServerRequestInterface
<ide> {
<del>
<ide> /**
<ide> * Array of parameters parsed from the URL.
<ide> *
<ide><path>src/Http/Session.php
<ide> */
<ide> class Session
<ide> {
<del>
<ide> /**
<ide> * The Session handler instance used as an engine for persisting the session data.
<ide> *
<ide><path>src/Http/Session/CacheSession.php
<ide> */
<ide> class CacheSession implements SessionHandlerInterface
<ide> {
<del>
<ide> /**
<ide> * Options for this session engine
<ide> *
<ide><path>src/I18n/ChainMessagesLoader.php
<ide> */
<ide> class ChainMessagesLoader
<ide> {
<del>
<ide> /**
<ide> * The list of callables to execute one after another for loading messages
<ide> *
<ide><path>src/I18n/DateFormatTrait.php
<ide> */
<ide> trait DateFormatTrait
<ide> {
<del>
<ide> /**
<ide> * The default locale to be used for displaying formatted date strings.
<ide> *
<ide><path>src/I18n/Formatter/IcuFormatter.php
<ide> */
<ide> class IcuFormatter implements FormatterInterface
<ide> {
<del>
<ide> /**
<ide> * Returns a string with all passed variables interpolated into the original
<ide> * message. Variables are interpolated using the MessageFormatter class.
<ide><path>src/I18n/Formatter/SprintfFormatter.php
<ide> */
<ide> class SprintfFormatter implements FormatterInterface
<ide> {
<del>
<ide> /**
<ide> * Returns a string with all passed variables interpolated into the original
<ide> * message. Variables are interpolated using the sprintf format.
<ide><path>src/I18n/I18n.php
<ide> */
<ide> class I18n
<ide> {
<del>
<ide> /**
<ide> * Default locale
<ide> *
<ide><path>src/I18n/MessagesFileLoader.php
<ide> */
<ide> class MessagesFileLoader
<ide> {
<del>
<ide> /**
<ide> * The package (domain) name.
<ide> *
<ide><path>src/I18n/Number.php
<ide> */
<ide> class Number
<ide> {
<del>
<ide> /**
<ide> * Default locale
<ide> *
<ide><path>src/I18n/Parser/MoFileParser.php
<ide> */
<ide> class MoFileParser
<ide> {
<del>
<ide> /**
<ide> * Magic used for validating the format of a MO file as well as
<ide> * detecting if the machine used to create that file was little endian.
<ide><path>src/I18n/PluralRules.php
<ide> */
<ide> class PluralRules
<ide> {
<del>
<ide> /**
<ide> * A map of locale => plurals group used to determine
<ide> * which plural rules apply to the language
<ide><path>src/I18n/Translator.php
<ide> */
<ide> class Translator extends BaseTranslator
<ide> {
<del>
<ide> const PLURAL_PREFIX = 'p:';
<ide>
<ide> /**
<ide><path>src/I18n/TranslatorRegistry.php
<ide> */
<ide> class TranslatorRegistry extends TranslatorLocator
<ide> {
<del>
<ide> /**
<ide> * A list of loader functions indexed by domain name. Loaders are
<ide> * callables that are invoked as a default for building translation
<ide><path>src/Log/Engine/ConsoleLog.php
<ide> */
<ide> class ConsoleLog extends BaseLog
<ide> {
<del>
<ide> /**
<ide> * Default config for this class
<ide> *
<ide><path>src/Log/Engine/FileLog.php
<ide> */
<ide> class FileLog extends BaseLog
<ide> {
<del>
<ide> /**
<ide> * Default config for this class
<ide> *
<ide><path>src/Log/Engine/SyslogLog.php
<ide> */
<ide> class SyslogLog extends BaseLog
<ide> {
<del>
<ide> /**
<ide> * Default config for this class
<ide> *
<ide><path>src/Log/Log.php
<ide> */
<ide> class Log
<ide> {
<del>
<ide> use StaticConfigTrait {
<ide> setConfig as protected _setConfig;
<ide> }
<ide><path>src/Log/LogEngineRegistry.php
<ide> */
<ide> class LogEngineRegistry extends ObjectRegistry
<ide> {
<del>
<ide> /**
<ide> * Resolve a logger classname.
<ide> *
<ide><path>src/Log/LogTrait.php
<ide> */
<ide> trait LogTrait
<ide> {
<del>
<ide> /**
<ide> * Convenience method to write a message to Log. See Log::write()
<ide> * for more information on writing to logs.
<ide><path>src/Mailer/Email.php
<ide> */
<ide> class Email implements JsonSerializable, Serializable
<ide> {
<del>
<ide> use StaticConfigTrait;
<ide> use ViewVarsTrait;
<ide>
<ide><path>src/Mailer/Exception/MissingActionException.php
<ide> */
<ide> class MissingActionException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Mailer/Exception/MissingMailerException.php
<ide> */
<ide> class MissingMailerException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'Mailer class "%s" could not be found.';
<ide> }
<ide><path>src/Mailer/Mailer.php
<ide> */
<ide> abstract class Mailer implements EventListenerInterface
<ide> {
<del>
<ide> use ModelAwareTrait;
<ide>
<ide> /**
<ide><path>src/Mailer/MailerAwareTrait.php
<ide> */
<ide> trait MailerAwareTrait
<ide> {
<del>
<ide> /**
<ide> * Returns a mailer instance.
<ide> *
<ide><path>src/Mailer/Transport/DebugTransport.php
<ide> */
<ide> class DebugTransport extends AbstractTransport
<ide> {
<del>
<ide> /**
<ide> * Send mail
<ide> *
<ide><path>src/Mailer/Transport/MailTransport.php
<ide> */
<ide> class MailTransport extends AbstractTransport
<ide> {
<del>
<ide> /**
<ide> * Send mail
<ide> *
<ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> */
<ide> class SmtpTransport extends AbstractTransport
<ide> {
<del>
<ide> /**
<ide> * Default config for this class
<ide> *
<ide><path>src/Network/Exception/SocketException.php
<ide> */
<ide> class SocketException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/ORM/Association.php
<ide> */
<ide> abstract class Association
<ide> {
<del>
<ide> use ConventionsTrait;
<ide> use LocatorAwareTrait;
<ide>
<ide><path>src/ORM/Association/BelongsTo.php
<ide> */
<ide> class BelongsTo extends Association
<ide> {
<del>
<ide> /**
<ide> * Valid strategies for this type of association
<ide> *
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> */
<ide> class BelongsToMany extends Association
<ide> {
<del>
<ide> /**
<ide> * Saving strategy that will only append to the links set
<ide> *
<ide><path>src/ORM/Association/DependentDeleteHelper.php
<ide> */
<ide> class DependentDeleteHelper
<ide> {
<del>
<ide> /**
<ide> * Cascade a delete to remove dependent records.
<ide> *
<ide><path>src/ORM/Association/DependentDeleteTrait.php
<ide> */
<ide> trait DependentDeleteTrait
<ide> {
<del>
<ide> /**
<ide> * Cascade a delete to remove dependent records.
<ide> *
<ide><path>src/ORM/Association/HasMany.php
<ide> */
<ide> class HasMany extends Association
<ide> {
<del>
<ide> /**
<ide> * Order in which target records should be returned
<ide> *
<ide><path>src/ORM/Association/Loader/SelectLoader.php
<ide> */
<ide> class SelectLoader
<ide> {
<del>
<ide> /**
<ide> * The alias of the association loading the results
<ide> *
<ide><path>src/ORM/Association/Loader/SelectWithPivotLoader.php
<ide> */
<ide> class SelectWithPivotLoader extends SelectLoader
<ide> {
<del>
<ide> /**
<ide> * The name of the junction association
<ide> *
<ide><path>src/ORM/AssociationCollection.php
<ide> */
<ide> class AssociationCollection implements IteratorAggregate
<ide> {
<del>
<ide> use AssociationsNormalizerTrait;
<ide> use LocatorAwareTrait;
<ide>
<ide><path>src/ORM/AssociationsNormalizerTrait.php
<ide> */
<ide> trait AssociationsNormalizerTrait
<ide> {
<del>
<ide> /**
<ide> * Returns an array out of the original passed associations list where dot notation
<ide> * is transformed into nested arrays so that they can be parsed by other routines
<ide><path>src/ORM/Behavior.php
<ide> */
<ide> class Behavior implements EventListenerInterface
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /**
<ide><path>src/ORM/Behavior/CounterCacheBehavior.php
<ide> */
<ide> class CounterCacheBehavior extends Behavior
<ide> {
<del>
<ide> /**
<ide> * Store the fields which should be ignored
<ide> *
<ide><path>src/ORM/Behavior/TimestampBehavior.php
<ide> */
<ide> class TimestampBehavior extends Behavior
<ide> {
<del>
<ide> /**
<ide> * Default config
<ide> *
<ide><path>src/ORM/Behavior/Translate/TranslateTrait.php
<ide> */
<ide> trait TranslateTrait
<ide> {
<del>
<ide> /**
<ide> * Returns the entity containing the translated fields for this object and for
<ide> * the specified language. If the translation for the passed language is not
<ide><path>src/ORM/Behavior/TranslateBehavior.php
<ide> */
<ide> class TranslateBehavior extends Behavior implements PropertyMarshalInterface
<ide> {
<del>
<ide> use LocatorAwareTrait;
<ide>
<ide> /**
<ide><path>src/ORM/Behavior/TreeBehavior.php
<ide> */
<ide> class TreeBehavior extends Behavior
<ide> {
<del>
<ide> /**
<ide> * Cached copy of the first column in a table's primary key.
<ide> *
<ide><path>src/ORM/BehaviorRegistry.php
<ide> */
<ide> class BehaviorRegistry extends ObjectRegistry implements EventDispatcherInterface
<ide> {
<del>
<ide> use EventDispatcherTrait;
<ide>
<ide> /**
<ide><path>src/ORM/EagerLoadable.php
<ide> */
<ide> class EagerLoadable
<ide> {
<del>
<ide> /**
<ide> * The name of the association to load.
<ide> *
<ide><path>src/ORM/EagerLoader.php
<ide> */
<ide> class EagerLoader
<ide> {
<del>
<ide> /**
<ide> * Nested array describing the association to be fetched
<ide> * and the options to apply for each of them, if any
<ide><path>src/ORM/Exception/MissingBehaviorException.php
<ide> */
<ide> class MissingBehaviorException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'Behavior class %s could not be found.';
<ide> }
<ide><path>src/ORM/Exception/MissingEntityException.php
<ide> */
<ide> class MissingEntityException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'Entity class %s could not be found.';
<ide> }
<ide><path>src/ORM/Exception/MissingTableClassException.php
<ide> */
<ide> class MissingTableClassException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'Table class %s could not be found.';
<ide> }
<ide><path>src/ORM/Exception/PersistenceFailedException.php
<ide> */
<ide> class PersistenceFailedException extends Exception
<ide> {
<del>
<ide> /**
<ide> * The entity on which the persistence operation failed
<ide> *
<ide><path>src/ORM/Exception/RolledbackTransactionException.php
<ide> */
<ide> class RolledbackTransactionException extends Exception
<ide> {
<del>
<ide> protected $_messageTemplate = 'The afterSave event in "%s" is aborting the transaction before the save process is done.';
<ide> }
<ide><path>src/ORM/LazyEagerLoader.php
<ide> */
<ide> class LazyEagerLoader
<ide> {
<del>
<ide> /**
<ide> * Loads the specified associations in the passed entity or list of entities
<ide> * by executing extra queries in the database and merging the results in the
<ide><path>src/ORM/Locator/LocatorAwareTrait.php
<ide> */
<ide> trait LocatorAwareTrait
<ide> {
<del>
<ide> /**
<ide> * Table locator instance
<ide> *
<ide><path>src/ORM/Locator/LocatorInterface.php
<ide> */
<ide> interface LocatorInterface
<ide> {
<del>
<ide> /**
<ide> * Stores a list of options to be used when instantiating an object
<ide> * with a matching alias.
<ide><path>src/ORM/Locator/TableLocator.php
<ide> */
<ide> class TableLocator implements LocatorInterface
<ide> {
<del>
<ide> /**
<ide> * Contains a list of locations where table classes should be looked for.
<ide> *
<ide><path>src/ORM/Marshaller.php
<ide> */
<ide> class Marshaller
<ide> {
<del>
<ide> use AssociationsNormalizerTrait;
<ide>
<ide> /**
<ide><path>src/ORM/ResultSet.php
<ide> */
<ide> class ResultSet implements ResultSetInterface
<ide> {
<del>
<ide> use CollectionTrait;
<ide>
<ide> /**
<ide><path>src/ORM/Rule/ExistsIn.php
<ide> */
<ide> class ExistsIn
<ide> {
<del>
<ide> /**
<ide> * The list of fields to check
<ide> *
<ide><path>src/ORM/Rule/IsUnique.php
<ide> */
<ide> class IsUnique
<ide> {
<del>
<ide> /**
<ide> * The list of fields to check
<ide> *
<ide><path>src/ORM/Rule/ValidCount.php
<ide> */
<ide> class ValidCount
<ide> {
<del>
<ide> /**
<ide> * The field to check
<ide> *
<ide><path>src/ORM/RulesChecker.php
<ide> */
<ide> class RulesChecker extends BaseRulesChecker
<ide> {
<del>
<ide> /**
<ide> * Returns a callable that can be used as a rule for checking the uniqueness of a value
<ide> * in the table.
<ide><path>src/ORM/SaveOptionsBuilder.php
<ide> */
<ide> class SaveOptionsBuilder extends ArrayObject
<ide> {
<del>
<ide> use AssociationsNormalizerTrait;
<ide>
<ide> /**
<ide><path>src/ORM/Table.php
<ide> */
<ide> class Table implements RepositoryInterface, EventListenerInterface, EventDispatcherInterface, ValidatorAwareInterface
<ide> {
<del>
<ide> use EventDispatcherTrait;
<ide> use RulesAwareTrait;
<ide> use ValidatorAwareTrait;
<ide><path>src/ORM/TableRegistry.php
<ide> */
<ide> class TableRegistry
<ide> {
<del>
<ide> /**
<ide> * LocatorInterface implementation instance.
<ide> *
<ide><path>src/Routing/Dispatcher.php
<ide> */
<ide> class Dispatcher
<ide> {
<del>
<ide> use EventDispatcherTrait;
<ide>
<ide> /**
<ide><path>src/Routing/DispatcherFactory.php
<ide> */
<ide> class DispatcherFactory
<ide> {
<del>
<ide> /**
<ide> * Stack of middleware to apply to dispatchers.
<ide> *
<ide><path>src/Routing/Exception/DuplicateNamedRouteException.php
<ide> */
<ide> class DuplicateNamedRouteException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Routing/Exception/MissingControllerException.php
<ide> */
<ide> class MissingControllerException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Routing/Exception/MissingDispatcherFilterException.php
<ide> */
<ide> class MissingDispatcherFilterException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Routing/Exception/MissingRouteException.php
<ide> */
<ide> class MissingRouteException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Routing/Exception/RedirectException.php
<ide> */
<ide> class RedirectException extends Exception
<ide> {
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/Routing/Filter/AssetFilter.php
<ide> */
<ide> class AssetFilter extends DispatcherFilter
<ide> {
<del>
<ide> /**
<ide> * Default priority for all methods in this filter
<ide> * This filter should run before the request gets parsed by router
<ide><path>src/Routing/Filter/ControllerFactoryFilter.php
<ide> */
<ide> class ControllerFactoryFilter extends DispatcherFilter
<ide> {
<del>
<ide> /**
<ide> * Priority is set high to allow other filters to be called first.
<ide> *
<ide><path>src/Routing/Filter/LocaleSelectorFilter.php
<ide> */
<ide> class LocaleSelectorFilter extends DispatcherFilter
<ide> {
<del>
<ide> /**
<ide> * List of valid locales for the request
<ide> *
<ide><path>src/Routing/Filter/RoutingFilter.php
<ide> */
<ide> class RoutingFilter extends DispatcherFilter
<ide> {
<del>
<ide> /**
<ide> * Priority setting.
<ide> *
<ide><path>src/Routing/RequestActionTrait.php
<ide> */
<ide> trait RequestActionTrait
<ide> {
<del>
<ide> /**
<ide> * Calls a controller's method from any location. Can be used to connect controllers together
<ide> * or tie plugins into a main application. requestAction can be used to return rendered views
<ide><path>src/Routing/Route/DashedRoute.php
<ide> */
<ide> class DashedRoute extends Route
<ide> {
<del>
<ide> /**
<ide> * Flag for tracking whether or not the defaults have been inflected.
<ide> *
<ide><path>src/Routing/Route/InflectedRoute.php
<ide> */
<ide> class InflectedRoute extends Route
<ide> {
<del>
<ide> /**
<ide> * Flag for tracking whether or not the defaults have been inflected.
<ide> *
<ide><path>src/Routing/Route/PluginShortRoute.php
<ide> */
<ide> class PluginShortRoute extends InflectedRoute
<ide> {
<del>
<ide> /**
<ide> * Parses a string URL into an array. If a plugin key is found, it will be copied to the
<ide> * controller parameter.
<ide><path>src/Routing/Route/RedirectRoute.php
<ide> */
<ide> class RedirectRoute extends Route
<ide> {
<del>
<ide> /**
<ide> * A Response object
<ide> *
<ide><path>src/Routing/Route/Route.php
<ide> */
<ide> class Route
<ide> {
<del>
<ide> /**
<ide> * An array of named segments in a Route.
<ide> * `/:controller/:action/:id` has 3 key elements
<ide><path>src/Routing/RouteBuilder.php
<ide> */
<ide> class RouteBuilder
<ide> {
<del>
<ide> /**
<ide> * Regular expression for auto increment IDs
<ide> *
<ide><path>src/Routing/RouteCollection.php
<ide> */
<ide> class RouteCollection
<ide> {
<del>
<ide> /**
<ide> * The routes connected to this collection.
<ide> * | 300 |
Python | Python | make set_model unconditional | da1ff3db476c8d0ed4cf794a3c7de1c7caf3f8b5 | <ide><path>keras/callbacks.py
<ide> def set_params(self, params):
<ide>
<ide> def set_model(self, model):
<ide> for callback in self.callbacks:
<del> if callback.model is None:
<del> callback.set_model(model)
<add> callback.set_model(model)
<ide>
<ide> def on_epoch_begin(self, epoch, logs=None):
<ide> """Called at the start of an epoch. | 1 |
Text | Text | change the capital "s" and remove 0. | f398d8346d5875e852b07fbf20278712e4cb0d34 | <ide><path>guide/english/miscellaneous/how-to-create-a-local-study-group/index.md
<ide> If you didn't see your city on <a href='https://www.freecodecamp.com/study-group
<ide> This also applies to creating smaller, more cohesive groups for neighbourhoods and districts inside of the same city. Thus, groups should ideally represent areas where its members don't have to commute longer than 15-20 minutes to meet each other.
<ide> However, be aware people may want to join from other places, as they may intend on moving there, or see your group as a nice source of resources and feedback, etc.
<ide>
<del>**Please, do not create groups for a whole State/province/department/county/etc. as they will not be added to the list.**
<add>**Please, do not create groups for a whole state/province/department/county/etc. as they will not be added to the list.**
<ide>
<ide> Assuming you've already signed into Facebook:
<del>0 . (optional) While creating the group you'll need to add at least one person. You could add <a href='https://www.facebook.com/FCC.GroupChancellor' target='_blank' rel='nofollow'>Justin</a> as a friend, who's in charge of freeCodeCamp's local groups and can **assist you in managing your members, events, and any issues that may come up (such as spammers, etc.)**.
<add>
<add>(This part is optional) While creating the group you'll need to add at least one person. You could add <a href='https://www.facebook.com/FCC.GroupChancellor' target='_blank' rel='nofollow'>Justin</a> as a friend, who's in charge of freeCodeCamp's local groups and can **assist you in managing your members, events, and any issues that may come up (such as spammers, etc.)**.
<ide> Also, he will probably not see be able to see any messages you may send until you "friend" him.
<ide>
<ide> Now, to the fun part! It's easy, just follow these steps: | 1 |
Javascript | Javascript | add time scale | 42a9faa1242f5440c71c34570e6437c8c6d92028 | <ide><path>examples/js/materials/nodes/utils/TimeNode.js
<ide> THREE.TimeNode = function( value ) {
<ide> THREE.FloatNode.call( this, value );
<ide>
<ide> this.requestUpdate = true;
<add> this.scale = 1;
<ide>
<ide> };
<ide>
<ide> THREE.TimeNode.prototype.constructor = THREE.TimeNode;
<ide>
<ide> THREE.TimeNode.prototype.updateAnimation = function( delta ) {
<ide>
<del> this.number += delta;
<add> this.number += delta * this.scale;
<ide>
<ide> }; | 1 |
Text | Text | remove travis ci badge | 6b4da92fcd21dfebb9ac2934de873fd55d3acf7e | <ide><path>README.md
<ide>
<ide> [![node][node]][node-url]
<ide> [![deps][deps]][deps-url]
<del>[![tests][tests]][tests-url]
<ide> [![builds2][builds2]][builds2-url]
<ide> [![coverage][cover]][cover-url]
<ide> [![licenses][licenses]][licenses-url]
<ide> src="https://static.monei.net/monei-logo.svg" height="30" alt="MONEI"></a>
<ide> [node-url]: https://nodejs.org
<ide> [deps]: https://img.shields.io/david/webpack/webpack.svg
<ide> [deps-url]: https://david-dm.org/webpack/webpack
<del>[tests]: https://img.shields.io/travis/webpack/webpack/main.svg
<del>[tests-url]: https://travis-ci.org/webpack/webpack
<ide> [prs]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg
<ide> [prs-url]: https://webpack.js.org/contribute/
<ide> [builds2]: https://dev.azure.com/webpack/webpack/_apis/build/status/webpack.webpack | 1 |
Python | Python | add batinfo to setup.py | 6310e1ef5fed8d0251e9db15a8cdd8e883ac5939 | <ide><path>setup.py
<ide> install_requires=['psutil>=0.4.1'],
<ide> extras_require={
<ide> 'HTML': ['jinja2>=2.0'],
<del> 'SENSORS': ['pysensors>=0.0.2']
<add> 'SENSORS': ['pysensors>=0.0.2'],
<ide> 'BATINFO': ['batinfo>=0.1.3']
<ide> },
<ide> packages=['glances'], | 1 |
Javascript | Javascript | register url to moduletemplates | bdb986b3ab140f0a375dc0a4508907cf0fb2e419 | <ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> this.outputOptions,
<ide> this.requestShortener
<ide> );
<del> /** @type {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} */
<add> /** @type {{url: ModuleTemplate, javascript: ModuleTemplate, webassembly: ModuleTemplate}} */
<ide> this.moduleTemplates = {
<add> url: new ModuleTemplate(this.runtimeTemplate, "url"),
<ide> javascript: new ModuleTemplate(this.runtimeTemplate, "javascript"),
<ide> webassembly: new ModuleTemplate(this.runtimeTemplate, "webassembly")
<ide> }; | 1 |
Text | Text | fix alphabetic ordering [ci skip] | 4daf1381365cd52958d6d53e9dcc7022eb9f7509 | <ide><path>website/docs/api/top-level.md
<ide> factories.
<ide> | `loggers` | Registry for functions that log [training results](/usage/training). |
<ide> | `lookups` | Registry for large lookup tables available via `vocab.lookups`. |
<ide> | `losses` | Registry for functions that create [losses](https://thinc.ai/docs/api-loss). |
<add>| `misc` | Registry for miscellaneous functions that return data assets, knowledge bases or anything else you may need. |
<ide> | `optimizers` | Registry for functions that create [optimizers](https://thinc.ai/docs/api-optimizers). |
<ide> | `readers` | Registry for training and evaluation data readers like [`Corpus`](/api/corpus). |
<ide> | `schedules` | Registry for functions that create [schedules](https://thinc.ai/docs/api-schedules). |
<ide> | `tokenizers` | Registry for tokenizer factories. Registered functions should return a callback that receives the `nlp` object and returns a [`Tokenizer`](/api/tokenizer) or a custom callable. |
<del>| `misc` | Registry for miscellaneous functions that return data assets, knowledge bases or anything else you may need. |
<ide>
<ide> ### spacy-transformers registry {#registry-transformers}
<ide> | 1 |
Ruby | Ruby | apply suggestions from code review | 1b8ceee4a2efeb7b9d02d0a971e0dce343bb090b | <ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
<ide> class Mysql2Adapter < AbstractMysqlAdapter
<ide> ER_BAD_DB_ERROR = 1049
<ide> ER_ACCESS_DENIED_ERROR = 1045
<ide> ER_CONN_HOST_ERROR = 2003
<del> ER_UNKOWN_HOST_ERROR = 2005
<add> ER_UNKNOWN_HOST_ERROR = 2005
<ide>
<ide> ADAPTER_NAME = "Mysql2"
<ide>
<ide> def new_client(config)
<ide> raise ActiveRecord::NoDatabaseError.db_error(config[:database])
<ide> elsif error.error_number == ConnectionAdapters::Mysql2Adapter::ER_ACCESS_DENIED_ERROR
<ide> raise ActiveRecord::DatabaseConnectionError.username_error(config[:username])
<del> elsif [ConnectionAdapters::Mysql2Adapter::ER_CONN_HOST_ERROR, ConnectionAdapters::Mysql2Adapter::ER_UNKOWN_HOST_ERROR].include?(error.error_number)
<add> elsif [ConnectionAdapters::Mysql2Adapter::ER_CONN_HOST_ERROR, ConnectionAdapters::Mysql2Adapter::ER_UNKNOWN_HOST_ERROR].include?(error.error_number)
<ide> raise ActiveRecord::DatabaseConnectionError.hostname_error(config[:host])
<ide> else
<ide> raise ActiveRecord::ConnectionNotEstablished, error.message
<ide><path>activerecord/lib/active_record/errors.rb
<ide> def db_error(db_name)
<ide>
<ide> To resolve this issue:
<ide>
<del> - Not created a database for this app, or deleted it? You may need to create your database.
<del> - Database name changed? Check your database.yml config has the correct database name.
<add> - Did you create the database for this app, or delete it? You may need to create your database.
<add> - Has the database name changed? Check your database.yml config has the correct database name.
<ide>
<ide> To create your database, run:\n\n bin/rails db:create
<ide> MSG
<ide> def initialize(message = nil)
<ide> class << self
<ide> def hostname_error(hostname)
<ide> DatabaseConnectionError.new(<<~MSG)
<del> We are having an issue connecting with your hostname: #{hostname}.\n
<del> Please check your database configuration or ensure there is a connection open to your hostname.
<add> There is an issue connecting with your hostname: #{hostname}.\n
<add> Please check your database configuration and ensure there is a valid connection to your database.
<ide> MSG
<ide> end
<ide>
<ide> def username_error(username)
<ide> DatabaseConnectionError.new(<<~MSG)
<del> We are having an issue connecting to your database with your username/password, username: #{username}.\n
<add> There is an issue connecting to your database with your username/password, username: #{username}.\n
<ide> Please check your database configuration to ensure the username/password are valid.
<ide> MSG
<ide> end | 2 |
Ruby | Ruby | remove unnecessary conditional | 529b060dbb445ccad7c0da4d66e7e2dc52b8382f | <ide><path>Library/Homebrew/cmd/--env.rb
<ide> module Homebrew
<ide> def __env
<ide> ENV.activate_extensions!
<del>
<del> if superenv?
<del> ENV.deps = ARGV.formulae.map(&:name) unless ARGV.named.empty?
<del> end
<del>
<add> ENV.deps = ARGV.formulae.map(&:name) if superenv?
<ide> ENV.setup_build_environment
<ide> ENV.universal_binary if ARGV.build_universal?
<add>
<ide> if $stdout.tty?
<ide> dump_build_env ENV
<ide> else | 1 |
Java | Java | add httpbasic clientwebrequestpostprocessor | b58a06208f261db26832db531eb975e1e7c7c232 | <ide><path>spring-web/src/main/java/org/springframework/web/client/reactive/ClientWebRequestPostProcessors.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.client.reactive;
<add>
<add>import java.nio.charset.Charset;
<add>import java.util.Base64;
<add>import java.util.Base64.Encoder;
<add>
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * Static factory methods for creating {@link ClientWebRequestPostProcesor} instances.
<add> *
<add> * @author Rob Winch
<add> * @since 5.0
<add> * @see DefaultClientWebRequestBuilder#apply(ClientWebRequestPostProcessors)
<add> */
<add>public abstract class ClientWebRequestPostProcessors {
<add>
<add> /**
<add> * Adds an Authorization header for HTTP Basic
<add> * @param username the username to add
<add> * @param password the password to add
<add> * @return the {@link ClientWebRequestPostProcessor} that adds the Authorization header
<add> */
<add> public static ClientWebRequestPostProcessor httpBasic(String username, String password) {
<add> Assert.notNull(username, "username cannot be null");
<add> Assert.notNull(password, "password cannot be null");
<add>
<add> return new ClientWebRequestPostProcessor() {
<add>
<add> @Override
<add> public ClientWebRequest postProcess(ClientWebRequest toPostProcess) {
<add> String authorization = authorization(username, password);
<add> toPostProcess.getHttpHeaders().set(HttpHeaders.AUTHORIZATION, authorization);
<add> return toPostProcess;
<add> }
<add>
<add> private String authorization(String username, String password) {
<add> String credentials = username + ":" + password;
<add> return authorization(credentials);
<add> }
<add>
<add> private String authorization(String credentials) {
<add> byte[] credentialBytes = credentials.getBytes(Charset.defaultCharset());
<add> Encoder encoder = Base64.getEncoder();
<add> String encodedCredentials = encoder.encodeToString(credentialBytes);
<add> return "Basic " + encodedCredentials;
<add> }
<add> };
<add> }
<add>
<add>}
<ide><path>spring-web/src/test/java/org/springframework/web/client/reactive/ClientWebRequestPostProcessorsTests.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.client.reactive;
<add>
<add>import java.nio.charset.Charset;
<add>import java.util.Base64;
<add>import java.util.Base64.Encoder;
<add>
<add>import org.junit.Test;
<add>import org.springframework.http.HttpHeaders;
<add>
<add>
<add>import static org.junit.Assert.*;
<add>import static org.springframework.web.client.reactive.ClientWebRequestPostProcessors.*;
<add>import static org.springframework.web.client.reactive.ClientWebRequestBuilders.*;
<add>
<add>/**
<add> *
<add> * @author Rob Winch
<add> * @since 5.0
<add> */
<add>public class ClientWebRequestPostProcessorsTests {
<add>
<add> @Test
<add> public void httpBasicWhenUsernamePasswordThenHeaderSet() {
<add> ClientWebRequest request = get("/").apply(httpBasic("user", "password")).build();
<add> assertEquals(request.getHttpHeaders().getFirst(HttpHeaders.AUTHORIZATION), basic("user:password"));
<add> }
<add>
<add> @Test
<add> public void httpBasicWhenUsernameEmptyThenHeaderSet() {
<add> ClientWebRequest request = get("/").apply(httpBasic("", "password")).build();
<add> assertEquals(request.getHttpHeaders().getFirst(HttpHeaders.AUTHORIZATION), basic(":password"));
<add> }
<add>
<add> @Test
<add> public void httpBasicWhenPasswordEmptyThenHeaderSet() {
<add> ClientWebRequest request = get("/").apply(httpBasic("user", "")).build();
<add> assertEquals(request.getHttpHeaders().getFirst(HttpHeaders.AUTHORIZATION), basic("user:"));
<add> }
<add>
<add> @Test(expected = IllegalArgumentException.class)
<add> public void httpBasicWhenUsernameNullThenIllegalArgumentException() {
<add> httpBasic(null, "password");
<add> }
<add>
<add> @Test(expected = IllegalArgumentException.class)
<add> public void httpBasicWhenPasswordNullThenIllegalArgumentException() {
<add> httpBasic("username", null);
<add> }
<add>
<add> private static String basic(String string) {
<add> Encoder encoder = Base64.getEncoder();
<add> byte[] bytes = string.getBytes(Charset.defaultCharset());
<add> return "Basic " + encoder.encodeToString(bytes);
<add> }
<add>} | 2 |
Python | Python | move beam search to nlp/modeling/ops | 55b82879955bc21527116366f4e44e7126b7b2a1 | <ide><path>official/nlp/modeling/ops/__init__.py
<add>
<ide><path>official/nlp/modeling/ops/beam_search.py
<add># Copyright 2018 The TensorFlow Authors. 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># ==============================================================================
<add>"""Beam search to find the translated sequence with the highest probability."""
<add>
<add>import numpy as np
<add>import tensorflow as tf
<add>
<add>
<add>def inf(dtype):
<add> """Returns a value close to infinity, but is still finite in `dtype`.
<add>
<add> This is useful to get a very large value that is still zero when multiplied by
<add> zero. The floating-point "Inf" value is NaN when multiplied by zero.
<add>
<add> Args:
<add> dtype: A dtype. The returned value will be finite when casted to this dtype.
<add>
<add> Returns:
<add> A very large value.
<add> """
<add> if dtype == "float32" or dtype == "bfloat16":
<add> return 1e7
<add> elif dtype == "float16":
<add> # Disable no-member lint error, as the linter thinks np.float16 does not
<add> # exist for some reason.
<add> return np.finfo(np.float16).max # pylint: disable=no-member
<add> else:
<add> raise AssertionError("Invalid dtype: %s" % dtype)
<add>
<add>
<add>class _StateKeys(object):
<add> """Keys to dictionary storing the state of the beam search loop."""
<add>
<add> # Variable storing the loop index.
<add> CUR_INDEX = "CUR_INDEX"
<add>
<add> # Top sequences that are alive for each batch item. Alive sequences are ones
<add> # that have not generated an EOS token. Sequences that reach EOS are marked as
<add> # finished and moved to the FINISHED_SEQ tensor.
<add> # Has shape [batch_size, beam_size, CUR_INDEX + 1]
<add> ALIVE_SEQ = "ALIVE_SEQ"
<add> # Log probabilities of each alive sequence. Shape [batch_size, beam_size]
<add> ALIVE_LOG_PROBS = "ALIVE_LOG_PROBS"
<add> # Dictionary of cached values for each alive sequence. The cache stores
<add> # the encoder output, attention bias, and the decoder attention output from
<add> # the previous iteration.
<add> ALIVE_CACHE = "ALIVE_CACHE"
<add>
<add> # Top finished sequences for each batch item.
<add> # Has shape [batch_size, beam_size, CUR_INDEX + 1]. Sequences that are
<add> # shorter than CUR_INDEX + 1 are padded with 0s.
<add> FINISHED_SEQ = "FINISHED_SEQ"
<add> # Scores for each finished sequence. Score = log probability / length norm
<add> # Shape [batch_size, beam_size]
<add> FINISHED_SCORES = "FINISHED_SCORES"
<add> # Flags indicating which sequences in the finished sequences are finished.
<add> # At the beginning, all of the sequences in FINISHED_SEQ are filler values.
<add> # True -> finished sequence, False -> filler. Shape [batch_size, beam_size]
<add> FINISHED_FLAGS = "FINISHED_FLAGS"
<add>
<add>
<add>def _expand_to_same_rank(tensor, target):
<add> """Expands a given tensor to target's rank to be broadcastable.
<add>
<add> Args:
<add> tensor: input tensor to tile. Shape: [b, d1, ..., da]
<add> target: target tensor. Shape: [b, d1, ..., da, ..., dn]
<add>
<add> Returns:
<add> Tiled tensor of shape [b, d1, ..., da, 1, ..., 1] with same rank of target.
<add>
<add> Raises:
<add> ValueError, if the shape rank of rank tensor/target is None.
<add> """
<add> if tensor.shape.rank is None:
<add> raise ValueError("Expect rank for tensor shape, but got None.")
<add> if target.shape.rank is None:
<add> raise ValueError("Expect rank for target shape, but got None.")
<add>
<add> with tf.name_scope("expand_rank"):
<add> diff_rank = target.shape.rank - tensor.shape.rank
<add> for _ in range(diff_rank):
<add> tensor = tf.expand_dims(tensor, -1)
<add> return tensor
<add>
<add>
<add>class SequenceBeamSearch(tf.Module):
<add> """Implementation of beam search loop."""
<add>
<add> def __init__(self,
<add> symbols_to_logits_fn,
<add> vocab_size,
<add> beam_size,
<add> alpha,
<add> max_decode_length,
<add> eos_id,
<add> padded_decode,
<add> dtype=tf.float32):
<add> """Initialize sequence beam search.
<add>
<add> Args:
<add> symbols_to_logits_fn: A function to provide logits, which is the
<add> interface to the Transformer model. The passed in arguments are: ids ->
<add> A tensor with shape [batch_size * beam_size, index]. index -> A
<add> scalar. cache -> A nested dictionary of tensors [batch_size *
<add> beam_size, ...].
<add> The function must return a tuple of logits and the updated cache: logits
<add> -> A tensor with shape [batch * beam_size, vocab_size]. updated cache
<add> -> A nested dictionary with the same structure as the input cache.
<add> vocab_size: An integer, the size of the vocabulary, used for topk
<add> computation.
<add> beam_size: An integer, number of beams for beam search.
<add> alpha: A float, defining the strength of length normalization.
<add> max_decode_length: An integer, the maximum number of steps to decode a
<add> sequence.
<add> eos_id: An integer. ID of end of sentence token.
<add> padded_decode: A bool, indicating if max_sequence_length padding is used
<add> for beam search.
<add> dtype: A tensorflow data type used for score computation. The default is
<add> tf.float32.
<add> """
<add> self.symbols_to_logits_fn = symbols_to_logits_fn
<add> self.vocab_size = vocab_size
<add> self.beam_size = beam_size
<add> self.alpha = alpha
<add> self.max_decode_length = max_decode_length
<add> self.eos_id = eos_id
<add> self.padded_decode = padded_decode
<add> self.dtype = tf.as_dtype(dtype)
<add>
<add> def search(self, initial_ids, initial_cache):
<add> """Beam search for sequences with highest scores.
<add>
<add> Args:
<add> initial_ids: initial ids to pass into the symbols_to_logits_fn. int tensor
<add> with shape [batch_size, 1]
<add> initial_cache: dictionary storing values to be passed into the
<add> symbols_to_logits_fn.
<add>
<add> Returns:
<add> finished_seq and finished_scores.
<add> """
<add> batch_size = (
<add> initial_ids.shape.as_list()[0]
<add> if self.padded_decode else tf.shape(initial_ids)[0])
<add> state, state_shapes = self._create_initial_state(initial_ids, initial_cache,
<add> batch_size)
<add>
<add> def _grow_alive_seq(state):
<add> """Grow alive sequences by one token, collect top 2*beam_size sequences.
<add>
<add> 2*beam_size sequences are collected because some sequences may have
<add> reached the EOS token. 2*beam_size ensures that at least beam_size
<add> sequences are still alive.
<add>
<add> Args:
<add> state: A dictionary with the current loop state.
<add>
<add> Returns:
<add> Tuple of
<add> (Top 2*beam_size sequences [batch_size, 2 * beam_size, cur_index + 1],
<add> Scores of returned sequences [batch_size, 2 * beam_size],
<add> New alive cache, for each of the 2 * beam_size sequences)
<add> """
<add> i = state[_StateKeys.CUR_INDEX]
<add> alive_seq = state[_StateKeys.ALIVE_SEQ]
<add> alive_log_probs = state[_StateKeys.ALIVE_LOG_PROBS]
<add> alive_cache = state[_StateKeys.ALIVE_CACHE]
<add>
<add> beams_to_keep = 2 * self.beam_size
<add>
<add> # Get logits for the next candidate IDs for the alive sequences. Get the
<add> # new cache values at the same time.
<add> if self.padded_decode:
<add> flat_ids = tf.reshape(
<add> tf.slice(alive_seq, [0, 0, i], [batch_size, self.beam_size, 1]),
<add> [batch_size * self.beam_size, -1])
<add> else:
<add> flat_ids = _flatten_beam_dim(alive_seq) # [batch_size * beam_size]
<add> flat_cache = tf.nest.map_structure(_flatten_beam_dim, alive_cache)
<add>
<add> flat_logits, flat_cache = self.symbols_to_logits_fn(
<add> flat_ids, i, flat_cache)
<add>
<add> # Unflatten logits to shape [batch_size, beam_size, vocab_size]
<add> logits = _unflatten_beam_dim(flat_logits, batch_size, self.beam_size)
<add> new_cache = tf.nest.map_structure(
<add> lambda t: _unflatten_beam_dim(t, batch_size, self.beam_size),
<add> flat_cache)
<add>
<add> # Convert logits to normalized log probs
<add> candidate_log_probs = _log_prob_from_logits(logits)
<add>
<add> # Calculate new log probabilities if each of the alive sequences were
<add> # extended # by the the candidate IDs.
<add> # Shape [batch_size, beam_size, vocab_size]
<add> log_probs = candidate_log_probs + tf.expand_dims(alive_log_probs, axis=2)
<add>
<add> # Each batch item has beam_size * vocab_size candidate sequences. For each
<add> # batch item, get the k candidates with the highest log probabilities.
<add> flat_log_probs = tf.reshape(log_probs,
<add> [-1, self.beam_size * self.vocab_size])
<add> topk_log_probs, topk_indices = tf.nn.top_k(
<add> flat_log_probs, k=beams_to_keep)
<add>
<add> # Extract the alive sequences that generate the highest log probabilities
<add> # after being extended.
<add> topk_beam_indices = topk_indices // self.vocab_size
<add> topk_seq, new_cache = _gather_beams([alive_seq, new_cache],
<add> topk_beam_indices, batch_size,
<add> beams_to_keep)
<add>
<add> # Append the most probable IDs to the topk sequences
<add> topk_ids = topk_indices % self.vocab_size
<add> if self.padded_decode:
<add> topk_seq = tf.transpose(topk_seq, perm=[2, 0, 1])
<add> # TODO(b/145533236, hongkuny): Reverts once TF fix the validation.
<add> topk_seq = tf.tensor_scatter_nd_update(topk_seq, [[i + 1]],
<add> tf.expand_dims(topk_ids, axis=0))
<add> topk_seq = tf.transpose(topk_seq, perm=[1, 2, 0])
<add> else:
<add> topk_seq = tf.concat(
<add> [topk_seq, tf.expand_dims(topk_ids, axis=2)], axis=2)
<add> return topk_seq, topk_log_probs, topk_ids, new_cache
<add>
<add> def _get_new_alive_state(new_seq, new_log_probs, new_finished_flags,
<add> new_cache):
<add> """Gather the top k sequences that are still alive.
<add>
<add> Args:
<add> new_seq: New sequences generated by growing the current alive sequences
<add> int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1]
<add> new_log_probs: Log probabilities of new sequences float32 tensor with
<add> shape [batch_size, beam_size]
<add> new_finished_flags: A boolean Tensor indicates which sequences are live
<add> inside the beam.
<add> new_cache: Dict of cached values for each sequence.
<add>
<add> Returns:
<add> Dictionary with alive keys from _StateKeys:
<add> {Top beam_size sequences that are still alive (don't end with eos_id)
<add> Log probabilities of top alive sequences
<add> Dict cache storing decoder states for top alive sequences}
<add> """
<add> # To prevent finished sequences from being considered, set log probs to
<add> # -inf.
<add> new_log_probs += tf.cast(new_finished_flags,
<add> self.dtype) * -inf(self.dtype)
<add>
<add> top_alive_seq, top_alive_log_probs, top_alive_cache = _gather_topk_beams(
<add> [new_seq, new_log_probs, new_cache], new_log_probs, batch_size,
<add> self.beam_size)
<add>
<add> return {
<add> _StateKeys.ALIVE_SEQ: top_alive_seq,
<add> _StateKeys.ALIVE_LOG_PROBS: top_alive_log_probs,
<add> _StateKeys.ALIVE_CACHE: top_alive_cache
<add> }
<add>
<add> def _get_new_finished_state(state, new_seq, new_log_probs,
<add> new_finished_flags):
<add> """Combine new and old finished sequences, and gather the top k sequences.
<add>
<add> Args:
<add> state: A dictionary with the current loop state.
<add> new_seq: New sequences generated by growing the current alive sequences
<add> int32 tensor with shape [batch_size, beam_size, i + 1]
<add> new_log_probs: Log probabilities of new sequences float32 tensor with
<add> shape [batch_size, beam_size]
<add> new_finished_flags: A boolean Tensor indicates which sequences are live
<add> inside the beam.
<add>
<add> Returns:
<add> Dictionary with finished keys from _StateKeys:
<add> {Top beam_size finished sequences based on score,
<add> Scores of finished sequences,
<add> Finished flags of finished sequences}
<add> """
<add> i = state[_StateKeys.CUR_INDEX]
<add> finished_seq = state[_StateKeys.FINISHED_SEQ]
<add> finished_scores = state[_StateKeys.FINISHED_SCORES]
<add> finished_flags = state[_StateKeys.FINISHED_FLAGS]
<add>
<add> # First append a column of 0-ids to finished_seq to increment the length.
<add> # New shape of finished_seq: [batch_size, beam_size, i + 1]
<add> if not self.padded_decode:
<add> finished_seq = tf.concat(
<add> [finished_seq,
<add> tf.zeros([batch_size, self.beam_size, 1], tf.int32)],
<add> axis=2)
<add>
<add> # Calculate new seq scores from log probabilities.
<add> length_norm = _length_normalization(self.alpha, i + 1, dtype=self.dtype)
<add> new_scores = new_log_probs / length_norm
<add>
<add> # Set the scores of the still-alive seq in new_seq to large negative
<add> # values.
<add> new_scores += ((1. - tf.cast(new_finished_flags, self.dtype)) *
<add> -inf(self.dtype))
<add>
<add> # Combine sequences, scores, and flags.
<add> finished_seq = tf.concat([finished_seq, new_seq], axis=1)
<add> finished_scores = tf.concat([finished_scores, new_scores], axis=1)
<add> finished_flags = tf.concat([finished_flags, new_finished_flags], axis=1)
<add>
<add> # Return the finished sequences with the best scores.
<add> top_finished_seq, top_finished_scores, top_finished_flags = (
<add> _gather_topk_beams([finished_seq, finished_scores, finished_flags],
<add> finished_scores, batch_size, self.beam_size))
<add>
<add> return {
<add> _StateKeys.FINISHED_SEQ: top_finished_seq,
<add> _StateKeys.FINISHED_SCORES: top_finished_scores,
<add> _StateKeys.FINISHED_FLAGS: top_finished_flags
<add> }
<add>
<add> def _search_step(state):
<add> """Beam search loop body.
<add>
<add> Grow alive sequences by a single ID. Sequences that have reached the EOS
<add> token are marked as finished. The alive and finished sequences with the
<add> highest log probabilities and scores are returned.
<add>
<add> A sequence's finished score is calculating by dividing the log probability
<add> by the length normalization factor. Without length normalization, the
<add> search is more likely to return shorter sequences.
<add>
<add> Args:
<add> state: A dictionary with the current loop state.
<add>
<add> Returns:
<add> new state dictionary.
<add> """
<add> # Grow alive sequences by one token.
<add> new_seq, new_log_probs, topk_ids, new_cache = _grow_alive_seq(state)
<add> new_finished_flags = tf.equal(topk_ids, self.eos_id)
<add> # Collect top beam_size alive sequences
<add> alive_state = _get_new_alive_state(new_seq, new_log_probs,
<add> new_finished_flags, new_cache)
<add>
<add> # Combine newly finished sequences with existing finished sequences, and
<add> # collect the top k scoring sequences.
<add> finished_state = _get_new_finished_state(state, new_seq, new_log_probs,
<add> new_finished_flags)
<add>
<add> # Increment loop index and create new state dictionary
<add> new_state = {_StateKeys.CUR_INDEX: state[_StateKeys.CUR_INDEX] + 1}
<add> new_state.update(alive_state)
<add> new_state.update(finished_state)
<add> return [new_state]
<add>
<add> finished_state = tf.nest.map_structure(
<add> tf.stop_gradient,
<add> tf.while_loop(
<add> self._continue_search,
<add> _search_step,
<add> loop_vars=[state],
<add> shape_invariants=[state_shapes],
<add> parallel_iterations=1))
<add> finished_state = finished_state[0]
<add> return self._process_finished_state(finished_state)
<add>
<add> def _process_finished_state(self, finished_state):
<add> alive_seq = finished_state[_StateKeys.ALIVE_SEQ]
<add> alive_log_probs = finished_state[_StateKeys.ALIVE_LOG_PROBS]
<add> finished_seq = finished_state[_StateKeys.FINISHED_SEQ]
<add> finished_scores = finished_state[_StateKeys.FINISHED_SCORES]
<add> finished_flags = finished_state[_StateKeys.FINISHED_FLAGS]
<add> # TF2 changes tf.where behavior. Should make parameters broadcastable.
<add> finished_cond = tf.reduce_any(finished_flags, 1, name="finished_cond")
<add> seq_cond = _expand_to_same_rank(finished_cond, finished_seq)
<add> score_cond = _expand_to_same_rank(finished_cond, finished_scores)
<add>
<add> # Account for corner case where there are no finished sequences for a
<add> # particular batch item. In that case, return alive sequences for that batch
<add> # item.
<add> finished_seq = tf.where(seq_cond, finished_seq, alive_seq)
<add> finished_scores = tf.where(score_cond, finished_scores, alive_log_probs)
<add> return finished_seq, finished_scores
<add>
<add> def _create_initial_state(self, initial_ids, initial_cache, batch_size):
<add> """Return initial state dictionary and its shape invariants."""
<add> for key, value in initial_cache.items():
<add> for inner_value in tf.nest.flatten(value):
<add> if inner_value.dtype != self.dtype:
<add> raise TypeError(
<add> "initial_cache element for key '%s' has dtype %s that does not "
<add> "match SequenceBeamSearch's dtype of %s. Value: %s" %
<add> (key, value.dtype.name, self.dtype.name, inner_value))
<add>
<add> # Current loop index (starts at 0)
<add> cur_index = tf.constant(0)
<add>
<add> # Create alive sequence with shape [batch_size, beam_size, 1]
<add> alive_seq = _expand_to_beam_size(initial_ids, self.beam_size)
<add> alive_seq = tf.expand_dims(alive_seq, axis=2)
<add> if self.padded_decode:
<add> alive_seq = tf.tile(alive_seq, [1, 1, self.max_decode_length + 1])
<add>
<add> # Create tensor for storing initial log probabilities.
<add> # Assume initial_ids are prob 1.0
<add> initial_log_probs = tf.constant([[0.] + [-float("inf")] *
<add> (self.beam_size - 1)],
<add> dtype=self.dtype)
<add> alive_log_probs = tf.tile(initial_log_probs, [batch_size, 1])
<add>
<add> # Expand all values stored in the dictionary to the beam size, so that each
<add> # beam has a separate cache.
<add> alive_cache = tf.nest.map_structure(
<add> lambda t: _expand_to_beam_size(t, self.beam_size), initial_cache)
<add>
<add> # Initialize tensor storing finished sequences with filler values.
<add> finished_seq = tf.zeros(tf.shape(alive_seq), tf.int32)
<add>
<add> # Set scores of the initial finished seqs to negative infinity.
<add> finished_scores = tf.ones([batch_size, self.beam_size],
<add> dtype=self.dtype) * -inf(self.dtype)
<add>
<add> # Initialize finished flags with all False values.
<add> finished_flags = tf.zeros([batch_size, self.beam_size], tf.bool)
<add>
<add> # Create state dictionary
<add> state = {
<add> _StateKeys.CUR_INDEX: cur_index,
<add> _StateKeys.ALIVE_SEQ: alive_seq,
<add> _StateKeys.ALIVE_LOG_PROBS: alive_log_probs,
<add> _StateKeys.ALIVE_CACHE: alive_cache,
<add> _StateKeys.FINISHED_SEQ: finished_seq,
<add> _StateKeys.FINISHED_SCORES: finished_scores,
<add> _StateKeys.FINISHED_FLAGS: finished_flags
<add> }
<add>
<add> # Create state invariants for each value in the state dictionary. Each
<add> # dimension must be a constant or None. A None dimension means either:
<add> # 1) the dimension's value is a tensor that remains the same but may
<add> # depend on the input sequence to the model (e.g. batch size).
<add> # 2) the dimension may have different values on different iterations.
<add> if self.padded_decode:
<add> state_shape_invariants = {
<add> _StateKeys.CUR_INDEX:
<add> tf.TensorShape([]),
<add> _StateKeys.ALIVE_SEQ:
<add> tf.TensorShape(
<add> [batch_size, self.beam_size, self.max_decode_length + 1]),
<add> _StateKeys.ALIVE_LOG_PROBS:
<add> tf.TensorShape([batch_size, self.beam_size]),
<add> _StateKeys.ALIVE_CACHE:
<add> tf.nest.map_structure(_get_shape, alive_cache),
<add> _StateKeys.FINISHED_SEQ:
<add> tf.TensorShape(
<add> [batch_size, self.beam_size, self.max_decode_length + 1]),
<add> _StateKeys.FINISHED_SCORES:
<add> tf.TensorShape([batch_size, self.beam_size]),
<add> _StateKeys.FINISHED_FLAGS:
<add> tf.TensorShape([batch_size, self.beam_size])
<add> }
<add> else:
<add> state_shape_invariants = {
<add> _StateKeys.CUR_INDEX:
<add> tf.TensorShape([]),
<add> _StateKeys.ALIVE_SEQ:
<add> tf.TensorShape([None, self.beam_size, None]),
<add> _StateKeys.ALIVE_LOG_PROBS:
<add> tf.TensorShape([None, self.beam_size]),
<add> _StateKeys.ALIVE_CACHE:
<add> tf.nest.map_structure(_get_shape_keep_last_dim, alive_cache),
<add> _StateKeys.FINISHED_SEQ:
<add> tf.TensorShape([None, self.beam_size, None]),
<add> _StateKeys.FINISHED_SCORES:
<add> tf.TensorShape([None, self.beam_size]),
<add> _StateKeys.FINISHED_FLAGS:
<add> tf.TensorShape([None, self.beam_size])
<add> }
<add>
<add> return state, state_shape_invariants
<add>
<add> def _continue_search(self, state):
<add> """Return whether to continue the search loop.
<add>
<add> The loops should terminate when
<add> 1) when decode length has been reached, or
<add> 2) when the worst score in the finished sequences is better than the best
<add> score in the alive sequences (i.e. the finished sequences are provably
<add> unchanging)
<add>
<add> Args:
<add> state: A dictionary with the current loop state.
<add>
<add> Returns:
<add> Bool tensor with value True if loop should continue, False if loop should
<add> terminate.
<add> """
<add> i = state[_StateKeys.CUR_INDEX]
<add> alive_log_probs = state[_StateKeys.ALIVE_LOG_PROBS]
<add> finished_scores = state[_StateKeys.FINISHED_SCORES]
<add> finished_flags = state[_StateKeys.FINISHED_FLAGS]
<add>
<add> not_at_max_decode_length = tf.less(i, self.max_decode_length)
<add>
<add> # Calculate largest length penalty (the larger penalty, the better score).
<add> max_length_norm = _length_normalization(
<add> self.alpha, self.max_decode_length, dtype=self.dtype)
<add> # Get the best possible scores from alive sequences.
<add> best_alive_scores = alive_log_probs[:, 0] / max_length_norm
<add>
<add> # Compute worst score in finished sequences for each batch element
<add> finished_scores *= tf.cast(finished_flags,
<add> self.dtype) # set filler scores to zero
<add> lowest_finished_scores = tf.reduce_min(finished_scores, axis=1)
<add>
<add> # If there are no finished sequences in a batch element, then set the lowest
<add> # finished score to -INF for that element.
<add> finished_batches = tf.reduce_any(finished_flags, 1)
<add> lowest_finished_scores += ((1.0 - tf.cast(finished_batches, self.dtype)) *
<add> -inf(self.dtype))
<add>
<add> worst_finished_score_better_than_best_alive_score = tf.reduce_all(
<add> tf.greater(lowest_finished_scores, best_alive_scores))
<add>
<add> return tf.logical_and(
<add> not_at_max_decode_length,
<add> tf.logical_not(worst_finished_score_better_than_best_alive_score))
<add>
<add>
<add>def sequence_beam_search(symbols_to_logits_fn,
<add> initial_ids,
<add> initial_cache,
<add> vocab_size,
<add> beam_size,
<add> alpha,
<add> max_decode_length,
<add> eos_id,
<add> padded_decode=False,
<add> dtype="float32"):
<add> """Search for sequence of subtoken ids with the largest probability.
<add>
<add> Args:
<add> symbols_to_logits_fn: A function that takes in ids, index, and cache as
<add> arguments. The passed in arguments will have shape: ids -> A tensor with
<add> shape [batch_size * beam_size, index]. index -> A scalar. cache -> A
<add> nested dictionary of tensors [batch_size * beam_size, ...].
<add> The function must return a tuple of logits and new cache: logits -> A
<add> tensor with shape [batch * beam_size, vocab_size]. new cache -> A nested
<add> dictionary with the same shape/structure as the inputted cache.
<add> initial_ids: An int32 tensor with shape [batch_size]. Starting ids for each
<add> batch item.
<add> initial_cache: A dictionary, containing starting decoder variables
<add> information.
<add> vocab_size: An integer, the size of tokens.
<add> beam_size: An integer, the number of beams.
<add> alpha: A float, defining the strength of length normalization.
<add> max_decode_length: An integer, the maximum length to decoded a sequence.
<add> eos_id: An integer, ID of eos token, used to determine when a sequence has
<add> finished.
<add> padded_decode: A bool, indicating if max_sequence_length padding is used for
<add> beam search.
<add> dtype: A tensorflow data type used for score computation. The default is
<add> tf.float32.
<add>
<add> Returns:
<add> Top decoded sequences [batch_size, beam_size, max_decode_length]
<add> sequence scores [batch_size, beam_size]
<add> """
<add> sbs = SequenceBeamSearch(symbols_to_logits_fn, vocab_size, beam_size, alpha,
<add> max_decode_length, eos_id, padded_decode, dtype)
<add> return sbs.search(initial_ids, initial_cache)
<add>
<add>
<add>def _log_prob_from_logits(logits):
<add> return logits - tf.reduce_logsumexp(logits, axis=2, keepdims=True)
<add>
<add>
<add>def _length_normalization(alpha, length, dtype=tf.float32):
<add> """Return length normalization factor."""
<add> return tf.pow(((5. + tf.cast(length, dtype)) / 6.), alpha)
<add>
<add>
<add>def _expand_to_beam_size(tensor, beam_size):
<add> """Tiles a given tensor by beam_size.
<add>
<add> Args:
<add> tensor: tensor to tile [batch_size, ...]
<add> beam_size: How much to tile the tensor by.
<add>
<add> Returns:
<add> Tiled tensor [batch_size, beam_size, ...]
<add> """
<add> tensor = tf.expand_dims(tensor, axis=1)
<add> tile_dims = [1] * tensor.shape.ndims
<add> tile_dims[1] = beam_size
<add>
<add> return tf.tile(tensor, tile_dims)
<add>
<add>
<add>def _shape_list(tensor):
<add> """Return a list of the tensor's shape, and ensure no None values in list."""
<add> # Get statically known shape (may contain None's for unknown dimensions)
<add> shape = tensor.get_shape().as_list()
<add>
<add> # Ensure that the shape values are not None
<add> dynamic_shape = tf.shape(tensor)
<add> for i in range(len(shape)): # pylint: disable=consider-using-enumerate
<add> if shape[i] is None:
<add> shape[i] = dynamic_shape[i]
<add> return shape
<add>
<add>
<add>def _get_shape_keep_last_dim(tensor):
<add> shape_list = _shape_list(tensor)
<add>
<add> # Only the last
<add> for i in range(len(shape_list) - 1):
<add> shape_list[i] = None
<add>
<add> if isinstance(shape_list[-1], tf.Tensor):
<add> shape_list[-1] = None
<add> return tf.TensorShape(shape_list)
<add>
<add>
<add>def _get_shape(tensor):
<add> """Return the shape of the input tensor."""
<add> return tf.TensorShape(_shape_list(tensor))
<add>
<add>
<add>def _flatten_beam_dim(tensor):
<add> """Reshapes first two dimensions in to single dimension.
<add>
<add> Args:
<add> tensor: Tensor to reshape of shape [A, B, ...]
<add>
<add> Returns:
<add> Reshaped tensor of shape [A*B, ...]
<add> """
<add> shape = _shape_list(tensor)
<add> shape[0] *= shape[1]
<add> shape.pop(1) # Remove beam dim
<add> return tf.reshape(tensor, shape)
<add>
<add>
<add>def _unflatten_beam_dim(tensor, batch_size, beam_size):
<add> """Reshapes first dimension back to [batch_size, beam_size].
<add>
<add> Args:
<add> tensor: Tensor to reshape of shape [batch_size*beam_size, ...]
<add> batch_size: Tensor, original batch size.
<add> beam_size: int, original beam size.
<add>
<add> Returns:
<add> Reshaped tensor of shape [batch_size, beam_size, ...]
<add> """
<add> shape = _shape_list(tensor)
<add> new_shape = [batch_size, beam_size] + shape[1:]
<add> return tf.reshape(tensor, new_shape)
<add>
<add>
<add>def _gather_beams(nested, beam_indices, batch_size, new_beam_size):
<add> """Gather beams from nested structure of tensors.
<add>
<add> Each tensor in nested represents a batch of beams, where beam refers to a
<add> single search state (beam search involves searching through multiple states
<add> in parallel).
<add>
<add> This function is used to gather the top beams, specified by
<add> beam_indices, from the nested tensors.
<add>
<add> Args:
<add> nested: Nested structure (tensor, list, tuple or dict) containing tensors
<add> with shape [batch_size, beam_size, ...].
<add> beam_indices: int32 tensor with shape [batch_size, new_beam_size]. Each
<add> value in beam_indices must be between [0, beam_size), and are not
<add> necessarily unique.
<add> batch_size: int size of batch
<add> new_beam_size: int number of beams to be pulled from the nested tensors.
<add>
<add> Returns:
<add> Nested structure containing tensors with shape
<add> [batch_size, new_beam_size, ...]
<add> """
<add> # Computes the i'th coodinate that contains the batch index for gather_nd.
<add> # Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..].
<add> batch_pos = tf.range(batch_size * new_beam_size) // new_beam_size
<add> batch_pos = tf.reshape(batch_pos, [batch_size, new_beam_size])
<add>
<add> # Create coordinates to be passed to tf.gather_nd. Stacking creates a tensor
<add> # with shape [batch_size, beam_size, 2], where the last dimension contains
<add> # the (i, j) gathering coordinates.
<add> coordinates = tf.stack([batch_pos, beam_indices], axis=2)
<add>
<add> return tf.nest.map_structure(lambda state: tf.gather_nd(state, coordinates),
<add> nested)
<add>
<add>
<add>def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size):
<add> """Gather top beams from nested structure."""
<add> _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size)
<add> return _gather_beams(nested, topk_indexes, batch_size, beam_size)
<add><path>official/nlp/modeling/ops/beam_search_test.py
<del><path>official/nlp/transformer/beam_search_v1_test.py
<ide> # ==============================================================================
<ide> """Test beam search helper methods."""
<ide>
<del>import tensorflow.compat.v1 as tf
<add>import tensorflow as tf
<ide>
<del>from official.nlp.transformer import beam_search_v1 as beam_search
<add>from official.nlp.modeling.ops import beam_search
<ide>
<ide>
<ide> class BeamSearchHelperTests(tf.test.TestCase):
<ide>
<del> def setUp(self):
<del> super(BeamSearchHelperTests, self).setUp()
<del> tf.compat.v1.disable_eager_execution()
<del>
<ide> def test_expand_to_beam_size(self):
<ide> x = tf.ones([7, 4, 2, 5])
<ide> x = beam_search._expand_to_beam_size(x, 3)
<del> with self.session() as sess:
<del> shape = sess.run(tf.shape(x))
<add> shape = tf.shape(x)
<ide> self.assertAllEqual([7, 3, 4, 2, 5], shape)
<ide>
<del> def test_shape_list(self):
<del> y = tf.compat.v1.placeholder(dtype=tf.int32, shape=[])
<del> x = tf.ones([7, y, 2, 5])
<del> shape = beam_search._shape_list(x)
<del> self.assertIsInstance(shape[0], int)
<del> self.assertIsInstance(shape[1], tf.Tensor)
<del> self.assertIsInstance(shape[2], int)
<del> self.assertIsInstance(shape[3], int)
<del>
<ide> def test_get_shape_keep_last_dim(self):
<ide> y = tf.constant(4.0)
<ide> x = tf.ones([7, tf.cast(tf.sqrt(y), tf.int32), 2, 5])
<ide> def test_get_shape_keep_last_dim(self):
<ide> def test_flatten_beam_dim(self):
<ide> x = tf.ones([7, 4, 2, 5])
<ide> x = beam_search._flatten_beam_dim(x)
<del> with self.session() as sess:
<del> shape = sess.run(tf.shape(x))
<del> self.assertAllEqual([28, 2, 5], shape)
<add> self.assertAllEqual([28, 2, 5], tf.shape(x))
<ide>
<ide> def test_unflatten_beam_dim(self):
<ide> x = tf.ones([28, 2, 5])
<ide> x = beam_search._unflatten_beam_dim(x, 7, 4)
<del> with self.session() as sess:
<del> shape = sess.run(tf.shape(x))
<del> self.assertAllEqual([7, 4, 2, 5], shape)
<add> self.assertAllEqual([7, 4, 2, 5], tf.shape(x))
<ide>
<ide> def test_gather_beams(self):
<ide> x = tf.reshape(tf.range(24), [2, 3, 4])
<ide> def test_gather_beams(self):
<ide> # [20 21 22 23]]]
<ide>
<ide> y = beam_search._gather_beams(x, [[1, 2], [0, 2]], 2, 2)
<del> with self.session() as sess:
<del> y = sess.run(y)
<del>
<ide> self.assertAllEqual([[[4, 5, 6, 7],
<ide> [8, 9, 10, 11]],
<ide> [[12, 13, 14, 15],
<ide> def test_gather_topk_beams(self):
<ide> x_scores = [[0, 1, 1], [1, 0, 1]]
<ide>
<ide> y = beam_search._gather_topk_beams(x, x_scores, 2, 2)
<del> with self.session() as sess:
<del> y = sess.run(y)
<del>
<ide> self.assertAllEqual([[[4, 5, 6, 7],
<ide> [8, 9, 10, 11]],
<ide> [[12, 13, 14, 15],
<ide><path>official/nlp/nhnet/models.py
<ide> from official.nlp.nhnet import configs
<ide> from official.nlp.nhnet import decoder
<ide> from official.nlp.nhnet import utils
<del>from official.nlp.transformer import beam_search
<add>from official.nlp.modeling.ops import beam_search
<ide>
<ide>
<ide> def embedding_linear(embedding_matrix, x):
<ide><path>official/nlp/transformer/beam_search.py
<del># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
<del>#
<del># Licensed under the Apache License, Version 2.0 (the "License");
<del># you may not use this file except in compliance with the License.
<del># You may obtain a copy of the License at
<del>#
<del># http://www.apache.org/licenses/LICENSE-2.0
<del>#
<del># Unless required by applicable law or agreed to in writing, software
<del># distributed under the License is distributed on an "AS IS" BASIS,
<del># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del># See the License for the specific language governing permissions and
<del># limitations under the License.
<del># ==============================================================================
<del>"""Beam search in TF v2."""
<del>
<del>import tensorflow as tf
<del>
<del>from official.nlp.transformer import beam_search_v1 as v1
<del>
<del>_StateKeys = v1._StateKeys # pylint: disable=protected-access
<del>
<del>
<del>class SequenceBeamSearchV2(v1.SequenceBeamSearch):
<del> """Implementation of beam search loop in v2."""
<del>
<del> def search(self, initial_ids, initial_cache):
<del> """Beam search for sequences with highest scores."""
<del> state, state_shapes = self._create_initial_state(initial_ids, initial_cache)
<del>
<del> finished_state = tf.nest.map_structure(
<del> tf.stop_gradient,
<del> tf.while_loop(self._continue_search,
<del> self._search_step,
<del> loop_vars=[state],
<del> shape_invariants=[state_shapes],
<del> parallel_iterations=1))
<del> finished_state = finished_state[0]
<del>
<del> alive_seq = finished_state[_StateKeys.ALIVE_SEQ]
<del> alive_log_probs = finished_state[_StateKeys.ALIVE_LOG_PROBS]
<del> finished_seq = finished_state[_StateKeys.FINISHED_SEQ]
<del> finished_scores = finished_state[_StateKeys.FINISHED_SCORES]
<del> finished_flags = finished_state[_StateKeys.FINISHED_FLAGS]
<del>
<del> # 2.0 changes tf.where behavior. Should make parameters broadcastable.
<del> finished_cond = tf.reduce_any(finished_flags, 1, name="finished_cond")
<del> seq_cond = _expand_to_same_rank(finished_cond, finished_seq)
<del> score_cond = _expand_to_same_rank(finished_cond, finished_scores)
<del>
<del> # Account for corner case where there are no finished sequences for a
<del> # particular batch item. In that case, return alive sequences for that batch
<del> # item.
<del> finished_seq = tf.where(seq_cond, finished_seq, alive_seq)
<del> finished_scores = tf.where(
<del> score_cond, finished_scores, alive_log_probs)
<del> return finished_seq, finished_scores
<del>
<del>
<del>def sequence_beam_search(symbols_to_logits_fn,
<del> initial_ids,
<del> initial_cache,
<del> vocab_size,
<del> beam_size,
<del> alpha,
<del> max_decode_length,
<del> eos_id,
<del> padded_decode=False,
<del> dtype="float32"):
<del> """Search for sequence of subtoken ids with the largest probability.
<del>
<del> Args:
<del> symbols_to_logits_fn: A function that takes in ids, index, and cache as
<del> arguments. The passed in arguments will have shape:
<del> ids -> A tensor with shape [batch_size * beam_size, index].
<del> index -> A scalar.
<del> cache -> A nested dictionary of tensors [batch_size * beam_size, ...].
<del> The function must return a tuple of logits and new cache:
<del> logits -> A tensor with shape [batch * beam_size, vocab_size].
<del> new cache -> A nested dictionary with the same shape/structure as the
<del> inputted cache.
<del> initial_ids: An int32 tensor with shape [batch_size]. Starting ids for
<del> each batch item.
<del> initial_cache: A dictionary, containing starting decoder variables
<del> information.
<del> vocab_size: An integer, the size of tokens.
<del> beam_size: An integer, the number of beams.
<del> alpha: A float, defining the strength of length normalization.
<del> max_decode_length: An integer, the maximum length to decoded a sequence.
<del> eos_id: An integer, ID of eos token, used to determine when a sequence has
<del> finished.
<del> padded_decode: A bool, indicating if max_sequence_length padding is used
<del> for beam search.
<del> dtype: A tensorflow data type used for score computation. The default is
<del> tf.float32.
<del>
<del> Returns:
<del> Top decoded sequences [batch_size, beam_size, max_decode_length]
<del> sequence scores [batch_size, beam_size]
<del> """
<del> batch_size = (
<del> initial_ids.shape.as_list()[0] if padded_decode else
<del> tf.shape(initial_ids)[0])
<del> sbs = SequenceBeamSearchV2(symbols_to_logits_fn, vocab_size, batch_size,
<del> beam_size, alpha, max_decode_length, eos_id,
<del> padded_decode, dtype)
<del> return sbs.search(initial_ids, initial_cache)
<del>
<del>
<del>def _expand_to_same_rank(tensor, target):
<del> """Expands a given tensor to target's rank to be broadcastable.
<del>
<del> Args:
<del> tensor: input tensor to tile. Shape: [b, d1, ..., da]
<del> target: target tensor. Shape: [b, d1, ..., da, ..., dn]
<del>
<del> Returns:
<del> Tiled tensor of shape [b, d1, ..., da, 1, ..., 1] with same rank of target.
<del>
<del> Raises:
<del> ValueError, if the shape rank of rank tensor/target is None.
<del> """
<del> if tensor.shape.rank is None:
<del> raise ValueError("Expect rank for tensor shape, but got None.")
<del> if target.shape.rank is None:
<del> raise ValueError("Expect rank for target shape, but got None.")
<del>
<del> with tf.name_scope("expand_rank"):
<del> diff_rank = target.shape.rank - tensor.shape.rank
<del> for _ in range(diff_rank):
<del> tensor = tf.expand_dims(tensor, -1)
<del> return tensor
<ide><path>official/nlp/transformer/beam_search_v1.py
<ide> # limitations under the License.
<ide> # ==============================================================================
<ide> """Beam search to find the translated sequence with the highest probability.
<del>
<del>Source implementation from Tensor2Tensor:
<del>https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/beam_search.py
<ide> """
<ide>
<del>import numpy as np
<ide> import tensorflow.compat.v1 as tf
<del>from tensorflow.python.util import nest
<del>
<del>
<del>def inf(dtype):
<del> """Returns a value close to infinity, but is still finite in `dtype`.
<del>
<del> This is useful to get a very large value that is still zero when multiplied by
<del> zero. The floating-point "Inf" value is NaN when multiplied by zero.
<del>
<del> Args:
<del> dtype: A dtype. The returned value will be finite when casted to this dtype.
<del>
<del> Returns:
<del> A very large value.
<del> """
<del> if dtype == "float32" or dtype == "bfloat16":
<del> return 1e7
<del> elif dtype == "float16":
<del> # Disable no-member lint error, as the linter thinks np.float16 does not
<del> # exist for some reason.
<del> return np.finfo(np.float16).max # pylint: disable=no-member
<del> else:
<del> raise AssertionError('Invalid dtype: %s' % dtype)
<del>
<del>
<del>class _StateKeys(object):
<del> """Keys to dictionary storing the state of the beam search loop."""
<del>
<del> # Variable storing the loop index.
<del> CUR_INDEX = "CUR_INDEX"
<add>from official.nlp.modeling.ops import beam_search
<ide>
<del> # Top sequences that are alive for each batch item. Alive sequences are ones
<del> # that have not generated an EOS token. Sequences that reach EOS are marked as
<del> # finished and moved to the FINISHED_SEQ tensor.
<del> # Has shape [batch_size, beam_size, CUR_INDEX + 1]
<del> ALIVE_SEQ = "ALIVE_SEQ"
<del> # Log probabilities of each alive sequence. Shape [batch_size, beam_size]
<del> ALIVE_LOG_PROBS = "ALIVE_LOG_PROBS"
<del> # Dictionary of cached values for each alive sequence. The cache stores
<del> # the encoder output, attention bias, and the decoder attention output from
<del> # the previous iteration.
<del> ALIVE_CACHE = "ALIVE_CACHE"
<add>_StateKeys = beam_search._StateKeys # pylint: disable=protected-access
<ide>
<del> # Top finished sequences for each batch item.
<del> # Has shape [batch_size, beam_size, CUR_INDEX + 1]. Sequences that are
<del> # shorter than CUR_INDEX + 1 are padded with 0s.
<del> FINISHED_SEQ = "FINISHED_SEQ"
<del> # Scores for each finished sequence. Score = log probability / length norm
<del> # Shape [batch_size, beam_size]
<del> FINISHED_SCORES = "FINISHED_SCORES"
<del> # Flags indicating which sequences in the finished sequences are finished.
<del> # At the beginning, all of the sequences in FINISHED_SEQ are filler values.
<del> # True -> finished sequence, False -> filler. Shape [batch_size, beam_size]
<del> FINISHED_FLAGS = "FINISHED_FLAGS"
<ide>
<del>
<del>class SequenceBeamSearch(object):
<add>class SequenceBeamSearch(beam_search.SequenceBeamSearch):
<ide> """Implementation of beam search loop."""
<ide>
<del> def __init__(self,
<del> symbols_to_logits_fn,
<del> vocab_size,
<del> batch_size,
<del> beam_size,
<del> alpha,
<del> max_decode_length,
<del> eos_id,
<del> padded_decode,
<del> dtype=tf.float32):
<del> """Initialize sequence beam search.
<del>
<del> Args:
<del> symbols_to_logits_fn: A function to provide logits, which is the
<del> interface to the Transformer model. The passed in arguments are:
<del> ids -> A tensor with shape [batch_size * beam_size, index].
<del> index -> A scalar.
<del> cache -> A nested dictionary of tensors [batch_size * beam_size, ...].
<del> The function must return a tuple of logits and the updated cache:
<del> logits -> A tensor with shape [batch * beam_size, vocab_size].
<del> updated cache -> A nested dictionary with the same structure as the
<del> input cache.
<del> vocab_size: An integer, the size of the vocabulary, used for topk
<del> computation.
<del> batch_size: An integer, the decode batch size.
<del> beam_size: An integer, number of beams for beam search.
<del> alpha: A float, defining the strength of length normalization.
<del> max_decode_length: An integer, the maximum number of steps to decode
<del> a sequence.
<del> eos_id: An integer. ID of end of sentence token.
<del> padded_decode: A bool, indicating if max_sequence_length padding is used
<del> for beam search.
<del> dtype: A tensorflow data type used for score computation. The default is
<del> tf.float32.
<del> """
<del> self.symbols_to_logits_fn = symbols_to_logits_fn
<del> self.vocab_size = vocab_size
<del> self.batch_size = batch_size
<del> self.beam_size = beam_size
<del> self.alpha = alpha
<del> self.max_decode_length = max_decode_length
<del> self.eos_id = eos_id
<del> self.padded_decode = padded_decode
<del> self.dtype = tf.as_dtype(dtype)
<del>
<del> def search(self, initial_ids, initial_cache):
<del> """Beam search for sequences with highest scores."""
<del> state, state_shapes = self._create_initial_state(initial_ids, initial_cache)
<del>
<del> finished_state = tf.while_loop(
<del> self._continue_search, self._search_step, loop_vars=[state],
<del> shape_invariants=[state_shapes], parallel_iterations=1, back_prop=False)
<del> finished_state = finished_state[0]
<del>
<add> def _process_finished_state(self, finished_state):
<ide> alive_seq = finished_state[_StateKeys.ALIVE_SEQ]
<ide> alive_log_probs = finished_state[_StateKeys.ALIVE_LOG_PROBS]
<ide> finished_seq = finished_state[_StateKeys.FINISHED_SEQ]
<ide> def search(self, initial_ids, initial_cache):
<ide> tf.reduce_any(finished_flags, 1), finished_scores, alive_log_probs)
<ide> return finished_seq, finished_scores
<ide>
<del> def _create_initial_state(self, initial_ids, initial_cache):
<del> """Return initial state dictionary and its shape invariants.
<del>
<del> Args:
<del> initial_ids: initial ids to pass into the symbols_to_logits_fn.
<del> int tensor with shape [batch_size, 1]
<del> initial_cache: dictionary storing values to be passed into the
<del> symbols_to_logits_fn.
<del>
<del> Returns:
<del> state and shape invariant dictionaries with keys from _StateKeys
<del> """
<del> for key, value in initial_cache.items():
<del> for inner_value in nest.flatten(value):
<del> if inner_value.dtype != self.dtype:
<del> raise TypeError(
<del> "initial_cache element for key '%s' has dtype %s that does not "
<del> "match SequenceBeamSearch's dtype of %s. Value: %s" %
<del> (key, value.dtype.name, self.dtype.name, inner_value))
<del>
<del> # Current loop index (starts at 0)
<del> cur_index = tf.constant(0)
<del>
<del> # Create alive sequence with shape [batch_size, beam_size, 1]
<del> alive_seq = _expand_to_beam_size(initial_ids, self.beam_size)
<del> alive_seq = tf.expand_dims(alive_seq, axis=2)
<del> if self.padded_decode:
<del> alive_seq = tf.tile(alive_seq, [1, 1, self.max_decode_length + 1])
<del>
<del> # Create tensor for storing initial log probabilities.
<del> # Assume initial_ids are prob 1.0
<del> initial_log_probs = tf.constant(
<del> [[0.] + [-float("inf")] * (self.beam_size - 1)], dtype=self.dtype)
<del> alive_log_probs = tf.tile(initial_log_probs, [self.batch_size, 1])
<del>
<del> # Expand all values stored in the dictionary to the beam size, so that each
<del> # beam has a separate cache.
<del> alive_cache = nest.map_structure(
<del> lambda t: _expand_to_beam_size(t, self.beam_size), initial_cache)
<del>
<del> # Initialize tensor storing finished sequences with filler values.
<del> finished_seq = tf.zeros(tf.shape(alive_seq), tf.int32)
<del>
<del> # Set scores of the initial finished seqs to negative infinity.
<del> finished_scores = tf.ones([self.batch_size, self.beam_size],
<del> dtype=self.dtype) * -inf(self.dtype)
<del>
<del> # Initialize finished flags with all False values.
<del> finished_flags = tf.zeros([self.batch_size, self.beam_size], tf.bool)
<del>
<del> # Create state dictionary
<del> state = {
<del> _StateKeys.CUR_INDEX: cur_index,
<del> _StateKeys.ALIVE_SEQ: alive_seq,
<del> _StateKeys.ALIVE_LOG_PROBS: alive_log_probs,
<del> _StateKeys.ALIVE_CACHE: alive_cache,
<del> _StateKeys.FINISHED_SEQ: finished_seq,
<del> _StateKeys.FINISHED_SCORES: finished_scores,
<del> _StateKeys.FINISHED_FLAGS: finished_flags
<del> }
<del>
<del> # Create state invariants for each value in the state dictionary. Each
<del> # dimension must be a constant or None. A None dimension means either:
<del> # 1) the dimension's value is a tensor that remains the same but may
<del> # depend on the input sequence to the model (e.g. batch size).
<del> # 2) the dimension may have different values on different iterations.
<del> if self.padded_decode:
<del> state_shape_invariants = {
<del> _StateKeys.CUR_INDEX:
<del> tf.TensorShape([]),
<del> _StateKeys.ALIVE_SEQ:
<del> tf.TensorShape(
<del> [self.batch_size, self.beam_size,
<del> self.max_decode_length + 1]),
<del> _StateKeys.ALIVE_LOG_PROBS:
<del> tf.TensorShape([self.batch_size, self.beam_size]),
<del> _StateKeys.ALIVE_CACHE:
<del> nest.map_structure(_get_shape, alive_cache),
<del> _StateKeys.FINISHED_SEQ:
<del> tf.TensorShape(
<del> [self.batch_size, self.beam_size,
<del> self.max_decode_length + 1]),
<del> _StateKeys.FINISHED_SCORES:
<del> tf.TensorShape([self.batch_size, self.beam_size]),
<del> _StateKeys.FINISHED_FLAGS:
<del> tf.TensorShape([self.batch_size, self.beam_size])
<del> }
<del> else:
<del> state_shape_invariants = {
<del> _StateKeys.CUR_INDEX:
<del> tf.TensorShape([]),
<del> _StateKeys.ALIVE_SEQ:
<del> tf.TensorShape([None, self.beam_size, None]),
<del> _StateKeys.ALIVE_LOG_PROBS:
<del> tf.TensorShape([None, self.beam_size]),
<del> _StateKeys.ALIVE_CACHE:
<del> nest.map_structure(_get_shape_keep_last_dim, alive_cache),
<del> _StateKeys.FINISHED_SEQ:
<del> tf.TensorShape([None, self.beam_size, None]),
<del> _StateKeys.FINISHED_SCORES:
<del> tf.TensorShape([None, self.beam_size]),
<del> _StateKeys.FINISHED_FLAGS:
<del> tf.TensorShape([None, self.beam_size])
<del> }
<del>
<del> return state, state_shape_invariants
<del>
<del> def _continue_search(self, state):
<del> """Return whether to continue the search loop.
<del>
<del> The loops should terminate when
<del> 1) when decode length has been reached, or
<del> 2) when the worst score in the finished sequences is better than the best
<del> score in the alive sequences (i.e. the finished sequences are provably
<del> unchanging)
<del>
<del> Args:
<del> state: A dictionary with the current loop state.
<del>
<del> Returns:
<del> Bool tensor with value True if loop should continue, False if loop should
<del> terminate.
<del> """
<del> i = state[_StateKeys.CUR_INDEX]
<del> alive_log_probs = state[_StateKeys.ALIVE_LOG_PROBS]
<del> finished_scores = state[_StateKeys.FINISHED_SCORES]
<del> finished_flags = state[_StateKeys.FINISHED_FLAGS]
<del>
<del> not_at_max_decode_length = tf.less(i, self.max_decode_length)
<del>
<del> # Calculate largest length penalty (the larger penalty, the better score).
<del> max_length_norm = _length_normalization(self.alpha, self.max_decode_length,
<del> dtype=self.dtype)
<del> # Get the best possible scores from alive sequences.
<del> best_alive_scores = alive_log_probs[:, 0] / max_length_norm
<del>
<del> # Compute worst score in finished sequences for each batch element
<del> finished_scores *= tf.cast(finished_flags,
<del> self.dtype) # set filler scores to zero
<del> lowest_finished_scores = tf.reduce_min(finished_scores, axis=1)
<del>
<del> # If there are no finished sequences in a batch element, then set the lowest
<del> # finished score to -INF for that element.
<del> finished_batches = tf.reduce_any(finished_flags, 1)
<del> lowest_finished_scores += ((1.0 -
<del> tf.cast(finished_batches, self.dtype)) *
<del> -inf(self.dtype))
<del>
<del> worst_finished_score_better_than_best_alive_score = tf.reduce_all(
<del> tf.greater(lowest_finished_scores, best_alive_scores)
<del> )
<del>
<del> return tf.logical_and(
<del> not_at_max_decode_length,
<del> tf.logical_not(worst_finished_score_better_than_best_alive_score)
<del> )
<del>
<del> def _search_step(self, state):
<del> """Beam search loop body.
<del>
<del> Grow alive sequences by a single ID. Sequences that have reached the EOS
<del> token are marked as finished. The alive and finished sequences with the
<del> highest log probabilities and scores are returned.
<del>
<del> A sequence's finished score is calculating by dividing the log probability
<del> by the length normalization factor. Without length normalization, the
<del> search is more likely to return shorter sequences.
<del>
<del> Args:
<del> state: A dictionary with the current loop state.
<del>
<del> Returns:
<del> new state dictionary.
<del> """
<del> # Grow alive sequences by one token.
<del> new_seq, new_log_probs, topk_ids, new_cache = self._grow_alive_seq(state)
<del> new_finished_flags = tf.equal(topk_ids, self.eos_id)
<del> # Collect top beam_size alive sequences
<del> alive_state = self._get_new_alive_state(new_seq, new_log_probs,
<del> new_finished_flags, new_cache)
<del>
<del> # Combine newly finished sequences with existing finished sequences, and
<del> # collect the top k scoring sequences.
<del> finished_state = self._get_new_finished_state(state, new_seq, new_log_probs,
<del> new_finished_flags)
<del>
<del> # Increment loop index and create new state dictionary
<del> new_state = {_StateKeys.CUR_INDEX: state[_StateKeys.CUR_INDEX] + 1}
<del> new_state.update(alive_state)
<del> new_state.update(finished_state)
<del> return [new_state]
<del>
<del> def _grow_alive_seq(self, state):
<del> """Grow alive sequences by one token, and collect top 2*beam_size sequences.
<del>
<del> 2*beam_size sequences are collected because some sequences may have reached
<del> the EOS token. 2*beam_size ensures that at least beam_size sequences are
<del> still alive.
<del>
<del> Args:
<del> state: A dictionary with the current loop state.
<del> Returns:
<del> Tuple of
<del> (Top 2*beam_size sequences [batch_size, 2 * beam_size, cur_index + 1],
<del> Scores of returned sequences [batch_size, 2 * beam_size],
<del> New alive cache, for each of the 2 * beam_size sequences)
<del> """
<del> i = state[_StateKeys.CUR_INDEX]
<del> alive_seq = state[_StateKeys.ALIVE_SEQ]
<del> alive_log_probs = state[_StateKeys.ALIVE_LOG_PROBS]
<del> alive_cache = state[_StateKeys.ALIVE_CACHE]
<del>
<del> beams_to_keep = 2 * self.beam_size
<del>
<del> # Get logits for the next candidate IDs for the alive sequences. Get the new
<del> # cache values at the same time.
<del> if self.padded_decode:
<del> flat_ids = tf.reshape(
<del> tf.slice(alive_seq, [0, 0, i], [self.batch_size, self.beam_size, 1]),
<del> [self.batch_size * self.beam_size, -1])
<del> else:
<del> flat_ids = _flatten_beam_dim(alive_seq) # [batch_size * beam_size]
<del> flat_cache = nest.map_structure(_flatten_beam_dim, alive_cache)
<del>
<del> flat_logits, flat_cache = self.symbols_to_logits_fn(flat_ids, i, flat_cache)
<del>
<del> # Unflatten logits to shape [batch_size, beam_size, vocab_size]
<del> logits = _unflatten_beam_dim(flat_logits, self.batch_size, self.beam_size)
<del> new_cache = nest.map_structure(
<del> lambda t: _unflatten_beam_dim(t, self.batch_size, self.beam_size),
<del> flat_cache)
<del>
<del> # Convert logits to normalized log probs
<del> candidate_log_probs = _log_prob_from_logits(logits)
<del>
<del> # Calculate new log probabilities if each of the alive sequences were
<del> # extended # by the the candidate IDs.
<del> # Shape [batch_size, beam_size, vocab_size]
<del> log_probs = candidate_log_probs + tf.expand_dims(alive_log_probs, axis=2)
<del>
<del> # Each batch item has beam_size * vocab_size candidate sequences. For each
<del> # batch item, get the k candidates with the highest log probabilities.
<del> flat_log_probs = tf.reshape(log_probs,
<del> [-1, self.beam_size * self.vocab_size])
<del> topk_log_probs, topk_indices = tf.nn.top_k(flat_log_probs, k=beams_to_keep)
<del>
<del> # Extract the alive sequences that generate the highest log probabilities
<del> # after being extended.
<del> topk_beam_indices = topk_indices // self.vocab_size
<del> topk_seq, new_cache = _gather_beams(
<del> [alive_seq, new_cache], topk_beam_indices, self.batch_size,
<del> beams_to_keep)
<del>
<del> # Append the most probable IDs to the topk sequences
<del> topk_ids = topk_indices % self.vocab_size
<del> if self.padded_decode:
<del> topk_seq = tf.transpose(topk_seq, perm=[2, 0, 1])
<del> # TODO(b/145533236, hongkuny): Reverts once TF fix the validation.
<del> topk_seq = tf.tensor_scatter_nd_update(topk_seq, [[i + 1]],
<del> tf.expand_dims(topk_ids, axis=0))
<del> topk_seq = tf.transpose(topk_seq, perm=[1, 2, 0])
<del> else:
<del> topk_seq = tf.concat([topk_seq, tf.expand_dims(topk_ids, axis=2)], axis=2)
<del> return topk_seq, topk_log_probs, topk_ids, new_cache
<del>
<del> def _get_new_alive_state(self, new_seq, new_log_probs, new_finished_flags,
<del> new_cache):
<del> """Gather the top k sequences that are still alive.
<del>
<del> Args:
<del> new_seq: New sequences generated by growing the current alive sequences
<del> int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1]
<del> new_log_probs: Log probabilities of new sequences float32 tensor with
<del> shape [batch_size, beam_size]
<del> new_finished_flags: A boolean Tensor indicates which sequences are live
<del> inside the beam.
<del> new_cache: Dict of cached values for each sequence.
<del>
<del> Returns:
<del> Dictionary with alive keys from _StateKeys:
<del> {Top beam_size sequences that are still alive (don't end with eos_id)
<del> Log probabilities of top alive sequences
<del> Dict cache storing decoder states for top alive sequences}
<del> """
<del> # To prevent finished sequences from being considered, set log probs to -inf
<del> new_log_probs += tf.cast(new_finished_flags, self.dtype) * -inf(self.dtype)
<del>
<del> top_alive_seq, top_alive_log_probs, top_alive_cache = _gather_topk_beams(
<del> [new_seq, new_log_probs, new_cache], new_log_probs, self.batch_size,
<del> self.beam_size)
<del>
<del> return {
<del> _StateKeys.ALIVE_SEQ: top_alive_seq,
<del> _StateKeys.ALIVE_LOG_PROBS: top_alive_log_probs,
<del> _StateKeys.ALIVE_CACHE: top_alive_cache
<del> }
<del>
<del> def _get_new_finished_state(self, state, new_seq, new_log_probs,
<del> new_finished_flags):
<del> """Combine new and old finished sequences, and gather the top k sequences.
<del>
<del> Args:
<del> state: A dictionary with the current loop state.
<del> new_seq: New sequences generated by growing the current alive sequences
<del> int32 tensor with shape [batch_size, beam_size, i + 1]
<del> new_log_probs: Log probabilities of new sequences float32 tensor with
<del> shape [batch_size, beam_size]
<del> new_finished_flags: A boolean Tensor indicates which sequences are live
<del> inside the beam.
<del>
<del> Returns:
<del> Dictionary with finished keys from _StateKeys:
<del> {Top beam_size finished sequences based on score,
<del> Scores of finished sequences,
<del> Finished flags of finished sequences}
<del> """
<del> i = state[_StateKeys.CUR_INDEX]
<del> finished_seq = state[_StateKeys.FINISHED_SEQ]
<del> finished_scores = state[_StateKeys.FINISHED_SCORES]
<del> finished_flags = state[_StateKeys.FINISHED_FLAGS]
<del>
<del> # First append a column of 0-ids to finished_seq to increment the length.
<del> # New shape of finished_seq: [batch_size, beam_size, i + 1]
<del> if not self.padded_decode:
<del> finished_seq = tf.concat([
<del> finished_seq,
<del> tf.zeros([self.batch_size, self.beam_size, 1], tf.int32)
<del> ],
<del> axis=2)
<del>
<del> # Calculate new seq scores from log probabilities.
<del> length_norm = _length_normalization(self.alpha, i + 1, dtype=self.dtype)
<del> new_scores = new_log_probs / length_norm
<del>
<del> # Set the scores of the still-alive seq in new_seq to large negative values.
<del> new_scores += ((1. - tf.cast(new_finished_flags, self.dtype)) *
<del> -inf(self.dtype))
<del>
<del> # Combine sequences, scores, and flags.
<del> finished_seq = tf.concat([finished_seq, new_seq], axis=1)
<del> finished_scores = tf.concat([finished_scores, new_scores], axis=1)
<del> finished_flags = tf.concat([finished_flags, new_finished_flags], axis=1)
<del>
<del> # Return the finished sequences with the best scores.
<del> top_finished_seq, top_finished_scores, top_finished_flags = (
<del> _gather_topk_beams([finished_seq, finished_scores, finished_flags],
<del> finished_scores, self.batch_size, self.beam_size))
<del>
<del> return {
<del> _StateKeys.FINISHED_SEQ: top_finished_seq,
<del> _StateKeys.FINISHED_SCORES: top_finished_scores,
<del> _StateKeys.FINISHED_FLAGS: top_finished_flags
<del> }
<del>
<ide>
<ide> def sequence_beam_search(
<ide> symbols_to_logits_fn, initial_ids, initial_cache, vocab_size, beam_size,
<ide> def sequence_beam_search(
<ide> Top decoded sequences [batch_size, beam_size, max_decode_length]
<ide> sequence scores [batch_size, beam_size]
<ide> """
<del> batch_size = (
<del> initial_ids.shape.as_list()[0] if padded_decode else
<del> tf.shape(initial_ids)[0])
<del> sbs = SequenceBeamSearch(symbols_to_logits_fn, vocab_size, batch_size,
<del> beam_size, alpha, max_decode_length, eos_id,
<del> padded_decode)
<add> sbs = SequenceBeamSearch(symbols_to_logits_fn, vocab_size, beam_size, alpha,
<add> max_decode_length, eos_id, padded_decode)
<ide> return sbs.search(initial_ids, initial_cache)
<del>
<del>
<del>def _log_prob_from_logits(logits):
<del> return logits - tf.reduce_logsumexp(logits, axis=2, keepdims=True)
<del>
<del>
<del>def _length_normalization(alpha, length, dtype=tf.float32):
<del> """Return length normalization factor."""
<del> return tf.pow(((5. + tf.cast(length, dtype)) / 6.), alpha)
<del>
<del>
<del>def _expand_to_beam_size(tensor, beam_size):
<del> """Tiles a given tensor by beam_size.
<del>
<del> Args:
<del> tensor: tensor to tile [batch_size, ...]
<del> beam_size: How much to tile the tensor by.
<del>
<del> Returns:
<del> Tiled tensor [batch_size, beam_size, ...]
<del> """
<del> tensor = tf.expand_dims(tensor, axis=1)
<del> tile_dims = [1] * tensor.shape.ndims
<del> tile_dims[1] = beam_size
<del>
<del> return tf.tile(tensor, tile_dims)
<del>
<del>
<del>def _shape_list(tensor):
<del> """Return a list of the tensor's shape, and ensure no None values in list."""
<del> # Get statically known shape (may contain None's for unknown dimensions)
<del> shape = tensor.get_shape().as_list()
<del>
<del> # Ensure that the shape values are not None
<del> dynamic_shape = tf.shape(tensor)
<del> for i in range(len(shape)): # pylint: disable=consider-using-enumerate
<del> if shape[i] is None:
<del> shape[i] = dynamic_shape[i]
<del> return shape
<del>
<del>
<del>def _get_shape_keep_last_dim(tensor):
<del> shape_list = _shape_list(tensor)
<del>
<del> # Only the last
<del> for i in range(len(shape_list) - 1):
<del> shape_list[i] = None
<del>
<del> if isinstance(shape_list[-1], tf.Tensor):
<del> shape_list[-1] = None
<del> return tf.TensorShape(shape_list)
<del>
<del>
<del>def _get_shape(tensor):
<del> """Return the shape of the input tensor."""
<del> return tf.TensorShape(_shape_list(tensor))
<del>
<del>
<del>def _flatten_beam_dim(tensor):
<del> """Reshapes first two dimensions in to single dimension.
<del>
<del> Args:
<del> tensor: Tensor to reshape of shape [A, B, ...]
<del>
<del> Returns:
<del> Reshaped tensor of shape [A*B, ...]
<del> """
<del> shape = _shape_list(tensor)
<del> shape[0] *= shape[1]
<del> shape.pop(1) # Remove beam dim
<del> return tf.reshape(tensor, shape)
<del>
<del>
<del>def _unflatten_beam_dim(tensor, batch_size, beam_size):
<del> """Reshapes first dimension back to [batch_size, beam_size].
<del>
<del> Args:
<del> tensor: Tensor to reshape of shape [batch_size*beam_size, ...]
<del> batch_size: Tensor, original batch size.
<del> beam_size: int, original beam size.
<del>
<del> Returns:
<del> Reshaped tensor of shape [batch_size, beam_size, ...]
<del> """
<del> shape = _shape_list(tensor)
<del> new_shape = [batch_size, beam_size] + shape[1:]
<del> return tf.reshape(tensor, new_shape)
<del>
<del>
<del>def _gather_beams(nested, beam_indices, batch_size, new_beam_size):
<del> """Gather beams from nested structure of tensors.
<del>
<del> Each tensor in nested represents a batch of beams, where beam refers to a
<del> single search state (beam search involves searching through multiple states
<del> in parallel).
<del>
<del> This function is used to gather the top beams, specified by
<del> beam_indices, from the nested tensors.
<del>
<del> Args:
<del> nested: Nested structure (tensor, list, tuple or dict) containing tensors
<del> with shape [batch_size, beam_size, ...].
<del> beam_indices: int32 tensor with shape [batch_size, new_beam_size]. Each
<del> value in beam_indices must be between [0, beam_size), and are not
<del> necessarily unique.
<del> batch_size: int size of batch
<del> new_beam_size: int number of beams to be pulled from the nested tensors.
<del>
<del> Returns:
<del> Nested structure containing tensors with shape
<del> [batch_size, new_beam_size, ...]
<del> """
<del> # Computes the i'th coodinate that contains the batch index for gather_nd.
<del> # Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..].
<del> batch_pos = tf.range(batch_size * new_beam_size) // new_beam_size
<del> batch_pos = tf.reshape(batch_pos, [batch_size, new_beam_size])
<del>
<del> # Create coordinates to be passed to tf.gather_nd. Stacking creates a tensor
<del> # with shape [batch_size, beam_size, 2], where the last dimension contains
<del> # the (i, j) gathering coordinates.
<del> coordinates = tf.stack([batch_pos, beam_indices], axis=2)
<del>
<del> return nest.map_structure(
<del> lambda state: tf.gather_nd(state, coordinates), nested)
<del>
<del>
<del>def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size):
<del> """Gather top beams from nested structure."""
<del> _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size)
<del> return _gather_beams(nested, topk_indexes, batch_size, beam_size)
<ide><path>official/nlp/transformer/transformer.py
<ide>
<ide> import tensorflow as tf
<ide> from official.nlp.modeling.layers import position_embedding
<add>from official.nlp.modeling.ops import beam_search
<ide> from official.nlp.transformer import attention_layer
<del>from official.nlp.transformer import beam_search
<ide> from official.nlp.transformer import embedding_layer
<ide> from official.nlp.transformer import ffn_layer
<ide> from official.nlp.transformer import metrics | 7 |
PHP | PHP | fix the code indent of object operators | c7a0002432351690d28223afa7caa272e769e226 | <ide><path>app/Providers/RouteServiceProvider.php
<ide> public function map()
<ide> protected function mapWebRoutes()
<ide> {
<ide> Route::middleware('web')
<del> ->namespace($this->namespace)
<del> ->group(base_path('routes/web.php'));
<add> ->namespace($this->namespace)
<add> ->group(base_path('routes/web.php'));
<ide> }
<ide>
<ide> /**
<ide> protected function mapWebRoutes()
<ide> protected function mapApiRoutes()
<ide> {
<ide> Route::prefix('api')
<del> ->middleware('api')
<del> ->namespace($this->namespace)
<del> ->group(base_path('routes/api.php'));
<add> ->middleware('api')
<add> ->namespace($this->namespace)
<add> ->group(base_path('routes/api.php'));
<ide> }
<ide> } | 1 |
Java | Java | implement nativeanimated modulus node on android | 9b4927c9c444c61b8ddf3c1f17325d1b85bf6a2d | <ide><path>ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.animated;
<add>
<add>import com.facebook.react.bridge.JSApplicationCausedNativeException;
<add>import com.facebook.react.bridge.ReadableArray;
<add>import com.facebook.react.bridge.ReadableMap;
<add>
<add>/*package*/ class ModulusAnimatedNode extends ValueAnimatedNode {
<add>
<add> private final NativeAnimatedNodesManager mNativeAnimatedNodesManager;
<add> private final int mInputNode;
<add> private final int mModulus;
<add>
<add> public ModulusAnimatedNode(
<add> ReadableMap config,
<add> NativeAnimatedNodesManager nativeAnimatedNodesManager) {
<add> mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
<add> mInputNode = config.getInt("input");
<add> mModulus = config.getInt("modulus");
<add> }
<add>
<add> @Override
<add> public void update() {
<add> AnimatedNode animatedNode = mNativeAnimatedNodesManager.getNodeById(mInputNode);
<add> if (animatedNode != null && animatedNode instanceof ValueAnimatedNode) {
<add> mValue = ((ValueAnimatedNode) animatedNode).mValue % mModulus;
<add> } else {
<add> throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " +
<add> "Animated.modulus node");
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java
<ide> public void createAnimatedNode(int tag, ReadableMap config) {
<ide> node = new DivisionAnimatedNode(config, this);
<ide> } else if ("multiplication".equals(type)) {
<ide> node = new MultiplicationAnimatedNode(config, this);
<add> } else if ("modulus".equals(type)) {
<add> node = new ModulusAnimatedNode(config, this);
<ide> } else if ("diffclamp".equals(type)) {
<ide> node = new DiffClampAnimatedNode(config, this);
<ide> } else if ("transform".equals(type)) { | 2 |
Ruby | Ruby | remove redundant blank line at the bottom | 42cf5eba260f97e6da0ef66b954d95b9e7c2b102 | <ide><path>railties/lib/rails/generators/rails/controller/templates/controller.rb
<ide> class <%= class_name %>Controller < ApplicationController
<ide> <% actions.each do |action| -%>
<ide> def <%= action %>
<ide> end
<del>
<add><%= "\n" unless action == actions.last -%>
<ide> <% end -%>
<ide> end
<ide> <% end -%> | 1 |
PHP | PHP | remove more uses of deprecated properties/methods | 65174c1112fc042a9f7c45bf1705a79fc68d50ac | <ide><path>src/Controller/Component/AuthComponent.php
<ide> public function authCheck(Event $event)
<ide> /* @var \Cake\Controller\Controller $controller */
<ide> $controller = $event->getSubject();
<ide>
<del> $action = strtolower($controller->request->params['action']);
<add> $action = strtolower($controller->request->getParam('action'));
<ide> if (!$controller->isAction($action)) {
<ide> return null;
<ide> }
<ide> public function implementedEvents()
<ide> */
<ide> protected function _isAllowed(Controller $controller)
<ide> {
<del> $action = strtolower($controller->request->params['action']);
<add> $action = strtolower($controller->request->getParam('action'));
<ide>
<ide> return in_array($action, array_map('strtolower', $this->allowedActions));
<ide> }
<ide><path>src/Controller/Component/CsrfComponent.php
<ide> class CsrfComponent extends Component
<ide> * Validates the CSRF token for POST data. If
<ide> * the request is a GET request, and the cookie value is absent a cookie will be set.
<ide> *
<del> * Once a cookie is set it will be copied into request->params['_csrfToken']
<add> * Once a cookie is set it will be copied into request->getParam('_csrfToken')
<ide> * so that application and framework code can easily access the csrf token.
<ide> *
<ide> * RequestAction requests do not get checked, nor will
<ide><path>src/Routing/Router.php
<ide> public static function reload()
<ide> *
<ide> * ```
<ide> * Router::addUrlFilter(function ($params, $request) {
<del> * if (isset($request->params['lang']) && !isset($params['lang'])) {
<del> * $params['lang'] = $request->params['lang'];
<add> * if ($request->getParam('lang') && !isset($params['lang'])) {
<add> * $params['lang'] = $request->getParam('lang');
<ide> * }
<ide> * return $params;
<ide> * });
<ide> public static function url($url = null, $full = false)
<ide> if ($request) {
<ide> $params = $request->params;
<ide> $here = $request->here;
<del> $base = $request->base;
<add> $base = $request->getAttribute('base');
<ide> } else {
<ide> $base = Configure::read('App.base');
<ide> if (isset(static::$_requestContext['_base'])) {
<ide> public static function normalize($url = '/')
<ide> * Instructs the router to parse out file extensions
<ide> * from the URL. For example, http://example.com/posts.rss would yield a file
<ide> * extension of "rss". The file extension itself is made available in the
<del> * controller as `$this->request->params['_ext']`, and is used by the RequestHandler
<add> * controller as `$this->request->getParam('_ext')`, and is used by the RequestHandler
<ide> * component to automatically switch to alternate layouts and templates, and
<ide> * load helpers corresponding to the given content, i.e. RssHelper. Switching
<ide> * layouts and helpers requires that the chosen extension has a defined mime type
<ide> public static function parseNamedParams(ServerRequest $request, array $options =
<ide> return $request;
<ide> }
<ide> $named = [];
<del> foreach ($request->params['pass'] as $key => $value) {
<add> foreach ($request->getParam('pass') as $key => $value) {
<ide> if (strpos($value, $options['separator']) === false) {
<ide> continue;
<ide> } | 3 |
Go | Go | get pkg/term to build for solaris | b216dc9115ebc0b803551ff761f5464fcbde09e1 | <ide><path>pkg/term/tc_linux_cgo.go
<ide> import (
<ide> import "C"
<ide>
<ide> // Termios is the Unix API for terminal I/O.
<del>// It is passthgrouh for syscall.Termios in order to make it portable with
<add>// It is passthrough for syscall.Termios in order to make it portable with
<ide> // other platforms where it is not available or handled differently.
<ide> type Termios syscall.Termios
<ide>
<ide><path>pkg/term/tc_other.go
<ide> // +build !windows
<ide> // +build !linux !cgo
<add>// +build !solaris !cgo
<ide>
<ide> package term
<ide>
<ide><path>pkg/term/tc_solaris_cgo.go
<add>// +build solaris,cgo
<add>
<add>package term
<add>
<add>import (
<add> "syscall"
<add> "unsafe"
<add>)
<add>
<add>// #include <termios.h>
<add>import "C"
<add>
<add>// Termios is the Unix API for terminal I/O.
<add>// It is passthrough for syscall.Termios in order to make it portable with
<add>// other platforms where it is not available or handled differently.
<add>type Termios syscall.Termios
<add>
<add>// MakeRaw put the terminal connected to the given file descriptor into raw
<add>// mode and returns the previous state of the terminal so that it can be
<add>// restored.
<add>func MakeRaw(fd uintptr) (*State, error) {
<add> var oldState State
<add> if err := tcget(fd, &oldState.termios); err != 0 {
<add> return nil, err
<add> }
<add>
<add> newState := oldState.termios
<add>
<add> newState.Iflag &^= (syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON | syscall.IXANY)
<add> newState.Oflag &^= syscall.OPOST
<add> newState.Lflag &^= (syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN)
<add> newState.Cflag &^= (syscall.CSIZE | syscall.PARENB)
<add> newState.Cflag |= syscall.CS8
<add>
<add> /*
<add> VMIN is the minimum number of characters that needs to be read in non-canonical mode for it to be returned
<add> Since VMIN is overloaded with another element in canonical mode when we switch modes it defaults to 4. It
<add> needs to be explicitly set to 1.
<add> */
<add> newState.Cc[C.VMIN] = 1
<add> newState.Cc[C.VTIME] = 0
<add>
<add> if err := tcset(fd, &newState); err != 0 {
<add> return nil, err
<add> }
<add> return &oldState, nil
<add>}
<add>
<add>func tcget(fd uintptr, p *Termios) syscall.Errno {
<add> ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p)))
<add> if ret != 0 {
<add> return err.(syscall.Errno)
<add> }
<add> return 0
<add>}
<add>
<add>func tcset(fd uintptr, p *Termios) syscall.Errno {
<add> ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p)))
<add> if ret != 0 {
<add> return err.(syscall.Errno)
<add> }
<add> return 0
<add>}
<ide><path>pkg/term/term.go
<ide> import (
<ide> "os"
<ide> "os/signal"
<ide> "syscall"
<del> "unsafe"
<ide> )
<ide>
<ide> var (
<ide> func GetFdInfo(in interface{}) (uintptr, bool) {
<ide> return inFd, isTerminalIn
<ide> }
<ide>
<del>// GetWinsize returns the window size based on the specified file descriptor.
<del>func GetWinsize(fd uintptr) (*Winsize, error) {
<del> ws := &Winsize{}
<del> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(ws)))
<del> // Skip errno = 0
<del> if err == 0 {
<del> return ws, nil
<del> }
<del> return ws, err
<del>}
<del>
<del>// SetWinsize tries to set the specified window size for the specified file descriptor.
<del>func SetWinsize(fd uintptr, ws *Winsize) error {
<del> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws)))
<del> // Skip errno = 0
<del> if err == 0 {
<del> return nil
<del> }
<del> return err
<del>}
<del>
<ide> // IsTerminal returns true if the given file descriptor is a terminal.
<ide> func IsTerminal(fd uintptr) bool {
<ide> var termios Termios
<ide><path>pkg/term/term_solaris.go
<add>// +build solaris
<add>
<add>package term
<add>
<add>import (
<add> "syscall"
<add> "unsafe"
<add>)
<add>
<add>/*
<add>#include <unistd.h>
<add>#include <stropts.h>
<add>#include <termios.h>
<add>
<add>// Small wrapper to get rid of variadic args of ioctl()
<add>int my_ioctl(int fd, int cmd, struct winsize *ws) {
<add> return ioctl(fd, cmd, ws);
<add>}
<add>*/
<add>import "C"
<add>
<add>// GetWinsize returns the window size based on the specified file descriptor.
<add>func GetWinsize(fd uintptr) (*Winsize, error) {
<add> ws := &Winsize{}
<add> ret, err := C.my_ioctl(C.int(fd), C.int(syscall.TIOCGWINSZ), (*C.struct_winsize)(unsafe.Pointer(ws)))
<add> // Skip retval = 0
<add> if ret == 0 {
<add> return ws, nil
<add> }
<add> return ws, err
<add>}
<add>
<add>// SetWinsize tries to set the specified window size for the specified file descriptor.
<add>func SetWinsize(fd uintptr, ws *Winsize) error {
<add> ret, err := C.my_ioctl(C.int(fd), C.int(syscall.TIOCSWINSZ), (*C.struct_winsize)(unsafe.Pointer(ws)))
<add> // Skip retval = 0
<add> if ret == 0 {
<add> return nil
<add> }
<add> return err
<add>}
<ide><path>pkg/term/term_unix.go
<add>// +build !solaris,!windows
<add>
<add>package term
<add>
<add>import (
<add> "syscall"
<add> "unsafe"
<add>)
<add>
<add>// GetWinsize returns the window size based on the specified file descriptor.
<add>func GetWinsize(fd uintptr) (*Winsize, error) {
<add> ws := &Winsize{}
<add> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(ws)))
<add> // Skipp errno = 0
<add> if err == 0 {
<add> return ws, nil
<add> }
<add> return ws, err
<add>}
<add>
<add>// SetWinsize tries to set the specified window size for the specified file descriptor.
<add>func SetWinsize(fd uintptr, ws *Winsize) error {
<add> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws)))
<add> // Skipp errno = 0
<add> if err == 0 {
<add> return nil
<add> }
<add> return err
<add>} | 6 |
Javascript | Javascript | improve error messages | 9e0f771224759484bd95358f02de650916287488 | <ide><path>lib/buffer.js
<ide> Buffer.from = function from(value, encodingOrOffset, length) {
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE',
<ide> 'first argument',
<del> ['string', 'buffer', 'arrayBuffer', 'array', 'array-like object']
<add> ['string', 'buffer', 'arrayBuffer', 'array', 'array-like object'],
<add> value
<ide> );
<ide> };
<ide>
<ide> function byteLength(string, encoding) {
<ide> }
<ide>
<ide> throw new errors.TypeError(
<del> 'ERR_INVALID_ARG_TYPE', 'string', ['string', 'buffer', 'arrayBuffer']
<add> 'ERR_INVALID_ARG_TYPE', 'string',
<add> ['string', 'buffer', 'arrayBuffer'], string
<ide> );
<ide> }
<ide>
<ide> Buffer.prototype.toString = function toString(encoding, start, end) {
<ide> Buffer.prototype.equals = function equals(b) {
<ide> if (!isUint8Array(b)) {
<ide> throw new errors.TypeError(
<del> 'ERR_INVALID_ARG_TYPE', 'otherBuffer', ['buffer', 'uint8Array']
<add> 'ERR_INVALID_ARG_TYPE', 'otherBuffer',
<add> ['buffer', 'uint8Array'], b
<ide> );
<ide> }
<ide> if (this === b)
<ide> Buffer.prototype.compare = function compare(target,
<ide> thisEnd) {
<ide> if (!isUint8Array(target)) {
<ide> throw new errors.TypeError(
<del> 'ERR_INVALID_ARG_TYPE', 'target', ['buffer', 'uint8Array']
<add> 'ERR_INVALID_ARG_TYPE', 'target',
<add> ['buffer', 'uint8Array'], target
<ide> );
<ide> }
<ide> if (arguments.length === 1)
<ide> function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
<ide> }
<ide>
<ide> throw new errors.TypeError(
<del> 'ERR_INVALID_ARG_TYPE', 'val', ['string', 'buffer', 'uint8Array']
<add> 'ERR_INVALID_ARG_TYPE', 'value',
<add> ['string', 'buffer', 'uint8Array'], val
<ide> );
<ide> }
<ide>
<ide> Buffer.prototype.fill = function fill(val, start, end, encoding) {
<ide> }
<ide>
<ide> if (encoding !== undefined && typeof encoding !== 'string') {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'encoding', 'string');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'encoding',
<add> 'string', encoding);
<ide> }
<ide> var normalizedEncoding = normalizeEncoding(encoding);
<ide> if (normalizedEncoding === undefined) {
<ide><path>test/parallel/test-buffer-bytelength.js
<ide> const assert = require('assert');
<ide> const SlowBuffer = require('buffer').SlowBuffer;
<ide> const vm = require('vm');
<ide>
<del>// coerce values to string
<del>const errMsg = common.expectsError({
<del> code: 'ERR_INVALID_ARG_TYPE',
<del> type: TypeError,
<del> message: 'The "string" argument must be one of type string, ' +
<del> 'buffer, or arrayBuffer'
<del>}, 4);
<del>assert.throws(() => { Buffer.byteLength(32, 'latin1'); }, errMsg);
<del>assert.throws(() => { Buffer.byteLength(NaN, 'utf8'); }, errMsg);
<del>assert.throws(() => { Buffer.byteLength({}, 'latin1'); }, errMsg);
<del>assert.throws(() => { Buffer.byteLength(); }, errMsg);
<add>[
<add> [32, 'latin1'],
<add> [NaN, 'utf8'],
<add> [{}, 'latin1'],
<add> []
<add>].forEach((args) => {
<add> common.expectsError(
<add> () => Buffer.byteLength(...args),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "string" argument must be one of type string, ' +
<add> `buffer, or arrayBuffer. Received type ${typeof args[0]}`
<add> }
<add> );
<add>});
<ide>
<ide> assert.strictEqual(Buffer.byteLength('', undefined, true), -1);
<ide>
<ide><path>test/parallel/test-buffer-compare-offset.js
<ide> assert.throws(() => a.compare(b, -Infinity, Infinity), oor);
<ide> assert.throws(() => a.compare(), common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "target" argument must be one of type buffer or uint8Array'
<add> message: 'The "target" argument must be one of ' +
<add> 'type buffer or uint8Array. Received type undefined'
<ide> }));
<ide><path>test/parallel/test-buffer-compare.js
<ide> assert.throws(() => Buffer.compare('abc', Buffer.alloc(1)), errMsg);
<ide> assert.throws(() => Buffer.alloc(1).compare('abc'), common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "target" argument must be one of type buffer or uint8Array'
<add> message: 'The "target" argument must be one of ' +
<add> 'type buffer or uint8Array. Received type string'
<ide> }));
<ide><path>test/parallel/test-buffer-equals.js
<ide> assert.ok(!d.equals(e));
<ide> assert.ok(d.equals(d));
<ide> assert.ok(d.equals(new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65])));
<ide>
<del>assert.throws(() => Buffer.alloc(1).equals('abc'),
<del> common.expectsError({
<del> code: 'ERR_INVALID_ARG_TYPE',
<del> type: TypeError,
<del> message: 'The "otherBuffer" argument must be one of type ' +
<del> 'buffer or uint8Array'
<del> }));
<add>common.expectsError(
<add> () => Buffer.alloc(1).equals('abc'),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "otherBuffer" argument must be one of type ' +
<add> 'buffer or uint8Array. Received type string'
<add> }
<add>);
<ide><path>test/parallel/test-buffer-fill.js
<ide> deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, -1]), [0, 0, 0, 0]);
<ide>
<ide>
<ide> // Check exceptions
<del>assert.throws(
<del> () => buf1.fill(0, -1),
<del> common.expectsError({ code: 'ERR_INDEX_OUT_OF_RANGE' }));
<del>assert.throws(
<del> () => buf1.fill(0, 0, buf1.length + 1),
<del> common.expectsError({ code: 'ERR_INDEX_OUT_OF_RANGE' }));
<del>assert.throws(
<del> () => buf1.fill('', -1),
<del> common.expectsError({ code: 'ERR_INDEX_OUT_OF_RANGE' }));
<del>assert.throws(
<del> () => buf1.fill('', 0, buf1.length + 1),
<del> common.expectsError({ code: 'ERR_INDEX_OUT_OF_RANGE' }));
<del>assert.throws(
<add>[
<add> [0, -1],
<add> [0, 0, buf1.length + 1],
<add> ['', -1],
<add> ['', 0, buf1.length + 1]
<add>].forEach((args) => {
<add> common.expectsError(
<add> () => buf1.fill(...args),
<add> { code: 'ERR_INDEX_OUT_OF_RANGE' }
<add> );
<add>});
<add>
<add>common.expectsError(
<ide> () => buf1.fill('a', 0, buf1.length, 'node rocks!'),
<del> common.expectsError({
<add> {
<ide> code: 'ERR_UNKNOWN_ENCODING',
<ide> type: TypeError,
<ide> message: 'Unknown encoding: node rocks!'
<del> }));
<del>assert.throws(
<del> () => buf1.fill('a', 0, 0, NaN),
<del> common.expectsError({
<del> code: 'ERR_INVALID_ARG_TYPE',
<del> message: 'The "encoding" argument must be of type string'
<del> }));
<del>assert.throws(
<del> () => buf1.fill('a', 0, 0, null),
<del> common.expectsError({
<del> code: 'ERR_INVALID_ARG_TYPE',
<del> message: 'The "encoding" argument must be of type string'
<del> }));
<del>assert.throws(
<add> }
<add>);
<add>
<add>[
<add> ['a', 0, 0, NaN],
<add> ['a', 0, 0, null]
<add>].forEach((args) => {
<add> common.expectsError(
<add> () => buf1.fill(...args),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> message: 'The "encoding" argument must be of type ' +
<add> `string. Received type ${args[3] === null ? 'null' : typeof args[3]}`
<add> }
<add> );
<add>});
<add>
<add>common.expectsError(
<ide> () => buf1.fill('a', 0, 0, 'foo'),
<del> common.expectsError({
<add> {
<ide> code: 'ERR_UNKNOWN_ENCODING',
<ide> type: TypeError,
<ide> message: 'Unknown encoding: foo'
<del> }));
<del>
<add> }
<add>);
<ide>
<ide> function genBuffer(size, args) {
<ide> const b = Buffer.allocUnsafe(size);
<ide><path>test/parallel/test-buffer-from.js
<ide> deepStrictEqual(
<ide> );
<ide>
<ide> [
<del> {},
<del> new Boolean(true),
<del> { valueOf() { return null; } },
<del> { valueOf() { return undefined; } },
<del> { valueOf: null },
<del> Object.create(null)
<del>].forEach((input) => {
<add> [{}, 'object'],
<add> [new Boolean(true), 'boolean'],
<add> [{ valueOf() { return null; } }, 'object'],
<add> [{ valueOf() { return undefined; } }, 'object'],
<add> [{ valueOf: null }, 'object'],
<add> [Object.create(null), 'object']
<add>].forEach(([input, actualType]) => {
<ide> const err = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The first argument must be one of type string, buffer, ' +
<del> 'arrayBuffer, array, or array-like object'
<add> 'arrayBuffer, array, or array-like object. Received ' +
<add> `type ${actualType}`
<ide> });
<ide> throws(() => Buffer.from(input), err);
<ide> });
<ide><path>test/parallel/test-buffer-includes.js
<ide> assert(twoByteString.includes(
<ide> assert(!twoByteString.includes('\u03a3', -2, 'ucs2'));
<ide>
<ide> const mixedByteStringUcs2 =
<del> Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2');
<add> Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2');
<ide> assert(mixedByteStringUcs2.includes('bc', 0, 'ucs2'));
<ide> assert(mixedByteStringUcs2.includes('\u03a3', 0, 'ucs2'));
<ide> assert(!mixedByteStringUcs2.includes('\u0396', 0, 'ucs2'));
<ide> for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
<ide> const length = lengths[lengthIndex];
<ide>
<ide> const patternBufferUcs2 =
<del> allCharsBufferUcs2.slice(index, index + length);
<add> allCharsBufferUcs2.slice(index, index + length);
<ide> assert.ok(
<ide> allCharsBufferUcs2.includes(patternBufferUcs2, 0, 'ucs2'));
<ide>
<ide> for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
<ide> }
<ide> }
<ide>
<del>const expectedError = common.expectsError({
<del> code: 'ERR_INVALID_ARG_TYPE',
<del> type: TypeError,
<del> message: 'The "val" argument must be one of type ' +
<del> 'string, buffer, or uint8Array'
<del>}, 3);
<del>assert.throws(() => {
<del> b.includes(() => {});
<del>}, expectedError);
<del>assert.throws(() => {
<del> b.includes({});
<del>}, expectedError);
<del>assert.throws(() => {
<del> b.includes([]);
<del>}, expectedError);
<add>[
<add> () => { },
<add> {},
<add> []
<add>].forEach((val) => {
<add> common.expectsError(
<add> () => b.includes(val),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "value" argument must be one of type string, ' +
<add> `buffer, or uint8Array. Received type ${typeof val}`
<add> }
<add> );
<add>});
<ide>
<ide> // test truncation of Number arguments to uint8
<ide> {
<ide><path>test/parallel/test-buffer-indexof.js
<ide> assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
<ide> }
<ide> }
<ide>
<del>const argumentExpected = common.expectsError({
<del> code: 'ERR_INVALID_ARG_TYPE',
<del> type: TypeError,
<del> message: 'The "val" argument must be one of type ' +
<del> 'string, buffer, or uint8Array'
<del>}, 3);
<del>
<del>assert.throws(() => {
<del> b.indexOf(() => { });
<del>}, argumentExpected);
<del>
<del>assert.throws(() => {
<del> b.indexOf({});
<del>}, argumentExpected);
<del>
<del>assert.throws(() => {
<del> b.indexOf([]);
<del>}, argumentExpected);
<add>[
<add> () => {},
<add> {},
<add> []
<add>].forEach((val) => {
<add> common.expectsError(
<add> () => b.indexOf(val),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "value" argument must be one of type string, ' +
<add> `buffer, or uint8Array. Received type ${typeof val}`
<add> }
<add> );
<add>});
<ide>
<ide> // Test weird offset arguments.
<ide> // The following offsets coerce to NaN or 0, searching the whole Buffer | 9 |
Python | Python | add some additional checks | fffdb1688817b228fedd7ce8e548b51944468daf | <ide><path>libcloud/storage/drivers/local.py
<ide> def download_object_range(self, obj, destination_path, start_bytes,
<ide>
<ide> def download_object_range_as_stream(self, obj, start_bytes, end_bytes=None,
<ide> chunk_size=None):
<add> if end_bytes and start_bytes > end_bytes:
<add> raise ValueError('start_bytes must be smaller than end_bytes')
<add>
<ide> path = self.get_object_cdn_url(obj)
<ide> with open(path, 'rb') as obj_file:
<ide> file_size = len(obj_file.read())
<ide>
<add> if end_bytes and end_bytes > file_size:
<add> raise ValueError('end_bytes is larger than file size')
<add>
<ide> if not end_bytes:
<ide> read_bytes = (file_size - start_bytes) + 1
<ide> else: | 1 |
Text | Text | add formnovalidate and novalidate too | f8349f9614b25bf964a90c176209a19827184dd8 | <ide><path>docs/docs/ref-04-tags-and-attributes.md
<ide> For a list of events, see [Supported Events](/react/docs/events.html).
<ide> accept accessKey action allowFullScreen allowTransparency alt autoCapitalize
<ide> autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked
<ide> className colSpan content contentEditable contextMenu controls data dateTime
<del>dir disabled draggable encType form frameBorder height hidden href htmlFor
<del>httpEquiv icon id label lang list loop max maxLength method min multiple name
<del>pattern placeholder poster preload radioGroup readOnly rel required role
<del>rowSpan sandbox scope scrollLeft scrollTop seamless selected size span
<del>spellCheck src step style tabIndex target title type value width wmode
<add>dir disabled draggable encType form formNoValidate frameBorder height hidden
<add>href htmlFor httpEquiv icon id label lang list loop max maxLength method min
<add>multiple name noValidate pattern placeholder poster preload radioGroup
<add>readOnly rel required role rowSpan sandbox scope scrollLeft scrollTop seamless
<add>selected size span spellCheck src step style tabIndex target title type value
<add>width wmode
<ide> ```
<ide>
<ide> The non-standard `autoCapitalize` attribute is supported for Mobile Safari, and the `property` attribute is supported for Open Graph `<meta>` tags. | 1 |
Javascript | Javascript | destroy socket on error | eb09b0644b3cb910d318d1d2a80cd2215b63cdcc | <ide><path>lib/http2.js
<ide> ClientRequest.prototype.onSocket = function(socket) {
<ide> // and we need to make sure we don't double-fire the error event.
<ide> req._hadError = true;
<ide> parser.finish();
<add> socket.destroy();
<ide> }
<ide> socket.on('error', errorListener);
<ide> | 1 |
Java | Java | improve exception handling when clients disconnect | 80ff5ae9c513372db37eb0dbcb19048adb09b21f | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractResponseBodyFlushProcessor.java
<ide> public final void onNext(Publisher<DataBuffer> publisher) {
<ide>
<ide> @Override
<ide> public final void onError(Throwable t) {
<del> if (logger.isErrorEnabled()) {
<del> logger.error(this.state + " onError: " + t, t);
<add> if (logger.isTraceEnabled()) {
<add> logger.trace(this.state + " onError: " + t);
<ide> }
<ide> this.state.get().onError(this, t);
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractResponseBodyProcessor.java
<ide> public final void onNext(DataBuffer dataBuffer) {
<ide>
<ide> @Override
<ide> public final void onError(Throwable t) {
<del> if (logger.isErrorEnabled()) {
<del> logger.error(this.state + " onError: " + t, t);
<add> if (logger.isTraceEnabled()) {
<add> logger.trace(this.state + " onError: " + t);
<ide> }
<ide> this.state.get().onError(this, t);
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorHttpHandlerAdapter.java
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.ipc.netty.http.HttpChannel;
<ide>
<add>import org.apache.commons.logging.LogFactory;
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.util.Assert;
<ide>
<add>import io.netty.handler.codec.http.HttpResponseStatus;
<add>
<ide> /**
<ide> * Adapt {@link HttpHandler} to the Reactor Netty channel handling function.
<ide> *
<ide> public Mono<Void> apply(HttpChannel channel) {
<ide> NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(channel.delegate().alloc());
<ide> ReactorServerHttpRequest adaptedRequest = new ReactorServerHttpRequest(channel, bufferFactory);
<ide> ReactorServerHttpResponse adaptedResponse = new ReactorServerHttpResponse(channel, bufferFactory);
<del> return this.httpHandler.handle(adaptedRequest, adaptedResponse);
<add> return this.httpHandler.handle(adaptedRequest, adaptedResponse)
<add> .otherwise(ex -> {
<add> LogFactory.getLog(ReactorHttpHandlerAdapter.class).error("Could not complete request", ex);
<add> channel.status(HttpResponseStatus.INTERNAL_SERVER_ERROR);
<add> return Mono.empty();
<add> });
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/RxNettyHttpHandlerAdapter.java
<ide> package org.springframework.http.server.reactive;
<ide>
<ide> import io.netty.buffer.ByteBuf;
<add>import io.netty.handler.codec.http.HttpResponseStatus;
<ide> import io.reactivex.netty.protocol.http.server.HttpServerRequest;
<ide> import io.reactivex.netty.protocol.http.server.HttpServerResponse;
<ide> import io.reactivex.netty.protocol.http.server.RequestHandler;
<add>
<add>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.adapter.RxJava1Adapter;
<add>import reactor.core.publisher.Mono;
<ide> import rx.Observable;
<ide>
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerRes
<ide> NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(response.unsafeNettyChannel().alloc());
<ide> RxNettyServerHttpRequest adaptedRequest = new RxNettyServerHttpRequest(request, bufferFactory);
<ide> RxNettyServerHttpResponse adaptedResponse = new RxNettyServerHttpResponse(response, bufferFactory);
<del> Publisher<Void> result = this.httpHandler.handle(adaptedRequest, adaptedResponse);
<add> Publisher<Void> result = this.httpHandler.handle(adaptedRequest, adaptedResponse)
<add> .otherwise(ex -> {
<add> LogFactory.getLog(RxNettyHttpHandlerAdapter.class).error("Could not complete request", ex);
<add> response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
<add> return Mono.empty();
<add> });
<ide> return RxJava1Adapter.publisherToObservable(result);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/server/handler/ExceptionHandlingWebHandler.java
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<add>import java.util.HashSet;
<ide> import java.util.List;
<add>import java.util.Set;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide> import reactor.core.publisher.Mono;
<ide>
<add>import org.springframework.core.NestedCheckedException;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.WebExceptionHandler;
<ide> * @since 5.0
<ide> */
<ide> public class ExceptionHandlingWebHandler extends WebHandlerDecorator {
<add> /**
<add> * Log category to use on network IO exceptions after a client has gone away.
<add> * <p>The Servlet API does not provide notifications when a client disconnects;
<add> * see <a href="https://java.net/jira/browse/SERVLET_SPEC-44">SERVLET_SPEC-44</a>.
<add> * Therefore network IO failures may occur simply because a client has gone away,
<add> * and that can fill the logs with unnecessary stack traces.
<add> * <p>We make a best effort to identify such network failures, on a per-server
<add> * basis, and log them under a separate log category. A simple one-line message
<add> * is logged at DEBUG level, while a full stack trace is shown at TRACE level.
<add> * @see #disconnectedClientLogger
<add> */
<add> private static final String DISCONNECTED_CLIENT_LOG_CATEGORY =
<add> "org.springframework.web.server.handler.DisconnectedClient";
<add>
<add> /**
<add> * Separate logger to use on network IO failure after a client has gone away.
<add> * @see #DISCONNECTED_CLIENT_LOG_CATEGORY
<add> */
<add> private static final Log disconnectedClientLogger = LogFactory.getLog(DISCONNECTED_CLIENT_LOG_CATEGORY);
<add>
<add> private static final Set<String> disconnectedClientExceptions;
<add>
<add> static {
<add> Set<String> set = new HashSet<>(3);
<add> set.add("ClientAbortException"); // Tomcat
<add> set.add("EOFException"); // Tomcat
<add> set.add("EofException"); // Jetty
<add> // java.io.IOException "Broken pipe" on WildFly, Glassfish (already covered)
<add> disconnectedClientExceptions = Collections.unmodifiableSet(set);
<add> }
<ide>
<ide> private static Log logger = LogFactory.getLog(ExceptionHandlingWebHandler.class);
<ide>
<ide> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> }
<ide>
<ide> private Mono<? extends Void> handleUnresolvedException(ServerWebExchange exchange, Throwable ex) {
<del> if (logger.isDebugEnabled()) {
<del> logger.debug("Could not complete request", ex);
<del> }
<add> logError(ex);
<ide> exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
<ide> return Mono.empty();
<ide> }
<ide>
<add> private void logError(Throwable t) {
<add> @SuppressWarnings("serial")
<add> NestedCheckedException nestedException = new NestedCheckedException("", t) {};
<add>
<add> if ("Broken pipe".equalsIgnoreCase(nestedException.getMostSpecificCause().getMessage()) ||
<add> disconnectedClientExceptions.contains(t.getClass().getSimpleName())) {
<add>
<add> if (disconnectedClientLogger.isTraceEnabled()) {
<add> disconnectedClientLogger.trace("Looks like the client has gone away", t);
<add> }
<add> else if (disconnectedClientLogger.isDebugEnabled()) {
<add> disconnectedClientLogger.debug("Looks like the client has gone away: " +
<add> nestedException.getMessage() + " (For full stack trace, set the '" +
<add> DISCONNECTED_CLIENT_LOG_CATEGORY + "' log category to TRACE level)");
<add> }
<add> }
<add> else {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Could not complete request", t);
<add> }
<add> }
<add> }
<add>
<ide> } | 5 |
Python | Python | add importorskip for janome | 30a34ebb6edb513e262d1f47b6742b4480282f3c | <ide><path>spacy/tests/conftest.py
<ide> def fi_tokenizer():
<ide>
<ide> @pytest.fixture
<ide> def ja_tokenizer():
<add> janome = pytest.importorskip("janome")
<ide> return Japanese.Defaults.create_tokenizer()
<ide>
<ide> | 1 |
Go | Go | add ovrouter binary | ec68d342d150730d650a6292c62bee1dd4f7735a | <ide><path>libnetwork/cmd/ovrouter/ovrouter.go
<add>package main
<add>
<add>import (
<add> "fmt"
<add> "net"
<add> "os"
<add> "os/signal"
<add>
<add> "github.com/docker/docker/pkg/reexec"
<add> "github.com/docker/libnetwork/driverapi"
<add> "github.com/docker/libnetwork/drivers/overlay"
<add> "github.com/docker/libnetwork/netlabel"
<add> "github.com/docker/libnetwork/types"
<add> "github.com/vishvananda/netlink"
<add>)
<add>
<add>type router struct {
<add> d driverapi.Driver
<add>}
<add>
<add>type endpoint struct {
<add> addr net.IPNet
<add> mac net.HardwareAddr
<add> name string
<add> id int
<add>}
<add>
<add>func (r *router) RegisterDriver(name string, driver driverapi.Driver, c driverapi.Capability) error {
<add> r.d = driver
<add> return nil
<add>}
<add>
<add>func (ep *endpoint) Interfaces() []driverapi.InterfaceInfo {
<add> return nil
<add>}
<add>
<add>func (ep *endpoint) AddInterface(ID int, mac net.HardwareAddr, ipv4 net.IPNet, ipv6 net.IPNet) error {
<add> ep.id = ID
<add> ep.addr = ipv4
<add> ep.mac = mac
<add> return nil
<add>}
<add>
<add>func (ep *endpoint) InterfaceNames() []driverapi.InterfaceNameInfo {
<add> return []driverapi.InterfaceNameInfo{ep}
<add>
<add>}
<add>
<add>func (ep *endpoint) SetNames(srcName, dstPrefix string) error {
<add> ep.name = srcName
<add> return nil
<add>}
<add>
<add>func (ep *endpoint) ID() int {
<add> return ep.id
<add>}
<add>
<add>func (ep *endpoint) SetGateway(net.IP) error {
<add> return nil
<add>}
<add>
<add>func (ep *endpoint) SetGatewayIPv6(net.IP) error {
<add> return nil
<add>}
<add>
<add>func (ep *endpoint) AddStaticRoute(destination *net.IPNet, routeType int,
<add> nextHop net.IP, interfaceID int) error {
<add> return nil
<add>}
<add>
<add>func (ep *endpoint) SetHostsPath(string) error {
<add> return nil
<add>}
<add>
<add>func (ep *endpoint) SetResolvConfPath(string) error {
<add> return nil
<add>}
<add>
<add>func main() {
<add> if reexec.Init() {
<add> return
<add> }
<add>
<add> r := &router{}
<add> if err := overlay.Init(r); err != nil {
<add> fmt.Printf("Failed to initialize overlay driver: %v\n", err)
<add> os.Exit(1)
<add> }
<add>
<add> opt := make(map[string]interface{})
<add> if len(os.Args) > 1 {
<add> opt[netlabel.OverlayBindInterface] = os.Args[1]
<add> }
<add> if len(os.Args) > 2 {
<add> opt[netlabel.OverlayNeighborIP] = os.Args[2]
<add> }
<add> if len(os.Args) > 3 {
<add> opt[netlabel.KVProvider] = os.Args[3]
<add> }
<add> if len(os.Args) > 4 {
<add> opt[netlabel.KVProviderURL] = os.Args[4]
<add> }
<add>
<add> r.d.Config(opt)
<add>
<add> if err := r.d.CreateNetwork(types.UUID("testnetwork"),
<add> map[string]interface{}{}); err != nil {
<add> fmt.Printf("Failed to create network in the driver: %v\n", err)
<add> os.Exit(1)
<add> }
<add>
<add> ep := &endpoint{}
<add> if err := r.d.CreateEndpoint(types.UUID("testnetwork"), types.UUID("testep"),
<add> ep, map[string]interface{}{}); err != nil {
<add> fmt.Printf("Failed to create endpoint in the driver: %v\n", err)
<add> os.Exit(1)
<add> }
<add>
<add> if err := r.d.Join(types.UUID("testnetwork"), types.UUID("testep"),
<add> "", ep, map[string]interface{}{}); err != nil {
<add> fmt.Printf("Failed to join an endpoint in the driver: %v\n", err)
<add> os.Exit(1)
<add> }
<add>
<add> link, err := netlink.LinkByName(ep.name)
<add> if err != nil {
<add> fmt.Printf("Failed to find the container interface with name %s: %v\n",
<add> ep.name, err)
<add> os.Exit(1)
<add> }
<add>
<add> ipAddr := &netlink.Addr{IPNet: &ep.addr, Label: ""}
<add> if err := netlink.AddrAdd(link, ipAddr); err != nil {
<add> fmt.Printf("Failed to add address to the interface: %v\n", err)
<add> os.Exit(1)
<add> }
<add>
<add> sigCh := make(chan os.Signal, 1)
<add> signal.Notify(sigCh, os.Interrupt, os.Kill)
<add>
<add> for {
<add> select {
<add> case <-sigCh:
<add> r.d.Leave(types.UUID("testnetwork"), types.UUID("testep"))
<add> overlay.Fini(r.d)
<add> os.Exit(0)
<add> }
<add> }
<add>} | 1 |
Python | Python | fix stop_gradient inconsistent api | 0bc856f90a746ce3c8078f5ec4fb5156c88d8fdd | <ide><path>keras/backend/cntk_backend.py
<ide> def batch_set_value(tuples):
<ide>
<ide>
<ide> def stop_gradient(variables):
<del> return C.stop_gradient(C.combine(variables))
<add> if isinstance(variables, (list, tuple)):
<add> return map(C.stop_gradient, variables)
<add> else:
<add> return C.stop_gradient(variables)
<ide>
<ide>
<ide> def switch(condition, then_expression, else_expression):
<ide><path>keras/backend/tensorflow_backend.py
<ide> def stop_gradient(variables):
<ide> """Returns `variables` but with zero gradient w.r.t. every other variable.
<ide>
<ide> # Arguments
<del> variables: List of variables.
<add> variables: tensor or list of tensors to consider constant with respect
<add> to any other variable.
<ide>
<ide> # Returns
<del> The same list of variables.
<add> A single tensor or a list of tensors (depending on the passed argument)
<add> that has constant gradient with respect to any other variable.
<ide> """
<del> return tf.stop_gradient(variables)
<add> if isinstance(variables, (list, tuple)):
<add> return map(tf.stop_gradient, variables)
<add> else:
<add> return tf.stop_gradient(variables)
<ide>
<ide>
<ide> # CONTROL FLOW
<ide><path>keras/backend/theano_backend.py
<ide> def gradients(loss, variables):
<ide>
<ide>
<ide> def stop_gradient(variables):
<del> """Returns `variables` but with zero gradient with respect to every other
<del> variables.
<add> """Returns `variables` but with zero gradient w.r.t. every other variable.
<add>
<add> # Arguments
<add> variables: tensor or list of tensors to consider constant with respect
<add> to any other variable.
<add>
<add> # Returns
<add> A single tensor or a list of tensors (depending on the passed argument)
<add> that has constant gradient with respect to any other variable.
<ide> """
<del> return theano.gradient.disconnected_grad(variables)
<add> if isinstance(variables, (list, tuple)):
<add> return map(theano.gradient.disconnected_grad, variables)
<add> else:
<add> return theano.gradient.disconnected_grad(variables)
<ide>
<ide>
<ide> # CONTROL FLOW
<ide><path>tests/keras/backend/backend_test.py
<ide> def test_gradient(self):
<ide> assert_allclose(zero_list[i], z_list[i], atol=1e-05)
<ide> assert_allclose(zero_list[i + 1], zero_list[i + 1], atol=1e-05)
<ide>
<add> def test_stop_gradient(self):
<add> # This test checks the consistency of the stop_gradient backend API.
<add> # It doesn't check the functionality (which is checked at the
<add> # test_gradient test).
<add> val = np.random.random((4, 2))
<add> for k in BACKENDS:
<add> a = k.variable(val)
<add> b = k.square(a)
<add> c, d = k.stop_gradient([a, b])
<add> e = k.stop_gradient(b)
<add>
<ide> # cntk currently not support function in this way, so can't test as this
<ide> def test_function(self):
<ide> test_backend = [KTH, KTF] | 4 |
PHP | PHP | correct bad comparision | f2e953d8929e31f05909a8174278d5e1381e79db | <ide><path>lib/Cake/Test/Case/I18n/MultibyteTest.php
<ide> function testUsingMbStrtolower() {
<ide>
<ide> $string = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ';
<ide> $result = mb_strtolower($string);
<del> $expected = 'ႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅ';
<add> $expected = 'ⴀⴁⴂⴃⴄⴅⴆⴇⴈⴉⴊⴋⴌⴍⴎⴏⴐⴑⴒⴓⴔⴕⴖⴗⴘⴙⴚⴛⴜⴝⴞⴟⴠⴡⴢⴣⴤⴥ';
<ide> $this->assertEqual($expected, $result);
<ide>
<ide> $string = 'ḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẖẗẘẙẚẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸ'; | 1 |
Text | Text | add message to ask questions on spectrum | 5e4dc75db1c52a6f562a9090130bb863fe285e6d | <ide><path>.github/issue_template.md
<ide> <!--- Provide a general summary of the issue in the Title above -->
<ide>
<add><!--
<add>IMPORTANT
<add>> If you have a question about Next.js you should ask your question on Spectrum https://spectrum.chat/next-js
<add>> or join our Slack community at https://zeit.chat and ask in the `#next` channel
<add>-->
<add>
<ide> <!--
<ide> Thank you very much for contributing to Next.js by creating an issue! ❤️
<ide> To avoid duplicate issues we ask you to check off the following list | 1 |
Ruby | Ruby | disallow nil value for token#create | bcc4f1bb292698c1ba3fbad5720706ddd123fbd0 | <ide><path>Library/Homebrew/version.rb
<ide> class Token
<ide> include Comparable
<ide>
<ide> def self.create(val)
<del> return NULL_TOKEN if val.nil?
<del> return NULL_TOKEN if val.respond_to?(:null?) && val.null?
<del>
<ide> raise TypeError, "Token value must be a string; got a #{val.class} (#{val})" unless val.respond_to?(:to_str)
<ide>
<ide> case val | 1 |
Javascript | Javascript | handle suspenselistcomponent getting retried | e04f4259c4c2063038c47e0364f4d7ac71236bc0 | <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.js
<ide> import {
<ide> HostRoot,
<ide> ClassComponent,
<ide> SuspenseComponent,
<add> SuspenseListComponent,
<ide> FunctionComponent,
<ide> ForwardRef,
<ide> MemoComponent,
<ide> export function resolveRetryThenable(boundaryFiber: Fiber, thenable: Thenable) {
<ide> retryTime = suspenseState.retryTime;
<ide> }
<ide> break;
<add> case SuspenseListComponent:
<add> retryCache = boundaryFiber.stateNode;
<add> break;
<ide> default:
<ide> invariant(
<ide> false,
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseList-test.internal.js
<ide> describe('ReactSuspenseList', () => {
<ide> ReactFeatureFlags = require('shared/ReactFeatureFlags');
<ide> ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false;
<ide> ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
<add> ReactFeatureFlags.enableSuspenseServerRenderer = true;
<ide> React = require('react');
<ide> ReactNoop = require('react-noop-renderer');
<ide> Scheduler = require('scheduler'); | 2 |
Text | Text | improve description and tests descriptions | 052173e5023752bcbe39dbd193347a1025f8d4b7 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/zhang-suen-thinning-algorithm.md
<ide> dashedName: zhang-suen-thinning-algorithm
<ide>
<ide> This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of:
<ide>
<del><!-- TODO write fully in markdown>
<del><!-- markdownlint-disable -->
<del>
<del><pre>
<del> ################# #############
<del> ################## ################
<del> ################### ##################
<del> ######## ####### ###################
<del> ###### ####### ####### ######
<del> ###### ####### #######
<del> ################# #######
<del> ################ #######
<del> ################# #######
<del> ###### ####### #######
<del> ###### ####### #######
<del> ###### ####### ####### ######
<del> ######## ####### ###################
<del> ######## ####### ###### ################## ######
<del> ######## ####### ###### ################ ######
<del> ######## ####### ###### ############# ######
<del></pre>
<add>```js
<add>const testImage1 = [
<add> ' ',
<add> '######### ######## ',
<add> '### #### #### #### ',
<add> '### ### ### ### ',
<add> '### #### ### ',
<add> '######### ### ',
<add> '### #### ### ### ',
<add> '### #### ### #### #### ### ',
<add> '### #### ### ######## ### ',
<add> ' '
<add>];
<add>```
<ide>
<ide> It produces the thinned output:
<ide>
<del><pre>
<del>
<del> # ########## #######
<del> ## # #### #
<del> # # ##
<del> # # #
<del> # # #
<del> # # #
<del> ############ #
<del> # # #
<del> # # #
<del> # # #
<del> # # #
<del> # ##
<del> # ############
<del> ### ###
<del>
<del></pre>
<add>```js
<add>[ ' ',
<add> '######## ###### ',
<add> '# # ## ',
<add> '# # # ',
<add> '# # # ',
<add> '###### # # ',
<add> '# ## # ',
<add> '# # # ## ## # ',
<add> '# # #### ',
<add> ' ' ];
<add>```
<ide>
<del><h2>Algorithm</h2>
<add>## Algorithm
<ide>
<ide> Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:
<ide>
<del><table border="3">
<del> <tr><td style="text-align: center;">P9</td><td style="text-align: center;">P2</td><td style="text-align: center;">P3</td></tr>
<del> <tr><td style="text-align: center;">P8</td><td style="text-align: center;"><strong>P1</strong></td><td style="text-align: center;">P4</td></tr>
<del> <tr><td style="text-align: center;">P7</td><td style="text-align: center;">P6</td><td style="text-align: center;">P5</td></tr>
<del></table>
<add>$$\begin{array}{|c|c|c|}
<add> \\hline
<add> P9 & P2 & P3\\\\ \\hline
<add> P8 & \boldsymbol{P1} & P4\\\\ \\hline
<add> P7 & P6 & P5\\\\ \\hline
<add>\end{array}$$
<ide>
<ide> Obviously the boundary pixels of the image cannot have the full eight neighbours.
<ide>
<del><ul>
<del> <li>Define $A(P1)$ = the number of transitions from white to black, (0 -> 1) in the sequence P2, P3, P4, P5, P6, P7, P8, P9, P2. (Note the extra P2 at the end - it is circular).</li>
<del> <li>Define $B(P1)$ = the number of black pixel neighbours of P1. ( = sum(P2 .. P9) )</li>
<del></ul>
<add>- Define $A(P1)$ = the number of transitions from white to black, ($0 \to 1$) in the sequence P2, P3, P4, P5, P6, P7, P8, P9, P2. (Note the extra P2 at the end - it is circular).
<add>- Define $B(P1)$ = the number of black pixel neighbours of P1. ($= \\sum(P2 \ldots P9)$)
<ide>
<ide> **Step 1:**
<ide>
<ide> All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
<ide>
<del> <ol>
<del> <li>The pixel is black and has eight neighbours</li>
<del> <li>$2 <= B(P1) <= 6$</li>
<del> <li>$A(P1) = 1$</li>
<del> <li>At least one of <strong>P2, P4 and P6</strong> is white</li>
<del> <li>At least one of <strong>P4, P6 and P8</strong> is white</li>
<del> </ol>
<add>1. The pixel is black and has eight neighbours
<add>2. $2 \le B(P1) \le 6$
<add>3. $A(P1) = 1$
<add>4. At least one of $P2$, $P4$ and $P6$ is white
<add>5. At least one of $P4$, $P6$ and $P8$ is white
<ide>
<ide> After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
<ide>
<ide> **Step 2:**
<ide>
<ide> All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
<ide>
<del> <ol>
<del> <li>The pixel is black and has eight neighbours</li>
<del> <li>$2 <= B(P1) <= 6$</li>
<del> <li>$A(P1) = 1$</li>
<del> <li>At least one of <strong>P2, P4 and P8</strong> is white</li>
<del> <li>At least one of <strong>P2, P6 and P8</strong> is white</li>
<del> </ol>
<del>
<add>1. The pixel is black and has eight neighbours
<add>2. $2 \le B(P1) \le 6$
<add>3. $A(P1) = 1$
<add>4. At least one of $P2$, $P4$ and $P8$ is white
<add>5. At least one of $P2$, $P6$ and $P8$ is white
<add>
<ide> After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
<ide>
<ide> **Iteration:**
<ide> If any pixels were set in this round of either step 1 or step 2 then all steps a
<ide>
<ide> # --instructions--
<ide>
<del>Write a routine to perform Zhang-Suen thinning on the provided image matrix.
<add>Write a routine to perform Zhang-Suen thinning on the provided `image`, an array of strings, where each string represents single line of the image. In the string, `#` represents black pixel, and whitespace represents white pixel. Function should return thinned image, using the same representation.
<ide>
<ide> # --hints--
<ide>
<ide> assert.equal(typeof thinImage, 'function');
<ide> `thinImage` should return an array.
<ide>
<ide> ```js
<del>assert(Array.isArray(result));
<add>assert(Array.isArray(thinImage(_testImage1)));
<ide> ```
<ide>
<ide> `thinImage` should return an array of strings.
<ide>
<ide> ```js
<del>assert.equal(typeof result[0], 'string');
<add>assert.equal(typeof thinImage(_testImage1)[0], 'string');
<ide> ```
<ide>
<del>`thinImage` should return an array of strings.
<add>`thinImage(testImage1)` should return a thinned image as in the example.
<ide>
<ide> ```js
<del>assert.deepEqual(result, expected);
<add>assert.deepEqual(thinImage(_testImage1), expected1);
<add>```
<add>
<add>`thinImage(testImage2)` should return a thinned image.
<add>
<add>```js
<add>assert.deepEqual(thinImage(_testImage2), expected2);
<ide> ```
<ide>
<ide> # --seed--
<ide>
<ide> ## --after-user-code--
<ide>
<ide> ```js
<del>const imageForTests = [
<add>const _testImage1 = [
<add> ' ',
<add> '######### ######## ',
<add> '### #### #### #### ',
<add> '### ### ### ### ',
<add> '### #### ### ',
<add> '######### ### ',
<add> '### #### ### ### ',
<add> '### #### ### #### #### ### ',
<add> '### #### ### ######## ### ',
<add> ' '
<add>];
<add>const expected1 = [
<add> ' ',
<add> '######## ###### ',
<add> '# # ## ',
<add> '# # # ',
<add> '# # # ',
<add> '###### # # ',
<add> '# ## # ',
<add> '# # # ## ## # ',
<add> '# # #### ',
<add> ' '
<add>];
<add>const _testImage2 = [
<ide> ' ',
<ide> ' ################# ############# ',
<ide> ' ################## ################ ',
<ide> const imageForTests = [
<ide> ' ######## ####### ###### ################ ###### ',
<ide> ' ######## ####### ###### ############# ###### ',
<ide> ' '];
<del>const expected = [
<add>const expected2 = [
<ide> ' ',
<ide> ' ',
<ide> ' # ########## ####### ',
<ide> const expected = [
<ide> ' ',
<ide> ' '
<ide> ];
<del>const result = thinImage(imageForTests);
<ide> ```
<ide>
<ide> ## --seed-contents--
<ide>
<ide> ```js
<del>const testImage = [
<del> ' ',
<del> ' ################# ############# ',
<del> ' ################## ################ ',
<del> ' ################### ################## ',
<del> ' ######## ####### ################### ',
<del> ' ###### ####### ####### ###### ',
<del> ' ###### ####### ####### ',
<del> ' ################# ####### ',
<del> ' ################ ####### ',
<del> ' ################# ####### ',
<del> ' ###### ####### ####### ',
<del> ' ###### ####### ####### ',
<del> ' ###### ####### ####### ###### ',
<del> ' ######## ####### ################### ',
<del> ' ######## ####### ###### ################## ###### ',
<del> ' ######## ####### ###### ################ ###### ',
<del> ' ######## ####### ###### ############# ###### ',
<del> ' '];
<del>
<ide> function thinImage(image) {
<ide>
<ide> }
<add>
<add>const testImage1 = [
<add> ' ',
<add> '######### ######## ',
<add> '### #### #### #### ',
<add> '### ### ### ### ',
<add> '### #### ### ',
<add> '######### ### ',
<add> '### #### ### ### ',
<add> '### #### ### #### #### ### ',
<add> '### #### ### ######## ### ',
<add> ' '
<add>];
<ide> ```
<ide>
<ide> # --solutions-- | 1 |
Text | Text | changelog entries for `{{#each}}` & `{{#each-in}}` | 0ddac17b8d4172dd77bd6a1e3183b67a728e3558 | <ide><path>CHANGELOG.md
<ide>
<ide> - [#16613](https://github.com/emberjs/ember.js/pull/16613) [BUGFIX] Prevent errors in ember-engines + 3.1 + proxies.
<ide> - [#16597](https://github.com/emberjs/ember.js/pull/16597) [BUGFIX] Ensure `Ember.run.cancelTimers` is present.
<del>- [#16605](https://github.com/emberjs/ember.js/pull/16605) [BUGFIX] Use resetCache on container destroy
<del>- [#16615](https://github.com/emberjs/ember.js/pull/16615) [BUGFIX] Fix NAMESPACES_BY_ID leaks
<add>- [#16605](https://github.com/emberjs/ember.js/pull/16605) [BUGFIX] Use resetCache on container destroy.
<add>- [#16615](https://github.com/emberjs/ember.js/pull/16615) [BUGFIX] Fix NAMESPACES_BY_ID leaks.
<ide> - [#16539](https://github.com/emberjs/ember.js/pull/16539) [BUGFIX] Ember is already registered by the libraries registry already.
<del>- [#16559](https://github.com/emberjs/ember.js/pull/16559) [BUGFIX] Fix property normalization, Update glimmer-vm to 0.34.0
<add>- [#16559](https://github.com/emberjs/ember.js/pull/16559) [BUGFIX] Fix property normalization, Update glimmer-vm to 0.34.0.
<ide> - [#16563](https://github.com/emberjs/ember.js/pull/16563) [BUGFIX] Ensure `ariaRole` can be initially false.
<del>- [#16550](https://github.com/emberjs/ember.js/pull/16550) [BUGFIX] Decrement counter of pending requests in the next tick
<del>- [#16551](https://github.com/emberjs/ember.js/pull/16551) [BUGFIX] Fix `proto` return value for native classes
<add>- [#16550](https://github.com/emberjs/ember.js/pull/16550) [BUGFIX] Decrement counter of pending requests in the next tick.
<add>- [#16551](https://github.com/emberjs/ember.js/pull/16551) [BUGFIX] Fix `proto` return value for native classes.
<ide> - [#16558](https://github.com/emberjs/ember.js/pull/16558) [BUGFIX] Ensure ComponentDefinitions do not leak heap space.
<del>- [#16560](https://github.com/emberjs/ember.js/pull/16560) [BUGFIX] avoid strict assertion when object proxy calls thru for function
<add>- [#16560](https://github.com/emberjs/ember.js/pull/16560) [BUGFIX] avoid strict assertion when object proxy calls thru for function.
<ide> - [#16564](https://github.com/emberjs/ember.js/pull/16564) [BUGFIX] Ensure Ember.isArray does not trigger proxy assertion.
<del>- [#16572](https://github.com/emberjs/ember.js/pull/16572) [BUGFIX] Fix curly component class reference setup
<add>- [#16572](https://github.com/emberjs/ember.js/pull/16572) [BUGFIX] Fix curly component class reference setup.
<ide> - [#16493](https://github.com/emberjs/ember.js/pull/16493) [BUGFIX] Ensure proxies have access to `getOwner(this)`.
<del>- [#16494](https://github.com/emberjs/ember.js/pull/16494) [BUGFIX] Adjust assertion to allow for either undefined or null
<del>- [#16499](https://github.com/emberjs/ember.js/pull/16499) [BUGFIX] Object to string serialization
<add>- [#16494](https://github.com/emberjs/ember.js/pull/16494) [BUGFIX] Adjust assertion to allow for either undefined or null.
<add>- [#16499](https://github.com/emberjs/ember.js/pull/16499) [BUGFIX] Object to string serialization.
<ide> - [#16514](https://github.com/emberjs/ember.js/pull/16514) [BUGFIX] Bring back (with deprecation) Ember.EXTEND_PROTOTYPES.
<del>- [#16520](https://github.com/emberjs/ember.js/pull/16520) [BUGFIX] Adds options checking ability to debug/deprecation test helpers
<add>- [#16520](https://github.com/emberjs/ember.js/pull/16520) [BUGFIX] Adds options checking ability to debug/deprecation test helpers.
<ide> - [#16526](https://github.com/emberjs/ember.js/pull/16526) [BUGFIX] Ensure setting a `NAME_KEY` does not error.
<ide> - [#16527](https://github.com/emberjs/ember.js/pull/16527) [BUGFIX] Update glimmer-vm to 0.33.5.
<del>- [#16250](https://github.com/emberjs/ember.js/pull/16250) [DEPRECATION] Deprecation of `Ember.Logger`
<add>- [#16250](https://github.com/emberjs/ember.js/pull/16250) [DEPRECATION] Deprecation of `Ember.Logger`.
<ide> - [#16436](https://github.com/emberjs/ember.js/pull/16436) [BUGFIX] Refactor `CoreObject` to leverage native JS semantics.
<ide> - [#16382](https://github.com/emberjs/ember.js/pull/16382) Upgrade `backburner.js` to 2.2.2.
<del>- [#16387](https://github.com/emberjs/ember.js/pull/16387) [BUGFIX] Add an assertion that actions cannot be sent from a destroyed/destroying object
<del>- [#16386](https://github.com/emberjs/ember.js/pull/16386) [BUGFIX] Add an assertion if you attempt a `transitionTo` when the app is destroyed
<del>- [#16433](https://github.com/emberjs/ember.js/pull/16433) [CLEANUP] Remove `content` alias
<del>- [#16462](https://github.com/emberjs/ember.js/pull/16462) [CLEANUP] Remove deprecated `MODEL_FACTORY_INJECTIONS`
<add>- [#16387](https://github.com/emberjs/ember.js/pull/16387) [BUGFIX] Add an assertion that actions cannot be sent from a destroyed/destroying object.
<add>- [#16386](https://github.com/emberjs/ember.js/pull/16386) [BUGFIX] Add an assertion if you attempt a `transitionTo` when the app is destroyed.
<add>- [#16399](https://github.com/emberjs/ember.js/pull/16399) [BUGFIX] `{{#each}}` and `{{#each-in}}` now support objects implementing the native iteration protocol, including `Map` and `Set`.
<add>- [#16399](https://github.com/emberjs/ember.js/pull/16399) [BUGFIX] `{{#each-in}}` now correctly handles `key="@index"` (using the index/position). The new `key="@key"` option uses the item's key.
<add>- [#16433](https://github.com/emberjs/ember.js/pull/16433) [CLEANUP] Remove `content` alias.
<add>- [#16462](https://github.com/emberjs/ember.js/pull/16462) [CLEANUP] Remove deprecated `MODEL_FACTORY_INJECTIONS`.
<ide> - [emberjs/rfcs#286](https://github.com/emberjs/rfcs/blob/master/text/0286-block-let-template-helper.md) [FEATURE] Enabled block `let` handlebars helper by default.
<ide>
<ide> ### v3.1.2 (May 7, 2018) | 1 |
Go | Go | reorganize code between unix and windows files | a65f83317c88734536219209d975e7e3ca6c4f85 | <ide><path>daemon/config/config_unix.go
<ide> const (
<ide> DefaultIpcMode = "private"
<ide> )
<ide>
<add>// BridgeConfig stores all the bridge driver specific
<add>// configuration.
<add>type BridgeConfig struct {
<add> commonBridgeConfig
<add>
<add> // These fields are common to all unix platforms.
<add> commonUnixBridgeConfig
<add>
<add> // Fields below here are platform specific.
<add> EnableIPv6 bool `json:"ipv6,omitempty"`
<add> EnableIPTables bool `json:"iptables,omitempty"`
<add> EnableIP6Tables bool `json:"ip6tables,omitempty"`
<add> EnableIPForward bool `json:"ip-forward,omitempty"`
<add> EnableIPMasq bool `json:"ip-masq,omitempty"`
<add> EnableUserlandProxy bool `json:"userland-proxy,omitempty"`
<add> UserlandProxyPath string `json:"userland-proxy-path,omitempty"`
<add> FixedCIDRv6 string `json:"fixed-cidr-v6,omitempty"`
<add>}
<add>
<ide> // Config defines the configuration of a docker daemon.
<ide> // It includes json tags to deserialize configuration from a file
<ide> // using the same names that the flags in the command line uses.
<ide> type Config struct {
<ide> Rootless bool `json:"rootless,omitempty"`
<ide> }
<ide>
<del>// BridgeConfig stores all the bridge driver specific
<del>// configuration.
<del>type BridgeConfig struct {
<del> commonBridgeConfig
<del>
<del> // These fields are common to all unix platforms.
<del> commonUnixBridgeConfig
<del>
<del> // Fields below here are platform specific.
<del> EnableIPv6 bool `json:"ipv6,omitempty"`
<del> EnableIPTables bool `json:"iptables,omitempty"`
<del> EnableIP6Tables bool `json:"ip6tables,omitempty"`
<del> EnableIPForward bool `json:"ip-forward,omitempty"`
<del> EnableIPMasq bool `json:"ip-masq,omitempty"`
<del> EnableUserlandProxy bool `json:"userland-proxy,omitempty"`
<del> UserlandProxyPath string `json:"userland-proxy-path,omitempty"`
<del> FixedCIDRv6 string `json:"fixed-cidr-v6,omitempty"`
<del>}
<del>
<ide> // IsSwarmCompatible defines if swarm mode can be enabled in this config
<ide> func (conf *Config) IsSwarmCompatible() error {
<ide> if conf.ClusterStore != "" || conf.ClusterAdvertise != "" {
<ide> func (conf *Config) ValidatePlatformConfig() error {
<ide> return verifyDefaultCgroupNsMode(conf.CgroupNamespaceMode)
<ide> }
<ide>
<del>// IsRootless returns conf.Rootless
<add>// IsRootless returns conf.Rootless on Linux but false on Windows
<ide> func (conf *Config) IsRootless() bool {
<ide> return conf.Rootless
<ide> }
<ide><path>daemon/config/config_windows.go
<ide> type BridgeConfig struct {
<ide> }
<ide>
<ide> // Config defines the configuration of a docker daemon.
<del>// These are the configuration settings that you pass
<del>// to the docker daemon when you launch it with say: `dockerd -e windows`
<add>// It includes json tags to deserialize configuration from a file
<add>// using the same names that the flags in the command line uses.
<ide> type Config struct {
<ide> CommonConfig
<ide>
<ide> func (conf *Config) GetRuntime(name string) *types.Runtime {
<ide> return nil
<ide> }
<ide>
<del>// GetInitPath returns the configure docker-init path
<del>func (conf *Config) GetInitPath() string {
<del> return ""
<del>}
<del>
<ide> // GetDefaultRuntimeName returns the current default runtime
<ide> func (conf *Config) GetDefaultRuntimeName() string {
<ide> return StockRuntimeName
<ide> func (conf *Config) GetExecRoot() string {
<ide> return ""
<ide> }
<ide>
<add>// GetInitPath returns the configured docker-init path
<add>func (conf *Config) GetInitPath() string {
<add> return ""
<add>}
<add>
<ide> // IsSwarmCompatible defines if swarm mode can be enabled in this config
<ide> func (conf *Config) IsSwarmCompatible() error {
<ide> return nil
<ide> func (conf *Config) ValidatePlatformConfig() error {
<ide> return nil
<ide> }
<ide>
<del>// IsRootless returns conf.Rootless on Unix but false on Windows
<add>// IsRootless returns conf.Rootless on Linux but false on Windows
<ide> func (conf *Config) IsRootless() bool {
<ide> return false
<ide> } | 2 |
Text | Text | simplify the definition of reducers | 6d18395e242d8cd2f49af097a0bc1be24f1cc3c1 | <ide><path>docs/basics/Reducers.md
<ide> # Reducers
<ide>
<del>[Actions](./Actions.md) describe the fact that *something happened*, but don't specify how the application's state changes in response. This is the job of reducers.
<add>**Reducers** specify how the application's state changes in response to [actions](./Actions.md) sent to the store. Remember that actions only describe the fact that *something happened*, but don't describe how the application's state changes.
<ide>
<ide> ## Designing the State Shape
<ide> | 1 |
Text | Text | fix a spelling error in api-guide | e2c35920d180be47c835ee24a99440cb89dec58c | <ide><path>docs/api-guide/serializers.md
<ide> The [html-json-forms][html-json-forms] package provides an algorithm and seriali
<ide>
<ide> ## QueryFields
<ide>
<del>[djangorestframework-queryfields][djangorestframework-queryfields] allows API clients to specify which fields will be sent in the response via inclusion or exclusion query paramaters.
<add>[djangorestframework-queryfields][djangorestframework-queryfields] allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.
<ide>
<ide>
<ide> [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion | 1 |
Java | Java | add logger.isinfoenabled check before logger.info | b92515bdee5a3f153183e2f86ee5e378c28b0d1e | <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java
<ide> public Object getObject() throws BeansException {
<ide> return getSingletonInstance();
<ide> }
<ide> else {
<del> if (this.targetName == null) {
<add> if (this.targetName == null && logger.isInfoEnabled()) {
<ide> logger.info("Using non-singleton proxies with singleton targets is often undesirable. " +
<ide> "Enable prototype proxies by setting the 'targetName' property.");
<ide> } | 1 |
Javascript | Javascript | integrate animation service with chart | 3e59438646382d66b2b1313731f237f43c4cc9dc | <ide><path>src/Chart.Core.js
<ide>
<ide> Chart.animationService = {
<ide> animations: [],
<del> addAnimation: function(chart, animationObject) {
<add> addAnimation: function(chartInstance, animationObject) {
<ide> for (var index = 0; index < this.animations.length; ++ index){
<del> if (this.animations[index].chart === chart){
<add> if (this.animations[index].chartInstance === chartInstance){
<ide> // replacing an in progress animation
<ide> this.animations[index].lastTimeRun = null;
<ide> this.animations[index].animationObject = animationObject;
<ide> }
<ide>
<ide> this.animations.push({
<del> chart: chart,
<add> chartInstance: chartInstance,
<ide> animationObject: animationObject,
<ide> lastTimeRun: null
<ide> });
<ide> currentAnimation.animationObject.currentStep++;
<ide> }
<ide>
<del> currentAnimation.animationObject.render(currentAnimation.animationObject);
<add> currentAnimation.animationObject.render(currentAnimation.chartInstance, currentAnimation.animationObject);
<ide>
<ide> if (currentAnimation.animationObject.currentStep == currentAnimation.animationObject.numSteps){
<ide> // executed the last frame. Remove the animation. | 1 |
Mixed | Python | add adam optimizer | 9f595fe7f7856ae9ea8a1e8439e1342757f0f3a4 | <ide><path>docs/sources/optimizers.md
<ide> __Arguments__:
<ide>
<ide> - __lr__: float >= 0. Learning rate.
<ide> - __rho__: float >= 0.
<del>- __epsilon__: float >= 0. Fuzz factor.
<ide>\ No newline at end of file
<add>- __epsilon__: float >= 0. Fuzz factor.
<add>
<add>---
<add>
<add>## Adam
<add>
<add>```python
<add>keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8, kappa=1-1e-8)
<add>```
<add>
<add>Adam optimizer, proposed by Kingma and Lei Ba in [Adam: A Method For Stochastic Optimization](http://arxiv.org/pdf/1412.6980v4.pdf). Default parameters are those suggested in the paper. The parameter "lambda" from the paper has been renamed kappa, for syntactic reasons.
<add>
<add>__Arguments__:
<add>
<add>- __lr__: float >= 0. Learning rate.
<add>- __beta_1__, __beta_2__: floats, 0 < beta < 1. Generally close to 1.
<add>- __epsilon__: float >= 0. Fuzz factor.
<add>- __kappa__: float 0 < kappa < 1. Lambda parameter in the original paper.
<add>
<add>---
<ide>\ No newline at end of file
<ide><path>keras/optimizers.py
<ide> def get_updates(self, params, cost):
<ide>
<ide>
<ide> class Adadelta(Optimizer):
<del>
<add> '''
<add> Reference: http://arxiv.org/abs/1212.5701
<add> '''
<ide> def __init__(self, lr=1.0, rho=0.95, epsilon=1e-6, *args, **kwargs):
<ide> self.__dict__.update(locals())
<ide>
<ide> def get_updates(self, params, cost):
<ide> updates.append((d_a, new_d_a))
<ide> return updates
<ide>
<add>
<add>class Adam(Optimizer):
<add> '''
<add> Reference: http://arxiv.org/abs/1412.6980
<add>
<add> Default parameters follow those provided in the original paper
<add>
<add> lambda is renamed kappa.
<add> '''
<add> def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8, kappa=1-1e-8, *args, **kwargs):
<add> self.__dict__.update(locals())
<add> self.iterations = shared_scalar(0)
<add>
<add> def get_updates(self, params, cost):
<add> grads = self.get_gradients(cost, params)
<add> updates = [(self.iterations, self.iterations+1.)]
<add>
<add> i = self.iterations
<add> beta_1_t = self.beta_1 * (self.kappa**i)
<add>
<add> # the update below seems missing from the paper, but is obviously required
<add> beta_2_t = self.beta_2 * (self.kappa**i)
<add>
<add> for p, g in zip(params, grads):
<add> m = theano.shared(p.get_value() * 0.) # zero init of moment
<add> v = theano.shared(p.get_value() * 0.) # zero init of velocity
<add>
<add> m_t = ((1. - self.beta_1) * m) + (self.beta_1 * g)
<add> v_t = (self.beta_2 * v) + (1 - self.beta_2) * (g**2)
<add>
<add> m_b_t = m_t / (1 - beta_1_t)
<add> v_b_t = v_t / (1 - beta_2_t)
<add>
<add> p_t = p - self.lr * m_b_t / (T.sqrt(v_t) + self.epsilon)
<add>
<add> updates.append((m, m_t))
<add> updates.append((v, v_t))
<add> updates.append((p, p_t))
<add> return updates
<add>
<ide> # aliases
<ide> sgd = SGD
<ide> rmsprop = RMSprop
<ide> adagrad = Adagrad
<ide> adadelta = Adadelta
<add>adam = Adam
<ide>
<ide> from utils.generic_utils import get_from_module
<ide> def get(identifier): | 2 |
Javascript | Javascript | replace string concatenation with template | cb87c92694d7b9779acc6c6bf24d0298b259ecb2 | <ide><path>lib/_http_server.js
<ide> ServerResponse.prototype.detachSocket = function detachSocket(socket) {
<ide> };
<ide>
<ide> ServerResponse.prototype.writeContinue = function writeContinue(cb) {
<del> this._writeRaw('HTTP/1.1 100 Continue' + CRLF + CRLF, 'ascii', cb);
<add> this._writeRaw(`HTTP/1.1 100 Continue${CRLF}${CRLF}`, 'ascii', cb);
<ide> this._sent100 = true;
<ide> };
<ide>
<ide> function writeHead(statusCode, reason, obj) {
<ide> if (checkInvalidHeaderChar(this.statusMessage))
<ide> throw new errors.Error('ERR_INVALID_CHAR', 'statusMessage');
<ide>
<del> var statusLine = 'HTTP/1.1 ' + statusCode + ' ' + this.statusMessage + CRLF;
<add> var statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}${CRLF}`;
<ide>
<ide> if (statusCode === 204 || statusCode === 304 ||
<ide> (statusCode >= 100 && statusCode <= 199)) {
<ide> function onParserExecute(server, socket, parser, state, ret, d) {
<ide> }
<ide>
<ide> const badRequestResponse = Buffer.from(
<del> 'HTTP/1.1 400 ' + STATUS_CODES[400] + CRLF + CRLF, 'ascii'
<add> `HTTP/1.1 400 ${STATUS_CODES[400]}${CRLF}${CRLF}`, 'ascii'
<ide> );
<ide> function socketOnError(e) {
<ide> // Ignore further errors | 1 |
Java | Java | add generatedtype infrastructure | fd191d165bb6c886d8c3720c96240441f89d75cd | <ide><path>spring-core/src/main/java/org/springframework/aot/generator/DefaultGeneratedTypeContext.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generator;
<add>
<add>import java.util.LinkedHashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.function.Function;
<add>import java.util.stream.Collectors;
<add>
<add>import org.springframework.aot.hint.RuntimeHints;
<add>import org.springframework.javapoet.JavaFile;
<add>
<add>/**
<add> * Default {@link GeneratedTypeContext} implementation.
<add> *
<add> * @author Stephane Nicoll
<add> * @since 6.0
<add> */
<add>public class DefaultGeneratedTypeContext implements GeneratedTypeContext {
<add>
<add> private final String packageName;
<add>
<add> private final RuntimeHints runtimeHints;
<add>
<add> private final Function<String, GeneratedType> generatedTypeFactory;
<add>
<add> private final Map<String, GeneratedType> generatedTypes;
<add>
<add> /**
<add> * Create a context targeting the specified package name and using the specified
<add> * factory to create a {@link GeneratedType} per requested package name.
<add> * @param packageName the main package name
<add> * @param generatedTypeFactory the factory to use to create a {@link GeneratedType}
<add> * based on a package name.
<add> */
<add> public DefaultGeneratedTypeContext(String packageName, Function<String, GeneratedType> generatedTypeFactory) {
<add> this.packageName = packageName;
<add> this.runtimeHints = new RuntimeHints();
<add> this.generatedTypeFactory = generatedTypeFactory;
<add> this.generatedTypes = new LinkedHashMap<>();
<add> }
<add>
<add> @Override
<add> public RuntimeHints runtimeHints() {
<add> return this.runtimeHints;
<add> }
<add>
<add> @Override
<add> public GeneratedType getGeneratedType(String packageName) {
<add> return this.generatedTypes.computeIfAbsent(packageName, this.generatedTypeFactory);
<add> }
<add>
<add> @Override
<add> public GeneratedType getMainGeneratedType() {
<add> return getGeneratedType(this.packageName);
<add> }
<add>
<add> /**
<add> * Specify if a {@link GeneratedType} for the specified package name is registered.
<add> * @param packageName the package name to use
<add> * @return {@code true} if a type is registered for that package
<add> */
<add> public boolean hasGeneratedType(String packageName) {
<add> return this.generatedTypes.containsKey(packageName);
<add> }
<add>
<add> /**
<add> * Return the list of {@link JavaFile} of known generated type.
<add> * @return the java files of bootstrap classes in this instance
<add> */
<add> public List<JavaFile> toJavaFiles() {
<add> return this.generatedTypes.values().stream()
<add> .map(GeneratedType::toJavaFile)
<add> .collect(Collectors.toList());
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/generator/GeneratedType.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generator;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.function.Consumer;
<add>import java.util.function.Predicate;
<add>
<add>import javax.lang.model.element.Modifier;
<add>
<add>import org.springframework.javapoet.ClassName;
<add>import org.springframework.javapoet.JavaFile;
<add>import org.springframework.javapoet.MethodSpec;
<add>import org.springframework.javapoet.TypeSpec;
<add>
<add>/**
<add> * Wrapper for a generated {@linkplain TypeSpec type}.
<add> *
<add> * @author Stephane Nicoll
<add> * @since 6.0
<add> */
<add>public class GeneratedType {
<add>
<add> private final ClassName className;
<add>
<add> private final TypeSpec.Builder type;
<add>
<add> private final List<MethodSpec> methods;
<add>
<add> GeneratedType(ClassName className, Consumer<TypeSpec.Builder> type) {
<add> this.className = className;
<add> this.type = TypeSpec.classBuilder(className);
<add> type.accept(this.type);
<add> this.methods = new ArrayList<>();
<add> }
<add>
<add> /**
<add> * Create an instance for the specified {@link ClassName}, customizing the type with
<add> * the specified {@link Consumer consumer callback}.
<add> * @param className the class name
<add> * @param type a callback to customize the type, i.e. to change default modifiers
<add> * @return a new {@link GeneratedType}
<add> */
<add> public static GeneratedType of(ClassName className, Consumer<TypeSpec.Builder> type) {
<add> return new GeneratedType(className, type);
<add> }
<add>
<add> /**
<add> * Create an instance for the specified {@link ClassName}, as a {@code public} type.
<add> * @param className the class name
<add> * @return a new {@link GeneratedType}
<add> */
<add> public static GeneratedType of(ClassName className) {
<add> return of(className, type -> type.addModifiers(Modifier.PUBLIC));
<add> }
<add>
<add> /**
<add> * Return the {@link ClassName} of this instance.
<add> * @return the class name
<add> */
<add> public ClassName getClassName() {
<add> return this.className;
<add> }
<add>
<add> /**
<add> * Customize the type of this instance.
<add> * @param type the consumer of the type builder
<add> * @return this for method chaining
<add> */
<add> public GeneratedType customizeType(Consumer<TypeSpec.Builder> type) {
<add> type.accept(this.type);
<add> return this;
<add> }
<add>
<add> /**
<add> * Add a method using the state of the specified {@link MethodSpec.Builder},
<add> * updating the name of the method if a similar method already exists.
<add> * @param method a method builder representing the method to add
<add> * @return the added method
<add> */
<add> public MethodSpec addMethod(MethodSpec.Builder method) {
<add> MethodSpec methodToAdd = createUniqueNameIfNecessary(method.build());
<add> this.methods.add(methodToAdd);
<add> return methodToAdd;
<add> }
<add>
<add> /**
<add> * Return a {@link JavaFile} with the state of this instance.
<add> * @return a java file
<add> */
<add> public JavaFile toJavaFile() {
<add> return JavaFile.builder(this.className.packageName(),
<add> this.type.addMethods(this.methods).build()).indent("\t").build();
<add> }
<add>
<add> private MethodSpec createUniqueNameIfNecessary(MethodSpec method) {
<add> List<MethodSpec> candidates = this.methods.stream().filter(isSimilar(method)).toList();
<add> if (candidates.isEmpty()) {
<add> return method;
<add> }
<add> MethodSpec updatedMethod = method.toBuilder().setName(method.name + "_").build();
<add> return createUniqueNameIfNecessary(updatedMethod);
<add> }
<add>
<add> private Predicate<MethodSpec> isSimilar(MethodSpec method) {
<add> return candidate -> method.name.equals(candidate.name)
<add> && method.parameters.size() == candidate.parameters.size();
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/generator/GeneratedTypeContext.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generator;
<add>
<add>import org.springframework.aot.hint.RuntimeHints;
<add>
<add>/**
<add> * Context passed to object that can generate code, giving access to a main
<add> * {@link GeneratedType} as well as to a {@link GeneratedType} in a given
<add> * package if privileged access is required.
<add> *
<add> * @author Stephane Nicoll
<add> * @since 6.0
<add> */
<add>public interface GeneratedTypeContext {
<add>
<add> /**
<add> * Return the {@link RuntimeHints} instance to use to contribute hints for
<add> * generated types.
<add> * @return the runtime hints
<add> */
<add> RuntimeHints runtimeHints();
<add>
<add> /**
<add> * Return a {@link GeneratedType} for the specified package. If it does not
<add> * exist, it is created.
<add> * @param packageName the package name to use
<add> * @return a generated type
<add> */
<add> GeneratedType getGeneratedType(String packageName);
<add>
<add> /**
<add> * Return the main {@link GeneratedType}.
<add> * @return the generated type for the target package
<add> */
<add> GeneratedType getMainGeneratedType();
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/generator/DefaultGeneratedTypeContextTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generator;
<add>
<add>import javax.lang.model.element.Modifier;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.javapoet.ClassName;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>
<add>/**
<add> * Tests for {@link DefaultGeneratedTypeContext}.
<add> *
<add> * @author Stephane Nicoll
<add> */
<add>class DefaultGeneratedTypeContextTests {
<add>
<add> @Test
<add> void runtimeHints() {
<add> DefaultGeneratedTypeContext context = createComAcmeContext();
<add> assertThat(context.runtimeHints()).isNotNull();
<add> }
<add>
<add> @Test
<add> void getGeneratedTypeMatchesGetMainGeneratedTypeForMainPackage() {
<add> DefaultGeneratedTypeContext context = createComAcmeContext();
<add> assertThat(context.getMainGeneratedType().getClassName()).isEqualTo(ClassName.get("com.acme", "Main"));
<add> assertThat(context.getGeneratedType("com.acme")).isSameAs(context.getMainGeneratedType());
<add> }
<add>
<add> @Test
<add> void getMainGeneratedTypeIsLazilyCreated() {
<add> DefaultGeneratedTypeContext context = createComAcmeContext();
<add> assertThat(context.hasGeneratedType("com.acme")).isFalse();
<add> context.getMainGeneratedType();
<add> assertThat(context.hasGeneratedType("com.acme")).isTrue();
<add> }
<add>
<add> @Test
<add> void getGeneratedTypeRegisterInstance() {
<add> DefaultGeneratedTypeContext context = createComAcmeContext();
<add> assertThat(context.hasGeneratedType("com.example")).isFalse();
<add> GeneratedType generatedType = context.getGeneratedType("com.example");
<add> assertThat(generatedType).isNotNull();
<add> assertThat(generatedType.getClassName().simpleName()).isEqualTo("Main");
<add> assertThat(context.hasGeneratedType("com.example")).isTrue();
<add> }
<add>
<add> @Test
<add> void getGeneratedTypeReuseInstance() {
<add> DefaultGeneratedTypeContext context = createComAcmeContext();
<add> GeneratedType generatedType = context.getGeneratedType("com.example");
<add> assertThat(generatedType.getClassName().packageName()).isEqualTo("com.example");
<add> assertThat(context.getGeneratedType("com.example")).isSameAs(generatedType);
<add> }
<add>
<add> @Test
<add> void toJavaFilesWithNoTypeIsEmpty() {
<add> DefaultGeneratedTypeContext writerContext = createComAcmeContext();
<add> assertThat(writerContext.toJavaFiles()).hasSize(0);
<add> }
<add>
<add> @Test
<add> void toJavaFilesWithDefaultTypeIsAddedLazily() {
<add> DefaultGeneratedTypeContext writerContext = createComAcmeContext();
<add> writerContext.getMainGeneratedType();
<add> assertThat(writerContext.toJavaFiles()).hasSize(1);
<add> }
<add>
<add> @Test
<add> void toJavaFilesWithDefaultTypeAndAdditionaTypes() {
<add> DefaultGeneratedTypeContext writerContext = createComAcmeContext();
<add> writerContext.getGeneratedType("com.example");
<add> writerContext.getGeneratedType("com.another");
<add> writerContext.getGeneratedType("com.another.another");
<add> assertThat(writerContext.toJavaFiles()).hasSize(3);
<add> }
<add>
<add> private DefaultGeneratedTypeContext createComAcmeContext() {
<add> return new DefaultGeneratedTypeContext("com.acme", packageName ->
<add> GeneratedType.of(ClassName.get(packageName, "Main"), type -> type.addModifiers(Modifier.PUBLIC)));
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/generator/GeneratedTypeTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generator;
<add>
<add>import java.io.IOException;
<add>import java.io.StringWriter;
<add>
<add>import javax.lang.model.element.Modifier;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.javapoet.ClassName;
<add>import org.springframework.javapoet.CodeBlock;
<add>import org.springframework.javapoet.FieldSpec;
<add>import org.springframework.javapoet.MethodSpec;
<add>import org.springframework.javapoet.TypeName;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>
<add>/**
<add> * Tests for {@link GeneratedType}.
<add> *
<add> * @author Stephane Nicoll
<add> */
<add>class GeneratedTypeTests {
<add>
<add> private static final ClassName TEST_CLASS_NAME = ClassName.get("com.acme", "Test");
<add>
<add> @Test
<add> void className() {
<add> GeneratedType generatedType = new GeneratedType(TEST_CLASS_NAME,
<add> type -> type.addModifiers(Modifier.STATIC));
<add> assertThat(generatedType.getClassName()).isEqualTo(TEST_CLASS_NAME);
<add> assertThat(generateCode(generatedType)).contains("static class Test {");
<add> }
<add>
<add> @Test
<add> void createWithCustomField() {
<add> GeneratedType generatedType = new GeneratedType(TEST_CLASS_NAME,
<add> type -> type.addField(FieldSpec.builder(TypeName.BOOLEAN, "enabled").build()));
<add> assertThat(generateCode(generatedType)).contains("boolean enabled;");
<add> }
<add>
<add> @Test
<add> void customizeType() {
<add> GeneratedType generatedType = createTestGeneratedType();
<add> generatedType.customizeType(type -> type.addJavadoc("Test javadoc."))
<add> .customizeType(type -> type.addJavadoc(" Another test javadoc"));
<add> assertThat(generateCode(generatedType)).containsSequence(
<add> "/**\n",
<add> " * Test javadoc. Another test javadoc\n",
<add> " */");
<add> }
<add>
<add> @Test
<add> void addMethod() {
<add> GeneratedType generatedType = createTestGeneratedType();
<add> generatedType.addMethod(MethodSpec.methodBuilder("test").returns(Integer.class)
<add> .addCode(CodeBlock.of("return 42;")));
<add> assertThat(generateCode(generatedType)).containsSequence(
<add> "\tInteger test() {\n",
<add> "\t\treturn 42;\n",
<add> "\t}");
<add> }
<add>
<add> @Test
<add> void addMultipleMethods() {
<add> GeneratedType generatedType = createTestGeneratedType();
<add> generatedType.addMethod(MethodSpec.methodBuilder("first"));
<add> generatedType.addMethod(MethodSpec.methodBuilder("second"));
<add> assertThat(generateCode(generatedType))
<add> .containsSequence("\tvoid first() {\n", "\t}")
<add> .containsSequence("\tvoid second() {\n", "\t}");
<add> }
<add>
<add> @Test
<add> void addSimilarMethodGenerateUniqueNames() {
<add> GeneratedType generatedType = createTestGeneratedType();
<add> MethodSpec firstMethod = generatedType.addMethod(MethodSpec.methodBuilder("test"));
<add> MethodSpec secondMethod = generatedType.addMethod(MethodSpec.methodBuilder("test"));
<add> MethodSpec thirdMethod = generatedType.addMethod(MethodSpec.methodBuilder("test"));
<add> assertThat(firstMethod.name).isEqualTo("test");
<add> assertThat(secondMethod.name).isEqualTo("test_");
<add> assertThat(thirdMethod.name).isEqualTo("test__");
<add> assertThat(generateCode(generatedType))
<add> .containsSequence("\tvoid test() {\n", "\t}")
<add> .containsSequence("\tvoid test_() {\n", "\t}")
<add> .containsSequence("\tvoid test__() {\n", "\t}");
<add> }
<add>
<add> @Test
<add> void addMethodWithSameNameAndDifferentArgumentsDoesNotChangeName() {
<add> GeneratedType generatedType = createTestGeneratedType();
<add> generatedType.addMethod(MethodSpec.methodBuilder("test"));
<add> MethodSpec secondMethod = generatedType.addMethod(MethodSpec.methodBuilder("test")
<add> .addParameter(String.class, "param"));
<add> assertThat(secondMethod.name).isEqualTo("test");
<add> }
<add>
<add> private GeneratedType createTestGeneratedType() {
<add> return GeneratedType.of(TEST_CLASS_NAME);
<add> }
<add>
<add> private String generateCode(GeneratedType generatedType) {
<add> try {
<add> StringWriter out = new StringWriter();
<add> generatedType.toJavaFile().writeTo(out);
<add> return out.toString();
<add> }
<add> catch (IOException ex) {
<add> throw new IllegalStateException(ex);
<add> }
<add> }
<add>
<add>} | 5 |
Ruby | Ruby | fix undefined variable ruby_version | 4f5643a67681f399dbabaeefb758a9c871ba513f | <ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb
<ide> def check_for_other_package_managers
<ide> end
<ide>
<ide> def check_ruby_version
<del> return if RUBY_VERSION[/\d\.\d/] == "2.0"
<add> ruby_version = "2.0"
<add> return if RUBY_VERSION[/\d\.\d/] == ruby_version
<ide>
<ide> <<-EOS.undent
<ide> Ruby version #{RUBY_VERSION} is unsupported on #{MacOS.version}. Homebrew
<ide><path>Library/Homebrew/test/os/mac/diagnostic_spec.rb
<ide> expect(subject.check_homebrew_prefix)
<ide> .to match("Your Homebrew's prefix is not /usr/local.")
<ide> end
<add>
<add> specify "#check_ruby_version" do
<add> expected_string = <<-EXPECTED
<add>Ruby version 2.3.3p222 is unsupported on 10.13. Homebrew
<add>is developed and tested on Ruby 2.0, and may not work correctly
<add>on other Rubies. Patches are accepted as long as they don't cause breakage
<add>on supported Rubies.
<add> EXPECTED
<add> allow(MacOS).to receive(:version).and_return(OS::Mac::Version.new("10.13"))
<add> stub_const("RUBY_VERSION", "2.3.3p222")
<add>
<add> expect(subject.check_ruby_version)
<add> .to match(expected_string)
<add> end
<ide> end | 2 |
Python | Python | fix merge conflict for jinja templating | 02bfeb68e5cf1a4c4c6a5b2fd43135514a3a0835 | <ide><path>airflow/www/utils.py
<ide> def wrapper(*args, **kwargs):
<ide> </table>
<ide> ''').render(**locals())
<ide> utils.send_email(task.email, subject, content)
<del>
<ide> return f(*args, **kwargs)
<ide> return wrapper
<ide> | 1 |
Python | Python | fix outdated docstring | 905335bd9ca4a7126a612b94ac43401b6f03bff7 | <ide><path>numpy/lib/shape_base.py
<ide> def _replace_zero_by_x_arrays(sub_arys):
<ide>
<ide> def array_split(ary,indices_or_sections,axis = 0):
<ide> """
<del> Split an array into multiple sub-arrays of equal or near-equal size.
<add> Split an array into multiple sub-arrays.
<ide>
<ide> Please refer to the ``split`` documentation. The only difference
<ide> between these functions is that ``array_split`` allows
<ide> def array_split(ary,indices_or_sections,axis = 0):
<ide> st = div_points[i]; end = div_points[i+1]
<ide> sub_arys.append(_nx.swapaxes(sary[st:end],axis,0))
<ide>
<del> # there is a wierd issue with array slicing that allows
<del> # 0x10 arrays and other such things. The following cluge is needed
<add> # there is a weird issue with array slicing that allows
<add> # 0x10 arrays and other such things. The following kludge is needed
<ide> # to get around this issue.
<ide> sub_arys = _replace_zero_by_x_arrays(sub_arys)
<del> # end cluge.
<add> # end kludge.
<ide>
<ide> return sub_arys
<ide>
<ide> def split(ary,indices_or_sections,axis=0):
<ide> """
<del> Split an array into multiple sub-arrays of equal size.
<add> Split an array into multiple sub-arrays.
<ide>
<ide> Parameters
<ide> ---------- | 1 |
Javascript | Javascript | fix scriptloader args | e6a17214e2924d9f58ef05939e78cd588f28cb06 | <ide><path>client/src/components/Donation/PayPalButtonScriptLoader.js
<ide> export class PayPalButtonScriptLoader extends Component {
<ide> if (subscription) queries += '&vault=true&intent=subscription';
<ide>
<ide> scriptLoader(
<del> 'paypal-sdk',
<ide> 'paypal-sdk',
<ide> true,
<ide> `https://www.paypal.com/sdk/js${queries}`, | 1 |
Javascript | Javascript | extract getcachedirectory helper | f989981d194743dc860ba9009a17a1ecee23c081 | <ide><path>static/index.js
<ide> window.onload = function() {
<ide> // Ensure ATOM_HOME is always set before anything else is required
<ide> setupAtomHome();
<ide>
<del> var cacheDir = path.join(process.env.ATOM_HOME, 'compile-cache');
<del> // Use separate compile cache when sudo'ing as root to avoid permission issues
<del> if (process.env.USER === 'root' && process.env.SUDO_USER && process.env.SUDO_USER !== process.env.USER) {
<del> cacheDir = path.join(cacheDir, 'root');
<del> }
<del>
<ide> // Normalize to make sure drive letter case is consistent on Windows
<ide> process.resourcesPath = path.normalize(process.resourcesPath);
<ide>
<ide> window.onload = function() {
<ide> var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep);
<ide>
<ide> if (loadSettings.profileStartup) {
<del> profileStartup(cacheDir, loadSettings, Date.now() - startTime);
<add> profileStartup(loadSettings, Date.now() - startTime);
<ide> } else {
<del> setupWindow(cacheDir, loadSettings);
<add> setupWindow(loadSettings);
<ide> setLoadTime(Date.now() - startTime);
<ide> }
<ide> } catch (error) {
<ide> handleSetupError(error);
<ide> }
<ide> }
<ide>
<add>var getCacheDirectory = function() {
<add> var cacheDir = path.join(process.env.ATOM_HOME, 'compile-cache');
<add> // Use separate compile cache when sudo'ing as root to avoid permission issues
<add> if (process.env.USER === 'root' && process.env.SUDO_USER && process.env.SUDO_USER !== process.env.USER) {
<add> cacheDir = path.join(cacheDir, 'root');
<add> }
<add> return cacheDir;
<add>}
<add>
<ide> var setLoadTime = function(loadTime) {
<ide> if (global.atom) {
<ide> global.atom.loadTime = loadTime;
<ide> var handleSetupError = function(error) {
<ide> console.error(error.stack || error);
<ide> }
<ide>
<del>var setupWindow = function(cacheDir, loadSettings) {
<add>var setupWindow = function(loadSettings) {
<add> var cacheDir = getCacheDirectory();
<add>
<ide> setupCoffeeCache(cacheDir);
<ide>
<ide> ModuleCache = require('../src/module-cache');
<ide> var setupSourceMapCache = function(cacheDir) {
<ide>
<ide> var setupVmCompatibility = function() {
<ide> var vm = require('vm');
<del> if (!vm.Script.createContext)
<add> if (!vm.Script.createContext) {
<ide> vm.Script.createContext = vm.createContext;
<add> }
<ide> }
<ide>
<del>var profileStartup = function(cacheDir, loadSettings, initialTime) {
<add>var profileStartup = function(loadSettings, initialTime) {
<ide> var profile = function() {
<ide> console.profile('startup');
<ide> try {
<ide> var startTime = Date.now()
<del> setupWindow(cacheDir, loadSettings);
<add> setupWindow(loadSettings);
<ide> setLoadTime(Date.now() - startTime + initialTime);
<ide> } catch (error) {
<ide> handleSetupError(error); | 1 |
Mixed | Javascript | add compose operator | ddb3ae7c308a997325043f175826d324f5fb6352 | <ide><path>doc/api/stream.md
<ide> option. In the code example above, data will be in a single chunk if the file
<ide> has less then 64 KiB of data because no `highWaterMark` option is provided to
<ide> [`fs.createReadStream()`][].
<ide>
<add>##### `readable.compose(stream[, options])`
<add>
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>> Stability: 1 - Experimental
<add>
<add>* `stream` {Stream|Iterable|AsyncIterable|Function}
<add>* `options` {Object}
<add> * `signal` {AbortSignal} allows destroying the stream if the signal is
<add> aborted.
<add>* Returns: {Duplex} a stream composed with the stream `stream`.
<add>
<add>```mjs
<add>import { Readable } from 'node:stream';
<add>
<add>async function* splitToWords(source) {
<add> for await (const chunk of source) {
<add> const words = String(chunk).split(' ');
<add>
<add> for (const word of words) {
<add> yield word;
<add> }
<add> }
<add>}
<add>
<add>const wordsStream = Readable.from(['this is', 'compose as operator']).compose(splitToWords);
<add>const words = await wordsStream.toArray();
<add>
<add>console.log(words); // prints ['this', 'is', 'compose', 'as', 'operator']
<add>```
<add>
<add>See [`stream.compose`][] for more information.
<add>
<ide> ##### `readable.iterator([options])`
<ide>
<ide> <!-- YAML
<ide> await finished(compose(s1, s2, s3));
<ide> console.log(res); // prints 'HELLOWORLD'
<ide> ```
<ide>
<add>See [`readable.compose(stream)`][] for `stream.compose` as operator.
<add>
<ide> ### `stream.Readable.from(iterable[, options])`
<ide>
<ide> <!-- YAML
<ide> contain multi-byte characters.
<ide> [`process.stdin`]: process.md#processstdin
<ide> [`process.stdout`]: process.md#processstdout
<ide> [`readable._read()`]: #readable_readsize
<add>[`readable.compose(stream)`]: #readablecomposestream-options
<ide> [`readable.map`]: #readablemapfn-options
<ide> [`readable.push('')`]: #readablepush
<ide> [`readable.setEncoding()`]: #readablesetencodingencoding
<ide> [`stream.Readable.from()`]: #streamreadablefromiterable-options
<ide> [`stream.addAbortSignal()`]: #streamaddabortsignalsignal-stream
<add>[`stream.compose`]: #streamcomposestreams
<ide> [`stream.cork()`]: #writablecork
<ide> [`stream.finished()`]: #streamfinishedstream-options-callback
<ide> [`stream.pipe()`]: #readablepipedestination-options
<ide><path>lib/internal/streams/operators.js
<ide> const { AbortController } = require('internal/abort_controller');
<ide>
<ide> const {
<ide> codes: {
<add> ERR_INVALID_ARG_VALUE,
<ide> ERR_INVALID_ARG_TYPE,
<ide> ERR_MISSING_ARGS,
<ide> ERR_OUT_OF_RANGE,
<ide> const {
<ide> } = require('internal/validators');
<ide> const { kWeakHandler } = require('internal/event_target');
<ide> const { finished } = require('internal/streams/end-of-stream');
<add>const staticCompose = require('internal/streams/compose');
<add>const {
<add> addAbortSignalNoValidate,
<add>} = require('internal/streams/add-abort-signal');
<add>const { isWritable, isNodeStream } = require('internal/streams/utils');
<ide>
<ide> const {
<ide> ArrayPrototypePush,
<ide> const {
<ide> const kEmpty = Symbol('kEmpty');
<ide> const kEof = Symbol('kEof');
<ide>
<add>function compose(stream, options) {
<add> if (options != null) {
<add> validateObject(options, 'options');
<add> }
<add> if (options?.signal != null) {
<add> validateAbortSignal(options.signal, 'options.signal');
<add> }
<add>
<add> if (isNodeStream(stream) && !isWritable(stream)) {
<add> throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable');
<add> }
<add>
<add> const composedStream = staticCompose(this, stream);
<add>
<add> if (options?.signal) {
<add> // Not validating as we already validated before
<add> addAbortSignalNoValidate(
<add> options.signal,
<add> composedStream
<add> );
<add> }
<add>
<add> return composedStream;
<add>}
<add>
<ide> function map(fn, options) {
<ide> if (typeof fn !== 'function') {
<ide> throw new ERR_INVALID_ARG_TYPE(
<ide> module.exports.streamReturningOperators = {
<ide> flatMap,
<ide> map,
<ide> take,
<add> compose,
<ide> };
<ide>
<ide> module.exports.promiseReturningOperators = {
<ide><path>test/parallel/test-stream-compose-operator.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const {
<add> Readable, Transform,
<add>} = require('stream');
<add>const assert = require('assert');
<add>
<add>{
<add> // with async generator
<add> const stream = Readable.from(['a', 'b', 'c', 'd']).compose(async function *(stream) {
<add> let str = '';
<add> for await (const chunk of stream) {
<add> str += chunk;
<add>
<add> if (str.length === 2) {
<add> yield str;
<add> str = '';
<add> }
<add> }
<add> });
<add> const result = ['ab', 'cd'];
<add> (async () => {
<add> for await (const item of stream) {
<add> assert.strictEqual(item, result.shift());
<add> }
<add> })().then(common.mustCall());
<add>}
<add>
<add>{
<add> // With Transformer
<add> const stream = Readable.from(['a', 'b', 'c', 'd']).compose(new Transform({
<add> objectMode: true,
<add> transform: common.mustCall((chunk, encoding, callback) => {
<add> callback(null, chunk);
<add> }, 4)
<add> }));
<add> const result = ['a', 'b', 'c', 'd'];
<add> (async () => {
<add> for await (const item of stream) {
<add> assert.strictEqual(item, result.shift());
<add> }
<add> })().then(common.mustCall());
<add>}
<add>
<add>{
<add> // Throwing an error during `compose` (before waiting for data)
<add> const stream = Readable.from([1, 2, 3, 4, 5]).compose(async function *(stream) { // eslint-disable-line require-yield
<add>
<add> throw new Error('boom');
<add> });
<add>
<add> assert.rejects(async () => {
<add> for await (const item of stream) {
<add> assert.fail('should not reach here, got ' + item);
<add> }
<add> }, /boom/).then(common.mustCall());
<add>}
<add>
<add>{
<add> // Throwing an error during `compose` (when waiting for data)
<add> const stream = Readable.from([1, 2, 3, 4, 5]).compose(async function *(stream) {
<add> for await (const chunk of stream) {
<add> if (chunk === 3) {
<add> throw new Error('boom');
<add> }
<add> yield chunk;
<add> }
<add> });
<add>
<add> assert.rejects(
<add> stream.toArray(),
<add> /boom/,
<add> ).then(common.mustCall());
<add>}
<add>
<add>{
<add> // Throwing an error during `compose` (after finishing all readable data)
<add> const stream = Readable.from([1, 2, 3, 4, 5]).compose(async function *(stream) { // eslint-disable-line require-yield
<add>
<add> // eslint-disable-next-line no-unused-vars,no-empty
<add> for await (const chunk of stream) {
<add> }
<add>
<add> throw new Error('boom');
<add> });
<add> assert.rejects(
<add> stream.toArray(),
<add> /boom/,
<add> ).then(common.mustCall());
<add>}
<add>
<add>{
<add> // AbortSignal
<add> const ac = new AbortController();
<add> const stream = Readable.from([1, 2, 3, 4, 5])
<add> .compose(async function *(source) {
<add> // Should not reach here
<add> for await (const chunk of source) {
<add> yield chunk;
<add> }
<add> }, { signal: ac.signal });
<add>
<add> ac.abort();
<add>
<add> assert.rejects(async () => {
<add> for await (const item of stream) {
<add> assert.fail('should not reach here, got ' + item);
<add> }
<add> }, {
<add> name: 'AbortError',
<add> }).then(common.mustCall());
<add>}
<add>
<add>{
<add> assert.throws(
<add> () => Readable.from(['a']).compose(Readable.from(['b'])),
<add> { code: 'ERR_INVALID_ARG_VALUE' }
<add> );
<add>}
<add>
<add>{
<add> assert.throws(
<add> () => Readable.from(['a']).compose(),
<add> { code: 'ERR_INVALID_ARG_TYPE' }
<add> );
<add>}
<ide><path>test/parallel/test-stream-compose.js
<ide> const assert = require('assert');
<ide> }
<ide>
<ide> {
<del> try {
<del> compose();
<del> } catch (err) {
<del> assert.strictEqual(err.code, 'ERR_MISSING_ARGS');
<del> }
<add> assert.throws(
<add> () => compose(),
<add> { code: 'ERR_MISSING_ARGS' }
<add> );
<ide> }
<ide>
<ide> {
<del> try {
<del> compose(new Writable(), new PassThrough());
<del> } catch (err) {
<del> assert.strictEqual(err.code, 'ERR_INVALID_ARG_VALUE');
<del> }
<add> assert.throws(
<add> () => compose(new Writable(), new PassThrough()),
<add> { code: 'ERR_INVALID_ARG_VALUE' }
<add> );
<ide> }
<ide>
<ide> {
<del> try {
<del> compose(new PassThrough(), new Readable({ read() {} }), new PassThrough());
<del> } catch (err) {
<del> assert.strictEqual(err.code, 'ERR_INVALID_ARG_VALUE');
<del> }
<add> assert.throws(
<add> () => compose(new PassThrough(), new Readable({ read() {} }), new PassThrough()),
<add> { code: 'ERR_INVALID_ARG_VALUE' }
<add> );
<ide> }
<ide>
<ide> { | 4 |
Python | Python | update tfds readconfig parameter | 55ec81945a43a487a512a372475c6b7758bd0486 | <ide><path>official/vision/image_classification/dataset_factory.py
<ide> def load_tfds(self) -> tf.data.Dataset:
<ide> decoders['image'] = tfds.decode.SkipDecoding()
<ide>
<ide> read_config = tfds.ReadConfig(
<del> interleave_parallel_reads=64,
<add> interleave_cycle_length=64,
<ide> interleave_block_length=1)
<ide>
<ide> dataset = builder.as_dataset( | 1 |
Python | Python | add ior and w to the curses interface | fdebbce53ed545064bafb86bec07bc0dabf132c3 | <ide><path>glances/plugins/glances_docker.py
<ide> def update(self):
<ide> container['cpu'] = self.get_docker_cpu(container['Id'], self.thread_list[container['Id']].stats)
<ide> container['memory'] = self.get_docker_memory(container['Id'], self.thread_list[container['Id']].stats)
<ide> container['network'] = self.get_docker_network(container['Id'], self.thread_list[container['Id']].stats)
<add> container['io'] = self.get_docker_io(container['Id'], self.thread_list[container['Id']].stats)
<ide>
<ide> elif self.input_method == 'snmp':
<ide> # Update stats using SNMP
<ide> def get_docker_network(self, container_id, all_stats):
<ide>
<ide> Input: id is the full container id
<ide> Output: a dict {'time_since_update': 3000, 'rx': 10, 'tx': 65}.
<add> with:
<add> time_since_update: number of seconds elapsed between the latest grab
<add> rx: Number of byte received
<add> tx: Number of byte transmited
<ide> """
<ide> # Init the returned dict
<ide> network_new = {}
<ide>
<ide> # Read the rx/tx stats (in bytes)
<ide> try:
<del> netiocounters = all_stats["network"]
<add> netcounters = all_stats["network"]
<ide> except KeyError as e:
<ide> # all_stats do not have NETWORK information
<ide> logger.debug("Can not grab NET usage for container {0} ({1})".format(container_id, e))
<ide> # No fallback available...
<ide> return network_new
<ide>
<ide> # Previous network interface stats are stored in the network_old variable
<del> if not hasattr(self, 'netiocounters_old'):
<add> if not hasattr(self, 'inetcounters_old'):
<ide> # First call, we init the network_old var
<del> self.netiocounters_old = {}
<add> self.netcounters_old = {}
<ide> try:
<del> self.netiocounters_old[container_id] = netiocounters
<add> self.netcounters_old[container_id] = netcounters
<ide> except (IOError, UnboundLocalError):
<ide> pass
<ide>
<del> if container_id not in self.netiocounters_old:
<add> if container_id not in self.netcounters_old:
<ide> try:
<del> self.netiocounters_old[container_id] = netiocounters
<add> self.netcounters_old[container_id] = netcounters
<ide> except (IOError, UnboundLocalError):
<ide> pass
<ide> else:
<ide> # By storing time data we enable Rx/s and Tx/s calculations in the
<ide> # XML/RPC API, which would otherwise be overly difficult work
<ide> # for users of the API
<ide> network_new['time_since_update'] = getTimeSinceLastUpdate('docker_net_{0}'.format(container_id))
<del> network_new['rx'] = netiocounters["rx_bytes"] - self.netiocounters_old[container_id]["rx_bytes"]
<del> network_new['tx'] = netiocounters["tx_bytes"] - self.netiocounters_old[container_id]["tx_bytes"]
<del> network_new['cumulative_rx'] = netiocounters["rx_bytes"]
<del> network_new['cumulative_tx'] = netiocounters["tx_bytes"]
<add> network_new['rx'] = netcounters["rx_bytes"] - self.netcounters_old[container_id]["rx_bytes"]
<add> network_new['tx'] = netcounters["tx_bytes"] - self.netcounters_old[container_id]["tx_bytes"]
<add> network_new['cumulative_rx'] = netcounters["rx_bytes"]
<add> network_new['cumulative_tx'] = netcounters["tx_bytes"]
<ide>
<ide> # Save stats to compute next bitrate
<del> self.netiocounters_old[container_id] = netiocounters
<add> self.netcounters_old[container_id] = netcounters
<ide>
<ide> # Return the stats
<ide> return network_new
<ide>
<add> def get_docker_io(self, container_id, all_stats):
<add> """Return the container IO usage using the Docker API (v1.0 or higher).
<add>
<add> Input: id is the full container id
<add> Output: a dict {'time_since_update': 3000, 'ior': 10, 'iow': 65}.
<add> with:
<add> time_since_update: number of seconds elapsed between the latest grab
<add> ior: Number of byte readed
<add> iow: Number of byte written
<add> """
<add> # Init the returned dict
<add> io_new = {}
<add>
<add> # Read the ior/iow stats (in bytes)
<add> try:
<add> iocounters = all_stats["blkio_stats"]
<add> except KeyError as e:
<add> # all_stats do not have io information
<add> logger.debug("Can not grab block IO usage for container {0} ({1})".format(container_id, e))
<add> # No fallback available...
<add> return io_new
<add>
<add> # Previous io interface stats are stored in the io_old variable
<add> if not hasattr(self, 'iocounters_old'):
<add> # First call, we init the io_old var
<add> self.iocounters_old = {}
<add> try:
<add> self.iocounters_old[container_id] = iocounters
<add> except (IOError, UnboundLocalError):
<add> pass
<add>
<add> if container_id not in self.iocounters_old:
<add> try:
<add> self.iocounters_old[container_id] = iocounters
<add> except (IOError, UnboundLocalError):
<add> pass
<add> else:
<add> # By storing time data we enable IoR/s and IoW/s calculations in the
<add> # XML/RPC API, which would otherwise be overly difficult work
<add> # for users of the API
<add> try:
<add> # Read IOR and IOW value in the structure list of dict
<add> ior = [i for i in iocounters['io_service_bytes_recursive'] if i['op'] == 'Read'][0]['value']
<add> iow = [i for i in iocounters['io_service_bytes_recursive'] if i['op'] == 'Write'][0]['value']
<add> ior_old = [i for i in self.iocounters_old[container_id]['io_service_bytes_recursive'] if i['op'] == 'Read'][0]['value']
<add> iow_old = [i for i in self.iocounters_old[container_id]['io_service_bytes_recursive'] if i['op'] == 'Write'][0]['value']
<add> except (IndexError, KeyError) as e:
<add> # all_stats do not have io information
<add> logger.debug("Can not grab block IO usage for container {0} ({1})".format(container_id, e))
<add> else:
<add> io_new['time_since_update'] = getTimeSinceLastUpdate('docker_io_{0}'.format(container_id))
<add> io_new['ior'] = ior - ior_old
<add> io_new['iow'] = iow - iow_old
<add> io_new['cumulative_ior'] = ior
<add> io_new['cumulative_iow'] = iow
<add>
<add> # Save stats to compute next bitrate
<add> self.iocounters_old[container_id] = iocounters
<add>
<add> # Return the stats
<add> return io_new
<add>
<ide> def get_user_ticks(self):
<ide> """Return the user ticks by reading the environment variable."""
<ide> return os.sysconf(os.sysconf_names['SC_CLK_TCK'])
<ide> def msg_curse(self, args=None):
<ide> ret.append(self.curse_new_line())
<ide> # Header
<ide> ret.append(self.curse_new_line())
<del> msg = '{0:>14}'.format('Id')
<del> ret.append(self.curse_add_line(msg))
<del> msg = ' {0:20}'.format('Name')
<add> # msg = '{0:>14}'.format('Id')
<add> # ret.append(self.curse_add_line(msg))
<add> # Get the maximum containers name (cutted to 20 char max)
<add> name_max_width = min(20, len(max(self.stats['containers'], key=lambda x: len(x['name']))['name']))
<add> msg = ' {0:{width}}'.format('Name', width=name_max_width)
<ide> ret.append(self.curse_add_line(msg))
<ide> msg = '{0:>26}'.format('Status')
<ide> ret.append(self.curse_add_line(msg))
<ide> msg = '{0:>6}'.format('CPU%')
<ide> ret.append(self.curse_add_line(msg))
<ide> msg = '{0:>7}'.format('MEM')
<ide> ret.append(self.curse_add_line(msg))
<add> msg = '{0:>6}'.format('IOR/s')
<add> ret.append(self.curse_add_line(msg))
<add> msg = '{0:>6}'.format('IOW/s')
<add> ret.append(self.curse_add_line(msg))
<ide> msg = '{0:>6}'.format('Rx/s')
<ide> ret.append(self.curse_add_line(msg))
<ide> msg = '{0:>6}'.format('Tx/s')
<ide> def msg_curse(self, args=None):
<ide> for container in self.stats['containers']:
<ide> ret.append(self.curse_new_line())
<ide> # Id
<del> msg = '{0:>14}'.format(container['Id'][0:12])
<del> ret.append(self.curse_add_line(msg))
<add> # msg = '{0:>14}'.format(container['Id'][0:12])
<add> # ret.append(self.curse_add_line(msg))
<ide> # Name
<del> name = container['Names'][0]
<del> if len(name) > 20:
<del> name = '_' + name[-19:]
<add> name = container['name']
<add> if len(name) > name_max_width:
<add> name = '_' + name[-name_max_width + 1:]
<ide> else:
<del> name = name[:20]
<del> msg = ' {0:20}'.format(name)
<add> name = name[:name_max_width]
<add> msg = ' {0:{width}}'.format(name, width=name_max_width)
<ide> ret.append(self.curse_add_line(msg))
<ide> # Status
<ide> status = self.container_alert(container['Status'])
<ide> def msg_curse(self, args=None):
<ide> except KeyError:
<ide> msg = '{0:>7}'.format('?')
<ide> ret.append(self.curse_add_line(msg))
<add> # IO R/W
<add> for r in ['ior', 'iow']:
<add> try:
<add> value = self.auto_unit(int(container['io'][r] // container['io']['time_since_update'] * 8)) + "b"
<add> msg = '{0:>6}'.format(value)
<add> except KeyError:
<add> msg = '{0:>6}'.format('?')
<add> ret.append(self.curse_add_line(msg))
<ide> # NET RX/TX
<ide> for r in ['rx', 'tx']:
<ide> try: | 1 |
Ruby | Ruby | replace http with curl | 64ebecf0c1e07f9d5354e3d7fefb4241369e74b3 | <ide><path>Library/Homebrew/utils/repology.rb
<ide> # frozen_string_literal: true
<ide>
<del>require "net/http"
<del>require "json"
<add>require "utils/curl"
<ide>
<ide> module RepologyParser
<ide> def call_api(url)
<ide> ohai "- Calling API #{url}" if Homebrew.args.verbose?
<ide> uri = URI(url)
<del> response = Net::HTTP.get(uri)
<del>
<del> ohai "Parsing response" if Homebrew.args.verbose?
<del> JSON.parse(response)
<add> curl(uri)
<ide> end
<ide>
<ide> def query_repology_api(last_package_in_response = "") | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.