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
PHP
PHP
remove dead code
31956c2abb51340dc91a8e8ba2a195e35fdc4948
<ide><path>lib/Cake/View/View.php <ide> protected function _getViewFileName($name = null) { <ide> } <ide> } <ide> } <del> $defaultPath = $paths[0]; <del> <del> if ($this->plugin) { <del> $pluginPaths = App::path('plugins'); <del> foreach ($paths as $path) { <del> if (strpos($path, $pluginPaths[0]) === 0) { <del> $defaultPath = $path; <del> break; <del> } <del> } <del> } <ide> throw new MissingViewException(array('file' => $name . $this->ext)); <ide> } <ide>
1
Javascript
Javascript
fix cypress login in development
e98257749fe1c7140032f7feaff884b16d17ff52
<ide><path>cypress/support/commands.js <ide> Cypress.Commands.add('login', () => { <ide> cy.visit('/'); <ide> cy.contains("Get started (it's free)").click(); <del> cy.url().should('eq', Cypress.config().baseUrl + '/learn/'); <add> cy.location().should(loc => { <add> // I'm not 100% sure why logins get redirected to /learn/ via 301 in <add> // development, but not in production, but they do. Hence to make it easier <add> // work on tests, we'll just allow for both. <add> expect(loc.pathname).to.match(/^\/learn\/?$/); <add> }); <ide> cy.contains('Welcome back'); <ide> }); <ide>
1
Text
Text
fix links to fonts.md
4f6d9d844072e6e1cbac49f483a231e1ab4969fb
<ide><path>docs/docs/axes/labelling.md <ide> The scale label configuration is nested under the scale configuration in the `sc <ide> | `display` | `boolean` | `false` | If true, display the axis title. <ide> | `align` | `string` | `'center'` | Alignment of the axis title. Possible options are `'start'`, `'center'` and `'end'` <ide> | `labelString` | `string` | `''` | The text for the title. (i.e. "# of People" or "Response Choices"). <del>| `font` | `Font` | `defaults.font` | See [Fonts](fonts.md) <add>| `font` | `Font` | `defaults.font` | See [Fonts](../general/fonts.md) <ide> | `padding` | `number`\|`object` | `4` | Padding to apply around scale labels. Only `top` and `bottom` are implemented. <ide> <ide> ## Creating Custom Tick Formats <ide><path>docs/docs/axes/radial/linear.md <ide> The following options are used to configure the point labels that are shown on t <ide> | ---- | ---- | ------- | ------- | ----------- <ide> | `display` | `boolean` | | `true` | if true, point labels are shown. <ide> | `callback` | `function` | | | Callback function to transform data labels to point labels. The default implementation simply returns the current string. <del>| `font` | `Font` | Yes | `defaults.font` | See [Fonts](fonts.md) <add>| `font` | `Font` | Yes | `defaults.font` | See [Fonts](../general/fonts.md) <ide> <ide> The scriptable context is the same as for the [Angle Line Options](#angle-line-options). <ide> <ide><path>docs/docs/axes/styling.md <ide> The tick configuration is nested under the scale configuration in the `ticks` ke <ide> | ---- | ---- | :-------------------------------: | ------- | ----------- <ide> | `callback` | `function` | | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats). <ide> | `display` | `boolean` | | `true` | If true, show tick labels. <del>| `font` | `Font` | Yes | `defaults.font` | See [Fonts](fonts.md) <add>| `font` | `Font` | Yes | `defaults.font` | See [Fonts](../general/fonts.md) <ide> | `major` | `object` | | `{}` | [Major ticks configuration](#major-tick-configuration). <ide> | `padding` | `number` | | `0` | Sets the offset of the tick labels from the axis <ide> | `reverse` | `boolean` | | `false` | Reverses order of tick labels. <ide><path>docs/docs/configuration/title.md <ide> The title configuration is passed into the `options.title` namespace. The global <ide> | `align` | `string` | `'center'` | Alignment of the title. [more...](#align) <ide> | `display` | `boolean` | `false` | Is the title shown? <ide> | `position` | `string` | `'top'` | Position of title. [more...](#position) <del>| `font` | `Font` | `defaults.font` | See [Fonts](fonts.md) <add>| `font` | `Font` | `defaults.font` | See [Fonts](../general/fonts.md) <ide> | `padding` | <code>number&#124;{top: number, bottom: number}</code> | `10` | Adds padding above and below the title text if a single number is specified. It is also possible to change top and bottom padding separately. <ide> | `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text. See [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height). <ide> | `text` | <code>string&#124;string[]</code> | `''` | Title text to display. If specified as an array, text is rendered on multiple lines. <ide><path>docs/docs/configuration/tooltip.md <ide> The tooltip configuration is passed into the `options.tooltips` namespace. The g <ide> | `itemSort` | `function` | | Sort tooltip items. [more...](#sort-callback) <ide> | `filter` | `function` | | Filter tooltip items. [more...](#filter-callback) <ide> | `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.8)'` | Background color of the tooltip. <del>| `titleFont` | `Font` | `{style: 'bold', color: '#fff'}` | See [Fonts](fonts.md). <add>| `titleFont` | `Font` | `{style: 'bold', color: '#fff'}` | See [Fonts](../general/fonts.md). <ide> | `titleAlign` | `string` | `'left'` | Horizontal alignment of the title text lines. [more...](#alignment) <ide> | `titleSpacing` | `number` | `2` | Spacing to add to top and bottom of each title line. <ide> | `titleMarginBottom` | `number` | `6` | Margin to add on bottom of title section. <del>| `bodyFont` | `Font` | `{color: '#fff'}` | See [Fonts](fonts.md). <add>| `bodyFont` | `Font` | `{color: '#fff'}` | See [Fonts](../general/fonts.md). <ide> | `bodyAlign` | `string` | `'left'` | Horizontal alignment of the body text lines. [more...](#alignment) <ide> | `bodySpacing` | `number` | `2` | Spacing to add to top and bottom of each tooltip item. <del>| `footerFont` | `Font` | `{style: 'bold', color: '#fff'}` | See [Fonts](fonts.md). <add>| `footerFont` | `Font` | `{style: 'bold', color: '#fff'}` | See [Fonts](../general/fonts.md). <ide> | `footerAlign` | `string` | `'left'` | Horizontal alignment of the footer text lines. [more...](#alignment) <ide> | `footerSpacing` | `number` | `2` | Spacing to add to top and bottom of each footer line. <ide> | `footerMarginTop` | `number` | `6` | Margin to add before drawing the footer.
5
Go
Go
modify context key
1377a2ddee3f3a35e242237d4e60c6a9d39fc552
<ide><path>api/server/httputils/httputils.go <ide> import ( <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <del>type contextKey string <del> <ide> // APIVersionKey is the client's requested API version. <del>const APIVersionKey contextKey = "api-version" <add>type APIVersionKey struct{} <ide> <ide> // APIFunc is an adapter to allow the use of ordinary functions as Docker API endpoints. <ide> // Any function that has the appropriate signature can be registered as an API endpoint (e.g. getVersion). <ide> func VersionFromContext(ctx context.Context) string { <ide> return "" <ide> } <ide> <del> if val := ctx.Value(APIVersionKey); val != nil { <add> if val := ctx.Value(APIVersionKey{}); val != nil { <ide> return val.(string) <ide> } <ide> <ide><path>api/server/middleware/version.go <ide> func (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http. <ide> if versions.GreaterThan(apiVersion, v.defaultVersion) { <ide> return versionUnsupportedError{version: apiVersion, maxVersion: v.defaultVersion} <ide> } <del> ctx = context.WithValue(ctx, httputils.APIVersionKey, apiVersion) <add> ctx = context.WithValue(ctx, httputils.APIVersionKey{}, apiVersion) <ide> return handler(ctx, w, r, vars) <ide> } <ide> <ide><path>api/server/server.go <ide> func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc { <ide> <ide> // use intermediate variable to prevent "should not use basic type <ide> // string as key in context.WithValue" golint errors <del> var ki interface{} = dockerversion.UAStringKey <del> ctx := context.WithValue(context.Background(), ki, r.Header.Get("User-Agent")) <add> ctx := context.WithValue(context.Background(), dockerversion.UAStringKey{}, r.Header.Get("User-Agent")) <ide> handlerFunc := s.handlerWithGlobalMiddlewares(handler) <ide> <ide> vars := mux.Vars(r) <ide><path>dockerversion/useragent.go <ide> import ( <ide> ) <ide> <ide> // UAStringKey is used as key type for user-agent string in net/context struct <del>const UAStringKey = "upstream-user-agent" <add>type UAStringKey struct{} <ide> <ide> // DockerUserAgent is the User-Agent the Docker client uses to identify itself. <ide> // In accordance with RFC 7231 (5.5.3) is of the form: <ide> func DockerUserAgent(ctx context.Context) string { <ide> func getUserAgentFromContext(ctx context.Context) string { <ide> var upstreamUA string <ide> if ctx != nil { <del> var ki interface{} = ctx.Value(UAStringKey) <add> var ki interface{} = ctx.Value(UAStringKey{}) <ide> if ki != nil { <del> upstreamUA = ctx.Value(UAStringKey).(string) <add> upstreamUA = ctx.Value(UAStringKey{}).(string) <ide> } <ide> } <ide> return upstreamUA
4
Text
Text
add regex for comma separated const declarations
bc42ad1f2763beb083f235da068ddf9a74f68b8c
<ide><path>curriculum/challenges/english/03-front-end-libraries/redux/use-const-for-action-types.md <ide> The `authReducer` function should handle multiple action types with a switch sta <ide> ```js <ide> const noWhiteSpace = __helpers.removeWhiteSpace(code); <ide> assert( <del> /constLOGIN=(['"`])LOGIN\1/.test(noWhiteSpace) && <del> /constLOGOUT=(['"`])LOGOUT\1/.test(noWhiteSpace) <add> (/constLOGIN=(['"`])LOGIN\1/.test(noWhiteSpace) && <add> /constLOGOUT=(['"`])LOGOUT\1/.test(noWhiteSpace)) || <add> /const(LOGIN|LOGOUT)=(['"`])\1\2,(?!\1)(LOGIN|LOGOUT)=(['"`])\3\4/.test(noWhiteSpace) <ide> ); <ide> ``` <ide>
1
Ruby
Ruby
use map! to avoid an extra object creation
3152bb06cc3f82d05674bea60c2668d824e3c7a6
<ide><path>activerecord/lib/active_record/core.rb <ide> def inspect <ide> <ide> # Returns a hash of the given methods with their names as keys and returned values as values. <ide> def slice(*methods) <del> Hash[methods.map { |method| [method, public_send(method)] }].with_indifferent_access <add> Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access <ide> end <ide> <ide> def set_transaction_state(state) # :nodoc:
1
Ruby
Ruby
fix regression from multiple mountpoint support
2bd60c844ce92047e03359f4dde4b19f49de92ea
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def define_generate_prefix(app, name) <ide> script_namer = ->(options) do <ide> prefix_options = options.slice(*_route.segment_keys) <ide> prefix_options[:relative_url_root] = "".freeze <add> <add> if options[:_recall] <add> prefix_options.reverse_merge!(options[:_recall].slice(*_route.segment_keys)) <add> end <add> <ide> # We must actually delete prefix segment keys to avoid passing them to next url_for. <ide> _route.segment_keys.each { |k| options.delete(k) } <ide> _routes.url_helpers.send("#{name}_path", prefix_options) <ide><path>actionpack/lib/action_dispatch/routing/routes_proxy.rb <ide> def method_missing(method, *args) <ide> def #{method}(*args) <ide> options = args.extract_options! <ide> options = url_options.merge((options || {}).symbolize_keys) <del> options.reverse_merge!(script_name: @script_namer.call(options)) if @script_namer <add> <add> if @script_namer <add> options[:script_name] = merge_script_names( <add> options[:script_name], <add> @script_namer.call(options) <add> ) <add> end <add> <ide> args << options <ide> @helpers.#{method}(*args) <ide> end <ide> def #{method}(*args) <ide> super <ide> end <ide> end <add> <add> # Keeps the part of the script name provided by the global <add> # context via ENV["SCRIPT_NAME"], which `mount` doesn't know <add> # about since it depends on the specific request, but use our <add> # script name resolver for the mount point dependent part. <add> def merge_script_names(previous_script_name, new_script_name) <add> return new_script_name unless previous_script_name <add> <add> resolved_parts = new_script_name.count("/") <add> previous_parts = previous_script_name.count("/") <add> context_parts = previous_parts - resolved_parts + 1 <add> <add> (previous_script_name.split("/").slice(0, context_parts).join("/")) + new_script_name <add> end <ide> end <ide> end <ide> end <ide><path>railties/test/railties/engine_test.rb <ide> def through_vegetables <ide> assert_equal "/vegetables/1/bukkits/posts", last_response.body <ide> end <ide> <add> test "route helpers resolve script name correctly when called with different script name from current one" do <add> @plugin.write "app/controllers/posts_controller.rb", <<-RUBY <add> class PostsController < ActionController::Base <add> def index <add> render plain: fruit_bukkits.posts_path(fruit_id: 2) <add> end <add> end <add> RUBY <add> <add> app_file "config/routes.rb", <<-RUBY <add> Rails.application.routes.draw do <add> resources :fruits do <add> mount Bukkits::Engine => "/bukkits" <add> end <add> end <add> RUBY <add> <add> @plugin.write "config/routes.rb", <<-RUBY <add> Bukkits::Engine.routes.draw do <add> resources :posts, only: :index <add> end <add> RUBY <add> <add> boot_rails <add> <add> get("/fruits/1/bukkits/posts") <add> assert_equal "/fruits/2/bukkits/posts", last_response.body <add> end <add> <ide> private <ide> def app <ide> Rails.application <ide><path>railties/test/railties/mounted_engine_test.rb <ide> class Engine < ::Rails::Engine <ide> @plugin.write "config/routes.rb", <<-RUBY <ide> Blog::Engine.routes.draw do <ide> resources :posts <add> get '/different_context', to: 'posts#different_context' <ide> get '/generate_application_route', to: 'posts#generate_application_route' <ide> get '/application_route_in_view', to: 'posts#application_route_in_view' <ide> get '/engine_polymorphic_path', to: 'posts#engine_polymorphic_path' <ide> def index <ide> render plain: blog.post_path(1) <ide> end <ide> <add> def different_context <add> render plain: blog.post_path(1, user: "ada") <add> end <add> <ide> def generate_application_route <ide> path = main_app.url_for(controller: "/main", <ide> action: "index", <ide> def app <ide> get "/john/blog/posts" <ide> assert_equal "/john/blog/posts/1", last_response.body <ide> <add> # test generating engine route from engine with a different context <add> get "/john/blog/different_context" <add> assert_equal "/ada/blog/posts/1", last_response.body <add> <ide> # test generating engine's route from engine with default_url_options <ide> get "/john/blog/posts", {}, "SCRIPT_NAME" => "/foo" <ide> assert_equal "/foo/john/blog/posts/1", last_response.body
4
Javascript
Javascript
fix distance of sphere center to plane
5806d75e8cbca6e5e5bdccc16bc2b5f3424367f7
<ide><path>src/math/Sphere.js <ide> Object.assign( Sphere.prototype, { <ide> return box.intersectsSphere( this ); <ide> <ide> }, <del> <add> <ide> intersectsPlane: function ( plane ) { <ide> <del> // We use the following equation to compute the signed distance from <del> // the center of the sphere to the plane. <del> // <del> // distance = q * n - d <del> // <del> // If this distance is greater than the radius of the sphere, <del> // then there is no intersection. <del> <del> return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; <add> return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; <ide> <ide> }, <ide> <add> <ide> clampPoint: function ( point, optionalTarget ) { <ide> <ide> var deltaLengthSq = this.center.distanceToSquared( point );
1
Javascript
Javascript
fix export with folders that contain dot
38ad8d870c6b358e0dda624e982eba7a9a00ddbe
<ide><path>packages/next/export/worker.js <ide> process.on( <ide> }) <ide> <ide> let htmlFilename = `${path}${sep}index.html` <del> if (extname(path) !== '') { <add> const pageExt = extname(page) <add> const pathExt = extname(path) <add> // Make sure page isn't a folder with a dot in the name e.g. `v1.2` <add> if (pageExt !== pathExt && pathExt !== '') { <ide> // If the path has an extension, use that as the filename instead <ide> htmlFilename = path <ide> } else if (path === '/') { <ide><path>test/integration/export/next.config.js <ide> module.exports = (phase) => { <ide> '/file-name.md': { page: '/dynamic', query: { text: 'this file has an extension' } }, <ide> '/query': { page: '/query', query: { a: 'blue' } } <ide> } <del> } <add> } // end exportPathMap <ide> } <ide> } <ide><path>test/integration/export/pages/v1.12/docs.js <add>export default function Docs (props) { <add> return ( <add> <div>Hello again 👋</div> <add> ) <add>} <ide><path>test/integration/export/pages/v1.12/index.js <add>export default function Index (props) { <add> return ( <add> <div>Hello 👋</div> <add> ) <add>} <ide><path>test/integration/export/test/index.test.js <ide> import { <ide> stopApp, <ide> killApp, <ide> findPort, <del> renderViaHTTP <add> renderViaHTTP, <add> File <ide> } from 'next-test-utils' <ide> <ide> import ssr from './ssr' <ide> const access = promisify(fs.access) <ide> const appDir = join(__dirname, '../') <ide> const context = {} <ide> const devContext = {} <add>const nextConfig = new File(join(appDir, 'next.config.js')) <ide> <ide> describe('Static Export', () => { <add> it('should export with folder that has dot in name', async () => { <add> const outdir = join(appDir, 'out') <add> nextConfig.replace(/exportPathMap: function (.|\n|\r\n)*end exportPathMap/gm, '// disabled exportPathMap') <add> <add> await nextBuild(appDir) <add> await nextExport(appDir, { outdir }) <add> <add> let doesExists = true <add> await access(join(outdir, 'v1.12/index.html')) <add> .then(() => { <add> doesExists = true <add> }) <add> <add> expect(doesExists).toBe(true) <add> nextConfig.restore() <add> }) <ide> it('should delete existing exported files', async () => { <ide> const outdir = join(appDir, 'out') <ide> const tempfile = join(outdir, 'temp.txt') <ide> describe('Static Export', () => { <ide> stopApp(context.server), <ide> killApp(devContext.server) <ide> ]) <add> nextConfig.restore() <ide> }) <ide> <ide> ssr(context)
5
PHP
PHP
avoid unneeded local var assignment
4fa66f56ea41178b912ad9cd6b6c18a6bcabccad
<ide><path>src/Http/Client/Response.php <ide> public function getCookie(string $name) <ide> return null; <ide> } <ide> <del> $cookie = $this->cookies->get($name); <del> <del> return $cookie->getValue(); <add> return $this->cookies->get($name)->getValue(); <ide> } <ide> <ide> /**
1
Ruby
Ruby
fix dependency names
ab00c0f719a5646060a9fbd15fbecb1b2a9eb16d
<ide><path>Library/Homebrew/compat/requirements.rb <ide> class CVSRequirement < Requirement <ide> class EmacsRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("EmacsRequirement", "'depends_on \"cvs\"'") <add> odeprecated("EmacsRequirement", "'depends_on \"emacs\"'") <ide> which "emacs" <ide> end <ide> end <ide> <ide> class FortranRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("FortranRequirement", "'depends_on \"cvs\"'") <add> odeprecated("FortranRequirement", "'depends_on \"gcc\"'") <ide> which "gfortran" <ide> end <ide> end <ide> <ide> class GitRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("GitRequirement", "'depends_on \"cvs\"'") <add> odeprecated("GitRequirement", "'depends_on \"git\"'") <ide> which "git" <ide> end <ide> end <ide> <ide> class GPG2Requirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("GPG2Requirement", "'depends_on \"cvs\"'") <add> odeprecated("GPG2Requirement", "'depends_on \"gnupg\"'") <ide> which "gpg" <ide> end <ide> end <ide> <ide> class MercurialRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("MercurialRequirement", "'depends_on \"cvs\"'") <add> odeprecated("MercurialRequirement", "'depends_on \"mercurial\"'") <ide> which "hg" <ide> end <ide> end <ide> <ide> class MPIRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("MPIRequirement", "'depends_on \"cvs\"'") <add> odeprecated("MPIRequirement", "'depends_on \"open-mpi\"'") <ide> which "mpicc" <ide> end <ide> end <ide> <ide> class MysqlRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("MysqlRequirement", "'depends_on \"cvs\"'") <add> odeprecated("MysqlRequirement", "'depends_on \"mysql\"'") <ide> which "mysql_config" <ide> end <ide> end <ide> <ide> class PerlRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("PerlRequirement", "'depends_on \"cvs\"'") <add> odeprecated("PerlRequirement", "'depends_on \"perl\"'") <ide> which "perl" <ide> end <ide> end <ide> <ide> class PostgresqlRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("PostgresqlRequirement", "'depends_on \"cvs\"'") <add> odeprecated("PostgresqlRequirement", "'depends_on \"postgresql\"'") <ide> which "pg_config" <ide> end <ide> end <ide> <ide> class PythonRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("PythonRequirement", "'depends_on \"cvs\"'") <add> odeprecated("PythonRequirement", "'depends_on \"python\"'") <ide> which "python" <ide> end <ide> end <ide> <ide> class Python3Requirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("Python3Requirement", "'depends_on \"cvs\"'") <add> odeprecated("Python3Requirement", "'depends_on \"python3\"'") <ide> which "python3" <ide> end <ide> end <ide> <ide> class RbenvRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("RbenvRequirement", "'depends_on \"cvs\"'") <add> odeprecated("RbenvRequirement", "'depends_on \"rbenv\"'") <ide> which "rbenv" <ide> end <ide> end <ide> <ide> class RubyRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("RubyRequirement", "'depends_on \"cvs\"'") <add> odeprecated("RubyRequirement", "'depends_on \"ruby\"'") <ide> which "ruby" <ide> end <ide> end <ide> <ide> class SubversionRequirement < Requirement <ide> fatal true <ide> satisfy do <del> odeprecated("SubversionRequirement", "'depends_on \"cvs\"'") <add> odeprecated("SubversionRequirement", "'depends_on \"subversion\"'") <ide> which "svn" <ide> end <ide> end <ide> class TeXRequirement < Requirement <ide> cask "mactex" <ide> download "https://www.tug.org/mactex/" <ide> satisfy do <del> odeprecated("TeXRequirement", "'depends_on \"cvs\"'") <add> odeprecated("TeXRequirement") <ide> which("tex") || which("latex") <ide> end <ide> end
1
PHP
PHP
apply fixes from styleci
bf2acca4e7f3db44ceb28483a0b43b9e66375eec
<ide><path>tests/Testing/Fluent/AssertTest.php <ide> public function testAssertWhereContainsFailsWithMissingNestedValue() <ide> $this->expectException(AssertionFailedError::class); <ide> $this->expectExceptionMessage('Property [id] does not contain [5].'); <ide> <del> $assert->whereContains('id', [1,2,3,4,5]); <add> $assert->whereContains('id', [1, 2, 3, 4, 5]); <ide> } <ide> <ide> public function testAssertWhereContainsFailsWhenDoesNotMatchType() <ide> { <ide> $assert = AssertableJson::fromArray([ <del> 'foo' => [1,2,3,4] <add> 'foo' => [1, 2, 3, 4], <ide> ]); <ide> <ide> $this->expectException(AssertionFailedError::class); <ide> public function testAssertWhereContainsWithNestedValue() <ide> ]); <ide> <ide> $assert->whereContains('id', 1); <del> $assert->whereContains('id', [1,2,3,4]); <del> $assert->whereContains('id', [4,3,2,1]); <add> $assert->whereContains('id', [1, 2, 3, 4]); <add> $assert->whereContains('id', [4, 3, 2, 1]); <ide> } <ide> <ide> public function testAssertWhereContainsWithMatchingType() <ide> { <ide> $assert = AssertableJson::fromArray([ <del> 'foo' => [1,2,3,4] <add> 'foo' => [1, 2, 3, 4], <ide> ]); <ide> <ide> $assert->whereContains('foo', 1); <ide> $assert->whereContains('foo', [1]); <ide> } <del> <add> <ide> public function testAssertWhereContainsWithNullValue() <ide> { <ide> $assert = AssertableJson::fromArray([ <ide> public function testAssertWhereContainsWithNullValue() <ide> public function testAssertWhereContainsWithOutOfOrderMatchingType() <ide> { <ide> $assert = AssertableJson::fromArray([ <del> 'foo' => [4,1,7,3] <add> 'foo' => [4, 1, 7, 3], <ide> ]); <ide> <del> $assert->whereContains('foo', [1,7,4,3]); <add> $assert->whereContains('foo', [1, 7, 4, 3]); <ide> } <ide> <ide> public function testAssertWhereContainsWithOutOfOrderNestedMatchingType() <ide> public function testAssertWhereContainsWithNullExpectation() <ide> <ide> $assert->whereContains('foo', null); <ide> } <add> <ide> public function testAssertNestedWhereMatchesValue() <ide> { <ide> $assert = AssertableJson::fromArray([
1
Go
Go
remove uncalled configuresysinit
2648655a4a0aaf41e02dec4064c5b6e68fa7b9fe
<ide><path>daemon/daemon_unix.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver" <del> "github.com/docker/docker/dockerversion" <ide> derr "github.com/docker/docker/errors" <ide> pblkiodev "github.com/docker/docker/pkg/blkiodev" <del> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/parsers/kernel" <ide> "github.com/docker/docker/pkg/sysinfo" <ide> "github.com/docker/docker/runconfig" <del> "github.com/docker/docker/utils" <ide> "github.com/docker/docker/volume" <ide> "github.com/docker/libnetwork" <ide> nwconfig "github.com/docker/libnetwork/config" <ide> func migrateIfDownlevel(driver graphdriver.Driver, root string) error { <ide> return migrateIfAufs(driver, root) <ide> } <ide> <del>func configureSysInit(config *Config, rootUID, rootGID int) (string, error) { <del> localCopy := filepath.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.Version)) <del> sysInitPath := utils.DockerInitPath(localCopy) <del> if sysInitPath == "" { <del> return "", fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See https://docs.docker.com/project/set-up-dev-env/ for official build instructions.") <del> } <del> <del> if sysInitPath != localCopy { <del> // When we find a suitable dockerinit binary (even if it's our local binary), we copy it into config.Root at localCopy for future use (so that the original can go away without that being a problem, for example during a package upgrade). <del> if err := idtools.MkdirAs(filepath.Dir(localCopy), 0700, rootUID, rootGID); err != nil && !os.IsExist(err) { <del> return "", err <del> } <del> if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil { <del> return "", err <del> } <del> if err := os.Chmod(localCopy, 0700); err != nil { <del> return "", err <del> } <del> sysInitPath = localCopy <del> } <del> return sysInitPath, nil <del>} <del> <ide> func isBridgeNetworkDisabled(config *Config) bool { <ide> return config.Bridge.Iface == disableNetworkBridge <ide> } <ide><path>daemon/daemon_windows.go <ide> package daemon <ide> <ide> import ( <ide> "fmt" <del> "os" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> func migrateIfDownlevel(driver graphdriver.Driver, root string) error { <ide> return nil <ide> } <ide> <del>func configureSysInit(config *Config, rootUID, rootGID int) (string, error) { <del> // TODO Windows. <del> return os.Getenv("TEMP"), nil <del>} <del> <ide> func isBridgeNetworkDisabled(config *Config) bool { <ide> return false <ide> }
2
Python
Python
add cumsum and cumprod ops to backend
31ecfb28c3202b4e551027bb1f2aef39a9eee936
<ide><path>keras/backend/tensorflow_backend.py <ide> def prod(x, axis=None, keepdims=False): <ide> return tf.reduce_prod(x, reduction_indices=axis, keep_dims=keepdims) <ide> <ide> <add>def cumsum(x, axis=0): <add> """Cumulative sum of the values in a tensor, alongside the specified axis. <add> <add> # Arguments <add> x: A tensor or variable. <add> axis: An integer, the axis to compute the sum. <add> <add> # Returns <add> A tensor of the cumulative sum of values of `x` along `axis`. <add> """ <add> axis = _normalize_axis(axis, ndim(x)) <add> return tf.cumsum(x, axis=axis) <add> <add> <add>def cumprod(x, axis=0): <add> """Cumulative product of the values in a tensor, alongside the specified axis. <add> <add> # Arguments <add> x: A tensor or variable. <add> axis: An integer, the axis to compute the product. <add> <add> # Returns <add> A tensor of the cumulative product of values of `x` along `axis`. <add> """ <add> axis = _normalize_axis(axis, ndim(x)) <add> return tf.cumprod(x, axis=axis) <add> <add> <ide> def var(x, axis=None, keepdims=False): <ide> """Variance of a tensor, alongside the specified axis. <ide> <ide><path>keras/backend/theano_backend.py <ide> def prod(x, axis=None, keepdims=False): <ide> return T.prod(x, axis=axis, keepdims=keepdims) <ide> <ide> <add>def cumsum(x, axis=0): <add> """Cumulative sum of the values in a tensor, alongside the specified axis. <add> <add> # Arguments <add> x: A tensor or variable. <add> axis: An integer, the axis to compute the sum. <add> <add> # Returns <add> A tensor of the cumulative sum of values of `x` along `axis`. <add> """ <add> return T.extra_ops.cumsum(x, axis=axis) <add> <add> <add>def cumprod(x, axis=0): <add> """Cumulative product of the values in a tensor, alongside the specified axis. <add> <add> # Arguments <add> x: A tensor or variable. <add> axis: An integer, the axis to compute the product. <add> <add> # Returns <add> A tensor of the cumulative product of values of `x` along `axis`. <add> """ <add> return T.extra_ops.cumprod(x, axis=axis) <add> <add> <ide> def mean(x, axis=None, keepdims=False): <ide> """Mean of a tensor, alongside the specified axis. <ide> """ <ide><path>tests/keras/backend/backend_test.py <ide> def test_elementwise_operations(self): <ide> check_single_tensor_operation('prod', (4, 2), axis=1, keepdims=True) <ide> check_single_tensor_operation('prod', (4, 2, 3), axis=[1, -1]) <ide> <add> check_single_tensor_operation('cumsum', (4, 2)) <add> check_single_tensor_operation('cumsum', (4, 2), axis=1) <add> <add> check_single_tensor_operation('cumprod', (4, 2)) <add> check_single_tensor_operation('cumprod', (4, 2), axis=1) <add> <ide> # does not work yet, wait for bool <-> int casting in TF (coming soon) <ide> # check_single_tensor_operation('any', (4, 2)) <ide> # check_single_tensor_operation('any', (4, 2), axis=1, keepdims=True)
3
Go
Go
add non-nil check before logging volume errors
b1570baadd76377aaeb7199c95ad6dc11b38f302
<ide><path>volume/store/store.go <ide> func lookupVolume(driverName, volumeName string) (volume.Volume, error) { <ide> if err != nil { <ide> err = errors.Cause(err) <ide> if _, ok := err.(net.Error); ok { <del> return nil, errors.Wrapf(err, "error while checking if volume %q exists in driver %q", v.Name(), v.DriverName()) <add> if v != nil { <add> volumeName = v.Name() <add> driverName = v.DriverName() <add> } <add> return nil, errors.Wrapf(err, "error while checking if volume %q exists in driver %q", volumeName, driverName) <ide> } <ide> <ide> // At this point, the error could be anything from the driver, such as "no such volume"
1
Text
Text
fix typo in readme
ba9dc748388618c64af42006bc92f2c1d1abde09
<ide><path>README.md <ide> us a report nonetheless. <ide> <ide> - [#5507](https://github.com/nodejs/node/pull/5507): _Fix a defect that makes <ide> the CacheBleed Attack possible_. Many, though not all, OpenSSL vulnerabilities <del> in the TLS/SSL protocols also effect Node.js. <add> in the TLS/SSL protocols also affect Node.js. <ide> <ide> - [CVE-2016-2216](https://nodejs.org/en/blog/vulnerability/february-2016-security-releases/): <ide> _Fix defects in HTTP header parsing for requests and responses that can allow
1
Python
Python
add more tests for pricing
0ef3c71e839cd79a6016e818754b343d1e83f245
<ide><path>test/test_pricing.py <ide> def test_invalid_module_pricing_cache(self): <ide> libcloud.pricing.invalidate_module_pricing_cache(driver_type='compute', <ide> driver_name='foo') <ide> self.assertFalse('foo' in libcloud.pricing.PRICING_DATA['compute']) <add> libcloud.pricing.invalidate_module_pricing_cache(driver_type='compute', <add> driver_name='foo1') <add> <add> def test_set_pricing(self): <add> self.assertFalse('foo' in libcloud.pricing.PRICING_DATA['compute']) <add> <add> libcloud.pricing.set_pricing(driver_type='compute', driver_name='foo', <add> pricing={'foo': 1}) <add> self.assertTrue('foo' in libcloud.pricing.PRICING_DATA['compute']) <add>
1
PHP
PHP
add docs for _host option
91b787e3dd19fc69eb19e77d32bf69d0a662d737
<ide><path>src/Routing/Route/Route.php <ide> class Route <ide> * <ide> * - `_ext` - Defines the extensions used for this route. <ide> * - `pass` - Copies the listed parameters into params['pass']. <add> * - `_host` - Define the host name pattern if you want this route to only match <add> * specific host names. You can use `.*` and to create wildcard subdomains/hosts <add> * e.g. `*.example.com` matches all subdomains on `example.com`. <ide> * <ide> * @param string $template Template string with parameter placeholders <ide> * @param array|string $defaults Defaults for the route.
1
Go
Go
remove use of docker/go-connections
0f0e3163b5278e7eb047313d22c645fbaee26884
<ide><path>daemon/info.go <ide> import ( <ide> "github.com/docker/docker/pkg/sysinfo" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/registry" <del> "github.com/docker/go-connections/sockets" <ide> metrics "github.com/docker/go-metrics" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) { <ide> ServerVersion: dockerversion.Version, <ide> ClusterStore: daemon.configStore.ClusterStore, <ide> ClusterAdvertise: daemon.configStore.ClusterAdvertise, <del> HTTPProxy: maskCredentials(sockets.GetProxyEnv("http_proxy")), <del> HTTPSProxy: maskCredentials(sockets.GetProxyEnv("https_proxy")), <del> NoProxy: sockets.GetProxyEnv("no_proxy"), <add> HTTPProxy: maskCredentials(getEnvAny("HTTP_PROXY", "http_proxy")), <add> HTTPSProxy: maskCredentials(getEnvAny("HTTPS_PROXY", "https_proxy")), <add> NoProxy: getEnvAny("NO_PROXY", "no_proxy"), <ide> LiveRestoreEnabled: daemon.configStore.LiveRestoreEnabled, <ide> Isolation: daemon.defaultIsolation, <ide> } <ide> func maskCredentials(rawURL string) string { <ide> maskedURL := parsedURL.String() <ide> return maskedURL <ide> } <add> <add>func getEnvAny(names ...string) string { <add> for _, n := range names { <add> if val := os.Getenv(n); val != "" { <add> return val <add> } <add> } <add> return "" <add>}
1
PHP
PHP
fix route list for excluded middleware
7ebd21193df520d78269d7abd740537a2fae889e
<ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php <ide> protected function displayRoutes(array $routes) <ide> */ <ide> protected function getMiddleware($route) <ide> { <del> return collect($route->gatherMiddleware())->map(function ($middleware) { <add> return collect($this->router->gatherRouteMiddleware($route))->map(function ($middleware) { <ide> return $middleware instanceof Closure ? 'Closure' : $middleware; <ide> })->implode(','); <ide> }
1
Javascript
Javascript
add unit test for |missingpdfexception|
27a80f3b888e9c04f2d28976ae7353c6dcaa99a5
<ide><path>test/unit/api_spec.js <ide> /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ <ide> /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ <ide> /* globals PDFJS, expect, it, describe, Promise, combineUrl, waitsFor, <del> isArray */ <add> isArray, MissingPDFException */ <ide> <ide> 'use strict'; <ide> <ide> describe('api', function() { <ide> expect(true).toEqual(true); <ide> }); <ide> }); <add> it('creates pdf doc from non-existent URL', function() { <add> var nonExistentUrl = combineUrl(window.location.href, <add> '../pdfs/non-existent.pdf'); <add> var promise = PDFJS.getDocument(nonExistentUrl); <add> waitsForPromiseRejected(promise, function(error) { <add> expect(error instanceof MissingPDFException).toEqual(true); <add> }); <add> }); <ide> }); <ide> }); <ide> describe('PDFDocument', function() {
1
Javascript
Javascript
remove accidental .only
a54d3217652a09a3a619d3491bebdaf73651c8db
<ide><path>src/renderers/dom/client/__tests__/ReactMount-test.js <ide> describe('ReactMount', function() { <ide> }); <ide> } <ide> <del> it.only('warns when using two copies of React before throwing', function() { <add> it('warns when using two copies of React before throwing', function() { <ide> require('mock-modules').dumpCache(); <ide> var RD1 = require('ReactDOM'); <ide> require('mock-modules').dumpCache();
1
Text
Text
fix wording and remove reverted change
d1318f7dc7045ad0fa23c7e2e5a31e653b4b24b4
<ide><path>CHANGELOG.md <ide> <ide> ## Bug Fixes <ide> <del>- **$compile:** render nested transclusion at the root of a template <del> ([6d1e7cdc](https://github.com/angular/angular.js/commit/6d1e7cdc51c074139639e870b66997fb0df4523f), <del> [#8914](https://github.com/angular/angular.js/issues/8914), [#8925](https://github.com/angular/angular.js/issues/8925)) <ide> - **$location:** <ide> - don't call toString on null values <ide> ([c3a58a9f](https://github.com/angular/angular.js/commit/c3a58a9f34919f121587540e03ecbd51b25198d4)) <ide> <ide> - **ngModelController,formController:** due to [6046e14b](https://github.com/angular/angular.js/commit/6046e14bd22491168116e61ffdf5fd3fed5f135c), <ide> <del>- `ctrl.$error` does no more contain entries for validators that were <add>- `ctrl.$error` no longer contains entries for validators that were <ide> successful. <ide> - `ctrl.$setValidity` now differentiates between `true`, `false`, <ide> `undefined` and `null`, instead of previously only truthy vs falsy.
1
Javascript
Javascript
support multi-element directive
e46100f7097d9a8f174bdb9e15d4c6098395c3f2
<ide><path>src/jqLite.js <ide> function JQLite(element) { <ide> div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work! <ide> div.removeChild(div.firstChild); // remove the superfluous div <ide> JQLiteAddNodes(this, div.childNodes); <del> this.remove(); // detach the elements from the temporary DOM div. <add> var fragment = jqLite(document.createDocumentFragment()); <add> fragment.append(this); // detach the elements from the temporary DOM div. <ide> } else { <ide> JQLiteAddNodes(this, element); <ide> } <ide> forEach({ <ide> } <ide> }, <ide> <del> text: extend((msie < 9) <del> ? function(element, value) { <del> if (element.nodeType == 1 /** Element */) { <del> if (isUndefined(value)) <del> return element.innerText; <del> element.innerText = value; <del> } else { <del> if (isUndefined(value)) <del> return element.nodeValue; <del> element.nodeValue = value; <del> } <add> text: (function() { <add> var NODE_TYPE_TEXT_PROPERTY = []; <add> if (msie < 9) { <add> NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/ <add> NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/ <add> } else { <add> NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/ <add> NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/ <add> } <add> getText.$dv = ''; <add> return getText; <add> <add> function getText(element, value) { <add> var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType] <add> if (isUndefined(value)) { <add> return textProp ? element[textProp] : ''; <ide> } <del> : function(element, value) { <del> if (isUndefined(value)) { <del> return element.textContent; <del> } <del> element.textContent = value; <del> }, {$dv:''}), <add> element[textProp] = value; <add> } <add> })(), <ide> <ide> val: function(element, value) { <ide> if (isUndefined(value)) { <ide> forEach({ <ide> return this; <ide> } else { <ide> // we are a read, so read the first child. <del> if (this.length) <del> return fn(this[0], arg1, arg2); <add> var value = fn.$dv; <add> // Only if we have $dv do we iterate over all, otherwise it is just the first element. <add> var jj = value == undefined ? Math.min(this.length, 1) : this.length; <add> for (var j = 0; j < jj; j++) { <add> var nodeValue = fn(this[j], arg1, arg2); <add> value = value ? value + nodeValue : nodeValue; <add> } <add> return value; <ide> } <ide> } else { <ide> // we are a write, so apply to all children <ide> forEach({ <ide> // return self for chaining <ide> return this; <ide> } <del> return fn.$dv; <ide> }; <ide> }); <ide> <ide><path>src/ng/animator.js <ide> var $AnimatorProvider = function() { <ide> } <ide> <ide> function insert(element, parent, after) { <del> if (after) { <del> after.after(element); <del> } else { <del> parent.append(element); <del> } <add> var afterNode = after && after[after.length - 1]; <add> var parentNode = parent && parent[0] || afterNode && afterNode.parentNode; <add> var afterNextSibling = afterNode && afterNode.nextSibling; <add> forEach(element, function(node) { <add> if (afterNextSibling) { <add> parentNode.insertBefore(node, afterNextSibling); <add> } else { <add> parentNode.appendChild(node); <add> } <add> }); <ide> } <ide> <ide> function remove(element) { <ide><path>src/ng/compile.js <ide> function $CompileProvider($provide) { <ide> // jquery always rewraps, whereas we need to preserve the original selector so that we can modify it. <ide> $compileNodes = jqLite($compileNodes); <ide> } <add> var tempParent = document.createDocumentFragment(); <ide> // We can not compile top level text elements since text nodes can be merged and we will <ide> // not be able to attach scope data to them, so we will wrap them in <span> <ide> forEach($compileNodes, function(node, index){ <ide> if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { <del> $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0]; <add> $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0]; <ide> } <ide> }); <ide> var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority); <ide> function $CompileProvider($provide) { <ide> attrs = new Attributes(); <ide> <ide> // we must always refer to nodeList[i] since the nodes can be replaced underneath us. <del> directives = collectDirectives(nodeList[i], [], attrs, maxPriority); <add> directives = collectDirectives(nodeList[i], [], attrs, i == 0 ? maxPriority : undefined); <ide> <ide> nodeLinkFn = (directives.length) <ide> ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) <ide> function $CompileProvider($provide) { <ide> // iterate over the attributes <ide> for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, <ide> j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { <add> var attrStartName; <add> var attrEndName; <add> var index; <add> <ide> attr = nAttrs[j]; <ide> if (attr.specified) { <ide> name = attr.name; <ide> function $CompileProvider($provide) { <ide> if (NG_ATTR_BINDING.test(ngAttrName)) { <ide> name = ngAttrName.substr(6).toLowerCase(); <ide> } <add> if ((index = ngAttrName.lastIndexOf('Start')) != -1 && index == ngAttrName.length - 5) { <add> attrStartName = name; <add> attrEndName = name.substr(0, name.length - 5) + 'end'; <add> name = name.substr(0, name.length - 6); <add> } <ide> nName = directiveNormalize(name.toLowerCase()); <ide> attrsMap[nName] = name; <ide> attrs[nName] = value = trim((msie && name == 'href') <ide> function $CompileProvider($provide) { <ide> attrs[nName] = true; // presence means true <ide> } <ide> addAttrInterpolateDirective(node, directives, value, nName); <del> addDirective(directives, nName, 'A', maxPriority); <add> addDirective(directives, nName, 'A', maxPriority, attrStartName, attrEndName); <ide> } <ide> } <ide> <ide> function $CompileProvider($provide) { <ide> return directives; <ide> } <ide> <add> /** <add> * Given a node with an directive-start it collects all of the siblings until it find directive-end. <add> * @param node <add> * @param attrStart <add> * @param attrEnd <add> * @returns {*} <add> */ <add> function groupScan(node, attrStart, attrEnd) { <add> var nodes = []; <add> var depth = 0; <add> if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { <add> var startNode = node; <add> do { <add> if (!node) { <add> throw ngError(51, "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd); <add> } <add> if (node.hasAttribute(attrStart)) depth++; <add> if (node.hasAttribute(attrEnd)) depth--; <add> nodes.push(node); <add> node = node.nextSibling; <add> } while (depth > 0); <add> } else { <add> nodes.push(node); <add> } <add> return jqLite(nodes); <add> } <add> <add> /** <add> * Wrapper for linking function which converts normal linking function into a grouped <add> * linking function. <add> * @param linkFn <add> * @param attrStart <add> * @param attrEnd <add> * @returns {Function} <add> */ <add> function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { <add> return function(scope, element, attrs, controllers) { <add> element = groupScan(element[0], attrStart, attrEnd); <add> return linkFn(scope, element, attrs, controllers); <add> } <add> } <ide> <ide> /** <ide> * Once the directives have been collected, their compile functions are executed. This method <ide> function $CompileProvider($provide) { <ide> // executes all directives on the current element <ide> for(var i = 0, ii = directives.length; i < ii; i++) { <ide> directive = directives[i]; <add> var attrStart = directive.$$start; <add> var attrEnd = directive.$$end; <add> <add> // collect multiblock sections <add> if (attrStart) { <add> $compileNode = groupScan(compileNode, attrStart, attrEnd) <add> } <ide> $template = undefined; <ide> <ide> if (terminalPriority > directive.priority) { <ide> function $CompileProvider($provide) { <ide> transcludeDirective = directive; <ide> terminalPriority = directive.priority; <ide> if (directiveValue == 'element') { <del> $template = jqLite(compileNode); <add> $template = groupScan(compileNode, attrStart, attrEnd) <ide> $compileNode = templateAttrs.$$element = <ide> jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); <ide> compileNode = $compileNode[0]; <del> replaceWith(jqCollection, jqLite($template[0]), compileNode); <add> replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode); <ide> childTranscludeFn = compile($template, transcludeFn, terminalPriority); <ide> } else { <ide> $template = jqLite(JQLiteClone(compileNode)).contents(); <ide> function $CompileProvider($provide) { <ide> try { <ide> linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); <ide> if (isFunction(linkFn)) { <del> addLinkFns(null, linkFn); <add> addLinkFns(null, linkFn, attrStart, attrEnd); <ide> } else if (linkFn) { <del> addLinkFns(linkFn.pre, linkFn.post); <add> addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); <ide> } <ide> } catch (e) { <ide> $exceptionHandler(e, startingTag($compileNode)); <ide> function $CompileProvider($provide) { <ide> <ide> //////////////////// <ide> <del> function addLinkFns(pre, post) { <add> function addLinkFns(pre, post, attrStart, attrEnd) { <ide> if (pre) { <add> if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); <ide> pre.require = directive.require; <ide> preLinkFns.push(pre); <ide> } <ide> if (post) { <add> if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); <ide> post.require = directive.require; <ide> postLinkFns.push(post); <ide> } <ide> function $CompileProvider($provide) { <ide> * * `M`: comment <ide> * @returns true if directive was added. <ide> */ <del> function addDirective(tDirectives, name, location, maxPriority) { <del> var match = false; <add> function addDirective(tDirectives, name, location, maxPriority, startAttrName, endAttrName) { <add> var match = null; <ide> if (hasDirectives.hasOwnProperty(name)) { <ide> for(var directive, directives = $injector.get(name + Suffix), <ide> i = 0, ii = directives.length; i<ii; i++) { <ide> try { <ide> directive = directives[i]; <ide> if ( (maxPriority === undefined || maxPriority > directive.priority) && <ide> directive.restrict.indexOf(location) != -1) { <add> if (startAttrName) { <add> directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); <add> } <ide> tDirectives.push(directive); <del> match = true; <add> match = directive; <ide> } <ide> } catch(e) { $exceptionHandler(e); } <ide> } <ide> function $CompileProvider($provide) { <ide> * <ide> * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes <ide> * in the root of the tree. <del> * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, <add> * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep the shell, <ide> * but replace its DOM node reference. <ide> * @param {Node} newNode The new DOM node. <ide> */ <del> function replaceWith($rootElement, $element, newNode) { <del> var oldNode = $element[0], <del> parent = oldNode.parentNode, <add> function replaceWith($rootElement, elementsToRemove, newNode) { <add> var firstElementToRemove = elementsToRemove[0], <add> removeCount = elementsToRemove.length, <add> parent = firstElementToRemove.parentNode, <ide> i, ii; <ide> <ide> if ($rootElement) { <ide> for(i = 0, ii = $rootElement.length; i < ii; i++) { <del> if ($rootElement[i] == oldNode) { <del> $rootElement[i] = newNode; <add> if ($rootElement[i] == firstElementToRemove) { <add> $rootElement[i++] = newNode; <add> for (var j = i, j2 = j + removeCount - 1, <add> jj = $rootElement.length; <add> j < jj; j++, j2++) { <add> if (j2 < jj) { <add> $rootElement[j] = $rootElement[j2]; <add> } else { <add> delete $rootElement[j]; <add> } <add> } <add> $rootElement.length -= removeCount - 1; <ide> break; <ide> } <ide> } <ide> } <ide> <ide> if (parent) { <del> parent.replaceChild(newNode, oldNode); <add> parent.replaceChild(newNode, firstElementToRemove); <add> } <add> var fragment = document.createDocumentFragment(); <add> fragment.appendChild(firstElementToRemove); <add> newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; <add> for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { <add> var element = elementsToRemove[k]; <add> jqLite(element).remove(); // must do this way to clean up expando <add> fragment.appendChild(element); <add> delete elementsToRemove[k]; <ide> } <ide> <del> newNode[jqLite.expando] = oldNode[jqLite.expando]; <del> $element[0] = newNode; <add> elementsToRemove[0] = newNode; <add> elementsToRemove.length = 1 <ide> } <ide> }]; <ide> } <ide><path>src/ng/directive/ngRepeat.js <ide> var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) { <ide> if (lastBlockMap.hasOwnProperty(key)) { <ide> block = lastBlockMap[key]; <ide> animate.leave(block.element); <del> block.element[0][NG_REMOVED] = true; <add> forEach(block.element, function(element) { element[NG_REMOVED] = true}); <ide> block.scope.$destroy(); <ide> } <ide> } <ide><path>test/jqLiteSpec.js <ide> describe('jqLite', function() { <ide> <ide> it('should allow construction with html', function() { <ide> var nodes = jqLite('<div>1</div><span>2</span>'); <add> expect(nodes[0].parentNode).toBeDefined(); <add> expect(nodes[0].parentNode.nodeType).toBe(11); /** Document Fragment **/; <add> expect(nodes[0].parentNode).toBe(nodes[1].parentNode); <ide> expect(nodes.length).toEqual(2); <ide> expect(nodes[0].innerHTML).toEqual('1'); <ide> expect(nodes[1].innerHTML).toEqual('2'); <ide> describe('jqLite', function() { <ide> <ide> <ide> it('should read/write value', function() { <del> var element = jqLite('<div>abc</div>'); <del> expect(element.length).toEqual(1); <del> expect(element[0].innerHTML).toEqual('abc'); <add> var element = jqLite('<div>ab</div><span>c</span>'); <add> expect(element.length).toEqual(2); <add> expect(element[0].innerHTML).toEqual('ab'); <add> expect(element[1].innerHTML).toEqual('c'); <ide> expect(element.text()).toEqual('abc'); <ide> expect(element.text('xyz') == element).toBeTruthy(); <del> expect(element.text()).toEqual('xyz'); <add> expect(element.text()).toEqual('xyzxyz'); <ide> }); <ide> }); <ide> <ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> expect(element.attr('test4')).toBe('Misko'); <ide> })); <ide> }); <add> <add> <add> describe('multi-element directive', function() { <add> it('should group on link function', inject(function($compile, $rootScope) { <add> $rootScope.show = false; <add> element = $compile( <add> '<div>' + <add> '<span ng-show-start="show"></span>' + <add> '<span ng-show-end></span>' + <add> '</div>')($rootScope); <add> $rootScope.$digest(); <add> var spans = element.find('span'); <add> expect(spans.eq(0).css('display')).toBe('none'); <add> expect(spans.eq(1).css('display')).toBe('none'); <add> })); <add> <add> <add> it('should group on compile function', inject(function($compile, $rootScope) { <add> $rootScope.show = false; <add> element = $compile( <add> '<div>' + <add> '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' + <add> '<span ng-repeat-end>{{i}}B;</span>' + <add> '</div>')($rootScope); <add> $rootScope.$digest(); <add> expect(element.text()).toEqual('1A1B;2A2B;'); <add> })); <add> <add> <add> it('should group on $root compile function', inject(function($compile, $rootScope) { <add> $rootScope.show = false; <add> element = $compile( <add> '<div></div>' + <add> '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' + <add> '<span ng-repeat-end>{{i}}B;</span>' + <add> '<div></div>')($rootScope); <add> $rootScope.$digest(); <add> element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. <add> expect(element.text()).toEqual('1A1B;2A2B;'); <add> })); <add> <add> <add> it('should group on nested groups', inject(function($compile, $rootScope) { <add> $rootScope.show = false; <add> element = $compile( <add> '<div></div>' + <add> '<div ng-repeat-start="i in [1,2]">{{i}}A</div>' + <add> '<span ng-bind-start="\'.\'"></span>' + <add> '<span ng-bind-end></span>' + <add> '<div ng-repeat-end>{{i}}B;</div>' + <add> '<div></div>')($rootScope); <add> $rootScope.$digest(); <add> element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. <add> expect(element.text()).toEqual('1A..1B;2A..2B;'); <add> })); <add> <add> <add> it('should group on nested groups', inject(function($compile, $rootScope) { <add> $rootScope.show = false; <add> element = $compile( <add> '<div></div>' + <add> '<div ng-repeat-start="i in [1,2]">{{i}}(</div>' + <add> '<span ng-repeat-start="j in [2,3]">{{j}}-</span>' + <add> '<span ng-repeat-end>{{j}}</span>' + <add> '<div ng-repeat-end>){{i}};</div>' + <add> '<div></div>')($rootScope); <add> $rootScope.$digest(); <add> element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. <add> expect(element.text()).toEqual('1(2-23-3)1;2(2-23-3)2;'); <add> })); <add> <add> <add> it('should throw error if unterminated', function () { <add> module(function($compileProvider) { <add> $compileProvider.directive('foo', function() { <add> return { <add> }; <add> }); <add> }); <add> inject(function($compile, $rootScope) { <add> expect(function() { <add> element = $compile( <add> '<div>' + <add> '<span foo-start></span>' + <add> '</div>'); <add> }).toThrow("[NgErr51] Unterminated attribute, found 'foo-start' but no matching 'foo-end' found."); <add> }); <add> }); <add> <add> <add> it('should throw error if unterminated', function () { <add> module(function($compileProvider) { <add> $compileProvider.directive('foo', function() { <add> return { <add> }; <add> }); <add> }); <add> inject(function($compile, $rootScope) { <add> expect(function() { <add> element = $compile( <add> '<div>' + <add> '<span foo-start><span foo-end></span></span>' + <add> '</div>'); <add> }).toThrow("[NgErr51] Unterminated attribute, found 'foo-start' but no matching 'foo-end' found."); <add> }); <add> }); <add> <add> <add> it('should support data- and x- prefix', inject(function($compile, $rootScope) { <add> $rootScope.show = false; <add> element = $compile( <add> '<div>' + <add> '<span data-ng-show-start="show"></span>' + <add> '<span data-ng-show-end></span>' + <add> '<span x-ng-show-start="show"></span>' + <add> '<span x-ng-show-end></span>' + <add> '</div>')($rootScope); <add> $rootScope.$digest(); <add> var spans = element.find('span'); <add> expect(spans.eq(0).css('display')).toBe('none'); <add> expect(spans.eq(1).css('display')).toBe('none'); <add> expect(spans.eq(2).css('display')).toBe('none'); <add> expect(spans.eq(3).css('display')).toBe('none'); <add> })); <add> }); <ide> });
6
Text
Text
add documentation for per-binding state pattern
6d6de56571290412e052420f6425e0adb2eed1b2
<ide><path>src/README.md <ide> void Initialize(Local<Object> target, <ide> NODE_MODULE_CONTEXT_AWARE_INTERNAL(cares_wrap, Initialize) <ide> ``` <ide> <add><a id="per-binding-state"> <add>#### Per-binding state <add> <add>Some internal bindings, such as the HTTP parser, maintain internal state that <add>only affects that particular binding. In that case, one common way to store <add>that state is through the use of `Environment::BindingScope`, which gives all <add>new functions created within it access to an object for storing such state. <add>That object is always a [`BaseObject`][]. <add> <add>```c++ <add>// In the HTTP parser source code file: <add>class BindingData : public BaseObject { <add> public: <add> BindingData(Environment* env, Local<Object> obj) : BaseObject(env, obj) {} <add> <add> std::vector<char> parser_buffer; <add> bool parser_buffer_in_use = false; <add> <add> // ... <add>}; <add> <add>// Available for binding functions, e.g. the HTTP Parser constructor: <add>static void New(const FunctionCallbackInfo<Value>& args) { <add> BindingData* binding_data = Unwrap<BindingData>(args.Data()); <add> new Parser(binding_data, args.This()); <add>} <add> <add>// ... because the initialization function told the Environment to use this <add>// BindingData class for all functions created by it: <add>void InitializeHttpParser(Local<Object> target, <add> Local<Value> unused, <add> Local<Context> context, <add> void* priv) { <add> Environment* env = Environment::GetCurrent(context); <add> Environment::BindingScope<BindingData> binding_scope(env); <add> if (!binding_scope) return; <add> BindingData* binding_data = binding_scope.data; <add> <add> // Created within the Environment::BindingScope <add> Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New); <add> ... <add>} <add>``` <add> <ide> <a id="exception-handling"></a> <ide> ### Exception handling <ide>
1
PHP
PHP
apply fixes from styleci
f5a52813ef32730937c8fd87ca8bb8bdb748ef92
<ide><path>src/Illuminate/Database/DatabaseServiceProvider.php <ide> use Faker\Generator as FakerGenerator; <ide> use Illuminate\Contracts\Queue\EntityResolver; <ide> use Illuminate\Database\Connectors\ConnectionFactory; <del>use Illuminate\Database\Eloquent\Factory as EloquentFactory; <ide> use Illuminate\Database\Eloquent\Model; <ide> use Illuminate\Database\Eloquent\QueueEntityResolver; <ide> use Illuminate\Support\ServiceProvider;
1
Ruby
Ruby
add explicit rendering to diskcontroller#update
31780364b78dc24c712db3d9dc13fa1294f02ba1
<ide><path>activestorage/app/controllers/active_storage/disk_controller.rb <ide> def update <ide> if token = decode_verified_token <ide> if acceptable_content?(token) <ide> named_disk_service(token[:service_name]).upload token[:key], request.body, checksum: token[:checksum] <add> head :no_content <ide> else <ide> head :unprocessable_entity <ide> end
1
Ruby
Ruby
fix rubocop warnings
d01993da82bcb106aeac349ed5e66a445a40d1d2
<ide><path>Library/Homebrew/dev-cmd/create.rb <ide> def create <ide> <ide> def __gets <ide> gots = $stdin.gets.chomp <del> if gots.empty? then nil else gots end <add> gots.empty? ? nil : gots <ide> end <ide> end <ide>
1
Text
Text
fix controller name in getting started
d861ef6210438e37a7cde563f11fb158a13f7a4d
<ide><path>guides/source/getting_started.md <ide> Associations](association_basics.html) guide. <ide> <ide> ### Adding a Route for Comments <ide> <del>As with the `welcome` controller, we will need to add a route so that Rails <add>As with the `articles` controller, we will need to add a route so that Rails <ide> knows where we would like to navigate to see `comments`. Open up the <ide> `config/routes.rb` file again, and edit it as follows: <ide>
1
Ruby
Ruby
expect error for uppercase formula
ca6fc4873e4cb396e9ff650a52853ccd2359ac47
<ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb <ide> class Foo < Formula <ide> end <ide> end <ide> <add> describe "#audit_formula_name" do <add> specify "no issue" do <add> fa = formula_auditor "foo", <<~RUBY, core_tap: true, strict: true <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> homepage "https://brew.sh" <add> end <add> RUBY <add> <add> fa.audit_formula_name <add> expect(fa.problems).to be_empty <add> end <add> <add> specify "uppercase formula name" do <add> fa = formula_auditor "Foo", <<~RUBY <add> class Foo < Formula <add> url "https://brew.sh/Foo-1.0.tgz" <add> homepage "https://brew.sh" <add> end <add> RUBY <add> <add> fa.audit_formula_name <add> expect(fa.problems.first[:message]).to match "must not contain uppercase letters" <add> end <add> end <add> <ide> describe "#check_service_command" do <ide> specify "Not installed" do <ide> fa = formula_auditor "foo", <<~RUBY
1
Javascript
Javascript
add navigate proptype
b1be0425a55f584f8e97ca37ce2c3dd85ba65150
<ide><path>client/src/components/Donation/DonateForm.js <ide> const propTypes = { <ide> handleProcessing: PropTypes.func, <ide> isDonating: PropTypes.bool, <ide> isSignedIn: PropTypes.bool, <add> navigate: PropTypes.func.isRequired, <ide> showLoading: PropTypes.bool.isRequired, <ide> stripe: PropTypes.shape({ <ide> createToken: PropTypes.func.isRequired,
1
Javascript
Javascript
specify controller of a route via controllername
1af8c0771a3ed3df1dfea428bdc132ac64bf5c79
<ide><path>packages/ember-routing/lib/system/route.js <ide> Ember.Route = Ember.Object.extend({ <ide> @method setup <ide> */ <ide> setup: function(context) { <del> var controller = this.controllerFor(this.routeName, context); <add> var controller = this.controllerFor(this.controllerName || this.routeName, context); <ide> <ide> // Assign the route's controller so that it can more easily be <ide> // referenced in event handlers <ide><path>packages/ember/tests/routing/basic_test.js <ide> test("The route controller is still set when overriding the setupController hook <ide> deepEqual(container.lookup('route:home').controller, container.lookup('controller:home'), "route controller is the home controller"); <ide> }); <ide> <add>test("The route controller can be specified via controllerName", function() { <add> Router.map(function() { <add> this.route("home", { path: "/" }); <add> }); <add> <add> App.HomeRoute = Ember.Route.extend({ <add> controllerName: 'myController' <add> }); <add> <add> container.register('controller:myController', Ember.Controller.extend()); <add> <add> bootApplication(); <add> <add> deepEqual(container.lookup('route:home').controller, container.lookup('controller:myController'), "route controller is set by controllerName"); <add>}); <add> <ide> test("The Homepage with a `setupController` hook modifying other controllers", function() { <ide> Router.map(function() { <ide> this.route("home", { path: "/" });
2
Javascript
Javascript
fix usage when we're given no options
46d59fdda10f65b5647e935c571e3696ecbe5578
<ide><path>src/git-repository-async.js <ide> export default class GitRepositoryAsync { <ide> <ide> this._refreshingCount = 0 <ide> <del> let {refreshOnWindowFocus} = options || true <add> options = options || {} <add> <add> let {refreshOnWindowFocus = true} = options <ide> if (refreshOnWindowFocus) { <ide> const onWindowFocus = () => this.refreshStatus() <ide> window.addEventListener('focus', onWindowFocus)
1
Python
Python
add extra data
1f6526cf52daa1364bbae5f4c286203b249a42b2
<ide><path>libcloud/compute/drivers/openstack.py <ide> def _to_routers(self, obj): <ide> return [self._to_router(router) for router in routers] <ide> <ide> def _to_router(self, obj): <add> extra={} <add> extra['external_gateway_info'] = obj['external_gateway_info'] <add> extra['routes'] = obj['routes'] <ide> return OpenStack_2_Router(id=obj['id'], <ide> name=obj['name'], <ide> status=obj['status'], <ide> driver=self, <del> extra={}) <add> extra=extra) <ide> <ide> def ex_list_routers(self): <ide> """ <ide><path>libcloud/test/compute/test_openstack.py <ide> def test_ex_list_routers(self): <ide> self.assertEqual(len(routers), 2) <ide> self.assertEqual(router.name, 'router2') <ide> self.assertEqual(router.status, 'ACTIVE') <add> self.assertEqual(router.extra['routes'], []) <ide> <ide> def test_ex_create_router(self): <ide> router = self.driver.ex_create_router('router1', admin_state_up = True)
2
Text
Text
add changelogs for crypto
d27c9834f32ceb55e434821d3f69316b34f851c5
<ide><path>doc/api/crypto.md <ide> Returns `this` for method chaining. <ide> ### cipher.update(data[, input_encoding][, output_encoding]) <ide> <!-- YAML <ide> added: v0.1.94 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default `input_encoding` changed from `binary` to `utf8`. <ide> --> <ide> <ide> Updates the cipher with `data`. If the `input_encoding` argument is given, <ide> than once will result in an error being thrown. <ide> ### decipher.setAAD(buffer) <ide> <!-- YAML <ide> added: v1.0.0 <add>changes: <add> - version: v7.2.0 <add> pr-url: https://github.com/nodejs/node/pull/9398 <add> description: This method now returns a reference to `decipher`. <ide> --> <ide> <ide> When using an authenticated encryption mode (only `GCM` is currently <ide> Returns `this` for method chaining. <ide> ### decipher.setAuthTag(buffer) <ide> <!-- YAML <ide> added: v1.0.0 <add>changes: <add> - version: v7.2.0 <add> pr-url: https://github.com/nodejs/node/pull/9398 <add> description: This method now returns a reference to `decipher`. <ide> --> <ide> <ide> When using an authenticated encryption mode (only `GCM` is currently <ide> Returns `this` for method chaining. <ide> ### decipher.update(data[, input_encoding][, output_encoding]) <ide> <!-- YAML <ide> added: v0.1.94 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default `input_encoding` changed from `binary` to `utf8`. <ide> --> <ide> <ide> Updates the decipher with `data`. If the `input_encoding` argument is given, <ide> assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); <ide> ### ecdh.computeSecret(other_public_key[, input_encoding][, output_encoding]) <ide> <!-- YAML <ide> added: v0.11.14 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default `input_encoding` changed from `binary` to `utf8`. <ide> --> <ide> <ide> Computes the shared secret using `other_public_key` as the other <ide> called. Multiple calls will cause an error to be thrown. <ide> ### hash.update(data[, input_encoding]) <ide> <!-- YAML <ide> added: v0.1.92 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default `input_encoding` changed from `binary` to `utf8`. <ide> --> <ide> <ide> Updates the hash content with the given `data`, the encoding of which <ide> called. Multiple calls to `hmac.digest()` will result in an error being thrown. <ide> ### hmac.update(data[, input_encoding]) <ide> <!-- YAML <ide> added: v0.1.94 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default `input_encoding` changed from `binary` to `utf8`. <ide> --> <ide> <ide> Updates the `Hmac` content with the given `data`, the encoding of which <ide> called. Multiple calls to `sign.sign()` will result in an error being thrown. <ide> ### sign.update(data[, input_encoding]) <ide> <!-- YAML <ide> added: v0.1.92 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default `input_encoding` changed from `binary` to `utf8`. <ide> --> <ide> <ide> Updates the `Sign` content with the given `data`, the encoding of which <ide> console.log(verify.verify(publicKey, signature)); <ide> ### verifier.update(data[, input_encoding]) <ide> <!-- YAML <ide> added: v0.1.92 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default `input_encoding` changed from `binary` to `utf8`. <ide> --> <ide> <ide> Updates the `Verify` content with the given `data`, the encoding of which <ide> The `key` is the raw key used by the `algorithm` and `iv` is an <ide> ### crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding]) <ide> <!-- YAML <ide> added: v0.11.12 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default for the encoding parameters changed <add> from `binary` to `utf8`. <ide> --> <ide> <ide> Creates a `DiffieHellman` key exchange object using the supplied `prime` and an <ide> console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] <ide> ### crypto.pbkdf2(password, salt, iterations, keylen, digest, callback) <ide> <!-- YAML <ide> added: v0.5.5 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/4047 <add> description: Calling this function without passing the `digest` parameter <add> is deprecated now and will emit a warning. <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default encoding for `password` if it is a string changed <add> from `binary` to `utf8`. <ide> --> <ide> <ide> Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) <ide> An array of supported digest functions can be retrieved using <ide> ### crypto.pbkdf2Sync(password, salt, iterations, keylen, digest) <ide> <!-- YAML <ide> added: v0.9.3 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/4047 <add> description: Calling this function without passing the `digest` parameter <add> is deprecated now and will emit a warning. <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5522 <add> description: The default encoding for `password` if it is a string changed <add> from `binary` to `utf8`. <ide> --> <ide> <ide> Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
1
Javascript
Javascript
improve property descriptors in als.bind
3ea94ec84510f5ecd08b75e6e10ef7c5f5df4fe8
<ide><path>lib/async_hooks.js <ide> class AsyncResource { <ide> const ret = this.runInAsyncScope.bind(this, fn); <ide> ObjectDefineProperties(ret, { <ide> 'length': { <del> enumerable: true, <add> configurable: true, <add> enumerable: false, <ide> value: fn.length, <add> writable: false, <ide> }, <ide> 'asyncResource': { <add> configurable: true, <ide> enumerable: true, <ide> value: this, <add> writable: true, <ide> } <ide> }); <ide> return ret;
1
Ruby
Ruby
remove psych hack for ruby 1.9
185d7cdb429764c50fb62035fa918b7ba0a71fae
<ide><path>railties/lib/rails/application.rb <ide> def helpers_paths #:nodoc: <ide> <ide> console do <ide> unless ::Kernel.private_method_defined?(:y) <del> if RUBY_VERSION >= '2.0' <del> require "psych/y" <del> else <del> module ::Kernel <del> def y(*objects) <del> puts ::Psych.dump_stream(*objects) <del> end <del> private :y <del> end <del> end <add> require "psych/y" <ide> end <ide> end <ide>
1
PHP
PHP
remove @throws tag after removing exception
e73b6e3ac6060bd6cd7960caf7abd9b5310eebd5
<ide><path>src/I18n/DateFormatTrait.php <ide> public static function setJsonEncodeFormat($format): void <ide> * @param string|int|int[]|null $format Any format accepted by IntlDateFormatter. <ide> * @param \DateTimeZone|string|null $tz The timezone for the instance <ide> * @return static|null <del> * @throws \InvalidArgumentException If $format is a single int instead of array of constants <ide> */ <ide> public static function parseDateTime(string $time, $format = null, $tz = null) <ide> {
1
PHP
PHP
fix import order
c521b76acfed6b755a4b261c54980800d536c044
<ide><path>tests/TestCase/View/CellTest.php <ide> namespace Cake\Test\TestCase\View; <ide> <ide> use Cake\Cache\Cache; <del>use Cake\Http\ServerRequest; <ide> use Cake\Http\Response; <add>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Cell; <ide> use Cake\View\Exception\MissingCellTemplateException; <ide><path>tests/TestCase/View/ViewTest.php <ide> use Cake\Core\Configure; <ide> use Cake\Core\Plugin; <ide> use Cake\Event\EventInterface; <del>use Cake\Http\ServerRequest; <ide> use Cake\Http\Response; <add>use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\View; <ide> use RuntimeException;
2
PHP
PHP
convert closures to arrow functions
76e427ae10d6b7a3a6db02fb040805bfbced402f
<ide><path>src/Illuminate/Collections/Traits/EnumeratesValues.php <ide> public function some($key, $operator = null, $value = null) <ide> public function containsStrict($key, $value = null) <ide> { <ide> if (func_num_args() === 2) { <del> return $this->contains(function ($item) use ($key, $value) { <del> return data_get($item, $key) === $value; <del> }); <add> return $this->contains(fn ($item) => data_get($item, $key) === $value); <ide> } <ide> <ide> if ($this->useAsCallable($key)) { <ide> public function flatMap(callable $callback) <ide> */ <ide> public function mapInto($class) <ide> { <del> return $this->map(function ($value, $key) use ($class) { <del> return new $class($value, $key); <del> }); <add> return $this->map(fn ($value, $key) => new $class($value, $key)); <ide> } <ide> <ide> /** <ide> public function min($callback = null) <ide> { <ide> $callback = $this->valueRetriever($callback); <ide> <del> return $this->map(function ($value) use ($callback) { <del> return $callback($value); <del> })->filter(function ($value) { <del> return ! is_null($value); <del> })->reduce(function ($result, $value) { <del> return is_null($result) || $value < $result ? $value : $result; <del> }); <add> return $this->map(fn ($value) => $callback($value)) <add> ->filter(fn ($value) => ! is_null($value)) <add> ->reduce(fn ($result, $value) => is_null($result) || $value < $result ? $value : $result); <ide> } <ide> <ide> /** <ide> public function max($callback = null) <ide> { <ide> $callback = $this->valueRetriever($callback); <ide> <del> return $this->filter(function ($value) { <del> return ! is_null($value); <del> })->reduce(function ($result, $item) use ($callback) { <add> return $this->filter(fn ($value) => ! is_null($value))->reduce(function ($result, $item) use ($callback) { <ide> $value = $callback($item); <ide> <ide> return is_null($result) || $value > $result ? $value : $result; <ide> public function sum($callback = null) <ide> ? $this->identity() <ide> : $this->valueRetriever($callback); <ide> <del> return $this->reduce(function ($result, $item) use ($callback) { <del> return $result + $callback($item); <del> }, 0); <add> return $this->reduce(fn ($result, $item) => $result + $callback($item), 0); <ide> } <ide> <ide> /** <ide> public function whereIn($key, $values, $strict = false) <ide> { <ide> $values = $this->getArrayableItems($values); <ide> <del> return $this->filter(function ($item) use ($key, $values, $strict) { <del> return in_array(data_get($item, $key), $values, $strict); <del> }); <add> return $this->filter(fn ($item) => in_array(data_get($item, $key), $values, $strict)); <ide> } <ide> <ide> /** <ide> public function whereBetween($key, $values) <ide> */ <ide> public function whereNotBetween($key, $values) <ide> { <del> return $this->filter(function ($item) use ($key, $values) { <del> return data_get($item, $key) < reset($values) || data_get($item, $key) > end($values); <del> }); <add> return $this->filter( <add> fn ($item) => data_get($item, $key) < reset($values) || data_get($item, $key) > end($values) <add> ); <ide> } <ide> <ide> /** <ide> public function whereNotIn($key, $values, $strict = false) <ide> { <ide> $values = $this->getArrayableItems($values); <ide> <del> return $this->reject(function ($item) use ($key, $values, $strict) { <del> return in_array(data_get($item, $key), $values, $strict); <del> }); <add> return $this->reject(fn ($item) => in_array(data_get($item, $key), $values, $strict)); <ide> } <ide> <ide> /** <ide> public function pipeInto($class) <ide> public function pipeThrough($callbacks) <ide> { <ide> return Collection::make($callbacks)->reduce( <del> function ($carry, $callback) { <del> return $callback($carry); <del> }, <add> fn ($carry, $callback) => $callback($carry), <ide> $this, <ide> ); <ide> } <ide> public function collect() <ide> */ <ide> public function toArray() <ide> { <del> return $this->map(function ($value) { <del> return $value instanceof Arrayable ? $value->toArray() : $value; <del> })->all(); <add> return $this->map(fn ($value) => $value instanceof Arrayable ? $value->toArray() : $value)->all(); <ide> } <ide> <ide> /** <ide> protected function valueRetriever($value) <ide> return $value; <ide> } <ide> <del> return function ($item) use ($value) { <del> return data_get($item, $value); <del> }; <add> return fn ($item) => data_get($item, $value); <ide> } <ide> <ide> /** <ide> protected function valueRetriever($value) <ide> */ <ide> protected function equality($value) <ide> { <del> return function ($item) use ($value) { <del> return $item === $value; <del> }; <add> return fn ($item) => $item === $value; <ide> } <ide> <ide> /** <ide> protected function equality($value) <ide> */ <ide> protected function negate(Closure $callback) <ide> { <del> return function (...$params) use ($callback) { <del> return ! $callback(...$params); <del> }; <add> return fn (...$params) => ! $callback(...$params); <ide> } <ide> <ide> /** <ide> protected function negate(Closure $callback) <ide> */ <ide> protected function identity() <ide> { <del> return function ($value) { <del> return $value; <del> }; <add> return fn ($value) => $value; <ide> } <ide> }
1
Mixed
Ruby
add migrations_paths option to migration generator
b551a707552598bd0134a6ebecb076f0f7edeaa1
<ide><path>activerecord/lib/rails/generators/active_record/migration.rb <ide> def primary_key_type <ide> end <ide> <ide> def db_migrate_path <del> if defined?(Rails.application) && Rails.application <add> if migrations_paths = options[:migrations_paths] <add> migrations_paths <add> elsif defined?(Rails.application) && Rails.application <ide> Rails.application.config.paths["db/migrate"].to_ary.first <ide> else <ide> "db/migrate" <ide><path>activerecord/lib/rails/generators/active_record/migration/migration_generator.rb <ide> class MigrationGenerator < Base # :nodoc: <ide> argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" <ide> <ide> class_option :primary_key_type, type: :string, desc: "The type for primary key" <add> class_option :migrations_paths, type: :string, desc: "The migration path for your generated migrations. If this is not set it will default to db/migrate" <ide> <ide> def create_migration_file <ide> set_local_assigns! <ide><path>railties/CHANGELOG.md <add>* Add `--migrations_paths` option to migration generator. <add> <add> If you're using multiple databases and have a folder for each database <add> for migrations (ex db/migrate and db/new_db_migrate) you can now pass the <add> `--migrations_paths` option to the generator to make sure the the migration <add> is inserted into the correct folder. <add> <add> ``` <add> rails g migration CreateHouses --migrations_paths=db/kingston_migrate <add> invoke active_record <add> create db/kingston_migrate/20180830151055_create_houses.rb <add> ``` <add> <add> *Eileen M. Uchitelle* <add> <ide> * Deprecate `rake routes` in favor of `rails routes`. <ide> <ide> *Yuji Yaginuma* <ide><path>railties/test/generators/migration_generator_test.rb <ide> def test_add_uuid_to_create_table_migration <ide> end <ide> end <ide> <add> def test_migrations_paths_puts_migrations_in_that_folder <add> run_generator ["create_books", "--migrations_paths=db/test_migrate"] <add> assert_migration "db/test_migrate/create_books.rb" do |content| <add> assert_method :change, content do |change| <add> assert_match(/create_table :books/, change) <add> end <add> end <add> end <add> <ide> def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove_or_create <ide> migration = "delete_books" <ide> run_generator [migration, "title:string", "content:text"]
4
Javascript
Javascript
add an example
e812b9fa9ec7086ab8d64a32d86f6e991f84bc55
<ide><path>src/ng/filter/filters.js <ide> function jsonFilter() { <ide> * @kind function <ide> * @description <ide> * Converts string to lowercase. <add> * <add> * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example. <add> * <ide> * @see angular.lowercase <ide> */ <ide> var lowercaseFilter = valueFn(lowercase); <ide> var lowercaseFilter = valueFn(lowercase); <ide> * @kind function <ide> * @description <ide> * Converts string to uppercase. <del> * @see angular.uppercase <add> * @example <add> <example module="uppercaseFilterExample" name="filter-uppercase"> <add> <file name="index.html"> <add> <script> <add> angular.module('uppercaseFilterExample', []) <add> .controller('ExampleController', ['$scope', function($scope) { <add> $scope.title = 'This is a title'; <add> }]); <add> </script> <add> <div ng-controller="ExampleController"> <add> <!-- This title should be formatted normally --> <add> <h1>{{title}}</h1> <add> <!-- This title should be capitalized --> <add> <h1>{{title | uppercase}}</h1> <add> </div> <add> </file> <add> </example> <ide> */ <ide> var uppercaseFilter = valueFn(uppercase);
1
Javascript
Javascript
make .send() throw if message is undefined
6df7bdd954efb817b50dafad7f90a1285c59c0c9
<ide><path>lib/child_process.js <ide> function setupChannel(target, channel) { <ide> }; <ide> <ide> target.send = function(message, sendHandle) { <del> if (!target._channel) throw new Error('channel closed'); <add> if (typeof message === 'undefined') { <add> throw new TypeError('message cannot be undefined'); <add> } <add> <add> if (!target._channel) throw new Error("channel closed"); <ide> <ide> // For overflow protection don't write if channel queue is too deep. <ide> if (channel.writeQueueSize > 1024 * 1024) { <ide><path>test/simple/test-child-process-fork.js <ide> n.on('message', function(m) { <ide> messageCount++; <ide> }); <ide> <add>// https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) <add>// returns "undefined" but JSON.parse() cannot parse that... <add>assert.throws(function() { n.send(undefined); }, TypeError); <add>assert.throws(function() { n.send(); }, TypeError); <add> <ide> n.send({ hello: 'world' }); <ide> <ide> var childExitCode = -1;
2
PHP
PHP
fix inflectedroute calling parent() incorrectly
e8c75f19102a9e86134f0baeb274a27984957687
<ide><path>src/Routing/Route/InflectedRoute.php <ide> class InflectedRoute extends Route <ide> */ <ide> public function parse($url, $method = '') <ide> { <del> $params = parent::parse($url); <add> $params = parent::parse($url, $method); <ide> if (!$params) { <ide> return false; <ide> } <ide><path>src/Routing/Route/Route.php <ide> public function parse($url, $method = '') <ide> if (empty($method)) { <ide> // Deprecated reading the global state is deprecated and will be removed in 4.x <ide> $request = Router::getRequest(true) ?: ServerRequest::createFromGlobals(); <del> $method = $request->env('REQUEST_METHOD'); <add> $method = $request->getMethod(); <ide> } <ide> if (!in_array($method, (array)$this->defaults['_method'], true)) { <ide> return false; <ide><path>tests/TestCase/Routing/Route/InflectedRouteTest.php <ide> public function testParse() <ide> $this->assertEquals(['tv_shows'], $result['pass']); <ide> } <ide> <add> /** <add> * Test that parse() checks methods. <add> * <add> * @return void <add> */ <add> public function testParseMethodMatch() <add> { <add> $route = new InflectedRoute('/:controller/:action', ['_method' => 'POST']); <add> $this->assertFalse($route->parse('/blog_posts/add_new', 'GET')); <add> <add> $result = $route->parse('/blog_posts/add_new', 'POST'); <add> $this->assertEquals('BlogPosts', $result['controller']); <add> $this->assertEquals('add_new', $result['action']); <add> } <add> <ide> /** <ide> * @return void <ide> */ <ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php <ide> public function setUp() <ide> parent::setUp(); <ide> Configure::write('App.namespace', 'TestApp'); <ide> <add> Router::connect('/get/:controller/:action', ['_method' => 'GET'], ['routeClass' => 'InflectedRoute']); <ide> Router::connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']); <ide> DispatcherFactory::clear(); <ide> DispatcherFactory::add('Routing'); <ide> public function testGet() <ide> $this->assertNotEmpty($this->_response); <ide> $this->assertInstanceOf('Cake\Network\Response', $this->_response); <ide> $this->assertEquals('This is a test', $this->_response->body()); <add> <add> $this->_response = null; <add> $this->get('/get/request_action/test_request_action'); <add> $this->assertEquals('This is a test', $this->_response->body()); <add> } <add> <add> /** <add> * Test sending get requests sets the request method <add> * <add> * @return void <add> */ <add> public function testGetSpecificRouteHttpServer() <add> { <add> $this->useHttpServer(true); <add> $this->get('/get/request_action/test_request_action'); <add> $this->assertResponseOk(); <add> $this->assertEquals('This is a test', $this->_response->body()); <ide> } <ide> <ide> /**
4
Text
Text
add a changelog entry about web console inclusion
b4fd1e338b2c1ec2c501c0e1207a4f774ed6e30a
<ide><path>railties/CHANGELOG.md <add>* Include `web-console` into newly generated applications' Gemfile. <add> <add> *Genadi Samokovarov* <add> <ide> * `rails server` will only extend the logger to output to STDOUT <ide> in development environment. <ide>
1
Go
Go
optimize the rebroadcast for failure case
d6440c91394a0151a4db0325c728b9f894050a62
<ide><path>libnetwork/networkdb/cluster.go <ide> func (nDB *NetworkDB) reconnectNode() { <ide> return <ide> } <ide> <del> // Update all the local table state to a new time to <del> // force update on the node we are trying to rejoin, just in <del> // case that node has these in deleting state still. This is <del> // facilitate fast convergence after recovering from a gossip <del> // failure. <del> nDB.updateLocalTableTime() <del> <ide> logrus.Debugf("Initiating bulk sync with node %s after reconnect", node.Name) <ide> nDB.bulkSync([]string{node.Name}, true) <ide> } <ide><path>libnetwork/networkdb/event_delegate.go <ide> func (e *eventDelegate) NotifyLeave(mn *memberlist.Node) { <ide> var failed bool <ide> logrus.Infof("Node %s/%s, left gossip cluster", mn.Name, mn.Addr) <ide> e.broadcastNodeEvent(mn.Addr, opDelete) <del> e.nDB.deleteNodeTableEntries(mn.Name) <del> e.nDB.deleteNetworkEntriesForNode(mn.Name) <add> // The node left or failed, delete all the entries created by it. <add> // If the node was temporary down, deleting the entries will guarantee that the CREATE events will be accepted <add> // If the node instead left because was going down, then it makes sense to just delete all its state <ide> e.nDB.Lock() <add> e.nDB.deleteNetworkEntriesForNode(mn.Name) <add> e.nDB.deleteNodeTableEntries(mn.Name) <ide> if n, ok := e.nDB.nodes[mn.Name]; ok { <ide> delete(e.nDB.nodes, mn.Name) <ide> <ide> func (e *eventDelegate) NotifyLeave(mn *memberlist.Node) { <ide> if failed { <ide> logrus.Infof("Node %s/%s, added to failed nodes list", mn.Name, mn.Addr) <ide> } <del> <ide> } <ide> <ide> func (e *eventDelegate) NotifyUpdate(n *memberlist.Node) { <ide><path>libnetwork/networkdb/networkdb.go <ide> func (nDB *NetworkDB) DeleteEntry(tname, nid, key string) error { <ide> } <ide> <ide> func (nDB *NetworkDB) deleteNetworkEntriesForNode(deletedNode string) { <del> nDB.Lock() <ide> for nid, nodes := range nDB.networkNodes { <ide> updatedNodes := make([]string, 0, len(nodes)) <ide> for _, node := range nodes { <ide> func (nDB *NetworkDB) deleteNetworkEntriesForNode(deletedNode string) { <ide> } <ide> <ide> delete(nDB.networks, deletedNode) <del> nDB.Unlock() <ide> } <ide> <ide> // deleteNodeNetworkEntries is called in 2 conditions with 2 different outcomes: <ide> func (nDB *NetworkDB) deleteNodeNetworkEntries(nid, node string) { <ide> } <ide> <ide> func (nDB *NetworkDB) deleteNodeTableEntries(node string) { <del> nDB.Lock() <ide> nDB.indexes[byTable].Walk(func(path string, v interface{}) bool { <ide> oldEntry := v.(*entry) <ide> if oldEntry.node != node { <ide> func (nDB *NetworkDB) deleteNodeTableEntries(node string) { <ide> nid := params[1] <ide> key := params[2] <ide> <del> entry := &entry{ <del> ltime: oldEntry.ltime, <del> node: node, <del> value: oldEntry.value, <del> deleting: true, <del> reapTime: reapInterval, <del> } <del> <del> nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry) <del> nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry) <add> nDB.indexes[byTable].Delete(fmt.Sprintf("/%s/%s/%s", tname, nid, key)) <add> nDB.indexes[byNetwork].Delete(fmt.Sprintf("/%s/%s/%s", nid, tname, key)) <ide> <del> nDB.broadcaster.Write(makeEvent(opDelete, tname, nid, key, entry.value)) <add> nDB.broadcaster.Write(makeEvent(opDelete, tname, nid, key, oldEntry.value)) <ide> return false <ide> }) <del> nDB.Unlock() <ide> } <ide> <ide> // WalkTable walks a single table in NetworkDB and invokes the passed <ide> func (nDB *NetworkDB) updateLocalNetworkTime() { <ide> n.ltime = ltime <ide> } <ide> } <del> <del>func (nDB *NetworkDB) updateLocalTableTime() { <del> nDB.Lock() <del> defer nDB.Unlock() <del> <del> ltime := nDB.tableClock.Increment() <del> nDB.indexes[byTable].Walk(func(path string, v interface{}) bool { <del> entry := v.(*entry) <del> if entry.node != nDB.config.NodeName { <del> return false <del> } <del> <del> params := strings.Split(path[1:], "/") <del> tname := params[0] <del> nid := params[1] <del> key := params[2] <del> entry.ltime = ltime <del> <del> nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry) <del> nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry) <del> <del> return false <del> }) <del>}
3
PHP
PHP
use negated filter for reject
f42a0244951ef71719839a5863847b8eadeca504
<ide><path>src/Illuminate/Support/Collection.php <ide> public function reduce($callback, $initial = null) <ide> } <ide> <ide> /** <del> * Create a colleciton of all elements that do not pass a given truth test. <add> * Create a collection of all elements that do not pass a given truth test. <ide> * <ide> * @param \Closure|mixed $callback <ide> * @return \Illuminate\Support\Collection <ide> */ <ide> public function reject($callback) <ide> { <del> $results = []; <del> <del> foreach ($this->items as $key => $value) <add> if ($callback instanceof Closure) <ide> { <del> if ($callback instanceof Closure) <add> return $this->filter(function($item) use ($callback) <ide> { <del> if ( ! $callback($value)) <del> { <del> $results[$key] = $value; <del> } <del> } <del> elseif ($callback != $value) <del> { <del> $results[$key] = $value; <del> } <add> return ! $callback($item); <add> }); <ide> } <ide> <del> return new static($results); <add> return $this->filter(function($item) use ($callback) <add> { <add> return $item != $callback; <add> }); <ide> } <ide> <ide> /**
1
Ruby
Ruby
drop runtime conditionals in parameter parsing
eb10496a1c3d9fe58b91aa0ec17d9f218738d5dc
<ide><path>actionpack/lib/action_dispatch/middleware/params_parser.rb <ide> def initialize(message, original_exception) <ide> end <ide> end <ide> <del> DEFAULT_PARSERS = { Mime::JSON => :json } <add> DEFAULT_PARSERS = { <add> Mime::JSON => lambda { |raw_post| <add> data = ActiveSupport::JSON.decode(raw_post) <add> data = {:_json => data} unless data.is_a?(Hash) <add> Request::Utils.deep_munge(data).with_indifferent_access <add> } <add> } <ide> <ide> def initialize(app, parsers = {}) <ide> @app, @parsers = app, DEFAULT_PARSERS.merge(parsers) <ide> def parse_formatted_parameters(env) <ide> <ide> return false if request.content_length.zero? <ide> <del> strategy = @parsers[request.content_mime_type] <add> strategy = @parsers.fetch(request.content_mime_type) { return false } <ide> <del> return false unless strategy <add> strategy.call(request.raw_post) <ide> <del> case strategy <del> when Proc <del> strategy.call(request.raw_post) <del> when :json <del> data = ActiveSupport::JSON.decode(request.raw_post) <del> data = {:_json => data} unless data.is_a?(Hash) <del> Request::Utils.deep_munge(data).with_indifferent_access <del> else <del> false <del> end <ide> rescue => e # JSON or Ruby code block errors <ide> logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}" <ide>
1
PHP
PHP
add method to register multiple components'
7fc934449119483ae62263cc5cbd0900360812eb
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php <ide> public function check($name, ...$parameters) <ide> * Register a class-based component alias directive. <ide> * <ide> * @param string $class <del> * @param string $alias <add> * @param string|null $alias <ide> * @return void <ide> */ <del> public function component($class, $alias) <add> public function component($class, $alias = null) <ide> { <add> $alias = $alias ?: strtolower(class_basename($class)); <add> <ide> $this->directive($alias, function ($expression) use ($class) { <ide> return static::compileClassComponentOpening( <ide> $class, $expression ?: '[]', static::newComponentHash($class) <ide> public function component($class, $alias) <ide> }); <ide> } <ide> <add> /** <add> * Register an array of class-based components. <add> * <add> * @param array $components <add> * @return void <add> */ <add> public function components(array $components) <add> { <add> foreach ($components as $key => $value) { <add> if (is_numeric($key)) { <add> static::component($value); <add> } else { <add> static::component($key, $value); <add> } <add> } <add> } <add> <ide> /** <ide> * Register a component alias directive. <ide> *
1
Python
Python
run length encoding
50545d10c55859e3a3d792132ca6769f219bb130
<ide><path>compression/run_length_encoding.py <add># https://en.wikipedia.org/wiki/Run-length_encoding <add> <add> <add>def run_length_encode(text: str) -> list: <add> """ <add> Performs Run Length Encoding <add> >>> run_length_encode("AAAABBBCCDAA") <add> [('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)] <add> >>> run_length_encode("A") <add> [('A', 1)] <add> >>> run_length_encode("AA") <add> [('A', 2)] <add> >>> run_length_encode("AAADDDDDDFFFCCCAAVVVV") <add> [('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)] <add> """ <add> encoded = [] <add> count = 1 <add> <add> for i in range(len(text)): <add> if i + 1 < len(text) and text[i] == text[i + 1]: <add> count += 1 <add> else: <add> encoded.append((text[i], count)) <add> count = 1 <add> <add> return encoded <add> <add> <add>def run_length_decode(encoded: list) -> str: <add> """ <add> Performs Run Length Decoding <add> >>> run_length_decode([('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)]) <add> 'AAAABBBCCDAA' <add> >>> run_length_decode([('A', 1)]) <add> 'A' <add> >>> run_length_decode([('A', 2)]) <add> 'AA' <add> >>> run_length_decode([('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)]) <add> 'AAADDDDDDFFFCCCAAVVVV' <add> """ <add> return "".join(char * length for char, length in encoded) <add> <add> <add>if __name__ == "__main__": <add> from doctest import testmod <add> <add> testmod(name="run_length_encode", verbose=True) <add> testmod(name="run_length_decode", verbose=True)
1
Text
Text
add v3.16.9 to changelog.md
71f62351f501dba5c7a04a474e8c47c9bd73ddf9
<ide><path>CHANGELOG.md <ide> - [#18694](https://github.com/emberjs/ember.js/pull/18694) [BUGFIX] Ensure tag updates are buffered, remove error message <ide> - [#18709](https://github.com/emberjs/ember.js/pull/18709) [BUGFIX] Fix `this` in `@tracked` initializer <ide> <add>### v3.16.9 (July 29, 2020) <add> <add>- [#19001](https://github.com/emberjs/ember.js/pull/19001) [BUGFIX] Invoke methods correctly in `TextSupport` `sendAction` <add>- [#19023](https://github.com/emberjs/ember.js/pull/19023) [BUGFIX] Avoid over eager property access during `init` <add>- [#19048](https://github.com/emberjs/ember.js/pull/19048) [BUGFIX] Update `router.js` to ensure `transition.abort` works for query param only transitions <add>- [#19057](https://github.com/emberjs/ember.js/pull/19057) [BUGFIX] Parallelize `inject-babel-helpers` plugin <add>- [#19059](https://github.com/emberjs/ember.js/pull/19059) [BUGFIX] Prevent `<base target="_parent">` from erroring in HistoryLocation <add> <ide> ### v3.16.8 (April 24, 2020) <ide> <ide> - [#18879](https://github.com/emberjs/ember.js/pull/18879) Ensure errors thrown during component construction do not cause (unrelated) errors during application teardown (fixes a common issue when using `setupOnerror` with components asserting during `constructor`/`init`/`didInssertElement`).
1
Python
Python
emit single warning for multiple dlls
b90cbbad4e0d3e31c7ae1e7cfdc1932c3ccb396b
<ide><path>numpy/core/__init__.py <ide> DLL_filenames.append(filename) <ide> if len(DLL_filenames) > 1: <ide> import warnings <del> warnings.warn("loaded more than 1 DLL from .libs:", <add> warnings.warn("loaded more than 1 DLL from .libs:\n%s" % <add> "\n".join(DLL_filenames), <ide> stacklevel=1) <del> for DLL_filename in DLL_filenames: <del> warnings.warn(DLL_filename, stacklevel=1) <ide> <ide> # disables OpenBLAS affinity setting of the main thread that limits <ide> # python threads or processes to one core
1
Ruby
Ruby
fix rubocop errors re \xfc
11eaf1c1dd48e86a38b8dc83a2b35d99f746b1f8
<ide><path>actionview/test/template/template_test.rb <ide> def test_text_template_does_not_html_escape <ide> end <ide> <ide> def test_raw_template <del> @template = new_template("<%= hello %>", :handler => ActionView::Template::Handlers::Raw.new) <add> @template = new_template("<%= hello %>", handler: ActionView::Template::Handlers::Raw.new) <ide> assert_equal "<%= hello %>", render <ide> end <ide> <ide> def test_error_when_template_isnt_valid_utf8 <ide> @template = new_template("hello \xFCmlat", virtual_path: nil) <ide> render <ide> end <del> assert_match(/\xFC/, e.message) <add> # Hack: We write the regexp this way because the parser of RuboCop <add> # errs with /\xFC/. <add> assert_match(Regexp.new("\xFC"), e.message) <ide> end <ide> <ide> def with_external_encoding(encoding)
1
Javascript
Javascript
correct a typo
ebff4c1fd23eaf5b784f842535c0ff508e58091b
<ide><path>src/ngMessages/messages.js <ide> angular.module('ngMessages', []) <ide> * <ide> * @description <ide> * `ngMessages` is a directive that is designed to show and hide messages based on the state <del> * of a key/value object that is listens on. The directive itself compliments error message <add> * of a key/value object that it listens on. The directive itself compliments error message <ide> * reporting with the `ngModel` $error object (which stores a key/value state of validation errors). <ide> * <ide> * `ngMessages` manages the state of internal messages within its container element. The internal
1
PHP
PHP
add another condition to test && fix indentation
d2b63766148b0792ae6d9a95c44c7b4dc5bf7663
<ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testBelongsToManyWithMixedData() <ide> } <ide> <ide> /** <del> * Test belongsToMany association with the ForceNewTarget to force saving <add> * Test belongsToMany association with the ForceNewTarget to force saving <ide> * new records on the target tables with BTM relationships when the primaryKey(s) <ide> * of the target table is specified. <ide> * <ide> public function testBelongsToManyWithForceNew() <ide> 'body' => 'Fourth Article Body', <ide> 'author_id' => 1, <ide> 'tags' => [ <add> [ <add> 'id' => 3 <add> ], <ide> [ <ide> 'id' => 4, <ide> 'name' => 'tag4' <ide> ] <ide> ] <ide> ]; <ide> <del> $marshaller = new Marshaller($this->articles); <del> $article = $marshaller->one($data, [ <del> 'associated' => ['Tags'], <del> 'forceNew' => true <del> ]); <add> $marshaller = new Marshaller($this->articles); <add> $article = $marshaller->one($data, [ <add> 'associated' => ['Tags'], <add> 'forceNew' => true <add> ]); <ide> <del> $this->assertTrue($article->tags[0]->isNew(), 'The tag should be new'); <add> $this->assertFalse($article->tags[0]->isNew(), 'The tag should not be new'); <add> $this->assertTrue($article->tags[1]->isNew(), 'The tag should be new'); <ide> } <ide> <ide> /**
1
PHP
PHP
remove unneeded code
74b62bbbb32674dfa167e2812231bf302454e67f
<ide><path>src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php <ide> protected function restoreCollection($value) <ide> return new $collectionClass( <ide> collect($value->id)->map(function ($id) use ($collection) { <ide> return $collection[$id] ?? null; <del> })->when($collection->count() !== count($value->id), function ($collection) { <del> return $collection->filter(); <del> }) <add> })->filter() <ide> ); <ide> } <ide>
1
PHP
PHP
fix failing cookie test
e649ad07f25d4c55333c373b1e31bdcc7ca38bff
<ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php <ide> public function testAddFromResponse() <ide> ]); <ide> $response = (new Response()) <ide> ->withAddedHeader('Set-Cookie', 'test=value') <del> ->withAddedHeader('Set-Cookie', 'expiring=soon; Expires=Wed, 09-Jun-2021 10:18:14 GMT; Path=/; HttpOnly; Secure;') <add> ->withAddedHeader('Set-Cookie', 'expiring=soon; Expires=Mon, 09-Jun-2031 10:18:14 GMT; Path=/; HttpOnly; Secure;') <ide> ->withAddedHeader('Set-Cookie', 'session=123abc; Domain=www.example.com') <del> ->withAddedHeader('Set-Cookie', 'maxage=value; Max-Age=60; Expires=Wed, 09-Jun-2021 10:18:14 GMT;'); <add> ->withAddedHeader('Set-Cookie', 'maxage=value; Max-Age=60; Expires=Mon, 09-Jun-2031 10:18:14 GMT;'); <ide> $new = $collection->addFromResponse($response, $request); <ide> $this->assertNotSame($new, $collection, 'Should clone collection'); <ide> <ide> public function testAddFromResponse() <ide> <ide> $this->assertNull($new->get('test')->getExpiry(), 'No expiry'); <ide> $this->assertSame( <del> '2021-06-09 10:18:14', <add> '2031-06-09 10:18:14', <ide> $new->get('expiring')->getExpiry()->format('Y-m-d H:i:s'), <ide> 'Has expiry' <ide> );
1
Javascript
Javascript
use login over custom button
456173f6779749ed3db4458293e75db33fd6b635
<ide><path>client/src/components/Intro/Intro.test.js <ide> /* global expect */ <ide> import React from 'react'; <ide> import renderer from 'react-test-renderer'; <del>// import ShallowRenderer from 'react-test-renderer/shallow'; <add>import { Provider } from 'react-redux'; <add>import { createStore } from '../../redux/createStore'; <ide> <ide> import 'jest-dom/extend-expect'; <ide> <ide> import Intro from './'; <ide> <add>function rendererCreateWithRedux(ui) { <add> return renderer.create(<Provider store={createStore()}>{ui}</Provider>); <add>} <add> <ide> describe('<Intro />', () => { <ide> it('has no blockquotes when loggedOut', () => { <del> const container = renderer.create(<Intro {...loggedOutProps} />).root; <add> const container = rendererCreateWithRedux(<Intro {...loggedOutProps} />) <add> .root; <ide> expect(container.findAllByType('blockquote').length === 0).toBeTruthy(); <ide> expect(container.findAllByType('h1').length === 1).toBeTruthy(); <ide> }); <ide> <ide> it('has a blockquote when loggedIn', () => { <del> const container = renderer.create(<Intro {...loggedInProps} />).root; <add> const container = rendererCreateWithRedux(<Intro {...loggedInProps} />) <add> .root; <ide> expect(container.findAllByType('blockquote').length === 1).toBeTruthy(); <ide> expect(container.findAllByType('h1').length === 1).toBeTruthy(); <ide> }); <ide><path>client/src/components/Intro/index.js <ide> import React from 'react'; <ide> import PropTypes from 'prop-types'; <ide> import { Link, Spacer, Loader, FullWidthRow } from '../helpers'; <ide> import { Row, Col } from '@freecodecamp/react-bootstrap'; <del>import { apiLocation, forumLocation } from '../../../config/env.json'; <add>import { forumLocation } from '../../../config/env.json'; <ide> import { randomQuote } from '../../utils/get-words'; <ide> import CurrentChallengeLink from '../helpers/CurrentChallengeLink'; <ide> <ide> import './intro.css'; <add>import Login from '../Header/components/Login'; <ide> <ide> const propTypes = { <ide> complete: PropTypes.bool, <ide> completedChallengeCount: PropTypes.number, <ide> isSignedIn: PropTypes.bool, <ide> name: PropTypes.string, <del> navigate: PropTypes.func, <ide> pending: PropTypes.bool, <ide> slug: PropTypes.string, <ide> username: PropTypes.string <ide> function Intro({ <ide> isSignedIn, <ide> username, <ide> name, <del> navigate, <ide> pending, <ide> complete, <ide> completedChallengeCount, <ide> function Intro({ <ide> </Col> <ide> <ide> <Col sm={8} smOffset={2} xs={12}> <del> <button <del> className={'btn-cta-big signup-btn btn-cta center-block'} <del> onClick={() => { <del> navigate(`${apiLocation}/signin`); <del> }} <del> > <add> <Login block={true}> <ide> Sign in to save your progress (it's free) <del> </button> <add> </Login> <ide> </Col> <ide> </Row> <ide> <Spacer />
2
Javascript
Javascript
fix path of data.json
a6b9d76ee4acf0cb23107af3fb7d2edbb73e8154
<ide><path>config/s3ProjectConfig.js <ide> fileMap = function(revision,tag,date) { <ide> "ember-runtime.js": fileObject("ember-runtime", ".js", "text/javascript", revision, tag, date), <ide> "ember.min.js": fileObject("ember.min", ".js", "text/javascript", revision, tag, date), <ide> "ember.prod.js": fileObject("ember.prod", ".js", "text/javascript", revision, tag, date), <del>// "../docs/build/data.json": fileObject("ember-docs", ".json", "application/json", revision, tag, date) <add> "../docs/data.json": fileObject("ember-docs", ".json", "application/json", revision, tag, date) <ide> }; <ide> }; <ide>
1
PHP
PHP
remove uneeded phpcs ignores
191bdf171764d8d5fead4fa76f4505cf8ed6c991
<ide><path>src/Collection/CollectionTrait.php <ide> public function cartesianProduct(?callable $operation = null, ?callable $filter <ide> <ide> $currentIndexes[$lastIndex]++; <ide> <del> // phpcs:ignore Squiz.ControlStructures.ForLoopDeclaration.SpacingAfterFirst <ide> for ( <ide> $changeIndex = $lastIndex; <del> // phpcs:ignore Squiz.ControlStructures.ForLoopDeclaration.SpacingAfterSecond <ide> $currentIndexes[$changeIndex] === $collectionArraysCounts[$changeIndex] && $changeIndex > 0; <ide> $changeIndex-- <ide> ) { <ide><path>src/Console/HelperRegistry.php <ide> protected function _throwMissingClassError(string $class, ?string $plugin): void <ide> */ <ide> protected function _create($class, string $alias, array $config): Helper <ide> { <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var \Cake\Console\Helper */ <ide> return new $class($this->_io, $config); <ide> } <ide><path>src/Console/TaskRegistry.php <ide> protected function _throwMissingClassError(string $class, ?string $plugin): void <ide> */ <ide> protected function _create($class, string $alias, array $config): Shell <ide> { <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var \Cake\Console\Shell */ <ide> return new $class($this->_Shell->getIo()); <ide> } <ide><path>src/Controller/ControllerFactory.php <ide> function ($val) { <ide> throw $this->missingController($request); <ide> } <ide> <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var class-string<\Cake\Controller\Controller>|null */ <ide> return App::className($pluginPath . $controller, $namespace, 'Controller'); <ide> } <ide><path>src/Core/App.php <ide> public static function className(string $class, string $type = '', string $suffi <ide> $fullname = '\\' . str_replace('/', '\\', $type . '\\' . $name) . $suffix; <ide> <ide> if (static::_classExistsInBase($fullname, $base)) { <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var class-string */ <ide> return $base . $fullname; <ide> } <ide> public static function className(string $class, string $type = '', string $suffi <ide> return null; <ide> } <ide> <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var class-string */ <ide> return 'Cake' . $fullname; <ide> } <ide><path>src/Core/PluginCollection.php <ide> public function get(string $name): PluginInterface <ide> public function create(string $name, array $config = []): PluginInterface <ide> { <ide> if (strpos($name, '\\') !== false) { <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var \Cake\Core\PluginInterface */ <ide> return new $name($config); <ide> } <ide><path>src/Datasource/ConnectionRegistry.php <ide> protected function _create($class, string $alias, array $config) <ide> <ide> unset($config['className']); <ide> <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var \Cake\Datasource\ConnectionInterface */ <ide> return new $class($config); <ide> } <ide><path>src/Http/Middleware/CspMiddleware.php <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface <ide> { <ide> $response = $handler->handle($request); <ide> <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var \Psr\Http\Message\ResponseInterface */ <ide> return $this->csp->injectCSPHeader($response); <ide> } <ide><path>src/I18n/DateFormatTrait.php <ide> protected function _formatObject($date, $format, ?string $locale): string <ide> $locale = I18n::getLocale(); <ide> } <ide> <del> // phpcs:ignore Generic.Files.LineLength <del> if (preg_match('/@calendar=(japanese|buddhist|chinese|persian|indian|islamic|hebrew|coptic|ethiopic)/', $locale)) { <add> if ( <add> preg_match( <add> '/@calendar=(japanese|buddhist|chinese|persian|indian|islamic|hebrew|coptic|ethiopic)/', <add> $locale <add> ) <add> ) { <ide> $calendar = IntlDateFormatter::TRADITIONAL; <ide> } else { <ide> $calendar = IntlDateFormatter::GREGORIAN; <ide><path>src/Utility/Text.php <ide> public static function truncate(string $text, int $length = 100, array $options <ide> } <ide> <ide> if ($truncate === '') { <del> // phpcs:ignore Generic.Files.LineLength <del> if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/i', $tag[2])) { <add> if ( <add> !preg_match( <add> '/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/i', <add> $tag[2] <add> ) <add> ) { <ide> if (preg_match('/<[\w]+[^>]*>/', $tag[0])) { <ide> array_unshift($openTags, $tag[2]); <ide> } elseif (preg_match('/<\/([\w]+)[^>]*>/', $tag[0], $closeTag)) { <ide><path>src/View/ViewBuilder.php <ide> public function build( <ide> ]; <ide> $data += $this->_options; <ide> <del> // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat <ide> /** @var \Cake\View\View */ <ide> return new $className($request, $response, $events, $data); <ide> }
11
Javascript
Javascript
reduce closures when resolving promises
947337134363ac73ad5a27030797bdaa90f8b304
<ide><path>src/ng/q.js <ide> function $$QProvider() { <ide> */ <ide> function qFactory(nextTick, exceptionHandler) { <ide> var $qMinErr = minErr('$q', TypeError); <del> function callOnce(self, resolveFn, rejectFn) { <del> var called = false; <del> function wrap(fn) { <del> return function(value) { <del> if (called) return; <del> called = true; <del> fn.call(self, value); <del> }; <del> } <del> <del> return [wrap(resolveFn), wrap(rejectFn)]; <del> } <ide> <ide> /** <ide> * @ngdoc method <ide> function qFactory(nextTick, exceptionHandler) { <ide> }, <ide> <ide> $$resolve: function(val) { <del> var then, fns; <del> <del> fns = callOnce(this, this.$$resolve, this.$$reject); <add> var then; <add> var that = this; <add> var done = false; <ide> try { <ide> if ((isObject(val) || isFunction(val))) then = val && val.then; <ide> if (isFunction(then)) { <ide> this.promise.$$state.status = -1; <del> then.call(val, fns[0], fns[1], this.notify); <add> then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify)); <ide> } else { <ide> this.promise.$$state.value = val; <ide> this.promise.$$state.status = 1; <ide> scheduleProcessQueue(this.promise.$$state); <ide> } <ide> } catch (e) { <del> fns[1](e); <add> rejectPromise(e); <ide> exceptionHandler(e); <ide> } <add> <add> function resolvePromise(val) { <add> if (done) return; <add> done = true; <add> that.$$resolve(val); <add> } <add> function rejectPromise(val) { <add> if (done) return; <add> done = true; <add> that.$$reject(val); <add> } <ide> }, <ide> <ide> reject: function(reason) {
1
Python
Python
improve model variable naming - clip [tf]
97e32b7854fc74e271863adc31b1bcee38e0b065
<ide><path>src/transformers/models/clip/modeling_tf_clip.py <ide> TFModelInputType, <ide> TFPreTrainedModel, <ide> get_initializer, <del> input_processing, <ide> keras_serializable, <add> unpack_inputs, <ide> ) <ide> from ...tf_utils import shape_list <ide> from ...utils import logging <ide> def set_input_embeddings(self, value: tf.Variable): <ide> self.text_model.embeddings.weight = value <ide> self.text_model.embeddings.vocab_size = shape_list(value)[0] <ide> <add> @unpack_inputs <ide> def call( <ide> self, <ide> input_ids: Optional[TFModelInputType] = None, <ide> def call( <ide> training: bool = False, <ide> **kwargs, <ide> ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]: <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> if input_ids is None: <add> raise ValueError("You have to specify input_ids") <add> <add> input_shape = shape_list(input_ids) <add> <add> if attention_mask is None: <add> attention_mask = tf.fill(dims=input_shape, value=1) <add> <add> text_model_outputs = self.text_model( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> position_ids=position_ids, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> if inputs["input_ids"] is None: <del> raise ValueError("You have to specify either input_ids") <del> <del> input_shape = shape_list(inputs["input_ids"]) <del> <del> if inputs["attention_mask"] is None: <del> inputs["attention_mask"] = tf.fill(dims=input_shape, value=1) <del> <del> text_model_outputs = self.text_model( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> position_ids=inputs["position_ids"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> <ide> return text_model_outputs <ide> def __init__(self, config: CLIPVisionConfig, **kwargs): <ide> def get_input_embeddings(self) -> tf.keras.layers.Layer: <ide> return self.vision_model.embeddings <ide> <add> @unpack_inputs <ide> def call( <ide> self, <ide> pixel_values: Optional[TFModelInputType] = None, <ide> def call( <ide> training: bool = False, <ide> **kwargs, <ide> ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]: <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=pixel_values, <del> output_attentions=output_attentions, <del> output_hidden_states=output_hidden_states, <del> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <ide> <del> if "input_ids" in inputs: <del> inputs["pixel_values"] = inputs.pop("input_ids") <del> <del> if inputs["pixel_values"] is None: <add> if pixel_values is None: <ide> raise ValueError("You have to specify pixel_values") <ide> <ide> vision_model_outputs = self.vision_model( <del> pixel_values=inputs["pixel_values"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <add> pixel_values=pixel_values, <add> output_attentions=output_attentions, <add> output_hidden_states=output_hidden_states, <add> return_dict=return_dict, <add> training=training, <ide> ) <ide> <ide> return vision_model_outputs <ide> def build(self, input_shape: tf.TensorShape): <ide> <ide> super().build(input_shape) <ide> <add> @unpack_inputs <ide> def get_text_features( <ide> self, <ide> input_ids: Optional[TFModelInputType] = None, <ide> def get_text_features( <ide> training: bool = False, <ide> **kwargs, <ide> ) -> tf.Tensor: <del> inputs = input_processing( <del> func=self.get_text_features, <del> config=self.config, <add> <add> if input_ids is None: <add> raise ValueError("You have to specify either input_ids") <add> <add> input_shape = shape_list(input_ids) <add> <add> if attention_mask is None: <add> attention_mask = tf.fill(dims=input_shape, value=1) <add> <add> text_outputs = self.text_model( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> position_ids=position_ids, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> if inputs["input_ids"] is None: <del> raise ValueError("You have to specify either input_ids") <del> <del> input_shape = shape_list(inputs["input_ids"]) <del> <del> if inputs["attention_mask"] is None: <del> inputs["attention_mask"] = tf.fill(dims=input_shape, value=1) <del> <del> text_outputs = self.text_model( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> position_ids=inputs["position_ids"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> <ide> pooled_output = text_outputs[1] <ide> text_features = self.text_projection(inputs=pooled_output) <ide> <ide> return text_features <ide> <add> @unpack_inputs <ide> def get_image_features( <ide> self, <ide> pixel_values: Optional[TFModelInputType] = None, <ide> def get_image_features( <ide> training: bool = False, <ide> **kwargs, <ide> ) -> tf.Tensor: <del> inputs = input_processing( <del> func=self.get_image_features, <del> config=self.config, <del> input_ids=pixel_values, <add> if pixel_values is None: <add> raise ValueError("You have to specify pixel_values") <add> <add> vision_outputs = self.vision_model( <add> pixel_values=pixel_values, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> if "input_ids" in inputs: <del> inputs["pixel_values"] = inputs.pop("input_ids") <del> <del> if inputs["pixel_values"] is None: <del> raise ValueError("You have to specify pixel_values") <del> <del> vision_outputs = self.vision_model( <del> pixel_values=inputs["pixel_values"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> <ide> pooled_output = vision_outputs[1] # pooled_output <ide> image_features = self.visual_projection(inputs=pooled_output) <ide> <ide> return image_features <ide> <add> @unpack_inputs <ide> def call( <ide> self, <ide> input_ids: Optional[TFModelInputType] = None, <ide> def call( <ide> training: bool = False, <ide> **kwargs, <ide> ) -> Union[TFCLIPOutput, Tuple[tf.Tensor]]: <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=input_ids, <del> pixel_values=pixel_values, <del> attention_mask=attention_mask, <del> position_ids=position_ids, <del> return_loss=return_loss, <del> output_attentions=output_attentions, <del> output_hidden_states=output_hidden_states, <del> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <ide> <del> if inputs["input_ids"] is None: <add> if input_ids is None: <ide> raise ValueError("You have to specify either input_ids") <del> if inputs["pixel_values"] is None: <add> if pixel_values is None: <ide> raise ValueError("You have to specify pixel_values") <ide> <del> input_shape = shape_list(inputs["input_ids"]) <add> input_shape = shape_list(input_ids) <ide> <del> if inputs["attention_mask"] is None: <del> inputs["attention_mask"] = tf.fill(dims=input_shape, value=1) <add> if attention_mask is None: <add> attention_mask = tf.fill(dims=input_shape, value=1) <ide> <ide> vision_outputs = self.vision_model( <del> pixel_values=inputs["pixel_values"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <add> pixel_values=pixel_values, <add> output_attentions=output_attentions, <add> output_hidden_states=output_hidden_states, <add> return_dict=return_dict, <add> training=training, <ide> ) <ide> <ide> text_outputs = self.text_model( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> position_ids=inputs["position_ids"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <add> input_ids=input_ids, <add> attention_mask=attention_mask, <add> position_ids=position_ids, <add> output_attentions=output_attentions, <add> output_hidden_states=output_hidden_states, <add> return_dict=return_dict, <add> training=training, <ide> ) <ide> <ide> image_embeds = vision_outputs[1] <ide> def call( <ide> logits_per_image = tf.transpose(logits_per_text) <ide> <ide> loss = None <del> if inputs["return_loss"]: <add> if return_loss: <ide> loss = clip_loss(logits_per_text) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs) <ide> return (loss,) + output if loss is not None else output <ide> <ide> def __init__(self, config: CLIPTextConfig, *inputs, **kwargs): <ide> <ide> self.clip = TFCLIPTextMainLayer(config, name="clip") <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=CLIPTextConfig) <ide> def call( <ide> def call( <ide> >>> last_hidden_state = outputs.last_hidden_state <ide> >>> pooled_output = outputs.pooler_output # pooled (EOS token) states <ide> ```""" <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> <add> outputs = self.clip( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> position_ids=position_ids, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> outputs = self.clip( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> position_ids=inputs["position_ids"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> <ide> return outputs <ide> def serving(self, inputs): <ide> <ide> return self.serving_output(output) <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING) <ide> @replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=CLIPVisionConfig) <ide> def call( <ide> def call( <ide> >>> last_hidden_state = outputs.last_hidden_state <ide> >>> pooled_output = outputs.pooler_output # pooled CLS states <ide> ```""" <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=pixel_values, <add> <add> outputs = self.clip( <add> pixel_values=pixel_values, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> if "input_ids" in inputs: <del> inputs["pixel_values"] = inputs.pop("input_ids") <del> <del> outputs = self.clip( <del> pixel_values=inputs["pixel_values"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> <ide> return outputs <ide> def serving(self, inputs): <ide> <ide> return self.serving_output(output) <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> def get_text_features( <ide> self, <ide> def get_text_features( <ide> >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf") <ide> >>> text_features = model.get_text_features(**inputs) <ide> ```""" <del> inputs = input_processing( <del> func=self.get_text_features, <del> config=self.config, <add> <add> text_features = self.clip.get_text_features( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> position_ids=position_ids, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> text_features = self.clip.get_text_features( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> position_ids=inputs["position_ids"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <ide> ) <ide> <ide> return text_features <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING) <ide> def get_image_features( <ide> self, <ide> def get_image_features( <ide> <ide> >>> image_features = model.get_image_features(**inputs) <ide> ```""" <del> inputs = input_processing( <del> func=self.get_image_features, <del> config=self.config, <del> input_ids=pixel_values, <add> <add> image_features = self.clip.get_image_features( <add> pixel_values=pixel_values, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> if "input_ids" in inputs: <del> inputs["pixel_values"] = inputs.pop("input_ids") <del> <del> image_features = self.clip.get_image_features( <del> pixel_values=inputs["pixel_values"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <ide> ) <ide> <ide> return image_features <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @replace_return_docstrings(output_type=TFCLIPOutput, config_class=CLIPConfig) <ide> def call( <ide> def call( <ide> >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score <ide> >>> probs = tf.nn.softmax(logits_per_image, axis=1) # we can take the softmax to get the label probabilities <ide> ```""" <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> <add> outputs = self.clip( <ide> input_ids=input_ids, <ide> pixel_values=pixel_values, <ide> attention_mask=attention_mask, <ide> def call( <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> outputs = self.clip( <del> input_ids=inputs["input_ids"], <del> pixel_values=inputs["pixel_values"], <del> attention_mask=inputs["attention_mask"], <del> position_ids=inputs["position_ids"], <del> return_loss=inputs["return_loss"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <ide> ) <ide> <ide> return outputs
1
Text
Text
remove repeated word in modules.md
01e158c600d451bcbb3da4d276a9e61dcc84ebe4
<ide><path>doc/api/modules.md <ide> added: v13.7.0 <ide> <ide> > Stability: 1 - Experimental <ide> <del>Helpers for for interacting with the source map cache. This cache is <add>Helpers for interacting with the source map cache. This cache is <ide> populated when source map parsing is enabled and <ide> [source map include directives][] are found in a modules' footer. <ide>
1
PHP
PHP
update doc block
672761ca3828220dee3279a8f630784ae68c9f2d
<ide><path>src/Illuminate/Support/Facades/Cache.php <ide> * @method static bool missing(string $key) <ide> * @method static mixed get(string $key, mixed $default = null) <ide> * @method static mixed pull(string $key, mixed $default = null) <del> * @method static bool put(string $key, $value, \DateTimeInterface|\DateInterval|int $ttl) <del> * @method static bool add(string $key, $value, \DateTimeInterface|\DateInterval|int $ttl) <add> * @method static bool put(string $key, $value, \DateTimeInterface|\DateInterval|int $ttl = null) <add> * @method static bool add(string $key, $value, \DateTimeInterface|\DateInterval|int $ttl = null) <ide> * @method static int|bool increment(string $key, $value = 1) <ide> * @method static int|bool decrement(string $key, $value = 1) <ide> * @method static bool forever(string $key, $value)
1
Javascript
Javascript
destroy the socket on parse error
ff7d053ae6b7f620516049e5c9bd1b6ab348835f
<ide><path>lib/_http_server.js <ide> function socketOnError(e) { <ide> <ide> if (!this.server.emit('clientError', e, this)) { <ide> if (this.writable) { <del> this.end(badRequestResponse); <del> return; <add> this.write(badRequestResponse); <ide> } <ide> this.destroy(e); <ide> } <ide><path>test/parallel/test-http-server-destroy-socket-on-client-error.js <add>'use strict'; <add> <add>const { expectsError, mustCall } = require('../common'); <add> <add>// Test that the request socket is destroyed if the `'clientError'` event is <add>// emitted and there is no listener for it. <add> <add>const assert = require('assert'); <add>const { createServer } = require('http'); <add>const { createConnection } = require('net'); <add> <add>const server = createServer(); <add> <add>server.on('connection', mustCall((socket) => { <add> socket.on('error', expectsError({ <add> type: Error, <add> message: 'Parse Error', <add> code: 'HPE_INVALID_METHOD', <add> bytesParsed: 0, <add> rawPacket: Buffer.from('FOO /\r\n') <add> })); <add>})); <add> <add>server.listen(0, () => { <add> const chunks = []; <add> const socket = createConnection({ <add> allowHalfOpen: true, <add> port: server.address().port <add> }); <add> <add> socket.on('connect', mustCall(() => { <add> socket.write('FOO /\r\n'); <add> })); <add> <add> socket.on('data', (chunk) => { <add> chunks.push(chunk); <add> }); <add> <add> socket.on('end', mustCall(() => { <add> const expected = Buffer.from('HTTP/1.1 400 Bad Request\r\n\r\n'); <add> assert(Buffer.concat(chunks).equals(expected)); <add> <add> server.close(); <add> })); <add>});
2
Mixed
Javascript
expose image cache interrogation to js
69c889815e7dfede6503be7cb20c6515f503116e
<ide><path>Libraries/Image/Image.android.js <ide> var Image = React.createClass({ <ide> abortPrefetch(requestId: number) { <ide> ImageLoader.abortRequest(requestId); <ide> }, <add> <add> /** <add> * Perform cache interrogation. <add> * <add> * @param urls the list of image URLs to check the cache for. <add> * @return a mapping from url to cache status, such as "disk" or "memory". If a requested URL is <add> * not in the mapping, it means it's not in the cache. <add> */ <add> async queryCache(urls: Array<string>): Promise<Map<string, 'memory' | 'disk'>> { <add> return await ImageLoader.queryCache(urls); <add> } <ide> }, <ide> <ide> mixins: [NativeMethodsMixin], <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/image/ImageLoaderModule.java <ide> import com.facebook.datasource.DataSource; <ide> import com.facebook.datasource.DataSubscriber; <ide> import com.facebook.drawee.backends.pipeline.Fresco; <add>import com.facebook.imagepipeline.core.ImagePipeline; <ide> import com.facebook.imagepipeline.image.CloseableImage; <ide> import com.facebook.imagepipeline.request.ImageRequest; <ide> import com.facebook.imagepipeline.request.ImageRequestBuilder; <ide> import com.facebook.react.bridge.Arguments; <add>import com.facebook.react.bridge.GuardedAsyncTask; <ide> import com.facebook.react.bridge.LifecycleEventListener; <ide> import com.facebook.react.bridge.Promise; <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> import com.facebook.react.bridge.ReactContextBaseJavaModule; <ide> import com.facebook.react.bridge.ReactMethod; <add>import com.facebook.react.bridge.ReadableArray; <ide> import com.facebook.react.bridge.WritableMap; <ide> <ide> public class ImageLoaderModule extends ReactContextBaseJavaModule implements <ide> public void abortRequest(final int requestId) { <ide> } <ide> } <ide> <add> @ReactMethod <add> public void queryCache(final ReadableArray uris, final Promise promise) { <add> // perform cache interrogation in async task as disk cache checks are expensive <add> new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { <add> @Override <add> protected void doInBackgroundGuarded(Void... params) { <add> WritableMap result = Arguments.createMap(); <add> ImagePipeline imagePipeline = Fresco.getImagePipeline(); <add> for (int i = 0; i < uris.size(); i++) { <add> String uriString = uris.getString(i); <add> final Uri uri = Uri.parse(uriString); <add> if (imagePipeline.isInBitmapMemoryCache(uri)) { <add> result.putString(uriString, "memory"); <add> } else if (imagePipeline.isInDiskCacheSync(uri)) { <add> result.putString(uriString, "disk"); <add> } <add> } <add> promise.resolve(result); <add> } <add> }.executeOnExecutor(GuardedAsyncTask.THREAD_POOL_EXECUTOR); <add> } <add> <ide> private void registerRequest(int requestId, DataSource<Void> request) { <ide> synchronized (mEnqueuedRequestMonitor) { <ide> mEnqueuedRequests.put(requestId, request);
2
Javascript
Javascript
increase updatepreview delay
02753514903ee304bb4dbf51a09e39ef84de6a84
<ide><path>client/commonFramework/update-preview.js <ide> window.common = (function(global) { <ide> return Observable.fromCallback($(preview).ready, $(preview))() <ide> .first() <ide> // delay is need here for first initial run <del> .delay(50); <add> .delay(100); <ide> }) <ide> .map(() => code); <ide> };
1
PHP
PHP
fix cs - psr12
4d1e628624ca523cbe62d80c38d392b4aeb22f97
<ide><path>tests/TestCase/Auth/Storage/MemoryStorageTest.php <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> <del> $this->storage = new MemoryStorage; <add> $this->storage = new MemoryStorage(); <ide> $this->user = ['username' => 'giantGummyLizard']; <ide> } <ide> <ide><path>tests/TestCase/Console/CommandTest.php <ide> public function testExecuteCommandInstanceInvalid() <ide> $this->expectExceptionMessage("Command 'stdClass' is not a subclass"); <ide> <ide> $command = new Command(); <del> $command->executeCommand(new \stdClass, [], $this->getMockIo(new ConsoleOutput())); <add> $command->executeCommand(new \stdClass(), [], $this->getMockIo(new ConsoleOutput())); <ide> } <ide> <ide> protected function getMockIo($output) <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testRenderViewChangesResponse() <ide> */ <ide> public function testBeforeRenderCallbackChangingViewClass() <ide> { <del> $Controller = new Controller(new ServerRequest, new Response()); <add> $Controller = new Controller(new ServerRequest(), new Response()); <ide> <ide> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) { <ide> $controller = $event->getSubject(); <ide> public function testBeforeRenderCallbackChangingViewClass() <ide> */ <ide> public function testBeforeRenderEventCancelsRender() <ide> { <del> $Controller = new Controller(new ServerRequest, new Response()); <add> $Controller = new Controller(new ServerRequest(), new Response()); <ide> <ide> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) { <ide> return false; <ide> public function testRedirectBeforeRedirectListenerReturnResponse() <ide> ->getMock(); <ide> $Controller = new Controller(null, $Response); <ide> <del> $newResponse = new Response; <add> $newResponse = new Response(); <ide> $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) use ($newResponse) { <ide> return $newResponse; <ide> }); <ide> public function testResponse() <ide> $controller = new PostsController(); <ide> $this->assertInstanceOf(Response::class, $controller->getResponse()); <ide> <del> $response = new Response; <add> $response = new Response(); <ide> $this->assertSame($controller, $controller->setResponse($response)); <ide> $this->assertSame($response, $controller->getResponse()); <ide> } <ide><path>tests/TestCase/Controller/Exception/AuthSecurityExceptionTest.php <ide> class AuthSecurityExceptionTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> $this->authSecurityException = new AuthSecurityException; <add> $this->authSecurityException = new AuthSecurityException(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Controller/Exception/SecurityExceptionTest.php <ide> class SecurityExceptionTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> $this->securityException = new SecurityException; <add> $this->securityException = new SecurityException(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Core/FunctionsTest.php <ide> public function hInputProvider() <ide> [null, null], <ide> [1, 1], <ide> [1.1, 1.1], <del> [new \stdClass, '(object)stdClass'], <add> [new \stdClass(), '(object)stdClass'], <ide> [new Response(), ''], <ide> [['clean', '"clean-me'], ['clean', '&quot;clean-me']], <ide> ]; <ide><path>tests/TestCase/Database/ConnectionTest.php <ide> public function testGetLoggerDefault() <ide> public function testSetLogger() <ide> { <ide> $this->deprecated(function () { <del> $logger = new QueryLogger; <add> $logger = new QueryLogger(); <ide> $this->connection->logger($logger); <ide> $this->assertSame($logger, $this->connection->logger()); <ide> }); <ide> public function testGetAndSetLogger() <ide> */ <ide> public function testLoggerDecorator() <ide> { <del> $logger = new QueryLogger; <add> $logger = new QueryLogger(); <ide> $this->connection->enableQueryLogging(true); <ide> $this->connection->setLogger($logger); <ide> $st = $this->connection->prepare('SELECT 1'); <ide> public function testTransactionalWithException() <ide> $connection->expects($this->never())->method('commit'); <ide> $connection->transactional(function ($conn) use ($connection) { <ide> $this->assertSame($connection, $conn); <del> throw new \InvalidArgumentException; <add> throw new \InvalidArgumentException(); <ide> }); <ide> } <ide> <ide><path>tests/TestCase/Database/DriverTest.php <ide> public function testCompileQuery() <ide> ->disableOriginalConstructor() <ide> ->getMock(); <ide> <del> $result = $driver->compileQuery($query, new ValueBinder); <add> $result = $driver->compileQuery($query, new ValueBinder()); <ide> <ide> $this->assertInternalType('array', $result); <ide> $this->assertSame($query, $result[0]); <ide><path>tests/TestCase/Database/Expression/FunctionExpressionTest.php <ide> class FunctionExpressionTest extends TestCase <ide> public function testArityZero() <ide> { <ide> $f = new FunctionExpression('MyFunction'); <del> $this->assertEquals('MyFunction()', $f->sql(new ValueBinder)); <add> $this->assertEquals('MyFunction()', $f->sql(new ValueBinder())); <ide> } <ide> <ide> /** <ide> public function testArityZero() <ide> public function testArityMultiplePlainValues() <ide> { <ide> $f = new FunctionExpression('MyFunction', ['foo', 'bar']); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $this->assertEquals('MyFunction(:param0, :param1)', $f->sql($binder)); <ide> <ide> $this->assertEquals('foo', $binder->bindings()[':param0']['value']); <ide> $this->assertEquals('bar', $binder->bindings()[':param1']['value']); <ide> <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $f = new FunctionExpression('MyFunction', ['bar']); <ide> $this->assertEquals('MyFunction(:param0)', $f->sql($binder)); <ide> $this->assertEquals('bar', $binder->bindings()[':param0']['value']); <ide> public function testArityMultiplePlainValues() <ide> */ <ide> public function testLiteralParams() <ide> { <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $f = new FunctionExpression('MyFunction', ['foo' => 'literal', 'bar']); <ide> $this->assertEquals('MyFunction(foo, :param0)', $f->sql($binder)); <ide> } <ide> public function testLiteralParams() <ide> */ <ide> public function testFunctionNesting() <ide> { <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $f = new FunctionExpression('MyFunction', ['foo', 'bar']); <ide> $g = new FunctionExpression('Wrapper', ['bar' => 'literal', $f]); <ide> $this->assertEquals('Wrapper(bar, MyFunction(:param0, :param1))', $g->sql($binder)); <ide> public function testFunctionNesting() <ide> */ <ide> public function testFunctionNestingQueryExpression() <ide> { <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $q = new QueryExpression('a'); <ide> $f = new FunctionExpression('MyFunction', [$q]); <ide> $this->assertEquals('MyFunction(a)', $f->sql($binder)); <ide> public function testFunctionWithDatabaseQuery() <ide> ->newQuery() <ide> ->select(['column']); <ide> <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $function = new FunctionExpression('MyFunction', [$query]); <ide> $this->assertEquals( <ide> 'MyFunction((SELECT column))', <ide> public function testFunctionWithOrmQuery() <ide> ->find() <ide> ->select(['column']); <ide> <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $function = new FunctionExpression('MyFunction', [$query]); <ide> $this->assertEquals( <ide> 'MyFunction((SELECT Articles.column AS Articles__column FROM articles Articles))', <ide> public function testFunctionWithOrmQuery() <ide> */ <ide> public function testNumericLiteral() <ide> { <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $f = new FunctionExpression('MyFunction', ['a_field' => 'literal', '32' => 'literal']); <ide> $this->assertEquals('MyFunction(a_field, 32)', $f->sql($binder)); <ide> <ide><path>tests/TestCase/Database/Expression/IdentifierExpressionTest.php <ide> public function testGetAndSet() <ide> public function testSQL() <ide> { <ide> $expression = new IdentifierExpression('foo'); <del> $this->assertEquals('foo', $expression->sql(new ValueBinder)); <add> $this->assertEquals('foo', $expression->sql(new ValueBinder())); <ide> } <ide> } <ide><path>tests/TestCase/Database/Expression/TupleComparisonTest.php <ide> class TupleComparisonTest extends TestCase <ide> public function testsSimpleTuple() <ide> { <ide> $f = new TupleComparison(['field1', 'field2'], [1, 2], ['integer', 'integer'], '='); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $this->assertEquals('(field1, field2) = (:tuple0, :tuple1)', $f->sql($binder)); <ide> $this->assertSame(1, $binder->bindings()[':tuple0']['value']); <ide> $this->assertSame(2, $binder->bindings()[':tuple1']['value']); <ide> public function testTupleWithExpressionFields() <ide> { <ide> $field1 = new QueryExpression(['a' => 1]); <ide> $f = new TupleComparison([$field1, 'field2'], [4, 5], ['integer', 'integer'], '>'); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $this->assertEquals('(a = :c0, field2) > (:tuple1, :tuple2)', $f->sql($binder)); <ide> $this->assertSame(1, $binder->bindings()[':c0']['value']); <ide> $this->assertSame(4, $binder->bindings()[':tuple1']['value']); <ide> public function testTupleWithExpressionValues() <ide> { <ide> $value1 = new QueryExpression(['a' => 1]); <ide> $f = new TupleComparison(['field1', 'field2'], [$value1, 2], ['integer', 'integer'], '='); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $this->assertEquals('(field1, field2) = (a = :c0, :tuple1)', $f->sql($binder)); <ide> $this->assertSame(1, $binder->bindings()[':c0']['value']); <ide> $this->assertSame(2, $binder->bindings()[':tuple1']['value']); <ide> public function testTupleWithInComparison() <ide> ['integer', 'integer'], <ide> 'IN' <ide> ); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $this->assertEquals('(field1, field2) IN ((:tuple0,:tuple1), (:tuple2,:tuple3))', $f->sql($binder)); <ide> $this->assertSame(1, $binder->bindings()[':tuple0']['value']); <ide> $this->assertSame(2, $binder->bindings()[':tuple1']['value']); <ide> public function testTraverse() <ide> $value1 = new QueryExpression(['a' => 1]); <ide> $field2 = new QueryExpression(['b' => 2]); <ide> $f = new TupleComparison(['field1', $field2], [$value1, 2], ['integer', 'integer'], '='); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $expressions = []; <ide> <ide> $collector = function ($e) use (&$expressions) { <ide> public function testValueAsSingleExpression() <ide> { <ide> $value = new QueryExpression('SELECT 1, 1'); <ide> $f = new TupleComparison(['field1', 'field2'], $value); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $this->assertEquals('(field1, field2) = (SELECT 1, 1)', $f->sql($binder)); <ide> } <ide> <ide> public function testFieldAsSingleExpression() <ide> { <ide> $value = [1, 1]; <ide> $f = new TupleComparison(new QueryExpression('a, b'), $value); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $this->assertEquals('(a, b) = (:tuple0, :tuple1)', $f->sql($binder)); <ide> } <ide> } <ide><path>tests/TestCase/Database/ExpressionTypeCastingTest.php <ide> class ExpressionTypeCastingTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> Type::set('test', new TestType); <add> Type::set('test', new TestType()); <ide> } <ide> <ide> /** <ide> public function setUp() <ide> public function testComparisonSimple() <ide> { <ide> $comparison = new Comparison('field', 'the thing', 'test', '='); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $sql = $comparison->sql($binder); <ide> $this->assertEquals('field = (CONCAT(:param0, :param1))', $sql); <ide> $this->assertEquals('the thing', $binder->bindings()[':param0']['value']); <ide> public function testComparisonSimple() <ide> public function testComparisonMultiple() <ide> { <ide> $comparison = new Comparison('field', ['2', '3'], 'test[]', 'IN'); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $sql = $comparison->sql($binder); <ide> $this->assertEquals('field IN (CONCAT(:param0, :param1),CONCAT(:param2, :param3))', $sql); <ide> $this->assertEquals('2', $binder->bindings()[':param0']['value']); <ide> public function testComparisonMultiple() <ide> public function testBetween() <ide> { <ide> $between = new BetweenExpression('field', 'from', 'to', 'test'); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $sql = $between->sql($binder); <ide> $this->assertEquals('field BETWEEN CONCAT(:param0, :param1) AND CONCAT(:param2, :param3)', $sql); <ide> $this->assertEquals('from', $binder->bindings()[':param0']['value']); <ide> public function testCaseExpression() <ide> ['test', 'test'] <ide> ); <ide> <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $sql = $case->sql($binder); <ide> $this->assertEquals('CASE WHEN foo = :c0 THEN CONCAT(:param1, :param2) ELSE CONCAT(:param3, :param4) END', $sql); <ide> <ide> public function testCaseExpression() <ide> public function testFunctionExpression() <ide> { <ide> $function = new FunctionExpression('DATE', ['2016-01'], ['test']); <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $sql = $function->sql($binder); <ide> $this->assertEquals('DATE(CONCAT(:param0, :param1))', $sql); <ide> $this->assertEquals('2016-01', $binder->bindings()[':param0']['value']); <ide> public function testValuesExpression() <ide> $values->add(['title' => 'foo']); <ide> $values->add(['title' => 'bar']); <ide> <del> $binder = new ValueBinder; <add> $binder = new ValueBinder(); <ide> $sql = $values->sql($binder); <ide> $this->assertEquals( <ide> ' VALUES ((CONCAT(:param0, :param1))), ((CONCAT(:param2, :param3)))', <ide><path>tests/TestCase/Database/FunctionsBuilderTest.php <ide> class FunctionsBuilderTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> $this->functions = new FunctionsBuilder; <add> $this->functions = new FunctionsBuilder(); <ide> } <ide> <ide> /** <ide> public function testArbitrary() <ide> $function = $this->functions->MyFunc(['b' => 'literal']); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <ide> $this->assertEquals('MyFunc', $function->getName()); <del> $this->assertEquals('MyFunc(b)', $function->sql(new ValueBinder)); <add> $this->assertEquals('MyFunc(b)', $function->sql(new ValueBinder())); <ide> <ide> $function = $this->functions->MyFunc(['b'], ['string'], 'integer'); <ide> $this->assertEquals('integer', $function->getReturnType()); <ide> public function testSum() <ide> { <ide> $function = $this->functions->sum('total'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('SUM(total)', $function->sql(new ValueBinder)); <add> $this->assertEquals('SUM(total)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('float', $function->getReturnType()); <ide> <ide> $function = $this->functions->sum('total', ['integer']); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('SUM(total)', $function->sql(new ValueBinder)); <add> $this->assertEquals('SUM(total)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('integer', $function->getReturnType()); <ide> } <ide> <ide> public function testAvg() <ide> { <ide> $function = $this->functions->avg('salary'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('AVG(salary)', $function->sql(new ValueBinder)); <add> $this->assertEquals('AVG(salary)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('float', $function->getReturnType()); <ide> } <ide> <ide> public function testMAX() <ide> { <ide> $function = $this->functions->max('created', ['datetime']); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('MAX(created)', $function->sql(new ValueBinder)); <add> $this->assertEquals('MAX(created)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('datetime', $function->getReturnType()); <ide> } <ide> <ide> public function testMin() <ide> { <ide> $function = $this->functions->min('created', ['date']); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('MIN(created)', $function->sql(new ValueBinder)); <add> $this->assertEquals('MIN(created)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('date', $function->getReturnType()); <ide> } <ide> <ide> public function testCount() <ide> { <ide> $function = $this->functions->count('*'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('COUNT(*)', $function->sql(new ValueBinder)); <add> $this->assertEquals('COUNT(*)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('integer', $function->getReturnType()); <ide> } <ide> <ide> public function testConcat() <ide> { <ide> $function = $this->functions->concat(['title' => 'literal', ' is a string']); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('CONCAT(title, :param0)', $function->sql(new ValueBinder)); <add> $this->assertEquals('CONCAT(title, :param0)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('string', $function->getReturnType()); <ide> } <ide> <ide> public function testCoalesce() <ide> { <ide> $function = $this->functions->coalesce(['NULL' => 'literal', '1', 'a'], ['a' => 'date']); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('COALESCE(NULL, :param0, :param1)', $function->sql(new ValueBinder)); <add> $this->assertEquals('COALESCE(NULL, :param0, :param1)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('date', $function->getReturnType()); <ide> } <ide> <ide> public function testNow() <ide> { <ide> $function = $this->functions->now(); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('NOW()', $function->sql(new ValueBinder)); <add> $this->assertEquals('NOW()', $function->sql(new ValueBinder())); <ide> $this->assertEquals('datetime', $function->getReturnType()); <ide> <ide> $function = $this->functions->now('date'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('CURRENT_DATE()', $function->sql(new ValueBinder)); <add> $this->assertEquals('CURRENT_DATE()', $function->sql(new ValueBinder())); <ide> $this->assertEquals('date', $function->getReturnType()); <ide> <ide> $function = $this->functions->now('time'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('CURRENT_TIME()', $function->sql(new ValueBinder)); <add> $this->assertEquals('CURRENT_TIME()', $function->sql(new ValueBinder())); <ide> $this->assertEquals('time', $function->getReturnType()); <ide> } <ide> <ide> public function testExtract() <ide> { <ide> $function = $this->functions->extract('day', 'created'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('EXTRACT(day FROM created)', $function->sql(new ValueBinder)); <add> $this->assertEquals('EXTRACT(day FROM created)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('integer', $function->getReturnType()); <ide> <ide> $function = $this->functions->datePart('year', 'modified'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('EXTRACT(year FROM modified)', $function->sql(new ValueBinder)); <add> $this->assertEquals('EXTRACT(year FROM modified)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('integer', $function->getReturnType()); <ide> } <ide> <ide> public function testDateAdd() <ide> { <ide> $function = $this->functions->dateAdd('created', -3, 'day'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('DATE_ADD(created, INTERVAL -3 day)', $function->sql(new ValueBinder)); <add> $this->assertEquals('DATE_ADD(created, INTERVAL -3 day)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('datetime', $function->getReturnType()); <ide> } <ide> <ide> public function testDayOfWeek() <ide> { <ide> $function = $this->functions->dayOfWeek('created'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('DAYOFWEEK(created)', $function->sql(new ValueBinder)); <add> $this->assertEquals('DAYOFWEEK(created)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('integer', $function->getReturnType()); <ide> <ide> $function = $this->functions->weekday('created'); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('DAYOFWEEK(created)', $function->sql(new ValueBinder)); <add> $this->assertEquals('DAYOFWEEK(created)', $function->sql(new ValueBinder())); <ide> $this->assertEquals('integer', $function->getReturnType()); <ide> } <ide> <ide> public function testRand() <ide> { <ide> $function = $this->functions->rand(); <ide> $this->assertInstanceOf('Cake\Database\Expression\FunctionExpression', $function); <del> $this->assertEquals('RAND()', $function->sql(new ValueBinder)); <add> $this->assertEquals('RAND()', $function->sql(new ValueBinder())); <ide> $this->assertEquals('float', $function->getReturnType()); <ide> } <ide> } <ide><path>tests/TestCase/Database/Log/LoggedQueryTest.php <ide> class LoggedQueryTest extends TestCase <ide> */ <ide> public function testStringConversion() <ide> { <del> $logged = new LoggedQuery; <add> $logged = new LoggedQuery(); <ide> $logged->query = 'SELECT foo FROM bar'; <ide> $this->assertEquals('duration=0 rows=0 SELECT foo FROM bar', (string)$logged); <ide> } <ide><path>tests/TestCase/Database/Log/QueryLoggerTest.php <ide> public function testStringInterpolation() <ide> $logger = $this->getMockBuilder('\Cake\Database\Log\QueryLogger') <ide> ->setMethods(['_log']) <ide> ->getMock(); <del> $query = new LoggedQuery; <add> $query = new LoggedQuery(); <ide> $query->query = 'SELECT a FROM b where a = :p1 AND b = :p2 AND c = :p3 AND d = :p4 AND e = :p5 AND f = :p6'; <ide> $query->params = ['p1' => 'string', 'p3' => null, 'p2' => 3, 'p4' => true, 'p5' => false, 'p6' => 0]; <ide> <ide> public function testStringInterpolationNotNamed() <ide> $logger = $this->getMockBuilder('\Cake\Database\Log\QueryLogger') <ide> ->setMethods(['_log']) <ide> ->getMock(); <del> $query = new LoggedQuery; <add> $query = new LoggedQuery(); <ide> $query->query = 'SELECT a FROM b where a = ? AND b = ? AND c = ? AND d = ? AND e = ? AND f = ?'; <ide> $query->params = ['string', '3', null, true, false, 0]; <ide> <ide> public function testStringInterpolationDuplicate() <ide> $logger = $this->getMockBuilder('\Cake\Database\Log\QueryLogger') <ide> ->setMethods(['_log']) <ide> ->getMock(); <del> $query = new LoggedQuery; <add> $query = new LoggedQuery(); <ide> $query->query = 'SELECT a FROM b where a = :p1 AND b = :p1 AND c = :p2 AND d = :p2'; <ide> $query->params = ['p1' => 'string', 'p2' => 3]; <ide> <ide> public function testStringInterpolationNamed() <ide> $logger = $this->getMockBuilder('\Cake\Database\Log\QueryLogger') <ide> ->setMethods(['_log']) <ide> ->getMock(); <del> $query = new LoggedQuery; <add> $query = new LoggedQuery(); <ide> $query->query = 'SELECT a FROM b where a = :p1 AND b = :p11 AND c = :p20 AND d = :p2'; <ide> $query->params = ['p11' => 'test', 'p1' => 'string', 'p2' => 3, 'p20' => 5]; <ide> <ide> public function testStringInterpolationSpecialChars() <ide> $logger = $this->getMockBuilder('\Cake\Database\Log\QueryLogger') <ide> ->setMethods(['_log']) <ide> ->getMock(); <del> $query = new LoggedQuery; <add> $query = new LoggedQuery(); <ide> $query->query = 'SELECT a FROM b where a = :p1 AND b = :p2 AND c = :p3 AND d = :p4'; <ide> $query->params = ['p1' => '$2y$10$dUAIj', 'p2' => '$0.23', 'p3' => 'a\\0b\\1c\\d', 'p4' => "a'b"]; <ide> <ide> public function testStringInterpolationSpecialChars() <ide> */ <ide> public function testLogFunction() <ide> { <del> $logger = new QueryLogger; <del> $query = new LoggedQuery; <add> $logger = new QueryLogger(); <add> $query = new LoggedQuery(); <ide> $query->query = 'SELECT a FROM b where a = ? AND b = ? AND c = ?'; <ide> $query->params = ['string', '3', null]; <ide> <ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testUpdateArrayFields() <ide> { <ide> $this->loadFixtures('Comments'); <ide> $query = new Query($this->connection); <del> $date = new \DateTime; <add> $date = new \DateTime(); <ide> $query->update('comments') <ide> ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date']) <ide> ->where(['id' => 1]); <ide> public function testUpdateSetCallable() <ide> { <ide> $this->loadFixtures('Comments'); <ide> $query = new Query($this->connection); <del> $date = new \DateTime; <add> $date = new \DateTime(); <ide> $query->update('comments') <ide> ->set(function ($exp) use ($date) { <ide> return $exp <ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php <ide> public static function configProvider() <ide> 'instance' => 'Sqlite', <ide> 'database' => ':memory:', <ide> ]], <del> 'Direct instance' => [new FakeConnection], <add> 'Direct instance' => [new FakeConnection()], <ide> ]; <ide> } <ide> <ide> public function testParseDsnInvalid() <ide> */ <ide> public function testConfigWithObject() <ide> { <del> $connection = new FakeConnection; <add> $connection = new FakeConnection(); <ide> ConnectionManager::setConfig('test_variant', $connection); <ide> $this->assertSame($connection, ConnectionManager::get('test_variant')); <ide> } <ide> public function testConfigWithObject() <ide> */ <ide> public function testConfigWithCallable() <ide> { <del> $connection = new FakeConnection; <add> $connection = new FakeConnection(); <ide> $callable = function ($alias) use ($connection) { <ide> $this->assertEquals('test_variant', $alias); <ide> <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> public function testMissingRenderSafe() <ide> ->setMethods(['render']) <ide> ->getMock(); <ide> $controller->helpers = ['Fail', 'Boom']; <del> $controller->request = new ServerRequest; <add> $controller->request = new ServerRequest(); <ide> $controller->expects($this->at(0)) <ide> ->method('render') <ide> ->with('missingHelper') <ide> public function testRenderExceptionInBeforeRender() <ide> $controller = $this->getMockBuilder('Cake\Controller\Controller') <ide> ->setMethods(['beforeRender']) <ide> ->getMock(); <del> $controller->request = new ServerRequest; <add> $controller->request = new ServerRequest(); <ide> $controller->expects($this->any()) <ide> ->method('beforeRender') <ide> ->will($this->throwException($exception)); <ide> function (Event $event) { <ide> $event->getSubject()->viewBuilder()->setLayoutPath('boom'); <ide> } <ide> ); <del> $controller->setRequest(new ServerRequest); <add> $controller->setRequest(new ServerRequest()); <ide> <ide> $ExceptionRenderer->setController($controller); <ide> <ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php <ide> public function testRendererFactory() <ide> <ide> $factory = function ($exception) { <ide> $this->assertInstanceOf('LogicException', $exception); <del> $response = new Response; <add> $response = new Response(); <ide> $mock = $this->getMockBuilder('StdClass') <ide> ->setMethods(['render']) <ide> ->getMock(); <ide><path>tests/TestCase/Event/EventManagerTest.php <ide> public function testDispatch() <ide> public function testDispatchWithKeyName() <ide> { <ide> $manager = new EventManager(); <del> $listener = new EventTestListener; <add> $listener = new EventTestListener(); <ide> $manager->on('fake.event', [$listener, 'listenerFunction']); <ide> $event = 'fake.event'; <ide> $manager->dispatch($event); <ide> public function testDispatchWithKeyName() <ide> */ <ide> public function testDispatchReturnValue() <ide> { <del> $manager = new EventManager; <add> $manager = new EventManager(); <ide> $listener = $this->getMockBuilder(__NAMESPACE__ . '\EventTestListener') <ide> ->getMock(); <ide> $anotherListener = $this->getMockBuilder(__NAMESPACE__ . '\EventTestListener') <ide> public function testDispatchFalseStopsEvent() <ide> public function testDispatchPrioritized() <ide> { <ide> $manager = new EventManager(); <del> $listener = new EventTestListener; <add> $listener = new EventTestListener(); <ide> $manager->on('fake.event', [$listener, 'listenerFunction']); <ide> $manager->on('fake.event', ['priority' => 5], [$listener, 'secondListenerFunction']); <ide> $event = new Event('fake.event'); <ide><path>tests/TestCase/ExceptionsTest.php <ide> public function testPersistenceFailedException() <ide> $this->assertSame($previous, $exception->getPrevious()); <ide> $this->assertSame($entity, $exception->getEntity()); <ide> <del> $exception = new PersistenceFailedException(new Entity, 'message', null, $previous); <add> $exception = new PersistenceFailedException(new Entity(), 'message', null, $previous); <ide> $this->assertSame('message', $exception->getMessage()); <ide> $this->assertSame(500, $exception->getCode()); <ide> $this->assertSame($previous, $exception->getPrevious()); <ide><path>tests/TestCase/Http/ActionDispatcherTest.php <ide> public function testDispatchAfterDispatchEventModifyResponse() <ide> 'action' => 'index', <ide> 'pass' => [], <ide> ], <del> 'session' => new Session <add> 'session' => new Session() <ide> ]); <ide> $res = new Response(); <ide> $this->dispatcher->getEventManager()->on('Dispatcher.afterDispatch', function (Event $event) { <ide><path>tests/TestCase/Http/Client/Adapter/StreamTest.php <ide> class CakeStreamWrapper implements \ArrayAccess <ide> public function stream_open($path, $mode, $options, &$openedPath) <ide> { <ide> if ($path == 'http://throw_exception/') { <del> throw new \Exception; <add> throw new \Exception(); <ide> } <ide> <ide> $query = parse_url($path, PHP_URL_QUERY); <ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> public function testAllowMethodException() <ide> public function testSession() <ide> { <ide> $this->deprecated(function () { <del> $session = new Session; <add> $session = new Session(); <ide> $request = new ServerRequest(['session' => $session]); <ide> $this->assertSame($session, $request->session()); <ide> <ide> public function testSession() <ide> */ <ide> public function testGetSession() <ide> { <del> $session = new Session; <add> $session = new Session(); <ide> $request = new ServerRequest(['session' => $session]); <ide> $this->assertSame($session, $request->getSession()); <ide> <ide><path>tests/TestCase/Http/SessionTest.php <ide> public function testUsingPluginHandler() <ide> public function testEngineWithPreMadeInstance() <ide> { <ide> static::setAppNamespace(); <del> $engine = new \TestApp\Http\Session\TestAppLibSession; <add> $engine = new \TestApp\Http\Session\TestAppLibSession(); <ide> $session = new Session(['handler' => ['engine' => $engine]]); <ide> $this->assertSame($engine, $session->engine()); <ide> <ide><path>tests/TestCase/I18n/Parser/MoFileParserTest.php <ide> class MoFileParserTest extends TestCase <ide> */ <ide> public function testParse() <ide> { <del> $parser = new MoFileParser; <add> $parser = new MoFileParser(); <ide> $file = APP . 'Locale' . DS . 'rule_1_mo' . DS . 'core.mo'; <ide> $messages = $parser->parse($file); <ide> $this->assertCount(3, $messages); <ide> public function testParse() <ide> */ <ide> public function testParse0() <ide> { <del> $parser = new MoFileParser; <add> $parser = new MoFileParser(); <ide> $file = APP . 'Locale' . DS . 'rule_0_mo' . DS . 'core.mo'; <ide> $messages = $parser->parse($file); <ide> $this->assertCount(3, $messages); <ide> public function testParse0() <ide> */ <ide> public function testParse2() <ide> { <del> $parser = new MoFileParser; <add> $parser = new MoFileParser(); <ide> $file = APP . 'Locale' . DS . 'rule_9_mo' . DS . 'core.mo'; <ide> $messages = $parser->parse($file); <ide> $this->assertCount(3, $messages); <ide> public function testParse2() <ide> */ <ide> public function testParseFull() <ide> { <del> $parser = new MoFileParser; <add> $parser = new MoFileParser(); <ide> $file = APP . 'Locale' . DS . 'rule_0_mo' . DS . 'default.mo'; <ide> $messages = $parser->parse($file); <ide> $this->assertCount(5, $messages); <ide><path>tests/TestCase/I18n/Parser/PoFileParserTest.php <ide> public function tearDown() <ide> */ <ide> public function testParse() <ide> { <del> $parser = new PoFileParser; <add> $parser = new PoFileParser(); <ide> $file = APP . 'Locale' . DS . 'rule_1_po' . DS . 'default.po'; <ide> $messages = $parser->parse($file); <ide> $this->assertCount(8, $messages); <ide> public function testParse() <ide> */ <ide> public function testParseMultiLine() <ide> { <del> $parser = new PoFileParser; <add> $parser = new PoFileParser(); <ide> $file = APP . 'Locale' . DS . 'en' . DS . 'default.po'; <ide> $messages = $parser->parse($file); <ide> $this->assertCount(12, $messages); <ide> public function testParseMultiLine() <ide> */ <ide> public function testQuotedString() <ide> { <del> $parser = new PoFileParser; <add> $parser = new PoFileParser(); <ide> $file = APP . 'Locale' . DS . 'en' . DS . 'default.po'; <ide> $messages = $parser->parse($file); <ide> <ide><path>tests/TestCase/Log/Engine/FileLogTest.php <ide> public function testLogFileWriting() <ide> $result = file_get_contents(LOGS . 'random.log'); <ide> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Random: Test warning/', $result); <ide> <del> $object = new StringObject; <add> $object = new StringObject(); <ide> $log->log('debug', $object); <ide> $this->assertFileExists(LOGS . 'debug.log'); <ide> $result = file_get_contents(LOGS . 'debug.log'); <ide> $this->assertContains('Debug: Hey!', $result); <ide> <del> $object = new JsonObject; <add> $object = new JsonObject(); <ide> $log->log('debug', $object); <ide> $this->assertFileExists(LOGS . 'debug.log'); <ide> $result = file_get_contents(LOGS . 'debug.log'); <ide><path>tests/TestCase/Log/LogTest.php <ide> public function testSetConfigVariants($settings) <ide> public function testConfigInjectErrorOnWrongType() <ide> { <ide> $this->expectException(\RuntimeException::class); <del> Log::setConfig('test', new \StdClass); <add> Log::setConfig('test', new \StdClass()); <ide> Log::info('testing'); <ide> } <ide> <ide> public function testConfigInjectErrorOnWrongType() <ide> public function testSetConfigInjectErrorOnWrongType() <ide> { <ide> $this->expectException(\RuntimeException::class); <del> Log::setConfig('test', new \StdClass); <add> Log::setConfig('test', new \StdClass()); <ide> Log::info('testing'); <ide> } <ide> <ide> public function testWriteUnhandled() <ide> */ <ide> public function testCreateLoggerWithCallable() <ide> { <del> $instance = new FileLog; <add> $instance = new FileLog(); <ide> Log::setConfig('default', function ($alias) use ($instance) { <ide> $this->assertEquals('default', $alias); <ide> <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testSendRenderWithHelpers() <ide> $this->Email->setViewVars(['time' => $timestamp]); <ide> <ide> $result = $this->Email->send(); <del> $dateTime = new \DateTime; <add> $dateTime = new \DateTime(); <ide> $dateTime->setTimestamp($timestamp); <ide> $this->assertContains('Right now: ' . $dateTime->format($dateTime::ATOM), $result['message']); <ide> <ide><path>tests/TestCase/ORM/AssociationTest.php <ide> class AssociationTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> $this->source = new TestTable; <add> $this->source = new TestTable(); <ide> $config = [ <ide> 'className' => '\Cake\Test\TestCase\ORM\TestTable', <ide> 'foreignKey' => 'a_key', <ide> public function testBindingKeyDefault() <ide> */ <ide> public function testBindingDefaultNoOwningSide() <ide> { <del> $target = new Table; <add> $target = new Table(); <ide> $target->setPrimaryKey(['foo', 'site_id']); <ide> $this->association->setTarget($target); <ide> <ide> public function testTarget() <ide> $table = $this->association->target(); <ide> $this->assertInstanceOf(__NAMESPACE__ . '\TestTable', $table); <ide> <del> $other = new Table; <add> $other = new Table(); <ide> $this->association->target($other); <ide> $this->assertSame($other, $this->association->target()); <ide> }); <ide> public function testSetTarget() <ide> $table = $this->association->getTarget(); <ide> $this->assertInstanceOf(__NAMESPACE__ . '\TestTable', $table); <ide> <del> $other = new Table; <add> $other = new Table(); <ide> $this->assertSame($this->association, $this->association->setTarget($other)); <ide> $this->assertSame($other, $this->association->getTarget()); <ide> } <ide> public function testSource() <ide> $table = $this->association->source(); <ide> $this->assertSame($this->source, $table); <ide> <del> $other = new Table; <add> $other = new Table(); <ide> $this->association->source($other); <ide> $this->assertSame($other, $this->association->source()); <ide> }); <ide> public function testSetSource() <ide> $table = $this->association->getSource(); <ide> $this->assertSame($this->source, $table); <ide> <del> $other = new Table; <add> $other = new Table(); <ide> $this->assertSame($this->association, $this->association->setSource($other)); <ide> $this->assertSame($other, $this->association->getSource()); <ide> } <ide><path>tests/TestCase/ORM/Behavior/Translate/TranslateTraitTest.php <ide> class TranslateTraitTest extends TestCase <ide> */ <ide> public function testTranslationCreate() <ide> { <del> $entity = new TestEntity; <add> $entity = new TestEntity(); <ide> $entity->translation('eng')->set('title', 'My Title'); <ide> $this->assertEquals('My Title', $entity->translation('eng')->get('title')); <ide> <ide> public function testTranslationCreate() <ide> */ <ide> public function testTranslationModify() <ide> { <del> $entity = new TestEntity; <add> $entity = new TestEntity(); <ide> $entity->set('_translations', [ <ide> 'eng' => new Entity(['title' => 'My Title']), <ide> 'spa' => new Entity(['title' => 'Titulo']) <ide> public function testTranslationModify() <ide> */ <ide> public function testTranslationEmpty() <ide> { <del> $entity = new TestEntity; <add> $entity = new TestEntity(); <ide> $entity->set('_translations', [ <ide> 'eng' => new Entity(['title' => 'My Title']), <ide> 'spa' => new Entity(['title' => 'Titulo']) <ide> public function testTranslationEmpty() <ide> */ <ide> public function testTranslationDirty() <ide> { <del> $entity = new TestEntity; <add> $entity = new TestEntity(); <ide> $entity->set('_translations', [ <ide> 'eng' => new Entity(['title' => 'My Title']), <ide> 'spa' => new Entity(['title' => 'Titulo']) <ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php <ide> public function testSaveNewRecordWithTranslatesField() <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->addBehavior('Translate', [ <ide> 'fields' => ['title'], <del> 'validator' => (new \Cake\Validation\Validator)->add('title', 'notBlank', ['rule' => 'notBlank']) <add> 'validator' => (new \Cake\Validation\Validator())->add('title', 'notBlank', ['rule' => 'notBlank']) <ide> ]); <ide> $table->setEntityClass(__NAMESPACE__ . '\Article'); <ide> <ide> public function testSaveNewRecordWithOnlyTranslationsNotDefaultLocale() <ide> $table = $this->getTableLocator()->get('Groups'); <ide> $table->addBehavior('Translate', [ <ide> 'fields' => ['title'], <del> 'validator' => (new \Cake\Validation\Validator)->add('title', 'notBlank', ['rule' => 'notBlank']) <add> 'validator' => (new \Cake\Validation\Validator())->add('title', 'notBlank', ['rule' => 'notBlank']) <ide> ]); <ide> <ide> $data = [ <ide> public function testBuildMarshalMapBuildEntitiesValidationErrors() <ide> 'fields' => ['title', 'body'], <ide> 'validator' => 'custom' <ide> ]); <del> $validator = (new Validator)->add('title', 'notBlank', ['rule' => 'notBlank']); <add> $validator = (new Validator())->add('title', 'notBlank', ['rule' => 'notBlank']); <ide> $table->setValidator('custom', $validator); <ide> $translate = $table->behaviors()->get('Translate'); <ide> <ide> public function testBuildMarshalMapUpdateEntitiesValidationErrors() <ide> 'fields' => ['title', 'body'], <ide> 'validator' => 'custom' <ide> ]); <del> $validator = (new Validator)->add('title', 'notBlank', ['rule' => 'notBlank']); <add> $validator = (new Validator())->add('title', 'notBlank', ['rule' => 'notBlank']); <ide> $table->setValidator('custom', $validator); <ide> $translate = $table->behaviors()->get('Translate'); <ide> <ide><path>tests/TestCase/ORM/Locator/TableLocatorTest.php <ide> public function setUp() <ide> parent::setUp(); <ide> static::setAppNamespace(); <ide> <del> $this->_locator = new TableLocator; <add> $this->_locator = new TableLocator(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testValidateWithAssociationsAndCustomValidator() <ide> ] <ide> ] <ide> ]; <del> $validator = (new Validator)->add('body', 'numeric', ['rule' => 'numeric']); <add> $validator = (new Validator())->add('body', 'numeric', ['rule' => 'numeric']); <ide> $this->articles->setValidator('custom', $validator); <ide> <del> $validator2 = (new Validator)->requirePresence('thing'); <add> $validator2 = (new Validator())->requirePresence('thing'); <ide> $this->articles->Users->setValidator('customThing', $validator2); <ide> <ide> $this->articles->Comments->setValidator('default', $validator2); <ide> public function testSkipValidation() <ide> 'name' => 'Susan' <ide> ], <ide> ]; <del> $validator = (new Validator)->requirePresence('thing'); <add> $validator = (new Validator())->requirePresence('thing'); <ide> $this->articles->setValidator('default', $validator); <ide> $this->articles->Users->setValidator('default', $validator); <ide> <ide> public function testValidationWithInvalidFilled() <ide> 'title' => 'foo', <ide> 'number' => 'bar', <ide> ]; <del> $validator = (new Validator)->add('number', 'numeric', ['rule' => 'numeric']); <add> $validator = (new Validator())->add('number', 'numeric', ['rule' => 'numeric']); <ide> $marshall = new Marshaller($this->articles); <ide> $entity = $marshall->one($data, ['validate' => $validator]); <ide> $this->assertNotEmpty($entity->getError('number')); <ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function collectionMethodsProvider() <ide> ['shuffle', $identity], <ide> ['sample', $identity], <ide> ['take', 1], <del> ['append', new \ArrayIterator], <add> ['append', new \ArrayIterator()], <ide> ['compile', 1], <ide> ]; <ide> } <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testTableMethod() <ide> $table = new Table(['table' => 'users']); <ide> $this->assertEquals('users', $table->getTable()); <ide> <del> $table = new UsersTable; <add> $table = new UsersTable(); <ide> $this->assertEquals('users', $table->getTable()); <ide> <ide> $table = $this->getMockBuilder('\Cake\ORM\Table') <ide> public function testAliasMethod() <ide> $table = new Table(['table' => 'stuffs']); <ide> $this->assertEquals('stuffs', $table->alias()); <ide> <del> $table = new UsersTable; <add> $table = new UsersTable(); <ide> $this->assertEquals('Users', $table->alias()); <ide> <ide> $table = $this->getMockBuilder('\Cake\ORM\Table') <ide> public function testSetAlias() <ide> $table = new Table(['table' => 'stuffs']); <ide> $this->assertEquals('stuffs', $table->getAlias()); <ide> <del> $table = new UsersTable; <add> $table = new UsersTable(); <ide> $this->assertEquals('Users', $table->getAlias()); <ide> <ide> $table = $this->getMockBuilder('\Cake\ORM\Table') <ide> public function testTableClassNonExisting() <ide> { <ide> $this->expectException(\Cake\ORM\Exception\MissingEntityException::class); <ide> $this->expectExceptionMessage('Entity class FooUser could not be found.'); <del> $table = new Table; <add> $table = new Table(); <ide> $table->setEntityClass('FooUser'); <ide> } <ide> <ide> public function testTableClassNonExisting() <ide> */ <ide> public function testTableClassConventionForAPP() <ide> { <del> $table = new \TestApp\Model\Table\ArticlesTable; <add> $table = new \TestApp\Model\Table\ArticlesTable(); <ide> $this->assertEquals('TestApp\Model\Entity\Article', $table->getEntityClass()); <ide> } <ide> <ide> public function testTableClassConventionForAPP() <ide> public function testEntityClass() <ide> { <ide> $this->deprecated(function () { <del> $table = new Table; <add> $table = new Table(); <ide> $class = '\\' . $this->getMockClass('\Cake\ORM\Entity'); <ide> $table->entityClass($class); <ide> $this->assertEquals($class, $table->getEntityClass()); <ide> public function testEntityClass() <ide> */ <ide> public function testSetEntityClass() <ide> { <del> $table = new Table; <add> $table = new Table(); <ide> $class = '\\' . $this->getMockClass('\Cake\ORM\Entity'); <ide> $this->assertSame($table, $table->setEntityClass($class)); <ide> $this->assertEquals($class, $table->getEntityClass()); <ide> public function testAtomicSaveRollback() <ide> $connection->expects($this->once())->method('begin'); <ide> $connection->expects($this->once())->method('rollback'); <ide> $query->expects($this->once())->method('execute') <del> ->will($this->throwException(new \PDOException)); <add> ->will($this->throwException(new \PDOException())); <ide> <ide> $data = new Entity([ <ide> 'username' => 'superuser', <ide> public function testValidatorWithMissingMethod() <ide> */ <ide> public function testValidatorSetter() <ide> { <del> $table = new Table; <del> $validator = new \Cake\Validation\Validator; <add> $table = new Table(); <add> $validator = new \Cake\Validation\Validator(); <ide> $table->setValidator('other', $validator); <ide> $this->assertSame($validator, $table->getValidator('other')); <ide> $this->assertSame($table, $validator->getProvider('table')); <ide> public function testValidatorSetter() <ide> */ <ide> public function testHasValidator() <ide> { <del> $table = new Table; <add> $table = new Table(); <ide> $this->assertTrue($table->hasValidator('default')); <ide> $this->assertFalse($table->hasValidator('other')); <ide> <del> $validator = new \Cake\Validation\Validator; <add> $validator = new \Cake\Validation\Validator(); <ide> $table->setValidator('other', $validator); <ide> $this->assertTrue($table->hasValidator('other')); <ide> } <ide> public function testPatchEntitiesMarshallerUsage() <ide> $table->expects($this->once())->method('marshaller') <ide> ->will($this->returnValue($marshaller)); <ide> <del> $entities = [new Entity]; <add> $entities = [new Entity()]; <ide> $data = [['foo' => 'bar']]; <ide> $marshaller->expects($this->once()) <ide> ->method('mergeMany') <ide> public function testBuildValidatorEvent() <ide> public function testValidateUnique() <ide> { <ide> $table = $this->getTableLocator()->get('Users'); <del> $validator = new Validator; <add> $validator = new Validator(); <ide> $validator->add('username', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']); <ide> $validator->setProvider('table', $table); <ide> <ide> public function testValidateUnique() <ide> public function testValidateUniqueScope() <ide> { <ide> $table = $this->getTableLocator()->get('Users'); <del> $validator = new Validator; <add> $validator = new Validator(); <ide> $validator->add('username', 'unique', [ <ide> 'rule' => ['validateUnique', ['derp' => 'erp', 'scope' => 'id']], <ide> 'provider' => 'table' <ide> public function testValidateUniqueMultipleNulls() <ide> $table = $this->getTableLocator()->get('SiteArticles'); <ide> $table->save($entity); <ide> <del> $validator = new Validator; <add> $validator = new Validator(); <ide> $validator->add('site_id', 'unique', [ <ide> 'rule' => [ <ide> 'validateUnique', <ide> public function testCallbackArgumentTypes() <ide> 'Model.beforeFind', <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) { <ide> $this->assertInternalType('bool', $primary); <del> $associationBeforeFindCount ++; <add> $associationBeforeFindCount++; <ide> } <ide> ); <ide> <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$ass <ide> 'Model.beforeFind', <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) { <ide> $this->assertInternalType('bool', $primary); <del> $beforeFindCount ++; <add> $beforeFindCount++; <ide> } <ide> ); <ide> $table->find()->contain('authors')->first(); <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$bef <ide> 'Model.buildValidator', <ide> $callback = function (Event $event, Validator $validator, $name) use (&$buildValidatorCount) { <ide> $this->assertInternalType('string', $name); <del> $buildValidatorCount ++; <add> $buildValidatorCount++; <ide> } <ide> ); <ide> $table->getValidator(); <ide> function (Event $event, Query $query, ArrayObject $options, $primary) use (&$bef <ide> $eventManager->on( <ide> 'Model.buildRules', <ide> function (Event $event, RulesChecker $rules) use (&$buildRulesCount) { <del> $buildRulesCount ++; <add> $buildRulesCount++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.beforeRules', <ide> function (Event $event, Entity $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) { <ide> $this->assertInternalType('string', $operation); <del> $beforeRulesCount ++; <add> $beforeRulesCount++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.afterRules', <ide> function (Event $event, Entity $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) { <ide> $this->assertInternalType('bool', $result); <ide> $this->assertInternalType('string', $operation); <del> $afterRulesCount ++; <add> $afterRulesCount++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.beforeSave', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveCount) { <del> $beforeSaveCount ++; <add> $beforeSaveCount++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.afterSave', <ide> $afterSaveCallback = function (Event $event, Entity $entity, ArrayObject $options) use (&$afterSaveCount) { <del> $afterSaveCount ++; <add> $afterSaveCount++; <ide> } <ide> ); <ide> $entity = new Entity(['title' => 'Title']); <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveC <ide> $eventManager->on( <ide> 'Model.beforeDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeDeleteCount) { <del> $beforeDeleteCount ++; <add> $beforeDeleteCount++; <ide> } <ide> ); <ide> $eventManager->on( <ide> 'Model.afterDelete', <ide> function (Event $event, Entity $entity, ArrayObject $options) use (&$afterDeleteCount) { <del> $afterDeleteCount ++; <add> $afterDeleteCount++; <ide> } <ide> ); <ide> $this->assertTrue($table->delete($entity, ['checkRules' => false])); <ide><path>tests/TestCase/Routing/DispatcherTest.php <ide> public function testAfterDispatchReplaceResponse() <ide> 'action' => 'index', <ide> 'pass' => [], <ide> ], <del> 'session' => new Session <add> 'session' => new Session() <ide> ]); <ide> $this->dispatcher->addFilter($filter); <ide> $this->dispatcher->dispatch($request, $response); <ide><path>tests/TestCase/Validation/RulesProviderTest.php <ide> class RulesProviderTest extends TestCase <ide> */ <ide> public function testProxyToValidation() <ide> { <del> $provider = new RulesProvider; <add> $provider = new RulesProvider(); <ide> $this->assertTrue($provider->extension('foo.jpg', compact('provider'))); <ide> $this->assertFalse($provider->extension('foo.jpg', ['png'], compact('provider'))); <ide> } <ide><path>tests/TestCase/Validation/ValidationSetTest.php <ide> class ValidationSetTest extends TestCase <ide> */ <ide> public function testGetRule() <ide> { <del> $field = new ValidationSet; <add> $field = new ValidationSet(); <ide> $field->add('notBlank', ['rule' => 'notBlank', 'message' => 'Can not be empty']); <ide> $result = $field->rule('notBlank'); <ide> $this->assertInstanceOf('Cake\Validation\ValidationRule', $result); <ide> public function testGetRule() <ide> */ <ide> public function testGetRules() <ide> { <del> $field = new ValidationSet; <add> $field = new ValidationSet(); <ide> $field->add('notBlank', ['rule' => 'notBlank', 'message' => 'Can not be empty']); <ide> <ide> $result = $field->rules(); <ide> public function testGetRules() <ide> */ <ide> public function testArrayAccessGet() <ide> { <del> $set = (new ValidationSet) <add> $set = (new ValidationSet()) <ide> ->add('notBlank', ['rule' => 'notBlank']) <ide> ->add('numeric', ['rule' => 'numeric']) <ide> ->add('other', ['rule' => 'email']); <ide> public function testArrayAccessGet() <ide> */ <ide> public function testArrayAccessExists() <ide> { <del> $set = (new ValidationSet) <add> $set = (new ValidationSet()) <ide> ->add('notBlank', ['rule' => 'notBlank']) <ide> ->add('numeric', ['rule' => 'numeric']) <ide> ->add('other', ['rule' => 'email']); <ide> public function testArrayAccessExists() <ide> */ <ide> public function testArrayAccessSet() <ide> { <del> $set = (new ValidationSet) <add> $set = (new ValidationSet()) <ide> ->add('notBlank', ['rule' => 'notBlank']); <ide> <ide> $this->assertArrayNotHasKey('other', $set); <ide> public function testArrayAccessSet() <ide> */ <ide> public function testArrayAccessUnset() <ide> { <del> $set = (new ValidationSet) <add> $set = (new ValidationSet()) <ide> ->add('notBlank', ['rule' => 'notBlank']) <ide> ->add('numeric', ['rule' => 'numeric']) <ide> ->add('other', ['rule' => 'email']); <ide> public function testArrayAccessUnset() <ide> */ <ide> public function testIterator() <ide> { <del> $set = (new ValidationSet) <add> $set = (new ValidationSet()) <ide> ->add('notBlank', ['rule' => 'notBlank']) <ide> ->add('numeric', ['rule' => 'numeric']) <ide> ->add('other', ['rule' => 'email']); <ide> public function testIterator() <ide> */ <ide> public function testCount() <ide> { <del> $set = (new ValidationSet) <add> $set = (new ValidationSet()) <ide> ->add('notBlank', ['rule' => 'notBlank']) <ide> ->add('numeric', ['rule' => 'numeric']) <ide> ->add('other', ['rule' => 'email']); <ide> public function testCount() <ide> */ <ide> public function testRemoveRule() <ide> { <del> $set = (new ValidationSet) <add> $set = (new ValidationSet()) <ide> ->add('notBlank', ['rule' => 'notBlank']) <ide> ->add('numeric', ['rule' => 'numeric']) <ide> ->add('other', ['rule' => 'email']); <ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testIsInteger() <ide> $this->assertFalse(Validation::isInteger('2.5')); <ide> $this->assertFalse(Validation::isInteger(2.5)); <ide> $this->assertFalse(Validation::isInteger([])); <del> $this->assertFalse(Validation::isInteger(new \StdClass)); <add> $this->assertFalse(Validation::isInteger(new \StdClass())); <ide> $this->assertFalse(Validation::isInteger('2 bears')); <ide> $this->assertFalse(Validation::isInteger(true)); <ide> $this->assertFalse(Validation::isInteger(false)); <ide> public function testAscii() <ide> $this->assertFalse(Validation::ascii([])); <ide> $this->assertFalse(Validation::ascii(1001)); <ide> $this->assertFalse(Validation::ascii(3.14)); <del> $this->assertFalse(Validation::ascii(new \StdClass)); <add> $this->assertFalse(Validation::ascii(new \StdClass())); <ide> <ide> // Latin-1 supplement <ide> $this->assertFalse(Validation::ascii('some' . "\xc2\x82" . 'value')); <ide> public function testUtf8Basic() <ide> $this->assertFalse(Validation::utf8([])); <ide> $this->assertFalse(Validation::utf8(1001)); <ide> $this->assertFalse(Validation::utf8(3.14)); <del> $this->assertFalse(Validation::utf8(new \StdClass)); <add> $this->assertFalse(Validation::utf8(new \StdClass())); <ide> $this->assertTrue(Validation::utf8('1 big blue bus.')); <ide> $this->assertTrue(Validation::utf8(',.<>[]{;/?\)()')); <ide> <ide> public function testUtf8Extended() <ide> $this->assertFalse(Validation::utf8([], ['extended' => true])); <ide> $this->assertFalse(Validation::utf8(1001, ['extended' => true])); <ide> $this->assertFalse(Validation::utf8(3.14, ['extended' => true])); <del> $this->assertFalse(Validation::utf8(new \StdClass, ['extended' => true])); <add> $this->assertFalse(Validation::utf8(new \StdClass(), ['extended' => true])); <ide> $this->assertTrue(Validation::utf8('1 big blue bus.', ['extended' => true])); <ide> $this->assertTrue(Validation::utf8(',.<>[]{;/?\)()', ['extended' => true])); <ide> <ide><path>tests/TestCase/Validation/ValidatorTest.php <ide> public function testFieldDefault() <ide> public function testFieldSetter() <ide> { <ide> $validator = new Validator(); <del> $validationSet = new ValidationSet; <add> $validationSet = new ValidationSet(); <ide> $validator->field('thing', $validationSet); <ide> $this->assertSame($validationSet, $validator->field('thing')); <ide> } <ide> public function testErrorsWithEmptyAllowed() <ide> public function testProvider() <ide> { <ide> $validator = new Validator(); <del> $object = new \stdClass; <add> $object = new \stdClass(); <ide> $this->assertSame($validator, $validator->setProvider('foo', $object)); <ide> $this->assertSame($object, $validator->getProvider('foo')); <ide> $this->assertNull($validator->getProvider('bar')); <ide> <del> $another = new \stdClass; <add> $another = new \stdClass(); <ide> $this->assertSame($validator, $validator->setProvider('bar', $another)); <ide> $this->assertSame($another, $validator->getProvider('bar')); <ide> <del> $this->assertEquals(new \Cake\Validation\RulesProvider, $validator->getProvider('default')); <add> $this->assertEquals(new \Cake\Validation\RulesProvider(), $validator->getProvider('default')); <ide> } <ide> <ide> /** <ide> public function testErrorsFromCustomProvider() <ide> ->will($this->returnCallback(function ($data, $context) use ($thing) { <ide> $this->assertEquals('bar', $data); <ide> $expected = [ <del> 'default' => new \Cake\Validation\RulesProvider, <add> 'default' => new \Cake\Validation\RulesProvider(), <ide> 'thing' => $thing <ide> ]; <ide> $expected = [ <ide> public function testMethodsWithExtraArguments() <ide> $this->assertEquals('and', $a); <ide> $this->assertEquals('awesome', $b); <ide> $expected = [ <del> 'default' => new \Cake\Validation\RulesProvider, <add> 'default' => new \Cake\Validation\RulesProvider(), <ide> 'thing' => $thing <ide> ]; <ide> $expected = [ <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> public function testDefaultEntityError() <ide> $this->expectException(\RuntimeException::class); <ide> $this->expectExceptionMessage('Unable to find table class for current entity'); <ide> $context = new EntityContext($this->request, [ <del> 'entity' => new Entity, <add> 'entity' => new Entity(), <ide> ]); <ide> } <ide> <ide><path>tests/TestCase/View/Helper/TimeHelperTest.php <ide> public function testToUnix() <ide> */ <ide> public function testToAtom() <ide> { <del> $dateTime = new \DateTime; <add> $dateTime = new \DateTime(); <ide> $this->assertEquals($dateTime->format($dateTime::ATOM), $this->Time->toAtom($dateTime->getTimestamp())); <ide> } <ide> <ide> public function testToAtom() <ide> public function testToAtomOutputTimezone() <ide> { <ide> $this->Time->setConfig('outputTimezone', 'America/Vancouver'); <del> $dateTime = new Time; <add> $dateTime = new Time(); <ide> $vancouver = clone $dateTime; <ide> $vancouver->timezone('America/Vancouver'); <ide> $this->assertEquals($vancouver->format(Time::ATOM), $this->Time->toAtom($vancouver)); <ide> public function testToRss() <ide> public function testToRssOutputTimezone() <ide> { <ide> $this->Time->setConfig('outputTimezone', 'America/Vancouver'); <del> $dateTime = new Time; <add> $dateTime = new Time(); <ide> $vancouver = clone $dateTime; <ide> $vancouver->timezone('America/Vancouver'); <ide> <ide><path>tests/TestCase/View/StringTemplateTraitTest.php <ide> class StringTemplateTraitTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <del> $this->Template = new TestStringTemplate; <add> $this->Template = new TestStringTemplate(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/ViewVarsTraitTest.php <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> <del> $this->subject = new Controller; <add> $this->subject = new Controller(); <ide> } <ide> <ide> /**
46
Javascript
Javascript
remove dead code
fe0af2c073a2a59d3c25bad83bb55b9354110ae4
<ide><path>src/AngularPublic.js <ide> $$TestabilityProvider, <ide> $TimeoutProvider, <ide> $$RAFProvider, <del> $$AsyncCallbackProvider, <ide> $WindowProvider, <ide> $$jqLiteProvider, <ide> $$CookieReaderProvider <ide> function publishExternalAPI(angular) { <ide> $timeout: $TimeoutProvider, <ide> $window: $WindowProvider, <ide> $$rAF: $$RAFProvider, <del> $$asyncCallback: $$AsyncCallbackProvider, <ide> $$jqLite: $$jqLiteProvider, <ide> $$HashMap: $$HashMapProvider, <ide> $$cookieReader: $$CookieReaderProvider <ide><path>src/ngMock/angular-mocks.js <ide> angular.mock.animate = angular.module('ngAnimateMock', ['ng']) <ide> }; <ide> }); <ide> <del> $provide.decorator('$animate', ['$delegate', '$$asyncCallback', '$timeout', '$browser', '$$rAF', <del> function($delegate, $$asyncCallback, $timeout, $browser, $$rAF) { <add> $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', <add> function($delegate, $timeout, $browser, $$rAF) { <ide> var animate = { <ide> queue: [], <ide> cancel: $delegate.cancel, <ide> enabled: $delegate.enabled, <ide> triggerCallbackEvents: function() { <ide> $$rAF.flush(); <del> $$asyncCallback.flush(); <ide> }, <ide> triggerCallbackPromise: function() { <ide> $timeout.flush(0); <ide> angular.mock.$RAFDecorator = ['$delegate', function($delegate) { <ide> return rafFn; <ide> }]; <ide> <del>angular.mock.$AsyncCallbackDecorator = ['$delegate', function($delegate) { <del> var callbacks = []; <del> var addFn = function(fn) { <del> callbacks.push(fn); <del> }; <del> addFn.flush = function() { <del> angular.forEach(callbacks, function(fn) { <del> fn(); <del> }); <del> callbacks = []; <del> }; <del> return addFn; <del>}]; <del> <ide> /** <ide> * <ide> */ <ide> angular.module('ngMock', ['ng']).provider({ <ide> }).config(['$provide', function($provide) { <ide> $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); <ide> $provide.decorator('$$rAF', angular.mock.$RAFDecorator); <del> $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator); <ide> $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator); <ide> $provide.decorator('$controller', angular.mock.$ControllerDecorator); <ide> }]); <ide><path>test/ng/asyncCallbackSpec.js <del>'use strict'; <del>describe('$$asyncCallback', function() { <del> it('should perform a callback asynchronously', inject(function($$asyncCallback) { <del> var message = 'hello there '; <del> $$asyncCallback(function() { <del> message += 'Angular'; <del> }); <del> <del> expect(message).toBe('hello there '); <del> $$asyncCallback.flush(); <del> expect(message).toBe('hello there Angular'); <del> })); <del> <del> describe('mocks', function() { <del> it('should queue up all async callbacks', inject(function($$asyncCallback) { <del> var callback = jasmine.createSpy('callback'); <del> $$asyncCallback(callback); <del> $$asyncCallback(callback); <del> $$asyncCallback(callback); <del> expect(callback.callCount).toBe(0); <del> <del> $$asyncCallback.flush(); <del> expect(callback.callCount).toBe(3); <del> <del> $$asyncCallback(callback); <del> $$asyncCallback(callback); <del> expect(callback.callCount).toBe(3); <del> <del> $$asyncCallback.flush(); <del> expect(callback.callCount).toBe(5); <del> })); <del> }); <del>});
3
Ruby
Ruby
simplify post-install audit output
b46ebf8a29d9ac150895f426cbcf9a78359709ec
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def quote_dep(dep) <ide> Symbol === dep ? dep.inspect : "'#{dep}'" <ide> end <ide> <del> def audit_check_output warning_and_description <del> return unless warning_and_description <del> warning, description = *warning_and_description <del> problem "#{warning}\n#{description}" <add> def audit_check_output(output) <add> problem(output) if output <ide> end <ide> <ide> def audit_installed <ide><path>Library/Homebrew/formula_cellar_checks.rb <ide> def check_PATH bin <ide> prefix_bin = prefix_bin.realpath <ide> return if ORIGINAL_PATHS.include? prefix_bin <ide> <del> ["#{prefix_bin} is not in your PATH", <del> "You can amend this by altering your ~/.bashrc file"] <add> <<-EOS.undent <add> #{prefix_bin} is not in your PATH <add> You can amend this by altering your ~/.bashrc file <add> EOS <ide> end <ide> <ide> def check_manpages <ide> # Check for man pages that aren't in share/man <ide> return unless (f.prefix+'man').directory? <ide> <del> ['A top-level "man" directory was found.', <del> <<-EOS.undent <del> Homebrew requires that man pages live under share. <del> This can often be fixed by passing "--mandir=\#{man}" to configure. <del> EOS <del> ] <add> <<-EOS.undent <add> A top-level "man" directory was found <add> Homebrew requires that man pages live under share. <add> This can often be fixed by passing "--mandir=\#{man}" to configure. <add> EOS <ide> end <ide> <ide> def check_infopages <ide> # Check for info pages that aren't in share/info <ide> return unless (f.prefix+'info').directory? <ide> <del> ['A top-level "info" directory was found.', <del> <<-EOS.undent <del> Homebrew suggests that info pages live under share. <del> This can often be fixed by passing "--infodir=\#{info}" to configure. <del> EOS <del> ] <add> <<-EOS.undent <add> A top-level "info" directory was found <add> Homebrew suggests that info pages live under share. <add> This can often be fixed by passing "--infodir=\#{info}" to configure. <add> EOS <ide> end <ide> <ide> def check_jars <ide> return unless f.lib.directory? <ide> jars = f.lib.children.select { |g| g.extname == ".jar" } <ide> return if jars.empty? <ide> <del> ["JARs were installed to \"#{f.lib}\".", <del> <<-EOS.undent <del> Installing JARs to "lib" can cause conflicts between packages. <del> For Java software, it is typically better for the formula to <del> install to "libexec" and then symlink or wrap binaries into "bin". <del> See "activemq", "jruby", etc. for examples. <del> The offending files are: <del> #{jars * "\n "} <del> EOS <del> ] <add> <<-EOS.undent <add> JARs were installed to "#{f.lib}" <add> Installing JARs to "lib" can cause conflicts between packages. <add> For Java software, it is typically better for the formula to <add> install to "libexec" and then symlink or wrap binaries into "bin". <add> See "activemq", "jruby", etc. for examples. <add> The offending files are: <add> #{jars * "\n "} <add> EOS <ide> end <ide> <ide> def check_non_libraries <ide> def check_non_libraries <ide> end <ide> return if non_libraries.empty? <ide> <del> ["Non-libraries were installed to \"#{f.lib}\".", <del> <<-EOS.undent <del> Installing non-libraries to "lib" is discouraged. <del> The offending files are: <del> #{non_libraries * "\n "} <del> EOS <del> ] <add> <<-EOS.undent <add> Non-libraries were installed to "#{f.lib}" <add> Installing non-libraries to "lib" is discouraged. <add> The offending files are: <add> #{non_libraries * "\n "} <add> EOS <ide> end <ide> <ide> def check_non_executables bin <ide> def check_non_executables bin <ide> non_exes = bin.children.select { |g| g.directory? or not g.executable? } <ide> return if non_exes.empty? <ide> <del> ["Non-executables were installed to \"#{bin}\".", <del> <<-EOS.undent <del> The offending files are: <del> #{non_exes * "\n "} <del> EOS <del> ] <add> <<-EOS.undent <add> Non-executables were installed to "#{bin}" <add> The offending files are: <add> #{non_exes * "\n "} <add> EOS <ide> end <ide> <ide> def check_generic_executables bin <ide> def check_generic_executables bin <ide> generics = bin.children.select { |g| generic_names.include? g.basename.to_s } <ide> return if generics.empty? <ide> <del> ["Generic binaries were installed to \"#{bin}\".", <del> <<-EOS.undent <del> Binaries with generic names are likely to conflict with other software, <del> and suggest that this software should be installed to "libexec" and <del> then symlinked as needed. <add> <<-EOS.undent <add> Generic binaries were installed to "#{bin}" <add> Binaries with generic names are likely to conflict with other software, <add> and suggest that this software should be installed to "libexec" and then <add> symlinked as needed. <ide> <del> The offending files are: <del> #{generics * "\n "} <del> EOS <del> ] <add> The offending files are: <add> #{generics * "\n "} <add> EOS <ide> end <ide> <ide> def check_shadowed_headers <ide> def check_shadowed_headers <ide> <ide> return if files.empty? <ide> <del> ["Header files that shadow system header files were installed to \"#{f.include}\".", <del> "The offending files are: \n #{files * "\n "}"] <add> <<-EOS.undent <add> Header files that shadow system header files were installed to "#{f.include}" <add> The offending files are: <add> #{files * "\n "} <add> EOS <ide> end <ide> <ide> def check_easy_install_pth lib <ide> pth_found = Dir["#{lib}/python{2.7,3.4}/site-packages/easy-install.pth"].map { |f| File.dirname(f) } <ide> return if pth_found.empty? <ide> <del> ["easy-install.pth files were found in #{pth_found.join(", ")}.", <del> <<-EOS.undent <del> These .pth files are likely to cause link conflicts. Please <del> invoke setup.py with options --single-version-externally-managed <del> --record=install.txt. <del> EOS <del> ] <add> <<-EOS.undent <add> easy-install.pth files were found <add> These .pth files are likely to cause link conflicts. Please invoke <add> setup.py with options <add> --single-version-externally-managed --record=install.txt <add> The offending files are <add> #{pth_found * "\n "} <add> EOS <ide> end <ide> <ide> private <ide><path>Library/Homebrew/formula_installer.rb <ide> def pour <ide> <ide> ## checks <ide> <del> def print_check_output warning_and_description <del> return unless warning_and_description <del> warning, description = *warning_and_description <del> opoo warning <del> puts description <del> @show_summary_heading = true <add> def print_check_output(output) <add> if output <add> opoo output <add> @show_summary_heading = true <add> end <ide> end <ide> <ide> def audit_bin
3
Python
Python
add user options for compilers in scons command
cc9799e0981534cbb40ac6075bcefd90bdefdb87
<ide><path>numpy/distutils/command/scons.py <ide> class scons(old_build_ext): <ide> ('package-list=', None, <ide> 'If specified, only run scons on the given '\ <ide> 'packages (example: --package-list=scipy.cluster). If empty, '\ <del> 'no package is built')] <add> 'no package is built'), <add> ('fcompiler=', None, <add> "specify the Fortran compiler type"), <add> ('compiler=', None, <add> "specify the C compiler type"), <add> ('cxxcompiler=', None, <add> "specify the C++ compiler type (same as C by default)"), <add> ] <ide> <ide> def initialize_options(self): <ide> old_build_ext.initialize_options(self) <add> self.compiler = None <add> self.cxxcompiler = None <add> self.fcompiler = None <add> <ide> self.jobs = None <ide> self.silent = 0 <ide> self.scons_tool_path = '' <ide> def finalize_options(self): <ide> self.post_hooks = [] <ide> self.pkg_names = [] <ide> <add> if not self.cxxcompiler: <add> self.cxxcompiler = self.compiler <add> <ide> # To avoid trouble, just don't do anything if no sconscripts are used. <ide> # This is useful when for example f2py uses numpy.distutils, because <ide> # f2py does not pass compiler information to scons command, and the <ide> def finalize_options(self): <ide> <ide> self._init_ccompiler(self.compiler) <ide> self._init_fcompiler(self.fcompiler) <del> self._init_cxxcompiler(self.compiler) <add> self._init_cxxcompiler(self.cxxcompiler) <ide> <ide> if self.package_list: <ide> self.package_list = parse_package_list(self.package_list)
1
Mixed
Javascript
upgrade pbkdf2 without digest to an error
9f74184e98020eb71060ee38c2b3d649ad299bb6
<ide><path>doc/api/deprecations.md <ide> to the `constants` property exposed by the relevant module. For instance, <ide> <a id="DEP0009"></a> <ide> ### DEP0009: crypto.pbkdf2 without digest <ide> <del>Type: Runtime <add>Type: End-of-life <ide> <del>Use of the [`crypto.pbkdf2()`][] API without specifying a digest is deprecated. <del>Please specify a digest. <add>Use of the [`crypto.pbkdf2()`][] API without specifying a digest was deprecated <add>in Node.js 6.0 because the method defaulted to using the non-recommendend <add>`'SHA1'` digest. Previously, a deprecation warning was printed. Starting in <add>Node.js 8.0.0, calling `crypto.pbkdf2()` or `crypto.pbkdf2Sync()` with an <add>undefined `digest` will throw a `TypeError`. <ide> <ide> <a id="DEP0010"></a> <ide> ### DEP0010: crypto.createCredentials <ide><path>lib/crypto.js <ide> ECDH.prototype.getPublicKey = function getPublicKey(encoding, format) { <ide> }; <ide> <ide> <del>const pbkdf2DeprecationWarning = <del> internalUtil.deprecate(() => {}, 'crypto.pbkdf2 without specifying' + <del> ' a digest is deprecated. Please specify a digest', 'DEP0009'); <del> <del> <ide> exports.pbkdf2 = function(password, <ide> salt, <ide> iterations, <ide> exports.pbkdf2 = function(password, <ide> if (typeof digest === 'function') { <ide> callback = digest; <ide> digest = undefined; <del> pbkdf2DeprecationWarning(); <ide> } <ide> <ide> if (typeof callback !== 'function') <ide> exports.pbkdf2 = function(password, <ide> <ide> <ide> exports.pbkdf2Sync = function(password, salt, iterations, keylen, digest) { <del> if (typeof digest === 'undefined') { <del> digest = undefined; <del> pbkdf2DeprecationWarning(); <del> } <ide> return pbkdf2(password, salt, iterations, keylen, digest); <ide> }; <ide> <ide> <ide> function pbkdf2(password, salt, iterations, keylen, digest, callback) { <add> <add> if (digest === undefined) { <add> throw new TypeError( <add> 'The "digest" argument is required and must not be undefined'); <add> } <add> <ide> password = toBuf(password); <ide> salt = toBuf(salt); <ide> <ide><path>test/parallel/test-crypto-domains.js <ide> d.run(function() { <ide> one(); <ide> <ide> function one() { <del> crypto.pbkdf2('a', 'b', 1, 8, function() { <add> crypto.pbkdf2('a', 'b', 1, 8, 'sha1', function() { <ide> two(); <ide> throw new Error('pbkdf2'); <ide> }); <ide><path>test/parallel/test-crypto-pbkdf2.js <ide> assert.doesNotThrow(() => { <ide> assert.ifError(e); <ide> })); <ide> }); <add> <add>assert.throws(() => { <add> crypto.pbkdf2('password', 'salt', 8, 8, function() {}); <add>}, /^TypeError: The "digest" argument is required and must not be undefined$/); <add> <add>assert.throws(() => { <add> crypto.pbkdf2Sync('password', 'salt', 8, 8); <add>}, /^TypeError: The "digest" argument is required and must not be undefined$/); <ide><path>test/parallel/test-domain-crypto.js <ide> crypto.randomBytes(8); <ide> crypto.randomBytes(8, function() {}); <ide> crypto.pseudoRandomBytes(8); <ide> crypto.pseudoRandomBytes(8, function() {}); <del>crypto.pbkdf2('password', 'salt', 8, 8, function() {}); <add>crypto.pbkdf2('password', 'salt', 8, 8, 'sha1', function() {});
5
Javascript
Javascript
introduce `visit(ast, visitor)` utility
898f73deef5bdf0e87a9f3d8d4f0f3b1d20f87bb
<ide><path>packages/react-native-codegen/src/parsers/flow/index.js <ide> const {buildComponentSchema} = require('./components'); <ide> const {wrapComponentSchema} = require('./components/schema'); <ide> const {buildModuleSchema} = require('./modules'); <ide> const {wrapModuleSchema} = require('./modules/schema'); <del>const {createParserErrorCapturer} = require('./utils'); <add>const {createParserErrorCapturer, visit} = require('./utils'); <ide> const invariant = require('invariant'); <ide> <del>function isComponent(ast) { <del> const defaultExports = ast.body.filter( <del> node => node.type === 'ExportDefaultDeclaration', <del> ); <del> <del> if (defaultExports.length === 0) { <del> return false; <del> } <del> <del> let declaration = defaultExports[0].declaration; <del> // codegenNativeComponent can be nested inside a cast <del> // expression so we need to go one level deeper <del> if (declaration.type === 'TypeCastExpression') { <del> declaration = declaration.expression; <del> } <del> <del> if (declaration.type !== 'CallExpression') { <del> return false; <del> } <del> <del> return ( <del> declaration.callee.type === 'Identifier' && <del> declaration.callee.name === 'codegenNativeComponent' <del> ); <del>} <del> <del>function isModule( <add>function getConfigType( <ide> // TODO(T71778680): Flow-type this node. <ide> ast: $FlowFixMe, <del>) { <del> const moduleInterfaces = ast.body <del> .map(node => { <add>): 'module' | 'component' { <add> let isComponent = false; <add> let isModule = false; <add> <add> visit(ast, { <add> CallExpression(node) { <ide> if ( <del> node.type === 'ExportNamedDeclaration' && <del> node.exportKind === 'type' && <del> node.declaration.type === 'InterfaceDeclaration' <add> node.callee.type === 'Identifier' && <add> node.callee.name === 'codegenNativeComponent' <ide> ) { <del> return node.declaration; <add> isComponent = true; <ide> } <del> return node; <del> }) <del> .filter(declaration => { <del> return ( <del> declaration.type === 'InterfaceDeclaration' && <del> declaration.extends.length === 1 && <del> declaration.extends[0].type === 'InterfaceExtends' && <del> declaration.extends[0].id.name === 'TurboModule' <del> ); <del> }) <del> .map(declaration => declaration.id.name); <del> <del> if (moduleInterfaces.length === 0) { <del> return false; <del> } <del> <del> return true; <del>} <del> <del>function getConfigType( <del> // TODO(T71778680): Flow-type this node. <del> ast: $FlowFixMe, <del>): 'module' | 'component' { <del> const isConfigAComponent = isComponent(ast); <del> const isConfigAModule = isModule(ast); <add> }, <add> InterfaceExtends(node) { <add> if (node.id.name === 'TurboModule') { <add> isModule = true; <add> } <add> }, <add> }); <ide> <del> if (isConfigAModule && isConfigAComponent) { <add> if (isModule && isComponent) { <ide> throw new Error( <ide> 'Found type extending "TurboModule" and exported "codegenNativeComponent" declaration in one file. Split them into separated files.', <ide> ); <ide> } <ide> <del> if (isConfigAModule) { <add> if (isModule) { <ide> return 'module'; <del> } else if (isConfigAComponent) { <add> } else if (isComponent) { <ide> return 'component'; <ide> } else { <ide> throw new Error( <ide> function getConfigType( <ide> <ide> function buildSchema(contents: string, filename: ?string): SchemaType { <ide> const ast = flowParser.parse(contents); <del> <ide> const configType = getConfigType(ast); <ide> <del> if (configType === 'component') { <del> return wrapComponentSchema(buildComponentSchema(ast)); <del> } else { <del> if (filename === undefined || filename === null) { <del> throw new Error('Filepath expected while parasing a module'); <add> switch (configType) { <add> case 'component': { <add> return wrapComponentSchema(buildComponentSchema(ast)); <ide> } <del> const hasteModuleName = path.basename(filename).replace(/\.js$/, ''); <add> case 'module': { <add> if (filename === undefined || filename === null) { <add> throw new Error('Filepath expected while parasing a module'); <add> } <add> const hasteModuleName = path.basename(filename).replace(/\.js$/, ''); <ide> <del> const [parsingErrors, tryParse] = createParserErrorCapturer(); <del> const schema = tryParse(() => <del> buildModuleSchema(hasteModuleName, ast, tryParse), <del> ); <add> const [parsingErrors, tryParse] = createParserErrorCapturer(); <add> const schema = tryParse(() => <add> buildModuleSchema(hasteModuleName, ast, tryParse), <add> ); <ide> <del> if (parsingErrors.length > 0) { <del> /** <del> * TODO(T77968131): We have two options: <del> * - Throw the first error, but indicate there are more then one errors. <del> * - Display all errors, nicely formatted. <del> * <del> * For the time being, we're just throw the first error. <del> **/ <add> if (parsingErrors.length > 0) { <add> /** <add> * TODO(T77968131): We have two options: <add> * - Throw the first error, but indicate there are more then one errors. <add> * - Display all errors, nicely formatted. <add> * <add> * For the time being, we're just throw the first error. <add> **/ <ide> <del> throw parsingErrors[0]; <del> } <add> throw parsingErrors[0]; <add> } <ide> <del> invariant( <del> schema != null, <del> 'When there are no parsing errors, the schema should not be null', <del> ); <add> invariant( <add> schema != null, <add> 'When there are no parsing errors, the schema should not be null', <add> ); <ide> <del> return wrapModuleSchema(schema, hasteModuleName); <add> return wrapModuleSchema(schema, hasteModuleName); <add> } <add> default: <add> (configType: empty); <add> throw new Error(`Unsupported config type '${configType}'`); <ide> } <ide> } <ide> <ide><path>packages/react-native-codegen/src/parsers/flow/modules/index.js <ide> import type {TypeDeclarationMap} from '../utils.js'; <ide> import type {ParserErrorCapturer} from '../utils'; <ide> import type {NativeModuleTypeAnnotation} from '../../../CodegenSchema.js'; <ide> <del>const {resolveTypeAnnotation, getTypes, findChildren} = require('../utils.js'); <add>const {resolveTypeAnnotation, getTypes, visit} = require('../utils.js'); <ide> const {unwrapNullable, wrapNullable} = require('./utils'); <ide> const { <ide> IncorrectlyParameterizedFlowGenericParserError, <ide> function buildPropertySchema( <ide> }; <ide> } <ide> <del>function isCallIntoModuleRegistry(node) { <add>function isModuleRegistryCall(node) { <ide> if (node.type !== 'CallExpression') { <ide> return false; <ide> } <ide> function isCallIntoModuleRegistry(node) { <ide> return true; <ide> } <ide> <add>function isModuleInterface(node) { <add> return ( <add> node.type === 'InterfaceDeclaration' && <add> node.extends.length === 1 && <add> node.extends[0].type === 'InterfaceExtends' && <add> node.extends[0].id.name === 'TurboModule' <add> ); <add>} <add> <ide> function buildModuleSchema( <ide> hasteModuleName: string, <ide> /** <ide> function buildModuleSchema( <ide> tryParse: ParserErrorCapturer, <ide> ): NativeModuleSchema { <ide> const types = getTypes(ast); <del> const moduleInterfaceNames = (Object.keys( <del> types, <del> ): $ReadOnlyArray<string>).filter((typeName: string) => { <del> const declaration = types[typeName]; <del> return ( <del> declaration.type === 'InterfaceDeclaration' && <del> declaration.extends.length === 1 && <del> declaration.extends[0].type === 'InterfaceExtends' && <del> declaration.extends[0].id.name === 'TurboModule' <del> ); <del> }); <add> const moduleSpecs = (Object.values(types): $ReadOnlyArray<$FlowFixMe>).filter( <add> isModuleInterface, <add> ); <ide> <del> if (moduleInterfaceNames.length === 0) { <add> if (moduleSpecs.length === 0) { <ide> throw new ModuleFlowInterfaceNotFoundParserError(hasteModuleName, ast); <ide> } <ide> <del> if (moduleInterfaceNames.length > 1) { <add> if (moduleSpecs.length > 1) { <ide> throw new MoreThanOneModuleFlowInterfaceParserError( <ide> hasteModuleName, <del> moduleInterfaceNames.map(name => types[name]), <del> moduleInterfaceNames, <add> moduleSpecs, <add> moduleSpecs.map(node => node.id.name), <ide> ); <ide> } <ide> <del> const [moduleInterfaceName] = moduleInterfaceNames; <add> const [moduleSpec] = moduleSpecs; <ide> <del> if (moduleInterfaceName !== 'Spec') { <add> if (moduleSpec.id.name !== 'Spec') { <ide> throw new MisnamedModuleFlowInterfaceParserError( <ide> hasteModuleName, <del> types[moduleInterfaceName].id, <add> moduleSpec.id, <ide> ); <ide> } <ide> <ide> // Parse Module Names <ide> const moduleName = tryParse((): string => { <del> const callExpressions = findChildren(ast, isCallIntoModuleRegistry); <add> const callExpressions = []; <add> visit(ast, { <add> CallExpression(node) { <add> if (isModuleRegistryCall(node)) { <add> callExpressions.push(node); <add> } <add> }, <add> }); <add> <ide> if (callExpressions.length === 0) { <ide> throw new UnusedModuleFlowInterfaceParserError( <ide> hasteModuleName, <del> types[moduleInterfaceName], <add> moduleSpec, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> } <ide> }); <ide> <del> const declaration = types[moduleInterfaceName]; <del> return (declaration.body.properties: $ReadOnlyArray<$FlowFixMe>) <add> return (moduleSpec.body.properties: $ReadOnlyArray<$FlowFixMe>) <ide> .filter(property => property.type === 'ObjectTypeProperty') <ide> .map<?{ <ide> aliasMap: NativeModuleAliasMap, <ide><path>packages/react-native-codegen/src/parsers/flow/utils.js <ide> function createParserErrorCapturer(): [ <ide> return [errors, guard]; <ide> } <ide> <del>// TODO(T71778680): Flow-type this node. <del>function findChildren( <add>// TODO(T71778680): Flow-type ASTNodes. <add>function visit( <ide> astNode: $FlowFixMe, <del> predicate: (node: $FlowFixMe) => boolean, <del>): $ReadOnlyArray<$FlowFixMe> { <del> if (predicate(astNode)) { <del> return astNode; <del> } <del> <del> const found = []; <del> const queue = Object.values(astNode); <del> <add> visitor: { <add> [type: string]: (node: $FlowFixMe) => void, <add> }, <add>) { <add> const queue = [astNode]; <ide> while (queue.length !== 0) { <ide> let item = queue.shift(); <ide> <ide> if (!(typeof item === 'object' && item != null)) { <ide> continue; <ide> } <ide> <del> if (Array.isArray(item)) { <add> if ( <add> typeof item.type === 'string' && <add> typeof visitor[item.type] === 'function' <add> ) { <add> // Don't visit any children <add> visitor[item.type](item); <add> } else if (Array.isArray(item)) { <ide> queue.push(...item); <del> } else if (typeof item.type === 'string' && predicate(item)) { <del> found.push(item); <ide> } else { <ide> queue.push(...Object.values(item)); <ide> } <ide> } <del> <del> return found; <ide> } <ide> <ide> module.exports = { <ide> getValueFromTypes, <ide> resolveTypeAnnotation, <ide> createParserErrorCapturer, <ide> getTypes, <del> findChildren, <add> visit, <ide> };
3
PHP
PHP
remove multiple empty lines
c428da92979bd7f0367a18e5b55146592a2c9c51
<ide><path>src/Cache/CacheEngine.php <ide> abstract public function decrement($key, $offset = 1); <ide> */ <ide> abstract public function delete($key); <ide> <del> <ide> /** <ide> * Delete all keys from the cache <ide> * <ide><path>src/Controller/Component/SecurityComponent.php <ide> protected function _fieldsList(array $check) <ide> return $fieldList; <ide> } <ide> <del> <ide> /** <ide> * Get the unlocked string <ide> * <ide><path>src/Database/Schema/CachedCollection.php <ide> public function getCacheMetadata() <ide> return $this->_cache; <ide> } <ide> <del> <ide> /** <ide> * Sets the cache config name to use for caching table metadata, or <ide> * disables it if false is passed. <ide><path>src/Database/TypeMap.php <ide> public function getDefaults() <ide> return $this->_defaults; <ide> } <ide> <del> <ide> /** <ide> * Configures a map of default fields and their associated types to be <ide> * used as the default list of types for every function in this class <ide><path>src/Http/Client/Response.php <ide> protected function _getBody() <ide> return $this->stream->getContents(); <ide> } <ide> <del> <ide> /** <ide> * Read values as properties. <ide> * <ide><path>src/Mailer/Email.php <ide> public function returnPath($email = null, $name = null) <ide> return $this->setReturnPath($email, $name); <ide> } <ide> <del> <ide> /** <ide> * Sets "to" address. <ide> * <ide> public function emailFormat($format = null) <ide> return $this->setEmailFormat($format); <ide> } <ide> <del> <ide> /** <ide> * Sets the transport. <ide> * <ide> public function domain($domain = null) <ide> return $this->setDomain($domain); <ide> } <ide> <del> <ide> /** <ide> * Add attachments to the email message <ide> * <ide><path>src/ORM/Association/Loader/SelectLoader.php <ide> public function __construct(array $options) <ide> $this->sort = isset($options['sort']) ? $options['sort'] : null; <ide> } <ide> <del> <ide> /** <ide> * Returns a callable that can be used for injecting association results into a given <ide> * iterator. The options accepted by this method are the same as `Association::eagerLoader()` <ide><path>src/ORM/Table.php <ide> public function getAlias() <ide> return $this->_alias; <ide> } <ide> <del> <ide> /** <ide> * {@inheritDoc} <ide> * @deprecated 3.4.0 Use setAlias()/getAlias() instead. <ide> public function setRegistryAlias($registryAlias) <ide> return $this; <ide> } <ide> <del> <ide> /** <ide> * Returns the table registry key used to create this table instance. <ide> * <ide><path>src/Routing/Router.php <ide> public static function setRequestContext($request) <ide> throw new InvalidArgumentException('Unknown request type received.'); <ide> } <ide> <del> <ide> /** <ide> * Pops a request off of the request stack. Used when doing requestAction <ide> * <ide><path>tests/TestCase/Collection/CollectionTest.php <ide> class TestCollection extends \IteratorIterator implements CollectionInterface <ide> { <ide> use CollectionTrait; <ide> <del> <ide> public function __construct($items) <ide> { <ide> if (is_array($items)) { <ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> public function testMergeOptionsCustomScope() <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <del> <ide> $settings = [ <ide> 'page' => 1, <ide> 'limit' => 20, <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> public function testValidatePostUrlAsHashInput() <ide> [] <ide> ])); <ide> <del> <ide> $this->Controller->request->data = [ <ide> 'Model' => ['username' => '', 'password' => ''], <ide> '_Token' => compact('fields', 'unlocked', 'debug') <ide><path>tests/TestCase/Database/ExpressionTypeCastingIntegrationTest.php <ide> public function testSelectWithConditions() <ide> $this->assertEquals('4c2681c048298a29a7fb413140cf8569', $result[0]['id']); <ide> } <ide> <del> <ide> /** <ide> * Tests Select using value object in conditions <ide> * <ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testSelectTypeConversion() <ide> $this->assertInstanceOf('DateTime', $result[0]['the_date']); <ide> } <ide> <del> <ide> /** <ide> * Tests that the json type can save and get data symmetrically <ide> * <ide><path>tests/TestCase/Database/Type/BoolTypeTest.php <ide> public function testToDatabaseInvalid() <ide> $this->type->toDatabase([1, 2], $this->driver); <ide> } <ide> <del> <ide> /** <ide> * Tests that passing an invalid value will throw an exception <ide> * <ide><path>tests/TestCase/Filesystem/FolderTest.php <ide> public function testInPath() <ide> $result = $Base->pwd(); <ide> $this->assertEquals($basePath, $result); <ide> <del> <ide> // is "/" in "/tests/test_app/" <ide> $result = $Base->inPath(realpath(DS), true); <ide> $this->assertFalse($result, true); <ide> public function testInPath() <ide> $result = $Base->inPath(TMP . 'tests' . DS . 'other' . DS . $basePath, true); <ide> $this->assertFalse($result); <ide> <del> <ide> // is "/tests/test_app/" in "/" <ide> $result = $Base->inPath(realpath(DS)); <ide> $this->assertTrue($result); <ide><path>tests/TestCase/Http/ServerTest.php <ide> <ide> require_once __DIR__ . '/server_mocks.php'; <ide> <del> <ide> /** <ide> * Server test case <ide> */ <ide><path>tests/TestCase/I18n/Formatter/IcuFormatterTest.php <ide> public function testBadMessageFormatPHP7() <ide> { <ide> $this->skipIf(version_compare(PHP_VERSION, '7', '<')); <ide> <del> <ide> $formatter = new IcuFormatter(); <ide> $formatter->format('en_US', '{crazy format', ['some', 'vars']); <ide> } <ide><path>tests/TestCase/ORM/EagerLoaderTest.php <ide> public function testContainDotNotation() <ide> $this->assertEquals($expected, $loader->contain()); <ide> } <ide> <del> <ide> /** <ide> * Tests setting containments using direct key value pairs works just as with key array. <ide> * <ide><path>tests/TestCase/ORM/Locator/TableLocatorTest.php <ide> class MyUsersTable extends Table <ide> protected $_table = 'users'; <ide> } <ide> <del> <ide> /** <ide> * Test case for TableLocator <ide> */ <ide> class TableLocatorTest extends TestCase <ide> */ <ide> protected $_locator; <ide> <del> <ide> /** <ide> * setup <ide> * <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testComplexTypesInJoinedWhereWithMatching() <ide> $this->assertNotEmpty($result); <ide> $this->assertInstanceOf('Cake\I18n\Time', $result->_matchingData['Comments']->updated); <ide> <del> <ide> $query = $table->find() <ide> ->matching('Comments.Articles.Authors') <ide> ->where([ <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testSaveReplaceSaveStrategy() <ide> $this->assertTrue($authors->Articles->exists(['id' => $articleId])); <ide> } <ide> <del> <ide> /** <ide> * Test that save works with replace saveStrategy, replacing the already persisted entities even if no new entities are passed <ide> * <ide> public function testAtomicSaveRollbackOnFailure() <ide> $table->save($data); <ide> } <ide> <del> <ide> /** <ide> * Tests that only the properties marked as dirty are actually saved <ide> * to the database <ide> public function testLinkHasMany() <ide> <ide> $this->assertTrue($authors->Articles->link($author, $newArticles)); <ide> <del> <ide> $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id)); <ide> $this->assertCount($sizeArticles, $author->articles); <ide> $this->assertFalse($author->dirty('articles')); <ide> public function testUnlinkHasManyEmpty() <ide> $authors->Articles->unlink($author, [$article]); <ide> } <ide> <del> <ide> /** <ide> * Integration test for replacing entities which depend on their source entity with HasMany and failing transaction. False should be returned when <ide> * unlinking fails while replacing even when cascadeCallbacks is enabled <ide> public function testReplaceHasManyOnErrorDependentCascadeCallbacks() <ide> $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id)); <ide> } <ide> <del> <ide> /** <ide> * Integration test for replacing entities with HasMany and an empty target list. The transaction must be successfull <ide> * <ide> public function testReplaceHasMany() <ide> $this->assertEquals((new Collection($newArticles))->extract('title'), (new Collection($author->articles))->extract('title')); <ide> } <ide> <del> <ide> /** <ide> * Integration test to show how to unlink a single record from a belongsToMany <ide> * <ide><path>tests/TestCase/TestSuite/AssertHtmlTest.php <ide> public function testAssertHtmlRuntimeComplexity() <ide> $this->assertHtml($pattern, $input); <ide> } <ide> <del> <ide> /** <ide> * test that assertHtml knows how to handle correct quoting. <ide> * <ide><path>tests/TestCase/TestSuite/TestFixtureTest.php <ide> class StringsTestsFixture extends TestFixture <ide> ]; <ide> } <ide> <del> <ide> /** <ide> * ImportsFixture class <ide> */ <ide><path>tests/TestCase/Utility/HashTest.php <ide> public function testSortString() <ide> $this->assertEquals($expected, $result); <ide> } <ide> <del> <ide> /** <ide> * test sorting with string ignoring case. <ide> * <ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testLocalizedTime() <ide> I18N::locale($locale); <ide> } <ide> <del> <ide> /** <ide> * testBoolean method <ide> * <ide><path>tests/TestCase/Validation/ValidatorTest.php <ide> public function testDate() <ide> $this->assertNotEmpty($validator->errors(['username' => 'not a date'])); <ide> } <ide> <del> <ide> /** <ide> * Tests the dateTime proxy method <ide> * <ide> public function testIps() <ide> $this->assertProxyMethod($validator, 'ip'); <ide> $this->assertNotEmpty($validator->errors(['username' => 'not ip'])); <ide> <del> <ide> $this->assertProxyMethod($validator, 'ipv4', null, ['ipv4'], 'ip'); <ide> $this->assertNotEmpty($validator->errors(['username' => 'not ip'])); <ide> <ide><path>tests/TestCase/View/Helper/BreadcrumbsHelperTest.php <ide> public function testAdd() <ide> $this->assertEquals($expected, $result); <ide> } <ide> <del> <ide> /** <ide> * Test adding multiple crumbs at once to the trail using add() <ide> * <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testErrorMessageDisplay() <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> <del> <ide> $result = $this->Form->control('Article.content'); <ide> $expected = [ <ide> 'div' => ['class' => 'input text error'], <ide> public function testFormValueSourcesSettersGetters() <ide> $result = $this->Form->getValueSources(); <ide> $this->assertEquals($expected, $result); <ide> <del> <ide> $this->Form->request->data['id'] = '1'; <ide> $this->Form->request->query['id'] = '2'; <ide>
29
PHP
PHP
fix a bunch of things
e509b3958dde4fbe8454edc79c6870f60a1082e9
<ide><path>src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php <ide> public function auth($request) <ide> public function validAuthenticationResponse($request, $result) <ide> { <ide> if (Str::startsWith($request->channel_name, 'private')) { <del> return $this->decodedPusherResponse( <add> return $this->decodePusherResponse( <ide> $this->pusher->socket_auth($request->channel_name, $request->socket_id) <ide> ); <ide> } else { <del> return $this->decodedPusherResponse( <add> return $this->decodePusherResponse( <ide> $this->pusher->presence_auth( <ide> $request->channel_name, $request->socket_id, $request->user()->id, $result) <ide> ); <ide> } <ide> } <ide> <add> /** <add> * Decode the given Pusher response. <add> * <add> * @param mixed $response <add> * @return array <add> */ <add> protected function decodePusherResponse($response) <add> { <add> return json_decode($response, true); <add> } <add> <ide> /** <ide> * Broadcast the given event. <ide> * <ide> public function getPusher() <ide> { <ide> return $this->pusher; <ide> } <del> <del> /** <del> * Decoded PusherResponse. <del> * <del> * @param mixed $response <del> * @return array <del> */ <del> public function decodedPusherResponse($response) <del> { <del> return json_decode($response, true); <del> } <ide> }
1
PHP
PHP
fix failing tests
6d0e033663a3002c124eeb8cb7c849b8839f5292
<ide><path>lib/Cake/Test/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testViewClassMap() { <ide> $this->assertEquals($expected, $result); <ide> <ide> $this->RequestHandler->renderAs($this->Controller, 'json'); <del> $this->assertEquals('CustomJson', $this->Controller->viewClass); <add> $this->assertEquals('TestApp\View\CustomJsonView', $this->Controller->viewClass); <ide> } <ide> <ide> /** <ide> public function testDisabling() { <ide> */ <ide> public function testAutoResponseType() { <ide> $this->Controller->ext = '.thtml'; <del> $this->Controller->request->params['ext'] = 'rss'; <add> $this->Controller->request->params['_ext'] = 'rss'; <ide> $this->RequestHandler->initialize($this->Controller); <ide> $this->RequestHandler->startup($this->Controller); <ide> $this->assertEquals('.ctp', $this->Controller->ext); <ide> public function testAutoAjaxLayout() { <ide> $this->assertEquals($this->Controller->layout, $this->RequestHandler->ajaxLayout); <ide> <ide> $this->_init(); <del> $this->Controller->request->params['ext'] = 'js'; <add> $this->Controller->request->params['_ext'] = 'js'; <ide> $this->RequestHandler->initialize($this->Controller); <ide> $this->RequestHandler->startup($this->Controller); <ide> $this->assertNotEquals('ajax', $this->Controller->layout); <ide> public function testRenderAsWithAttachment() { <ide> <ide> $this->RequestHandler->renderAs($this->Controller, 'xml', array('attachment' => 'myfile.xml')); <ide> <del> $this->assertEquals('Xml', $this->Controller->viewClass); <add> $this->assertEquals('Cake\View\XmlView', $this->Controller->viewClass); <ide> } <ide> <ide> /** <ide> public function testClientProperties() { <ide> * @return void <ide> */ <ide> public function testAjaxRedirectAsRequestAction() { <add> Configure::write('App.namespace', 'TestApp'); <ide> App::build(array( <ide> 'View' => array(CAKE . 'Test/TestApp/View/') <ide> ), App::RESET); <add> Router::connect('/:controller/:action'); <ide> <del> $this->Controller->RequestHandler = $this->getMock('Cake\Controller\Component\RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); <add> $this->Controller->RequestHandler = $this->getMock( <add> 'Cake\Controller\Component\RequestHandlerComponent', <add> array('_stop'), <add> array(&$this->Controller->Components) <add> ); <ide> $this->Controller->request = $this->getMock('Cake\Network\Request'); <ide> $this->Controller->response = $this->getMock('Cake\Network\Response', array('_sendHeader')); <ide> $this->Controller->RequestHandler->request = $this->Controller->request; <ide> public function testAjaxRedirectAsRequestAction() { <ide> * @return void <ide> */ <ide> public function testAjaxRedirectAsRequestActionStillRenderingLayout() { <add> Configure::write('App.namespace', 'TestApp'); <ide> App::build(array( <ide> 'View' => array(CAKE . 'Test/TestApp/View/') <ide> ), App::RESET); <add> Router::connect('/:controller/:action'); <ide> <del> $this->Controller->RequestHandler = $this->getMock('Cake\Controller\Component\RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); <add> $this->Controller->RequestHandler = $this->getMock( <add> 'Cake\Controller\Component\RequestHandlerComponent', <add> array('_stop'), <add> array(&$this->Controller->Components) <add> ); <ide> $this->Controller->request = $this->getMock('Cake\Network\Request'); <ide> $this->Controller->response = $this->getMock('Cake\Network\Response', array('_sendHeader')); <ide> $this->Controller->RequestHandler->request = $this->Controller->request; <ide> public function testAjaxRedirectAsRequestActionStillRenderingLayout() { <ide> $result = ob_get_clean(); <ide> $this->assertRegExp('/posts index/', $result, 'RequestAction redirect failed.'); <ide> $this->assertRegExp('/Ajax!/', $result, 'Layout was not rendered.'); <del> <del> App::build(); <ide> } <ide> <ide> /** <ide> public function testAjaxRedirectAsRequestActionStillRenderingLayout() { <ide> * @return void <ide> */ <ide> public function testBeforeRedirectCallbackWithArrayUrl() { <add> Configure::write('App.namespace', 'TestApp'); <add> Router::connect('/:controller/:action/*'); <ide> $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'; <ide> <ide> Router::setRequestInfo(array( <ide> array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array()), <del> array('base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/') <add> array('base' => '', 'here' => '/accounts/', 'webroot' => '/') <ide> )); <ide> <del> $RequestHandler = $this->getMock('Cake\Controller\Component\RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components)); <add> $RequestHandler = $this->getMock( <add> 'Cake\Controller\Component\RequestHandlerComponent', <add> array('_stop'), <add> array(&$this->Controller->Components) <add> ); <ide> $RequestHandler->response = $this->getMock('Cake\Network\Response', array('_sendHeader')); <ide> $RequestHandler->request = new Request('posts/index'); <ide> $RequestHandler->response = $this->getMock('Cake\Network\Response', array('_sendHeader'));
1
Python
Python
use lamportclock from kombu.clocks instead
007804e8c96a59fc75727aa66eae1ad47b39cbc4
<ide><path>celery/app/base.py <ide> from functools import wraps <ide> from threading import Lock <ide> <add>from kombu.clocks import LamportClock <add> <ide> from .. import datastructures <ide> from .. import platforms <ide> from ..utils import cached_property, instantiate, lpmerge <ide> settings -> transport:%(transport)s results:%(results)s <ide> """ <ide> <del> <del>class LamportClock(object): <del> """Lamport's logical clock. <del> <del> From Wikipedia: <del> <del> "A Lamport logical clock is a monotonically incrementing software counter <del> maintained in each process. It follows some simple rules: <del> <del> * A process increments its counter before each event in that process; <del> * When a process sends a message, it includes its counter value with <del> the message; <del> * On receiving a message, the receiver process sets its counter to be <del> greater than the maximum of its own value and the received value <del> before it considers the message received. <del> <del> Conceptually, this logical clock can be thought of as a clock that only <del> has meaning in relation to messages moving between processes. When a <del> process receives a message, it resynchronizes its logical clock with <del> the sender. <del> <del> .. seealso:: <del> <del> http://en.wikipedia.org/wiki/Lamport_timestamps <del> http://en.wikipedia.org/wiki/Lamport's_Distributed_ <del> Mutual_Exclusion_Algorithm <del> <del> *Usage* <del> <del> When sending a message use :meth:`forward` to increment the clock, <del> when receiving a message use :meth:`adjust` to sync with <del> the time stamp of the incoming message. <del> <del> """ <del> #: The clocks current value. <del> value = 0 <del> <del> def __init__(self, initial_value=0): <del> self.value = initial_value <del> self.mutex = Lock() <del> <del> def adjust(self, other): <del> with self.mutex: <del> self.value = max(self.value, other) + 1 <del> <del> def forward(self): <del> with self.mutex: <del> self.value += 1 <del> return self.value <add>def pyimplementation(): <add> if hasattr(_platform, "python_implementation"): <add> return _platform.python_implementation() <add> elif sys.platform.startswith("java"): <add> return "Jython %s" % (sys.platform, ) <add> elif hasattr(sys, "pypy_version_info"): <add> v = ".".join(map(str, sys.pypy_version_info[:3])) <add> if sys.pypy_version_info[3:]: <add> v += "-" + "".join(map(str, sys.pypy_version_info[3:])) <add> return "PyPy %s" % (v, ) <add> else: <add> return "CPython" <ide> <ide> <ide> class Settings(datastructures.ConfigurationView):
1
Javascript
Javascript
convert chain watchers to use arrays
c4bdb77f4625fb134686b8aa52c8ec6a7baaa3a0
<ide><path>packages/ember-metal/lib/watching.js <ide> function addChainWatcher(obj, keyName, node) { <ide> nodes = m.chainWatchers = { __emberproto__: obj }; <ide> } <ide> <del> if (!nodes[keyName]) { nodes[keyName] = {}; } <del> nodes[keyName][guidFor(node)] = node; <add> if (!nodes[keyName]) { nodes[keyName] = []; } <add> nodes[keyName].push(node); <ide> Ember.watch(obj, keyName); <ide> } <ide> <ide> function removeChainWatcher(obj, keyName, node) { <ide> var m = metaFor(obj, false), <ide> nodes = m.chainWatchers; <ide> if (!nodes || nodes.__emberproto__ !== obj) { return; } //nothing to do <del> if (nodes[keyName]) { delete nodes[keyName][guidFor(node)]; } <add> if (nodes[keyName]) { <add> nodes = nodes[keyName]; <add> for (var i = 0, l = nodes.length; i < l; i++) { <add> if (nodes[i] === node) { nodes.splice(i, 1); } <add> } <add> } <ide> Ember.unwatch(obj, keyName); <ide> } <ide> <ide> function notifyChains(obj, m, keyName, methodName, arg) { <ide> nodes = nodes[keyName]; <ide> if (!nodes) { return; } <ide> <del> for(var key in nodes) { <del> if (!nodes.hasOwnProperty(key)) { continue; } <del> nodes[key][methodName](arg); <add> for(var i = 0, l = nodes.length; i < l; i++) { <add> nodes[i][methodName](arg); <ide> } <ide> } <ide> <ide><path>packages/ember-metal/tests/watching/watch_test.js <ide> test('when watching a global object, destroy should remove chain watchers from t <ide> <ide> var meta_Global = Ember.meta(Global); <ide> var chainNode = Ember.meta(obj).chains._chains.Global._chains.foo; <del> var guid = Ember.guidFor(chainNode); <add> var index = meta_Global.chainWatchers.foo.indexOf(chainNode); <ide> <ide> equal(meta_Global.watching.foo, 1, 'should be watching foo'); <del> strictEqual(meta_Global.chainWatchers.foo[guid], chainNode, 'should have chain watcher'); <add> strictEqual(meta_Global.chainWatchers.foo[index], chainNode, 'should have chain watcher'); <ide> <ide> Ember.destroy(obj); <ide> <add> index = meta_Global.chainWatchers.foo.indexOf(chainNode); <ide> equal(meta_Global.watching.foo, 0, 'should not be watching foo'); <del> strictEqual(meta_Global.chainWatchers.foo[guid], undefined, 'should not have chain watcher'); <add> equal(index, -1, 'should not have chain watcher'); <ide> <ide> Global = null; // reset <ide> }); <ide> test('when watching another object, destroy should remove chain watchers from th <ide> <ide> var meta_objB = Ember.meta(objB); <ide> var chainNode = Ember.meta(objA).chains._chains.b._chains.foo; <del> var guid = Ember.guidFor(chainNode); <add> var index = meta_objB.chainWatchers.foo.indexOf(chainNode); <ide> <ide> equal(meta_objB.watching.foo, 1, 'should be watching foo'); <del> strictEqual(meta_objB.chainWatchers.foo[guid], chainNode, 'should have chain watcher'); <add> strictEqual(meta_objB.chainWatchers.foo[index], chainNode, 'should have chain watcher'); <ide> <ide> Ember.destroy(objA); <ide> <add> index = meta_objB.chainWatchers.foo.indexOf(chainNode); <ide> equal(meta_objB.watching.foo, 0, 'should not be watching foo'); <del> strictEqual(meta_objB.chainWatchers.foo[guid], undefined, 'should not have chain watcher'); <add> equal(index, -1, 'should not have chain watcher'); <ide> });
2
Python
Python
fix runtests --benchmark-compare in python 3
3eac0cf37869aca0f4cf91f5ae703e63c6a97bbc
<ide><path>runtests.py <ide> def main(argv): <ide> <ide> # Fix commit ids (HEAD is local to current repo) <ide> out = subprocess.check_output(['git', 'rev-parse', commit_b]) <del> commit_b = out.strip() <add> commit_b = out.strip().decode('ascii') <ide> <ide> out = subprocess.check_output(['git', 'rev-parse', commit_a]) <del> commit_a = out.strip() <add> commit_a = out.strip().decode('ascii') <ide> <ide> cmd = ['asv', 'continuous', '-e', '-f', '1.05', <ide> commit_a, commit_b] + bench_args
1
Java
Java
update copyright header
48e834dfd1f5158913c44fcc40081f0d0d9cb370
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/AsyncWebRequestInterceptor.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2017 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.
1
Javascript
Javascript
add detox tests for textinput
fb5d95177b0771d4bb1b4d8ddab8054e6d653903
<ide><path>RNTester/e2e/__tests__/TextInput-test.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @emails oncall+react_native <add> * @format <add> */ <add> <add>/* global device, element, by, expect */ <add>const { <add> openComponentWithLabel, <add> openExampleWithTitle, <add>} = require('../e2e-helpers'); <add> <add>describe('TextInput', () => { <add> beforeAll(async () => { <add> await device.reloadReactNative(); <add> await openComponentWithLabel( <add> '<TextInput>', <add> 'Single and multi-line text inputs.', <add> ); <add> }); <add> <add> it('Live rewrite with spaces should replace spaces and enforce max length', async () => { <add> await openExampleWithTitle('Live Re-Write \\(<sp>'); <add> <add> await element(by.id('rewrite_sp_underscore_input')).typeText( <add> 'this is a long sentence', <add> ); <add> await expect(element(by.id('rewrite_sp_underscore_input'))).toHaveText( <add> 'this_is_a_long_sente', <add> ); <add> }); <add> <add> it('Live rewrite with no spaces should remove spaces', async () => { <add> await openExampleWithTitle('Live Re-Write \\(no spaces'); <add> <add> await element(by.id('rewrite_no_sp_input')).typeText( <add> 'this is a long sentence', <add> ); <add> await expect(element(by.id('rewrite_no_sp_input'))).toHaveText( <add> 'thisisalongsentence', <add> ); <add> }); <add> <add> it('Live rewrite with clear should remove spaces and clear', async () => { <add> await openExampleWithTitle('and clear'); <add> <add> await element(by.id('rewrite_clear_input')).typeText( <add> 'this is a long sentence', <add> ); <add> await expect(element(by.id('rewrite_clear_input'))).toHaveText( <add> 'thisisalongsentence', <add> ); <add> <add> await element(by.id('rewrite_clear_button')).tap(); <add> <add> await expect(element(by.id('rewrite_clear_input'))).toHaveText(''); <add> }); <add>}); <ide><path>RNTester/js/examples/TextInput/TextInputSharedExamples.js <ide> class RewriteExample extends React.Component<$FlowFixMeProps, any> { <ide> return ( <ide> <View style={styles.rewriteContainer}> <ide> <TextInput <add> testID="rewrite_sp_underscore_input" <add> autoCorrect={false} <ide> multiline={false} <ide> maxLength={limit} <ide> onChangeText={text => { <ide> class RewriteExampleInvalidCharacters extends React.Component< <ide> return ( <ide> <View style={styles.rewriteContainer}> <ide> <TextInput <add> testID="rewrite_no_sp_input" <add> autoCorrect={false} <ide> multiline={false} <ide> onChangeText={text => { <ide> this.setState({text: text.replace(/\s/g, '')}); <ide> class RewriteInvalidCharactersAndClearExample extends React.Component< <ide> return ( <ide> <View style={styles.rewriteContainer}> <ide> <TextInput <add> testID="rewrite_clear_input" <add> autoCorrect={false} <ide> ref={ref => { <ide> this.inputRef = ref; <ide> }} <ide> class RewriteInvalidCharactersAndClearExample extends React.Component< <ide> value={this.state.text} <ide> /> <ide> <Button <add> testID="rewrite_clear_button" <ide> onPress={() => { <ide> if (this.inputRef != null) { <ide> this.inputRef.clear();
2
Ruby
Ruby
eliminate a ruby warning in a test in action view
08eafc9646aa05e1c3408a9d32a26deb7d2c8fa0
<ide><path>actionview/test/template/form_helper_test.rb <ide> def test_inputs_use_before_type_cast_to_retain_information_from_validations_like <ide> end <ide> <ide> def test_inputs_dont_use_before_type_cast_when_value_did_not_come_from_user <del> def @post.id_came_from_user?; false; end <add> class << @post <add> undef id_came_from_user? <add> def id_came_from_user?; false; end <add> end <add> <ide> assert_dom_equal( <ide> %{<textarea id="post_id" name="post[id]">\n0</textarea>}, <ide> text_area("post", "id")
1
PHP
PHP
update error message
421eff96029398e7fa9cb20deefe4c8ea5c74037
<ide><path>src/Mailer/Mailer.php <ide> public function getTransport(): AbstractTransport <ide> { <ide> if ($this->transport === null) { <ide> throw new BadMethodCallException( <del> 'Transport was not defined. You must set on using setTransport() or set `transport` option in profile.' <add> 'Transport was not defined. You must set on using setTransport() or set `transport` option in your mailer profile.' <ide> ); <ide> } <ide>
1
Text
Text
fix typo in changelog_v6.md
c79b08136776c82411720d8f211675057e996d77
<ide><path>doc/changelogs/CHANGELOG_V6.md <ide> </tr> <ide> <tr> <ide> <td valign="top"> <del><a href="#6.10.1">6.10.2</a><br/> <add><a href="#6.10.2">6.10.2</a><br/> <ide> <a href="#6.10.1">6.10.1</a><br/> <ide> <a href="#6.10.0">6.10.0</a><br/> <ide> <a href="#6.9.5">6.9.5</a><br/>
1
PHP
PHP
update docblock for php analyses
f294134e2404dca84db92efa193ba574174cef30
<ide><path>src/Illuminate/Http/Resources/Json/JsonResource.php <ide> public function __construct($resource) <ide> /** <ide> * Create a new resource instance. <ide> * <del> * @param dynamic $parameters <add> * @param mixed $parameters <ide> * @return static <ide> */ <ide> public static function make(...$parameters)
1
Ruby
Ruby
fix lots of code highlighting issues
a07f2ace036e86060305d2ac0ad1a15950e2c932
<ide><path>actioncable/lib/action_cable/remote_connections.rb <ide> module ActionCable <ide> # it uses the internal channel that all of these servers are subscribed to. <ide> # <ide> # By default, server sends a "disconnect" message with "reconnect" flag set to true. <del> # You can override it by specifying the `reconnect` option: <add> # You can override it by specifying the +reconnect+ option: <ide> # <ide> # ActionCable.server.remote_connections.where(current_user: User.find(1)).disconnect(reconnect: false) <ide> class RemoteConnections <ide><path>actionview/lib/action_view/helpers/content_exfiltration_prevention_helper.rb <ide> module ContentExfiltrationPreventionHelper <ide> # <meta http-equiv="refresh" content='0;URL=https://attacker.com? <ide> # <ide> # The HTML following this tag, up until the next single quote would be sent to <del> # https://attacker.com. By closing any open attributes, we ensure that form <add> # +https://attacker.com+. By closing any open attributes, we ensure that form <ide> # contents are never exfiltrated this way. <ide> CLOSE_QUOTES_COMMENT = %q(<!-- '"` -->).html_safe.freeze <ide> <ide> module ContentExfiltrationPreventionHelper <ide> # <ide> # For example, an attacker might inject: <ide> # <del> # <form action="https://attacker.com"><textarea> <add> # <form action="https://attacker.com"><textarea> <ide> # <del> # The HTML following this tag, up until the next `</textarea>` or the end of <del> # the document would be captured by the attacker's <textarea>. By closing any <del> # open textarea tags, we ensure that form contents are never exfiltrated. <add> # The HTML following this tag, up until the next <tt></textarea></tt> or <add> # the end of the document would be captured by the attacker's <add> # <tt><textarea></tt>. By closing any open textarea tags, we ensure that <add> # form contents are never exfiltrated. <ide> CLOSE_CDATA_COMMENT = "<!-- </textarea></xmp> -->".html_safe.freeze <ide> <ide> # Close any open option tags before each form tag. This prevents attackers <ide> # from injecting unclosed options that could leak markup offsite. <ide> # <ide> # For example, an attacker might inject: <ide> # <del> # <form action="https://attacker.com"><option> <add> # <form action="https://attacker.com"><option> <ide> # <del> # The HTML following this tag, up until the next `</option>` or the end of <del> # the document would be captured by the attacker's <option>. By closing any <del> # open option tags, we ensure that form contents are never exfiltrated. <add> # The HTML following this tag, up until the next <tt></option></tt> or the <add> # end of the document would be captured by the attacker's <add> # <tt><option></tt>. By closing any open option tags, we ensure that form <add> # contents are never exfiltrated. <ide> CLOSE_OPTION_TAG = "</option>".html_safe.freeze <ide> <ide> # Close any open form tags before each new form tag. This prevents attackers <ide> # from injecting unclosed forms that could leak markup offsite. <ide> # <ide> # For example, an attacker might inject: <ide> # <del> # <form action="https://attacker.com"> <add> # <form action="https://attacker.com"> <ide> # <del> # The form elements following this tag, up until the next `</form>` would be <del> # captured by the attacker's <form>. By closing any open form tags, we <del> # ensure that form contents are never exfiltrated. <add> # The form elements following this tag, up until the next <tt></form></tt> <add> # would be captured by the attacker's <tt><form></tt>. By closing any open <add> # form tags, we ensure that form contents are never exfiltrated. <ide> CLOSE_FORM_TAG = "</form>".html_safe.freeze <ide> <ide> CONTENT_EXFILTRATION_PREVENTION_MARKUP = (CLOSE_QUOTES_COMMENT + CLOSE_CDATA_COMMENT + CLOSE_OPTION_TAG + CLOSE_FORM_TAG).freeze <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb <ide> def all_connection_pools <ide> connection_name_to_pool_manager.values.flat_map { |m| m.pool_configs.map(&:pool) } <ide> end <ide> <del> # Returns the pools for a connection handler and given role. If `:all` is passed, <add> # Returns the pools for a connection handler and given role. If +:all+ is passed, <ide> # all pools belonging to the connection handler will be returned. <ide> def connection_pool_list(role = nil) <ide> if role.nil? <ide><path>activerecord/lib/active_record/middleware/database_selector.rb <ide> module Middleware <ide> # config.active_record.database_resolver = MyResolver <ide> # config.active_record.database_resolver_context = MyResolver::MySession <ide> # <del> # Note: If you are using `rails new my_app --minimal` you will need to call <del> # `require "active_support/core_ext/integer/time"` to load the libraries <del> # for +Time+. <add> # Note: If you are using <tt>rails new my_app --minimal</tt> you will need <add> # to call <tt>require "active_support/core_ext/integer/time"</tt> to load <add> # the core extension in order to use +2.seconds+ <ide> class DatabaseSelector <ide> def initialize(app, resolver_klass = nil, context_klass = nil, options = {}) <ide> @app = app <ide><path>activerecord/lib/active_record/readonly_attributes.rb <ide> module ClassMethods <ide> # Attributes listed as readonly will be used to create a new record. <ide> # Assigning a new value to a readonly attribute on a persisted record raises an error. <ide> # <del> # By setting `config.active_record.raise_on_assign_to_attr_readonly` to `false`, it will <del> # not raise. The value will change in memory, but will not be persisted on `save`. <add> # By setting +config.active_record.raise_on_assign_to_attr_readonly+ to +false+, it will <add> # not raise. The value will change in memory, but will not be persisted on +save+. <ide> # <ide> # ==== Examples <ide> # <ide><path>activerecord/lib/active_record/relation/batches.rb <ide> def find_in_batches(start: nil, finish: nil, batch_size: 1000, error_on_ignore: <ide> # * <tt>:use_ranges</tt> - Specifies whether to use range iteration (id >= x AND id <= y). <ide> # It can make iterating over the whole or almost whole tables several times faster. <ide> # Only whole table iterations use this style of iteration by default. You can disable this behavior by passing +false+. <del> # If you iterate over the table and the only condition is, e.g., `archived_at: nil` (and only a tiny fraction <add> # If you iterate over the table and the only condition is, e.g., <tt>archived_at: nil</tt> (and only a tiny fraction <ide> # of the records are archived), it makes sense to opt in to this approach. <ide> # <ide> # Limits are honored, and if present there is no requirement for the batch <ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def _select!(*fields) # :nodoc: <ide> # # ) <ide> # # SELECT * FROM posts JOIN posts_with_tags ON posts_with_tags.id = posts.id <ide> # <del> # It is recommended to pass a query as `ActiveRecord::Relation`. If that is not possible <add> # It is recommended to pass a query as ActiveRecord::Relation. If that is not possible <ide> # and you have verified it is safe for the database, you can pass it as SQL literal <del> # using `Arel`. <add> # using +Arel+. <ide> # <ide> # Post.with(popular_posts: Arel.sql("... complex sql to calculate posts popularity ...")) <ide> # <ide> def _select!(*fields) # :nodoc: <ide> # posts_with_tags: Post.where("tags_count > ?", 0) <ide> # ) <ide> # <del> # or chain multiple `.with` calls <add> # or chain multiple +.with+ calls <ide> # <ide> # Post <ide> # .with(posts_with_comments: Post.where("comments_count > ?", 0)) <ide><path>activestorage/app/models/active_storage/blob.rb <ide> def create_before_direct_upload!(key: nil, filename:, byte_size:, checksum:, con <ide> # To prevent problems with case-insensitive filesystems, especially in combination <ide> # with databases which treat indices as case-sensitive, all blob keys generated are going <ide> # to only contain the base-36 character alphabet and will therefore be lowercase. To maintain <del> # the same or higher amount of entropy as in the base-58 encoding used by `has_secure_token` <add> # the same or higher amount of entropy as in the base-58 encoding used by +has_secure_token+ <ide> # the number of bytes used is increased to 28 from the standard 24 <ide> def generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) <ide> SecureRandom.base36(length) <ide><path>activesupport/lib/active_support/notifications/fanout.rb <ide> def groups_for(name) # :nodoc: <ide> groups <ide> end <ide> <del> # A Handle is used to record the start and finish time of event <add> # A +Handle+ is used to record the start and finish time of event <ide> # <del> # Both `#start` and `#finish` must each be called exactly once <add> # Both #start and #finish must each be called exactly once <ide> # <del> # Where possible, it's best to the block form, +ActiveSupport::Notifications.instrument+ <add> # Where possible, it's best to the block form, ActiveSupport::Notifications.instrument. <ide> # +Handle+ is a low-level API intended for cases where the block form can't be used. <ide> # <ide> # handle = ActiveSupport::Notifications.instrumenter.build_handle("my.event", {})
9
Javascript
Javascript
give an id to each gitrepository
ce105ab9140302de496130e9079fb3b9e9fc91b5
<ide><path>src/git-repository.js <ide> const fs = require('fs-plus') <ide> const path = require('path') <ide> const GitUtils = require('git-utils') <ide> <add>let nextId = 0 <add> <ide> // Extended: Represents the underlying git operations performed by Atom. <ide> // <ide> // This class shouldn't be instantiated directly but instead by accessing the <ide> class GitRepository { <ide> } <ide> <ide> constructor (path, options = {}) { <add> this.id = nextId++ <ide> this.emitter = new Emitter() <ide> this.subscriptions = new CompositeDisposable() <ide> this.repo = GitUtils.open(path) <ide> class GitRepository { <ide> // This destroys any tasks and subscriptions and releases the underlying <ide> // libgit2 repository handle. This method is idempotent. <ide> destroy () { <add> this.repo = null <add> <ide> if (this.emitter) { <ide> this.emitter.emit('did-destroy') <ide> this.emitter.dispose() <ide> this.emitter = null <ide> } <ide> <del> if (this.repo) { <del> this.repo = null <del> } <del> <ide> if (this.subscriptions) { <ide> this.subscriptions.dispose() <ide> this.subscriptions = null
1
Python
Python
extend list of stopwords for ru language
aa93b471a1cadb661c063dee4913ad8f2e492d48
<ide><path>spacy/lang/ru/stop_words.py <ide> STOP_WORDS = set( <ide> """ <del>а <add>а авось ага агу аж ай али алло ау ах ая <ide> <del>будем будет будете будешь буду будут будучи будь будьте бы был была были было <del>быть <add>б будем будет будете будешь буду будут будучи будь будьте бы был была были было <add>быть бац без безусловно бишь благо благодаря ближайшие близко более больше <add>будто бывает бывала бывали бываю бывают бытует <ide> <ide> в вам вами вас весь во вот все всё всего всей всем всём всеми всему всех всею <del>всея всю вся вы <add>всея всю вся вы ваш ваша ваше ваши вдали вдобавок вдруг ведь везде вернее <add>взаимно взаправду видно вишь включая вместо внакладе вначале вне вниз внизу <add>вновь вовсе возможно воистину вокруг вон вообще вопреки вперекор вплоть <add>вполне вправду вправе впрочем впрямь вресноту вроде вряд всегда всюду <add>всякий всякого всякой всячески вчеред <ide> <del>да для до <add>г го где гораздо гав <ide> <del>его едим едят ее её ей ел ела ем ему емъ если ест есть ешь еще ещё ею <add>д да для до дабы давайте давно давным даже далее далеко дальше данная <add>данного данное данной данном данному данные данный данных дану данунах <add>даром де действительно довольно доколе доколь долго должен должна <add>должно должны должный дополнительно другая другие другим другими <add>других другое другой <ide> <del>же <add>е его едим едят ее её ей ел ела ем ему емъ если ест есть ешь еще ещё ею едва <add>ежели еле <ide> <del>за <add>ж же <ide> <del>и из или им ими имъ их <add>з за затем зато зачем здесь значит зря <add> <add>и из или им ими имъ их ибо иль имеет имел имела имело именно иметь иначе <add>иногда иным иными итак ишь <add> <add>й <ide> <ide> к как кем ко когда кого ком кому комья которая которого которое которой котором <del>которому которою которую которые который которым которыми которых кто <add>которому которою которую которые который которым которыми которых кто ка кабы <add>каждая каждое каждые каждый кажется казалась казались казалось казался казаться <add>какая какие каким какими каков какого какой какому какою касательно кой коли <add>коль конечно короче кроме кстати ку куда <add> <add>л ли либо лишь любая любого любое любой любом любую любыми любых <ide> <del>меня мне мной мною мог моги могите могла могли могло могу могут мое моё моего <add>м меня мне мной мною мог моги могите могла могли могло могу могут мое моё моего <ide> моей моем моём моему моею можем может можете можешь мои мой моим моими моих <del>мочь мою моя мы <add>мочь мою моя мы мало меж между менее меньше мимо многие много многого многое <add>многом многому можно мол му <ide> <del>на нам нами нас наса наш наша наше нашего нашей нашем нашему нашею наши нашим <add>н на нам нами нас наса наш наша наше нашего нашей нашем нашему нашею наши нашим <ide> нашими наших нашу не него нее неё ней нем нём нему нет нею ним ними них но <add>наверняка наверху навряд навыворот над надо назад наиболее наизворот <add>наизнанку наипаче накануне наконец наоборот наперед наперекор наподобие <add>например напротив напрямую насилу настоящая настоящее настоящие настоящий <add>насчет нате находиться начала начале неважно негде недавно недалеко незачем <add>некем некогда некому некоторая некоторые некоторый некоторых некто некуда <add>нельзя немногие немногим немного необходимо необходимости необходимые <add>необходимым неоткуда непрерывно нередко несколько нету неужели нечего <add>нечем нечему нечто нешто нибудь нигде ниже низко никак никакой никем <add>никогда никого никому никто никуда ниоткуда нипочем ничего ничем ничему <add>ничто ну нужная нужно нужного нужные нужный нужных ныне нынешнее нынешней <add>нынешних нынче <ide> <ide> о об один одна одни одним одними одних одно одного одной одном одному одною <del>одну он она оне они оно от <add>одну он она оне они оно от оба общую обычно ого однажды однако ой около оный <add>оп опять особенно особо особую особые откуда отнелижа отнелиже отовсюду <add>отсюда оттого оттот оттуда отчего отчему ох очевидно очень ом <ide> <del>по при <add>п по при паче перед под подавно поди подобная подобно подобного подобные <add>подобный подобным подобных поелику пожалуй пожалуйста позже поистине <add>пока покамест поколе поколь покуда покудова помимо понеже поприще пор <add>пора посему поскольку после посреди посредством потом потому потомушта <add>похожем почему почти поэтому прежде притом причем про просто прочего <add>прочее прочему прочими проще прям пусть <add> <add>р ради разве ранее рано раньше рядом <ide> <ide> с сам сама сами самим самими самих само самого самом самому саму свое своё <ide> своего своей своем своём своему своею свои свой своим своими своих свою своя <del>себе себя собой собою <add>себе себя собой собою самая самое самой самый самых сверх свыше се сего сей <add>сейчас сие сих сквозь сколько скорее скоро следует слишком смогут сможет <add>сначала снова со собственно совсем сперва спокону спустя сразу среди сродни <add>стал стала стали стало стать суть сызнова <add> <add>та то ту ты ти так такая такие таким такими таких такого такое такой таком такому такою <add>такую те тебе тебя тем теми тех тобой тобою того той только том томах тому <add>тот тою также таки таков такова там твои твоим твоих твой твоя твоё <add>теперь тогда тоже тотчас точно туда тут тьфу тая <add> <add>у уже увы уж ура ух ую <add> <add>ф фу <add> <add>х ха хе хорошо хотел хотела хотелось хотеть хоть хотя хочешь хочу хуже <add> <add>ч чего чем чём чему что чтобы часто чаще чей через чтоб чуть чхать чьим <add>чьих чьё чё <add> <add>ш ша <ide> <del>та так такая такие таким такими таких такого такое такой таком такому такою <del>такую те тебе тебя тем теми тех то тобой тобою того той только том томах тому <del>тот тою ту ты <add>щ ща щас <ide> <del>у уже <add>ы ых ые ый <ide> <del>чего чем чём чему что чтобы <add>э эта эти этим этими этих это этого этой этом этому этот этою эту эдак эдакий <add>эй эка экий этак этакий эх <ide> <del>эта эти этим этими этих это этого этой этом этому этот этою эту <add>ю <ide> <del>я <add>я явно явных яко якобы якоже <ide> """.split() <ide> )
1
Ruby
Ruby
skip another test when arconn=sqlite3_mem
b8bd24d93825684e2311d085266cf66b4fb45368
<ide><path>activerecord/test/cases/migration/foreign_key_test.rb <ide> def test_schema_dumping_with_defferable_initially_immediate <ide> end <ide> <ide> def test_does_not_create_foreign_keys_when_bypassed_by_config <del> connection = ActiveRecord::Base.establish_connection( <del> { <del> adapter: "sqlite3", <del> database: "test/db/test.sqlite3", <del> foreign_keys: false, <del> } <del> ).connection <del> <del> connection.create_table "rockets", force: true do |t| <del> t.string :name <del> end <del> connection.create_table "astronauts", force: true do |t| <del> t.string :name <del> t.references :rocket <del> end <add> if current_adapter?(:SQLite3Adapter) && !ActiveRecord::Base.connection.supports_concurrent_connections? <add> skip("Can't reopen in-memory database") <add> else <add> begin <add> connection = ActiveRecord::Base.establish_connection( <add> { <add> adapter: "sqlite3", <add> database: "test/db/test.sqlite3", <add> foreign_keys: false, <add> } <add> ).connection <add> <add> connection.create_table "rockets", force: true do |t| <add> t.string :name <add> end <add> connection.create_table "astronauts", force: true do |t| <add> t.string :name <add> t.references :rocket <add> end <ide> <del> connection.add_foreign_key :astronauts, :rockets <add> connection.add_foreign_key :astronauts, :rockets <ide> <del> foreign_keys = connection.foreign_keys("astronauts") <del> assert_equal 0, foreign_keys.size <del> ensure <del> connection.drop_table "astronauts", if_exists: true rescue nil <del> connection.drop_table "rockets", if_exists: true rescue nil <add> foreign_keys = connection.foreign_keys("astronauts") <add> assert_equal 0, foreign_keys.size <add> ensure <add> connection.drop_table "astronauts", if_exists: true rescue nil <add> connection.drop_table "rockets", if_exists: true rescue nil <ide> <del> ActiveRecord::Base.establish_connection(:arunit) <add> ActiveRecord::Base.establish_connection(:arunit) <add> end <add> end <ide> end <ide> <ide> def test_schema_dumping
1
Ruby
Ruby
fix comment syntax
9e8592c2170a436af58f6459480b5281e8ad809b
<ide><path>railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb <ide> class ResourceRouteGenerator < NamedBase # :nodoc: <ide> # should give you <ide> # <ide> # namespace :admin do <del> # namespace :users <add> # namespace :users do <ide> # resources :products <ide> # end <ide> # end
1
PHP
PHP
update typehints for form/
cfb5bcf32c5a01f300baf8ea071afd241f7b37a6
<ide><path>src/Form/Form.php <ide> public function validate(array $data): bool <ide> * <ide> * @return array Last set validation errors. <ide> */ <del> public function getErrors() <add> public function getErrors(): array <ide> { <ide> return $this->_errors; <ide> } <ide><path>src/Form/Schema.php <ide> public function addFields(array $fields) <ide> * as a string. <ide> * @return $this <ide> */ <del> public function addField($name, $attrs) <add> public function addField(string $name, $attrs) <ide> { <ide> if (is_string($attrs)) { <ide> $attrs = ['type' => $attrs]; <ide> public function addField($name, $attrs) <ide> * @param string $name The field to remove. <ide> * @return $this <ide> */ <del> public function removeField($name) <add> public function removeField(string $name) <ide> { <ide> unset($this->_fields[$name]); <ide>
2
PHP
PHP
fix collection check
ba32303ad004b05850afb7b230fa81df34291b0a
<ide><path>src/View/Form/EntityContext.php <ide> protected function _prepare(): void <ide> $table = $this->_context['table']; <ide> /** @var \Cake\Datasource\EntityInterface|iterable $entity */ <ide> $entity = $this->_context['entity']; <add> <add> $this->_isCollection = is_iterable($entity); <add> <ide> if (empty($table)) { <del> if (is_iterable($entity)) { <add> if ($this->_isCollection) { <ide> foreach ($entity as $e) { <ide> $entity = $e; <ide> break; <ide> protected function _prepare(): void <ide> 'Unable to find table class for current entity.' <ide> ); <ide> } <del> $this->_isCollection = ( <del> is_array($entity) || <del> $entity instanceof Traversable <del> ); <ide> <ide> $alias = $this->_rootName = $table->getAlias(); <ide> $this->_tables[$alias] = $table; <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> public function testCollectionOperationsNoTableArg($collection): void <ide> <ide> $result = $context->error('1.body'); <ide> $this->assertEquals(['Not long enough'], $result); <add> <add> $this->assertNull($context->val('0')); <ide> } <ide> <ide> /**
2
Go
Go
remove graphdriver indexing by os (used for lcow)
076d9c60373d90284005ce363572995c539396fb
<ide><path>daemon/daemon.go <ide> var ( <ide> <ide> // Daemon holds information about the Docker daemon. <ide> type Daemon struct { <del> ID string <del> repository string <del> containers container.Store <del> containersReplica container.ViewDB <del> execCommands *exec.Store <del> imageService *images.ImageService <del> idIndex *truncindex.TruncIndex <del> configStore *config.Config <del> statsCollector *stats.Collector <del> defaultLogConfig containertypes.LogConfig <del> RegistryService registry.Service <del> EventsService *events.Events <del> netController libnetwork.NetworkController <del> volumes *volumesservice.VolumesService <del> discoveryWatcher discovery.Reloader <del> root string <del> seccompEnabled bool <del> apparmorEnabled bool <del> shutdown bool <del> idMapping *idtools.IdentityMapping <del> // TODO: move graphDrivers field to an InfoService <del> graphDrivers map[string]string // By operating system <del> <del> PluginStore *plugin.Store // todo: remove <add> ID string <add> repository string <add> containers container.Store <add> containersReplica container.ViewDB <add> execCommands *exec.Store <add> imageService *images.ImageService <add> idIndex *truncindex.TruncIndex <add> configStore *config.Config <add> statsCollector *stats.Collector <add> defaultLogConfig containertypes.LogConfig <add> RegistryService registry.Service <add> EventsService *events.Events <add> netController libnetwork.NetworkController <add> volumes *volumesservice.VolumesService <add> discoveryWatcher discovery.Reloader <add> root string <add> seccompEnabled bool <add> apparmorEnabled bool <add> shutdown bool <add> idMapping *idtools.IdentityMapping <add> graphDriver string // TODO: move graphDriver field to an InfoService <add> PluginStore *plugin.Store // TODO: remove <ide> pluginManager *plugin.Manager <ide> linkIndex *linkIndex <ide> containerdCli *containerd.Client <ide> func (daemon *Daemon) restore() error { <ide> return <ide> } <ide> // Ignore the container if it does not support the current driver being used by the graph <del> currentDriverForContainerOS := daemon.graphDrivers[c.OS] <del> if (c.Driver == "" && currentDriverForContainerOS == "aufs") || c.Driver == currentDriverForContainerOS { <add> if (c.Driver == "" && daemon.graphDriver == "aufs") || c.Driver == daemon.graphDriver { <ide> rwlayer, err := daemon.imageService.GetLayerByID(c.ID, c.OS) <ide> if err != nil { <ide> log.WithError(err).Error("failed to load container mount") <ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S <ide> } <ide> } <ide> <del> // On Windows we don't support the environment variable, or a user supplied graphdriver <del> // as Windows has no choice in terms of which graphdrivers to use. It's a case of <del> // running Windows containers on Windows - windowsfilter, running Linux containers on Windows, <del> // lcow. Unix platforms however run a single graphdriver for all containers, and it can <del> // be set through an environment variable, a daemon start parameter, or chosen through <del> // initialization of the layerstore through driver priority order for example. <del> d.graphDrivers = make(map[string]string) <del> layerStores := make(map[string]layer.Store) <ide> if isWindows { <del> d.graphDrivers[runtime.GOOS] = "windowsfilter" <del> if system.LCOWSupported() { <del> d.graphDrivers["linux"] = "lcow" <del> } <add> // On Windows we don't support the environment variable, or a user supplied graphdriver <add> d.graphDriver = "windowsfilter" <ide> } else { <del> driverName := os.Getenv("DOCKER_DRIVER") <del> if driverName == "" { <del> driverName = config.GraphDriver <add> // Unix platforms however run a single graphdriver for all containers, and it can <add> // be set through an environment variable, a daemon start parameter, or chosen through <add> // initialization of the layerstore through driver priority order for example. <add> if drv := os.Getenv("DOCKER_DRIVER"); drv != "" { <add> d.graphDriver = drv <add> logrus.Infof("Setting the storage driver from the $DOCKER_DRIVER environment variable (%s)", drv) <ide> } else { <del> logrus.Infof("Setting the storage driver from the $DOCKER_DRIVER environment variable (%s)", driverName) <add> d.graphDriver = config.GraphDriver // May still be empty. Layerstore init determines instead. <ide> } <del> d.graphDrivers[runtime.GOOS] = driverName // May still be empty. Layerstore init determines instead. <ide> } <ide> <ide> d.RegistryService = registryService <ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S <ide> return nil, err <ide> } <ide> <del> for operatingSystem, gd := range d.graphDrivers { <del> layerStores[operatingSystem], err = layer.NewStoreFromOptions(layer.StoreOptions{ <del> Root: config.Root, <del> MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"), <del> GraphDriver: gd, <del> GraphDriverOptions: config.GraphOptions, <del> IDMapping: idMapping, <del> PluginGetter: d.PluginStore, <del> ExperimentalEnabled: config.Experimental, <del> OS: operatingSystem, <del> }) <del> if err != nil { <del> return nil, err <del> } <del> <del> // As layerstore initialization may set the driver <del> d.graphDrivers[operatingSystem] = layerStores[operatingSystem].DriverName() <add> layerStore, err := layer.NewStoreFromOptions(layer.StoreOptions{ <add> Root: config.Root, <add> MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"), <add> GraphDriver: d.graphDriver, <add> GraphDriverOptions: config.GraphOptions, <add> IDMapping: idMapping, <add> PluginGetter: d.PluginStore, <add> ExperimentalEnabled: config.Experimental, <add> OS: runtime.GOOS, <add> }) <add> if err != nil { <add> return nil, err <ide> } <ide> <add> // As layerstore initialization may set the driver <add> d.graphDriver = layerStore.DriverName() <add> <ide> // Configure and validate the kernels security support. Note this is a Linux/FreeBSD <ide> // operation only, so it is safe to pass *just* the runtime OS graphdriver. <del> if err := configureKernelSecuritySupport(config, d.graphDrivers[runtime.GOOS]); err != nil { <add> if err := configureKernelSecuritySupport(config, d.graphDriver); err != nil { <ide> return nil, err <ide> } <ide> <del> imageRoot := filepath.Join(config.Root, "image", d.graphDrivers[runtime.GOOS]) <add> imageRoot := filepath.Join(config.Root, "image", d.graphDriver) <ide> ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb")) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <del> lgrMap := make(map[string]image.LayerGetReleaser) <del> for los, ls := range layerStores { <del> lgrMap[los] = ls <del> } <del> imageStore, err := image.NewImageStore(ifs, lgrMap) <add> // TODO remove multiple imagestores map now that LCOW is no more <add> imageStore, err := image.NewImageStore(ifs, map[string]image.LayerGetReleaser{ <add> runtime.GOOS: layerStore, <add> }) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S <ide> DistributionMetadataStore: distributionMetadataStore, <ide> EventsService: d.EventsService, <ide> ImageStore: imageStore, <del> LayerStores: layerStores, <add> LayerStores: map[string]layer.Store{runtime.GOOS: layerStore}, // TODO remove multiple LayerStores map now that LCOW is no more <ide> MaxConcurrentDownloads: *config.MaxConcurrentDownloads, <ide> MaxConcurrentUploads: *config.MaxConcurrentUploads, <ide> MaxDownloadAttempts: *config.MaxDownloadAttempts, <ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S <ide> engineCpus.Set(float64(info.NCPU)) <ide> engineMemory.Set(float64(info.MemTotal)) <ide> <del> gd := "" <del> for os, driver := range d.graphDrivers { <del> if len(gd) > 0 { <del> gd += ", " <del> } <del> gd += driver <del> if len(d.graphDrivers) > 1 { <del> gd = fmt.Sprintf("%s (%s)", gd, os) <del> } <del> } <ide> logrus.WithFields(logrus.Fields{ <del> "version": dockerversion.Version, <del> "commit": dockerversion.GitCommit, <del> "graphdriver(s)": gd, <add> "version": dockerversion.Version, <add> "commit": dockerversion.GitCommit, <add> "graphdriver": d.graphDriver, <ide> }).Info("Docker daemon") <ide> <ide> return d, nil <ide><path>daemon/info.go <ide> func (daemon *Daemon) fillClusterInfo(v *types.Info) { <ide> } <ide> <ide> func (daemon *Daemon) fillDriverInfo(v *types.Info) { <del> var ds [][2]string <del> drivers := "" <del> statuses := daemon.imageService.LayerStoreStatus() <del> for os, gd := range daemon.graphDrivers { <del> ds = append(ds, statuses[os]...) <del> drivers += gd <del> if len(daemon.graphDrivers) > 1 { <del> drivers += fmt.Sprintf(" (%s) ", os) <del> } <del> switch gd { <del> case "aufs", "devicemapper", "overlay": <del> v.Warnings = append(v.Warnings, fmt.Sprintf("WARNING: the %s storage-driver is deprecated, and will be removed in a future release.", gd)) <del> } <add> switch daemon.graphDriver { <add> case "aufs", "devicemapper", "overlay": <add> v.Warnings = append(v.Warnings, fmt.Sprintf("WARNING: the %s storage-driver is deprecated, and will be removed in a future release.", daemon.graphDriver)) <ide> } <del> drivers = strings.TrimSpace(drivers) <ide> <del> v.Driver = drivers <del> v.DriverStatus = ds <add> statuses := daemon.imageService.LayerStoreStatus() <add> v.Driver = daemon.graphDriver <add> v.DriverStatus = statuses[runtime.GOOS] <ide> <ide> fillDriverWarnings(v) <ide> }
2
Javascript
Javascript
pass persisted window sessions as folderstoopen
1ecff536c7ad683dbcdbe082190ca4b298b93b46
<ide><path>src/main-process/atom-application.js <ide> class AtomApplication extends EventEmitter { <ide> const { <ide> pathsToOpen, <ide> executedFrom, <add> foldersToOpen, <ide> urlsToOpen, <ide> benchmark, <ide> benchmarkTest, <ide> class AtomApplication extends EventEmitter { <ide> timeout, <ide> env <ide> }) <del> } else if (pathsToOpen.length > 0) { <add> } else if (pathsToOpen.length > 0 || foldersToOpen.length > 0) { <ide> return this.openPaths({ <ide> pathsToOpen, <add> foldersToOpen, <ide> executedFrom, <ide> pidToKillWhenClosed, <ide> devMode, <ide> class AtomApplication extends EventEmitter { <ide> // <ide> // options - <ide> // :pathsToOpen - The array of file paths to open <add> // :foldersToOpen - An array of additional paths to open that must be existing directories <ide> // :pidToKillWhenClosed - The integer of the pid to kill <ide> // :devMode - Boolean to control the opened window's dev mode. <ide> // :safeMode - Boolean to control the opened window's safe mode. <ide> class AtomApplication extends EventEmitter { <ide> // :addToLastWindow - Boolean of whether this should be opened in last focused window. <ide> openPaths ({ <ide> pathsToOpen, <add> foldersToOpen, <ide> executedFrom, <ide> pidToKillWhenClosed, <ide> devMode, <ide> class AtomApplication extends EventEmitter { <ide> addToLastWindow, <ide> env <ide> } = {}) { <del> if (!pathsToOpen || pathsToOpen.length === 0) return <ide> if (!env) env = process.env <add> if (!pathsToOpen) pathsToOpen = [] <add> if (!foldersToOpen) foldersToOpen = [] <add> <ide> devMode = Boolean(devMode) <ide> safeMode = Boolean(safeMode) <ide> clearWindowState = Boolean(clearWindowState) <ide> class AtomApplication extends EventEmitter { <ide> hasWaitSession: pidToKillWhenClosed != null <ide> }) <ide> }) <add> <add> for (const folderToOpen of foldersToOpen) { <add> locationsToOpen.push({ <add> pathToOpen: folderToOpen, <add> initialLine: null, <add> initialColumn: null, <add> mustBeDirectory: true, <add> forceAddToWindow: addToLastWindow, <add> hasWaitSession: pidToKillWhenClosed != null <add> }) <add> } <add> <add> if (locationsToOpen.length === 0) { <add> return <add> } <add> <ide> const normalizedPathsToOpen = locationsToOpen.map(location => location.pathToOpen).filter(Boolean) <ide> <ide> let existingWindow <ide> class AtomApplication extends EventEmitter { <ide> const states = await this.storageFolder.load('application.json') <ide> if (states) { <ide> return states.map(state => ({ <del> pathsToOpen: state.initialPaths, <add> foldersToOpen: state.initialPaths, <ide> urlsToOpen: [], <ide> devMode: this.devMode, <ide> safeMode: this.safeMode
1
PHP
PHP
remove unused variable
e121c1a6886113cd5a5ac8968160928cc02b972f
<ide><path>src/Illuminate/View/ViewServiceProvider.php <ide> public function registerViewFinder() <ide> */ <ide> public function registerEnvironment() <ide> { <del> $me = $this; <del> <del> $this->app['view'] = $this->app->share(function($app) use ($me) <add> $this->app['view'] = $this->app->share(function($app) <ide> { <ide> // Next we need to grab the engine resolver instance that will be used by the <ide> // environment. The resolver will be used by an environment to get each of <ide> public function sessionHasErrors($app) <ide> <ide> } <ide> <del>} <ide>\ No newline at end of file <add>}
1
Java
Java
avoid npe against null value from tostring call
ac581bed92181ce8ddfe629e94629a52e3dc972a
<ide><path>spring-core/src/main/java/org/springframework/core/log/LogFormatUtils.java <ide> import org.apache.commons.logging.Log; <ide> <ide> import org.springframework.lang.Nullable; <add>import org.springframework.util.ObjectUtils; <ide> <ide> /** <ide> * Utility methods for formatting and logging messages. <ide> public static String formatValue( <ide> } <ide> String result; <ide> try { <del> result = value.toString(); <add> result = ObjectUtils.nullSafeToString(value); <ide> } <ide> catch (Throwable ex) { <del> result = ex.toString(); <add> result = ObjectUtils.nullSafeToString(ex); <ide> } <ide> if (maxLength != -1) { <ide> result = (result.length() > maxLength ? result.substring(0, maxLength) + " (truncated)..." : result);
1
Text
Text
fix broken url caused in docs
22f91bb355d7744ce35b73443035591e553e9093
<ide><path>docs/advanced-features/codemods.md <ide> export default withRouter( <ide> ) <ide> ``` <ide> <del>This is just one case. All the cases that are transformed (and tested) can be found in the [`__testfixtures__` directory](./transforms/__testfixtures__/url-to-withrouter). <add>This is just one case. All the cases that are transformed (and tested) can be found in the [`__testfixtures__` directory](https://github.com/vercel/next.js/tree/canary/packages/next-codemod/transforms/__testfixtures__/url-to-withrouter). <ide> <ide> #### Usage <ide>
1
Ruby
Ruby
improve documentation of local_assigns
02b955766e5094c1f0afac04f415632e0463eea8
<ide><path>actionview/lib/action_view/template.rb <ide> class Template <ide> # expected_encoding <ide> # ) <ide> <add> ## <add> # :method: local_assigns <add> # <add> # Returns a hash with the defined local variables. <add> # <add> # Given this sub template rendering: <add> # <add> # <%= render "shared/header", { headline: "Welcome", person: person } %> <add> # <add> # You can use +local_assigns+ in the sub templates to access the local variables: <add> # <add> # local_assigns[:headline] # => "Welcome" <add> <ide> eager_autoload do <ide> autoload :Error <ide> autoload :Handlers <ide> def compile!(view) #:nodoc: <ide> end <ide> end <ide> <del> ## <del> # :method: local_assigns <del> # <del> # Returns a hash with the defined local variables <del> # <del> # local_assigns[:full] # => true <del> <ide> # Among other things, this method is responsible for properly setting <ide> # the encoding of the compiled template. <ide> #
1
Ruby
Ruby
add a finalizer to inline templates
52eafbd7495367aa48192100a922181d097e5b22
<ide><path>actionview/lib/action_view/renderer/template_renderer.rb <ide> def determine_template(options) <ide> else <ide> @lookup_context.formats.first <ide> end <del> Template.new(options[:inline], "inline template", handler, locals: keys, format: format) <add> Template::Inline.new(options[:inline], "inline template", handler, locals: keys, format: format) <ide> elsif options.key?(:template) <ide> if options[:template].respond_to?(:render) <ide> options[:template] <ide><path>actionview/lib/action_view/template.rb <ide> def self.finalize_compiled_template_methods=(_) <ide> autoload :Error <ide> autoload :Handlers <ide> autoload :HTML <add> autoload :Inline <ide> autoload :Text <ide> autoload :Types <ide> end <ide><path>actionview/lib/action_view/template/inline.rb <add># frozen_string_literal: true <add> <add>module ActionView #:nodoc: <add> class Template #:nodoc: <add> class Inline < Template #:nodoc: <add> # This finalizer is needed (and exactly with a proc inside another proc) <add> # otherwise templates leak in development. <add> Finalizer = proc do |method_name, mod| # :nodoc: <add> proc do <add> mod.module_eval do <add> remove_possible_method method_name <add> end <add> end <add> end <add> <add> def compile(mod) <add> super <add> ObjectSpace.define_finalizer(self, Finalizer[method_name, mod]) <add> end <add> end <add> end <add>end
3
Python
Python
add a flag to clear without confirmation
40f1a85850a4946d4db9b9380b663667e7b2788d
<ide><path>airflow/bin/cli.py <ide> def clear(args): <ide> end_date=args.end_date, <ide> only_failed=args.only_failed, <ide> only_running=args.only_running, <del> confirm_prompt=True) <add> confirm_prompt=not args.no_confirm) <ide> <ide> <ide> def webserver(args): <ide> def get_parser(): <ide> parser_clear.add_argument( <ide> "-sd", "--subdir", help=subdir_help, <ide> default=DAGS_FOLDER) <add> parser_clear.add_argument( <add> "-c", "--no_confirm", help=ht, action="store_true") <ide> parser_clear.set_defaults(func=clear) <ide> <ide> ht = "Run a single task instance"
1