content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Ruby | Ruby | introduce an `all` mime type | f8ba48c150fb70ed0bcb8ff74cf2aabc81173082 | <ide><path>actionpack/lib/action_dispatch/http/mime_type.rb
<ide> def html?
<ide> @@html_types.include?(to_sym) || @string =~ /html/
<ide> end
<ide>
<add> def all?; false; end
<ide>
<ide> private
<ide>
<ide> def method_missing(method, *args)
<ide> def respond_to_missing?(method, include_private = false) #:nodoc:
<ide> method.to_s.ends_with? '?'
<ide> end
<add>
<add> class All < Type
<add> def all?; true; end
<add> def html?; true; end
<add> end
<ide> end
<ide>
<ide> class NullType
<ide><path>actionpack/lib/action_dispatch/http/mime_types.rb
<ide> Mime::Type.register "application/zip", :zip, [], %w(zip)
<ide>
<ide> # Create Mime::ALL but do not add it to the SET.
<del>Mime::Type.add_type :ALL, Mime::Type.new("*/*", :all, [])
<add>Mime::Type.add_type :ALL, Mime::Type::All.new("*/*", :all, [])
<ide><path>actionpack/test/dispatch/mime_type_test.rb
<ide> class MimeTypeTest < ActiveSupport::TestCase
<ide> types.each do |type|
<ide> mime = Mime::Type[type.upcase]
<ide> assert mime.respond_to?("#{type}?"), "#{mime.inspect} does not respond to #{type}?"
<del> assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?"
<add> assert_equal type, mime.symbol, "#{mime.inspect} is not #{type}?"
<ide> invalid_types = types - [type]
<ide> invalid_types.delete(:html) if Mime::Type.html_types.include?(type)
<del> invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" }
<add> invalid_types.each { |other_type|
<add> assert_not_equal mime.symbol, other_type, "#{mime.inspect} is #{other_type}?"
<add> }
<ide> end
<ide> end
<ide> | 3 |
Javascript | Javascript | add tests for obj.assign util | fcb5aa83833829826b81d66f80620ee98c03f863 | <ide><path>test/unit/utils/obj.test.js
<ide> QUnit.test('isPlain', function(assert) {
<ide> 'string': 'xyz'
<ide> });
<ide> });
<add>
<add>QUnit.module('utils/obj.assign', function() {
<add> const assignTests = ['mocked'];
<add>
<add> // we only run "normal" tests where Object.assign is used when
<add> // Object.assign is supported
<add> if (Object.assign) {
<add> assignTests.push('unmocked');
<add> }
<add>
<add> assignTests.forEach(function(k) {
<add> QUnit.module(`with ${k} Object.assign`, {
<add> before() {
<add> if (k === 'mocked') {
<add> this.oldObjectAssign = Object.assign;
<add> Object.assign = null;
<add> }
<add> },
<add> after() {
<add> if (this.oldObjectAssign) {
<add> Object.assign = this.oldObjectAssign;
<add> }
<add> this.oldObjectAssign = null;
<add> }
<add> });
<add>
<add> QUnit.test('override object', function(assert) {
<add> const foo = {foo: 'yellow'};
<add>
<add> assert.deepEqual(Obj.assign(foo, {foo: 'blue'}), {foo: 'blue'}, 'Obj.assign should return overriden result');
<add> assert.deepEqual(foo, {foo: 'blue'}, 'foo should be modified directly');
<add> });
<add>
<add> QUnit.test('new object', function(assert) {
<add> const foo = {foo: 'yellow'};
<add>
<add> assert.deepEqual(Obj.assign({}, foo, {foo: 'blue'}), {foo: 'blue'}, 'Obj.assign should return result');
<add> assert.deepEqual(foo, {foo: 'yellow'}, 'foo should not be modified');
<add> });
<add>
<add> QUnit.test('empty override', function(assert) {
<add> const foo = {foo: 'yellow'};
<add>
<add> assert.deepEqual(Obj.assign(foo, {}), {foo: 'yellow'}, 'Obj.assign should return result');
<add> assert.deepEqual(foo, {foo: 'yellow'}, 'foo should not be modified');
<add> });
<add>
<add> QUnit.test('multiple override object', function(assert) {
<add> const foo = {foo: 'foo'};
<add> const bar = {foo: 'bar'};
<add> const baz = {foo: 'baz'};
<add>
<add> assert.deepEqual(Obj.assign(foo, bar, baz), baz, 'Obj.assign should return result');
<add> assert.deepEqual(foo, baz, 'foo should be overridden');
<add> });
<add>
<add> QUnit.test('additive properties', function(assert) {
<add> const foo = {};
<add> const expected = {one: 1, two: 2, three: 3};
<add>
<add> assert.deepEqual(Obj.assign(foo, {one: 1}, {two: 2}, {three: 3}), expected, 'Obj.assign should return result');
<add> assert.deepEqual(foo, expected, 'foo should be equal to result');
<add> });
<add>
<add> QUnit.test('deep override', function(assert) {
<add> const foo = {
<add> foo: {
<add> bar: {
<add> baz: 'buzz'
<add> }
<add> },
<add> blue: [55, 56],
<add> red: 'nope'
<add> };
<add>
<add> const baz = {
<add> foo: {
<add> bar: {
<add> baz: 'red'
<add> }
<add> },
<add> blue: [57]
<add> };
<add>
<add> const expected = {
<add> foo: {
<add> bar: {
<add> baz: 'red'
<add> }
<add> },
<add> blue: [57],
<add> red: 'nope'
<add> };
<add>
<add> assert.deepEqual(Obj.assign(foo, baz), expected, 'Obj.assign should return result');
<add> assert.deepEqual(foo, expected, 'foo is overridden');
<add> });
<add>
<add> QUnit.test('negative tests', function(assert) {
<add> const expected = {foo: 11};
<add>
<add> assert.deepEqual(Obj.assign({}, expected, undefined), expected, 'assign should undefined');
<add> assert.deepEqual(Obj.assign({}, expected, null), expected, 'assign should ignore null');
<add> assert.deepEqual(Obj.assign({}, expected, []), expected, 'assign should ignore Array');
<add> assert.deepEqual(Obj.assign({}, expected, ''), expected, 'assign should ignore string');
<add> assert.deepEqual(Obj.assign({}, expected, 11), expected, 'assign should ignore number');
<add> assert.deepEqual(Obj.assign({}, expected, new RegExp()), expected, 'assign should ignore RegExp');
<add> assert.deepEqual(Obj.assign({}, expected, new Date()), expected, 'assign should ignore Date');
<add> assert.deepEqual(Obj.assign({}, expected, true), expected, 'assign should ignore boolean');
<add> assert.deepEqual(Obj.assign({}, expected, () => {}), expected, 'assign should ignore function');
<add> });
<add> });
<add>});
<add> | 1 |
Text | Text | add workspace to exported class list | 8b093122accc2689c6e39d55cf41dde1ce0be227 | <ide><path>docs/README.md
<ide> The classes available from `require 'atom'` are:
<ide> * [SelectListView][SelectListView]
<ide> * [View][View]
<ide> * [WorkspaceView][WorkspaceView]
<add> * [Workspace][Workspace]
<ide>
<ide> ### How do I create a package?
<ide>
<ide> Atom ships with node 0.11.10 and the comprehensive node API docs are available
<ide> [SelectListView]: ../classes/SelectListView.html
<ide> [View]: ../classes/View.html
<ide> [WorkspaceView]: ../classes/WorkspaceView.html
<add>[Workspace]: ../classes/Workspace.html
<ide> [creating-a-package]: https://atom.io/docs/latest/creating-a-package
<ide> [node-docs]: http://nodejs.org/docs/v0.11.10/api | 1 |
Text | Text | add @meixg to collaborators | 53da438ab8b5595999546b482bd3cd7be15281a9 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Akhil Marsonya** <<akhil.marsonya27@gmail.com>> (he/him)
<ide> * [mcollina](https://github.com/mcollina) -
<ide> **Matteo Collina** <<matteo.collina@gmail.com>> (he/him)
<add>* [meixg](https://github.com/meixg) -
<add> **Xuguang Mei** <<meixuguang@gmail.com>> (he/him)
<ide> * [Mesteery](https://github.com/Mesteery) -
<ide> **Mestery** <<mestery@protonmail.com>> (he/him)
<ide> * [mhdawson](https://github.com/mhdawson) -
<ide> maintaining the Node.js project.
<ide> * [marsonya](https://github.com/marsonya) -
<ide> **Akhil Marsonya** <<akhil.marsonya27@gmail.com>> (he/him)
<ide> * [meixg](https://github.com/meixg) -
<del> **Xuguang Mei** <<meixg@foxmail.com>> (he/him)
<add> **Xuguang Mei** <<meixuguang@gmail.com>> (he/him)
<ide> * [Mesteery](https://github.com/Mesteery) -
<ide> **Mestery** <<mestery@protonmail.com>> (he/him)
<ide> * [PoojaDurgad](https://github.com/PoojaDurgad) - | 1 |
Go | Go | fix job and add tests | 8344b6d7368b90c567f43e0c17d4495e2e7b12f5 | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestUnPrivilegedCanMknod(t *testing.T) {
<ide> logDone("run - test un-privileged can mknod")
<ide> }
<ide>
<add>func TestCapDropCannotMknod(t *testing.T) {
<add> cmd := exec.Command(dockerBinary, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<add> out, _, err := runCommandWithOutput(cmd)
<add> if err == nil {
<add> t.Fatal(err, out)
<add> }
<add>
<add> if actual := strings.Trim(out, "\r\n"); actual == "ok" {
<add> t.Fatalf("expected output not ok received %s", actual)
<add> }
<add> deleteAllContainers()
<add>
<add> logDone("run - test --cap-drop=MKNOD cannot mknod")
<add>}
<add>
<add>func TestCapAddCanDownInterface(t *testing.T) {
<add> cmd := exec.Command(dockerBinary, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
<add> out, _, err := runCommandWithOutput(cmd)
<add> if err != nil {
<add> t.Fatal(err, out)
<add> }
<add>
<add> if actual := strings.Trim(out, "\r\n"); actual != "ok" {
<add> t.Fatalf("expected output ok received %s", actual)
<add> }
<add> deleteAllContainers()
<add>
<add> logDone("run - test --cap-add=NET_ADMIN can set eth0 down")
<add>}
<add>
<ide> func TestPrivilegedCanMount(t *testing.T) {
<ide> cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
<ide>
<ide><path>runconfig/hostconfig.go
<ide> func ContainerHostConfigFromJob(job *engine.Job) *HostConfig {
<ide> if VolumesFrom := job.GetenvList("VolumesFrom"); VolumesFrom != nil {
<ide> hostConfig.VolumesFrom = VolumesFrom
<ide> }
<add> if CapAdd := job.GetenvList("CapAdd"); CapAdd != nil {
<add> hostConfig.CapAdd = CapAdd
<add> }
<add> if CapDrop := job.GetenvList("CapDrop"); CapDrop != nil {
<add> hostConfig.CapDrop = CapDrop
<add> }
<ide> return hostConfig
<ide> } | 2 |
PHP | PHP | add brackets again, no passing tests without it | f09fa862dc5b1ff37fc856782141e543962ebf8e | <ide><path>src/Illuminate/Http/Request.php
<ide> public function is()
<ide> */
<ide> public function routeIs()
<ide> {
<del> if (! $route = $this->route() || ! $routeName = $route->getName()) {
<add> if (! ($route = $this->route()) || ! $routeName = $route->getName()) {
<ide> return false;
<ide> }
<ide> | 1 |
Java | Java | introduce routerfunction builder | 8202052b389b47dbf3be1678f3e22291b99b8334 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctionBuilder.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.reactive.function.server;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.function.BiFunction;
<add>import java.util.function.Consumer;
<add>import java.util.function.Function;
<add>import java.util.function.Supplier;
<add>
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.http.HttpMethod;
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * Default implementation of {@link RouterFunctions.Builder}.
<add> * @author Arjen Poutsma
<add> * @since 5.1
<add> */
<add>class RouterFunctionBuilder implements RouterFunctions.Builder {
<add>
<add> private List<RouterFunction<ServerResponse>> routerFunctions = new ArrayList<>();
<add>
<add> private List<HandlerFilterFunction<ServerResponse, ServerResponse>> filterFunctions = new ArrayList<>();
<add>
<add>
<add> @Override
<add> public RouterFunctions.Builder route(RequestPredicate predicate,
<add> HandlerFunction<ServerResponse> handlerFunction) {
<add> this.routerFunctions.add(RouterFunctions.route(predicate, handlerFunction));
<add> return this;
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routeGet(HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.method(HttpMethod.GET), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routeGet(String pattern, HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.GET(pattern), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routeHead(HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.method(HttpMethod.HEAD), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routeHead(String pattern, HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.HEAD(pattern), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routePost(HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.method(HttpMethod.POST), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routePost(String pattern, HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.POST(pattern), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routePut(HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.method(HttpMethod.PUT), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routePut(String pattern, HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.PUT(pattern), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routePatch(HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.method(HttpMethod.PATCH), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routePatch(String pattern, HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.PATCH(pattern), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routeDelete(HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.method(HttpMethod.DELETE), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routeDelete(String pattern, HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.DELETE(pattern), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routeOptions(HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.method(HttpMethod.OPTIONS), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder routeOptions(String pattern, HandlerFunction<ServerResponse> handlerFunction) {
<add> return route(RequestPredicates.OPTIONS(pattern), handlerFunction);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder nest(RequestPredicate predicate,
<add> Consumer<RouterFunctions.Builder> builderConsumer) {
<add>
<add> Assert.notNull(builderConsumer, "'builderConsumer' must not be null");
<add>
<add> RouterFunctionBuilder nestedBuilder = new RouterFunctionBuilder();
<add> builderConsumer.accept(nestedBuilder);
<add> RouterFunction<ServerResponse> nestedRoute = nestedBuilder.build();
<add>
<add> this.routerFunctions.add(RouterFunctions.nest(predicate, nestedRoute));
<add> return this;
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder nest(RequestPredicate predicate,
<add> Supplier<RouterFunction<ServerResponse>> routerFunctionSupplier) {
<add>
<add> Assert.notNull(routerFunctionSupplier, "'routerFunctionSupplier' must not be null");
<add>
<add> RouterFunction<ServerResponse> nestedRoute = routerFunctionSupplier.get();
<add>
<add> this.routerFunctions.add(RouterFunctions.nest(predicate, nestedRoute));
<add> return this;
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder nestPath(String pattern,
<add> Consumer<RouterFunctions.Builder> builderConsumer) {
<add> return nest(RequestPredicates.path(pattern), builderConsumer);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder nestPath(String pattern,
<add> Supplier<RouterFunction<ServerResponse>> routerFunctionSupplier) {
<add> return nest(RequestPredicates.path(pattern), routerFunctionSupplier);
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder filter(HandlerFilterFunction<ServerResponse, ServerResponse> filterFunction) {
<add> Assert.notNull(filterFunction, "'filterFunction' must not be null");
<add>
<add> this.filterFunctions.add(filterFunction);
<add> return this;
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder before(
<add> Function<ServerRequest, Mono<ServerRequest>> requestProcessor) {
<add>
<add> Assert.notNull(requestProcessor, "Function must not be null");
<add> return filter((request, next) -> requestProcessor.apply(request).flatMap(next::handle));
<add> }
<add>
<add> @Override
<add> public RouterFunctions.Builder after(
<add> BiFunction<ServerRequest, ServerResponse, Mono<ServerResponse>> responseProcessor) {
<add> return filter((request, next) -> next.handle(request)
<add> .flatMap(serverResponse -> responseProcessor.apply(request, serverResponse)));
<add> }
<add>
<add> @Override
<add> public <T extends Throwable> RouterFunctions.Builder exception(
<add> Class<T> exceptionType,
<add> BiFunction<T, ServerRequest, Mono<ServerResponse>> fallback) {
<add> Assert.notNull(exceptionType, "'exceptionType' must not be null");
<add> Assert.notNull(fallback, "'fallback' must not be null");
<add>
<add> return filter((request, next) -> next.handle(request)
<add> .onErrorResume(exceptionType, t -> fallback.apply(t, request)));
<add> }
<add>
<add> @Override
<add> public RouterFunction<ServerResponse> build() {
<add>
<add> RouterFunction<ServerResponse> result = this.routerFunctions.stream()
<add> .reduce(RouterFunction::and)
<add> .orElseThrow(IllegalStateException::new);
<add>
<add> if (this.filterFunctions.isEmpty()) {
<add> return result;
<add> }
<add> else {
<add> HandlerFilterFunction<ServerResponse, ServerResponse> filter =
<add> this.filterFunctions.stream()
<add> .reduce(HandlerFilterFunction::andThen)
<add> .orElseThrow(IllegalStateException::new);
<add>
<add> return result.filter(filter);
<add> }
<add> }
<add>
<add>}
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.function.BiFunction;
<add>import java.util.function.Consumer;
<ide> import java.util.function.Function;
<ide> import java.util.function.Supplier;
<ide>
<ide> public abstract class RouterFunctions {
<ide>
<ide> private static final HandlerFunction<ServerResponse> NOT_FOUND_HANDLER = request -> ServerResponse.notFound().build();
<ide>
<add> /**
<add> * Return a {@linkplain Builder builder} that offers a discoverable way to create router
<add> * functions.
<add> * @return a router function builder
<add> */
<add> public static Builder builder() {
<add> return new RouterFunctionBuilder();
<add> }
<ide>
<ide> /**
<ide> * Route to the given handler function if the given request predicate applies.
<ide> static <T extends ServerResponse> HandlerFunction<T> cast(HandlerFunction<?> han
<ide> return (HandlerFunction<T>) handlerFunction;
<ide> }
<ide>
<add> /**
<add> * Represents a builder for router functions.
<add> * <p>Each invocation of {@code route} creates a new {@link RouterFunction} that is
<add> * {@linkplain RouterFunction#and(RouterFunction) composed} with any previously built functions.
<add> * @since 5.1
<add> */
<add> public interface Builder {
<add>
<add> /**
<add> * Adds a route to the given handler function that matches if the given request predicate
<add> * applies.
<add> * <p>For instance, the following example routes GET requests for "/user" to the
<add> * {@code listUsers} method in {@code userController}:
<add> * <pre class="code">
<add> * RouterFunction<ServerResponse> route =
<add> * RouterFunctions.builder()
<add> * .route(RequestPredicates.GET("/user"), userController::listUsers)
<add> * .build();
<add> * </pre>
<add> * @param predicate the predicate to test
<add> * @param handlerFunction the handler function to route to if the predicate applies
<add> * @return this builder
<add> * @see RequestPredicates
<add> */
<add> Builder route(RequestPredicate predicate, HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code GET} requests.
<add> * @param handlerFunction the handler function to handle all {@code GET} requests
<add> * @return this builder
<add> */
<add> Builder routeGet(HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code GET} requests
<add> * that match the given pattern.
<add> * @param pattern the pattern to match to
<add> * @param handlerFunction the handler function to handle all {@code GET} requests that
<add> * match {@code pattern}
<add> * @return this builder
<add> */
<add> Builder routeGet(String pattern, HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code HEAD} requests.
<add> * @param handlerFunction the handler function to handle all {@code HEAD} requests
<add> * @return this builder
<add> */
<add> Builder routeHead(HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code HEAD} requests
<add> * that match the given pattern.
<add> * @param pattern the pattern to match to
<add> * @param handlerFunction the handler function to handle all {@code HEAD} requests that
<add> * match {@code pattern}
<add> * @return this builder
<add> */
<add> Builder routeHead(String pattern, HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code POST} requests.
<add> * @param handlerFunction the handler function to handle all {@code POST} requests
<add> * @return this builder
<add> */
<add> Builder routePost(HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code POST} requests
<add> * that match the given pattern.
<add> * @param pattern the pattern to match to
<add> * @param handlerFunction the handler function to handle all {@code POST} requests that
<add> * match {@code pattern}
<add> * @return this builder
<add> */
<add> Builder routePost(String pattern, HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code PUT} requests.
<add> * @param handlerFunction the handler function to handle all {@code PUT} requests
<add> * @return this builder
<add> */
<add> Builder routePut(HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code PUT} requests
<add> * that match the given pattern.
<add> * @param pattern the pattern to match to
<add> * @param handlerFunction the handler function to handle all {@code PUT} requests that
<add> * match {@code pattern}
<add> * @return this builder
<add> */
<add> Builder routePut(String pattern, HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code PATCH} requests.
<add> * @param handlerFunction the handler function to handle all {@code PATCH} requests
<add> * @return this builder
<add> */
<add> Builder routePatch(HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code PATCH} requests
<add> * that match the given pattern.
<add> * @param pattern the pattern to match to
<add> * @param handlerFunction the handler function to handle all {@code PATCH} requests that
<add> * match {@code pattern}
<add> * @return this builder
<add> */
<add> Builder routePatch(String pattern, HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code DELETE} requests.
<add> * @param handlerFunction the handler function to handle all {@code DELETE} requests
<add> * @return this builder
<add> */
<add> Builder routeDelete(HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code DELETE} requests
<add> * that match the given pattern.
<add> * @param pattern the pattern to match to
<add> * @param handlerFunction the handler function to handle all {@code DELETE} requests that
<add> * match {@code pattern}
<add> * @return this builder
<add> */
<add> Builder routeDelete(String pattern, HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code OPTIONS} requests.
<add> * @param handlerFunction the handler function to handle all {@code OPTIONS} requests
<add> * @return this builder
<add> */
<add> Builder routeOptions(HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Adds a route to the given handler function that handles all HTTP {@code OPTIONS} requests
<add> * that match the given pattern.
<add> * @param pattern the pattern to match to
<add> * @param handlerFunction the handler function to handle all {@code OPTIONS} requests that
<add> * match {@code pattern}
<add> * @return this builder
<add> */
<add> Builder routeOptions(String pattern, HandlerFunction<ServerResponse> handlerFunction);
<add>
<add> /**
<add> * Route to the supplied router function if the given request predicate applies. This method
<add> * can be used to create <strong>nested routes</strong>, where a group of routes share a
<add> * common path (prefix), header, or other request predicate.
<add> * <p>For instance, the following example creates a nested route with a "/user" path
<add> * predicate, so that GET requests for "/user" will list users,
<add> * and POST request for "/user" will create a new user.
<add> * <pre class="code">
<add> * RouterFunction<ServerResponse> nestedRoute =
<add> * RouterFunctions.builder()
<add> * .nest(RequestPredicates.path("/user"), () ->
<add> * RouterFunctions.builder()
<add> * .routeGet(this::listUsers)
<add> * .routePost(this::createUser);
<add> * .build();
<add> * )
<add> * .build();
<add> * </pre>
<add> * @param predicate the predicate to test
<add> * @param routerFunctionSupplier supplier for the nested router function to delegate to if
<add> * the predicate applies
<add> * @return this builder
<add> * @see RequestPredicates
<add> */
<add> Builder nest(RequestPredicate predicate, Supplier<RouterFunction<ServerResponse>> routerFunctionSupplier);
<add>
<add> /**
<add> * Route to a built router function if the given request predicate applies.
<add> * This method can be used to create <strong>nested routes</strong>, where a group of routes
<add> * share a common path (prefix), header, or other request predicate.
<add> * <p>For instance, the following example creates a nested route with a "/user" path
<add> * predicate, so that GET requests for "/user" will list users,
<add> * and POST request for "/user" will create a new user.
<add> * <pre class="code">
<add> * RouterFunction<ServerResponse> nestedRoute =
<add> * RouterFunctions.builder()
<add> * .nest(RequestPredicates.path("/user"), builder ->
<add> * builder.routeGet(this::listUsers)
<add> * .routePost(this::createUser);
<add> * )
<add> * .build();
<add> * </pre>
<add> * @param predicate the predicate to test
<add> * @param builderConsumer consumer for a {@code Builder} that provides the nested router
<add> * function
<add> * @return this builder
<add> * @see RequestPredicates
<add> */
<add> Builder nest(RequestPredicate predicate, Consumer<Builder> builderConsumer);
<add>
<add> /**
<add> * Route to the supplied router function if the given path prefix pattern applies. This method
<add> * can be used to create <strong>nested routes</strong>, where a group of routes share a
<add> * common path (prefix).
<add> * <p>For instance, the following example creates a nested route with a "/user" path
<add> * predicate, so that GET requests for "/user" will list users,
<add> * and POST request for "/user" will create a new user.
<add> * <pre class="code">
<add> * RouterFunction<ServerResponse> nestedRoute =
<add> * RouterFunctions.builder()
<add> * .nestPath("/user", () ->
<add> * RouterFunctions.builder()
<add> * .routeGet(this::listUsers)
<add> * .routePost(this::createUser);
<add> * .build();
<add> * )
<add> * .build();
<add> * </pre>
<add> * @param pattern the pattern to match to
<add> * @param routerFunctionSupplier supplier for the nested router function to delegate to if
<add> * the pattern matches
<add> * @return this builder
<add> */
<add> Builder nestPath(String pattern, Supplier<RouterFunction<ServerResponse>> routerFunctionSupplier);
<add>
<add> /**
<add> * Route to a built router function if the given path prefix pattern applies.
<add> * This method can be used to create <strong>nested routes</strong>, where a group of routes
<add> * share a common path (prefix), header, or other request predicate.
<add> * <p>For instance, the following example creates a nested route with a "/user" path
<add> * predicate, so that GET requests for "/user" will list users,
<add> * and POST request for "/user" will create a new user.
<add> * <pre class="code">
<add> * RouterFunction<ServerResponse> nestedRoute =
<add> * RouterFunctions.builder()
<add> * .nestPath("/user", builder ->
<add> * builder.routeGet(this::listUsers)
<add> * .routePost(this::createUser);
<add> * )
<add> * .build();
<add> * </pre>
<add> * @param pattern the pattern to match to
<add> * @param builderConsumer consumer for a {@code Builder} that provides the nested router
<add> * function
<add> * @return this builder
<add> */
<add> Builder nestPath(String pattern, Consumer<Builder> builderConsumer);
<add>
<add> /**
<add> * Filters all routes created by this builder with the given filter function. Filter
<add> * functions are typically used to address cross-cutting concerns, such as logging,
<add> * security, etc.
<add> * <p>For instance, the following example creates a filter that logs the request before
<add> * the handler function executes, and logs the response after.
<add> * <pre class="code">
<add> * RouterFunction<ServerResponse> filteredRoute =
<add> * RouterFunctions.builder()
<add> * .routeGet("/user", this::listUsers)
<add> * .filter((request, next) -> {
<add> * log(request);
<add> * Mono<ServerResponse> responseMono = next.handle(request);
<add> * return responseMono.doOnNext(response -> log(response);
<add> * })
<add> * .build();
<add> * </pre>
<add> * @param filterFunction the function to filter all routes built by this builder
<add> * @return this builder
<add> */
<add> Builder filter(HandlerFilterFunction<ServerResponse, ServerResponse> filterFunction);
<add>
<add> /**
<add> * Filters the request for all routes created by this builder with the given request
<add> * processing function. Filters are typically used to address cross-cutting concerns, such
<add> * as logging, security, etc.
<add> * <p>For instance, the following example creates a filter that logs the request before
<add> * the handler function executes.
<add> * <pre class="code">
<add> * RouterFunction<ServerResponse> filteredRoute =
<add> * RouterFunctions.builder()
<add> * .routeGet("/user", this::listUsers)
<add> * .before(request -> {
<add> * log(request);
<add> * return Mono.just(request);
<add> * })
<add> * .build();
<add> * </pre>
<add> * @param requestProcessor a function that transforms the request
<add> * @return this builder
<add> */
<add> Builder before(Function<ServerRequest, Mono<ServerRequest>> requestProcessor);
<add>
<add> /**
<add> * Filters the response for all routes created by this builder with the given response
<add> * processing function. Filters are typically used to address cross-cutting concerns, such
<add> * as logging, security, etc.
<add> * <p>For instance, the following example creates a filter that logs the response after
<add> * the handler function executes.
<add> * <pre class="code">
<add> * RouterFunction<ServerResponse> filteredRoute =
<add> * RouterFunctions.builder()
<add> * .routeGet("/user", this::listUsers)
<add> * .after((request, response) -> {
<add> * log(response);
<add> * return Mono.just(response);
<add> * })
<add> * .build();
<add> * </pre>
<add> * @param responseProcessor a function that transforms the response
<add> * @return this builder
<add> */
<add> Builder after(BiFunction<ServerRequest, ServerResponse, Mono<ServerResponse>> responseProcessor);
<add>
<add> <T extends Throwable> Builder exception(Class<T> exceptionType,
<add> BiFunction<T, ServerRequest, Mono<ServerResponse>> fallback);
<add>
<add> /**
<add> * Builds the {@code RouterFunction}. All created routes are
<add> * {@linkplain RouterFunction#and(RouterFunction) composed} with one another, and filters
<add> * (f any) are applied to the result.
<add> * @return the built router function
<add> */
<add> RouterFunction<ServerResponse> build();
<add>
<add> }
<add>
<ide>
<ide> /**
<ide> * Receives notifications from the logical structure of router functions.
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionBuilderTests.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.reactive.function.server;
<add>
<add>import java.net.URI;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import org.junit.Test;
<add>import reactor.core.publisher.Mono;
<add>import reactor.test.StepVerifier;
<add>
<add>import org.springframework.http.HttpMethod;
<add>import org.springframework.http.HttpStatus;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * @author Arjen Poutsma
<add> */
<add>public class RouterFunctionBuilderTests {
<add>
<add> private RouterFunctionBuilder builder = new RouterFunctionBuilder();
<add>
<add> @Test
<add> public void route() {
<add> RouterFunction<ServerResponse> route = this.builder
<add> .routeGet("/foo", request -> ServerResponse.ok().build())
<add> .routePost(request -> ServerResponse.noContent().build())
<add> .build();
<add>
<add> MockServerRequest fooRequest = MockServerRequest.builder().
<add> method(HttpMethod.GET).
<add> uri(URI.create("http://localhost/foo"))
<add> .build();
<add>
<add> Mono<Integer> responseMono = route.route(fooRequest)
<add> .flatMap(handlerFunction -> handlerFunction.handle(fooRequest))
<add> .map(ServerResponse::statusCode)
<add> .map(HttpStatus::value);
<add>
<add> StepVerifier.create(responseMono)
<add> .expectNext(200)
<add> .verifyComplete();
<add>
<add> MockServerRequest barRequest = MockServerRequest.builder().
<add> method(HttpMethod.POST).
<add> uri(URI.create("http://localhost"))
<add> .build();
<add>
<add> responseMono = route.route(barRequest)
<add> .flatMap(handlerFunction -> handlerFunction.handle(barRequest))
<add> .map(ServerResponse::statusCode)
<add> .map(HttpStatus::value);
<add>
<add> StepVerifier.create(responseMono)
<add> .expectNext(204)
<add> .verifyComplete();
<add>
<add> }
<add>
<add> @Test
<add> public void nest() {
<add> RouterFunction<?> route = this.builder
<add> .nestPath("/foo", builder -> {
<add> builder.nestPath("/bar",
<add> () -> RouterFunctions.builder()
<add> .routeGet("/baz", request -> ServerResponse.ok().build())
<add> .build());
<add> })
<add> .build();
<add>
<add> MockServerRequest fooRequest = MockServerRequest.builder().
<add> method(HttpMethod.GET).
<add> uri(URI.create("http://localhost/foo/bar/baz"))
<add> .build();
<add>
<add> Mono<Integer> responseMono = route.route(fooRequest)
<add> .flatMap(handlerFunction -> handlerFunction.handle(fooRequest))
<add> .map(ServerResponse::statusCode)
<add> .map(HttpStatus::value);
<add>
<add> StepVerifier.create(responseMono)
<add> .expectNext(200)
<add> .verifyComplete();
<add> }
<add>
<add> @Test
<add> public void filters() {
<add> AtomicInteger filterCount = new AtomicInteger();
<add>
<add> RouterFunction<?> route = this.builder
<add> .routeGet("/foo", request -> ServerResponse.ok().build())
<add> .routeGet("/bar", request -> Mono.error(new IllegalStateException()))
<add> .before(request -> {
<add> int count = filterCount.getAndIncrement();
<add> assertEquals(0, count);
<add> return Mono.just(request);
<add> })
<add> .after((request, response) -> {
<add> int count = filterCount.getAndIncrement();
<add> assertEquals(3, count);
<add> return Mono.just(response);
<add> })
<add> .filter((request, next) -> {
<add> int count = filterCount.getAndIncrement();
<add> assertEquals(1, count);
<add> Mono<ServerResponse> responseMono = next.handle(request);
<add> count = filterCount.getAndIncrement();
<add> assertEquals(2, count);
<add> return responseMono;
<add> })
<add> .exception(IllegalStateException.class, (e, request) -> ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build())
<add> .build();
<add>
<add> MockServerRequest fooRequest = MockServerRequest.builder().
<add> method(HttpMethod.GET).
<add> uri(URI.create("http://localhost/foo"))
<add> .build();
<add>
<add> Mono<ServerResponse> fooResponseMono = route.route(fooRequest)
<add> .flatMap(handlerFunction -> handlerFunction.handle(fooRequest));
<add>
<add>
<add> StepVerifier.create(fooResponseMono)
<add> .consumeNextWith(serverResponse -> {
<add> assertEquals(4, filterCount.get());
<add> })
<add> .verifyComplete();
<add>
<add> filterCount.set(0);
<add>
<add> MockServerRequest barRequest = MockServerRequest.builder().
<add> method(HttpMethod.GET).
<add> uri(URI.create("http://localhost/bar"))
<add> .build();
<add>
<add>
<add> Mono<Integer> barResponseMono = route.route(barRequest)
<add> .flatMap(handlerFunction -> handlerFunction.handle(barRequest))
<add> .map(ServerResponse::statusCode)
<add> .map(HttpStatus::value);
<add>
<add> StepVerifier.create(barResponseMono)
<add> .expectNext(500)
<add> .verifyComplete();
<add>
<add> }
<add>
<add>}
<ide>\ No newline at end of file | 3 |
Go | Go | fix usage for plugin commands | 65ed9daf70ccf0027f4eac8049667130deb249ed | <ide><path>api/client/plugin/disable.go
<ide> import (
<ide>
<ide> func newDisableCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> cmd := &cobra.Command{
<del> Use: "disable",
<add> Use: "disable PLUGIN",
<ide> Short: "Disable a plugin",
<ide> Args: cli.ExactArgs(1),
<ide> RunE: func(cmd *cobra.Command, args []string) error {
<ide><path>api/client/plugin/enable.go
<ide> import (
<ide>
<ide> func newEnableCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> cmd := &cobra.Command{
<del> Use: "enable",
<add> Use: "enable PLUGIN",
<ide> Short: "Enable a plugin",
<ide> Args: cli.ExactArgs(1),
<ide> RunE: func(cmd *cobra.Command, args []string) error {
<ide><path>api/client/plugin/inspect.go
<ide> import (
<ide>
<ide> func newInspectCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> cmd := &cobra.Command{
<del> Use: "inspect",
<add> Use: "inspect PLUGIN",
<ide> Short: "Inspect a plugin",
<ide> Args: cli.ExactArgs(1),
<ide> RunE: func(cmd *cobra.Command, args []string) error {
<ide><path>api/client/plugin/push.go
<ide> import (
<ide>
<ide> func newPushCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> cmd := &cobra.Command{
<del> Use: "push",
<add> Use: "push PLUGIN",
<ide> Short: "Push a plugin",
<ide> Args: cli.ExactArgs(1),
<ide> RunE: func(cmd *cobra.Command, args []string) error {
<ide><path>api/client/plugin/remove.go
<ide> import (
<ide>
<ide> func newRemoveCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> cmd := &cobra.Command{
<del> Use: "rm",
<add> Use: "rm PLUGIN",
<ide> Short: "Remove a plugin",
<ide> Aliases: []string{"remove"},
<ide> Args: cli.RequiresMinArgs(1),
<ide><path>api/client/plugin/set.go
<ide> import (
<ide>
<ide> func newSetCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> cmd := &cobra.Command{
<del> Use: "set",
<add> Use: "set PLUGIN key1=value1 [key2=value2...]",
<ide> Short: "Change settings for a plugin",
<ide> Args: cli.RequiresMinArgs(2),
<ide> RunE: func(cmd *cobra.Command, args []string) error { | 6 |
Python | Python | set --cover3-package to celery | 0a7f92b4b6ff5f103b1b84b1844bc79792871e9f | <ide><path>testproj/settings.py
<ide> )
<ide>
<ide> NOSE_ARGS = [os.path.join(here, os.pardir, "celery", "tests"),
<add> "--cover3-package=celery",
<ide> "--cover3-branch",
<ide> "--cover3-exclude=%s" % ",".join(COVERAGE_EXCLUDE_MODULES)]
<ide> TEST_DATABASE_NAME=":memory" | 1 |
Javascript | Javascript | isolate donation views | 26bb9a4e218de89325f62a1c9865c12b359f0e9f | <ide><path>client/src/client-only-routes/ShowCertification.js
<ide> const ShowCertification = props => {
<ide> executeGA({
<ide> type: 'event',
<ide> data: {
<del> category: 'Donation',
<add> category: 'Donation View',
<ide> action: 'Displayed Certificate Donation',
<ide> nonInteraction: true
<ide> }
<ide> const ShowCertification = props => {
<ide> props.executeGA({
<ide> type: 'event',
<ide> data: {
<del> category: 'donation',
<add> category: 'Donation',
<ide> action: `certificate ${action}`,
<ide> label: duration,
<ide> value: amount
<ide><path>client/src/components/Donation/DonationModal.js
<ide> function DonateModal({
<ide> executeGA({
<ide> type: 'event',
<ide> data: {
<del> category: 'donation',
<add> category: 'Donation',
<ide> action: `Modal ${action}`,
<ide> label: duration,
<ide> value: amount
<ide> function DonateModal({
<ide> executeGA({
<ide> type: 'event',
<ide> data: {
<del> category: 'Donation',
<add> category: 'Donation View',
<ide> action: `Displayed ${
<ide> isBlockDonation ? 'block' : 'progress'
<ide> } donation modal`,
<ide><path>client/src/pages/donate.js
<ide> export class DonatePage extends Component {
<ide> this.props.executeGA({
<ide> type: 'event',
<ide> data: {
<del> category: 'Donation',
<add> category: 'Donation View',
<ide> action: `Displayed donate page`,
<ide> nonInteraction: true
<ide> }
<ide> export class DonatePage extends Component {
<ide> this.props.executeGA({
<ide> type: 'event',
<ide> data: {
<del> category: 'donation',
<add> category: 'Donation',
<ide> action: `donate page ${action}`,
<ide> label: duration,
<ide> value: amount
<ide><path>client/src/redux/ga-saga.test.js
<ide> describe('ga-saga', () => {
<ide> const mockEventPayload = {
<ide> type: 'event',
<ide> data: {
<del> category: 'donation',
<add> category: 'Donation',
<ide> action: 'year end gift paypal button click'
<ide> }
<ide> }; | 4 |
Python | Python | make __array_priority__ = 1000 | 3c2603f1fe11ef6bc44de1160a7ab43325a35883 | <ide><path>numpy/polynomial/polytemplate.py
<ide> class $name(pu.PolyBase) :
<ide> # Default window
<ide> window = np.array($domain)
<ide> # Don't let participate in array operations. Value doesn't matter.
<del> __array_priority__ = 0
<add> __array_priority__ = 1000
<ide>
<ide> def has_samecoef(self, other):
<ide> """Check if coefficients match.
<ide> def __divmod__(self, other) :
<ide> try :
<ide> quo, rem = ${nick}div(self.coef, other)
<ide> except :
<add> print 'hi'
<ide> return NotImplemented
<ide> quo = self.__class__(quo, self.domain, self.window)
<ide> rem = self.__class__(rem, self.domain, self.window)
<ide> def mapparms(self) :
<ide> applied to the input arguments before the series is evaluated. The
<ide> map depends on the ``domain`` and ``window``; if the current
<ide> ``domain`` is equal to the ``window`` the resulting map is the
<del> identity. If the coeffients of the ``$name`` instance are to be
<add> identity. If the coefficients of the ``$name`` instance are to be
<ide> used by themselves outside this class, then the linear function
<ide> must be substituted for the ``x`` in the standard representation of
<ide> the base polynomials. | 1 |
PHP | PHP | use simple strings where applicable | 228e9ca1cfcfbe28f1965b8bebc66d52b1d3aeca | <ide><path>src/Console/ConsoleErrorHandler.php
<ide> protected function _displayException($exception)
<ide> }
<ide>
<ide> $message = sprintf(
<del> "<error>%s</error> %s in [%s, line %s]",
<add> '<error>%s</error> %s in [%s, line %s]',
<ide> $errorName,
<ide> $exception->getMessage(),
<ide> $exception->getFile(),
<ide><path>src/Shell/CommandListShell.php
<ide> public function startup()
<ide> public function main()
<ide> {
<ide> if (!$this->param('xml') && !$this->param('version')) {
<del> $this->out("<info>Current Paths:</info>", 2);
<del> $this->out("* app: " . APP_DIR);
<del> $this->out("* root: " . rtrim(ROOT, DIRECTORY_SEPARATOR));
<del> $this->out("* core: " . rtrim(CORE_PATH, DIRECTORY_SEPARATOR));
<del> $this->out("");
<add> $this->out('<info>Current Paths:</info>', 2);
<add> $this->out('* app: ' . APP_DIR);
<add> $this->out('* root: ' . rtrim(ROOT, DIRECTORY_SEPARATOR));
<add> $this->out('* core: ' . rtrim(CORE_PATH, DIRECTORY_SEPARATOR));
<add> $this->out('');
<ide>
<del> $this->out("<info>Available Shells:</info>", 2);
<add> $this->out('<info>Available Shells:</info>', 2);
<ide> }
<ide>
<ide> if ($this->param('version')) {
<ide> protected function _asText($shellList)
<ide> $this->out();
<ide> }
<ide>
<del> $this->out("To run an app or core command, type <info>`cake shell_name [args]`</info>");
<del> $this->out("To run a plugin command, type <info>`cake Plugin.shell_name [args]`</info>");
<del> $this->out("To get help on a specific command, type <info>`cake shell_name --help`</info>", 2);
<add> $this->out('To run an app or core command, type <info>`cake shell_name [args]`</info>');
<add> $this->out('To run a plugin command, type <info>`cake Plugin.shell_name [args]`</info>');
<add> $this->out('To get help on a specific command, type <info>`cake shell_name --help`</info>', 2);
<ide> }
<ide>
<ide> /**
<ide><path>src/Shell/RoutesShell.php
<ide> public function generate()
<ide> $this->out("> $url");
<ide> $this->out();
<ide> } catch (MissingRouteException $e) {
<del> $this->err("<warning>The provided parameters do not match any routes.</warning>");
<add> $this->err('<warning>The provided parameters do not match any routes.</warning>');
<ide> $this->out();
<ide>
<ide> return false;
<ide> public function getOptionParser()
<ide> ])->addSubcommand('generate', [
<ide> 'help' => 'Check a routing array against the routes. ' .
<ide> "Will output the URL if there is a match.\n\n" .
<del> "Routing parameters should be supplied in a key:value format. " .
<del> "For example `controller:Articles action:view 2`"
<add> 'Routing parameters should be supplied in a key:value format. ' .
<add> 'For example `controller:Articles action:view 2`'
<ide> ]);
<ide>
<ide> return $parser;
<ide><path>src/Shell/ServerShell.php
<ide> protected function _welcome()
<ide> public function main()
<ide> {
<ide> $command = sprintf(
<del> "php -S %s:%d -t %s %s",
<add> 'php -S %s:%d -t %s %s',
<ide> $this->_host,
<ide> $this->_port,
<ide> escapeshellarg($this->_documentRoot),
<ide><path>src/Shell/Task/ExtractTask.php
<ide> protected function _formatString($string)
<ide> if ($quote === '"') {
<ide> $string = stripcslashes($string);
<ide> } else {
<del> $string = strtr($string, ["\\'" => "'", "\\\\" => "\\"]);
<add> $string = strtr($string, ["\\'" => "'", '\\\\' => '\\']);
<ide> }
<ide> $string = str_replace("\r\n", "\n", $string);
<ide>
<ide><path>tests/TestCase/Console/ConsoleErrorHandlerTest.php
<ide> public function testHandleError()
<ide> public function testHandleFatalError()
<ide> {
<ide> ob_start();
<del> $content = "<error>Fatal Error:</error> This is a fatal error in [/some/file, line 275]";
<add> $content = '<error>Fatal Error:</error> This is a fatal error in [/some/file, line 275]';
<ide> $this->stderr->expects($this->once())->method('write')
<ide> ->with($this->stringContains($content));
<ide>
<ide><path>tests/TestCase/Console/ConsoleIoTest.php
<ide> public function testOut()
<ide> {
<ide> $this->out->expects($this->at(0))
<ide> ->method('write')
<del> ->with("Just a test", 1);
<add> ->with('Just a test', 1);
<ide>
<ide> $this->out->expects($this->at(1))
<ide> ->method('write')
<ide> public function testErr()
<ide> {
<ide> $this->err->expects($this->at(0))
<ide> ->method('write')
<del> ->with("Just a test", 1);
<add> ->with('Just a test', 1);
<ide>
<ide> $this->err->expects($this->at(1))
<ide> ->method('write')
<ide> public function testNl()
<ide> }
<ide> $this->assertEquals($this->io->nl(), $newLine);
<ide> $this->assertEquals($this->io->nl(true), $newLine);
<del> $this->assertEquals("", $this->io->nl(false));
<add> $this->assertEquals('', $this->io->nl(false));
<ide> $this->assertEquals($this->io->nl(2), $newLine . $newLine);
<ide> $this->assertEquals($this->io->nl(1), $newLine);
<ide> }
<ide> public function testHr()
<ide> $this->out->expects($this->at(1))->method('write')->with($bar, 1);
<ide> $this->out->expects($this->at(2))->method('write')->with('', 0);
<ide>
<del> $this->out->expects($this->at(3))->method('write')->with("", true);
<add> $this->out->expects($this->at(3))->method('write')->with('', true);
<ide> $this->out->expects($this->at(4))->method('write')->with($bar, 1);
<del> $this->out->expects($this->at(5))->method('write')->with("", true);
<add> $this->out->expects($this->at(5))->method('write')->with('', true);
<ide>
<del> $this->out->expects($this->at(6))->method('write')->with("", 2);
<add> $this->out->expects($this->at(6))->method('write')->with('', 2);
<ide> $this->out->expects($this->at(7))->method('write')->with($bar, 1);
<del> $this->out->expects($this->at(8))->method('write')->with("", 2);
<add> $this->out->expects($this->at(8))->method('write')->with('', 2);
<ide>
<ide> $this->io->hr();
<ide> $this->io->hr(true);
<ide><path>tests/TestCase/Console/ConsoleOutputTest.php
<ide> public function testFormattingSimple()
<ide> public function testFormattingNotEatingTags()
<ide> {
<ide> $this->output->expects($this->once())->method('_write')
<del> ->with("<red> Something bad");
<add> ->with('<red> Something bad');
<ide>
<ide> $this->output->write('<red> Something bad', false);
<ide> }
<ide> public function testFormattingCustom()
<ide> public function testFormattingMissingStyleName()
<ide> {
<ide> $this->output->expects($this->once())->method('_write')
<del> ->with("<not_there>Error:</not_there> Something bad");
<add> ->with('<not_there>Error:</not_there> Something bad');
<ide>
<ide> $this->output->write('<not_there>Error:</not_there> Something bad', false);
<ide> }
<ide><path>tests/TestCase/Console/ShellTest.php
<ide> public function testError()
<ide>
<ide> $this->io->expects($this->at(1))
<ide> ->method('err')
<del> ->with("Searched all...");
<add> ->with('Searched all...');
<ide>
<ide> $this->Shell->error('Foo Not Found', 'Searched all...');
<ide> $this->assertSame($this->Shell->stopped, 1);
<ide> public function testCreateFileNoReply()
<ide> touch($file);
<ide> $this->assertFileExists($file);
<ide>
<del> $contents = "My content";
<add> $contents = 'My content';
<ide> $result = $this->Shell->createFile($file, $contents);
<ide> $this->assertFileExists($file);
<ide> $this->assertTextEquals('', file_get_contents($file));
<ide> public function testCreateFileOverwrite()
<ide> touch($file);
<ide> $this->assertFileExists($file);
<ide>
<del> $contents = "My content";
<add> $contents = 'My content';
<ide> $result = $this->Shell->createFile($file, $contents);
<ide> $this->assertFileExists($file);
<ide> $this->assertTextEquals($contents, file_get_contents($file));
<ide><path>tests/TestCase/Controller/Component/CookieComponentTest.php
<ide> public function testWriteConfigKeyWithCustomEncryptionKey()
<ide> $name = 'sampleCookieTest';
<ide> $value = 'some data';
<ide> $encryption = 'aes';
<del> $prefix = "Q2FrZQ==.";
<add> $prefix = 'Q2FrZQ==.';
<ide> $key = 'justanotherencryptionkeyjustanotherencryptionkey';
<ide>
<ide> $this->Cookie->configKey($name, compact('key', 'encryption'));
<ide> public function testCheckingSavedEmpty()
<ide> */
<ide> public function testCheckKeyWithSpaces()
<ide> {
<del> $this->Cookie->write('CookieComponent Test', "test");
<add> $this->Cookie->write('CookieComponent Test', 'test');
<ide> $this->assertTrue($this->Cookie->check('CookieComponent Test'));
<ide> $this->Cookie->delete('CookieComponent Test');
<ide>
<del> $this->Cookie->write('CookieComponent Test.Test Case', "test");
<add> $this->Cookie->write('CookieComponent Test.Test Case', 'test');
<ide> $this->assertTrue($this->Cookie->check('CookieComponent Test.Test Case'));
<ide> }
<ide>
<ide> protected function _encrypt($value)
<ide> $value = $this->_implode($value);
<ide> }
<ide>
<del> return "Q2FrZQ==." . base64_encode(Security::encrypt($value, $this->Cookie->config('key')));
<add> return 'Q2FrZQ==.' . base64_encode(Security::encrypt($value, $this->Cookie->config('key')));
<ide> }
<ide> }
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testBeforeRenderEventCancelsRender()
<ide> public static function statusCodeProvider()
<ide> {
<ide> return [
<del> [300, "Multiple Choices"],
<del> [301, "Moved Permanently"],
<del> [302, "Found"],
<del> [303, "See Other"],
<del> [304, "Not Modified"],
<del> [305, "Use Proxy"],
<del> [307, "Temporary Redirect"],
<del> [403, "Forbidden"],
<add> [300, 'Multiple Choices'],
<add> [301, 'Moved Permanently'],
<add> [302, 'Found'],
<add> [303, 'See Other'],
<add> [304, 'Not Modified'],
<add> [305, 'Use Proxy'],
<add> [307, 'Temporary Redirect'],
<add> [403, 'Forbidden'],
<ide> ];
<ide> }
<ide>
<ide><path>tests/TestCase/Core/ConfigureTest.php
<ide> public function testCheckingSavedEmpty()
<ide> */
<ide> public function testCheckKeyWithSpaces()
<ide> {
<del> $this->assertTrue(Configure::write('Configure Test', "test"));
<add> $this->assertTrue(Configure::write('Configure Test', 'test'));
<ide> $this->assertTrue(Configure::check('Configure Test'));
<ide> Configure::delete('Configure Test');
<ide>
<del> $this->assertTrue(Configure::write('Configure Test.Test Case', "test"));
<add> $this->assertTrue(Configure::write('Configure Test.Test Case', 'test'));
<ide> $this->assertTrue(Configure::check('Configure Test.Test Case'));
<ide> }
<ide>
<ide><path>tests/TestCase/Core/StaticConfigTraitTest.php
<ide> public function testCanUpdateClassMap()
<ide> 'syslog' => 'Cake\Log\Engine\SyslogLog',
<ide> ];
<ide> $result = TestLogStaticConfig::dsnClassMap();
<del> $this->assertEquals($expected, $result, "The class map should match the class property");
<add> $this->assertEquals($expected, $result, 'The class map should match the class property');
<ide>
<ide> $expected = [
<ide> 'console' => 'Special\EngineLog',
<ide> 'file' => 'Cake\Log\Engine\FileLog',
<ide> 'syslog' => 'Cake\Log\Engine\SyslogLog',
<ide> ];
<ide> $result = TestLogStaticConfig::dsnClassMap(['console' => 'Special\EngineLog']);
<del> $this->assertEquals($expected, $result, "Should be possible to change the map");
<add> $this->assertEquals($expected, $result, 'Should be possible to change the map');
<ide>
<ide> $expected = [
<ide> 'console' => 'Special\EngineLog',
<ide> public function testCanUpdateClassMap()
<ide> 'my' => 'Special\OtherLog'
<ide> ];
<ide> $result = TestLogStaticConfig::dsnClassMap(['my' => 'Special\OtherLog']);
<del> $this->assertEquals($expected, $result, "Should be possible to add to the map");
<add> $this->assertEquals($expected, $result, 'Should be possible to add to the map');
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Driver/MysqlTest.php
<ide> public function testConnectionConfigCustom()
<ide> $dsn = 'mysql:host=foo;port=3440;dbname=bar;charset=a-language';
<ide> $expected = $config;
<ide> $expected['init'][] = "SET time_zone = 'Antarctica'";
<del> $expected['init'][] = "SET NAMES a-language";
<add> $expected['init'][] = 'SET NAMES a-language';
<ide> $expected['flags'] += [
<ide> PDO::ATTR_PERSISTENT => false,
<ide> PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
<ide> public function testConnectionConfigCustom()
<ide> $connection->expects($this->at(0))->method('exec')->with('Execute this');
<ide> $connection->expects($this->at(1))->method('exec')->with('this too');
<ide> $connection->expects($this->at(2))->method('exec')->with("SET time_zone = 'Antarctica'");
<del> $connection->expects($this->at(3))->method('exec')->with("SET NAMES a-language");
<add> $connection->expects($this->at(3))->method('exec')->with('SET NAMES a-language');
<ide> $connection->expects($this->exactly(4))->method('exec');
<ide>
<ide> $driver->expects($this->once())->method('_connect')
<ide><path>tests/TestCase/Database/Expression/FunctionExpressionTest.php
<ide> public function testArityMultiplePlainValues()
<ide> {
<ide> $f = new FunctionExpression('MyFunction', ['foo', 'bar']);
<ide> $binder = new ValueBinder;
<del> $this->assertEquals("MyFunction(:param0, :param1)", $f->sql($binder));
<add> $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>
<ide> $binder = new ValueBinder;
<ide> $f = new FunctionExpression('MyFunction', ['bar']);
<del> $this->assertEquals("MyFunction(:param0)", $f->sql($binder));
<add> $this->assertEquals('MyFunction(:param0)', $f->sql($binder));
<ide> $this->assertEquals('bar', $binder->bindings()[':param0']['value']);
<ide> }
<ide>
<ide> public function testLiteralParams()
<ide> {
<ide> $binder = new ValueBinder;
<ide> $f = new FunctionExpression('MyFunction', ['foo' => 'literal', 'bar']);
<del> $this->assertEquals("MyFunction(foo, :param0)", $f->sql($binder));
<add> $this->assertEquals('MyFunction(foo, :param0)', $f->sql($binder));
<ide> }
<ide>
<ide> /**
<ide> public function testFunctionNesting()
<ide> $binder = new ValueBinder;
<ide> $f = new FunctionExpression('MyFunction', ['foo', 'bar']);
<ide> $g = new FunctionExpression('Wrapper', ['bar' => 'literal', $f]);
<del> $this->assertEquals("Wrapper(bar, (MyFunction(:param0, :param1)))", $g->sql($binder));
<add> $this->assertEquals('Wrapper(bar, (MyFunction(:param0, :param1)))', $g->sql($binder));
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/FunctionsBuilderTest.php
<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->returnType());
<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->returnType());
<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->returnType());
<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->returnType());
<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->returnType());
<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->returnType());
<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->returnType());
<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->returnType());
<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->returnType());
<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->returnType());
<ide> }
<ide> }
<ide><path>tests/TestCase/Error/DebuggerTest.php
<ide> public function testMaskObject()
<ide> Debugger::setOutputMask(['password' => '[**********]']);
<ide> $object = new SecurityThing();
<ide> $result = Debugger::exportVar($object);
<del> $expected = "object(Cake\\Test\\TestCase\\Error\\SecurityThing){password=>[**********]}";
<add> $expected = 'object(Cake\\Test\\TestCase\\Error\\SecurityThing){password=>[**********]}';
<ide> $this->assertEquals($expected, preg_replace('/\s+/', '', $result));
<ide> }
<ide>
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> public static function exceptionProvider()
<ide> [
<ide> new MissingLayoutException(['file' => 'layouts/my_layout.ctp']),
<ide> [
<del> "/Missing Layout/",
<add> '/Missing Layout/',
<ide> "/layouts\/my_layout.ctp/"
<ide> ],
<ide> 500
<ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php
<ide> public function testHandleException()
<ide> $this->assertInstanceOf('Cake\Http\Response', $result);
<ide> $this->assertNotSame($result, $response);
<ide> $this->assertEquals(404, $result->getStatusCode());
<del> $this->assertContains("was not found", '' . $result->getBody());
<add> $this->assertContains('was not found', '' . $result->getBody());
<ide> }
<ide>
<ide> /**
<ide> public function testHandleExceptionLogAndTrace()
<ide> $result = $middleware($request, $response, $next);
<ide> $this->assertNotSame($result, $response);
<ide> $this->assertEquals(404, $result->getStatusCode());
<del> $this->assertContains("was not found", '' . $result->getBody());
<add> $this->assertContains('was not found', '' . $result->getBody());
<ide> }
<ide>
<ide> /**
<ide> public function testHandleExceptionSkipLog()
<ide> $result = $middleware($request, $response, $next);
<ide> $this->assertNotSame($result, $response);
<ide> $this->assertEquals(404, $result->getStatusCode());
<del> $this->assertContains("was not found", '' . $result->getBody());
<add> $this->assertContains('was not found', '' . $result->getBody());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Http/ResponseTest.php
<ide> public function testDisableCache()
<ide> $response = new Response();
<ide> $expected = [
<ide> 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
<del> 'Last-Modified' => gmdate("D, d M Y H:i:s") . " GMT",
<add> 'Last-Modified' => gmdate('D, d M Y H:i:s') . ' GMT',
<ide> 'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
<ide> 'Content-Type' => 'text/html; charset=UTF-8',
<ide> ];
<ide> public function testWithDisabledCache()
<ide> $response = new Response();
<ide> $expected = [
<ide> 'Expires' => ['Mon, 26 Jul 1997 05:00:00 GMT'],
<del> 'Last-Modified' => [gmdate("D, d M Y H:i:s") . " GMT"],
<add> 'Last-Modified' => [gmdate('D, d M Y H:i:s') . ' GMT'],
<ide> 'Cache-Control' => ['no-store, no-cache, must-revalidate, post-check=0, pre-check=0'],
<ide> 'Content-Type' => ['text/html; charset=UTF-8'],
<ide> ];
<ide> public function testCache()
<ide> $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
<ide> $response->expires('+1 day');
<ide> $expected = [
<del> 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
<del> 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
<add> 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
<add> 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
<ide> 'Expires' => $time->format('D, j M Y H:i:s') . ' GMT',
<ide> 'Cache-Control' => 'public, max-age=' . ($time->format('U') - time()),
<ide> 'Content-Type' => 'text/html; charset=UTF-8',
<ide> public function testCache()
<ide> $since = time();
<ide> $time = '+5 day';
<ide> $expected = [
<del> 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
<del> 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
<del> 'Expires' => gmdate("D, j M Y H:i:s", strtotime($time)) . " GMT",
<add> 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
<add> 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
<add> 'Expires' => gmdate('D, j M Y H:i:s', strtotime($time)) . ' GMT',
<ide> 'Cache-Control' => 'public, max-age=' . (strtotime($time) - time()),
<ide> 'Content-Type' => 'text/html; charset=UTF-8',
<ide> ];
<ide> public function testCache()
<ide> $since = time();
<ide> $time = time();
<ide> $expected = [
<del> 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
<del> 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
<del> 'Expires' => gmdate("D, j M Y H:i:s", $time) . " GMT",
<add> 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
<add> 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
<add> 'Expires' => gmdate('D, j M Y H:i:s', $time) . ' GMT',
<ide> 'Cache-Control' => 'public, max-age=0',
<ide> 'Content-Type' => 'text/html; charset=UTF-8',
<ide> ];
<ide> public function testWithCache()
<ide> $this->assertFalse($response->hasHeader('Date'));
<ide> $this->assertFalse($response->hasHeader('Last-Modified'));
<ide>
<del> $this->assertEquals(gmdate("D, j M Y G:i:s ", $since) . 'GMT', $new->getHeaderLine('Date'));
<del> $this->assertEquals(gmdate("D, j M Y H:i:s ", $since) . 'GMT', $new->getHeaderLine('Last-Modified'));
<del> $this->assertEquals(gmdate("D, j M Y H:i:s", $time) . " GMT", $new->getHeaderLine('Expires'));
<add> $this->assertEquals(gmdate('D, j M Y G:i:s ', $since) . 'GMT', $new->getHeaderLine('Date'));
<add> $this->assertEquals(gmdate('D, j M Y H:i:s ', $since) . 'GMT', $new->getHeaderLine('Last-Modified'));
<add> $this->assertEquals(gmdate('D, j M Y H:i:s', $time) . ' GMT', $new->getHeaderLine('Expires'));
<ide> $this->assertEquals('public, max-age=0', $new->getHeaderLine('Cache-Control'));
<ide> }
<ide>
<ide> public function testCompress()
<ide> $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
<ide>
<ide> $response = new Response();
<del> if (ini_get("zlib.output_compression") === '1' || !extension_loaded("zlib")) {
<add> if (ini_get('zlib.output_compression') === '1' || !extension_loaded('zlib')) {
<ide> $this->assertFalse($response->compress());
<ide> $this->markTestSkipped('Is not possible to test output compression');
<ide> }
<ide> public function testOutputCompressed()
<ide> $result = $response->outputCompressed();
<ide> $this->assertFalse($result);
<ide>
<del> if (!extension_loaded("zlib")) {
<add> if (!extension_loaded('zlib')) {
<ide> $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded');
<ide> }
<ide>
<ide> $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
<ide>
<del> if (ini_get("zlib.output_compression") !== '1') {
<add> if (ini_get('zlib.output_compression') !== '1') {
<ide> ob_start('ob_gzhandler');
<ide> }
<ide> $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
<ide> public function testOutputCompressed()
<ide> $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
<ide> $result = $response->outputCompressed();
<ide> $this->assertFalse($result);
<del> if (ini_get("zlib.output_compression") !== '1') {
<add> if (ini_get('zlib.output_compression') !== '1') {
<ide> ob_get_clean();
<ide> }
<ide> }
<ide> public function testFile()
<ide> $this->assertTrue($result !== false);
<ide> $output = ob_get_clean();
<ide>
<del> $expected = "/* this is the test asset css file */";
<add> $expected = '/* this is the test asset css file */';
<ide> $this->assertEquals($expected, trim($output));
<ide> $this->assertEquals($expected, trim($response->getBody()->getContents()));
<ide> }
<ide> public function testWithFileDownloadAndName()
<ide> $body = $new->getBody();
<ide> $this->assertInstanceOf('Zend\Diactoros\Stream', $body);
<ide>
<del> $expected = "/* this is the test asset css file */";
<add> $expected = '/* this is the test asset css file */';
<ide> $this->assertEquals($expected, trim($body->getContents()));
<ide> $this->assertEquals($expected, trim($new->getFile()->read()));
<ide> }
<ide> public function testFileRange()
<ide> $result = $response->send();
<ide> $output = ob_get_clean();
<ide> $this->assertEquals(206, $response->statusCode());
<del> $this->assertEquals("is the test asset ", $output);
<add> $this->assertEquals('is the test asset ', $output);
<ide> $this->assertNotSame(false, $result);
<ide> }
<ide>
<ide> public function testFileRangeNoDownload()
<ide> $result = $response->send();
<ide> $output = ob_get_clean();
<ide> $this->assertEquals(206, $response->statusCode());
<del> $this->assertEquals("is the test asset ", $output);
<add> $this->assertEquals('is the test asset ', $output);
<ide> $this->assertNotSame(false, $result);
<ide> }
<ide>
<ide><path>tests/TestCase/Http/ServerRequestTest.php
<ide> public function testEnvironmentDetection($name, $env, $expected)
<ide> $request = ServerRequestFactory::fromGlobals();
<ide> $uri = $request->getUri();
<ide>
<del> $this->assertEquals($expected['url'], $request->url, "URL is incorrect");
<add> $this->assertEquals($expected['url'], $request->url, 'URL is incorrect');
<ide> $this->assertEquals('/' . $expected['url'], $uri->getPath(), 'Uri->getPath() is incorrect');
<ide>
<del> $this->assertEquals($expected['base'], $request->base, "base is incorrect");
<del> $this->assertEquals($expected['base'], $request->getAttribute('base'), "base is incorrect");
<add> $this->assertEquals($expected['base'], $request->base, 'base is incorrect');
<add> $this->assertEquals($expected['base'], $request->getAttribute('base'), 'base is incorrect');
<ide>
<del> $this->assertEquals($expected['webroot'], $request->webroot, "webroot error");
<del> $this->assertEquals($expected['webroot'], $request->getAttribute('webroot'), "webroot is incorrect");
<add> $this->assertEquals($expected['webroot'], $request->webroot, 'webroot error');
<add> $this->assertEquals($expected['webroot'], $request->getAttribute('webroot'), 'webroot is incorrect');
<ide>
<ide> if (isset($expected['urlParams'])) {
<del> $this->assertEquals($expected['urlParams'], $request->query, "GET param mismatch");
<add> $this->assertEquals($expected['urlParams'], $request->query, 'GET param mismatch');
<ide> }
<ide> }
<ide>
<ide><path>tests/TestCase/I18n/TimeTest.php
<ide> public function testDefaultLocaleEffectsFormatting($class)
<ide> * @param string $result
<ide> * @return void
<ide> */
<del> public function assertTimeFormat($expected, $result, $message = "")
<add> public function assertTimeFormat($expected, $result, $message = '')
<ide> {
<ide> $expected = str_replace([',', '(', ')', ' at', ' م.', ' ه.ش.', ' AP', ' AH', ' SAKA', 'à '], '', $expected);
<ide> $expected = str_replace([' '], ' ', $expected);
<ide><path>tests/TestCase/Log/Engine/ConsoleLogTest.php
<ide> public function testConsoleOutputlogs()
<ide> $output->expects($this->at(0))
<ide> ->method('outputAs');
<ide>
<del> $message = " Error: oh noes</error>";
<add> $message = ' Error: oh noes</error>';
<ide> $output->expects($this->at(1))
<ide> ->method('write')
<ide> ->with($this->stringContains($message));
<ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public function testFormatAddressJapanese()
<ide> " =?ISO-2022-JP?B?GyRCPWgkZCRWJGk+Lk8pJE5pLjQ7O1IlUSUkJV0lUSUkJV0lUSUkGyhC?=\r\n" .
<ide> " =?ISO-2022-JP?B?GyRCJV0kTiU3JWUhPCVqJXMlLCVzJTclZSE8JWolcyUsJXMkTiUwGyhC?=\r\n" .
<ide> " =?ISO-2022-JP?B?GyRCITwlaiVzJUAlJCUwITwlaiVzJUAlJCROJV0lcyVdJTMlVCE8GyhC?=\r\n" .
<del> " =?ISO-2022-JP?B?GyRCJE4lXSVzJV0lMyVKITwkTkQ5NVdMPyRORDk9dRsoQg==?= <cake@cakephp.org>"];
<add> ' =?ISO-2022-JP?B?GyRCJE4lXSVzJV0lMyVKITwkTkQ5NVdMPyRORDk9dRsoQg==?= <cake@cakephp.org>'];
<ide> $this->assertSame($expected, $result);
<ide> }
<ide>
<ide> public function testSubjectJapanese()
<ide> $this->Email->subject('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?');
<ide> $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
<ide> " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
<del> " =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=";
<add> ' =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=';
<ide> $this->assertSame($expected, $this->Email->subject());
<ide> }
<ide>
<ide> public function testSendWithContent()
<ide> $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: '));
<ide> $this->assertTrue((bool)strpos($result['headers'], 'To: '));
<ide>
<del> $result = $this->Email->send("Other body");
<add> $result = $this->Email->send('Other body');
<ide> $expected = "Other body\r\n\r\n";
<ide> $this->assertSame($expected, $result['message']);
<ide> $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: '));
<ide> public function testSendWithoutFrom()
<ide> $this->Email->to('cake@cakephp.org');
<ide> $this->Email->subject('My title');
<ide> $this->Email->profile(['empty']);
<del> $this->Email->send("Forgot to set From");
<add> $this->Email->send('Forgot to set From');
<ide> }
<ide>
<ide> /**
<ide> public function testSendWithoutTo()
<ide> $this->Email->from('cake@cakephp.org');
<ide> $this->Email->subject('My title');
<ide> $this->Email->profile(['empty']);
<del> $this->Email->send("Forgot to set To");
<add> $this->Email->send('Forgot to set To');
<ide> }
<ide>
<ide> /**
<ide> public function testSendWithoutTransport()
<ide> $this->Email->to('cake@cakephp.org');
<ide> $this->Email->from('cake@cakephp.org');
<ide> $this->Email->subject('My title');
<del> $this->Email->send("Forgot to set To");
<add> $this->Email->send('Forgot to set To');
<ide> }
<ide>
<ide> /**
<ide> public function testSendNoTemplateWithAttachments()
<ide> "Content-Type: text/plain; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "Hello" .
<add> 'Hello' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> public function testSendNoTemplateWithDataStringAttachment()
<ide> "Content-Type: text/plain; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "Hello" .
<add> 'Hello' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> public function testSendNoTemplateWithAttachmentsAsBoth()
<ide> "Content-Type: text/plain; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "Hello" .
<add> 'Hello' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "--alt-$boundary\r\n" .
<ide> "Content-Type: text/html; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "Hello" .
<add> 'Hello' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> public function testSendWithInlineAttachments()
<ide> "Content-Type: text/plain; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "Hello" .
<add> 'Hello' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "--alt-$boundary\r\n" .
<ide> "Content-Type: text/html; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "Hello" .
<add> 'Hello' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> public function testSendWithInlineAttachmentsHtmlOnly()
<ide> "Content-Type: text/html; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "Hello" .
<add> 'Hello' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> public function testSendWithNoContentDispositionAttachments()
<ide> "Content-Type: text/plain; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "Hello" .
<add> 'Hello' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> public function testSendRenderBoth()
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "\r\n" .
<del> "This email was sent using the CakePHP Framework, https://cakephp.org." .
<add> 'This email was sent using the CakePHP Framework, https://cakephp.org.' .
<ide> "\r\n" .
<ide> "\r\n" .
<ide> "--$boundary\r\n" .
<ide> "Content-Type: text/html; charset=UTF-8\r\n" .
<ide> "Content-Transfer-Encoding: 8bit\r\n" .
<ide> "\r\n" .
<del> "<!DOCTYPE html";
<add> '<!DOCTYPE html';
<ide> $this->assertStringStartsWith($expected, $result['message']);
<ide>
<ide> $expected = "</html>\r\n" .
<ide> public function testHeaderEncoding()
<ide> $email = new Email(['headerCharset' => 'iso-2022-jp-ms', 'transport' => 'debug']);
<ide> $email->subject('あれ?もしかしての前と');
<ide> $headers = $email->getHeaders(['subject']);
<del> $expected = "?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=";
<add> $expected = '?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=';
<ide> $this->assertContains($expected, $headers['Subject']);
<ide>
<ide> $email->to('someone@example.com')->from('someone@example.com');
<ide> public function testBodyEncoding()
<ide> ]);
<ide> $email->subject('あれ?もしかしての前と');
<ide> $headers = $email->getHeaders(['subject']);
<del> $expected = "?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=";
<add> $expected = '?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=';
<ide> $this->assertContains($expected, $headers['Subject']);
<ide>
<ide> $email->to('someone@example.com')->from('someone@example.com');
<ide> public function testBodyEncodingIso2022Jp()
<ide> ]);
<ide> $email->subject('あれ?もしかしての前と');
<ide> $headers = $email->getHeaders(['subject']);
<del> $expected = "?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=";
<add> $expected = '?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=';
<ide> $this->assertContains($expected, $headers['Subject']);
<ide>
<ide> $email->to('someone@example.com')->from('someone@example.com');
<ide> $result = $email->send('①㈱');
<del> $this->assertTextContains("Content-Type: text/plain; charset=ISO-2022-JP", $result['headers']);
<del> $this->assertTextNotContains("Content-Type: text/plain; charset=ISO-2022-JP-MS", $result['headers']); // not charset=iso-2022-jp-ms
<add> $this->assertTextContains('Content-Type: text/plain; charset=ISO-2022-JP', $result['headers']);
<add> $this->assertTextNotContains('Content-Type: text/plain; charset=ISO-2022-JP-MS', $result['headers']); // not charset=iso-2022-jp-ms
<ide> $this->assertTextNotContains(mb_convert_encoding('①㈱', 'ISO-2022-JP-MS'), $result['message']);
<ide> }
<ide>
<ide> public function testBodyEncodingIso2022JpMs()
<ide> ]);
<ide> $email->subject('あれ?もしかしての前と');
<ide> $headers = $email->getHeaders(['subject']);
<del> $expected = "?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=";
<add> $expected = '?ISO-2022-JP?B?GyRCJCIkbCEpJGIkNyQrJDckRiROQTAkSBsoQg==?=';
<ide> $this->assertContains($expected, $headers['Subject']);
<ide>
<ide> $email->to('someone@example.com')->from('someone@example.com');
<ide> $result = $email->send('①㈱');
<del> $this->assertTextContains("Content-Type: text/plain; charset=ISO-2022-JP", $result['headers']);
<del> $this->assertTextNotContains("Content-Type: text/plain; charset=iso-2022-jp-ms", $result['headers']); // not charset=iso-2022-jp-ms
<add> $this->assertTextContains('Content-Type: text/plain; charset=ISO-2022-JP', $result['headers']);
<add> $this->assertTextNotContains('Content-Type: text/plain; charset=iso-2022-jp-ms', $result['headers']); // not charset=iso-2022-jp-ms
<ide> $this->assertContains(mb_convert_encoding('①㈱', 'ISO-2022-JP-MS'), $result['message']);
<ide> }
<ide>
<ide> public function testEncode()
<ide> $result = $this->Email->encode('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?');
<ide> $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
<ide> " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
<del> " =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=";
<add> ' =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=';
<ide> $this->assertSame($expected, $result);
<ide> }
<ide>
<ide> public function testDecode()
<ide> $this->Email->headerCharset = 'ISO-2022-JP';
<ide> $result = $this->Email->decode("=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
<ide> " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
<del> " =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=");
<add> ' =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=');
<ide> $expected = '長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?';
<ide> $this->assertSame($expected, $result);
<ide> }
<ide> protected function _getEmailByNewStyleCharset($charset, $headerCharset)
<ide> */
<ide> public function testWrapLongLine()
<ide> {
<del> $message = '<a href="http://cakephp.org">' . str_repeat('x', Email::LINE_LENGTH_MUST) . "</a>";
<add> $message = '<a href="http://cakephp.org">' . str_repeat('x', Email::LINE_LENGTH_MUST) . '</a>';
<ide>
<ide> $this->Email->reset();
<ide> $this->Email->transport('debug');
<ide> public function testWrapLongLine()
<ide> $this->assertEquals($expected, $result['message']);
<ide> $this->assertLineLengths($result['message']);
<ide>
<del> $str1 = "a ";
<del> $str2 = " b";
<add> $str1 = 'a ';
<add> $str2 = ' b';
<ide> $length = strlen($str1) + strlen($str2);
<ide> $message = $str1 . str_repeat('x', Email::LINE_LENGTH_MUST - $length - 1) . $str2;
<ide>
<ide><path>tests/TestCase/Mailer/Transport/DebugTransportTest.php
<ide> public function testSend()
<ide> $headers = "From: CakePHP Test <noreply@cakephp.org>\r\n";
<ide> $headers .= "To: CakePHP <cake@cakephp.org>\r\n";
<ide> $headers .= "Cc: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>\r\n";
<del> $headers .= "Date: " . $date . "\r\n";
<add> $headers .= 'Date: ' . $date . "\r\n";
<ide> $headers .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n";
<ide> $headers .= "Subject: Testing Message\r\n";
<ide> $headers .= "MIME-Version: 1.0\r\n";
<ide> $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
<del> $headers .= "Content-Transfer-Encoding: 8bit";
<add> $headers .= 'Content-Transfer-Encoding: 8bit';
<ide>
<ide> $data = "First Line\r\n";
<ide> $data .= "Second Line\r\n";
<ide><path>tests/TestCase/Mailer/Transport/MailTransportTest.php
<ide> public function testSendData()
<ide> $encoded = '=?UTF-8?B?Rm/DuCBCw6VyIELDqXogRm/DuCBCw6VyIELDqXogRm/DuCBCw6VyIELDqXog?=';
<ide> $encoded .= ' =?UTF-8?B?Rm/DuCBCw6VyIELDqXo=?=';
<ide>
<del> $data = "From: CakePHP Test <noreply@cakephp.org>" . PHP_EOL;
<del> $data .= "Return-Path: CakePHP Return <pleasereply@cakephp.org>" . PHP_EOL;
<del> $data .= "Cc: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>" . PHP_EOL;
<del> $data .= "Bcc: phpnut@cakephp.org" . PHP_EOL;
<del> $data .= "X-Mailer: CakePHP Email" . PHP_EOL;
<del> $data .= "Date: " . $date . PHP_EOL;
<del> $data .= "X-add: " . $encoded . PHP_EOL;
<del> $data .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>" . PHP_EOL;
<del> $data .= "MIME-Version: 1.0" . PHP_EOL;
<del> $data .= "Content-Type: text/plain; charset=UTF-8" . PHP_EOL;
<del> $data .= "Content-Transfer-Encoding: 8bit";
<add> $data = 'From: CakePHP Test <noreply@cakephp.org>' . PHP_EOL;
<add> $data .= 'Return-Path: CakePHP Return <pleasereply@cakephp.org>' . PHP_EOL;
<add> $data .= 'Cc: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>' . PHP_EOL;
<add> $data .= 'Bcc: phpnut@cakephp.org' . PHP_EOL;
<add> $data .= 'X-Mailer: CakePHP Email' . PHP_EOL;
<add> $data .= 'Date: ' . $date . PHP_EOL;
<add> $data .= 'X-add: ' . $encoded . PHP_EOL;
<add> $data .= 'Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>' . PHP_EOL;
<add> $data .= 'MIME-Version: 1.0' . PHP_EOL;
<add> $data .= 'Content-Type: text/plain; charset=UTF-8' . PHP_EOL;
<add> $data .= 'Content-Transfer-Encoding: 8bit';
<ide>
<ide> $this->MailTransport->expects($this->once())->method('_mail')
<ide> ->with(
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php
<ide> public function testSendData()
<ide> $data .= "Return-Path: CakePHP Return <pleasereply@cakephp.org>\r\n";
<ide> $data .= "To: CakePHP <cake@cakephp.org>\r\n";
<ide> $data .= "Cc: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>\r\n";
<del> $data .= "Date: " . $date . "\r\n";
<add> $data .= 'Date: ' . $date . "\r\n";
<ide> $data .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n";
<ide> $data .= "Subject: Testing SMTP\r\n";
<ide> $data .= "MIME-Version: 1.0\r\n";
<ide><path>tests/TestCase/Network/SessionTest.php
<ide> public function testCheckingSavedEmpty()
<ide> public function testCheckKeyWithSpaces()
<ide> {
<ide> $session = new Session();
<del> $session->write('Session Test', "test");
<add> $session->write('Session Test', 'test');
<ide> $this->assertTrue($session->check('Session Test'));
<ide> $session->delete('Session Test');
<ide>
<del> $session->write('Session Test.Test Case', "test");
<add> $session->write('Session Test.Test Case', 'test');
<ide> $this->assertTrue($session->check('Session Test.Test Case'));
<ide> }
<ide>
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testCountWithBind()
<ide> $query = $table
<ide> ->find()
<ide> ->select(['title', 'id'])
<del> ->where("title LIKE :val")
<add> ->where('title LIKE :val')
<ide> ->group(['id', 'title'])
<ide> ->bind(':val', '%Second%');
<ide> $count = $query->count();
<ide> public function testSubqueryBind()
<ide> $table = TableRegistry::get('Articles');
<ide> $sub = $table->find()
<ide> ->select(['id'])
<del> ->where("title LIKE :val")
<add> ->where('title LIKE :val')
<ide> ->bind(':val', 'Second %');
<ide>
<ide> $query = $table
<ide> ->find()
<ide> ->select(['title'])
<del> ->where(["id NOT IN" => $sub]);
<add> ->where(['id NOT IN' => $sub]);
<ide> $result = $query->toArray();
<ide> $this->assertCount(2, $result);
<ide> $this->assertEquals('First Article', $result[0]->title);
<ide><path>tests/TestCase/Routing/Filter/RoutingFilterTest.php
<ide> public function testBeforeDispatchSkipWhenControllerSet()
<ide> {
<ide> $filter = new RoutingFilter();
<ide>
<del> $request = new ServerRequest("/testcontroller/testaction/params1/params2/params3");
<add> $request = new ServerRequest('/testcontroller/testaction/params1/params2/params3');
<ide> $request->addParams(['controller' => 'articles']);
<ide> $event = new Event(__CLASS__, $this, compact('request'));
<ide> $filter->beforeDispatch($event);
<ide> public function testBeforeDispatchSetsParameters()
<ide> Router::connect('/:controller/:action/*');
<ide> $filter = new RoutingFilter();
<ide>
<del> $request = new ServerRequest("/testcontroller/testaction/params1/params2/params3");
<add> $request = new ServerRequest('/testcontroller/testaction/params1/params2/params3');
<ide> $event = new Event(__CLASS__, $this, compact('request'));
<ide> $filter->beforeDispatch($event);
<ide>
<ide> public function testBeforeDispatchRedirectRoute()
<ide> });
<ide> $filter = new RoutingFilter();
<ide>
<del> $request = new ServerRequest("/home");
<add> $request = new ServerRequest('/home');
<ide> $response = new Response();
<ide> $event = new Event(__CLASS__, $this, compact('request', 'response'));
<ide> $response = $filter->beforeDispatch($event);
<ide><path>tests/TestCase/Routing/Route/RouteTest.php
<ide> public function testComplexRouteCompilingAndParsing()
<ide> $this->assertEquals($result['_matchedRoute'], '/posts/:month/:day/:year/*');
<ide>
<ide> $route = new Route(
<del> "/:extra/page/:slug/*",
<add> '/:extra/page/:slug/*',
<ide> ['controller' => 'pages', 'action' => 'view', 'extra' => null],
<del> ["extra" => '[a-z1-9_]*', "slug" => '[a-z1-9_]+', "action" => 'view']
<add> ['extra' => '[a-z1-9_]*', 'slug' => '[a-z1-9_]+', 'action' => 'view']
<ide> );
<ide> $result = $route->compile();
<ide>
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testUuidRoutes()
<ide> public function testRouteSymmetry()
<ide> {
<ide> Router::connect(
<del> "/:extra/page/:slug/*",
<add> '/:extra/page/:slug/*',
<ide> ['controller' => 'pages', 'action' => 'view', 'extra' => null],
<del> ["extra" => '[a-z1-9_]*', "slug" => '[a-z1-9_]+', "action" => 'view']
<add> ['extra' => '[a-z1-9_]*', 'slug' => '[a-z1-9_]+', 'action' => 'view']
<ide> );
<ide>
<ide> $result = Router::parse('/some_extra/page/this_is_the_slug', 'GET');
<ide> public function testRouteSymmetry()
<ide>
<ide> Router::reload();
<ide> Router::connect(
<del> "/:extra/page/:slug/*",
<add> '/:extra/page/:slug/*',
<ide> ['controller' => 'pages', 'action' => 'view', 'extra' => null],
<del> ["extra" => '[a-z1-9_]*', "slug" => '[a-z1-9_]+']
<add> ['extra' => '[a-z1-9_]*', 'slug' => '[a-z1-9_]+']
<ide> );
<ide>
<ide> $result = Router::url([
<ide><path>tests/TestCase/Shell/CompletionShellTest.php
<ide> public function testMain()
<ide> $this->Shell->runCommand(['main']);
<ide> $output = $this->out->output;
<ide>
<del> $expected = "/This command is not intended to be called manually/";
<add> $expected = '/This command is not intended to be called manually/';
<ide> $this->assertRegExp($expected, $output);
<ide> }
<ide>
<ide> public function testCommands()
<ide> $this->Shell->runCommand(['commands']);
<ide> $output = $this->out->output;
<ide>
<del> $expected = "TestPlugin.example TestPlugin.sample TestPluginTwo.example unique welcome " .
<add> $expected = 'TestPlugin.example TestPlugin.sample TestPluginTwo.example unique welcome ' .
<ide> "cache i18n orm_cache plugin routes server i18m sample testing_dispatch\n";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide> public function testOptionsNoArguments()
<ide> $this->Shell->runCommand(['options']);
<ide> $output = $this->out->output;
<ide>
<del> $expected = "";
<add> $expected = '';
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide> public function testOptionsNonExistingCommand()
<ide> {
<ide> $this->Shell->runCommand(['options', 'foo']);
<ide> $output = $this->out->output;
<del> $expected = "";
<add> $expected = '';
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide>
<ide><path>tests/TestCase/Shell/Task/UnloadTaskTest.php
<ide> public function testUnload()
<ide> {
<ide> $bootstrap = new File($this->bootstrap, false);
<ide>
<del> $this->_addPluginToBootstrap("TestPlugin");
<add> $this->_addPluginToBootstrap('TestPlugin');
<ide>
<del> $this->_addPluginToBootstrap("TestPluginSecond");
<add> $this->_addPluginToBootstrap('TestPluginSecond');
<ide>
<ide> $expected = "Plugin::load('TestPlugin', ['autoload' => true, 'bootstrap' => false, 'routes' => false]);";
<ide> $this->assertContains($expected, $bootstrap->read());
<ide><path>tests/TestCase/TestSuite/AssertHtmlTest.php
<ide> public function testAssertHtmlQuoting()
<ide> ];
<ide> $this->assertHtml($pattern, $input);
<ide>
<del> $input = "<span><strong>Text</strong></span>";
<add> $input = '<span><strong>Text</strong></span>';
<ide> $pattern = [
<ide> '<span',
<ide> '<strong',
<ide><path>tests/TestCase/TestSuite/TestCaseTest.php
<ide> public function testAssertTextContains()
<ide> $stringDirty = "some\nstring\r\nwith\rdifferent\nline endings!";
<ide> $stringClean = "some\nstring\nwith\ndifferent\nline endings!";
<ide>
<del> $this->assertContains("different", $stringDirty);
<add> $this->assertContains('different', $stringDirty);
<ide> $this->assertNotContains("different\rline", $stringDirty);
<ide>
<ide> $this->assertTextContains("different\rline", $stringDirty);
<ide><path>tests/TestCase/Utility/TextTest.php
<ide> public function tearDown()
<ide> public function testUuidGeneration()
<ide> {
<ide> $result = Text::uuid();
<del> $pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/";
<add> $pattern = '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/';
<ide> $match = (bool)preg_match($pattern, $result);
<ide> $this->assertTrue($match);
<ide> }
<ide> public function testMultipleUuidGeneration()
<ide> {
<ide> $check = [];
<ide> $count = mt_rand(10, 1000);
<del> $pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/";
<add> $pattern = '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/';
<ide>
<ide> for ($i = 0; $i < $count; $i++) {
<ide> $result = Text::uuid();
<ide> public function testInsert()
<ide> $result = Text::insert($string, ['src' => 'foo', 'extra' => 'bar'], ['clean' => 'html']);
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Text::insert("this is a ? string", "test");
<del> $expected = "this is a test string";
<add> $result = Text::insert('this is a ? string', 'test');
<add> $expected = 'this is a test string';
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Text::insert("this is a ? string with a ? ? ?", ['long', 'few?', 'params', 'you know']);
<del> $expected = "this is a long string with a few? params you know";
<add> $result = Text::insert('this is a ? string with a ? ? ?', ['long', 'few?', 'params', 'you know']);
<add> $expected = 'this is a long string with a few? params you know';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Text::insert('update saved_urls set url = :url where id = :id', ['url' => 'http://www.testurl.com/param1:url/param2:id', 'id' => 1]);
<del> $expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1";
<add> $expected = 'update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Text::insert('update saved_urls set url = :url where id = :id', ['id' => 1, 'url' => 'http://www.testurl.com/param1:url/param2:id']);
<del> $expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1";
<add> $expected = 'update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Text::insert(':me cake. :subject :verb fantastic.', ['me' => 'I :verb', 'subject' => 'cake', 'verb' => 'is']);
<del> $expected = "I :verb cake. cake is fantastic.";
<add> $expected = 'I :verb cake. cake is fantastic.';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Text::insert(':I.am: :not.yet: passing.', ['I.am' => 'We are'], ['before' => ':', 'after' => ':', 'clean' => ['replacement' => ' of course', 'method' => 'text']]);
<del> $expected = "We are of course passing.";
<add> $expected = 'We are of course passing.';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Text::insert(
<ide> ':I.am: :not.yet: passing.',
<ide> ['I.am' => 'We are'],
<ide> ['before' => ':', 'after' => ':', 'clean' => true]
<ide> );
<del> $expected = "We are passing.";
<add> $expected = 'We are passing.';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = Text::insert('?-pended result', ['Pre']);
<del> $expected = "Pre-pended result";
<add> $expected = 'Pre-pended result';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $string = 'switching :timeout / :timeout_count';
<ide> public function testWrapBlockWithIndentAt1()
<ide> public function testWrapBlockIndentWithMultibyte()
<ide> {
<ide> $text = 'This is the song that never ends. 这是永远不会结束的歌曲。 This is the song that never ends.';
<del> $result = Text::wrapBlock($text, ['width' => 33, 'indent' => " → ", 'indentAt' => 1]);
<add> $result = Text::wrapBlock($text, ['width' => 33, 'indent' => ' → ', 'indentAt' => 1]);
<ide> $expected = <<<TEXT
<ide> This is the song that never ends.
<ide> → 这是永远不会结束的歌曲。 This is the song
<ide> public function testTruncateTrimWidth()
<ide> 素晴らしい、でしょ?
<ide> HTML;
<ide> $this->assertEquals("<IMG src=\"mypic.jpg\">このimageタグはXHTMLに準拠していない!<br>\n<hr/><b>でも次の…</b>", Text::truncate($text, 30, ['html' => true]));
<del> $this->assertEquals("<IMG src=\"mypic.jpg\">このimageタグはXHTMLに準拠し…", Text::truncate($text, 30, ['html' => true, 'trimWidth' => true]));
<add> $this->assertEquals('<IMG src="mypic.jpg">このimageタグはXHTMLに準拠し…', Text::truncate($text, 30, ['html' => true, 'trimWidth' => true]));
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> public function testNotBlank()
<ide> $this->assertTrue(Validation::notBlank(0.0));
<ide> $this->assertTrue(Validation::notBlank('0.0'));
<ide> $this->assertFalse(Validation::notBlank("\t "));
<del> $this->assertFalse(Validation::notBlank(""));
<add> $this->assertFalse(Validation::notBlank(''));
<ide> }
<ide>
<ide> /**
<ide> public function testNotBlankIso88591AppEncoding()
<ide> $this->assertTrue(Validation::notBlank('José'));
<ide> $this->assertTrue(Validation::notBlank(utf8_decode('José')));
<ide> $this->assertFalse(Validation::notBlank("\t "));
<del> $this->assertFalse(Validation::notBlank(""));
<add> $this->assertFalse(Validation::notBlank(''));
<ide> }
<ide>
<ide> /**
<ide> public function testEmailCustomRegex()
<ide> */
<ide> public function testEqualTo()
<ide> {
<del> $this->assertTrue(Validation::equalTo("1", "1"));
<del> $this->assertFalse(Validation::equalTo(1, "1"));
<del> $this->assertFalse(Validation::equalTo("", null));
<del> $this->assertFalse(Validation::equalTo("", false));
<add> $this->assertTrue(Validation::equalTo('1', '1'));
<add> $this->assertFalse(Validation::equalTo(1, '1'));
<add> $this->assertFalse(Validation::equalTo('', null));
<add> $this->assertFalse(Validation::equalTo('', false));
<ide> $this->assertFalse(Validation::equalTo(0, false));
<ide> $this->assertFalse(Validation::equalTo(null, false));
<ide> }
<ide> public function testContainNonAlphaNumeric()
<ide> $this->assertTrue(Validation::containsNonAlphaNumeric("\n"));
<ide> $this->assertTrue(Validation::containsNonAlphaNumeric("\t"));
<ide> $this->assertTrue(Validation::containsNonAlphaNumeric("\r"));
<del> $this->assertTrue(Validation::containsNonAlphaNumeric(" "));
<add> $this->assertTrue(Validation::containsNonAlphaNumeric(' '));
<ide>
<ide> $this->assertTrue(Validation::containsNonAlphaNumeric('#abcdef'));
<ide> $this->assertTrue(Validation::containsNonAlphaNumeric('abc#def'));
<ide><path>tests/TestCase/View/CellTest.php
<ide> public function testACachedViewCellReRendersWhenGivenADifferentTemplate()
<ide> 'path' => CACHE,
<ide> ]);
<ide> $cell = $this->View->cell('Articles::customTemplateViewBuilder', [], ['cache' => true]);
<del> $result = $cell->render("alternate_teaser_list");
<del> $result2 = $cell->render("not_the_alternate_teaser_list");
<add> $result = $cell->render('alternate_teaser_list');
<add> $result2 = $cell->render('not_the_alternate_teaser_list');
<ide> $this->assertContains('This is the alternate template', $result);
<ide> $this->assertContains('This is NOT the alternate template', $result2);
<ide> Cache::delete('celltest');
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testControlCheckboxWithDisabledElements()
<ide>
<ide> $expected = [
<ide> ['div' => ['class' => 'input select']],
<del> ['label' => ['for' => "contact-multiple"]],
<add> ['label' => ['for' => 'contact-multiple']],
<ide> 'Multiple',
<ide> '/label',
<del> ['input' => ['type' => 'hidden', 'name' => "Contact[multiple]", 'disabled' => 'disabled', 'value' => '']],
<add> ['input' => ['type' => 'hidden', 'name' => 'Contact[multiple]', 'disabled' => 'disabled', 'value' => '']],
<ide> ['div' => ['class' => 'checkbox']],
<del> ['label' => ['for' => "contact-multiple-1"]],
<del> ['input' => ['type' => 'checkbox', 'name' => "Contact[multiple][]", 'value' => 1, 'disabled' => 'disabled', 'id' => "contact-multiple-1"]],
<add> ['label' => ['for' => 'contact-multiple-1']],
<add> ['input' => ['type' => 'checkbox', 'name' => 'Contact[multiple][]', 'value' => 1, 'disabled' => 'disabled', 'id' => 'contact-multiple-1']],
<ide> 'One',
<ide> '/label',
<ide> '/div',
<ide> ['div' => ['class' => 'checkbox']],
<del> ['label' => ['for' => "contact-multiple-2"]],
<del> ['input' => ['type' => 'checkbox', 'name' => "Contact[multiple][]", 'value' => 2, 'disabled' => 'disabled', 'id' => "contact-multiple-2"]],
<add> ['label' => ['for' => 'contact-multiple-2']],
<add> ['input' => ['type' => 'checkbox', 'name' => 'Contact[multiple][]', 'value' => 2, 'disabled' => 'disabled', 'id' => 'contact-multiple-2']],
<ide> 'Two',
<ide> '/label',
<ide> '/div',
<ide> ['div' => ['class' => 'checkbox']],
<del> ['label' => ['for' => "contact-multiple-3"]],
<del> ['input' => ['type' => 'checkbox', 'name' => "Contact[multiple][]", 'value' => 3, 'disabled' => 'disabled', 'id' => "contact-multiple-3"]],
<add> ['label' => ['for' => 'contact-multiple-3']],
<add> ['input' => ['type' => 'checkbox', 'name' => 'Contact[multiple][]', 'value' => 3, 'disabled' => 'disabled', 'id' => 'contact-multiple-3']],
<ide> 'Three',
<ide> '/label',
<ide> '/div',
<ide> public function testControlCheckboxWithDisabledElements()
<ide>
<ide> $expected = [
<ide> ['div' => ['class' => 'input select']],
<del> ['label' => ['for' => "contact-multiple"]],
<add> ['label' => ['for' => 'contact-multiple']],
<ide> 'Multiple',
<ide> '/label',
<del> ['input' => ['type' => 'hidden', 'name' => "Contact[multiple]", 'value' => '']],
<add> ['input' => ['type' => 'hidden', 'name' => 'Contact[multiple]', 'value' => '']],
<ide> ['div' => ['class' => 'checkbox']],
<del> ['label' => ['for' => "contact-multiple-50"]],
<del> ['input' => ['type' => 'checkbox', 'name' => "Contact[multiple][]", 'value' => 50, 'disabled' => 'disabled', 'id' => "contact-multiple-50"]],
<add> ['label' => ['for' => 'contact-multiple-50']],
<add> ['input' => ['type' => 'checkbox', 'name' => 'Contact[multiple][]', 'value' => 50, 'disabled' => 'disabled', 'id' => 'contact-multiple-50']],
<ide> 'Fifty',
<ide> '/label',
<ide> '/div',
<ide> ['div' => ['class' => 'checkbox']],
<del> ['label' => ['for' => "contact-multiple-50f5c0cf"]],
<del> ['input' => ['type' => 'checkbox', 'name' => "Contact[multiple][]", 'value' => '50f5c0cf', 'id' => "contact-multiple-50f5c0cf"]],
<add> ['label' => ['for' => 'contact-multiple-50f5c0cf']],
<add> ['input' => ['type' => 'checkbox', 'name' => 'Contact[multiple][]', 'value' => '50f5c0cf', 'id' => 'contact-multiple-50f5c0cf']],
<ide> 'Stringy',
<ide> '/label',
<ide> '/div',
<ide> public function testError()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<del> $result = $this->Form->error('Article.field', "<strong>Badness!</strong>");
<add> $result = $this->Form->error('Article.field', '<strong>Badness!</strong>');
<ide> $expected = [
<ide> ['div' => ['class' => 'error-message']],
<ide> '<strong>Badness!</strong>',
<ide> '/div',
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<del> $result = $this->Form->error('Article.field', "<strong>Badness!</strong>", ['escape' => false]);
<add> $result = $this->Form->error('Article.field', '<strong>Badness!</strong>', ['escape' => false]);
<ide> $expected = [
<ide> ['div' => ['class' => 'error-message']],
<ide> '<strong', 'Badness!', '/strong',
<ide> public function testTextArea()
<ide> public function testTextAreaWithStupidCharacters()
<ide> {
<ide> $result = $this->Form->textarea('Post.content', [
<del> 'value' => "GREAT®",
<add> 'value' => 'GREAT®',
<ide> 'rows' => '15',
<ide> 'cols' => '75'
<ide> ]);
<ide> public function testFormMagicControlLabel()
<ide> ]];
<ide> $this->assertHtml($expected, $result);
<ide>
<del> $result = $this->Form->control("1.name");
<add> $result = $this->Form->control('1.name');
<ide> $expected = [
<ide> 'label' => ['for' => '1-name'],
<ide> 'Name',
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testTableCells()
<ide> {
<ide> $tr = [
<ide> 'td content 1',
<del> ['td content 2', ["width" => "100px"]],
<add> ['td content 2', ['width' => '100px']],
<ide> ['td content 3', ['width' => '100px']]
<ide> ];
<ide> $result = $this->Html->tableCells($tr);
<ide><path>tests/TestCase/View/Helper/RssHelperTest.php
<ide> public function testChannelElements()
<ide> 'link' => 'http://example.com'
<ide> ],
<ide> 'cloud' => [
<del> 'domain' => "rpc.sys.com",
<del> 'port' => "80",
<del> 'path' => "/RPC2",
<del> 'registerProcedure' => "myCloud.rssPleaseNotify",
<del> 'protocol' => "xml-rpc"
<add> 'domain' => 'rpc.sys.com',
<add> 'port' => '80',
<add> 'path' => '/RPC2',
<add> 'registerProcedure' => 'myCloud.rssPleaseNotify',
<add> 'protocol' => 'xml-rpc'
<ide> ]
<ide> ];
<ide> $content = 'content-here';
<ide> public function testChannelElements()
<ide> '<link', 'http://example.com', '/link',
<ide> '/image',
<ide> 'cloud' => [
<del> 'domain' => "rpc.sys.com",
<del> 'port' => "80",
<del> 'path' => "/RPC2",
<del> 'registerProcedure' => "myCloud.rssPleaseNotify",
<del> 'protocol' => "xml-rpc"
<add> 'domain' => 'rpc.sys.com',
<add> 'port' => '80',
<add> 'path' => '/RPC2',
<add> 'registerProcedure' => 'myCloud.rssPleaseNotify',
<add> 'protocol' => 'xml-rpc'
<ide> ],
<ide> 'content-here',
<ide> '/channel',
<ide> public function testChannelElementAttributes()
<ide> '/image',
<ide> 'atom:link' => [
<ide> 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
<del> 'href' => "http://www.example.com/rss.xml",
<del> 'rel' => "self",
<del> 'type' => "application/rss+xml"
<add> 'href' => 'http://www.example.com/rss.xml',
<add> 'rel' => 'self',
<add> 'type' => 'application/rss+xml'
<ide> ],
<ide> 'content-here',
<ide> '/channel',
<ide><path>tests/TestCase/View/Helper/UrlHelperTest.php
<ide> public function testUrlConversion()
<ide> $this->assertEquals('/controller/action/1?one=1&two=2', $result);
<ide>
<ide> $result = $this->Helper->build(['controller' => 'posts', 'action' => 'index', 'page' => '1" onclick="alert(\'XSS\');"']);
<del> $this->assertEquals("/posts/index?page=1%22+onclick%3D%22alert%28%27XSS%27%29%3B%22", $result);
<add> $this->assertEquals('/posts/index?page=1%22+onclick%3D%22alert%28%27XSS%27%29%3B%22', $result);
<ide>
<ide> $result = $this->Helper->build('/controller/action/1/param:this+one+more');
<ide> $this->assertEquals('/controller/action/1/param:this+one+more', $result);
<ide> public function testUrlConversion()
<ide> $result = $this->Helper->build([
<ide> 'controller' => 'posts', 'action' => 'index', 'param' => '%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24'
<ide> ]);
<del> $this->assertEquals("/posts/index?param=%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524", $result);
<add> $this->assertEquals('/posts/index?param=%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524', $result);
<ide>
<ide> $result = $this->Helper->build([
<ide> 'controller' => 'posts', 'action' => 'index', 'page' => '1',
<ide> '?' => ['one' => 'value', 'two' => 'value', 'three' => 'purple']
<ide> ]);
<del> $this->assertEquals("/posts/index?one=value&two=value&three=purple&page=1", $result);
<add> $this->assertEquals('/posts/index?one=value&two=value&three=purple&page=1', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testUrlConversionUnescaped()
<ide> '1' => '2'
<ide> ]
<ide> ], ['escape' => false]);
<del> $this->assertEquals("/posts/view?k=v&1=2¶m=%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524", $result);
<add> $this->assertEquals('/posts/view?k=v&1=2¶m=%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524', $result);
<ide> }
<ide>
<ide> /**
<ide><path>tests/test_app/TestApp/Controller/AuthTestController.php
<ide> public function logout()
<ide> */
<ide> public function add()
<ide> {
<del> echo "add";
<add> echo 'add';
<ide> }
<ide>
<ide> /**
<ide> public function add()
<ide> */
<ide> public function view()
<ide> {
<del> echo "view";
<add> echo 'view';
<ide> }
<ide>
<ide> /**
<ide> public function view()
<ide> */
<ide> public function camelCase()
<ide> {
<del> echo "camelCase";
<add> echo 'camelCase';
<ide> }
<ide>
<ide> /** | 44 |
Python | Python | use log.info instead of print in setup.py's | 0f7dfd7f75d339098c1bb024dfb7181c7a31411a | <ide><path>numpy/core/setup.py
<ide> import os
<ide> import sys
<ide> from os.path import join
<add>from numpy.distutils import log
<ide> from distutils.dep_util import newer
<ide>
<ide> FUNCTIONS_TO_CHECK = [
<ide> def generate_config_h(ext, build_dir):
<ide> target = join(build_dir,'config.h')
<ide> if newer(__file__,target):
<ide> config_cmd = config.get_config_cmd()
<del> print 'Generating',target
<del> #
<add> log.info('Generating %s',target)
<ide> tc = generate_testcode(target)
<ide> from distutils import sysconfig
<ide> python_include = sysconfig.get_python_inc()
<ide> def generate_api(ext, build_dir):
<ide> sys.path.insert(0, codegen_dir)
<ide> try:
<ide> m = __import__(module_name)
<del> print 'executing', script
<add> log.info('executing %s', script)
<ide> h_file, c_file, doc_file = m.generate_api(build_dir)
<ide> finally:
<ide> del sys.path[0]
<ide><path>numpy/distutils/command/build_src.py
<ide> def build_library_sources(self, lib_name, build_info):
<ide> sources, h_files = self.filter_h_files(sources)
<ide>
<ide> if h_files:
<del> print self.package,'- nothing done with h_files=',h_files
<add> log.info('%s - nothing done with h_files = %s',
<add> self.package, h_files)
<ide>
<ide> #for f in h_files:
<ide> # self.distribution.headers.append((lib_name,f))
<ide> def build_extension_sources(self, ext):
<ide> sources, h_files = self.filter_h_files(sources)
<ide>
<ide> if h_files:
<del> print package,'- nothing done with h_files=',h_files
<add> log.info('%s - nothing done with h_files = %s',
<add> package, h_files)
<ide> #for f in h_files:
<ide> # self.distribution.headers.append((package,f))
<ide> | 2 |
Javascript | Javascript | add remaining path benchmarks & optimize | 99d9d7e716752b90e60103756875c42876d47bc4 | <ide><path>benchmark/path/basename.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>var v8 = require('v8');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add>
<add> // Force optimization before starting the benchmark
<add> p.basename('/foo/bar/baz/asdf/quux.html');
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.basename)');
<add> p.basename('/foo/bar/baz/asdf/quux.html');
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> p.basename('/foo/bar/baz/asdf/quux.html');
<add> p.basename('/foo/bar/baz/asdf/quux.html', '.html');
<add> }
<add> bench.end(n);
<add>}
<ide><path>benchmark/path/dirname.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>var v8 = require('v8');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add>
<add> // Force optimization before starting the benchmark
<add> p.dirname('/foo/bar/baz/asdf/quux');
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.dirname)');
<add> p.dirname('/foo/bar/baz/asdf/quux');
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> p.dirname('/foo/bar/baz/asdf/quux');
<add> }
<add> bench.end(n);
<add>}
<ide><path>benchmark/path/extname.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>var v8 = require('v8');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add>
<add> // Force optimization before starting the benchmark
<add> p.extname('index.html');
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.extname)');
<add> p.extname('index.html');
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> p.extname('index.html');
<add> p.extname('index');
<add> }
<add> bench.end(n);
<add>}
<ide><path>benchmark/path/format.js
<ide> var common = require('../common.js');
<ide> var path = require('path');
<add>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> type: ['win32', 'posix'],
<ide> function main(conf) {
<ide> name : 'index'
<ide> };
<ide>
<add> // Force optimization before starting the benchmark
<add> p.format(test);
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.format)');
<add> p.format(test);
<add>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.format(test);
<ide><path>benchmark/path/isAbsolute.js
<ide> var common = require('../common.js');
<ide> var path = require('path');
<add>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> type: ['win32', 'posix'],
<ide> function main(conf) {
<ide> ? ['//server', 'C:\\baz\\..', 'bar\\baz', '.']
<ide> : ['/foo/bar', '/baz/..', 'bar/baz', '.'];
<ide>
<add> // Force optimization before starting the benchmark
<add> p.isAbsolute(tests[0]);
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.isAbsolute)');
<add> p.isAbsolute(tests[0]);
<add>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> runTests(p, tests);
<ide><path>benchmark/path/join.js
<ide> var common = require('../common.js');
<ide> var path = require('path');
<add>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> type: ['win32', 'posix'],
<ide> function main(conf) {
<ide> var n = +conf.n;
<ide> var p = path[conf.type];
<ide>
<add> // Force optimization before starting the benchmark
<add> p.join('/foo', 'bar', '', 'baz/asdf', 'quux', '..');
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.join)');
<add> p.join('/foo', 'bar', '', 'baz/asdf', 'quux', '..');
<add>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.join('/foo', 'bar', '', 'baz/asdf', 'quux', '..');
<ide><path>benchmark/path/normalize.js
<ide> var common = require('../common.js');
<ide> var path = require('path');
<add>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> type: ['win32', 'posix'],
<ide> function main(conf) {
<ide> var n = +conf.n;
<ide> var p = path[conf.type];
<ide>
<add> // Force optimization before starting the benchmark
<add> p.normalize('/foo/bar//baz/asdf/quux/..');
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.normalize)');
<add> p.normalize('/foo/bar//baz/asdf/quux/..');
<add>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.normalize('/foo/bar//baz/asdf/quux/..');
<ide><path>benchmark/path/parse.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>var v8 = require('v8');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add> var test = conf.type === 'win32'
<add> ? 'C:\\path\\dir\\index.html'
<add> : '/home/user/dir/index.html';
<add>
<add> // Force optimization before starting the benchmark
<add> p.parse(test);
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.parse)');
<add> p.parse(test);
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> p.parse(test);
<add> }
<add> bench.end(n);
<add>}
<ide><path>benchmark/path/relative.js
<ide> var common = require('../common.js');
<ide> var path = require('path');
<add>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> type: ['win32', 'posix'],
<ide> function main(conf) {
<ide> var n = +conf.n;
<ide> var runTest = conf.type === 'win32' ? runWin32Test : runPosixTest;
<ide>
<add> // Force optimization before starting the benchmark
<add> runTest();
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(path[conf.type].relative)');
<add> runTest();
<add>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> runTest();
<ide><path>benchmark/path/resolve.js
<ide> var common = require('../common.js');
<ide> var path = require('path');
<add>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> type: ['win32', 'posix'],
<ide> function main(conf) {
<ide> var n = +conf.n;
<ide> var p = path[conf.type];
<ide>
<add> // Force optimization before starting the benchmark
<add> p.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile');
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(p.resolve)');
<add> p.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile');
<add>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); | 10 |
Text | Text | improve debian installation instructions | cddb443da428c0b9c9f4f5910a36f478110db224 | <ide><path>docs/sources/installation/debian.md
<ide> To verify that everything has worked as expected:
<ide>
<ide> Which should download the `ubuntu` image, and then start `bash` in a container.
<ide>
<del>> **Note**:
<add>> **Note**:
<ide> > If you want to enable memory and swap accounting see
<ide> > [this](/installation/ubuntulinux/#memory-and-swap-accounting).
<ide>
<ide> which is officially supported by Docker.
<ide> ### Installation
<ide>
<ide> 1. Install Kernel from wheezy-backports
<del>
<add>
<ide> Add the following line to your `/etc/apt/sources.list`
<ide>
<ide> `deb http://http.debian.net/debian wheezy-backports main`
<ide>
<ide> then install the `linux-image-amd64` package (note the use of
<ide> `-t wheezy-backports`)
<del>
<add>
<ide> $ sudo apt-get update
<ide> $ sudo apt-get install -t wheezy-backports linux-image-amd64
<ide>
<del>2. Install Docker using the get.docker.com script:
<add>2. Restart your system. This is necessary for Debian to use your new kernel.
<add>
<add>3. Install Docker using the get.docker.com script:
<ide>
<ide> `curl -sSL https://get.docker.com/ | sh`
<ide>
<ide> run the `docker` client as a user in the `docker` group then you don't
<ide> need to add `sudo` to all the client commands. From Docker 0.9.0 you can
<ide> use the `-G` flag to specify an alternative group.
<ide>
<del>> **Warning**:
<add>> **Warning**:
<ide> > The `docker` group (or the group specified with the `-G` flag) is
<ide> > `root`-equivalent; see [*Docker Daemon Attack Surface*](
<ide> > /articles/security/#docker-daemon-attack-surface) details. | 1 |
PHP | PHP | fix closing tag in definition list helper | 65d4b2448ba43fdfa61769a770786c1c47a43780 | <ide><path>laravel/html.php
<ide> public static function dl($list, $attributes = array())
<ide> $html .= '<dd>'.static::entities($description).'</dd>';
<ide> }
<ide>
<del> return '<dl'.static::attributes($attributes).'>'.$html.'</'.$type.'>';
<add> return '<dl'.static::attributes($attributes).'>'.$html.'</dl>';
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | fix duplicate spaces in readme | 4a864ca951aeb180cab896d6efa983c008daf1a0 | <ide><path>packages/next/README.md
<ide>
<ide> <p align="center">
<ide> <strong>
<del> Visit <a aria-label="next.js learn" href="https://nextjs.org/learn">https://nextjs.org/learn</a> to get started with Next.js.
<add> Visit <a aria-label="next.js learn" href="https://nextjs.org/learn">https://nextjs.org/learn</a> to get started with Next.js.
<ide> </strong>
<ide> </p>
<ide> | 1 |
Text | Text | update devops docs | f87f3a6786e5948090cc82fdb220a518025145f5 | <ide><path>docs/devops.md
<ide> The dev-team merges changes from the `production-staging` branch to `production-
<ide>
<ide> We use Azure Pipelines and other CI software (Travis, GitHub Actions), to continiously test and deploy our applications.
<ide>
<add>### Triggering a build and deplyment
<add>
<add>Currently we have given access only to the developer team to push to the production branches, beacuse of the automated deplyements on live sites. The changes to the `production-*` branches can land only via fast-forward merge to the [`upstream`](https://github.com/freeCodeCamp/freeCodeCamp).
<add>
<add>You should have configured your remotes correctly:
<add>
<add>```sh
<add>freeCodeCamp on master is 📦 v0.0.1 via ⬢ v10.16.0
<add>❯ git remote -v
<add>origin git@github.com:raisedadead/freeCodeCamp.git (fetch)
<add>origin git@github.com:raisedadead/freeCodeCamp.git (push)
<add>upstream git@github.com:freeCodeCamp/freeCodeCamp.git (fetch)
<add>upstream git@github.com:freeCodeCamp/freeCodeCamp.git (push)
<add>```
<add>
<add>The below commands will move changes from `master` to the `production-*` branch:
<add>
<add>```sh
<add>git checkout master
<add>git reset --hard upstream/master
<add>git checkout production-staging
<add>git merge master
<add>git push upstream
<add>```
<add>
<add>You will not be able to force push and if you have re-written the history in anyway it will error out.
<add>
<add>Once the changes are pushed, these should trigger our CI and CD pipilines:
<add>
<add>- Build Pipeline: https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_build
<add>- Release Pipeline: https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_release
<add>
<add>The build pipeline triggers the release pipeline after a hold of 15 minutes for devs to go in and intervene if necessary. We would make these to mannual approvals in future.
<add>
<add>> Note: The release pipeline is intentionaly not deploying to production site currently, before the upcoming release. This should change when the guide goes live in a few days.
<add>
<add>Should you find any anomalies please let us know on the tracker, or send an email to `dev@freecodecamp.org`. As always all security vulnerabilities should be reported to `security@freecodecamp.org` instead of the public tracker and forum.
<add>
<ide> ### Build Status
<ide>
<ide> | Platform | Type | Status |
<ide> There will be some known limitations and tradeoffs when using this beta version
<ide> ## Reporting issues and leaving feedback
<ide>
<ide> Please open fresh issues for discussions and reporting bugs. You can label them as **[`release: next/beta`](https://github.com/freeCodeCamp/freeCodeCamp/labels/release%3A%20next%2Fbeta)** for triage.
<del>
<del>## ToDo: Add guidelines
<del>
<del>- [ ] Checking and getting access to development logs and other resources
<del>- [ ] Merging master into production-staging via fast forward
<del>- [ ] ... | 1 |
Text | Text | add information about how to learn online | d29129ba99cff0bdbdf36a08a3b7f2f6f268cd04 | <ide><path>guide/english/game-development/unreal-engine/index.md
<ide> Unreal has gone through 4 major revisions. Although some code is common between
<ide> - Adventure Pinball: Forgotten Island
<ide>
<ide>
<add>
<ide> #### More Information:
<ide>
<del><a href='https://www.unrealengine.com/' target='_blank' rel='nofollow'>www.UnrealEngine.com</a>
<del><a href='https://github.com/EpicGames' target='_blank' rel='nofollow'>www.EpicGames.com</a>
<add>- <a href='https://www.unrealengine.com/' target='_blank' rel='nofollow'>www.UnrealEngine.com</a>
<add>- <a href='https://github.com/EpicGames' target='_blank' rel='nofollow'>www.EpicGames.com</a>
<add>- <a href='https://academy.unrealengine.com/' target='_blank' rel='nofollow'>https://academy.unrealengine.com/</a> | 1 |
PHP | PHP | remove deprecated "inline" option from helpers | 5df6c153102526efe5d9f827a3cab40b46b465b9 | <ide><path>src/View/Helper/FormHelper.php
<ide> public function postButton($title, $url, $options = array()) {
<ide> * - `data` - Array with key/value to pass in input hidden
<ide> * - `method` - Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'.
<ide> * - `confirm` - Can be used instead of $confirmMessage.
<del> * - `inline` - Whether or not the associated form tag should be output inline.
<del> * Set to false to have the form tag appended to the 'postLink' view block.
<del> * Defaults to true.
<del> * - `block` - Choose a custom block to append the form tag to. Using this option
<del> * will override the inline option.
<add> * - `block` - Choose a custom block to append the form tag to.
<ide> * - Other options are the same of HtmlHelper::link() method.
<ide> * - The option `onclick` will be replaced.
<ide> *
<ide> public function postButton($title, $url, $options = array()) {
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
<ide> */
<ide> public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
<del> $options += array('inline' => true, 'block' => null);
<del> if (!$options['inline'] && empty($options['block'])) {
<del> $options['block'] = __FUNCTION__;
<del> }
<del> unset($options['inline']);
<add> $options += array('block' => null);
<ide>
<ide> $requestMethod = 'POST';
<ide> if (!empty($options['method'])) {
<ide><path>src/View/Helper/HtmlHelper.php
<ide> public function docType($type = 'html5') {
<ide> *
<ide> * `$this->Html->meta('icon', 'favicon.ico');
<ide> *
<del> * Append the meta tag to `$scripts_for_layout`:
<del> *
<del> * `$this->Html->meta('description', 'A great page', array('inline' => false));`
<del> *
<ide> * Append the meta tag to custom view block:
<ide> *
<ide> * `$this->Html->meta('description', 'A great page', array('block' => 'metaTags'));`
<ide> *
<ide> * ### Options
<ide> *
<del> * - `inline` Whether or not the link element should be output inline. Set to false to
<del> * have the meta tag included in `$scripts_for_layout`, and appended to the 'meta' view block.
<del> * - `block` Choose a custom block to append the meta tag to. Using this option
<del> * will override the inline option.
<add> * - `block` Choose a block to append the meta tag to.
<ide> *
<ide> * @param string $type The title of the external resource
<ide> * @param string|array $url The address of the external resource or string for content attribute
<ide> public function docType($type = 'html5') {
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::meta
<ide> */
<ide> public function meta($type, $url = null, $options = array()) {
<del> $options += array('inline' => true, 'block' => null);
<del> if (!$options['inline'] && empty($options['block'])) {
<del> $options['block'] = __FUNCTION__;
<del> }
<del> unset($options['inline']);
<add> $options += array('block' => null);
<ide>
<ide> if (!is_array($type)) {
<ide> $types = array(
<ide> public function link($title, $url = null, $options = array(), $confirmMessage =
<ide> *
<ide> * `echo $this->Html->css(array('one.css', 'two.css'));`
<ide> *
<del> * Add the stylesheet to the `$scripts_for_layout` layout var:
<del> *
<del> * `$this->Html->css('styles.css', array('inline' => false));`
<del> *
<ide> * Add the stylesheet to a custom block:
<ide> *
<ide> * `$this->Html->css('styles.css', array('block' => 'layoutCss'));`
<ide> *
<ide> * ### Options
<ide> *
<del> * - `inline` If set to false, the generated tag will be appended to the 'css' block,
<del> * and included in the `$scripts_for_layout` layout variable. Defaults to true.
<ide> * - `block` Set the name of the block link/style tag will be appended to.
<del> * This overrides the `inline` option.
<ide> * - `plugin` False value will prevent parsing path as a plugin
<ide> * - `rel` Defaults to 'stylesheet'. If equal to 'import' the stylesheet will be imported.
<ide> * - `fullBase` If true the URL will get a full address for the css file.
<ide> public function css($path, $options = array()) {
<ide> unset($rel);
<ide> }
<ide>
<del> $options += array('block' => null, 'inline' => true, 'rel' => 'stylesheet');
<del> if (!$options['inline'] && empty($options['block'])) {
<del> $options['block'] = __FUNCTION__;
<del> }
<del> unset($options['inline']);
<add> $options += array('block' => null, 'rel' => 'stylesheet');
<ide>
<ide> if (is_array($path)) {
<ide> $out = '';
<ide> public function css($path, $options = array()) {
<ide> *
<ide> * `echo $this->Html->script(array('one.js', 'two.js'));`
<ide> *
<del> * Add the script file to the `$scripts_for_layout` layout var:
<del> *
<del> * `$this->Html->script('styles.js', array('inline' => false));`
<del> *
<ide> * Add the script file to a custom block:
<ide> *
<ide> * `$this->Html->script('styles.js', null, array('block' => 'bodyScript'));`
<ide> *
<ide> * ### Options
<ide> *
<del> * - `inline` Whether script should be output inline or into `$scripts_for_layout`. When set to false,
<del> * the script tag will be appended to the 'script' view block as well as `$scripts_for_layout`.
<ide> * - `block` The name of the block you want the script appended to. Leave undefined to output inline.
<del> * Using this option will override the inline option.
<ide> * - `once` Whether or not the script should be checked for uniqueness. If true scripts will only be
<ide> * included once, use false to allow the same script to be included more than once per request.
<ide> * - `plugin` False value will prevent parsing path as a plugin
<ide> * - `fullBase` If true the url will get a full address for the script file.
<ide> *
<ide> * @param string|array $url String or array of javascript files to include
<del> * @param array|boolean $options Array of options, and html attributes see above. If boolean sets $options['inline'] = value
<del> * @return mixed String of `<script />` tags or null if $inline is false or if $once is true and the file has been
<del> * included before.
<add> * @param array $options Array of options, and html attributes see above.
<add> * @return mixed String of `<script />` tags or null if block is specified in options
<add> * or if $once is true and the file has been included before.
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::script
<ide> */
<ide> public function script($url, $options = array()) {
<del> if (is_bool($options)) {
<del> list($inline, $options) = array($options, array());
<del> $options['inline'] = $inline;
<del> }
<del> $options = array_merge(array('block' => null, 'inline' => true, 'once' => true), $options);
<del> if (!$options['inline'] && empty($options['block'])) {
<del> $options['block'] = __FUNCTION__;
<del> }
<del> unset($options['inline']);
<add> $options = array_merge(array('block' => null, 'once' => true), $options);
<ide>
<ide> if (is_array($url)) {
<ide> $out = '';
<ide> public function script($url, $options = array()) {
<ide> * ### Options
<ide> *
<ide> * - `safe` (boolean) Whether or not the $script should be wrapped in <![CDATA[ ]]>
<del> * - `inline` (boolean) Whether or not the $script should be added to
<del> * `$scripts_for_layout` / `script` block, or output inline. (Deprecated, use `block` instead)
<ide> * - `block` Which block you want this script block appended to.
<del> * Defaults to `script`.
<ide> *
<ide> * @param string $script The script to wrap
<ide> * @param array $options The options to use. Options not listed above will be
<ide> public function script($url, $options = array()) {
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptBlock
<ide> */
<ide> public function scriptBlock($script, $options = array()) {
<del> $options += array('safe' => true, 'inline' => true);
<add> $options += array('safe' => true, 'block' => null);
<ide> if ($options['safe']) {
<ide> $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
<ide> }
<del> if (!$options['inline'] && empty($options['block'])) {
<del> $options['block'] = 'script';
<del> }
<del> unset($options['inline'], $options['safe']);
<add> unset($options['safe']);
<ide>
<ide> $out = $this->formatTemplate('javascriptblock', [
<ide> 'attrs' => $this->_templater->formatAttributes($options, ['block']),
<ide> public function scriptBlock($script, $options = array()) {
<ide> * ### Options
<ide> *
<ide> * - `safe` Whether the code block should contain a CDATA
<del> * - `inline` Should the generated script tag be output inline or in `$scripts_for_layout`
<add> * - `block` View block the output should be appended to
<ide> *
<ide> * @param array $options Options for the code block.
<ide> * @return void
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptStart
<ide> */
<ide> public function scriptStart($options = array()) {
<del> $options += array('safe' => true, 'inline' => true);
<add> $options += array('safe' => true, 'block' => null);
<ide> $this->_scriptBlockOptions = $options;
<ide> ob_start();
<ide> return null;
<ide> }
<ide>
<ide> /**
<ide> * End a Buffered section of JavaScript capturing.
<del> * Generates a script tag inline or in `$scripts_for_layout` depending on the settings
<del> * used when the scriptBlock was started
<add> * Generates a script tag inline or appends to specified view block depending on
<add> * the settings used when the scriptBlock was started
<ide> *
<ide> * @return mixed depending on the settings of scriptStart() either a script tag or null
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptEnd
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testPostLinkAfterGetForm() {
<ide> * @return void
<ide> */
<ide> public function testPostLinkFormBuffer() {
<del> $result = $this->Form->postLink('Delete', '/posts/delete/1', array('inline' => false));
<add> $result = $this->Form->postLink('Delete', '/posts/delete/1', array('block' => 'postLink'));
<ide> $this->assertTags($result, array(
<ide> 'a' => array('href' => '#', 'onclick' => 'preg:/document\.post_\w+\.submit\(\); event\.returnValue = false; return false;/'),
<ide> 'Delete',
<ide> public function testPostLinkFormBuffer() {
<ide> ));
<ide>
<ide> $result = $this->Form->postLink('Delete', '/posts/delete/2',
<del> array('inline' => false, 'method' => 'DELETE')
<add> array('block' => 'postLink', 'method' => 'DELETE')
<ide> );
<ide> $this->assertTags($result, array(
<ide> 'a' => array('href' => '#', 'onclick' => 'preg:/document\.post_\w+\.submit\(\); event\.returnValue = false; return false;/'),
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testCssLink() {
<ide> $this->assertEquals(2, count($result));
<ide>
<ide> $this->View->expects($this->at(0))
<del> ->method('append')
<del> ->with('css', $this->matchesRegularExpression('/css_in_head.css/'));
<del>
<del> $this->View->expects($this->at(1))
<ide> ->method('append')
<ide> ->with('css', $this->matchesRegularExpression('/more_css_in_head.css/'));
<del>
<del> $result = $this->Html->css('css_in_head', array('inline' => false));
<del> $this->assertNull($result);
<del>
<del> $result = $this->Html->css('more_css_in_head', array('inline' => false));
<del> $this->assertNull($result);
<add> $this->Html->css('more_css_in_head.css', array('block' => 'css'));
<ide>
<ide> $result = $this->Html->css('screen', array('rel' => 'import'));
<ide> $expected = array(
<ide> public function testCssLinkBC() {
<ide> '/style'
<ide> );
<ide> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Html->css('css_in_head', null, array('inline' => false));
<del> $this->assertNull($result);
<del>
<del> $result = $this->Html->css('more_css_in_head', null, array('inline' => false));
<del> $this->assertNull($result);
<ide> }
<ide>
<ide> /**
<ide> public function testScriptTimestamping() {
<ide> touch(WWW_ROOT . 'js/__cake_js_test.js');
<ide> $timestamp = substr(strtotime('now'), 0, 8);
<ide>
<del> $result = $this->Html->script('__cake_js_test', array('inline' => true, 'once' => false));
<add> $result = $this->Html->script('__cake_js_test', array('once' => false));
<ide> $this->assertRegExp('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s');
<ide>
<ide> Configure::write('debug', 0);
<ide> Configure::write('Asset.timestamp', 'force');
<del> $result = $this->Html->script('__cake_js_test', array('inline' => true, 'once' => false));
<add> $result = $this->Html->script('__cake_js_test', array('once' => false));
<ide> $this->assertRegExp('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s');
<ide> unlink(WWW_ROOT . 'js/__cake_js_test.js');
<ide> Configure::write('Asset.timestamp', false);
<ide> public function testPluginScriptTimestamping() {
<ide> touch($pluginJsPath . DS . '__cake_js_test.js');
<ide> $timestamp = substr(strtotime('now'), 0, 8);
<ide>
<del> $result = $this->Html->script('TestPlugin.__cake_js_test', array('inline' => true, 'once' => false));
<add> $result = $this->Html->script('TestPlugin.__cake_js_test', array('once' => false));
<ide> $this->assertRegExp('/test_plugin\/js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s');
<ide>
<ide> Configure::write('debug', 0);
<ide> Configure::write('Asset.timestamp', 'force');
<del> $result = $this->Html->script('TestPlugin.__cake_js_test', array('inline' => true, 'once' => false));
<add> $result = $this->Html->script('TestPlugin.__cake_js_test', array('once' => false));
<ide> $this->assertRegExp('/test_plugin\/js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s');
<ide> unlink($pluginJsPath . DS . '__cake_js_test.js');
<ide> Configure::write('Asset.timestamp', false);
<ide> public function testScript() {
<ide> $result = $this->Html->script(array('foo', 'bar', 'baz'));
<ide> $this->assertNotRegExp('/foo.js/', $result);
<ide>
<del> $result = $this->Html->script('foo', array('inline' => true, 'once' => false));
<add> $result = $this->Html->script('foo', array('once' => false));
<ide> $this->assertNotNull($result);
<ide>
<ide> $result = $this->Html->script('jquery-1.3.2', array('defer' => true, 'encoding' => 'utf-8'));
<ide> public function testPluginScript() {
<ide> $result = $this->Html->script(array('TestPlugin.foo', 'TestPlugin.bar', 'TestPlugin.baz'));
<ide> $this->assertNotRegExp('/test_plugin\/js\/foo.js/', $result);
<ide>
<del> $result = $this->Html->script('TestPlugin.foo', array('inline' => true, 'once' => false));
<add> $result = $this->Html->script('TestPlugin.foo', array('once' => false));
<ide> $this->assertNotNull($result);
<ide>
<ide> $result = $this->Html->script('TestPlugin.jquery-1.3.2', array('defer' => true, 'encoding' => 'utf-8'));
<ide> public function testPluginScript() {
<ide> */
<ide> public function testScriptWithBlocks() {
<ide> $this->View->expects($this->at(0))
<del> ->method('append')
<del> ->with('script', $this->matchesRegularExpression('/script_in_head.js/'));
<del>
<del> $this->View->expects($this->at(1))
<del> ->method('append')
<del> ->with('script', $this->matchesRegularExpression('/bool_false.js/'));
<del>
<del> $this->View->expects($this->at(2))
<ide> ->method('append')
<ide> ->with('headScripts', $this->matchesRegularExpression('/second_script.js/'));
<ide>
<del> $result = $this->Html->script('script_in_head', array('inline' => false));
<del> $this->assertNull($result);
<del>
<del> $result = $this->Html->script('bool_false', false);
<del> $this->assertNull($result);
<del>
<ide> $result = $this->Html->script('second_script', array('block' => 'headScripts'));
<ide> $this->assertNull($result);
<ide> }
<ide> public function testScriptBlock() {
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $this->View->expects($this->at(0))
<del> ->method('append')
<del> ->with('script', $this->matchesRegularExpression('/window\.foo\s\=\s2;/'));
<del>
<del> $this->View->expects($this->at(1))
<ide> ->method('append')
<ide> ->with('scriptTop', $this->stringContains('alert('));
<ide>
<del> $result = $this->Html->scriptBlock('window.foo = 2;', array('inline' => false));
<del> $this->assertNull($result);
<del>
<ide> $result = $this->Html->scriptBlock('alert("hi")', array('block' => 'scriptTop'));
<ide> $this->assertNull($result);
<ide>
<ide> public function testScriptStartAndScriptEnd() {
<ide>
<ide> $this->View->expects($this->once())
<ide> ->method('append');
<del> $result = $this->Html->scriptStart(array('safe' => false, 'inline' => false));
<add>
<add> $result = $this->Html->scriptStart(array('safe' => false, 'block' => 'scripts'));
<ide> $this->assertNull($result);
<ide> echo 'this is some javascript';
<ide>
<ide> public function testMetaIcon() {
<ide> public function testMetaWithBlocks() {
<ide> $this->View->expects($this->at(0))
<ide> ->method('append')
<del> ->with('meta', $this->stringContains('ROBOTS'));
<add> ->with('metas', $this->stringContains('ROBOTS'));
<ide>
<ide> $this->View->expects($this->at(1))
<ide> ->method('append')
<ide> ->with('metaTags', $this->stringContains('favicon.ico'));
<ide>
<del> $result = $this->Html->meta(array('name' => 'ROBOTS', 'content' => 'ALL'), null, array('inline' => false));
<add> $result = $this->Html->meta(array('name' => 'ROBOTS', 'content' => 'ALL'), null, array('block' => 'metas'));
<ide> $this->assertNull($result);
<ide>
<ide> $result = $this->Html->meta('icon', 'favicon.ico', array('block' => 'metaTags')); | 4 |
Text | Text | add missing `returns` in fs & util | 9a18b0e668e136b75de4e7b92373193bbd50be08 | <ide><path>doc/api/fs.md
<ide> changes:
<ide> * `start` {integer}
<ide> * `end` {integer}
<ide> * `highWaterMark` {integer}
<add>* Returns: {stream.Readable}
<ide>
<ide> Returns a new [`ReadStream`][] object. (See [Readable Streams][]).
<ide>
<ide> changes:
<ide> * `mode` {integer}
<ide> * `autoClose` {boolean}
<ide> * `start` {integer}
<add>* Returns: {stream.Writable}
<ide>
<ide> Returns a new [`WriteStream`][] object. (See [Writable Stream][]).
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `path` {string|Buffer|URL}
<add>* Returns: {boolean}
<ide>
<ide> Synchronous version of [`fs.exists()`][].
<ide> Returns `true` if the path exists, `false` otherwise.
<ide> added: v0.1.95
<ide> -->
<ide>
<ide> * `fd` {integer}
<add>* Returns: {fs.Stats}
<ide>
<ide> Synchronous fstat(2). Returns an instance of [`fs.Stats`][].
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `path` {string|Buffer|URL}
<add>* Returns: {fs.Stats}
<ide>
<ide> Synchronous lstat(2). Returns an instance of [`fs.Stats`][].
<ide>
<ide> added: v5.10.0
<ide> * `prefix` {string}
<ide> * `options` {string|Object}
<ide> * `encoding` {string} **Default:** `'utf8'`
<add>* Returns: {string}
<ide>
<ide> The synchronous version of [`fs.mkdtemp()`][]. Returns the created
<ide> folder path.
<ide> changes:
<ide> * `path` {string|Buffer|URL}
<ide> * `flags` {string|number}
<ide> * `mode` {integer} **Default:** `0o666`
<add>* Returns: {number}
<ide>
<ide> Synchronous version of [`fs.open()`][]. Returns an integer representing the file
<ide> descriptor.
<ide> changes:
<ide> * `path` {string|Buffer|URL}
<ide> * `options` {string|Object}
<ide> * `encoding` {string} **Default:** `'utf8'`
<add>* Returns: {Array} An array of filenames
<ide>
<ide> Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
<ide> `'..'`.
<ide> changes:
<ide> * `options` {Object|string}
<ide> * `encoding` {string|null} **Default:** `null`
<ide> * `flag` {string} **Default:** `'r'`
<add>* Returns: {string|Buffer}
<ide>
<ide> Synchronous version of [`fs.readFile()`][]. Returns the contents of the `path`.
<ide>
<ide> changes:
<ide> * `path` {string|Buffer|URL}
<ide> * `options` {string|Object}
<ide> * `encoding` {string} **Default:** `'utf8'`
<add>* Returns: {string|Buffer}
<ide>
<ide> Synchronous readlink(2). Returns the symbolic link's string value.
<ide>
<ide> changes:
<ide> * `offset` {integer}
<ide> * `length` {integer}
<ide> * `position` {integer}
<add>* Returns: {number}
<ide>
<ide> Synchronous version of [`fs.read()`][]. Returns the number of `bytesRead`.
<ide>
<ide> changes:
<ide> * `path` {string|Buffer|URL}
<ide> * `options` {string|Object}
<ide> * `encoding` {string} **Default:** `'utf8'`
<add>* Returns: {string|Buffer}
<ide>
<ide> Synchronously computes the canonical pathname by resolving `.`, `..` and
<ide> symbolic links.
<ide> added: v9.2.0
<ide> * `path` {string|Buffer|URL}
<ide> * `options` {string|Object}
<ide> * `encoding` {string} **Default:** `'utf8'`
<add>* Returns: {string|Buffer}
<ide>
<ide> Synchronous realpath(3).
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `path` {string|Buffer|URL}
<add>* Returns: {fs.Stats}
<ide>
<ide> Synchronous stat(2). Returns an instance of [`fs.Stats`][].
<ide>
<ide> changes:
<ide> * `offset` {integer}
<ide> * `length` {integer}
<ide> * `position` {integer}
<add>* Returns: {number}
<ide>
<ide> ## fs.writeSync(fd, string[, position[, encoding]])
<ide> <!-- YAML
<ide> changes:
<ide> * `string` {string}
<ide> * `position` {integer}
<ide> * `encoding` {string}
<add>* Returns: {number}
<ide>
<ide> Synchronous versions of [`fs.write()`][]. Returns the number of bytes written.
<ide>
<ide><path>doc/api/util.md
<ide> contains circular references.
<ide> object formatting. Similar to `util.inspect()` without options. This will show
<ide> the full object not including non-enumerable properties and proxies.
<ide> * `%%` - single percent sign (`'%'`). This does not consume an argument.
<add>* Returns: {string} The formatted string
<ide>
<ide> If the placeholder does not have a corresponding argument, the placeholder is
<ide> not replaced.
<ide> changes:
<ide> This is useful to minimize the inspection output for large complicated
<ide> objects. To make it recurse indefinitely pass `null` or `Infinity`. Defaults
<ide> to `Infinity`.
<add>* Returns: {string} The representation of passed object
<ide>
<ide> The `util.inspect()` method returns a string representation of `object` that is
<ide> intended for debugging. The output of `util.inspect` may change at any time
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Internal alias for [`Array.isArray`][].
<ide>
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`.
<ide>
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated: Use [`Buffer.isBuffer()`][] instead.
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`.
<ide>
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`.
<ide>
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is an [`Error`][]. Otherwise, returns
<ide> `false`.
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a `Function`. Otherwise, returns
<ide> `false`.
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is strictly `null`. Otherwise, returns
<ide> `false`.
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is `null` or `undefined`. Otherwise,
<ide> returns `false`.
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`.
<ide>
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is strictly an `Object` **and** not a
<ide> `Function`. Otherwise, returns `false`.
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a primitive type. Otherwise, returns
<ide> `false`.
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`.
<ide>
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a `string`. Otherwise, returns `false`.
<ide>
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`.
<ide>
<ide> deprecated: v4.0.0
<ide> > Stability: 0 - Deprecated
<ide>
<ide> * `object` {any}
<add>* Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`.
<ide> | 2 |
Ruby | Ruby | convert datetime extensions to class reopens | dad8dabd31fb4808769272a4ba3380c1a9a30548 | <ide><path>activesupport/lib/active_support/core_ext/date_time.rb
<ide> require 'date'
<ide>
<add>require 'active_support/core_ext/date_time/acts_like'
<ide> require 'active_support/core_ext/date_time/calculations'
<add>require 'active_support/core_ext/date_time/conversions'
<ide> require 'active_support/core_ext/date_time/zones'
<del>
<del>require 'active_support/core_ext/time/behavior'
<del>class DateTime
<del> include ActiveSupport::CoreExtensions::Time::Behavior
<del>end
<del>
<del>require 'active_support/core_ext/util'
<del>ActiveSupport.core_ext DateTime, %w(conversions)
<ide><path>activesupport/lib/active_support/core_ext/date_time/conversions.rb
<del>module ActiveSupport #:nodoc:
<del> module CoreExtensions #:nodoc:
<del> module DateTime #:nodoc:
<del> # Converting datetimes to formatted strings, dates, and times.
<del> module Conversions
<del> def self.append_features(base) #:nodoc:
<del> base.class_eval do
<del> alias_method :default_inspect, :inspect
<del> alias_method :to_default_s, :to_s unless (instance_methods(false) & [:to_s, 'to_s']).empty?
<add>require 'active_support/inflector'
<ide>
<del> # Ruby 1.9 has DateTime#to_time which internally relies on Time. We define our own #to_time which allows
<del> # DateTimes outside the range of what can be created with Time.
<del> remove_method :to_time if instance_methods.include?(:to_time)
<del> end
<add>class DateTime
<add> # Ruby 1.9 has DateTime#to_time which internally relies on Time. We define our own #to_time which allows
<add> # DateTimes outside the range of what can be created with Time.
<add> remove_method :to_time if instance_methods.include?(:to_time)
<ide>
<del> super
<del>
<del> base.class_eval do
<del> alias_method :to_s, :to_formatted_s
<del> alias_method :inspect, :readable_inspect
<del> end
<del> end
<del>
<del> # Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
<del> #
<del> # This method is aliased to <tt>to_s</tt>.
<del> #
<del> # === Examples
<del> # datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
<del> #
<del> # datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
<del> # datetime.to_s(:db) # => "2007-12-04 00:00:00"
<del> # datetime.to_s(:number) # => "20071204000000"
<del> # datetime.to_formatted_s(:short) # => "04 Dec 00:00"
<del> # datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
<del> # datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
<del> # datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
<del> #
<del> # == Adding your own datetime formats to to_formatted_s
<del> # DateTime formats are shared with Time. You can add your own to the
<del> # Time::DATE_FORMATS hash. Use the format name as the hash key and
<del> # either a strftime string or Proc instance that takes a time or
<del> # datetime argument as the value.
<del> #
<del> # # config/initializers/time_formats.rb
<del> # Time::DATE_FORMATS[:month_and_year] = "%B %Y"
<del> # Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
<del> def to_formatted_s(format = :default)
<del> return to_default_s unless formatter = ::Time::DATE_FORMATS[format]
<del> formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
<del> end
<add> # Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
<add> #
<add> # This method is aliased to <tt>to_s</tt>.
<add> #
<add> # === Examples
<add> # datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
<add> #
<add> # datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
<add> # datetime.to_s(:db) # => "2007-12-04 00:00:00"
<add> # datetime.to_s(:number) # => "20071204000000"
<add> # datetime.to_formatted_s(:short) # => "04 Dec 00:00"
<add> # datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
<add> # datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
<add> # datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
<add> #
<add> # == Adding your own datetime formats to to_formatted_s
<add> # DateTime formats are shared with Time. You can add your own to the
<add> # Time::DATE_FORMATS hash. Use the format name as the hash key and
<add> # either a strftime string or Proc instance that takes a time or
<add> # datetime argument as the value.
<add> #
<add> # # config/initializers/time_formats.rb
<add> # Time::DATE_FORMATS[:month_and_year] = "%B %Y"
<add> # Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
<add> def to_formatted_s(format = :default)
<add> if formatter = ::Time::DATE_FORMATS[format]
<add> formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
<add> else
<add> to_default_s
<add> end
<add> end
<add> alias_method :to_default_s, :to_s unless (instance_methods(false) & [:to_s, 'to_s']).empty?
<add> alias_method :to_s, :to_formatted_s
<ide>
<del> # Returns the +utc_offset+ as an +HH:MM formatted string. Examples:
<del> #
<del> # datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
<del> # datetime.formatted_offset # => "-06:00"
<del> # datetime.formatted_offset(false) # => "-0600"
<del> def formatted_offset(colon = true, alternate_utc_string = nil)
<del> utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
<del> end
<del>
<del> # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000"
<del> def readable_inspect
<del> to_s(:rfc822)
<del> end
<add> # Returns the +utc_offset+ as an +HH:MM formatted string. Examples:
<add> #
<add> # datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
<add> # datetime.formatted_offset # => "-06:00"
<add> # datetime.formatted_offset(false) # => "-0600"
<add> def formatted_offset(colon = true, alternate_utc_string = nil)
<add> utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
<add> end
<add>
<add> # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000"
<add> def readable_inspect
<add> to_s(:rfc822)
<add> end
<add> alias_method :default_inspect, :inspect
<add> alias_method :inspect, :readable_inspect
<ide>
<del> # Converts self to a Ruby Date object; time portion is discarded
<del> def to_date
<del> ::Date.new(year, month, day)
<del> end
<add> # Converts self to a Ruby Date object; time portion is discarded
<add> def to_date
<add> ::Date.new(year, month, day)
<add> end
<ide>
<del> # Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class
<del> # If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time
<del> def to_time
<del> self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec) : self
<del> end
<add> # Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class
<add> # If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time
<add> def to_time
<add> self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec) : self
<add> end
<ide>
<del> # To be able to keep Times, Dates and DateTimes interchangeable on conversions
<del> def to_datetime
<del> self
<del> end
<add> # To be able to keep Times, Dates and DateTimes interchangeable on conversions
<add> def to_datetime
<add> self
<add> end
<ide>
<del> # Converts datetime to an appropriate format for use in XML
<del> def xmlschema
<del> strftime("%Y-%m-%dT%H:%M:%S%Z")
<del> end if RUBY_VERSION < '1.9'
<del>
<del> # Converts self to a floating-point number of seconds since the Unix epoch
<del> def to_f
<del> days_since_unix_epoch = self - ::DateTime.civil(1970)
<del> (days_since_unix_epoch * 86_400).to_f
<del> end
<del> end
<del> end
<add> # Converts datetime to an appropriate format for use in XML
<add> def xmlschema
<add> strftime("%Y-%m-%dT%H:%M:%S%Z")
<add> end if RUBY_VERSION < '1.9'
<add>
<add> # Converts self to a floating-point number of seconds since the Unix epoch
<add> def to_f
<add> days_since_unix_epoch = self - ::DateTime.civil(1970)
<add> (days_since_unix_epoch * 86_400).to_f
<ide> end
<ide> end | 2 |
PHP | PHP | add empty comments to empty classes | 0f4325eb7fa4b2cf5a2fd91cfb1299d64d88f09f | <ide><path>src/Illuminate/Container/BindingResolutionException.php
<ide> */
<ide> class BindingResolutionException extends Exception
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Bus/SelfHandling.php
<ide>
<ide> interface SelfHandling
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Container/BindingResolutionException.php
<ide>
<ide> class BindingResolutionException extends BaseException
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Encryption/DecryptException.php
<ide>
<ide> class DecryptException extends RuntimeException
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Encryption/EncryptException.php
<ide>
<ide> class EncryptException extends RuntimeException
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Filesystem/Cloud.php
<ide>
<ide> interface Cloud extends Filesystem
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Filesystem/FileNotFoundException.php
<ide>
<ide> class FileNotFoundException extends Exception
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Queue/ShouldBeQueued.php
<ide> */
<ide> interface ShouldBeQueued extends ShouldQueue
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Queue/ShouldQueue.php
<ide>
<ide> interface ShouldQueue
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Contracts/Validation/UnauthorizedException.php
<ide>
<ide> class UnauthorizedException extends RuntimeException
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Database/Eloquent/MassAssignmentException.php
<ide>
<ide> class MassAssignmentException extends RuntimeException
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Http/Exception/PostTooLargeException.php
<ide>
<ide> class PostTooLargeException extends Exception
<ide> {
<add> //
<ide> }
<ide><path>src/Illuminate/Session/TokenMismatchException.php
<ide>
<ide> class TokenMismatchException extends Exception
<ide> {
<add> //
<ide> } | 13 |
Text | Text | fix docs for oom-kill-disable | c92fb4d517281033a96fa05e0f1eadb899bfe2a3 | <ide><path>docs/reference/run.md
<ide> would be 2*300M, so processes can use 300M swap memory as well.
<ide> We set both memory and swap memory, so the processes in the container can use
<ide> 300M memory and 700M swap memory.
<ide>
<del>By default, Docker kills processes in a container if an out-of-memory (OOM)
<add>By default, kernel kills processes in a container if an out-of-memory (OOM)
<ide> error occurs. To change this behaviour, use the `--oom-kill-disable` option.
<ide> Only disable the OOM killer on containers where you have also set the
<ide> `-m/--memory` option. If the `-m` flag is not set, this can result in the host | 1 |
Text | Text | add the link for the tableau blog | 1e4b2dc65e9bfb96c63aea33285b34760368679b | <ide><path>guide/english/data-science-tools/tableau/index.md
<ide> If you want to learn Tableau on your own, it's possible to get a free license fo
<ide> ### Links:
<ide> * [Tableau Website](https://www.tableau.com)
<ide> * [Tableau Public Gallery](https://public.tableau.com/en-us/s/gallery)
<add> * [Tableau Blog](https://www.tableau.com/about/blog)
<ide> * [PostgreSQL Server](https://onlinehelp.tableau.com/current/pro/desktop/en-us/examples_postgresql.html)
<ide> * [Using R and Tableau](https://www.tableau.com/learn/whitepapers/using-r-and-tableau)
<ide> * [Tableau Integration with Python](https://community.tableau.com/thread/236479) | 1 |
Ruby | Ruby | collapse iteration to a map | 977ae5f27d6d754a2417821ad53248f06add770b | <ide><path>Library/Homebrew/options.rb
<ide> class Options
<ide> include Enumerable
<ide>
<ide> def self.create(array)
<del> options = new
<del> array.each do |e|
<del> case e
<del> when /^--(.+)$/
<del> options << Option.new($1)
<del> else
<del> options << Option.new(e)
<del> end
<del> end
<del> options
<add> new array.map { |e| Option.new(e[/^--(.+)$/, 1] || e) }
<ide> end
<ide>
<ide> def initialize(*args) | 1 |
Javascript | Javascript | revert temporary change | d1360a427ebe12783020cca5985537a8f27967f9 | <ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) {
<ide> const options = Object.assign({}, optionsOrPreset);
<ide> if (options.preset !== undefined) {
<del> this.hooks.statsPreset
<del> .for(String(options.preset))
<del> .call(options, context);
<add> this.hooks.statsPreset.for(options.preset).call(options, context);
<ide> }
<ide> this.hooks.statsNormalize.call(options, context);
<ide> return options; | 1 |
Java | Java | add sonar support to oculus twilight android | a48b4d5df16b20a6273e97366e97a74dd978a8b2 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientProvider.java
<ide> public static OkHttpClient createClient() {
<ide> if (sFactory != null) {
<ide> return sFactory.createNewNetworkModuleClient();
<ide> }
<add> return createClientBuilder().build();
<add> }
<ide>
<add> public static OkHttpClient.Builder createClientBuilder() {
<ide> // No timeouts by default
<ide> OkHttpClient.Builder client = new OkHttpClient.Builder()
<ide> .connectTimeout(0, TimeUnit.MILLISECONDS)
<ide> .readTimeout(0, TimeUnit.MILLISECONDS)
<ide> .writeTimeout(0, TimeUnit.MILLISECONDS)
<ide> .cookieJar(new ReactCookieJarContainer());
<ide>
<del> return enableTls12OnPreLollipop(client).build();
<add> return enableTls12OnPreLollipop(client);
<ide> }
<ide>
<ide> /* | 1 |
PHP | PHP | change attributes from protected to public | 6eae4c982b11e37e38120bbf2d33f1fe4b2cf2de | <ide><path>laravel/paginator.php
<ide> class Paginator {
<ide> *
<ide> * @var int
<ide> */
<del> protected $page;
<add> public $page;
<ide>
<ide> /**
<ide> * The last page available for the result set.
<ide> *
<ide> * @var int
<ide> */
<del> protected $last;
<add> public $last;
<ide>
<ide> /**
<ide> * The total number of results.
<ide> *
<ide> * @var int
<ide> */
<del> protected $total;
<add> public $total;
<ide>
<ide> /**
<ide> * The number of items per page.
<ide> *
<ide> * @var int
<ide> */
<del> protected $per_page;
<add> public $per_page;
<ide>
<ide> /**
<ide> * The values that should be appended to the end of the link query strings. | 1 |
Ruby | Ruby | fix tests and improve style | 5e5c78ebef173099754d2facb0c3b0691dee9334 | <ide><path>Library/Homebrew/extend/on_system.rb
<ide> def setup_base_os_methods(base)
<ide> base.define_method(:on_system) do |linux, macos:, &block|
<ide> @on_system_blocks_exist = true
<ide>
<del> raise ArgumentError, "The first argument to `on_system` must be `:linux`" unless linux == :linux
<add> raise ArgumentError, "The first argument to `on_system` must be `:linux`" if linux != :linux
<ide>
<ide> os_version, or_condition = if macos.to_s.include?("_or_")
<ide> macos.to_s.split(/_(?=or_)/).map(&:to_sym)
<ide><path>Library/Homebrew/test/formula_spec.rb
<ide> def install
<ide> end.new
<ide> end
<ide>
<del> it "doesn't call code on Ventura" do
<add> it "doesn't call code on Ventura", :needs_macos do
<ide> Homebrew::SimulateSystem.os = :ventura
<ide> f.brew { f.install }
<ide> expect(f.foo).to eq(0)
<ide> expect(f.bar).to eq(0)
<ide> end
<ide>
<del> it "calls code on Linux" do
<add> it "calls code on Linux", :needs_linux do
<ide> Homebrew::SimulateSystem.os = :linux
<ide> f.brew { f.install }
<ide> expect(f.foo).to eq(1)
<ide> expect(f.bar).to eq(1)
<ide> end
<ide>
<del> it "calls code within `on_system :linux, macos: :monterey` on Monterey" do
<add> it "calls code within `on_system :linux, macos: :monterey` on Monterey", :needs_macos do
<ide> Homebrew::SimulateSystem.os = :monterey
<ide> f.brew { f.install }
<ide> expect(f.foo).to eq(1)
<ide> expect(f.bar).to eq(0)
<ide> end
<ide>
<del> it "calls code within `on_system :linux, macos: :big_sur_or_older` on Big Sur" do
<add> it "calls code within `on_system :linux, macos: :big_sur_or_older` on Big Sur", :needs_macos do
<ide> Homebrew::SimulateSystem.os = :big_sur
<ide> f.brew { f.install }
<ide> expect(f.foo).to eq(0)
<ide> expect(f.bar).to eq(1)
<ide> end
<ide>
<del> it "calls code within `on_system :linux, macos: :big_sur_or_older` on Catalina" do
<add> it "calls code within `on_system :linux, macos: :big_sur_or_older` on Catalina", :needs_macos do
<ide> Homebrew::SimulateSystem.os = :catalina
<ide> f.brew { f.install }
<ide> expect(f.foo).to eq(0) | 2 |
Text | Text | add @jasonrudolph focus | db1879a8fb03e3ea721e76f803ff83a46503ab5f | <ide><path>docs/focus/2018-05-07.md
<ide>
<ide> - Atom Core
<ide> - Finish Atom CI experimentation
<add> - Fix failing tests on Electron 2.0 upgrade branch, and start using builds from that branch in our day-to-day workflows for ad-hoc regression detection ([#17273](https://github.com/atom/atom/pull/17273))
<ide> - Experiment with new [Electron auto-update service](https://electronjs.org/blog/autoupdating-electron-apps)
<ide> - Publish Atom Q2 plan
<ide> - GitHub Package | 1 |
Python | Python | add one more test from ticket #728 | 3811cb8173bfd05396b231696ccbab210a43129c | <ide><path>numpy/lib/tests/test_index_tricks.py
<ide> def check_mixed_type(self):
<ide> g = r_[10.1, 1:10]
<ide> assert(g.dtype == 'f8')
<ide>
<add> def check_more_mixed_type(self):
<add> g = r_[-10.1, array([1]), array([2,3,4]), 10.0]
<add> assert(g.dtype == 'f8')
<add>
<ide> def check_2d(self):
<ide> b = rand(5,5)
<ide> c = rand(5,5) | 1 |
Go | Go | add ps args to docker top | cfec1c3e1b88ceeca73144198df7a210ed3dc421 | <ide><path>api.go
<ide> func getContainersTop(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<add> if err := parseForm(r); err != nil {
<add> return err
<add> }
<ide> name := vars["name"]
<del> procsStr, err := srv.ContainerTop(name)
<add> ps_args := r.Form.Get("ps_args")
<add> procsStr, err := srv.ContainerTop(name, ps_args)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>api_params.go
<ide> type APIInfo struct {
<ide> }
<ide>
<ide> type APITop struct {
<del> PID string
<del> Tty string
<del> Time string
<del> Cmd string
<add> Titles []string
<add> Processes [][]string
<ide> }
<ide>
<ide> type APIRmi struct {
<ide><path>api_test.go
<ide> func TestGetContainersTop(t *testing.T) {
<ide> }
<ide>
<ide> r := httptest.NewRecorder()
<del> if err := getContainersTop(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
<add> req, err := http.NewRequest("GET", "/"+container.ID+"/top?ps_args=u", bytes.NewReader([]byte{}))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := getContainersTop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
<ide> t.Fatal(err)
<ide> }
<del> procs := []APITop{}
<add> procs := APITop{}
<ide> if err := json.Unmarshal(r.Body.Bytes(), &procs); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if len(procs) != 2 {
<del> t.Fatalf("Expected 2 processes, found %d.", len(procs))
<add> if len(procs.Titles) != 11 {
<add> t.Fatalf("Expected 11 titles, found %d.", len(procs.Titles))
<ide> }
<del>
<del> if procs[0].Cmd != "sh" && procs[0].Cmd != "busybox" {
<del> t.Fatalf("Expected `busybox` or `sh`, found %s.", procs[0].Cmd)
<add> if procs.Titles[0] != "USER" || procs.Titles[10] != "COMMAND" {
<add> t.Fatalf("Expected Titles[0] to be USER and Titles[10] to be COMMAND, found %s and %s.", procs.Titles[0], procs.Titles[10])
<ide> }
<ide>
<del> if procs[1].Cmd != "sh" && procs[1].Cmd != "busybox" {
<del> t.Fatalf("Expected `busybox` or `sh`, found %s.", procs[1].Cmd)
<add> if len(procs.Processes) != 2 {
<add> t.Fatalf("Expected 2 processes, found %d.", len(procs.Processes))
<add> }
<add> if procs.Processes[0][10] != "/bin/sh" && procs.Processes[0][10] != "sleep" {
<add> t.Fatalf("Expected `sleep` or `/bin/sh`, found %s.", procs.Processes[0][10])
<add> }
<add> if procs.Processes[1][10] != "/bin/sh" && procs.Processes[1][10] != "sleep" {
<add> t.Fatalf("Expected `sleep` or `/bin/sh`, found %s.", procs.Processes[1][10])
<ide> }
<ide> }
<ide>
<ide><path>commands.go
<ide> func (cli *DockerCli) CmdTop(args ...string) error {
<ide> if err := cmd.Parse(args); err != nil {
<ide> return nil
<ide> }
<del> if cmd.NArg() != 1 {
<add> if cmd.NArg() == 0 {
<ide> cmd.Usage()
<ide> return nil
<ide> }
<del> body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top", nil)
<add> val := url.Values{}
<add> if cmd.NArg() > 1 {
<add> val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
<add> }
<add>
<add> body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)
<ide> if err != nil {
<ide> return err
<ide> }
<del> var procs []APITop
<add> procs := APITop{}
<ide> err = json.Unmarshal(body, &procs)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
<del> fmt.Fprintln(w, "PID\tTTY\tTIME\tCMD")
<del> for _, proc := range procs {
<del> fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", proc.PID, proc.Tty, proc.Time, proc.Cmd)
<add> fmt.Fprintln(w, strings.Join(procs.Titles, "\t"))
<add> for _, proc := range procs.Processes {
<add> fmt.Fprintln(w, strings.Join(proc, "\t"))
<ide> }
<ide> w.Flush()
<ide> return nil
<ide><path>server.go
<ide> func (srv *Server) ImageHistory(name string) ([]APIHistory, error) {
<ide>
<ide> }
<ide>
<del>func (srv *Server) ContainerTop(name string) ([]APITop, error) {
<add>func (srv *Server) ContainerTop(name, ps_args string) (*APITop, error) {
<ide> if container := srv.runtime.Get(name); container != nil {
<del> output, err := exec.Command("lxc-ps", "--name", container.ID).CombinedOutput()
<add> output, err := exec.Command("lxc-ps", "--name", container.ID, "--", ps_args).CombinedOutput()
<ide> if err != nil {
<ide> return nil, fmt.Errorf("Error trying to use lxc-ps: %s (%s)", err, output)
<ide> }
<del> var procs []APITop
<add> procs := APITop{}
<ide> for i, line := range strings.Split(string(output), "\n") {
<del> if i == 0 || len(line) == 0 {
<add> if len(line) == 0 {
<ide> continue
<ide> }
<del> proc := APITop{}
<add> words := []string{}
<ide> scanner := bufio.NewScanner(strings.NewReader(line))
<ide> scanner.Split(bufio.ScanWords)
<ide> if !scanner.Scan() {
<ide> return nil, fmt.Errorf("Error trying to use lxc-ps")
<ide> }
<ide> // no scanner.Text because we skip container id
<del> scanner.Scan()
<del> proc.PID = scanner.Text()
<del> scanner.Scan()
<del> proc.Tty = scanner.Text()
<del> scanner.Scan()
<del> proc.Time = scanner.Text()
<del> scanner.Scan()
<del> proc.Cmd = scanner.Text()
<del> procs = append(procs, proc)
<del> }
<del> return procs, nil
<add> for scanner.Scan() {
<add> words = append(words, scanner.Text())
<add> }
<add> if i == 0 {
<add> procs.Titles = words
<add> } else {
<add> procs.Processes = append(procs.Processes, words)
<add> }
<add> }
<add> return &procs, nil
<ide>
<ide> }
<ide> return nil, fmt.Errorf("No such container: %s", name) | 5 |
Python | Python | prepare 1.0.3 release | 8c2a573ebfef0fce5061c611bacbcae4dd5adc73 | <ide><path>keras/__init__.py
<ide> from __future__ import absolute_import
<del>__version__ = '1.0.2'
<ide> from . import backend
<ide> from . import datasets
<ide> from . import engine
<ide> from . import objectives
<ide> from . import optimizers
<ide> from . import regularizers
<add>
<add>__version__ = '1.0.3'
<ide><path>setup.py
<ide>
<ide>
<ide> setup(name='Keras',
<del> version='1.0.2',
<add> version='1.0.3',
<ide> description='Deep Learning for Python',
<ide> author='Francois Chollet',
<ide> author_email='francois.chollet@gmail.com',
<ide> url='https://github.com/fchollet/keras',
<del> download_url='https://github.com/fchollet/keras/tarball/1.0.2',
<add> download_url='https://github.com/fchollet/keras/tarball/1.0.3',
<ide> license='MIT',
<ide> install_requires=['theano', 'pyyaml', 'six'],
<ide> extras_require={ | 2 |
Ruby | Ruby | update virtualenv to 15.2.0 | 7eaaaf6fa294e617969825e973d72e6a3711d403 | <ide><path>Library/Homebrew/language/python_virtualenv_constants.rb
<del>PYTHON_VIRTUALENV_URL = "https://files.pythonhosted.org/packages/d4/0c/9840c08189e030873387a73b90ada981885010dd9aea134d6de30cd24cb8/virtualenv-15.1.0.tar.gz".freeze
<del>PYTHON_VIRTUALENV_SHA256 = "02f8102c2436bb03b3ee6dede1919d1dac8a427541652e5ec95171ec8adbc93a".freeze
<add>PYTHON_VIRTUALENV_URL = "https://files.pythonhosted.org/packages/b1/72/2d70c5a1de409ceb3a27ff2ec007ecdd5cc52239e7c74990e32af57affe9/virtualenv-15.2.0.tar.gz".freeze
<add>PYTHON_VIRTUALENV_SHA256 = "1d7e241b431e7afce47e77f8843a276f652699d1fa4f93b9d8ce0076fd7b0b54".freeze | 1 |
Python | Python | add snowflake support to sql operator and sensor | 9c68e7cc6fc1bf7c5a9a0156a2f0cf166cf2dfbe | <ide><path>airflow/models/connection.py
<ide> "jira": ("airflow.providers.jira.hooks.jira.JiraHook", "jira_conn_id"),
<ide> "kubernetes": ("airflow.providers.cncf.kubernetes.hooks.kubernetes.KubernetesHook", "kubernetes_conn_id"),
<ide> "mongo": ("airflow.providers.mongo.hooks.mongo.MongoHook", "conn_id"),
<del> "mssql": ("airflow.providers.microsoft.mssql.hooks.mssql.MsSqlHook", "mssql_conn_id"),
<add> "mssql": ("airflow.providers.odbc.hooks.odbc.OdbcHook", "odbc_conn_id"),
<ide> "mysql": ("airflow.providers.mysql.hooks.mysql.MySqlHook", "mysql_conn_id"),
<ide> "odbc": ("airflow.providers.odbc.hooks.odbc.OdbcHook", "odbc_conn_id"),
<ide> "oracle": ("airflow.providers.oracle.hooks.oracle.OracleHook", "oracle_conn_id"),
<ide> "pig_cli": ("airflow.providers.apache.pig.hooks.pig.PigCliHook", "pig_cli_conn_id"),
<ide> "postgres": ("airflow.providers.postgres.hooks.postgres.PostgresHook", "postgres_conn_id"),
<ide> "presto": ("airflow.providers.presto.hooks.presto.PrestoHook", "presto_conn_id"),
<ide> "redis": ("airflow.providers.redis.hooks.redis.RedisHook", "redis_conn_id"),
<add> "snowflake": ("airflow.providers.snowflake.hooks.snowflake.SnowflakeHook", "snowflake_conn_id"),
<ide> "sqlite": ("airflow.providers.sqlite.hooks.sqlite.SqliteHook", "sqlite_conn_id"),
<ide> "tableau": ("airflow.providers.salesforce.hooks.tableau.TableauHook", "tableau_conn_id"),
<ide> "vertica": ("airflow.providers.vertica.hooks.vertica.VerticaHook", "vertica_conn_id"),
<ide><path>airflow/operators/sql.py
<ide> "oracle",
<ide> "postgres",
<ide> "presto",
<add> "snowflake",
<ide> "sqlite",
<ide> "vertica",
<ide> }
<ide><path>airflow/sensors/sql_sensor.py
<ide> def _get_hook(self):
<ide>
<ide> allowed_conn_type = {'google_cloud_platform', 'jdbc', 'mssql',
<ide> 'mysql', 'odbc', 'oracle', 'postgres',
<del> 'presto', 'sqlite', 'vertica'}
<add> 'presto', 'snowflake', 'sqlite', 'vertica'}
<ide> if conn.conn_type not in allowed_conn_type:
<ide> raise AirflowException("The connection type is not supported by SqlSensor. " +
<ide> "Supported connection types: {}".format(list(allowed_conn_type)))
<ide><path>tests/models/test_connection.py
<ide> from airflow.models import Connection, crypto
<ide> from airflow.models.connection import CONN_TYPE_TO_HOOK
<ide> from airflow.providers.sqlite.hooks.sqlite import SqliteHook
<add>from airflow.utils.module_loading import import_string
<ide> from tests.test_utils.config import conf_vars
<ide>
<ide> ConnectionParts = namedtuple("ConnectionParts", ["conn_type", "login", "password", "host", "port", "schema"])
<ide> def test_enforce_alphabetical_order(self):
<ide> expected_keys = sorted(current_keys)
<ide>
<ide> self.assertEqual(expected_keys, current_keys)
<add>
<add> def test_hooks_importable(self):
<add> for hook_path, _ in CONN_TYPE_TO_HOOK.values():
<add> self.assertTrue(issubclass(import_string(hook_path), BaseHook)) | 4 |
Go | Go | add check on docker run | 0abdea90947de867719c622a51f0382bcdf592ee | <ide><path>runconfig/parse.go
<ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf
<ide>
<ide> flPublish opts.ListOpts
<ide> flExpose opts.ListOpts
<del> flDns opts.ListOpts
<add> flDns = opts.NewListOpts(opts.ValidateIpAddress)
<ide> flDnsSearch = opts.NewListOpts(opts.ValidateDnsSearch)
<ide> flVolumesFrom opts.ListOpts
<ide> flLxcOpts opts.ListOpts | 1 |
Mixed | Python | update stop_words.py and add name in contributors | 6a06a3fa6a3af267710e05ef697d70d6b41f7be3 | <ide><path>.github/contributors/jaydeepborkar.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI GmbH](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [ ] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Jaydeep Borkar |
<add>| Company name (if applicable) | Pune University, India |
<add>| Title or role (if applicable) | CS Undergrad |
<add>| Date | 9/26/2019 |
<add>| GitHub username | jaydeepborkar |
<add>| Website (optional) | http://jaydeepborkar.github.io |
<ide><path>spacy/lang/hi/stop_words.py
<ide> from __future__ import unicode_literals
<ide>
<ide>
<del># Source: https://github.com/taranjeet/hindi-tokenizer/blob/master/stopwords.txt
<add># Source: https://github.com/taranjeet/hindi-tokenizer/blob/master/stopwords.txt, https://data.mendeley.com/datasets/bsr3frvvjc/1#file-a21d5092-99d7-45d8-b044-3ae9edd391c6
<add>
<ide> STOP_WORDS = set(
<ide> """
<ide> अंदर
<ide> अंदर
<ide> आदि
<ide> आप
<add>अगर
<ide> इंहिं
<ide> इंहें
<ide> इंहों
<ide> मानो
<ide> मे
<ide> में
<add>मैं
<add>मुझको
<add>मेरा
<ide> यदि
<ide> यह
<ide> यहाँ
<ide> है
<ide> हैं
<ide> हो
<add>हूँ
<ide> होता
<ide> होति
<ide> होती | 2 |
Text | Text | fix edge guides for active record callbacks | 3820abd36d22ac133b4146c8d59c1dda847e4f91 | <ide><path>guides/source/active_record_callbacks.md
<ide> Halting Execution
<ide>
<ide> As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
<ide>
<del>The whole callback chain is wrapped in a transaction. If any _before_ callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; _after_ callbacks can only accomplish that by raising an exception.
<add>The whole callback chain is wrapped in a transaction. If any callback raises an exception, the execution chain gets halted and a ROLLBACK is issued. To intentionally stop a chain use:
<add>
<add>```ruby
<add>throw :abort
<add>```
<ide>
<ide> WARNING. Any exception that is not `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` will be re-raised by Rails after the callback chain is halted. Raising an exception other than `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` may break code that does not expect methods like `save` and `update_attributes` (which normally try to return `true` or `false`) to raise an exception.
<ide> | 1 |
Go | Go | use write lock in handlenodeevent | bc465326fe8eb5df6e87c7129c55a56dc017ced5 | <ide><path>libnetwork/networkdb/delegate.go
<ide> func (nDB *NetworkDB) handleNodeEvent(nEvent *NodeEvent) bool {
<ide> // time.
<ide> nDB.networkClock.Witness(nEvent.LTime)
<ide>
<del> nDB.RLock()
<del> defer nDB.RUnlock()
<add> nDB.Lock()
<add> defer nDB.Unlock()
<ide>
<ide> // check if the node exists
<ide> n, _, _ := nDB.findNode(nEvent.NodeName) | 1 |
Text | Text | add attribute article | 0d5389a37090b39e3ef22f250674efe6dd67e3af | <ide><path>guide/english/csharp/attributes/index.md
<add>---
<add>title: Attributes
<add>---
<add>
<add># Attributes
<add>Attributes allow the programmer to add metadata to assemblies, types, and members. When applied to a type or member, an attribute will take the form of `[Attribute]` or `[Attribute(args)]`. When applied to an assembly, an attribute will take the form of `[assembly:Attribute]` or `[assembly:Attribute(args)]`.
<add>
<add>An attribute is any class that inherits from the parent `Attribute` type. Conventionally, the name of an attribute in its definition will be `SomethingAttribute`, rather than just `Something`. When used, `[Something]` will still compile:
<add>```csharp
<add>public class PluginAttribute : Attribute
<add>{
<add> // Attribute members
<add>}
<add>
<add>[Plugin]
<add>public class MyPlugin
<add>{
<add> // Plugin members
<add>}
<add>```
<add>
<add>As mentioned above, attributes can have constructors like any other class. However, all arguments in an attribute constructor must be compile-time constants.
<add>```csharp
<add>public static class Variables // For the purposes of demonstration
<add>{
<add> public static string MyPluginName = "Cool Plugin";
<add> public const string MyConstPluginName = "Amazing Plugin";
<add>}
<add>
<add>public class PluginAttribute : Attribute
<add>{
<add> public string Name { get; private set; }
<add>
<add> public PluginAttribute(string name)
<add> {
<add> Name = name;
<add> }
<add>}
<add>
<add>[Plugin(MyPluginName)] // Won't compile because MyPluginName isn't const
<add>[Plugin(MyConstPluginName)] // OK
<add>[Plugin("My Cool Plugin")] // OK
<add>public class MyPlugin
<add>{
<add> // Plugin members
<add>}
<add>```
<add>
<add>## Accessing a Type's Attributes
<add>The `System.Attribute.GetCustomAttributes(Type)` method returns an array of all the attributes applied to a type. The programmer can then loop through this array to find the desired attribute using the `is` keyword.
<add>```csharp
<add>public void PrintPluginName()
<add>{
<add> var type = typeof(MyPlugin); // Returns a Type object representing our MyPlugin class
<add> var attributes = System.Attribute.GetCustomAttributes(type); // Returns an Attribute[]
<add>
<add> foreach (var a in attributes)
<add> {
<add> if (a is PluginAttribute plugin)
<add> Console.WriteLine($"Plugin Name: {plugin.Name}");
<add> }
<add>}
<add>```
<add>
<add>#### Additional Information
<add>* [Attributes - Microsoft Programming Guide](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/)
<add>* [Accessing Attributes Using Reflection - Microsoft Programming Guide](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection)
<add>* [Creating Custom Attributes - Microsoft Programming Guide](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/creating-custom-attributes) | 1 |
Javascript | Javascript | remove ie8 code | 0c5a455ecb33041f973e9770e8d8dc5fccfcf484 | <ide><path>src/renderers/dom/shared/syntheticEvents/SyntheticUIEvent.js
<ide>
<ide> var SyntheticEvent = require('SyntheticEvent');
<ide>
<del>var getEventTarget = require('getEventTarget');
<del>
<ide> /**
<ide> * @interface UIEvent
<ide> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<ide> */
<ide> var UIEventInterface = {
<del> view: function(event) {
<del> if (event.view) {
<del> return event.view;
<del> }
<del>
<del> var target = getEventTarget(event);
<del> if (target.window === target) {
<del> // target is a window object
<del> return target;
<del> }
<del>
<del> var doc = target.ownerDocument;
<del> // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
<del> if (doc) {
<del> return doc.defaultView || doc.parentWindow;
<del> } else {
<del> return window;
<del> }
<del> },
<del> detail: function(event) {
<del> return event.detail || 0;
<del> },
<add> view: null,
<add> detail: null,
<ide> };
<ide>
<ide> /** | 1 |
PHP | PHP | test the extend system | 647cca5a44ad2bd56be1969a096dbd94b18dc3c6 | <ide><path>tests/Redis/RedisManagerExtensionTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Redis;
<add>
<add>use Illuminate\Contracts\Redis\Connector;
<add>use Illuminate\Foundation\Application;
<add>use Illuminate\Redis\RedisManager;
<add>use PHPUnit\Framework\TestCase;
<add>
<add>class RedisManagerExtensionTest extends TestCase
<add>{
<add> /**
<add> * Redis manager instance.
<add> *
<add> * @var RedisManager
<add> */
<add> protected $redis;
<add>
<add> protected function setUp(): void
<add> {
<add> parent::setUp();
<add>
<add> $this->redis = new RedisManager(new Application(), 'my_custom_driver', [
<add> 'default' => [
<add> 'host' => 'some-host',
<add> 'port' => 'some-port',
<add> 'database' => 5,
<add> 'timeout' => 0.5,
<add> ],
<add> 'clusters' => [
<add> 'my-cluster' => [
<add> [
<add> 'host' => 'some-host',
<add> 'port' => 'some-port',
<add> 'database' => 5,
<add> 'timeout' => 0.5,
<add> ]
<add> ]
<add> ]
<add> ]);
<add>
<add> $this->redis->extend('my_custom_driver', function () {
<add> return new FakeRedisConnnector();
<add> });
<add> }
<add>
<add> public function test_using_custom_redis_connector_with_single_redis_instance()
<add> {
<add> $this->assertEquals(
<add> 'my-redis-connection', $this->redis->resolve()
<add> );
<add> }
<add>
<add> public function test_using_custom_redis_connector_with_redis_cluster_instance()
<add> {
<add> $this->assertEquals(
<add> 'my-redis-cluster-connection', $this->redis->resolve('my-cluster')
<add> );
<add> }
<add>}
<add>
<add>class FakeRedisConnnector implements Connector
<add>{
<add> /**
<add> * Create a new clustered Predis connection.
<add> *
<add> * @param array $config
<add> * @param array $options
<add> * @return \Illuminate\Contracts\Redis\Connection
<add> */
<add> public function connect(array $config, array $options)
<add> {
<add> return 'my-redis-connection';
<add> }
<add>
<add> /**
<add> * Create a new clustered Predis connection.
<add> *
<add> * @param array $config
<add> * @param array $clusterOptions
<add> * @param array $options
<add> * @return \Illuminate\Contracts\Redis\Connection
<add> */
<add> public function connectToCluster(array $config, array $clusterOptions, array $options)
<add> {
<add> return 'my-redis-cluster-connection';
<add> }
<add>} | 1 |
Javascript | Javascript | adjust validation to account for buffer.kmaxlength | 3c564632fafd0400fb6123cc398d736b6dbec7e6 | <ide><path>lib/buffer.js
<ide> const {
<ide> } = require('internal/errors');
<ide> const {
<ide> validateBuffer,
<del> validateInt32,
<add> validateInteger,
<ide> validateString
<ide> } = require('internal/validators');
<add>// Provide validateInteger() but with kMaxLength as the default maximum value.
<add>const validateOffset = (value, name, min = 0, max = kMaxLength) =>
<add> validateInteger(value, name, min, max);
<ide>
<ide> const {
<ide> FastBuffer,
<ide> Buffer.concat = function concat(list, length) {
<ide> }
<ide> }
<ide> } else {
<del> validateInt32(length, 'length', 0);
<add> validateOffset(length, 'length');
<ide> }
<ide>
<ide> const buffer = Buffer.allocUnsafe(length);
<ide> Buffer.prototype.compare = function compare(target,
<ide> if (targetStart === undefined)
<ide> targetStart = 0;
<ide> else
<del> validateInt32(targetStart, 'targetStart', 0);
<add> validateOffset(targetStart, 'targetStart');
<ide>
<ide> if (targetEnd === undefined)
<ide> targetEnd = target.length;
<ide> else
<del> validateInt32(targetEnd, 'targetEnd', 0, target.length);
<add> validateOffset(targetEnd, 'targetEnd', 0, target.length);
<ide>
<ide> if (sourceStart === undefined)
<ide> sourceStart = 0;
<ide> else
<del> validateInt32(sourceStart, 'sourceStart', 0);
<add> validateOffset(sourceStart, 'sourceStart');
<ide>
<ide> if (sourceEnd === undefined)
<ide> sourceEnd = this.length;
<ide> else
<del> validateInt32(sourceEnd, 'sourceEnd', 0, this.length);
<add> validateOffset(sourceEnd, 'sourceEnd', 0, this.length);
<ide>
<ide> if (sourceStart >= sourceEnd)
<ide> return (targetStart >= targetEnd ? 0 : -1);
<ide> function _fill(buf, value, offset, end, encoding) {
<ide> offset = 0;
<ide> end = buf.length;
<ide> } else {
<del> validateInt32(offset, 'offset', 0);
<add> validateOffset(offset, 'offset');
<ide> // Invalid ranges are not set to a default, so can range check early.
<ide> if (end === undefined) {
<ide> end = buf.length;
<ide> } else {
<del> validateInt32(end, 'end', 0, buf.length);
<add> validateOffset(end, 'end', 0, buf.length);
<ide> }
<ide> if (offset >= end)
<ide> return buf;
<ide> Buffer.prototype.write = function write(string, offset, length, encoding) {
<ide>
<ide> // Buffer#write(string, offset[, length][, encoding])
<ide> } else {
<del> validateInt32(offset, 'offset', 0, this.length);
<add> validateOffset(offset, 'offset', 0, this.length);
<ide>
<ide> const remaining = this.length - offset;
<ide>
<ide> Buffer.prototype.write = function write(string, offset, length, encoding) {
<ide> encoding = length;
<ide> length = remaining;
<ide> } else {
<del> validateInt32(length, 'length', 0, this.length);
<add> validateOffset(length, 'length', 0, this.length);
<ide> if (length > remaining)
<ide> length = remaining;
<ide> } | 1 |
Java | Java | add flatmap alias to mapmany | 1d5b004d39b91d5d18980d2747a34665f11d0ee9 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> import rx.operators.OperationConcat;
<ide> import rx.operators.OperationDefer;
<ide> import rx.operators.OperationDematerialize;
<del>import rx.operators.OperationGroupBy;
<ide> import rx.operators.OperationFilter;
<ide> import rx.operators.OperationFinally;
<add>import rx.operators.OperationGroupBy;
<ide> import rx.operators.OperationMap;
<ide> import rx.operators.OperationMaterialize;
<ide> import rx.operators.OperationMerge;
<ide> public void call(Object args) {
<ide>
<ide> /**
<ide> * Returns a connectable observable sequence that upon connection causes the source sequence to push results into the specified subject.
<del> *
<del> * @param subject the subject to push source elements into.
<del> * @param <R> result type
<add> *
<add> * @param subject
<add> * the subject to push source elements into.
<add> * @param <R>
<add> * result type
<ide> * @return a connectable observable sequence that upon connection causes the source sequence to push results into the specified subject.
<ide> */
<ide> public <R> ConnectableObservable<R> multicast(Subject<T, R> subject) {
<ide> public R call(T t1) {
<ide> * and then merges the results of that function applied to every item emitted by the original
<ide> * Observable, emitting these merged results as its own sequence.
<ide> * <p>
<add> * Note: mapMany and flatMap are equivalent.
<add> * <p>
<ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mapMany.png">
<ide> *
<ide> * @param sequence
<ide> public R call(T t1) {
<ide> * @return an Observable that emits a sequence that is the result of applying the transformation
<ide> * function to each item emitted by the source Observable and merging the results of
<ide> * the Observables obtained from this transformation
<add> * @see {@link #flatMap(Observable, Func1)}
<ide> */
<ide> public static <T, R> Observable<R> mapMany(Observable<T> sequence, Func1<T, Observable<R>> func) {
<ide> return create(OperationMap.mapMany(sequence, func));
<ide> public static <T> Observable<T> finallyDo(Observable<T> source, Action0 action)
<ide> return create(OperationFinally.finallyDo(source, action));
<ide> }
<ide>
<add> /**
<add> * Creates a new Observable sequence by applying a function that you supply to each object in the
<add> * original Observable sequence, where that function is itself an Observable that emits objects,
<add> * and then merges the results of that function applied to every item emitted by the original
<add> * Observable, emitting these merged results as its own sequence.
<add> * <p>
<add> * Note: mapMany and flatMap are equivalent.
<add> * <p>
<add> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mapMany.png">
<add> *
<add> * @param sequence
<add> * the source Observable
<add> * @param func
<add> * a function to apply to each item emitted by the source Observable, generating a
<add> * Observable
<add> * @param <T>
<add> * the type emitted by the source Observable
<add> * @param <R>
<add> * the type emitted by the Observables emitted by <code>func</code>
<add> * @return an Observable that emits a sequence that is the result of applying the transformation
<add> * function to each item emitted by the source Observable and merging the results of
<add> * the Observables obtained from this transformation
<add> * @see {@link #mapMany(Observable, Func1)}
<add> */
<add> public static <T, R> Observable<R> flatMap(Observable<T> sequence, Func1<T, Observable<R>> func) {
<add> return mapMany(sequence, func);
<add> }
<add>
<add> /**
<add> * Creates a new Observable sequence by applying a function that you supply to each object in the
<add> * original Observable sequence, where that function is itself an Observable that emits objects,
<add> * and then merges the results of that function applied to every item emitted by the original
<add> * Observable, emitting these merged results as its own sequence.
<add> * <p>
<add> * Note: mapMany and flatMap are equivalent.
<add> * <p>
<add> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mapMany.png">
<add> *
<add> * @param sequence
<add> * the source Observable
<add> * @param func
<add> * a function to apply to each item emitted by the source Observable, generating a
<add> * Observable
<add> * @param <T>
<add> * the type emitted by the source Observable
<add> * @param <R>
<add> * the type emitted by the Observables emitted by <code>func</code>
<add> * @return an Observable that emits a sequence that is the result of applying the transformation
<add> * function to each item emitted by the source Observable and merging the results of
<add> * the Observables obtained from this transformation
<add> * @see {@link #mapMany(Observable, Func1)}
<add> */
<add> public static <T, R> Observable<R> flatMap(Observable<T> sequence, final Object func) {
<add> return mapMany(sequence, func);
<add> }
<add>
<ide> /**
<ide> * Groups the elements of an observable and selects the resulting elements by using a specified function.
<ide> *
<ide> public static <T> Iterable<T> mostRecent(Observable<T> source, T initialValue) {
<ide>
<ide> /**
<ide> * Returns a connectable observable sequence that upon connection causes the source sequence to push results into the specified subject.
<del> *
<del> * @param source the source sequence whose elements will be pushed into the specified subject.
<del> * @param subject the subject to push source elements into.
<del> * @param <T> source type
<del> * @param <R> result type
<add> *
<add> * @param source
<add> * the source sequence whose elements will be pushed into the specified subject.
<add> * @param subject
<add> * the subject to push source elements into.
<add> * @param <T>
<add> * source type
<add> * @param <R>
<add> * result type
<ide> * @return a connectable observable sequence that upon connection causes the source sequence to push results into the specified subject.
<ide> */
<ide> public static <T, R> ConnectableObservable<R> multicast(Observable<T> source, final Subject<T, R> subject) {
<ide> public static <T, R> ConnectableObservable<R> multicast(Observable<T> source, fi
<ide>
<ide> /**
<ide> * Returns the only element of an observable sequence and throws an exception if there is not exactly one element in the observable sequence.
<del> *
<add> *
<ide> * @param that
<ide> * the source Observable
<ide> * @return The single element in the observable sequence.
<ide> public Boolean call(T t1) {
<ide> });
<ide> }
<ide>
<add> /**
<add> * Creates a new Observable sequence by applying a function that you supply to each item in the
<add> * original Observable sequence, where that function is itself an Observable that emits items, and
<add> * then merges the results of that function applied to every item emitted by the original
<add> * Observable, emitting these merged results as its own sequence.
<add> * <p>
<add> * Note: mapMany and flatMap are equivalent.
<add> * <p>
<add> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mapMany.png">
<add> *
<add> * @param func
<add> * a function to apply to each item in the sequence, that returns an Observable.
<add> * @return an Observable that emits a sequence that is the result of applying the transformation
<add> * function to each item in the input sequence and merging the results of the
<add> * Observables obtained from this transformation.
<add> * @see {@link #mapMany(Func1)}
<add> */
<add> public <R> Observable<R> flatMap(Func1<T, Observable<R>> func) {
<add> return mapMany(func);
<add> }
<add>
<add> /**
<add> * Creates a new Observable sequence by applying a function that you supply to each item in the
<add> * original Observable sequence, where that function is itself an Observable that emits items, and
<add> * then merges the results of that function applied to every item emitted by the original
<add> * Observable, emitting these merged results as its own sequence.
<add> * <p>
<add> * Note: mapMany and flatMap are equivalent.
<add> * <p>
<add> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mapMany.png">
<add> *
<add> * @param callback
<add> * a function to apply to each item in the sequence that returns an Observable.
<add> * @return an Observable that emits a sequence that is the result of applying the transformation'
<add> * function to each item in the input sequence and merging the results of the
<add> * Observables obtained from this transformation.
<add> * @see {@link #mapMany(Object)}
<add> */
<add> public <R> Observable<R> flatMap(final Object callback) {
<add> return mapMany(callback);
<add> }
<add>
<ide> /**
<ide> * Filters an Observable by discarding any of its emissions that do not meet some test.
<ide> * <p>
<ide> public R call(T t1) {
<ide> * then merges the results of that function applied to every item emitted by the original
<ide> * Observable, emitting these merged results as its own sequence.
<ide> * <p>
<add> * Note: mapMany and flatMap are equivalent.
<add> * <p>
<ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mapMany.png">
<ide> *
<ide> * @param func
<ide> * a function to apply to each item in the sequence, that returns an Observable.
<ide> * @return an Observable that emits a sequence that is the result of applying the transformation
<ide> * function to each item in the input sequence and merging the results of the
<ide> * Observables obtained from this transformation.
<add> * @see {@link #flatMap(Func1)}
<ide> */
<ide> public <R> Observable<R> mapMany(Func1<T, Observable<R>> func) {
<ide> return mapMany(this, func);
<ide> public <R> Observable<R> mapMany(Func1<T, Observable<R>> func) {
<ide> * then merges the results of that function applied to every item emitted by the original
<ide> * Observable, emitting these merged results as its own sequence.
<ide> * <p>
<add> * Note: mapMany and flatMap are equivalent.
<add> * <p>
<ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mapMany.png">
<ide> *
<ide> * @param callback
<ide> * a function to apply to each item in the sequence that returns an Observable.
<ide> * @return an Observable that emits a sequence that is the result of applying the transformation'
<ide> * function to each item in the input sequence and merging the results of the
<ide> * Observables obtained from this transformation.
<add> * @see {@link #flatMap(Object))}
<ide> */
<ide> public <R> Observable<R> mapMany(final Object callback) {
<ide> @SuppressWarnings("rawtypes") | 1 |
Python | Python | drop unneeded test | a98049c5de9a4ac9e93eac9798e00df9c93caf81 | <ide><path>rest_framework/tests/decorators.py
<ide> def _finalize_response(self, request, response, *args, **kwargs):
<ide> response.request = request
<ide> return APIView.finalize_response(self, request, response, *args, **kwargs)
<ide>
<del> def test_wrap_view(self):
<del>
<del> @api_view(['GET'])
<del> def view(request):
<del> return Response({})
<del>
<del> self.assertTrue(isinstance(view.cls_instance, APIView))
<del>
<ide> def test_calling_method(self):
<ide>
<ide> @api_view(['GET']) | 1 |
Javascript | Javascript | fix inaccuracy in $provide.service docs | ef03dfc4a4fc32c4a5145cec4db0f97087bfa6c1 | <ide><path>src/auto/injector.js
<ide> function annotate(fn, strictDi, name) {
<ide> *
<ide> * Register a **service constructor**, which will be invoked with `new` to create the service
<ide> * instance.
<del> * This is short for registering a service where its provider's `$get` property is the service
<del> * constructor function that will be used to instantiate the service instance.
<add> * This is short for registering a service where its provider's `$get` property is a factory
<add> * function that returns an instance instantiated by the injector from the service constructor
<add> * function.
<add> *
<add> * Internally it looks a bit like this:
<add> *
<add> * ```
<add> * {
<add> * $get: function() {
<add> * return $injector.instantiate(constructor);
<add> * }
<add> * }
<add> * ```
<add> *
<ide> *
<ide> * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
<ide> * as a type/class. | 1 |
Go | Go | fix the 'but is not' typo | 9c15322894152095539e41623ef33ec0ebdc6c3f | <ide><path>runtime.go
<ide> func (runtime *Runtime) Register(container *Container) error {
<ide> return err
<ide> }
<ide> if !strings.Contains(string(output), "RUNNING") {
<del> utils.Debugf("Container %s was supposed to be running be is not.", container.ID)
<add> utils.Debugf("Container %s was supposed to be running but is not.", container.ID)
<ide> if runtime.config.AutoRestart {
<ide> utils.Debugf("Restarting")
<ide> container.State.SetGhost(false) | 1 |
Java | Java | enable asyncsupported flag in spring test mvc | 2a15b5a89585c24203e32537b0306cff45076638 | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockAsyncContext.java
<del>/*
<del> * Copyright 2002-2012 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package org.springframework.test.web.servlet.request;
<del>
<del>import java.io.IOException;
<del>import java.util.ArrayList;
<del>import java.util.List;
<del>
<del>import javax.servlet.AsyncContext;
<del>import javax.servlet.AsyncEvent;
<del>import javax.servlet.AsyncListener;
<del>import javax.servlet.ServletContext;
<del>import javax.servlet.ServletException;
<del>import javax.servlet.ServletRequest;
<del>import javax.servlet.ServletResponse;
<del>import javax.servlet.http.HttpServletRequest;
<del>import javax.servlet.http.HttpServletResponse;
<del>
<del>import org.springframework.beans.BeanUtils;
<del>import org.springframework.mock.web.MockHttpServletRequest;
<del>import org.springframework.mock.web.MockHttpServletResponse;
<del>import org.springframework.web.util.WebUtils;
<del>
<del>/**
<del> * Mock implementation of the {@link AsyncContext} interface.
<del> *
<del> * @author Rossen Stoyanchev
<del> * @since 3.2
<del> */
<del>class MockAsyncContext implements AsyncContext {
<del>
<del> private final HttpServletRequest request;
<del>
<del> private final HttpServletResponse response;
<del>
<del> private final List<AsyncListener> listeners = new ArrayList<AsyncListener>();
<del>
<del> private String dispatchedPath;
<del>
<del> private long timeout = 10 * 1000L; // 10 seconds is Tomcat's default
<del>
<del>
<del> public MockAsyncContext(ServletRequest request, ServletResponse response) {
<del> this.request = (HttpServletRequest) request;
<del> this.response = (HttpServletResponse) response;
<del> }
<del>
<del> @Override
<del> public ServletRequest getRequest() {
<del> return this.request;
<del> }
<del>
<del> @Override
<del> public ServletResponse getResponse() {
<del> return this.response;
<del> }
<del>
<del> @Override
<del> public boolean hasOriginalRequestAndResponse() {
<del> return (this.request instanceof MockHttpServletRequest) && (this.response instanceof MockHttpServletResponse);
<del> }
<del>
<del> public String getDispatchedPath() {
<del> return this.dispatchedPath;
<del> }
<del>
<del> @Override
<del> public void dispatch() {
<del> dispatch(this.request.getRequestURI());
<del> }
<del>
<del> @Override
<del> public void dispatch(String path) {
<del> dispatch(null, path);
<del> }
<del>
<del> @Override
<del> public void dispatch(ServletContext context, String path) {
<del> this.dispatchedPath = path;
<del> }
<del>
<del> @Override
<del> public void complete() {
<del> Servlet3MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(request, Servlet3MockHttpServletRequest.class);
<del> if (mockRequest != null) {
<del> mockRequest.setAsyncStarted(false);
<del> }
<del> for (AsyncListener listener : this.listeners) {
<del> try {
<del> listener.onComplete(new AsyncEvent(this, this.request, this.response));
<del> }
<del> catch (IOException e) {
<del> throw new IllegalStateException("AsyncListener failure", e);
<del> }
<del> }
<del> }
<del>
<del> @Override
<del> public void start(Runnable runnable) {
<del> runnable.run();
<del> }
<del>
<del> public List<AsyncListener> getListeners() {
<del> return this.listeners;
<del> }
<del>
<del> @Override
<del> public void addListener(AsyncListener listener) {
<del> this.listeners.add(listener);
<del> }
<del>
<del> @Override
<del> public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) {
<del> this.listeners.add(listener);
<del> }
<del>
<del> @Override
<del> public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException {
<del> return BeanUtils.instantiateClass(clazz);
<del> }
<del>
<del> @Override
<del> public long getTimeout() {
<del> return this.timeout;
<del> }
<del>
<del> @Override
<del> public void setTimeout(long timeout) {
<del> this.timeout = timeout;
<del> }
<del>
<del>}
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java
<ide> public final MockHttpServletRequest buildRequest(ServletContext servletContext)
<ide> Assert.notNull(request, "Post-processor [" + postProcessor.getClass().getName() + "] returned null");
<ide> }
<ide>
<add> request.setAsyncSupported(true);
<add>
<ide> return request;
<ide> }
<ide>
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/Servlet3MockHttpServletRequest.java
<del>/*
<del> * Copyright 2002-2012 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package org.springframework.test.web.servlet.request;
<del>
<del>import java.io.IOException;
<del>import java.util.Collection;
<del>import java.util.HashMap;
<del>import java.util.Map;
<del>
<del>import javax.servlet.AsyncContext;
<del>import javax.servlet.DispatcherType;
<del>import javax.servlet.ServletContext;
<del>import javax.servlet.ServletException;
<del>import javax.servlet.ServletRequest;
<del>import javax.servlet.ServletResponse;
<del>import javax.servlet.http.HttpServletResponse;
<del>import javax.servlet.http.Part;
<del>
<del>import org.springframework.mock.web.MockHttpServletRequest;
<del>
<del>/**
<del> * A Servlet 3 sub-class of MockHttpServletRequest.
<del> *
<del> * @author Rossen Stoyanchev
<del> * @since 3.2
<del> */
<del>class Servlet3MockHttpServletRequest extends MockHttpServletRequest {
<del>
<del> private boolean asyncStarted;
<del>
<del> private MockAsyncContext asyncContext;
<del>
<del> private Map<String, Part> parts = new HashMap<String, Part>();
<del>
<del>
<del> public Servlet3MockHttpServletRequest(ServletContext servletContext) {
<del> super(servletContext);
<del> }
<del>
<del> @Override
<del> public boolean isAsyncSupported() {
<del> return true;
<del> }
<del>
<del> @Override
<del> public AsyncContext startAsync() {
<del> return startAsync(this, null);
<del> }
<del>
<del> @Override
<del> public AsyncContext startAsync(ServletRequest request, ServletResponse response) {
<del> this.asyncStarted = true;
<del> this.asyncContext = new MockAsyncContext(request, response);
<del> return this.asyncContext;
<del> }
<del>
<del> @Override
<del> public AsyncContext getAsyncContext() {
<del> return this.asyncContext;
<del> }
<del>
<del> public void setAsyncContext(MockAsyncContext asyncContext) {
<del> this.asyncContext = asyncContext;
<del> }
<del>
<del> @Override
<del> public DispatcherType getDispatcherType() {
<del> return DispatcherType.REQUEST;
<del> }
<del>
<del> @Override
<del> public boolean isAsyncStarted() {
<del> return this.asyncStarted;
<del> }
<del>
<del> @Override
<del> public void setAsyncStarted(boolean asyncStarted) {
<del> this.asyncStarted = asyncStarted;
<del> }
<del>
<del> @Override
<del> public void addPart(Part part) {
<del> this.parts.put(part.getName(), part);
<del> }
<del>
<del> @Override
<del> public Part getPart(String key) throws IOException, IllegalStateException, ServletException {
<del> return this.parts.get(key);
<del> }
<del>
<del> @Override
<del> public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException {
<del> return this.parts.values();
<del> }
<del>
<del> @Override
<del> public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
<del> throw new UnsupportedOperationException();
<del> }
<del>
<del>}
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/Servlet3MockMultipartHttpServletRequest.java
<del>/*
<del> * Copyright 2002-2012 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package org.springframework.test.web.servlet.request;
<del>
<del>import java.io.IOException;
<del>import java.util.Collection;
<del>import java.util.HashMap;
<del>import java.util.Map;
<del>
<del>import javax.servlet.AsyncContext;
<del>import javax.servlet.DispatcherType;
<del>import javax.servlet.ServletException;
<del>import javax.servlet.ServletRequest;
<del>import javax.servlet.ServletResponse;
<del>import javax.servlet.http.HttpServletResponse;
<del>import javax.servlet.http.Part;
<del>
<del>import org.springframework.mock.web.MockMultipartHttpServletRequest;
<del>
<del>/**
<del> * A Servlet 3 sub-class of MockMultipartHttpServletRequest.
<del> *
<del> * @author Rossen Stoyanchev
<del> * @since 3.2
<del> */
<del>class Servlet3MockMultipartHttpServletRequest extends MockMultipartHttpServletRequest {
<del>
<del> private boolean asyncStarted;
<del>
<del> private MockAsyncContext asyncContext;
<del>
<del> private Map<String, Part> parts = new HashMap<String, Part>();
<del>
<del>
<del> @Override
<del> public boolean isAsyncSupported() {
<del> return true;
<del> }
<del>
<del> @Override
<del> public AsyncContext startAsync() {
<del> return startAsync(this, null);
<del> }
<del>
<del> @Override
<del> public AsyncContext startAsync(ServletRequest request, ServletResponse response) {
<del> this.asyncStarted = true;
<del> this.asyncContext = new MockAsyncContext(request, response);
<del> return this.asyncContext;
<del> }
<del>
<del> @Override
<del> public AsyncContext getAsyncContext() {
<del> return this.asyncContext;
<del> }
<del>
<del> public void setAsyncContext(MockAsyncContext asyncContext) {
<del> this.asyncContext = asyncContext;
<del> }
<del>
<del> @Override
<del> public DispatcherType getDispatcherType() {
<del> return DispatcherType.REQUEST;
<del> }
<del>
<del> @Override
<del> public boolean isAsyncStarted() {
<del> return this.asyncStarted;
<del> }
<del>
<del> @Override
<del> public void setAsyncStarted(boolean asyncStarted) {
<del> this.asyncStarted = asyncStarted;
<del> }
<del>
<del> @Override
<del> public void addPart(Part part) {
<del> this.parts.put(part.getName(), part);
<del> }
<del>
<del> @Override
<del> public Part getPart(String key) throws IOException, IllegalStateException, ServletException {
<del> return this.parts.get(key);
<del> }
<del>
<del> @Override
<del> public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException {
<del> return this.parts.values();
<del> }
<del>
<del> @Override
<del> public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
<del> throw new UnsupportedOperationException();
<del> }
<del>
<del>}
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilder.java
<ide> import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
<ide> import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
<ide> import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
<add>import org.springframework.web.servlet.handler.AbstractHandlerMapping;
<ide> import org.springframework.web.servlet.handler.MappedInterceptor;
<ide> import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
<ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
<ide> public class StandaloneMockMvcBuilder extends DefaultMockMvcBuilder<StandaloneMo
<ide>
<ide> private boolean useTrailingSlashPatternMatch = true;
<ide>
<add> private Boolean removeSemicolonContent;
<add>
<ide>
<ide> /**
<ide> * Protected constructor. Not intended for direct instantiation.
<ide> public StandaloneMockMvcBuilder setUseTrailingSlashPatternMatch(boolean useTrail
<ide> return this;
<ide> }
<ide>
<add> /**
<add> * Set if ";" (semicolon) content should be stripped from the request URI. The value,
<add> * if provided, is in turn set on
<add> * {@link AbstractHandlerMapping#setRemoveSemicolonContent(boolean)}.
<add> */
<add> public void setRemoveSemicolonContent(boolean removeSemicolonContent) {
<add> this.removeSemicolonContent = removeSemicolonContent;
<add> }
<add>
<ide> @Override
<ide> protected void initWebAppContext(WebApplicationContext cxt) {
<ide> StubWebApplicationContext mockCxt = (StubWebApplicationContext) cxt;
<ide> public RequestMappingHandlerMapping requestMappingHandlerMapping() {
<ide> handlerMapping.setOrder(0);
<ide> handlerMapping.setInterceptors(getInterceptors());
<ide>
<add> if (removeSemicolonContent != null) {
<add> handlerMapping.setRemoveSemicolonContent(removeSemicolonContent);
<add> }
<add>
<ide> return handlerMapping;
<ide> }
<ide> | 5 |
PHP | PHP | fix more fqcn docblocks | b0eb42d40ace46b71095b55af65910dc2520ddcb | <ide><path>src/Http/Server.php
<ide> public function setApp(BaseApplication $app)
<ide> /**
<ide> * Get the current application.
<ide> *
<del> * @return BaseApplication The application that will be run.
<add> * @return \Cake\Http\BaseApplication The application that will be run.
<ide> */
<ide> public function getApp()
<ide> {
<ide><path>src/ORM/Table.php
<ide> protected function _transactionCommitted($atomic, $primary)
<ide> * created entities. This callback will be called *before* the entity
<ide> * is persisted.
<ide> * @param array $options The options to use when saving.
<del> * @return EntityInterface An entity.
<add> * @return \Cake\Datasource\EntityInterface An entity.
<ide> */
<ide> public function findOrCreate($search, callable $callback = null, $options = [])
<ide> {
<ide> public function findOrCreate($search, callable $callback = null, $options = [])
<ide> * created entities. This callback will be called *before* the entity
<ide> * is persisted.
<ide> * @param array $options The options to use when saving.
<del> * @return EntityInterface An entity.
<add> * @return \Cake\Datasource\EntityInterface An entity.
<ide> */
<ide> protected function _processFindOrCreate($search, callable $callback = null, $options = [])
<ide> { | 2 |
PHP | PHP | fix method order | cd0939d35b68db2e0661efac53a7ca3b932430a8 | <ide><path>src/Illuminate/Notifications/Events/NotificationSent.php
<ide> class NotificationSent
<ide> */
<ide> public function __construct($notifiable, $notification, $channel)
<ide> {
<add> $this->channel = $channel;
<ide> $this->notifiable = $notifiable;
<ide> $this->notification = $notification;
<del> $this->channel = $channel;
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove @eventof jsdocs tag | 363fb4fc79a098da30a6431aab3c0191aba1d377 | <ide><path>src/ng/directive/ngInclude.js
<ide>
<ide> /**
<ide> * @ngdoc event
<del> * @name ng.directive:ngInclude#$includeContentError
<del> * @eventOf ng.directive:ngInclude
<add> * @name ngInclude#$includeContentError
<ide> * @eventType emit on the scope ngInclude was declared in
<ide> * @description
<ide> * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299) | 1 |
Javascript | Javascript | remove arbitrary timer | f99e6988557e17624962c2bc36bebd7fa3119eec | <ide><path>test/parallel/test-dgram-send-callback-buffer-length.js
<ide> const assert = require('assert');
<ide> const dgram = require('dgram');
<ide> const client = dgram.createSocket('udp4');
<ide>
<del>const timer = setTimeout(function() {
<del> throw new Error('Timeout');
<del>}, common.platformTimeout(200));
<del>
<ide> const buf = Buffer.allocUnsafe(256);
<ide> const offset = 20;
<ide> const len = buf.length - offset;
<ide>
<ide> const messageSent = common.mustCall(function messageSent(err, bytes) {
<del> assert.notEqual(bytes, buf.length);
<del> assert.equal(bytes, buf.length - offset);
<del> clearTimeout(timer);
<add> assert.notStrictEqual(bytes, buf.length);
<add> assert.strictEqual(bytes, buf.length - offset);
<ide> client.close();
<ide> });
<ide> | 1 |
PHP | PHP | fix autoincrement reflection in sqlserver | 4912fc207d0dbb739577e4ea0f6cf32e043f10c4 | <ide><path>src/Database/Schema/SqlserverSchema.php
<ide> public function listTablesSql($config)
<ide> */
<ide> public function describeColumnSql($tableName, $config)
<ide> {
<del> $sql = "SELECT DISTINCT TABLE_SCHEMA AS [schema], COLUMN_NAME AS [name], DATA_TYPE AS [type],
<del> IS_NULLABLE AS [null], COLUMN_DEFAULT AS [default],
<del> CHARACTER_MAXIMUM_LENGTH AS [char_length],
<del> NUMERIC_PRECISION AS [precision],
<del> NUMERIC_SCALE AS [scale],
<del> '' AS [comment], ORDINAL_POSITION AS [ordinal_position]
<del> FROM INFORMATION_SCHEMA.COLUMNS
<del> WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?
<del> ORDER BY ordinal_position";
<add> $sql = "SELECT DISTINCT
<add> AC.name AS [name],
<add> TY.name AS [type],
<add> AC.max_length AS [char_length],
<add> AC.precision AS [precision],
<add> AC.scale AS [scale],
<add> AC.is_identity AS [autoincrement],
<add> AC.is_nullable AS [null],
<add> OBJECT_DEFINITION(AC.default_object_id) AS [default]
<add> FROM sys.[tables] T
<add> INNER JOIN sys.[schemas] S ON S.[schema_id] = T.[schema_id]
<add> INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
<add> INNER JOIN sys.[types] TY ON TY.[user_type_id] = AC.[user_type_id]
<add> WHERE T.[name] = ? AND S.[name] = ?";
<ide>
<ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
<ide> return [$sql, [$tableName, $schema]];
<ide> public function convertColumnDescription(Table $table, $row)
<ide> if (!empty($row['default'])) {
<ide> $row['default'] = trim($row['default'], '()');
<ide> }
<del>
<add> if (!empty($row['autoincrement'])) {
<add> $field['autoIncrement'] = true;
<add> }
<ide> if ($field['type'] === 'boolean') {
<ide> $row['default'] = (int)$row['default'];
<ide> }
<ide>
<ide> $field += [
<del> 'null' => $row['null'] === 'YES' ? true : false,
<add> 'null' => $row['null'] === '1' ? true : false,
<ide> 'default' => $row['default'],
<ide> ];
<ide> $table->addColumn($row['name'], $field);
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> public function testConvertColumn($type, $length, $precision, $scale, $expected)
<ide> $field = [
<ide> 'name' => 'field',
<ide> 'type' => $type,
<del> 'null' => 'YES',
<add> 'null' => '1',
<ide> 'default' => 'Default value',
<ide> 'char_length' => $length,
<ide> 'precision' => $precision,
<ide> public function testDescribeTable()
<ide> }
<ide> }
<ide>
<add> /**
<add> * Test describing a table with postgres and composite keys
<add> *
<add> * @return void
<add> */
<add> public function testDescribeTableCompositeKey()
<add> {
<add> $this->_needsConnection();
<add> $connection = ConnectionManager::get('test');
<add> $sql = <<<SQL
<add>CREATE TABLE schema_composite (
<add> [id] INTEGER IDENTITY(1, 1),
<add> [site_id] INTEGER NOT NULL,
<add> [name] VARCHAR(255),
<add> PRIMARY KEY([id], [site_id])
<add>);
<add>SQL;
<add> $connection->execute($sql);
<add> $schema = new SchemaCollection($connection);
<add> $result = $schema->describe('schema_composite');
<add> $connection->execute('DROP TABLE schema_composite');
<add>
<add> $this->assertEquals(['id', 'site_id'], $result->primaryKey());
<add> $this->assertNull($result->column('site_id')['autoIncrement'], 'site_id should not be autoincrement');
<add> $this->assertTrue($result->column('id')['autoIncrement'], 'id should be autoincrement');
<add> }
<add>
<ide> /**
<ide> * Test that describe accepts tablenames containing `schema.table`.
<ide> * | 2 |
Javascript | Javascript | support min and max dates on time scale | 35011e5ae396d5dd68961d14ec50d8ef5f3a809e | <ide><path>src/scales/scale.time.js
<ide> scaleLabelMoments.push(labelMoment);
<ide> }, this);
<ide>
<del> this.firstTick = moment.min.call(this, scaleLabelMoments);
<del> this.lastTick = moment.max.call(this, scaleLabelMoments);
<add> if (this.options.time.min) {
<add> this.firstTick = this.parseTime(this.options.time.min);
<add> } else {
<add> this.firstTick = moment.min.call(this, scaleLabelMoments);
<add> }
<add>
<add> if (this.options.time.max) {
<add> this.lastTick = this.parseTime(this.options.time.max);
<add> } else {
<add> this.lastTick = moment.max.call(this, scaleLabelMoments);
<add> }
<ide> } else {
<ide> this.firstTick = null;
<ide> this.lastTick = null; | 1 |
Python | Python | add several danish alternative spellings | 0ffd27b0f64cb12bef7a4c337edfb9c4a3b03a00 | <ide><path>spacy/lang/da/__init__.py
<ide> from __future__ import unicode_literals
<ide>
<ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
<add>from .norm_exceptions import NORM_EXCEPTIONS
<ide> from .stop_words import STOP_WORDS
<ide> from .lex_attrs import LEX_ATTRS
<ide> from .morph_rules import MORPH_RULES
<ide> class DanishDefaults(Language.Defaults):
<ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
<ide> lex_attr_getters.update(LEX_ATTRS)
<ide> lex_attr_getters[LANG] = lambda text: 'da'
<del> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
<add> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM],
<add> BASE_NORMS, NORM_EXCEPTIONS)
<ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
<ide> # morph_rules = MORPH_RULES
<ide> tag_map = TAG_MAP
<ide><path>spacy/lang/da/norm_exceptions.py
<add># coding: utf8
<add>"""
<add>Special-case rules for normalizing tokens to improve the model's predictions.
<add>For example 'mysterium' vs 'mysterie' and similar.
<add>"""
<add>
<add># Sources:
<add># 1: https://dsn.dk/retskrivning/om-retskrivningsordbogen/mere-om-retskrivningsordbogen-2012/endrede-stave-og-ordformer/
<add># 2: http://www.tjerry-korrektur.dk/ord-med-flere-stavemaader/
<add>
<add>_exc = {
<add> # Alternative spelling
<add> "a-kraft-værk": "a-kraftværk", # 1
<add> "ålborg": "aalborg", # 2
<add> "århus": "aarhus",
<add> "accessoirer": "accessoires", # 1
<add> "affektert": "affekteret", # 1
<add> "afrikander": "afrikaaner", # 1
<add> "aftabuere": "aftabuisere", # 1
<add> "aftabuering": "aftabuisering", # 1
<add> "akvarium": "akvarie", # 1
<add> "alenefader": "alenefar", # 1
<add> "alenemoder": "alenemor", # 1
<add> "alkoholambulatorium": "alkoholambulatorie", # 1
<add> "ambulatorium": "ambulatorie", # 1
<add> "ananassene": "ananasserne", # 2
<add> "anførelsestegn": "anførselstegn", # 1
<add> "anseelig": "anselig", # 2
<add> "antioxydant": "antioxidant", # 1
<add> "artrig": "artsrig", # 1
<add> "auditorium": "auditorie", # 1
<add> "avocado": "avokado", # 2
<add> "bagerst": "bagest", # 2
<add> "bagstræv": "bagstræb", # 1
<add> "bagstræver": "bagstræber", # 1
<add> "bagstræverisk": "bagstræberisk", # 1
<add> "balde": "balle", # 2
<add> "barselorlov": "barselsorlov", # 1
<add> "barselvikar": "barselsvikar", # 1
<add> "baskien": "baskerlandet", # 1
<add> "bayrisk": "bayersk", # 1
<add> "bedstefader": "bedstefar", # 1
<add> "bedstemoder": "bedstemor", # 1
<add> "behefte": "behæfte", # 1
<add> "beheftelse": "behæftelse", # 1
<add> "bidragydende": "bidragsydende", # 1
<add> "bidragyder": "bidragsyder", # 1
<add> "billiondel": "billiontedel", # 1
<add> "blaseret": "blasert", # 1
<add> "bleskifte": "bleskift", # 1
<add> "blodbroder": "blodsbroder", # 2
<add> "blyantspidser": "blyantsspidser", # 2
<add> "boligministerium": "boligministerie", # 1
<add> "borhul": "borehul", # 1
<add> "broder": "bror", # 2
<add> "buldog": "bulldog", # 2
<add> "bådhus": "bådehus", # 1
<add> "børnepleje": "barnepleje", # 1
<add> "børneseng": "barneseng", # 1
<add> "børnestol": "barnestol", # 1
<add> "cairo": "kairo", # 1
<add> "cambodia": "cambodja", # 1
<add> "cambodianer": "cambodjaner", # 1
<add> "cambodiansk": "cambodjansk", # 1
<add> "camouflage": "kamuflage", # 2
<add> "campylobacter": "kampylobakter", # 1
<add> "centeret": "centret", # 2
<add> "chefskahyt": "chefkahyt", # 1
<add> "chefspost": "chefpost", # 1
<add> "chefssekretær": "chefsekretær", # 1
<add> "chefsstol": "chefstol", # 1
<add> "cirkulærskrivelse": "cirkulæreskrivelse", # 1
<add> "cognacsglas": "cognacglas", # 1
<add> "columnist": "kolumnist", # 1
<add> "cricket": "kricket", # 2
<add> "dagplejemoder": "dagplejemor", # 1
<add> "damaskesdug": "damaskdug", # 1
<add> "damp-barn": "dampbarn", # 1
<add> "delfinarium": "delfinarie", # 1
<add> "dentallaboratorium": "dentallaboratorie", # 1
<add> "diaramme": "diasramme", # 1
<add> "diaré": "diarré", # 1
<add> "dioxyd": "dioxid", # 1
<add> "dommedagsprædiken": "dommedagspræken", # 1
<add> "donut": "doughnut", # 2
<add> "driftmæssig": "driftsmæssig", # 1
<add> "driftsikker": "driftssikker", # 1
<add> "driftsikring": "driftssikring", # 1
<add> "drikkejogurt": "drikkeyoghurt", # 1
<add> "drivein": "drive-in", # 1
<add> "driveinbiograf": "drive-in-biograf", # 1
<add> "drøvel": "drøbel", # 1
<add> "dødskriterium": "dødskriterie", # 1
<add> "e-mail-adresse": "e-mailadresse", # 1
<add> "e-post-adresse": "e-postadresse", # 1
<add> "egypten": "ægypten", # 2
<add> "ekskommunicere": "ekskommunikere", # 1
<add> "eksperimentarium": "eksperimentarie", # 1
<add> "elsass": "Alsace", # 1
<add> "elsasser": "alsacer", # 1
<add> "elsassisk": "alsacisk", # 1
<add> "elvetal": "ellevetal", # 1
<add> "elvetiden": "ellevetiden", # 1
<add> "elveårig": "elleveårig", # 1
<add> "elveårs": "elleveårs", # 1
<add> "elveårsbarn": "elleveårsbarn", # 1
<add> "elvte": "ellevte", # 1
<add> "elvtedel": "ellevtedel", # 1
<add> "energiministerium": "energiministerie", # 1
<add> "erhvervsministerium": "erhvervsministerie", # 1
<add> "espaliere": "spaliere", # 2
<add> "evangelium": "evangelie", # 1
<add> "fagministerium": "fagministerie", # 1
<add> "fakse": "faxe", # 1
<add> "fangstkvota": "fangstkvote", # 1
<add> "fader": "far", # 2
<add> "farbroder": "farbror", # 1
<add> "farfader": "farfar", # 1
<add> "farmoder": "farmor", # 1
<add> "federal": "føderal", # 1
<add> "federalisering": "føderalisering", # 1
<add> "federalisme": "føderalisme", # 1
<add> "federalist": "føderalist", # 1
<add> "federalistisk": "føderalistisk", # 1
<add> "federation": "føderation", # 1
<add> "federativ": "føderativ", # 1
<add> "fejlbeheftet": "fejlbehæftet", # 1
<add> "femetagers": "femetages", # 2
<add> "femhundredekroneseddel": "femhundredkroneseddel", # 2
<add> "filmpremiere": "filmpræmiere", # 2
<add> "finansimperium": "finansimperie", # 1
<add> "finansministerium": "finansministerie", # 1
<add> "firehjulstræk": "firhjulstræk", # 2
<add> "fjernstudium": "fjernstudie", # 1
<add> "formalier": "formalia", # 1
<add> "formandsskift": "formandsskifte", # 1
<add> "fornemst": "fornemmest", # 2
<add> "fornuftparti": "fornuftsparti", # 1
<add> "fornuftstridig": "fornuftsstridig", # 1
<add> "fornuftvæsen": "fornuftsvæsen", # 1
<add> "fornuftægteskab": "fornuftsægteskab", # 1
<add> "forretningsministerium": "forretningsministerie", # 1
<add> "forskningsministerium": "forskningsministerie", # 1
<add> "forstudium": "forstudie", # 1
<add> "forsvarsministerium": "forsvarsministerie", # 1
<add> "frilægge": "fritlægge", # 1
<add> "frilæggelse": "fritlæggelse", # 1
<add> "frilægning": "fritlægning", # 1
<add> "fristille": "fritstille", # 1
<add> "fristilling": "fritstilling", # 1
<add> "fuldttegnet": "fuldtegnet", # 1
<add> "fødestedskriterium": "fødestedskriterie", # 1
<add> "fødevareministerium": "fødevareministerie", # 1
<add> "følesløs": "følelsesløs", # 1
<add> "følgeligt": "følgelig", # 1
<add> "førne": "førn", # 1
<add> "gearskift": "gearskifte", # 2
<add> "gladeligt": "gladelig", # 1
<add> "glosehefte": "glosehæfte", # 1
<add> "glædeløs": "glædesløs", # 1
<add> "gonoré": "gonorré", # 1
<add> "grangiveligt": "grangivelig", # 1
<add> "grundliggende": "grundlæggende", # 2
<add> "grønsag": "grøntsag", # 2
<add> "gudbenådet": "gudsbenådet", # 1
<add> "gudfader": "gudfar", # 1
<add> "gudmoder": "gudmor", # 1
<add> "gulvmop": "gulvmoppe", # 1
<add> "gymnasium": "gymnasie", # 1
<add> "hackning": "hacking", # 1
<add> "halvbroder": "halvbror", # 1
<add> "halvelvetiden": "halvellevetiden", # 1
<add> "handelsgymnasium": "handelsgymnasie", # 1
<add> "hefte": "hæfte", # 1
<add> "hefteklamme": "hæfteklamme", # 1
<add> "heftelse": "hæftelse", # 1
<add> "heftemaskine": "hæftemaskine", # 1
<add> "heftepistol": "hæftepistol", # 1
<add> "hefteplaster": "hæfteplaster", # 1
<add> "heftestraf": "hæftestraf", # 1
<add> "heftning": "hæftning", # 1
<add> "helbroder": "helbror", # 1
<add> "hjemmeklasse": "hjemklasse", # 1
<add> "hjulspin": "hjulspind", # 1
<add> "huggevåben": "hugvåben", # 1
<add> "hulmurisolering": "hulmursisolering", # 1
<add> "hurtiggående": "hurtigtgående", # 2
<add> "hurtigttørrende": "hurtigtørrende", # 2
<add> "husmoder": "husmor", # 1
<add> "hydroxyd": "hydroxid", # 1
<add> "håndmikser": "håndmixer", # 1
<add> "højtaler": "højttaler", # 2
<add> "hønemoder": "hønemor", # 1
<add> "ide": "idé", # 2
<add> "imperium": "imperie", # 1
<add> "imponerthed": "imponerethed", # 1
<add> "inbox": "indboks", # 2
<add> "indenrigsministerium": "indenrigsministerie", # 1
<add> "indhefte": "indhæfte", # 1
<add> "indheftning": "indhæftning", # 1
<add> "indicium": "indicie", # 1
<add> "indkassere": "inkassere", # 2
<add> "iota": "jota", # 1
<add> "jobskift": "jobskifte", # 1
<add> "jogurt": "yoghurt", # 1
<add> "jukeboks": "jukebox", # 1
<add> "justitsministerium": "justitsministerie", # 1
<add> "kalorifere": "kalorifer", # 1
<add> "kandidatstipendium": "kandidatstipendie", # 1
<add> "kannevas": "kanvas", # 1
<add> "kaperssauce": "kaperssovs", # 1
<add> "kigge": "kikke", # 2
<add> "kirkeministerium": "kirkeministerie", # 1
<add> "klapmydse": "klapmyds", # 1
<add> "klimakterium": "klimakterie", # 1
<add> "klogeligt": "klogelig", # 1
<add> "knivblad": "knivsblad", # 1
<add> "kollegaer": "kolleger", # 2
<add> "kollegium": "kollegie", # 1
<add> "kollegiehefte": "kollegiehæfte", # 1
<add> "kollokviumx": "kollokvium", # 1
<add> "kommissorium": "kommissorie", # 1
<add> "kompendium": "kompendie", # 1
<add> "komplicerthed": "komplicerethed", # 1
<add> "konfederation": "konføderation", # 1
<add> "konfedereret": "konfødereret", # 1
<add> "konferensstudium": "konferensstudie", # 1
<add> "konservatorium": "konservatorie", # 1
<add> "konsulere": "konsultere", # 1
<add> "kradsbørstig": "krasbørstig", # 2
<add> "kravsspecifikation": "kravspecifikation", # 1
<add> "krematorium": "krematorie", # 1
<add> "krep": "crepe", # 1
<add> "krepnylon": "crepenylon", # 1
<add> "kreppapir": "crepepapir", # 1
<add> "kricket": "cricket", # 2
<add> "kriterium": "kriterie", # 1
<add> "kroat": "kroater", # 2
<add> "kroki": "croquis", # 1
<add> "kronprinsepar": "kronprinspar", # 2
<add> "kropdoven": "kropsdoven", # 1
<add> "kroplus": "kropslus", # 1
<add> "krøllefedt": "krølfedt", # 1
<add> "kulturministerium": "kulturministerie", # 1
<add> "kuponhefte": "kuponhæfte", # 1
<add> "kvota": "kvote", # 1
<add> "kvotaordning": "kvoteordning", # 1
<add> "laboratorium": "laboratorie", # 1
<add> "laksfarve": "laksefarve", # 1
<add> "laksfarvet": "laksefarvet", # 1
<add> "laksrød": "lakserød", # 1
<add> "laksyngel": "lakseyngel", # 1
<add> "laksørred": "lakseørred", # 1
<add> "landbrugsministerium": "landbrugsministerie", # 1
<add> "landskampstemning": "landskampsstemning", # 1
<add> "langust": "languster", # 1
<add> "lappegrejer": "lappegrej", # 1
<add> "lavløn": "lavtløn", # 1
<add> "lillebroder": "lillebror", # 1
<add> "linear": "lineær", # 1
<add> "loftlampe": "loftslampe", # 2
<add> "log-in": "login", # 1
<add> "login": "log-in", # 2
<add> "lovmedholdig": "lovmedholdelig", # 1
<add> "ludder": "luder", # 2
<add> "lysholder": "lyseholder", # 1
<add> "lægeskifte": "lægeskift", # 1
<add> "lærvillig": "lærevillig", # 1
<add> "løgsauce": "løgsovs", # 1
<add> "madmoder": "madmor", # 1
<add> "majonæse": "mayonnaise", # 1
<add> "mareridtagtig": "mareridtsagtig", # 1
<add> "margen": "margin", # 2
<add> "martyrium": "martyrie", # 1
<add> "mellemstatlig": "mellemstatslig", # 1
<add> "menneskene": "menneskerne", # 2
<add> "metropolis": "metropol", # 1
<add> "miks": "mix", # 1
<add> "mikse": "mixe", # 1
<add> "miksepult": "mixerpult", # 1
<add> "mikser": "mixer", # 1
<add> "mikserpult": "mixerpult", # 1
<add> "mikslån": "mixlån", # 1
<add> "miksning": "mixning", # 1
<add> "miljøministerium": "miljøministerie", # 1
<add> "milliarddel": "milliardtedel", # 1
<add> "milliondel": "milliontedel", # 1
<add> "ministerium": "ministerie", # 1
<add> "mop": "moppe", # 1
<add> "moder": "mor", # 2
<add> "moratorium": "moratorie", # 1
<add> "morbroder": "morbror", # 1
<add> "morfader": "morfar", # 1
<add> "mormoder": "mormor", # 1
<add> "musikkonservatorium": "musikkonservatorie", # 1
<add> "muslingskal": "muslingeskal", # 1
<add> "mysterium": "mysterie", # 1
<add> "naturalieydelse": "naturalydelse", # 1
<add> "naturalieøkonomi": "naturaløkonomi", # 1
<add> "navnebroder": "navnebror", # 1
<add> "nerium": "nerie", # 1
<add> "nådeløs": "nådesløs", # 1
<add> "nærforestående": "nærtforestående", # 1
<add> "nærstående": "nærtstående", # 1
<add> "observatorium": "observatorie", # 1
<add> "oldefader": "oldefar", # 1
<add> "oldemoder": "oldemor", # 1
<add> "opgraduere": "opgradere", # 1
<add> "opgraduering": "opgradering", # 1
<add> "oratorium": "oratorie", # 1
<add> "overbookning": "overbooking", # 1
<add> "overpræsidium": "overpræsidie", # 1
<add> "overstatlig": "overstatslig", # 1
<add> "oxyd": "oxid", # 1
<add> "oxydere": "oxidere", # 1
<add> "oxydering": "oxidering", # 1
<add> "pakkenellike": "pakkenelliker", # 1
<add> "papirtynd": "papirstynd", # 1
<add> "pastoralseminarium": "pastoralseminarie", # 1
<add> "peanutsene": "peanuttene", # 2
<add> "penalhus": "pennalhus", # 2
<add> "pensakrav": "pensumkrav", # 1
<add> "pepperoni": "peperoni", # 1
<add> "peruaner": "peruvianer", # 1
<add> "petrole": "petrol", # 1
<add> "piltast": "piletast", # 1
<add> "piltaste": "piletast", # 1
<add> "planetarium": "planetarie", # 1
<add> "plasteret": "plastret", # 2
<add> "plastic": "plastik", # 2
<add> "play-off-kamp": "playoffkamp", # 1
<add> "plejefader": "plejefar", # 1
<add> "plejemoder": "plejemor", # 1
<add> "podium": "podie", # 2
<add> "praha": "prag", # 2
<add> "preciøs": "pretiøs", # 2
<add> "privilegium": "privilegie", # 1
<add> "progredere": "progrediere", # 1
<add> "præsidium": "præsidie", # 1
<add> "psykodelisk": "psykedelisk", # 1
<add> "pudsegrejer": "pudsegrej", # 1
<add> "referensgruppe": "referencegruppe", # 1
<add> "referensramme": "referenceramme", # 1
<add> "refugium": "refugie", # 1
<add> "registeret": "registret", # 2
<add> "remedium": "remedie", # 1
<add> "remiks": "remix", # 1
<add> "reservert": "reserveret", # 1
<add> "ressortministerium": "ressortministerie", # 1
<add> "ressource": "resurse", # 2
<add> "resætte": "resette", # 1
<add> "rettelig": "retteligt", # 1
<add> "rettetaste": "rettetast", # 1
<add> "returtaste": "returtast", # 1
<add> "risici": "risikoer", # 2
<add> "roll-on": "rollon", # 1
<add> "rollehefte": "rollehæfte", # 1
<add> "rostbøf": "roastbeef", # 1
<add> "rygsæksturist": "rygsækturist", # 1
<add> "rødstjært": "rødstjert", # 1
<add> "saddel": "sadel", # 2
<add> "samaritan": "samaritaner", # 2
<add> "sanatorium": "sanatorie", # 1
<add> "sauce": "sovs", # 1
<add> "scanning": "skanning", # 2
<add> "sceneskifte": "sceneskift", # 1
<add> "scilla": "skilla", # 1
<add> "sejflydende": "sejtflydende", # 1
<add> "selvstudium": "selvstudie", # 1
<add> "seminarium": "seminarie", # 1
<add> "sennepssauce": "sennepssovs ", # 1
<add> "servitutbeheftet": "servitutbehæftet", # 1
<add> "sit-in": "sitin", # 1
<add> "skatteministerium": "skatteministerie", # 1
<add> "skifer": "skiffer", # 2
<add> "skyldsfølelse": "skyldfølelse", # 1
<add> "skysauce": "skysovs", # 1
<add> "sladdertaske": "sladretaske", # 2
<add> "sladdervorn": "sladrevorn", # 2
<add> "slagsbroder": "slagsbror", # 1
<add> "slettetaste": "slettetast", # 1
<add> "smørsauce": "smørsovs", # 1
<add> "snitsel": "schnitzel", # 1
<add> "snobbeeffekt": "snobeffekt", # 2
<add> "socialministerium": "socialministerie", # 1
<add> "solarium": "solarie", # 1
<add> "soldebroder": "soldebror", # 1
<add> "spagetti": "spaghetti", # 1
<add> "spagettistrop": "spaghettistrop", # 1
<add> "spagettiwestern": "spaghettiwestern", # 1
<add> "spin-off": "spinoff", # 1
<add> "spinnefiskeri": "spindefiskeri", # 1
<add> "spolorm": "spoleorm", # 1
<add> "sproglaboratorium": "sproglaboratorie", # 1
<add> "spækbræt": "spækkebræt", # 2
<add> "stand-in": "standin", # 1
<add> "stand-up-comedy": "standupcomedy", # 1
<add> "stand-up-komiker": "standupkomiker", # 1
<add> "statsministerium": "statsministerie", # 1
<add> "stedbroder": "stedbror", # 1
<add> "stedfader": "stedfar", # 1
<add> "stedmoder": "stedmor", # 1
<add> "stilehefte": "stilehæfte", # 1
<add> "stipendium": "stipendie", # 1
<add> "stjært": "stjert", # 1
<add> "stjærthage": "stjerthage", # 1
<add> "storebroder": "storebror", # 1
<add> "stortå": "storetå", # 1
<add> "strabads": "strabadser", # 1
<add> "strømlinjet": "strømlinet", # 1
<add> "studium": "studie", # 1
<add> "stænkelap": "stænklap", # 1
<add> "sundhedsministerium": "sundhedsministerie", # 1
<add> "suppositorium": "suppositorie", # 1
<add> "svejts": "schweiz", # 1
<add> "svejtser": "schweizer", # 1
<add> "svejtserfranc": "schweizerfranc", # 1
<add> "svejtserost": "schweizerost", # 1
<add> "svejtsisk": "schweizisk", # 1
<add> "svigerfader": "svigerfar", # 1
<add> "svigermoder": "svigermor", # 1
<add> "svirebroder": "svirebror", # 1
<add> "symposium": "symposie", # 1
<add> "sælarium": "sælarie", # 1
<add> "søreme": "sørme", # 2
<add> "søterritorium": "søterritorie", # 1
<add> "t-bone-steak": "t-bonesteak", # 1
<add> "tabgivende": "tabsgivende", # 1
<add> "tabuere": "tabuisere", # 1
<add> "tabuering": "tabuisering", # 1
<add> "tackle": "takle", # 2
<add> "tackling": "takling", # 2
<add> "taifun": "tyfon", # 1
<add> "take-off": "takeoff", # 1
<add> "taknemlig": "taknemmelig", # 2
<add> "talehørelærer": "tale-høre-lærer", # 1
<add> "talehøreundervisning": "tale-høre-undervisning", # 1
<add> "tandstik": "tandstikker", # 1
<add> "tao": "dao", # 1
<add> "taoisme": "daoisme", # 1
<add> "taoist": "daoist", # 1
<add> "taoistisk": "daoistisk", # 1
<add> "taverne": "taverna", # 1
<add> "teateret": "teatret", # 2
<add> "tekno": "techno", # 1
<add> "temposkifte": "temposkift", # 1
<add> "terrarium": "terrarie", # 1
<add> "territorium": "territorie", # 1
<add> "tesis": "tese", # 1
<add> "tidsstudium": "tidsstudie", # 1
<add> "tipoldefader": "tipoldefar", # 1
<add> "tipoldemoder": "tipoldemor", # 1
<add> "tomatsauce": "tomatsovs", # 1
<add> "tonart": "toneart", # 1
<add> "trafikministerium": "trafikministerie", # 1
<add> "tredve": "tredive", # 1
<add> "tredver": "trediver", # 1
<add> "tredveårig": "trediveårig", # 1
<add> "tredveårs": "trediveårs", # 1
<add> "tredveårsfødselsdag": "trediveårsfødselsdag", # 1
<add> "tredvte": "tredivte", # 1
<add> "tredvtedel": "tredivtedel", # 1
<add> "troldunge": "troldeunge", # 1
<add> "trommestikke": "trommestik", # 1
<add> "trubadur": "troubadour", # 2
<add> "trøstepræmie": "trøstpræmie", # 2
<add> "tummerum": "trummerum", # 1
<add> "tumultuarisk": "tumultarisk", # 1
<add> "tunghørighed": "tunghørhed", # 1
<add> "tus": "tusch", # 2
<add> "tusind": "tusinde", # 2
<add> "tvillingbroder": "tvillingebror", # 1
<add> "tvillingbror": "tvillingebror", # 1
<add> "tvillingebroder": "tvillingebror", # 1
<add> "ubeheftet": "ubehæftet", # 1
<add> "udenrigsministerium": "udenrigsministerie", # 1
<add> "udhulning": "udhuling", # 1
<add> "udslaggivende": "udslagsgivende", # 1
<add> "udspekulert": "udspekuleret", # 1
<add> "udviklingsministerium": "udviklingsministerie", # 1
<add> "uforpligtigende": "uforpligtende", # 1
<add> "uheldvarslende": "uheldsvarslende", # 1
<add> "uimponerthed": "uimponerethed", # 1
<add> "undervisningsministerium": "undervisningsministerie", # 1
<add> "unægtelig": "unægteligt", # 1
<add> "urinale": "urinal", # 1
<add> "uvederheftig": "uvederhæftig", # 1
<add> "vabel": "vable", # 2
<add> "vadi": "wadi", # 1
<add> "vaklevorn": "vakkelvorn", # 1
<add> "vanadin": "vanadium", # 1
<add> "vaselin": "vaseline", # 1
<add> "vederheftig": "vederhæftig", # 1
<add> "vedhefte": "vedhæfte", # 1
<add> "velar": "velær", # 1
<add> "videndeling": "vidensdeling", # 2
<add> "vinkelanførelsestegn": "vinkelanførselstegn", # 1
<add> "vipstjært": "vipstjert", # 1
<add> "vismut": "bismut", # 1
<add> "visvas": "vissevasse", # 1
<add> "voksværk": "vokseværk", # 1
<add> "værtdyr": "værtsdyr", # 1
<add> "værtplante": "værtsplante", # 1
<add> "wienersnitsel": "wienerschnitzel", # 1
<add> "yderliggående": "yderligtgående", # 2
<add> "zombi": "zombie", # 1
<add> "ægbakke": "æggebakke", # 1
<add> "ægformet": "æggeformet", # 1
<add> "ægleder": "æggeleder", # 1
<add> "ækvilibrist": "ekvilibrist", # 2
<add> "æselsøre": "æseløre", # 1
<add> "øjehule": "øjenhule", # 1
<add> "øjelåg": "øjenlåg", # 1
<add> "øjeåbner": "øjenåbner", # 1
<add> "økonomiministerium": "økonomiministerie", # 1
<add> "ørenring": "ørering", # 2
<add> "øvehefte": "øvehæfte" # 1
<add>}
<add>
<add>
<add>NORM_EXCEPTIONS = {}
<add>
<add>for string, norm in _exc.items():
<add> NORM_EXCEPTIONS[string] = norm
<add> NORM_EXCEPTIONS[string.title()] = norm
<ide><path>spacy/tests/lang/da/test_exceptions.py
<ide> def test_da_tokenizer_handles_custom_base_exc(da_tokenizer):
<ide> assert len(tokens) == 8
<ide> assert tokens[6].text == "i"
<ide> assert tokens[7].text == "."
<add>
<add>@pytest.mark.parametrize('text,norm',
<add> [("akvarium", "akvarie"), ("bedstemoder", "bedstemor")])
<add>def test_da_tokenizer_norm_exceptions(da_tokenizer, text, norm):
<add> tokens = da_tokenizer(text)
<add> assert tokens[0].norm_ == norm | 3 |
Go | Go | clean unused variables and fix typo | 229e735837f841dc36564d148803a015f8c6abf0 | <ide><path>libnetwork/controller.go
<ide> type ipamData struct {
<ide>
<ide> type driverTable map[string]*driverData
<ide>
<del>//type networkTable map[string]*network
<del>//type endpointTable map[string]*endpoint
<ide> type ipamTable map[string]*ipamData
<ide> type sandboxTable map[string]*sandbox
<ide>
<ide> type controller struct {
<del> id string
<del> //networks networkTable
<add> id string
<ide> drivers driverTable
<ide> ipamDrivers ipamTable
<ide> sandboxes sandboxTable | 1 |
Text | Text | release notes for the 0.9.8 release | 56eeba0f3c5acc8667147b4534e3c17b8ffe06b5 | <ide><path>CHANGELOG.md
<del># <angular/> 0.9.8 astral-projection (in-progress) #
<add># <angular/> 0.9.8 astral-projection (2010-12-23) #
<add>
<add>### Docs/Getting started
<add>- angular-seed project to get you hacking on an angular apps quickly
<add> https://github.com/angular/angular-seed
<add>
<add>### Performance
<add>- Delegate JSON parsing to native parser (JSON.parse) if available
<ide>
<ide> ### Bug Fixes
<ide> - Ignore input widgets which have no name (issue #153)
<ide>
<add>
<ide> # <angular/> 0.9.7 sonic-scream (2010-12-10) #
<ide>
<ide> ### Bug Fixes | 1 |
Javascript | Javascript | create require.main, remove process.cat() | 1020efb6f7f86e03c0d177bcd6db0acc15da4a08 | <ide><path>src/node.js
<ide> process.assert = function (x, msg) {
<ide> if (!(x)) throw new Error(msg || "assertion error");
<ide> };
<ide>
<del>process.cat = function(location, encoding) {
<del> var url_re = new RegExp("^http:\/\/");
<del> if (url_re.exec(location)) {
<del> throw new Error("process.cat for http urls is temporarally disabled.");
<del> }
<del> //var f = url_re.exec(location) ? process.http.cat : process.fs.cat;
<del> //return f(location, encoding);
<del> return process.fs.cat(location, encoding);
<del>};
<del>
<ide> // From jQuery.extend in the jQuery JavaScript Library v1.3.2
<ide> // Copyright (c) 2009 John Resig
<ide> // Dual licensed under the MIT and GPL licenses.
<ide> Module.prototype.loadObject = function (filename, loadPromise) {
<ide> }, 0);
<ide> };
<ide>
<del>Module.prototype.loadScript = function (filename, loadPromise) {
<del> var self = this;
<del> if (filename.match(/^http:\/\//)) {
<del> var catPromise = new process.Promise();
<del> loadModule('http', this)
<add>function cat (id, loadPromise) {
<add> var promise;
<add>
<add> if (id.match(/^http:\/\//)) {
<add> promise = new process.Promise();
<add> loadModule('http', process.mainModule)
<ide> .addCallback(function(http) {
<del> http.cat(filename)
<add> http.cat(id)
<ide> .addCallback(function(content) {
<del> catPromise.emitSuccess(content);
<add> promise.emitSuccess(content);
<ide> })
<ide> .addErrback(function() {
<del> catPromise.emitError.apply(null, arguments);
<add> promise.emitError.apply(null, arguments);
<ide> });
<ide> })
<ide> .addErrback(function() {
<ide> loadPromise.emitError(new Error("could not load core module \"http\""));
<ide> });
<ide> } else {
<del> var catPromise = process.cat(filename);
<add> promise = process.fs.cat(id);
<ide> }
<ide>
<add> return promise;
<add>}
<add>
<add>Module.prototype.loadScript = function (filename, loadPromise) {
<add> var self = this;
<add> var catPromise = cat(filename, loadPromise);
<add>
<ide> catPromise.addErrback(function () {
<ide> loadPromise.emitError(new Error("Error reading " + filename));
<ide> });
<ide> Module.prototype.loadScript = function (filename, loadPromise) {
<ide>
<ide> require.paths = process.paths;
<ide> require.async = requireAsync;
<add> require.main = process.mainModule;
<ide>
<ide> // create wrapper function
<ide> var wrapper = "var __wrap__ = function (exports, require, module, __filename) { "
<ide> if (process.ARGV[1].charAt(0) != "/" && !/^http:\/\//.exec(process.ARGV[1])) {
<ide> process.ARGV[1] = path.join(cwd, process.ARGV[1]);
<ide> }
<ide>
<del>// Load the root module--the command line argument.
<del>var m = createModule(".");
<add>// Load the main module--the command line argument.
<add>process.mainModule = createModule(".");
<ide> var loadPromise = new process.Promise();
<del>m.load(process.ARGV[1], loadPromise);
<add>process.mainModule.load(process.ARGV[1], loadPromise);
<ide> loadPromise.wait();
<ide>
<ide> }()); // end annonymous namespace | 1 |
Text | Text | add multiple build guide to benchmarking doc | 24388771ea6660ed53ee2f91672af7afaab334b0 | <ide><path>doc/guides/writing-and-running-benchmarks.md
<ide> First build two versions of Node.js, one from the master branch (here called
<ide> `./node-master`) and another with the pull request applied (here called
<ide> `./node-pr-5134`).
<ide>
<add>To run multiple compiled versions in parallel you need to copy the output of the
<add>build: `cp ./out/Release/node ./node-master`. Check out the following example:
<add>
<add>```console
<add>$ git checkout master
<add>$ ./configure && make -j4
<add>$ cp ./out/Release/node ./node-master
<add>
<add>$ git checkout pr-5134
<add>$ ./configure && make -j4
<add>$ cp ./out/Release/node ./node-pr-5134
<add>```
<add>
<ide> The `compare.js` tool will then produce a csv file with the benchmark results.
<ide>
<ide> ```console | 1 |
Java | Java | fix displaymetrics keyboardlistener dependency | 4254e8a0a9a9b2cfbaed6037de360420e6c268e4 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerImpl.java
<ide>
<ide> import javax.annotation.Nullable;
<ide>
<add>import java.lang.reflect.InvocationTargetException;
<add>import java.lang.reflect.Method;
<ide> import java.util.ArrayList;
<ide> import java.util.Collection;
<ide> import java.util.List;
<ide> import android.content.Context;
<ide> import android.content.Intent;
<ide> import android.os.AsyncTask;
<add>import android.os.Build;
<ide> import android.os.Bundle;
<add>import android.util.DisplayMetrics;
<add>import android.view.Display;
<ide> import android.view.View;
<add>import android.view.WindowManager;
<ide>
<ide> import com.facebook.common.logging.FLog;
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
<ide> import com.facebook.react.modules.core.DeviceEventManagerModule;
<ide> import com.facebook.react.uimanager.AppRegistry;
<add>import com.facebook.react.uimanager.DisplayMetricsHolder;
<ide> import com.facebook.react.uimanager.UIImplementationProvider;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> import com.facebook.react.uimanager.ViewManager;
<ide> public T get() throws Exception {
<ide>
<ide> // TODO(9577825): remove this
<ide> ApplicationHolder.setApplication((Application) applicationContext.getApplicationContext());
<add> setDisplayMetrics(applicationContext);
<ide>
<ide> mApplicationContext = applicationContext;
<ide> mJSBundleFile = jsBundleFile;
<ide> private static void initializeSoLoaderIfNecessary(Context applicationContext) {
<ide> SoLoader.init(applicationContext, /* native exopackage */ false);
<ide> }
<ide>
<add> private static void setDisplayMetrics(Context context) {
<add> DisplayMetrics displayMetrics = new DisplayMetrics();
<add> displayMetrics.setTo(context.getResources().getDisplayMetrics());
<add> WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
<add> Display display = wm.getDefaultDisplay();
<add>
<add> // Get the real display metrics if we are using API level 17 or higher.
<add> // The real metrics include system decor elements (e.g. soft menu bar).
<add> //
<add> // See: http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics)
<add> if (Build.VERSION.SDK_INT >= 17){
<add> display.getRealMetrics(displayMetrics);
<add>
<add> } else {
<add> // For 14 <= API level <= 16, we need to invoke getRawHeight and getRawWidth to get the real dimensions.
<add> // Since react-native only supports API level 16+ we don't have to worry about other cases.
<add> //
<add> // Reflection exceptions are rethrown at runtime.
<add> //
<add> // See: http://stackoverflow.com/questions/14341041/how-to-get-real-screen-height-and-width/23861333#23861333
<add> try {
<add> Method mGetRawH = Display.class.getMethod("getRawHeight");
<add> Method mGetRawW = Display.class.getMethod("getRawWidth");
<add> displayMetrics.widthPixels = (Integer) mGetRawW.invoke(display);
<add> displayMetrics.heightPixels = (Integer) mGetRawH.invoke(display);
<add> } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
<add> throw new RuntimeException("Error getting real dimensions for API level < 17", e);
<add> }
<add> }
<add> DisplayMetricsHolder.setDisplayMetrics(displayMetrics);
<add> }
<add>
<ide> /**
<ide> * Trigger react context initialization asynchronously in a background async task. This enables
<ide> * applications to pre-load the application JS, and execute global code before
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
<ide> */
<ide> public class ReactRootView extends SizeMonitoringFrameLayout implements RootView {
<ide>
<del> private final KeyboardListener mKeyboardListener = new KeyboardListener();
<del>
<ide> private @Nullable ReactInstanceManager mReactInstanceManager;
<ide> private @Nullable String mJSModuleName;
<ide> private @Nullable Bundle mLaunchOptions;
<add> private @Nullable KeyboardListener mKeyboardListener;
<ide> private int mTargetTag = -1;
<ide> private final float[] mTargetCoordinates = new float[2];
<ide> private boolean mChildIsHandlingNativeGesture = false;
<ide> public void run() {
<ide> Assertions.assertNotNull(mReactInstanceManager)
<ide> .attachMeasuredRootView(ReactRootView.this);
<ide> mIsAttachedToInstance = true;
<del> getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardListener);
<add> getViewTreeObserver().addOnGlobalLayoutListener(getKeyboardListener());
<ide> }
<ide> });
<ide> }
<ide> protected void onDetachedFromWindow() {
<ide> if (mReactInstanceManager != null && !mAttachScheduled) {
<ide> mReactInstanceManager.detachRootView(this);
<ide> mIsAttachedToInstance = false;
<del> getViewTreeObserver().removeOnGlobalLayoutListener(mKeyboardListener);
<add> getViewTreeObserver().removeOnGlobalLayoutListener(getKeyboardListener());
<ide> }
<ide> }
<ide>
<ide> public void startReactApplication(
<ide> if (mWasMeasured && mIsAttachedToWindow) {
<ide> mReactInstanceManager.attachMeasuredRootView(this);
<ide> mIsAttachedToInstance = true;
<del> getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardListener);
<add> getViewTreeObserver().addOnGlobalLayoutListener(getKeyboardListener());
<ide> } else {
<ide> mAttachScheduled = true;
<ide> }
<ide> public void startReactApplication(
<ide> mWasMeasured = true;
<ide> }
<ide>
<add> private KeyboardListener getKeyboardListener() {
<add> if (mKeyboardListener == null) {
<add> mKeyboardListener = new KeyboardListener();
<add> }
<add> return mKeyboardListener;
<add> }
<add>
<ide> private class KeyboardListener implements ViewTreeObserver.OnGlobalLayoutListener {
<add> private final Rect mVisibleViewArea;
<add>
<ide> private int mKeyboardHeight = 0;
<del> private final Rect mVisibleViewArea = new Rect();
<add>
<add> /* package */ KeyboardListener() {
<add> mVisibleViewArea = new Rect();
<add> }
<ide>
<ide> @Override
<ide> public void onGlobalLayout() {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java
<ide>
<ide> import javax.annotation.Nullable;
<ide>
<del>import java.lang.reflect.InvocationTargetException;
<del>import java.lang.reflect.Method;
<del>import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<del>import android.content.Context;
<del>import android.os.Build;
<del>import android.util.DisplayMetrics;
<del>import android.view.Display;
<del>import android.view.WindowManager;
<del>
<del>import com.facebook.csslayout.CSSLayoutContext;
<del>import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.animation.Animation;
<del>import com.facebook.react.bridge.Arguments;
<ide> import com.facebook.react.bridge.Callback;
<ide> import com.facebook.react.bridge.LifecycleEventListener;
<ide> import com.facebook.react.bridge.OnBatchCompleteListener;
<ide> import com.facebook.react.bridge.ReactMethod;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<del>import com.facebook.react.bridge.WritableArray;
<ide> import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<ide> import com.facebook.systrace.Systrace;
<ide> public UIManagerModule(
<ide> UIImplementation uiImplementation) {
<ide> super(reactContext);
<ide> mEventDispatcher = new EventDispatcher(reactContext);
<del>
<del> DisplayMetrics displayMetrics = getDisplayMetrics();
<del>
<del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics);
<del> mModuleConstants = createConstants(displayMetrics, viewManagerList);
<add> mModuleConstants = createConstants(viewManagerList);
<ide> mUIImplementation = uiImplementation;
<ide>
<ide> reactContext.addLifecycleEventListener(this);
<ide> public void onCatalystInstanceDestroy() {
<ide> mEventDispatcher.onCatalystInstanceDestroyed();
<ide> }
<ide>
<del> private static Map<String, Object> createConstants(
<del> DisplayMetrics displayMetrics,
<del> List<ViewManager> viewManagerList) {
<add> private static Map<String, Object> createConstants(List<ViewManager> viewManagerList) {
<ide> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateUIManagerConstants");
<ide> try {
<del> return UIManagerModuleConstantsHelper.createConstants(
<del> displayMetrics,
<del> viewManagerList);
<add> return UIManagerModuleConstantsHelper.createConstants(viewManagerList);
<ide> } finally {
<ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<ide> }
<ide> public EventDispatcher getEventDispatcher() {
<ide> public void sendAccessibilityEvent(int tag, int eventType) {
<ide> mUIImplementation.sendAccessibilityEvent(tag, eventType);
<ide> }
<del>
<del> private DisplayMetrics getDisplayMetrics() {
<del> Context context = getReactApplicationContext();
<del>
<del> DisplayMetrics displayMetrics = new DisplayMetrics();
<del> displayMetrics.setTo(context.getResources().getDisplayMetrics());
<del> WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
<del> Display display = wm.getDefaultDisplay();
<del>
<del> // Get the real display metrics if we are using API level 17 or higher.
<del> // The real metrics include system decor elements (e.g. soft menu bar).
<del> //
<del> // See: http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics)
<del> if (Build.VERSION.SDK_INT >= 17){
<del> display.getRealMetrics(displayMetrics);
<del>
<del> } else {
<del> // For 14 <= API level <= 16, we need to invoke getRawHeight and getRawWidth to get the real dimensions.
<del> // Since react-native only supports API level 16+ we don't have to worry about other cases.
<del> //
<del> // Reflection exceptions are rethrown at runtime.
<del> //
<del> // See: http://stackoverflow.com/questions/14341041/how-to-get-real-screen-height-and-width/23861333#23861333
<del> try {
<del> Method mGetRawH = Display.class.getMethod("getRawHeight");
<del> Method mGetRawW = Display.class.getMethod("getRawWidth");
<del> displayMetrics.widthPixels = (Integer) mGetRawW.invoke(display);
<del> displayMetrics.heightPixels = (Integer) mGetRawH.invoke(display);
<del> } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
<del> throw new RuntimeException("Error getting real dimensions for API level < 17", e);
<del> }
<del> }
<del>
<del> return displayMetrics;
<del> }
<del>
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide>
<del>import android.text.InputType;
<ide> import android.util.DisplayMetrics;
<ide> import android.view.accessibility.AccessibilityEvent;
<ide> import android.widget.ImageView;
<ide> .build();
<ide> }
<ide>
<del> public static Map<String, Object> getConstants(DisplayMetrics displayMetrics) {
<add> public static Map<String, Object> getConstants() {
<ide> HashMap<String, Object> constants = new HashMap<String, Object>();
<ide> constants.put(
<ide> "UIView",
<ide> public static Map<String, Object> getConstants(DisplayMetrics displayMetrics) {
<ide> "ScaleAspectFill",
<ide> ImageView.ScaleType.CENTER_CROP.ordinal())));
<ide>
<add> DisplayMetrics displayMetrics = DisplayMetricsHolder.getDisplayMetrics();
<ide> constants.put(
<ide> "Dimensions",
<ide> MapBuilder.of(
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstantsHelper.java
<ide>
<ide> package com.facebook.react.uimanager;
<ide>
<del>import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<del>import android.util.DisplayMetrics;
<del>
<ide> import com.facebook.react.common.MapBuilder;
<ide>
<ide> /**
<ide> * {@link UIManagerModuleConstants}.
<ide> * TODO(6845124): Create a test for this
<ide> */
<del> /* package */ static Map<String, Object> createConstants(
<del> DisplayMetrics displayMetrics,
<del> List<ViewManager> viewManagers) {
<del> Map<String, Object> constants = UIManagerModuleConstants.getConstants(displayMetrics);
<add> /* package */ static Map<String, Object> createConstants(List<ViewManager> viewManagers) {
<add> Map<String, Object> constants = UIManagerModuleConstants.getConstants();
<ide> Map bubblingEventTypesConstants = UIManagerModuleConstants.getBubblingEventTypeConstants();
<ide> Map directEventTypesConstants = UIManagerModuleConstants.getDirectEventTypeConstants();
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java
<ide> import android.widget.TextView;
<ide>
<ide> import com.facebook.infer.annotation.Assertions;
<del>import com.facebook.react.bridge.JSApplicationCausedNativeException;
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.bridge.ReactContext;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.common.MapBuilder;
<ide> import com.facebook.react.uimanager.BaseViewManager;
<ide> import com.facebook.react.uimanager.PixelUtil;
<del>import com.facebook.react.uimanager.annotations.ReactProp;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> import com.facebook.react.uimanager.ViewDefaults;
<ide> import com.facebook.react.uimanager.ViewProps;
<add>import com.facebook.react.uimanager.annotations.ReactProp;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<ide> import com.facebook.react.views.text.DefaultStyleValuesUtil;
<ide> import com.facebook.react.views.text.ReactTextUpdate;
<ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import android.util.DisplayMetrics;
<ide> import android.view.View;
<ide>
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<ide> public void customIntGroupProp(View v, int index, Integer value) {
<ide> public void testNativePropsIncludeCorrectTypes() {
<ide> List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ViewManagerUnderTest());
<ide> ReactApplicationContext reactContext = new ReactApplicationContext(RuntimeEnvironment.application);
<add> DisplayMetrics displayMetrics = reactContext.getResources().getDisplayMetrics();
<add> DisplayMetricsHolder.setDisplayMetrics(displayMetrics);
<ide> UIManagerModule uiManagerModule = new UIManagerModule(
<ide> reactContext,
<ide> viewManagers,
<ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import android.util.DisplayMetrics;
<add>
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<ide> import com.facebook.react.common.MapBuilder;
<ide>
<ide> public class UIManagerModuleConstantsTest {
<ide> public void setUp() {
<ide> mReactContext = new ReactApplicationContext(RuntimeEnvironment.application);
<ide> mUIImplementation = mock(UIImplementation.class);
<add>
<add> DisplayMetrics displayMetrics = mReactContext.getResources().getDisplayMetrics();
<add> DisplayMetricsHolder.setDisplayMetrics(displayMetrics);
<ide> }
<ide>
<ide> @Test
<ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleTest.java
<ide> import java.util.List;
<ide>
<ide> import android.graphics.Color;
<add>import android.util.DisplayMetrics;
<ide> import android.view.Choreographer;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide> public Object answer(InvocationOnMock invocation) throws Throwable {
<ide> mReactContext = new ReactApplicationContext(RuntimeEnvironment.application);
<ide> mReactContext.initializeWithInstance(mCatalystInstanceMock);
<ide>
<add> DisplayMetrics displayMetrics = mReactContext.getResources().getDisplayMetrics();
<add> DisplayMetricsHolder.setDisplayMetrics(displayMetrics);
<add>
<ide> UIManagerModule uiManagerModuleMock = mock(UIManagerModule.class);
<ide> when(mCatalystInstanceMock.getNativeModule(UIManagerModule.class))
<ide> .thenReturn(uiManagerModuleMock);
<add>
<ide> }
<ide>
<ide> @Test
<ide><path>ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextTest.java
<ide> import android.os.Build;
<ide> import android.text.Spanned;
<ide> import android.text.TextUtils;
<add>import android.util.DisplayMetrics;
<ide> import android.text.style.AbsoluteSizeSpan;
<ide> import android.view.Choreographer;
<ide> import android.widget.TextView;
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<ide> import com.facebook.react.bridge.SimpleArray;
<ide> import com.facebook.react.bridge.SimpleMap;
<add>import com.facebook.react.uimanager.DisplayMetricsHolder;
<ide> import com.facebook.react.uimanager.ReactChoreographer;
<ide> import com.facebook.react.uimanager.UIImplementation;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> private void executePendingChoreographerCallbacks() {
<ide>
<ide> public UIManagerModule getUIManagerModule() {
<ide> ReactApplicationContext reactContext = ReactTestHelper.createCatalystContextForTest();
<add> DisplayMetrics displayMetrics = reactContext.getResources().getDisplayMetrics();
<add> DisplayMetricsHolder.setDisplayMetrics(displayMetrics);
<ide> List<ViewManager> viewManagers = Arrays.asList(
<ide> new ViewManager[] {
<ide> new ReactTextViewManager(),
<ide><path>ReactAndroid/src/test/java/com/facebook/react/views/textinput/TextInputTest.java
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide>
<add>import android.util.DisplayMetrics;
<ide> import android.view.Choreographer;
<ide> import android.widget.EditText;
<ide>
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<ide> import com.facebook.react.bridge.SimpleArray;
<ide> import com.facebook.react.bridge.SimpleMap;
<add>import com.facebook.react.uimanager.DisplayMetricsHolder;
<ide> import com.facebook.react.uimanager.ReactChoreographer;
<ide> import com.facebook.react.uimanager.UIImplementation;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> public UIManagerModule getUIManagerModule() {
<ide> new ViewManager[] {
<ide> new ReactTextInputManager(),
<ide> });
<add> DisplayMetrics displayMetrics = reactContext.getResources().getDisplayMetrics();
<add> DisplayMetricsHolder.setDisplayMetrics(displayMetrics);
<ide> UIManagerModule uiManagerModule = new UIManagerModule(
<ide> reactContext,
<ide> viewManagers, | 11 |
Text | Text | guide solution for add document elements with d3 | 01de9ca6f66c6bc172c3a2c2233d0b73cfd7a9cb | <ide><path>guide/english/certifications/data-visualization/data-visualization-with-d3/add-document-elements-with-d3/index.md
<ide> title: Add Document Elements with D3
<ide> ---
<ide> ## Add Document Elements with D3
<add> Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program  and write your own code 
<ide>
<del>[This challenge](https://learn.freecodecamp.org/data-visualization/data-visualization-with-d3/add-document-elements-with-d3) introduces three core methods of **d3.js**:
<del>* The `d3.select()` method
<del>* The `d3.append()` method
<del>* The `d3.text()` method
<add>### Problem Explanation:
<ide>
<del>### The select() Method
<del>The select method is crucial, because it tells the browser where to put any _d3.js_ code written afterwords. In _Javascript_, you would write `document.getElementById('#myId');`. In _d3.js_, you would write `d3.select('#myId')`.
<add>This challenge can be completed by referring to the example in the description and modifying the parameters to those that are in the instructions.
<ide>
<del>### The append() method
<del>The append method is similar to _jsx_ in _react_, markup in _html_ or the `appendChild()` method in _Javascript_. For Example, writing `d3.select('#myId').append('p')` would be the same as writing `...<p></p>...`
<add>#### Relevant Links
<ide>
<del>### The text() method
<del>The text method is the third step in applying content to a page using _d3.js_. We have selected an element in our html and added an element. Now, we need to fill the empty element. We do that like this: `d3.select('#myId').append('p').text('sup World!')`. This is akin to writing `...<p>'sup World!</p>...` in html.
<add>From the official D3 Documentation:
<add>* [Select](https://github.com/d3/d3-selection/blob/master/README.md#select)
<add>* [Append](https://github.com/d3/d3-selection/blob/master/README.md#selection_append)
<add>* [Text](https://github.com/d3/d3-selection/blob/master/README.md#selection_text)
<ide>
<del>### The Solution
<del>Add the folowing code to your editor:
<del>```
<del>d3.select('body')
<del> .append('h1')
<del> .text('Learning D3');
<add>##  Hint: 1
<add>
<add>* You will need to use `d3` to reference the D3 object and chain your methods
<add>
<add>> _try to solve the problem now_
<add>
<add>##  Hint: 2
<add>
<add>* To chain methods together, simply start the next one directly after the previous one has ended. The example shows this on separate lines to improve readability. Make sure not to put a semicolon after any of the methods or the code will break.
<add>
<add>> _try to solve the problem now_
<add>
<add>##  Hint: 3
<add>
<add>* The example shows exactly what is needed, all that needs to be changed are the parameters. E.g. replace 'ul' in the `select` method with 'body'.
<add>
<add>> _try to solve the problem now_
<add>
<add>## Spoiler Alert!
<add>
<add>**Solution ahead!**
<add>
<add>##  Basic Code Solution:
<add>```javascript
<add><body>
<add> <script>
<add>
<add> d3.select('body')
<add> .append('h1')
<add> .text('Learning D3');
<add>
<add> </script>
<add></body>
<ide> ```
<add>
<add># Code Explanation:
<add>
<add>* `d3` targets the D3 object
<add>* `.select('body')` uses the D3 `select` method to target the `body` HTML node
<add>* `.append('h1')` uses the D3 `append` method to "append" or attach an `h1` element to the `body` element
<add>* `.text('Learning D3')` uses the D3 `text` method to change the text of the `h1` element to 'Learning D3'
<add>* The semicolon ends the method chain, but is not required
<add>* Note that the methods are on separate lines for improved readability, as d3 method chains can get quite lengthy
<add>
<add>
<add>##  NOTES FOR CONTRIBUTIONS:
<add>
<add>*  **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
<add>* Add an explanation of your solution.
<add>* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. 
<add>* Please add your username only if you have added any **relevant main contents**. ( **_DO NOT_** _remove any existing usernames_)
<add>
<add>> See  <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.
<ide>\ No newline at end of file | 1 |
Javascript | Javascript | remove lazy invokation of segments | fb3f63f1ab6e9ebf25ddce74a19d975ef410d4f6 | <ide><path>packages/react-server/src/ReactFlightServer.js
<ide> type ReactModelObject = {+[key: string]: ReactModel};
<ide>
<ide> type Segment = {
<ide> id: number,
<del> query: () => ReactModel,
<add> model: ReactModel,
<ide> ping: () => void,
<ide> };
<ide>
<ide> export function createRequest(
<ide> },
<ide> };
<ide> request.pendingChunks++;
<del> const rootSegment = createSegment(request, () => model);
<add> const rootSegment = createSegment(request, model);
<ide> pingedSegments.push(rootSegment);
<ide> return request;
<ide> }
<ide> function pingSegment(request: Request, segment: Segment): void {
<ide> }
<ide> }
<ide>
<del>function createSegment(request: Request, query: () => ReactModel): Segment {
<add>function createSegment(request: Request, model: ReactModel): Segment {
<ide> const id = request.nextChunkId++;
<ide> const segment = {
<ide> id,
<del> query,
<add> model,
<ide> ping: () => pingSegment(request, segment),
<ide> };
<ide> return segment;
<ide> export function resolveModelToJSON(
<ide> if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
<ide> // Something suspended, we'll need to create a new segment and resolve it later.
<ide> request.pendingChunks++;
<del> const newSegment = createSegment(request, () => value);
<add> const newSegment = createSegment(request, value);
<ide> const ping = newSegment.ping;
<ide> x.then(ping, ping);
<ide> return serializeByRefID(newSegment.id);
<ide> function emitSymbolChunk(request: Request, id: number, name: string): void {
<ide> }
<ide>
<ide> function retrySegment(request: Request, segment: Segment): void {
<del> const query = segment.query;
<del> let value;
<ide> try {
<del> value = query();
<add> let value = segment.model;
<ide> while (
<ide> typeof value === 'object' &&
<ide> value !== null &&
<ide> function retrySegment(request: Request, segment: Segment): void {
<ide> // Attempt to render the server component.
<ide> // Doing this here lets us reuse this same segment if the next component
<ide> // also suspends.
<del> segment.query = () => value;
<add> segment.model = value;
<ide> value = attemptResolveElement(
<ide> element.type,
<ide> element.key, | 1 |
Javascript | Javascript | add missing semicolon in pcdloader | abf57981b7af55d82b1d415d555b5ec68d543609 | <ide><path>examples/js/loaders/PCDLoader.js
<ide> Object.assign( THREE.PCDLoader.prototype, THREE.EventDispatcher.prototype, {
<ide>
<ide> }
<ide>
<del> PCDheader.offset = {}
<add> PCDheader.offset = {};
<ide> var sizeSum = 0;
<ide> for ( var i = 0; i < PCDheader.fields.length; i ++ ) {
<ide> | 1 |
Python | Python | fix marian conversion script | f0c00d8ca90d5a954aeccfb614a9f4ebf30b92d4 | <ide><path>src/transformers/models/marian/convert_marian_to_pytorch.py
<ide> def __init__(self, source_dir, eos_token_id=0):
<ide> self.state_dict = dict(self.state_dict)
<ide> if cfg["tied-embeddings-all"]:
<ide> cfg["tied-embeddings-src"] = True
<add> cfg["tied-embeddings"] = True
<ide> self.share_encoder_decoder_embeddings = cfg["tied-embeddings-src"]
<ide>
<ide> # create the tokenizer here because we need to know the eos_token_id
<ide> def __init__(self, source_dir, eos_token_id=0):
<ide> decoder_ffn_dim=cfg["transformer-dim-ffn"],
<ide> encoder_ffn_dim=cfg["transformer-dim-ffn"],
<ide> d_model=cfg["dim-emb"],
<del> activation_function=cfg["transformer-aan-activation"],
<add> activation_function=cfg["transformer-ffn-activation"],
<ide> pad_token_id=self.pad_token_id,
<ide> eos_token_id=eos_token_id,
<ide> forced_eos_token_id=eos_token_id, | 1 |
Ruby | Ruby | fix clear_all_connections! deprecation warning | 25ae059d1653cac0e909fb014396290a22b4fa41 | <ide><path>actioncable/test/subscription_adapter/postgresql_test.rb
<ide> def setup
<ide> def teardown
<ide> super
<ide>
<del> ActiveRecord::Base.clear_all_connections!
<add> ActiveRecord::Base.connection.clear_all_connections!
<ide> end
<ide>
<ide> def cable_config | 1 |
Javascript | Javascript | fix the arguments order in `assert.strictequal` | 87d0aa8686be2f22af55227ff573f9b933436fd2 | <ide><path>test/parallel/test-fs-read-stream-fd-leak.js
<ide> function testLeak(endFn, callback) {
<ide> }
<ide>
<ide> assert.strictEqual(
<del> 0,
<ide> openCount,
<add> 0,
<ide> `no leaked file descriptors using ${endFn}() (got ${openCount})`
<ide> );
<ide> | 1 |
Java | Java | add @nonnull to the methods of emitter | b41ac3b61c6fa5191f8ad19e03f6e5457dbcc28f | <ide><path>src/main/java/io/reactivex/Emitter.java
<ide> */
<ide> package io.reactivex;
<ide>
<add>import io.reactivex.annotations.NonNull;
<add>
<ide> /**
<ide> * Base interface for emitting signals in a push-fashion in various generator-like source
<ide> * operators (create, generate).
<ide> * Signal a normal value.
<ide> * @param value the value to signal, not null
<ide> */
<del> void onNext(T value);
<add> void onNext(@NonNull T value);
<ide>
<ide> /**
<ide> * Signal a Throwable exception.
<ide> * @param error the Throwable to signal, not null
<ide> */
<del> void onError(Throwable error);
<add> void onError(@NonNull Throwable error);
<ide>
<ide> /**
<ide> * Signal a completion. | 1 |
Python | Python | reverse the type checks before `convert_to_tensor` | 9854e7b534ad6c05f2fe949b7f7969a4a12eac64 | <ide><path>keras/layers/preprocessing/index_lookup.py
<ide> def _lookup_table_from_file(self, filename):
<ide> return tf.lookup.StaticHashTable(initializer, self._default_value)
<ide>
<ide> def _standardize_inputs(self, inputs, dtype):
<del> if isinstance(inputs, (list, tuple, np.ndarray)):
<del> inputs = tf.convert_to_tensor(inputs)
<del> if inputs.dtype != dtype:
<add> if not isinstance(inputs, (tf.Tensor, tf.RaggedTensor, tf.SparseTensor)):
<add> inputs = tf.convert_to_tensor(inputs, dtype)
<add> elif inputs.dtype != dtype:
<ide> inputs = tf.cast(inputs, dtype)
<ide> return inputs
<ide>
<ide><path>keras/layers/preprocessing/index_lookup_test.py
<ide> def word_gen():
<ide> layer.adapt(batched_ds)
<ide>
<ide>
<add>class ArrayLike:
<add>
<add> def __init__(self, values):
<add> self.values = values
<add>
<add> def __array__(self):
<add> return np.array(self.values)
<add>
<add>
<ide> @keras_parameterized.run_all_keras_modes(always_skip_v1=True)
<ide> class IndexLookupOutputTest(keras_parameterized.TestCase,
<ide> preprocessing_test_utils.PreprocessingLayerTest):
<ide> def _write_to_temp_file(self, file_name, vocab_list):
<ide> writer.close()
<ide> return vocab_path
<ide>
<del> def test_int_output(self):
<add> @parameterized.named_parameters(
<add> ("array_2d", [None],
<add> np.array([["earth", "wind", "and", "fire"],
<add> ["fire", "and", "earth", "michigan"]]),
<add> [[2, 3, 4, 5],
<add> [5, 4, 2, 1]]),
<add> ("array_1d", [],
<add> np.array(["earth", "wind", "and", "fire"]),
<add> [2, 3, 4, 5]),
<add> ("array_0", [],
<add> tf.constant("earth"),
<add> 2),
<add> ("str", [],
<add> "earth",
<add> 2),
<add> ("list", [None],
<add> ["earth", "wind", "and", "fire"],
<add> [2, 3, 4, 5]),
<add> ("array_like", [None],
<add> ArrayLike(["earth", "wind", "and", "fire"]),
<add> [2, 3, 4, 5]),
<add> ) # pyformat: disable
<add> def test_int_output(self, shape, input_array, expected_output):
<ide> vocab_data = ["earth", "wind", "and", "fire"]
<del> input_array = np.array([["earth", "wind", "and", "fire"],
<del> ["fire", "and", "earth", "michigan"]])
<del> expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]
<ide>
<del> input_data = keras.Input(shape=(None,), dtype=tf.string)
<ide> layer = index_lookup.IndexLookup(
<ide> max_tokens=None,
<ide> num_oov_indices=1,
<ide> mask_token="",
<ide> oov_token="[OOV]",
<ide> dtype=tf.string)
<ide> layer.set_vocabulary(vocab_data)
<del> int_data = layer(input_data)
<del> model = keras.Model(inputs=input_data, outputs=int_data)
<del> output_dataset = model.predict(input_array)
<add> output_dataset = layer(input_array)
<ide> self.assertAllEqual(expected_output, output_dataset)
<ide>
<del> def test_int_output_rank_one(self):
<del> vocab_data = ["earth", "wind", "and", "fire"]
<del> input_data = np.array(["earth", "wind", "and", "fire"])
<del> expected_output = [2, 3, 4, 5]
<del>
<del> inputs = keras.Input(shape=(None,), dtype=tf.string)
<del> layer = index_lookup.IndexLookup(
<del> max_tokens=None,
<del> num_oov_indices=1,
<del> mask_token="",
<del> oov_token="[OOV]",
<del> dtype=tf.string)
<del> layer.set_vocabulary(vocab_data)
<add> # Again in a keras.Model
<add> inputs = keras.Input(shape=shape, dtype=tf.string)
<ide> outputs = layer(inputs)
<ide> model = keras.Model(inputs=inputs, outputs=outputs)
<del> output_dataset = model(input_data)
<del> self.assertAllEqual(expected_output, output_dataset)
<add> output_dataset = model(tf.constant(input_array))
<ide>
<del> def test_int_output_rank_zero(self):
<del> vocab_data = ["earth", "wind", "and", "fire"]
<del> input_data = tf.constant("earth")
<del> expected_output = 2
<del>
<del> inputs = keras.Input(shape=(), dtype=tf.string)
<del> layer = index_lookup.IndexLookup(
<del> max_tokens=None,
<del> num_oov_indices=1,
<del> mask_token="",
<del> oov_token="[OOV]",
<del> dtype=tf.string)
<del> layer.set_vocabulary(vocab_data)
<del> outputs = layer(inputs)
<del> model = keras.Model(inputs=inputs, outputs=outputs)
<del> output_dataset = model(input_data)
<ide> self.assertAllEqual(expected_output, output_dataset)
<ide>
<ide> def test_int_output_shape(self): | 2 |
Ruby | Ruby | add a skip for failing test | 3844854af109fb9eee75c90bacf8bf87eb2bf968 | <ide><path>actionpack/test/controller/render_test.rb
<ide> def test_dynamic_render
<ide> end
<ide>
<ide> def test_permitted_dynamic_render_file_hash
<add> skip "FIXME: this test passes on 4-2-stable but not master. Why?"
<ide> assert File.exist?(File.join(File.dirname(__FILE__), '../../test/abstract_unit.rb'))
<del> response = get :dynamic_render_permit, { id: { file: '../\\../test/abstract_unit.rb' } }
<add> response = get :dynamic_render_permit, params: { id: { file: '../\\../test/abstract_unit.rb' } }
<ide> assert_equal File.read(File.join(File.dirname(__FILE__), '../../test/abstract_unit.rb')),
<ide> response.body
<ide> end | 1 |
Javascript | Javascript | add initialvalues to the form | 17a2bae5b92362fb0ef841f6fa220b9f69970d6f | <ide><path>client/src/components/settings/Certification.js
<ide> import { projectMap, legacyProjectMap } from '../../resources/certProjectMap';
<ide> import SectionHeader from './SectionHeader';
<ide> import SolutionViewer from './SolutionViewer';
<ide> import { FullWidthRow, Spacer } from '../helpers';
<del>// import { Form } from '../formHelpers';
<add>import { Form } from '../formHelpers';
<add>
<ide> import { maybeUrlRE } from '../../utils';
<ide>
<ide> import './certification.css';
<ide> class CertificationSettings extends Component {
<ide> super(props);
<ide>
<ide> this.state = { ...initialState };
<add> this.handleSubmit = this.handleSubmit.bind(this);
<ide> }
<ide>
<ide> createHandleLinkButtonClick = to => e => {
<ide> class CertificationSettings extends Component {
<ide> );
<ide>
<ide> renderProjectsFor = (certName, isCert) => {
<del> console.log(certName);
<del> console.log(this.getUserIsCertMap());
<del> console.log(this.getUserIsCertMap()[certName]);
<ide> const { username, isHonest, createFlashMessage, verifyCert } = this.props;
<ide> const { superBlock } = first(projectMap[certName]);
<ide> const certLocation = `/certification/${username}/${superBlock}`;
<ide> class CertificationSettings extends Component {
<ide> ]);
<ide> };
<ide>
<del> renderLegacyCertifications = certName => (
<del> <FullWidthRow key={certName}>
<del> <Spacer />
<del> <h3>{certName}</h3>
<del> <Table>
<del> <thead>
<del> <tr>
<del> <th>Project Name</th>
<del> <th>Solution</th>
<del> </tr>
<del> </thead>
<del> <tbody>
<del> {this.renderLegacyProjectsFor(
<del> certName,
<del> this.getUserIsCertMap()[certName]
<del> )}
<del> </tbody>
<del> </Table>
<del> </FullWidthRow>
<del> );
<add> // legacy projects rendering
<add>
<add> handleSubmit() {
<add> console.log('handle');
<add> }
<add>
<add> renderLegacyCertifications = certName => {
<add> const challengeTitles = legacyProjectMap[certName].map(item => item.title);
<add> const { completedChallenges } = this.props;
<add>
<add> const initialObject = {};
<add> let fullform = 0;
<add> legacyProjectMap[certName].forEach(element => {
<add> let completedProject = find(completedChallenges, function(challenge) {
<add> return challenge['id'] === element['id'];
<add> });
<add>
<add> if (!completedProject) {
<add> initialObject[element.title] = '';
<add> } else {
<add> initialObject[element.title] = completedProject.solution;
<add> fullform++;
<add> }
<add> });
<add>
<add> console.log(fullform);
<add>
<add> return (
<add> <FullWidthRow key={certName}>
<add> <Spacer />
<add> <h3>{certName}</h3>
<add> <Form
<add> buttonText={'Claim Certification'}
<add> formFields={challengeTitles}
<add> id={certName}
<add> initialValues={{
<add> ...initialObject
<add> }}
<add> submit={this.handleSubmit}
<add> />
<add> </FullWidthRow>
<add> );
<add> };
<ide>
<ide> renderLegacyProjectsFor = (certName, isCert) => {
<del> console.log(certName);
<del> console.log(this.getUserIsCertMap()[certName]);
<ide> const { username, isHonest, createFlashMessage, verifyCert } = this.props;
<ide> const { superBlock } = first(legacyProjectMap[certName]);
<ide> const certLocation = `/certification/${username}/${superBlock}`;
<ide> class CertificationSettings extends Component {
<ide> 'honesty policy'
<ide> });
<ide> };
<add>
<ide> return legacyProjectMap[certName]
<ide> .map(({ title, id }) => (
<ide> <tr className='project-row' key={id}> | 1 |
Text | Text | add contributing.md to keras_nlp | e7ccb0b15feec540e41ff4a1a51ead14b032918c | <ide><path>official/nlp/keras_nlp/contributing.md
<add>## Contributing to KerasNLP
<add>
<add>Patches to KerasNLP are welcome!
<add>
<add>The source-of-truth repository lives under
<add>[TF Model Garden NLP](https://github.com/tensorflow/models/official/nlp/keras_nlp),
<add>and is mirrored as a read-only repository under
<add>[keras-team/keras-nlp](https://github.com/keras-team/keras-nlp).
<add>Contributions should be made as PRs to the TF Model Garden repository.
<add>This is to ensure the codebase is rigorously tested with state-of-art models
<add>on different accelerators.
<add>In the long run, we will move development to the current repository `keras-team/keras-nlp`.
<add>
<add>## :heavy_check_mark: Contributor checklist
<add>
<add>1. Ensure you have signed the [Contributor License Agreement](https://cla.developers.google.com/about/google-individual?csw=1).
<add> * All code contributors are required to sign a Contributor License Agreement.
<add> * Please read this [troubleshooting guide](Contributor-License-Agreements#troubleshooting-clas)
<add> if you encounter an issue.
<add>2. Please review the [contribution guidelines](https://github.com/tensorflow/models/wiki/How-to-contribute).
<add>3. Check if your changes are consistent with the [TensorFlow coding style](https://www.tensorflow.org/community/contribute/code_style). | 1 |
Go | Go | fix testbuildaddbadlinks for windows | d0dc14e5d6fe5f8ef9d4a8a8dc95fa087439a5b4 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> import (
<ide> "path/filepath"
<ide> "reflect"
<ide> "regexp"
<add> "runtime"
<ide> "strconv"
<ide> "strings"
<ide> "syscall"
<ide> func TestBuildAddBadLinks(t *testing.T) {
<ide> }
<ide> defer os.RemoveAll(tempDir)
<ide>
<del> symlinkTarget := fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
<add> var symlinkTarget string
<add> if runtime.GOOS == "windows" {
<add> var driveLetter string
<add> if abs, err := filepath.Abs(tempDir); err != nil {
<add> t.Fatal(err)
<add> } else {
<add> driveLetter = abs[:1]
<add> }
<add> tempDirWithoutDrive := tempDir[2:]
<add> symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive)
<add> } else {
<add> symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
<add> }
<add>
<add> t.Logf("***=== %s", symlinkTarget)
<ide> tarPath := filepath.Join(ctx.Dir, "links.tar")
<ide> nonExistingFile := filepath.Join(tempDir, targetFile)
<ide> fooPath := filepath.Join(ctx.Dir, targetFile) | 1 |
Mixed | PHP | add tests, update changelog, increase readability | 206aae2a7a5c97a7e0af3bed8e842635504de306 | <ide><path>CHANGELOG-5.5.md
<ide> ### Events
<ide> - ⚠️ Removed calling queue method on handlers ([0360cb1](https://github.com/laravel/framework/commit/0360cb1c6b71ec89d406517b19d1508511e98fb5), [ec96979](https://github.com/laravel/framework/commit/ec969797878f2c731034455af2397110732d14c4), [d9be4bf](https://github.com/laravel/framework/commit/d9be4bfe0367a8e07eed4931bdabf135292abb1b))
<ide>
<add>### Filesystem
<add>- ⚠️ Made `Storage::files()` work like `Storage::allFiles()` ([#18874](https://github.com/laravel/framework/pull/18874))
<add>
<ide> ### Helpers
<ide> - Added `throw_if()` and `throw_unless()` helpers ([18bb4df](https://github.com/laravel/framework/commit/18bb4dfc77c7c289e9b40c4096816ebeff1cd843))
<ide> - Added `dispatch_now()` helper function ([#18668](https://github.com/laravel/framework/pull/18668), [61f2e7b](https://github.com/laravel/framework/commit/61f2e7b4106f8eb0b79603d9792426f7c6a6d273))
<ide><path>src/Illuminate/Filesystem/Filesystem.php
<ide> public function glob($pattern, $flags = 0)
<ide> * Get an array of all files in a directory.
<ide> *
<ide> * @param string $directory
<add> * @param bool $ignoreDotFiles
<ide> * @return array
<ide> */
<del> public function files($directory, $hidden = false)
<add> public function files($directory, $ignoreDotFiles = false)
<ide> {
<del> return iterator_to_array(Finder::create()->files()->ignoreDotFiles(! $hidden)->in($directory)->depth(0), false);
<add> return iterator_to_array(
<add> Finder::create()->files()->ignoreDotFiles(! $ignoreDotFiles)->in($directory)->depth(0),
<add> false
<add> );
<ide> }
<ide>
<ide> /**
<ide> * Get all of the files from the given directory (recursive).
<ide> *
<ide> * @param string $directory
<del> * @param bool $hidden
<add> * @param bool $ignoreDotFiles
<ide> * @return array
<ide> */
<del> public function allFiles($directory, $hidden = false)
<add> public function allFiles($directory, $ignoreDotFiles = false)
<ide> {
<del> return iterator_to_array(Finder::create()->files()->ignoreDotFiles(! $hidden)->in($directory), false);
<add> return iterator_to_array(
<add> Finder::create()->files()->ignoreDotFiles(! $ignoreDotFiles)->in($directory),
<add> false
<add> );
<ide> }
<ide>
<ide> /**
<ide><path>tests/Filesystem/FilesystemTest.php
<ide> public function testIsFileChecksFilesProperly()
<ide> $this->assertTrue($filesystem->isFile($this->tempDir.'/foo/foo.txt'));
<ide> $this->assertFalse($filesystem->isFile($this->tempDir.'./foo'));
<ide> }
<add>
<add> public function testFilesMethodReturnsFileInfoObjects()
<add> {
<add> mkdir($this->tempDir.'/foo');
<add> file_put_contents($this->tempDir.'/foo/1.txt', '1');
<add> file_put_contents($this->tempDir.'/foo/2.txt', '2');
<add> mkdir($this->tempDir.'/foo/bar');
<add> $files = new Filesystem();
<add> foreach ($files->files($this->tempDir.'/foo') as $file) {
<add> $this->assertInstanceOf(\SplFileInfo::class, $file);
<add> }
<add> unset($files);
<add> }
<add>
<add> public function testAllFilesReturnsFileInfoObjects()
<add> {
<add> file_put_contents($this->tempDir.'/foo.txt', 'foo');
<add> file_put_contents($this->tempDir.'/bar.txt', 'bar');
<add> $files = new Filesystem();
<add> $allFiles = [];
<add> foreach ($files->allFiles($this->tempDir) as $file) {
<add> $this->assertInstanceOf(\SplFileInfo::class, $file);
<add> }
<add> }
<ide> } | 3 |
Javascript | Javascript | remove internal only error checking | 4de31d517f75dd91e64f71df7cc9d2baa3e435c2 | <ide><path>lib/async_hooks.js
<ide> const {
<ide>
<ide> const {
<ide> ERR_ASYNC_CALLBACK,
<add> ERR_ASYNC_TYPE,
<ide> ERR_INVALID_ASYNC_ID
<ide> } = require('internal/errors').codes;
<ide> const { validateString } = require('internal/validators');
<ide> const {
<ide> emitBefore,
<ide> emitAfter,
<ide> emitDestroy,
<add> enabledHooksExist,
<ide> initHooksExist,
<ide> } = internal_async_hooks;
<ide>
<ide> class AsyncResource {
<ide> this[trigger_async_id_symbol] = triggerAsyncId;
<ide>
<ide> if (initHooksExist()) {
<add> if (enabledHooksExist() && type.length === 0) {
<add> throw new ERR_ASYNC_TYPE(type);
<add> }
<add>
<ide> emitInit(asyncId, type, triggerAsyncId, this);
<ide> }
<ide>
<ide><path>lib/internal/async_hooks.js
<ide> const {
<ide> Error,
<ide> FunctionPrototypeBind,
<del> NumberIsSafeInteger,
<ide> ObjectDefineProperty,
<ide> Symbol,
<ide> } = primordials;
<ide>
<del>const {
<del> ERR_ASYNC_TYPE,
<del> ERR_INVALID_ASYNC_ID
<del>} = require('internal/errors').codes;
<del>
<ide> const async_wrap = internalBinding('async_wrap');
<ide> /* async_hook_fields is a Uint32Array wrapping the uint32_t array of
<ide> * Environment::AsyncHooks::fields_[]. Each index tracks the number of active
<ide> function fatalError(e) {
<ide> }
<ide>
<ide>
<del>function validateAsyncId(asyncId, type) {
<del> // Skip validation when async_hooks is disabled
<del> if (async_hook_fields[kCheck] <= 0) return;
<del>
<del> if (!NumberIsSafeInteger(asyncId) || asyncId < -1) {
<del> fatalError(new ERR_INVALID_ASYNC_ID(type, asyncId));
<del> }
<del>}
<del>
<ide> // Emit From Native //
<ide>
<ide> // Used by C++ to call all init() callbacks. Because some state can be setup
<ide> function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) {
<ide> }
<ide> }
<ide>
<add>function enabledHooksExist() {
<add> return async_hook_fields[kCheck] > 0;
<add>}
<ide>
<ide> function initHooksExist() {
<ide> return async_hook_fields[kInit] > 0;
<ide> function destroyHooksExist() {
<ide>
<ide>
<ide> function emitInitScript(asyncId, type, triggerAsyncId, resource) {
<del> validateAsyncId(asyncId, 'asyncId');
<del> if (triggerAsyncId !== null)
<del> validateAsyncId(triggerAsyncId, 'triggerAsyncId');
<del> if (async_hook_fields[kCheck] > 0 &&
<del> (typeof type !== 'string' || type.length <= 0)) {
<del> throw new ERR_ASYNC_TYPE(type);
<del> }
<del>
<ide> // Short circuit all checks for the common case. Which is that no hooks have
<ide> // been set. Do this to remove performance impact for embedders (and core).
<ide> if (async_hook_fields[kInit] === 0)
<ide> return;
<ide>
<del> // This can run after the early return check b/c running this function
<del> // manually means that the embedder must have used getDefaultTriggerAsyncId().
<ide> if (triggerAsyncId === null) {
<ide> triggerAsyncId = getDefaultTriggerAsyncId();
<ide> }
<ide> function emitInitScript(asyncId, type, triggerAsyncId, resource) {
<ide>
<ide>
<ide> function emitBeforeScript(asyncId, triggerAsyncId) {
<del> // Validate the ids. An id of -1 means it was never set and is visible on the
<del> // call graph. An id < -1 should never happen in any circumstance. Throw
<del> // on user calls because async state should still be recoverable.
<del> validateAsyncId(asyncId, 'asyncId');
<del> validateAsyncId(triggerAsyncId, 'triggerAsyncId');
<del>
<ide> pushAsyncIds(asyncId, triggerAsyncId);
<ide>
<ide> if (async_hook_fields[kBefore] > 0)
<ide> function emitBeforeScript(asyncId, triggerAsyncId) {
<ide>
<ide>
<ide> function emitAfterScript(asyncId) {
<del> validateAsyncId(asyncId, 'asyncId');
<del>
<ide> if (async_hook_fields[kAfter] > 0)
<ide> emitAfterNative(asyncId);
<ide>
<ide> function emitAfterScript(asyncId) {
<ide>
<ide>
<ide> function emitDestroyScript(asyncId) {
<del> validateAsyncId(asyncId, 'asyncId');
<del>
<ide> // Return early if there are no destroy callbacks, or invalid asyncId.
<ide> if (async_hook_fields[kDestroy] === 0 || asyncId <= 0)
<ide> return;
<ide> function popAsyncIds(asyncId) {
<ide> const stackLength = async_hook_fields[kStackLength];
<ide> if (stackLength === 0) return false;
<ide>
<del> if (async_hook_fields[kCheck] > 0 &&
<del> async_id_fields[kExecutionAsyncId] !== asyncId) {
<add> if (enabledHooksExist() && async_id_fields[kExecutionAsyncId] !== asyncId) {
<ide> // Do the same thing as the native code (i.e. crash hard).
<ide> return popAsyncIds_(asyncId);
<ide> }
<ide> module.exports = {
<ide> getOrSetAsyncId,
<ide> getDefaultTriggerAsyncId,
<ide> defaultTriggerAsyncIdScope,
<add> enabledHooksExist,
<ide> initHooksExist,
<ide> afterHooksExist,
<ide> destroyHooksExist,
<ide><path>test/async-hooks/test-emit-before-after.js
<ide>
<ide> const common = require('../common');
<ide> const assert = require('assert');
<del>const spawnSync = require('child_process').spawnSync;
<ide> const async_hooks = require('internal/async_hooks');
<ide> const initHooks = require('./init-hooks');
<ide>
<del>if (!common.isMainThread)
<del> common.skip('Worker bootstrapping works differently -> different async IDs');
<del>
<del>switch (process.argv[2]) {
<del> case 'test_invalid_async_id':
<del> async_hooks.emitBefore(-2, 1);
<del> return;
<del> case 'test_invalid_trigger_id':
<del> async_hooks.emitBefore(1, -2);
<del> return;
<del>}
<del>assert.ok(!process.argv[2]);
<del>
<del>
<del>const c1 = spawnSync(process.execPath, [
<del> '--expose-internals', __filename, 'test_invalid_async_id'
<del>]);
<del>assert.strictEqual(
<del> c1.stderr.toString().split(/[\r\n]+/g)[0],
<del> 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid asyncId value: -2');
<del>assert.strictEqual(c1.status, 1);
<del>
<del>const c2 = spawnSync(process.execPath, [
<del> '--expose-internals', __filename, 'test_invalid_trigger_id'
<del>]);
<del>assert.strictEqual(
<del> c2.stderr.toString().split(/[\r\n]+/g)[0],
<del> 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: -2');
<del>assert.strictEqual(c2.status, 1);
<del>
<ide> const expectedId = async_hooks.newAsyncId();
<ide> const expectedTriggerId = async_hooks.newAsyncId();
<ide> const expectedType = 'test_emit_before_after_type';
<ide> const expectedType = 'test_emit_before_after_type';
<ide> async_hooks.emitBefore(expectedId, expectedTriggerId);
<ide> async_hooks.emitAfter(expectedId);
<ide>
<add>const chkBefore = common.mustCall((id) => assert.strictEqual(id, expectedId));
<add>const chkAfter = common.mustCall((id) => assert.strictEqual(id, expectedId));
<add>
<add>const checkOnce = (fn) => {
<add> let called = false;
<add> return (...args) => {
<add> if (called) return;
<add>
<add> called = true;
<add> fn(...args);
<add> };
<add>};
<add>
<ide> initHooks({
<del> onbefore: common.mustCall((id) => assert.strictEqual(id, expectedId)),
<del> onafter: common.mustCall((id) => assert.strictEqual(id, expectedId)),
<add> onbefore: checkOnce(chkBefore),
<add> onafter: checkOnce(chkAfter),
<ide> allowNoInit: true
<ide> }).enable();
<ide>
<ide><path>test/async-hooks/test-emit-init.js
<ide>
<ide> const common = require('../common');
<ide> const assert = require('assert');
<del>const spawnSync = require('child_process').spawnSync;
<ide> const async_hooks = require('internal/async_hooks');
<ide> const initHooks = require('./init-hooks');
<ide>
<ide> const hooks1 = initHooks({
<ide>
<ide> hooks1.enable();
<ide>
<del>switch (process.argv[2]) {
<del> case 'test_invalid_async_id':
<del> async_hooks.emitInit();
<del> return;
<del> case 'test_invalid_trigger_id':
<del> async_hooks.emitInit(expectedId);
<del> return;
<del> case 'test_invalid_trigger_id_negative':
<del> async_hooks.emitInit(expectedId, expectedType, -2);
<del> return;
<del>}
<del>assert.ok(!process.argv[2]);
<del>
<del>
<del>const c1 = spawnSync(process.execPath, [
<del> '--expose-internals', __filename, 'test_invalid_async_id'
<del>]);
<del>assert.strictEqual(
<del> c1.stderr.toString().split(/[\r\n]+/g)[0],
<del> 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid asyncId value: undefined');
<del>assert.strictEqual(c1.status, 1);
<del>
<del>const c2 = spawnSync(process.execPath, [
<del> '--expose-internals', __filename, 'test_invalid_trigger_id'
<del>]);
<del>assert.strictEqual(
<del> c2.stderr.toString().split(/[\r\n]+/g)[0],
<del> 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: undefined');
<del>assert.strictEqual(c2.status, 1);
<del>
<del>const c3 = spawnSync(process.execPath, [
<del> '--expose-internals', __filename, 'test_invalid_trigger_id_negative'
<del>]);
<del>assert.strictEqual(
<del> c3.stderr.toString().split(/[\r\n]+/g)[0],
<del> 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: -2');
<del>assert.strictEqual(c3.status, 1);
<del>
<del>
<ide> async_hooks.emitInit(expectedId, expectedType, expectedTriggerId,
<ide> expectedResource);
<ide> | 4 |
PHP | PHP | add http_ check | 23d6a793748de8b1394c1c5b3fa155ec265f995a | <ide><path>src/Illuminate/Foundation/Testing/CrawlerTrait.php
<ide> protected function transformHeadersToServerVars(array $headers)
<ide> $server = [];
<ide>
<ide> foreach ($headers as $name => $value) {
<del> $name = 'HTTP_'.strtr(strtoupper($name), '-', '_');
<add> if (!starts_with($name, 'HTTP_')) {
<add> $name = 'HTTP_'.strtr(strtoupper($name), '-', '_');
<add> }
<ide>
<ide> $server[$name] = $value;
<ide> } | 1 |
Ruby | Ruby | fix another `brew style` from #971 | 3ffb9a2f7cda6652f75cb0c59c6d079ab1039e94 | <ide><path>Library/Homebrew/formulary.rb
<ide> def initialize(name)
<ide> super name, Formulary.core_path(name)
<ide> end
<ide>
<del> def get_formula(_spec, alias_path: nil)
<add> def get_formula(*)
<ide> raise FormulaUnavailableError, name
<ide> end
<ide> end | 1 |
Javascript | Javascript | bring bullet example up-to-date | 95c3c0b87af5d59e36d9e1f1bc262db3d10c3227 | <ide><path>examples/bullet/bullet.js
<del>var w = 960,
<del> h = 50,
<del> m = [5, 40, 20, 120]; // top right bottom left
<add>var innerWidth = 960,
<add> innerHeight = 50,
<add> margin = {top: 5, right: 40, bottom: 20, left: 120};
<ide>
<ide> var chart = bulletChart()
<del> .width(w - m[1] - m[3])
<del> .height(h - m[0] - m[2]);
<add> .width(innerWidth - margin.right - margin.left)
<add> .height(innerHeight - margin.top - margin.bottom);
<ide>
<ide> d3.json("bullets.json", function(data) {
<ide>
<ide> var vis = d3.select("#chart").selectAll("svg")
<ide> .data(data)
<ide> .enter().append("svg")
<ide> .attr("class", "bullet")
<del> .attr("width", w)
<del> .attr("height", h)
<add> .attr("width", innerWidth)
<add> .attr("height", innerHeight)
<ide> .append("g")
<del> .attr("transform", "translate(" + m[3] + "," + m[0] + ")")
<add> .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
<ide> .call(chart);
<ide>
<ide> var title = vis.append("g")
<ide> .attr("text-anchor", "end")
<del> .attr("transform", "translate(-6," + (h - m[0] - m[2]) / 2 + ")");
<add> .attr("transform", "translate(-6," + (innerHeight - margin.top - margin.bottom) / 2 + ")");
<ide>
<ide> title.append("text")
<ide> .attr("class", "title") | 1 |
PHP | PHP | add plain mail to notifications | f28bde37648f8125f39a01e804ef42db1ee183ed | <ide><path>src/Illuminate/Notifications/Channels/MailChannel.php
<ide> protected function messageBuilder($notifiable, $notification, $message)
<ide> protected function buildView($message)
<ide> {
<ide> if ($message->view) {
<del> return $message->view;
<add> return [
<add> 'html' => $message->view,
<add> 'text' => $message->textView,
<add> ];
<ide> }
<ide>
<ide> if (property_exists($message, 'theme') && ! is_null($message->theme)) {
<ide> protected function additionalMessageData($notification)
<ide> '__laravel_notification_id' => $notification->id,
<ide> '__laravel_notification' => get_class($notification),
<ide> '__laravel_notification_queued' => in_array(
<del> ShouldQueue::class, class_implements($notification)
<add> ShouldQueue::class,
<add> class_implements($notification)
<ide> ),
<ide> ];
<ide> }
<ide><path>src/Illuminate/Notifications/Messages/MailMessage.php
<ide> class MailMessage extends SimpleMessage implements Renderable
<ide> */
<ide> public $view;
<ide>
<add> /**
<add> * The plain text view to use for the message.
<add> *
<add> * @var string
<add> */
<add> public $textView;
<add>
<ide> /**
<ide> * The view data for the message.
<ide> *
<ide> class MailMessage extends SimpleMessage implements Renderable
<ide> public function view($view, array $data = [])
<ide> {
<ide> $this->view = $view;
<del> $this->viewData = $data;
<add> $this->viewData = array_merge($this->viewData, $data);
<ide>
<ide> $this->markdown = null;
<ide>
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Set the plain text view for the message.
<add> *
<add> * @param string $textView
<add> * @param array $data
<add> * @return $this
<add> */
<add> public function text($textView, array $data = [])
<add> {
<add> $this->textView = $textView;
<add> $this->viewData = array_merge($this->viewData, $data);
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Set the Markdown template for the notification.
<ide> *
<ide> public function render()
<ide> {
<ide> if (isset($this->view)) {
<ide> return Container::getInstance()->make('mailer')->render(
<del> $this->view, $this->data()
<add> [$this->view, $this->textView],
<add> $this->data()
<ide> );
<ide> }
<ide>
<ide><path>tests/Integration/Notifications/Fixtures/html.blade.php
<add>htmlContent
<ide><path>tests/Integration/Notifications/Fixtures/plain.blade.php
<add>plainContent
<ide><path>tests/Integration/Notifications/SendingMailNotificationsTest.php
<ide> use Illuminate\Notifications\Notifiable;
<ide> use Illuminate\Notifications\Notification;
<ide> use Illuminate\Support\Facades\Schema;
<add>use Illuminate\Support\Facades\View;
<ide> use Illuminate\Support\Str;
<ide> use Mockery as m;
<ide> use Orchestra\Testbench\TestCase;
<ide> protected function getEnvironmentSetUp($app)
<ide> $app->extend(MailFactory::class, function () {
<ide> return $this->mailFactory;
<ide> });
<add>
<add> View::addLocation(__DIR__.'/Fixtures');
<ide> }
<ide>
<ide> protected function setUp(): void
<ide> public function testMailIsSentUsingMailable()
<ide>
<ide> $user->notify($notification);
<ide> }
<add>
<add> public function testMailIsSentUsingMailMessageWithPlain()
<add> {
<add> $notification = new TestMailNotificationWithPlain;
<add> $notification->id = Str::uuid()->toString();
<add>
<add> $user = NotifiableUser::forceCreate([
<add> 'email' => 'taylor@laravel.com',
<add> ]);
<add>
<add> $this->mailer->shouldReceive('send')->once()->with(
<add> ['html' => 'html', 'text' => 'plain'],
<add> array_merge($notification->toMail($user)->toArray(), [
<add> '__laravel_notification_id' => $notification->id,
<add> '__laravel_notification' => get_class($notification),
<add> '__laravel_notification_queued' => false,
<add> ]),
<add> m::on(function ($closure) {
<add> $message = m::mock(Message::class);
<add>
<add> $message->shouldReceive('to')->once()->with(['taylor@laravel.com']);
<add>
<add> $message->shouldReceive('subject')->once()->with('Test Mail Notification With Plain');
<add>
<add> $closure($message);
<add>
<add> return true;
<add> })
<add> );
<add>
<add> $user->notify($notification);
<add> }
<ide> }
<ide>
<ide> class NotifiableUser extends Model
<ide> public function toMail($notifiable)
<ide> return $mailable;
<ide> }
<ide> }
<add>
<add>class TestMailNotificationWithPlain extends Notification
<add>{
<add> public function via($notifiable)
<add> {
<add> return [MailChannel::class];
<add> }
<add>
<add> public function toMail($notifiable)
<add> {
<add> return (new MailMessage)
<add> ->view('html')
<add> ->text('plain');
<add> }
<add>}
<ide><path>tests/Notifications/NotificationMailMessageTest.php
<ide> public function testTemplate()
<ide>
<ide> $this->assertSame('notifications::foo', $message->markdown);
<ide> }
<add> public function testHtmlView()
<add> {
<add> $message = new MailMessage;
<add>
<add> $this->assertSame(null, $message->view);
<add> $this->assertSame([], $message->viewData);
<add>
<add> $message->view('notifications::foo', [
<add> 'foo' => 'bar',
<add> ]);
<add>
<add> $this->assertSame('notifications::foo', $message->view);
<add> $this->assertSame(['foo' => 'bar'], $message->viewData);
<add> }
<add>
<add> public function testPlainView()
<add> {
<add> $message = new MailMessage;
<add>
<add> $this->assertSame(null, $message->textView);
<add> $this->assertSame([], $message->viewData);
<add>
<add> $message->text('notifications::foo', [
<add> 'foo' => 'bar',
<add> ]);
<add>
<add> $this->assertSame('notifications::foo', $message->textView);
<add> $this->assertSame(['foo' => 'bar'], $message->viewData);
<add> }
<add>
<ide>
<ide> public function testCcIsSetCorrectly()
<ide> { | 6 |
Python | Python | replace fsgrab by psutil | e1e8a99276d5a0f17a274750fea662aa12c210ab | <ide><path>src/glances.py
<ide> def add(self, item_state, item_type, item_value):
<ide>
<ide> class glancesGrabFs():
<ide> """
<del> Get FS stats: idem as structure http://www.i-scream.org/libstatgrab/docs/sg_get_fs_stats.3.html
<add> Get FS stats
<ide> """
<ide>
<ide> def __init__(self):
<ide> def __update__(self):
<ide> """
<ide> Update the stats
<ide> """
<del>
<del> # Reset the list
<del> self.fs_list = []
<del>
<add>
<ide> # Ignore the following fs
<del> ignore_fsname = ('none', 'gvfs-fuse-daemon', 'fusectl', 'cgroup')
<add> ignore_fsname = ('', 'none', 'gvfs-fuse-daemon', 'fusectl', 'cgroup')
<ide> ignore_fstype = ('binfmt_misc', 'devpts', 'iso9660', 'none', 'proc', 'sysfs', 'usbfs')
<add>
<add> # Reset the list
<add> self.fs_list = []
<ide>
<ide> # Open the current mounted FS
<del> mtab = open("/etc/mtab", "r")
<del> for line in mtab.readlines():
<del> if line.split()[0] in ignore_fsname: continue
<del> if line.split()[2] in ignore_fstype: continue
<del> # Get FS stats
<add> fs_stat = psutil.disk_partitions(True)
<add> for fs in range(len(fs_stat)):
<ide> fs_current = {}
<del> fs_name = self.__getmount__(line.split()[1])
<del> fs_stats = os.statvfs(fs_name)
<del> # Build the list
<del> fs_current['device_name'] = str(line.split()[0])
<del> fs_current['fs_type'] = str(line.split()[2])
<del> fs_current['mnt_point'] = str(fs_name)
<del> fs_current['size'] = float(fs_stats.f_blocks) * long(fs_stats.f_frsize)
<del> fs_current['used'] = float(fs_stats.f_blocks - fs_stats.f_bfree) * long(fs_stats.f_frsize)
<del> fs_current['avail'] = float(fs_stats.f_bfree) * long(fs_stats.f_frsize)
<del> self.fs_list.append(fs_current)
<del> mtab.close()
<del>
<del>
<del> def __getmount__(self, path):
<del> """
<del> Return the real root path of a file
<del> Exemple: /home/nicolargo can return /home or /
<del> """
<del> path = os.path.realpath(os.path.abspath(path))
<del> while path != os.path.sep:
<del> if os.path.ismount(path):
<del> return path
<del> path = os.path.abspath(os.path.join(path, os.pardir))
<del> return path
<add> fs_current['device_name'] = fs_stat[fs].device
<add> if fs_current['device_name'] in ignore_fsname: continue
<add> fs_current['fs_type'] = fs_stat[fs].fstype
<add> if fs_current['fs_type'] in ignore_fstype: continue
<add> fs_current['mnt_point'] = fs_stat[fs].mountpoint
<add> fs_usage = psutil.disk_usage(fs_current['mnt_point'])
<add> fs_current['size'] = fs_usage.total
<add> fs_current['used'] = fs_usage.used
<add> fs_current['avail'] = fs_usage.free
<add> self.fs_list.append(fs_current)
<ide>
<ide>
<ide> def get(self):
<ide> def __update__(self):
<ide>
<ide> # NET
<ide> try:
<del> self.networkinterface = statgrab.sg_get_network_iface_stats()
<add> self.network_old
<ide> except:
<del> self.networkinterface = {}
<del> try:
<del> self.network = statgrab.sg_get_network_io_stats_diff()
<del> except:
<del> self.network = {}
<add> self.network_old = psutil.network_io_counters(True)
<add> self.network = []
<add> else:
<add> try:
<add> self.network_new = psutil.network_io_counters(True)
<add> self.network = []
<add> for net in self.network_new:
<add> netstat = {}
<add> netstat['interface_name'] = net
<add> netstat['rx'] = self.network_new[net].bytes_recv - self.network_old[net].bytes_recv
<add> netstat['tx'] = self.network_new[net].bytes_sent - self.network_old[net].bytes_sent
<add> self.network.append(netstat)
<add> self.network_old = self.network_new
<add> except:
<add> self.network = []
<ide>
<ide> # DISK IO
<ide> try:
<ide> def getMem(self):
<ide>
<ide> def getMemSwap(self):
<ide> return self.memswap
<del>
<del>
<del> def getNetworkInterface(self):
<del> return self.networkinterface
<del>
<add>
<ide>
<ide> def getNetwork(self):
<ide> return self.network
<ide> def __autoUnit(self, val):
<ide> 560745673 -> 561M
<ide> ...
<ide> """
<del> if val >= 1073741824L:
<del> return "%.1fG" % (val / 1073741824L)
<del> elif val >= 1048576L:
<del> return "%.1fM" % (val / 1048576L)
<del> elif val >= 1024:
<del> return "%.1fK" % (val / 1024)
<del> else:
<del> return str(int(val))
<add> symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
<add> prefix = {
<add> 'Y': 1208925819614629174706176L,
<add> 'Z': 1180591620717411303424L,
<add> 'E': 1152921504606846976L,
<add> 'P': 1125899906842624L,
<add> 'T': 1099511627776L,
<add> 'G': 1073741824,
<add> 'M': 1048576,
<add> 'K': 1024
<add> }
<add> for key in reversed(symbols):
<add> if val >= prefix[key]:
<add> value = float(val) / prefix[key]
<add> return '%.1f%s' % (value, key)
<add> return "%s" % val
<add>
<ide>
<ide> def __getAlert(self, current = 0, max = 100):
<ide> # If current < CAREFUL of max then alert = OK
<ide> def display(self, stats):
<ide> self.displayCpu(stats.getCpu())
<ide> self.displayLoad(stats.getLoad(), stats.getCore())
<ide> self.displayMem(stats.getMem(), stats.getMemSwap())
<del> network_count = self.displayNetwork(stats.getNetwork(), stats.getNetworkInterface())
<add> network_count = self.displayNetwork(stats.getNetwork())
<ide> diskio_count = self.displayDiskIO(stats.getDiskIO(), self.network_y + network_count)
<ide> fs_count = self.displayFs(stats.getFs(), self.network_y + network_count + diskio_count)
<ide> log_count = self.displayLog(self.network_y + network_count + diskio_count + fs_count)
<ide> def displayMem(self, mem, memswap):
<ide> self.term_window.addnstr(self.mem_y+3, self.mem_x+30, str((mem['free']+mem['cache'])/1048576), 8)
<ide>
<ide>
<del> def displayNetwork(self, network, networkinterface):
<add> def displayNetwork(self, network):
<ide> """
<ide> Display the network interface bitrate
<ide> Return the number of interfaces
<ide> """
<ide> # Network interfaces bitrate
<del> if (not network or not networkinterface or not self.network_tag):
<add> if (not network or not self.network_tag):
<ide> return 0
<ide> screen_x = self.screen.getmaxyx()[1]
<ide> screen_y = self.screen.getmaxyx()[0]
<ide> if ((screen_y > self.network_y+3)
<ide> and (screen_x > self.network_x+28)):
<del> # Get the speed of the network interface
<del> # TODO: optimize...
<del> speed = {}
<del> for i in range(0, len(networkinterface)):
<del> # Strange think, on Ubuntu, libstatgrab return 65525 for my ethernet card...
<del> if networkinterface[i]['speed'] == 65535:
<del> speed[networkinterface[i]['interface_name']] = 0
<del> else:
<del> speed[networkinterface[i]['interface_name']] = networkinterface[i]['speed']*1000000
<ide> # Network interfaces bitrate
<ide> self.term_window.addnstr(self.network_y, self.network_x, _("Net rate"), 8, self.title_color if self.hascolors else curses.A_UNDERLINE)
<ide> self.term_window.addnstr(self.network_y, self.network_x+10, _("Rx/ps"), 8)
<ide> self.term_window.addnstr(self.network_y, self.network_x+20, _("Tx/ps"), 8)
<ide> # Adapt the maximum interface to the screen
<ide> ret = 2
<ide> for i in range(0, min(screen_y-self.network_y-3, len(network))):
<del> try:
<del> speed[network[i]['interface_name']]
<del> except:
<del> break
<del> elapsed_time = max (1, network[i]['systime'])
<add> elapsed_time = max (1, self.__refresh_time)
<ide> self.term_window.addnstr(self.network_y+1+i, self.network_x, network[i]['interface_name']+':', 8)
<del> self.term_window.addnstr(self.network_y+1+i, self.network_x+10, self.__autoUnit(network[i]['rx']/elapsed_time*8) + "b", 8, self.__getNetColor(network[i]['rx']/elapsed_time*8, speed[network[i]['interface_name']]))
<del> self.term_window.addnstr(self.network_y+1+i, self.network_x+20, self.__autoUnit(network[i]['tx']/elapsed_time*8) + "b", 8, self.__getNetColor(network[i]['tx']/elapsed_time*8, speed[network[i]['interface_name']]))
<add> self.term_window.addnstr(self.network_y+1+i, self.network_x+10, self.__autoUnit(network[i]['rx']/elapsed_time*8) + "b", 8)
<add> self.term_window.addnstr(self.network_y+1+i, self.network_x+20, self.__autoUnit(network[i]['tx']/elapsed_time*8) + "b", 8)
<ide> ret = ret + 1
<ide> return ret
<ide> return 0 | 1 |
Go | Go | simplify task code | dd67b4794ee79a5b72be1f4cbb48b7b0829ec4ee | <ide><path>integration/config/config_test.go
<ide> func TestTemplatedConfig(t *testing.T) {
<ide> swarm.ServiceWithName("svc"),
<ide> )
<ide>
<del> var tasks []swarmtypes.Task
<del> getRunningTasks := func(log poll.LogT) poll.Result {
<del> tasks = swarm.GetRunningTasks(t, c, serviceID)
<del> if len(tasks) > 0 {
<del> return poll.Success()
<del> }
<del> return poll.Continue("task still waiting")
<del> }
<del> poll.WaitOn(t, getRunningTasks, swarm.ServicePoll, poll.WithTimeout(1*time.Minute))
<del>
<del> task := tasks[0]
<del> getTask := func(log poll.LogT) poll.Result {
<del> if task.NodeID == "" || (task.Status.ContainerStatus == nil || task.Status.ContainerStatus.ContainerID == "") {
<del> task, _, _ = c.TaskInspectWithRaw(context.Background(), task.ID)
<del> }
<del> if task.NodeID != "" && task.Status.ContainerStatus != nil && task.Status.ContainerStatus.ContainerID != "" {
<del> return poll.Success()
<del> }
<del> return poll.Continue("task still waiting")
<del> }
<del> poll.WaitOn(t, getTask, swarm.ServicePoll, poll.WithTimeout(1*time.Minute))
<add> poll.WaitOn(t, swarm.RunningTasksCount(c, serviceID, 1), swarm.ServicePoll, poll.WithTimeout(1*time.Minute))
<add>
<add> tasks := swarm.GetRunningTasks(t, c, serviceID)
<add> assert.Assert(t, len(tasks) > 0, "no running tasks found for service %s", serviceID)
<ide>
<del> attach := swarm.ExecTask(t, d, task, types.ExecConfig{
<add> attach := swarm.ExecTask(t, d, tasks[0], types.ExecConfig{
<ide> Cmd: []string{"/bin/cat", "/" + templatedConfigName},
<ide> AttachStdout: true,
<ide> AttachStderr: true,
<ide> func TestTemplatedConfig(t *testing.T) {
<ide> "this is a config\n"
<ide> assertAttachedStream(t, attach, expect)
<ide>
<del> attach = swarm.ExecTask(t, d, task, types.ExecConfig{
<add> attach = swarm.ExecTask(t, d, tasks[0], types.ExecConfig{
<ide> Cmd: []string{"mount"},
<ide> AttachStdout: true,
<ide> AttachStderr: true, | 1 |
Ruby | Ruby | remove an unnecessary use of argv.build_head? | e91f359a56f8c798a35df06ab028af85ee423ddf | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def _fetch
<ide>
<ide> class SubversionDownloadStrategy < VCSDownloadStrategy
<ide> def cache_tag
<del> ARGV.build_head? ? "svn-HEAD" : "svn"
<add> resource.version.head? ? "svn-HEAD" : "svn"
<ide> end
<ide>
<ide> def repo_valid? | 1 |
Javascript | Javascript | remove async_wrap from async_hooks.js | 8c46fa69036757e2b86d9bea308b66d502420c5e | <ide><path>lib/async_hooks.js
<ide> const {
<ide> ERR_INVALID_ARG_TYPE,
<ide> ERR_INVALID_ASYNC_ID
<ide> } = require('internal/errors').codes;
<del>const async_wrap = process.binding('async_wrap');
<ide> const internal_async_hooks = require('internal/async_hooks');
<ide>
<ide> // Get functions
<ide> // For userland AsyncResources, make sure to emit a destroy event when the
<ide> // resource gets gced.
<del>const { registerDestroyHook } = async_wrap;
<add>const { registerDestroyHook } = internal_async_hooks;
<ide> const {
<ide> executionAsyncId,
<ide> triggerAsyncId,
<ide> const {
<ide> // Get constants
<ide> const {
<ide> kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,
<del>} = async_wrap.constants;
<add>} = internal_async_hooks.constants;
<ide>
<ide> // Listener API //
<ide>
<ide><path>lib/internal/async_hooks.js
<ide> const active_hooks = {
<ide> tmp_fields: null
<ide> };
<ide>
<add>const { registerDestroyHook } = async_wrap;
<ide>
<ide> // Each constant tracks how many callbacks there are for any given step of
<ide> // async execution. These are tracked so if the user didn't include callbacks
<ide> // for a given step, that step can bail out early.
<del>const { kInit, kBefore, kAfter, kDestroy, kPromiseResolve,
<add>const { kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,
<ide> kCheck, kExecutionAsyncId, kAsyncIdCounter, kTriggerAsyncId,
<ide> kDefaultTriggerAsyncId, kStackLength } = async_wrap.constants;
<ide>
<ide> module.exports = {
<ide> init_symbol, before_symbol, after_symbol, destroy_symbol,
<ide> promise_resolve_symbol
<ide> },
<add> constants: {
<add> kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve
<add> },
<ide> enableHooks,
<ide> disableHooks,
<ide> clearDefaultTriggerAsyncId,
<ide> module.exports = {
<ide> emitBefore: emitBeforeScript,
<ide> emitAfter: emitAfterScript,
<ide> emitDestroy: emitDestroyScript,
<add> registerDestroyHook,
<ide> }; | 2 |
Python | Python | introduce msvs 2019 | 317b712a52e0bb855bd18670ea8efa6c32bae032 | <ide><path>tools/gyp/pylib/gyp/MSVSVersion.py
<ide> def _CreateVersion(name, path, sdk_based=False):
<ide> if path:
<ide> path = os.path.normpath(path)
<ide> versions = {
<add> '2019': VisualStudioVersion('2019',
<add> 'Visual Studio 2019',
<add> solution_version='12.00',
<add> project_version='16.0',
<add> flat_sln=False,
<add> uses_vcxproj=True,
<add> path=path,
<add> sdk_based=sdk_based,
<add> default_toolset='v142',
<add> compatible_sdks=['v8.1', 'v10.0']),
<ide> '2017': VisualStudioVersion('2017',
<ide> 'Visual Studio 2017',
<ide> solution_version='12.00',
<ide> def _DetectVisualStudioVersions(versions_to_check, force_express):
<ide> 2013(e) - Visual Studio 2013 (12)
<ide> 2015 - Visual Studio 2015 (14)
<ide> 2017 - Visual Studio 2017 (15)
<add> 2019 - Visual Studio 2019 (16)
<ide> Where (e) is e for express editions of MSVS and blank otherwise.
<ide> """
<ide> version_to_year = {
<ide> def _DetectVisualStudioVersions(versions_to_check, force_express):
<ide> '11.0': '2012',
<ide> '12.0': '2013',
<ide> '14.0': '2015',
<del> '15.0': '2017'
<add> '15.0': '2017',
<add> '16.0': '2019',
<ide> }
<ide> versions = []
<ide> for version in versions_to_check: | 1 |
Javascript | Javascript | add note about indexof call throwing | 6306580d84486ecfbe966c6394980f3d0727320c | <ide><path>server/boot/challenge.js
<ide> module.exports = function(app) {
<ide>
<ide> var challengeId = String(req.user.currentChallenge.challengeId);
<ide> var challengeBlock = req.user.currentChallenge.challengeBlock;
<add> // TODO(berks) fix index call here
<ide> var indexOfChallenge = challengeMapWithIds[challengeBlock]
<ide> .indexOf(challengeId);
<ide> | 1 |
Ruby | Ruby | remove hyphen from bottle_extname_rx | 6ca42964cb20a321be56180df9c568c1c016e84e | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> class Pathname
<ide> include MachO
<ide>
<del> BOTTLE_EXTNAME_RX = /(\.[-a-z0-9_]+\.bottle\.(\d+\.)?tar\.gz)$/
<add> BOTTLE_EXTNAME_RX = /(\.[a-z0-9_]+\.bottle\.(\d+\.)?tar\.gz)$/
<ide>
<ide> def install *sources
<ide> sources.each do |src| | 1 |
Ruby | Ruby | upload packages from canonical name | 1f541f7dfb5ae373acfd9831792d1e4cdd6948ea | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def test_bot
<ide> existing_bottles = {}
<ide> Dir.glob("*.bottle*.tar.gz") do |filename|
<ide> formula_name = bottle_filename_formula_name filename
<del> formula = Formulary.factory formula_name rescue nil
<del> next unless formula
<add> canonical_formula_name = if tap
<add> "#{tap}/#{formula_name}"
<add> else
<add> formula_name
<add> end
<add> formula = Formulary.factory canonical_formula_name
<ide> existing_bottles[formula_name] = !!formula.bottle
<ide> end
<ide> | 1 |
Javascript | Javascript | add a comment | eff59f97ac63dd723b6932e7c6e2186735315401 | <ide><path>src/manipulation.js
<ide> var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>
<ide> rscriptType = /^$|\/(?:java|ecma)script/i,
<ide> rscriptTypeMasked = /^true\/(.*)/,
<ide> rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
<add>
<add> // We have to close these tags to support XHTML (#13200)
<ide> wrapMap = {
<ide>
<ide> // Support: IE 9 | 1 |
Javascript | Javascript | remove log in paperuimanager | 5d500f4dbcb48dad88e96c28f34459031c54019a | <ide><path>Libraries/ReactNative/PaperUIManager.js
<ide> function getViewManagerConfig(viewManagerName: string): any {
<ide> viewManagerConfigs[
<ide> viewManagerName
<ide> ] = NativeUIManager.getConstantsForViewManager(viewManagerName);
<del>
<del> if (viewManagerConfigs[viewManagerName] === undefined) {
<del> console.warn(
<del> 'Error: Unable to find getConstantsForViewManager for viewManager: ' +
<del> viewManagerName +
<del> '.',
<del> );
<del> }
<ide> } catch (e) {
<ide> console.error(
<ide> "NativeUIManager.getConstantsForViewManager('" +
<ide> function getViewManagerConfig(viewManagerName: string): any {
<ide> if (result != null && result.viewConfig != null) {
<ide> getConstants()[viewManagerName] = result.viewConfig;
<ide> lazifyViewManagerConfig(viewManagerName);
<del> } else {
<del> console.warn(
<del> 'Error: Unable to find viewManagerConfigs for viewManager: ' +
<del> viewManagerName +
<del> ' using lazyLoadView.',
<del> );
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | discourage people from using `temp` directly | 336f6425da64ef209dba03e745c55791e5a7f262 | <ide><path>spec/main-process/atom-application.test.js
<ide> import dedent from 'dedent'
<ide> import electron from 'electron'
<ide> import fs from 'fs-plus'
<ide> import path from 'path'
<del>import temp from 'temp'
<ide> import AtomApplication from '../../src/main-process/atom-application'
<ide> import parseCommandLine from '../../src/main-process/parse-command-line'
<ide>
<ide> describe('AtomApplication', function () {
<ide> }
<ide>
<ide> function makeTempDir (name) {
<del> return fs.realpathSync(temp.mkdirSync(name))
<add> return fs.realpathSync(require('temp').mkdirSync(name))
<ide> }
<ide>
<ide> let channelIdCounter = 0 | 1 |
Javascript | Javascript | add some optimizations to often used functions | 977d45a3e09393efbbdd2089e6e473f11c7f514b | <ide><path>src/core/core.helpers.js
<ide>
<ide> //-- Basic js utility methods
<ide> helpers.each = function(loopable, callback, self, reverse) {
<del> var additionalArgs = Array.prototype.slice.call(arguments, 3);
<ide> // Check to see if null or undefined firstly.
<del> if (loopable) {
<del> if (loopable.length === +loopable.length) {
<del> var i;
<del> if (reverse) {
<del> for (i = loopable.length - 1; i >= 0; i--) {
<del> callback.apply(self, [loopable[i], i].concat(additionalArgs));
<del> }
<del> } else {
<del> for (i = 0; i < loopable.length; i++) {
<del> callback.apply(self, [loopable[i], i].concat(additionalArgs));
<del> }
<add> var i, len;
<add> if (helpers.isArray(loopable)) {
<add> len = loopable.length;
<add> if (reverse) {
<add> for (i = len - 1; i >= 0; i--) {
<add> callback.call(self, loopable[i], i);
<ide> }
<ide> } else {
<del> for (var item in loopable) {
<del> callback.apply(self, [loopable[item], item].concat(additionalArgs));
<add> for (i = 0; i < len; i++) {
<add> callback.call(self, loopable[i], i);
<ide> }
<ide> }
<add> } else if (typeof loopable === 'object') {
<add> var keys = Object.keys(loopable);
<add> len = keys.length;
<add> for (i = 0; i < len; i++) {
<add> callback.call(self, loopable[keys[i]], keys[i]);
<add> }
<ide> }
<ide> };
<ide> helpers.clone = function(obj) {
<ide> return objClone;
<ide> };
<ide> helpers.extend = function(base) {
<del> helpers.each(Array.prototype.slice.call(arguments, 1), function(extensionObject) {
<add> var len = arguments.length;
<add> var additionalArgs = [];
<add> for(var i = 1; i < len; i++) {
<add> additionalArgs.push(arguments[i]);
<add> }
<add> helpers.each(additionalArgs, function(extensionObject) {
<ide> helpers.each(extensionObject, function(value, key) {
<ide> if (extensionObject.hasOwnProperty(key)) {
<ide> base[key] = value; | 1 |
Javascript | Javascript | add user timing marks for scheduling profiler tool | 40cddfeeb167d4964d82220142deb00f57fe197d | <ide><path>packages/react-reconciler/src/ReactFiberClassComponent.old.js
<ide> import {
<ide> debugRenderPhaseSideEffectsForStrictMode,
<ide> disableLegacyContext,
<ide> enableDebugTracing,
<add> enableSchedulingProfiler,
<ide> warnAboutDeprecatedLifecycles,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import ReactStrictModeWarnings from './ReactStrictModeWarnings.old';
<ide> import {requestCurrentSuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import {logForceUpdateScheduled, logStateUpdateScheduled} from './DebugTracing';
<ide>
<ide> import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev';
<add>import {
<add> markForceUpdateScheduled,
<add> markStateUpdateScheduled,
<add>} from './SchedulingProfiler';
<ide>
<ide> const fakeInternalInstance = {};
<ide> const isArray = Array.isArray;
<ide> const classComponentUpdater = {
<ide> }
<ide> }
<ide> }
<add>
<add> if (enableSchedulingProfiler) {
<add> markStateUpdateScheduled(fiber, lane);
<add> }
<ide> },
<ide> enqueueReplaceState(inst, payload, callback) {
<ide> const fiber = getInstance(inst);
<ide> const classComponentUpdater = {
<ide> }
<ide> }
<ide> }
<add>
<add> if (enableSchedulingProfiler) {
<add> markStateUpdateScheduled(fiber, lane);
<add> }
<ide> },
<ide> enqueueForceUpdate(inst, callback) {
<ide> const fiber = getInstance(inst);
<ide> const classComponentUpdater = {
<ide> }
<ide> }
<ide> }
<add>
<add> if (enableSchedulingProfiler) {
<add> markForceUpdateScheduled(fiber, lane);
<add> }
<ide> },
<ide> };
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js
<ide> import type {OpaqueIDType} from './ReactFiberHostConfig';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import {
<ide> enableDebugTracing,
<add> enableSchedulingProfiler,
<ide> enableNewReconciler,
<ide> } from 'shared/ReactFeatureFlags';
<ide>
<ide> import {
<ide> } from './ReactMutableSource.old';
<ide> import {getIsRendering} from './ReactCurrentFiber';
<ide> import {logStateUpdateScheduled} from './DebugTracing';
<add>import {markStateUpdateScheduled} from './SchedulingProfiler';
<ide>
<ide> const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals;
<ide>
<ide> function dispatchAction<S, A>(
<ide> }
<ide> }
<ide> }
<add>
<add> if (enableSchedulingProfiler) {
<add> markStateUpdateScheduled(fiber, lane);
<add> }
<ide> }
<ide>
<ide> export const ContextOnlyDispatcher: Dispatcher = {
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.old.js
<ide> import {
<ide> } from './ReactWorkTags';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<add>import {enableSchedulingProfiler} from 'shared/ReactFeatureFlags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import {getPublicInstance} from './ReactFiberHostConfig';
<ide> import {
<ide> import {
<ide> setRefreshHandler,
<ide> findHostInstancesForRefresh,
<ide> } from './ReactFiberHotReloading.old';
<add>import {markRenderScheduled} from './SchedulingProfiler';
<ide>
<ide> export {registerMutableSourceForHydration} from './ReactMutableSource.new';
<ide> export {createPortal} from './ReactPortal';
<ide> export function updateContainer(
<ide> const suspenseConfig = requestCurrentSuspenseConfig();
<ide> const lane = requestUpdateLane(current, suspenseConfig);
<ide>
<add> if (enableSchedulingProfiler) {
<add> markRenderScheduled(lane);
<add> }
<add>
<ide> const context = getContextForSubtree(parentComponent);
<ide> if (container.context === null) {
<ide> container.context = context;
<ide><path>packages/react-reconciler/src/ReactFiberThrow.old.js
<ide> import {
<ide> } from './ReactSideEffectTags';
<ide> import {shouldCaptureSuspense} from './ReactFiberSuspenseComponent.old';
<ide> import {NoMode, BlockingMode, DebugTracingMode} from './ReactTypeOfMode';
<del>import {enableDebugTracing} from 'shared/ReactFeatureFlags';
<add>import {
<add> enableDebugTracing,
<add> enableSchedulingProfiler,
<add>} from 'shared/ReactFeatureFlags';
<ide> import {createCapturedValue} from './ReactCapturedValue';
<ide> import {
<ide> enqueueCapturedUpdate,
<ide> import {
<ide> } from './ReactFiberWorkLoop.old';
<ide> import {logCapturedError} from './ReactFiberErrorLogger';
<ide> import {logComponentSuspended} from './DebugTracing';
<add>import {markComponentSuspended} from './SchedulingProfiler';
<ide>
<ide> import {
<ide> SyncLane,
<ide> function throwException(
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markComponentSuspended(sourceFiber, wakeable);
<add> }
<add>
<ide> if ((sourceFiber.mode & BlockingMode) === NoMode) {
<ide> // Reset the memoizedState to what it was before we attempted
<ide> // to render it.
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> deferRenderPhaseUpdateToNextBatch,
<ide> decoupleUpdatePriorityFromScheduler,
<ide> enableDebugTracing,
<add> enableSchedulingProfiler,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import invariant from 'shared/invariant';
<ide> import {
<ide> logRenderStarted,
<ide> logRenderStopped,
<ide> } from './DebugTracing';
<add>import {
<add> markCommitStarted,
<add> markCommitStopped,
<add> markLayoutEffectsStarted,
<add> markLayoutEffectsStopped,
<add> markPassiveEffectsStarted,
<add> markPassiveEffectsStopped,
<add> markRenderStarted,
<add> markRenderYielded,
<add> markRenderStopped,
<add>} from './SchedulingProfiler';
<ide>
<ide> // The scheduler is imported here *only* to detect whether it's been mocked
<ide> import * as Scheduler from 'scheduler';
<ide> function renderRootSync(root: FiberRoot, lanes: Lanes) {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markRenderStarted(lanes);
<add> }
<add>
<ide> do {
<ide> try {
<ide> workLoopSync();
<ide> function renderRootSync(root: FiberRoot, lanes: Lanes) {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markRenderStopped();
<add> }
<add>
<ide> // Set this to null to indicate there's no in-progress render.
<ide> workInProgressRoot = null;
<ide> workInProgressRootRenderLanes = NoLanes;
<ide> function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markRenderStarted(lanes);
<add> }
<add>
<ide> do {
<ide> try {
<ide> workLoopConcurrent();
<ide> function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
<ide> // Check if the tree has completed.
<ide> if (workInProgress !== null) {
<ide> // Still work remaining.
<add> if (enableSchedulingProfiler) {
<add> markRenderYielded();
<add> }
<ide> return RootIncomplete;
<ide> } else {
<ide> // Completed the tree.
<add> if (enableSchedulingProfiler) {
<add> markRenderStopped();
<add> }
<add>
<ide> // Set this to null to indicate there's no in-progress render.
<ide> workInProgressRoot = null;
<ide> workInProgressRootRenderLanes = NoLanes;
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markCommitStarted(lanes);
<add> }
<add>
<ide> if (finishedWork === null) {
<ide> if (__DEV__) {
<ide> if (enableDebugTracing) {
<ide> logCommitStopped();
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markCommitStopped();
<add> }
<add>
<ide> return null;
<ide> }
<ide> root.finishedWork = null;
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markCommitStopped();
<add> }
<add>
<ide> // This is a legacy edge case. We just committed the initial mount of
<ide> // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
<ide> // synchronously, but layout updates should be deferred until the end
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markCommitStopped();
<add> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> function commitLayoutEffects(root: FiberRoot, committedLanes: Lanes) {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markLayoutEffectsStarted(committedLanes);
<add> }
<add>
<ide> // TODO: Should probably move the bulk of this function to commitWork.
<ide> while (nextEffect !== null) {
<ide> setCurrentDebugFiberInDEV(nextEffect);
<ide> function commitLayoutEffects(root: FiberRoot, committedLanes: Lanes) {
<ide> logLayoutEffectsStopped();
<ide> }
<ide> }
<add>
<add> if (enableSchedulingProfiler) {
<add> markLayoutEffectsStopped();
<add> }
<ide> }
<ide>
<ide> export function flushPassiveEffects() {
<ide> function flushPassiveEffectsImpl() {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markPassiveEffectsStarted(lanes);
<add> }
<add>
<ide> if (__DEV__) {
<ide> isFlushingPassiveEffects = true;
<ide> }
<ide> function flushPassiveEffectsImpl() {
<ide> }
<ide> }
<ide>
<add> if (enableSchedulingProfiler) {
<add> markPassiveEffectsStopped();
<add> }
<add>
<ide> executionContext = prevExecutionContext;
<ide>
<ide> flushSyncCallbackQueue();
<ide><path>packages/react-reconciler/src/SchedulingProfiler.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> * @flow
<add> */
<add>
<add>import type {Lane, Lanes} from './ReactFiberLane';
<add>import type {Fiber} from './ReactInternalTypes';
<add>import type {Wakeable} from 'shared/ReactTypes';
<add>
<add>import {enableSchedulingProfiler} from 'shared/ReactFeatureFlags';
<add>import getComponentName from 'shared/getComponentName';
<add>import {getStackByFiberInDevAndProd} from './ReactFiberComponentStack';
<add>
<add>/**
<add> * If performance exists and supports the subset of the User Timing API that we
<add> * require.
<add> */
<add>const supportsUserTiming =
<add> typeof performance !== 'undefined' && typeof performance.mark === 'function';
<add>
<add>function formatLanes(laneOrLanes: Lane | Lanes): string {
<add> return ((laneOrLanes: any): number).toString();
<add>}
<add>
<add>export function markCommitStarted(lanes: Lanes): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark(`--commit-start-${formatLanes(lanes)}`);
<add> }
<add> }
<add>}
<add>
<add>export function markCommitStopped(): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark('--commit-stop');
<add> }
<add> }
<add>}
<add>
<add>const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
<add>
<add>// $FlowFixMe: Flow cannot handle polymorphic WeakMaps
<add>const wakeableIDs: WeakMap<Wakeable, number> = new PossiblyWeakMap();
<add>let wakeableID: number = 0;
<add>function getWakeableID(wakeable: Wakeable): number {
<add> if (!wakeableIDs.has(wakeable)) {
<add> wakeableIDs.set(wakeable, wakeableID++);
<add> }
<add> return ((wakeableIDs.get(wakeable): any): number);
<add>}
<add>
<add>// $FlowFixMe: Flow cannot handle polymorphic WeakMaps
<add>const cachedFiberStacks: WeakMap<Fiber, string> = new PossiblyWeakMap();
<add>function cacheFirstGetComponentStackByFiber(fiber: Fiber): string {
<add> if (cachedFiberStacks.has(fiber)) {
<add> return ((cachedFiberStacks.get(fiber): any): string);
<add> } else {
<add> const alternate = fiber.alternate;
<add> if (alternate !== null && cachedFiberStacks.has(alternate)) {
<add> return ((cachedFiberStacks.get(alternate): any): string);
<add> }
<add> }
<add> // TODO (brian) Generate and store temporary ID so DevTools can match up a component stack later.
<add> const componentStack = getStackByFiberInDevAndProd(fiber) || '';
<add> cachedFiberStacks.set(fiber, componentStack);
<add> return componentStack;
<add>}
<add>
<add>export function markComponentSuspended(fiber: Fiber, wakeable: Wakeable): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> const id = getWakeableID(wakeable);
<add> const componentName = getComponentName(fiber.type) || 'Unknown';
<add> const componentStack = cacheFirstGetComponentStackByFiber(fiber);
<add> performance.mark(
<add> `--suspense-suspend-${id}-${componentName}-${componentStack}`,
<add> );
<add> wakeable.then(
<add> () =>
<add> performance.mark(
<add> `--suspense-resolved-${id}-${componentName}-${componentStack}`,
<add> ),
<add> () =>
<add> performance.mark(
<add> `--suspense-rejected-${id}-${componentName}-${componentStack}`,
<add> ),
<add> );
<add> }
<add> }
<add>}
<add>
<add>export function markLayoutEffectsStarted(lanes: Lanes): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark(`--layout-effects-start-${formatLanes(lanes)}`);
<add> }
<add> }
<add>}
<add>
<add>export function markLayoutEffectsStopped(): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark('--layout-effects-stop');
<add> }
<add> }
<add>}
<add>
<add>export function markPassiveEffectsStarted(lanes: Lanes): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark(`--passive-effects-start-${formatLanes(lanes)}`);
<add> }
<add> }
<add>}
<add>
<add>export function markPassiveEffectsStopped(): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark('--passive-effects-stop');
<add> }
<add> }
<add>}
<add>
<add>export function markRenderStarted(lanes: Lanes): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark(`--render-start-${formatLanes(lanes)}`);
<add> }
<add> }
<add>}
<add>
<add>export function markRenderYielded(): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark('--render-yield');
<add> }
<add> }
<add>}
<add>
<add>export function markRenderStopped(): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark('--render-stop');
<add> }
<add> }
<add>}
<add>
<add>export function markRenderScheduled(lane: Lane): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> performance.mark(`--schedule-render-${formatLanes(lane)}`);
<add> }
<add> }
<add>}
<add>
<add>export function markForceUpdateScheduled(fiber: Fiber, lane: Lane): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> const componentName = getComponentName(fiber.type) || 'Unknown';
<add> const componentStack = cacheFirstGetComponentStackByFiber(fiber);
<add> performance.mark(
<add> `--schedule-forced-update-${formatLanes(
<add> lane,
<add> )}-${componentName}-${componentStack}`,
<add> );
<add> }
<add> }
<add>}
<add>
<add>export function markStateUpdateScheduled(fiber: Fiber, lane: Lane): void {
<add> if (enableSchedulingProfiler) {
<add> if (supportsUserTiming) {
<add> const componentName = getComponentName(fiber.type) || 'Unknown';
<add> const componentStack = cacheFirstGetComponentStackByFiber(fiber);
<add> performance.mark(
<add> `--schedule-state-update-${formatLanes(
<add> lane,
<add> )}-${componentName}-${componentStack}`,
<add> );
<add> }
<add> }
<add>}
<ide><path>packages/react-reconciler/src/__tests__/SchedulingProfiler-test.internal.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 react-core
<add> * @jest-environment node
<add> */
<add>
<add>'use strict';
<add>
<add>function normalizeCodeLocInfo(str) {
<add> return (
<add> str &&
<add> str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function(m, name) {
<add> return '\n in ' + name + ' (at **)';
<add> })
<add> );
<add>}
<add>
<add>describe('SchedulingProfiler', () => {
<add> let React;
<add> let ReactTestRenderer;
<add> let ReactNoop;
<add> let Scheduler;
<add>
<add> let marks;
<add>
<add> function createUserTimingPolyfill() {
<add> // This is not a true polyfill, but it gives us enough to capture marks.
<add> // Reference: https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API
<add> return {
<add> mark(markName) {
<add> marks.push(markName);
<add> },
<add> };
<add> }
<add>
<add> beforeEach(() => {
<add> jest.resetModules();
<add> global.performance = createUserTimingPolyfill();
<add>
<add> React = require('react');
<add>
<add> // ReactNoop must be imported after ReactTestRenderer!
<add> ReactTestRenderer = require('react-test-renderer');
<add> ReactNoop = require('react-noop-renderer');
<add>
<add> Scheduler = require('scheduler');
<add>
<add> marks = [];
<add> });
<add>
<add> afterEach(() => {
<add> delete global.performance;
<add> });
<add>
<add> // @gate !enableSchedulingProfiler
<add> it('should not mark if enableSchedulingProfiler is false', () => {
<add> ReactTestRenderer.create(<div />);
<add> expect(marks).toEqual([]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark sync render without suspends or state updates', () => {
<add> ReactTestRenderer.create(<div />);
<add>
<add> expect(marks).toEqual([
<add> '--schedule-render-1',
<add> '--render-start-1',
<add> '--render-stop',
<add> '--commit-start-1',
<add> '--layout-effects-start-1',
<add> '--layout-effects-stop',
<add> '--commit-stop',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark concurrent render without suspends or state updates', () => {
<add> ReactTestRenderer.create(<div />, {unstable_isConcurrent: true});
<add>
<add> expect(marks).toEqual(['--schedule-render-512']);
<add>
<add> marks.splice(0);
<add>
<add> expect(Scheduler).toFlushUntilNextPaint([]);
<add>
<add> expect(marks).toEqual([
<add> '--render-start-512',
<add> '--render-stop',
<add> '--commit-start-512',
<add> '--layout-effects-start-512',
<add> '--layout-effects-stop',
<add> '--commit-stop',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark render yields', async () => {
<add> function Bar() {
<add> Scheduler.unstable_yieldValue('Bar');
<add> return null;
<add> }
<add>
<add> function Foo() {
<add> Scheduler.unstable_yieldValue('Foo');
<add> return <Bar />;
<add> }
<add>
<add> ReactNoop.render(<Foo />);
<add> // Do one step of work.
<add> expect(ReactNoop.flushNextYield()).toEqual(['Foo']);
<add>
<add> expect(marks).toEqual([
<add> '--schedule-render-512',
<add> '--render-start-512',
<add> '--render-yield',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark sync render with suspense that resolves', async () => {
<add> const fakeSuspensePromise = Promise.resolve(true);
<add> function Example() {
<add> throw fakeSuspensePromise;
<add> }
<add>
<add> ReactTestRenderer.create(
<add> <React.Suspense fallback={null}>
<add> <Example />
<add> </React.Suspense>,
<add> );
<add>
<add> expect(marks).toEqual([
<add> '--schedule-render-1',
<add> '--render-start-1',
<add> '--suspense-suspend-0-Example-\n at Example\n at Suspense',
<add> '--render-stop',
<add> '--commit-start-1',
<add> '--layout-effects-start-1',
<add> '--layout-effects-stop',
<add> '--commit-stop',
<add> ]);
<add>
<add> marks.splice(0);
<add>
<add> await fakeSuspensePromise;
<add> expect(marks).toEqual([
<add> '--suspense-resolved-0-Example-\n at Example\n at Suspense',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark sync render with suspense that rejects', async () => {
<add> const fakeSuspensePromise = Promise.reject(new Error('error'));
<add> function Example() {
<add> throw fakeSuspensePromise;
<add> }
<add>
<add> ReactTestRenderer.create(
<add> <React.Suspense fallback={null}>
<add> <Example />
<add> </React.Suspense>,
<add> );
<add>
<add> expect(marks).toEqual([
<add> '--schedule-render-1',
<add> '--render-start-1',
<add> '--suspense-suspend-0-Example-\n at Example\n at Suspense',
<add> '--render-stop',
<add> '--commit-start-1',
<add> '--layout-effects-start-1',
<add> '--layout-effects-stop',
<add> '--commit-stop',
<add> ]);
<add>
<add> marks.splice(0);
<add>
<add> await expect(fakeSuspensePromise).rejects.toThrow();
<add> expect(marks).toEqual([
<add> '--suspense-rejected-0-Example-\n at Example\n at Suspense',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark concurrent render with suspense that resolves', async () => {
<add> const fakeSuspensePromise = Promise.resolve(true);
<add> function Example() {
<add> throw fakeSuspensePromise;
<add> }
<add>
<add> ReactTestRenderer.create(
<add> <React.Suspense fallback={null}>
<add> <Example />
<add> </React.Suspense>,
<add> {unstable_isConcurrent: true},
<add> );
<add>
<add> expect(marks).toEqual(['--schedule-render-512']);
<add>
<add> marks.splice(0);
<add>
<add> expect(Scheduler).toFlushUntilNextPaint([]);
<add>
<add> expect(marks).toEqual([
<add> '--render-start-512',
<add> '--suspense-suspend-0-Example-\n at Example\n at Suspense',
<add> '--render-stop',
<add> '--commit-start-512',
<add> '--layout-effects-start-512',
<add> '--layout-effects-stop',
<add> '--commit-stop',
<add> ]);
<add>
<add> marks.splice(0);
<add>
<add> await fakeSuspensePromise;
<add> expect(marks).toEqual([
<add> '--suspense-resolved-0-Example-\n at Example\n at Suspense',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark concurrent render with suspense that rejects', async () => {
<add> const fakeSuspensePromise = Promise.reject(new Error('error'));
<add> function Example() {
<add> throw fakeSuspensePromise;
<add> }
<add>
<add> ReactTestRenderer.create(
<add> <React.Suspense fallback={null}>
<add> <Example />
<add> </React.Suspense>,
<add> {unstable_isConcurrent: true},
<add> );
<add>
<add> expect(marks).toEqual(['--schedule-render-512']);
<add>
<add> marks.splice(0);
<add>
<add> expect(Scheduler).toFlushUntilNextPaint([]);
<add>
<add> expect(marks).toEqual([
<add> '--render-start-512',
<add> '--suspense-suspend-0-Example-\n at Example\n at Suspense',
<add> '--render-stop',
<add> '--commit-start-512',
<add> '--layout-effects-start-512',
<add> '--layout-effects-stop',
<add> '--commit-stop',
<add> ]);
<add>
<add> marks.splice(0);
<add>
<add> await expect(fakeSuspensePromise).rejects.toThrow();
<add> expect(marks).toEqual([
<add> '--suspense-rejected-0-Example-\n at Example\n at Suspense',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark cascading class component state updates', () => {
<add> class Example extends React.Component {
<add> state = {didMount: false};
<add> componentDidMount() {
<add> this.setState({didMount: true});
<add> }
<add> render() {
<add> return null;
<add> }
<add> }
<add>
<add> ReactTestRenderer.create(<Example />, {unstable_isConcurrent: true});
<add>
<add> expect(marks).toEqual(['--schedule-render-512']);
<add>
<add> marks.splice(0);
<add>
<add> expect(Scheduler).toFlushUntilNextPaint([]);
<add>
<add> expect(marks.map(normalizeCodeLocInfo)).toEqual([
<add> '--render-start-512',
<add> '--render-stop',
<add> '--commit-start-512',
<add> '--layout-effects-start-512',
<add> '--schedule-state-update-1-Example-\n in Example (at **)',
<add> '--layout-effects-stop',
<add> '--render-start-1',
<add> '--render-stop',
<add> '--commit-start-1',
<add> '--commit-stop',
<add> '--commit-stop',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark cascading class component force updates', () => {
<add> class Example extends React.Component {
<add> componentDidMount() {
<add> this.forceUpdate();
<add> }
<add> render() {
<add> return null;
<add> }
<add> }
<add>
<add> ReactTestRenderer.create(<Example />, {unstable_isConcurrent: true});
<add>
<add> expect(marks).toEqual(['--schedule-render-512']);
<add>
<add> marks.splice(0);
<add>
<add> expect(Scheduler).toFlushUntilNextPaint([]);
<add>
<add> expect(marks.map(normalizeCodeLocInfo)).toEqual([
<add> '--render-start-512',
<add> '--render-stop',
<add> '--commit-start-512',
<add> '--layout-effects-start-512',
<add> '--schedule-forced-update-1-Example-\n in Example (at **)',
<add> '--layout-effects-stop',
<add> '--render-start-1',
<add> '--render-stop',
<add> '--commit-start-1',
<add> '--commit-stop',
<add> '--commit-stop',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark render phase state updates for class component', () => {
<add> class Example extends React.Component {
<add> state = {didRender: false};
<add> render() {
<add> if (this.state.didRender === false) {
<add> this.setState({didRender: true});
<add> }
<add> return null;
<add> }
<add> }
<add>
<add> ReactTestRenderer.create(<Example />, {unstable_isConcurrent: true});
<add>
<add> expect(marks).toEqual(['--schedule-render-512']);
<add>
<add> marks.splice(0);
<add>
<add> expect(() => {
<add> expect(Scheduler).toFlushUntilNextPaint([]);
<add> }).toErrorDev('Cannot update during an existing state transition');
<add>
<add> expect(marks.map(normalizeCodeLocInfo)).toContain(
<add> '--schedule-state-update-1024-Example-\n in Example (at **)',
<add> );
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark render phase force updates for class component', () => {
<add> class Example extends React.Component {
<add> state = {didRender: false};
<add> render() {
<add> if (this.state.didRender === false) {
<add> this.forceUpdate(() => this.setState({didRender: true}));
<add> }
<add> return null;
<add> }
<add> }
<add>
<add> ReactTestRenderer.create(<Example />, {unstable_isConcurrent: true});
<add>
<add> expect(marks).toEqual(['--schedule-render-512']);
<add>
<add> marks.splice(0);
<add>
<add> expect(() => {
<add> expect(Scheduler).toFlushUntilNextPaint([]);
<add> }).toErrorDev('Cannot update during an existing state transition');
<add>
<add> expect(marks.map(normalizeCodeLocInfo)).toContain(
<add> '--schedule-forced-update-1024-Example-\n in Example (at **)',
<add> );
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark cascading layout updates', () => {
<add> function Example() {
<add> const [didMount, setDidMount] = React.useState(false);
<add> React.useLayoutEffect(() => {
<add> setDidMount(true);
<add> }, []);
<add> return didMount;
<add> }
<add>
<add> ReactTestRenderer.create(<Example />, {unstable_isConcurrent: true});
<add>
<add> expect(marks).toEqual(['--schedule-render-512']);
<add>
<add> marks.splice(0);
<add>
<add> expect(Scheduler).toFlushUntilNextPaint([]);
<add>
<add> expect(marks.map(normalizeCodeLocInfo)).toEqual([
<add> '--render-start-512',
<add> '--render-stop',
<add> '--commit-start-512',
<add> '--layout-effects-start-512',
<add> '--schedule-state-update-1-Example-\n in Example (at **)',
<add> '--layout-effects-stop',
<add> '--render-start-1',
<add> '--render-stop',
<add> '--commit-start-1',
<add> '--commit-stop',
<add> '--commit-stop',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark cascading passive updates', () => {
<add> function Example() {
<add> const [didMount, setDidMount] = React.useState(false);
<add> React.useEffect(() => {
<add> setDidMount(true);
<add> }, []);
<add> return didMount;
<add> }
<add>
<add> ReactTestRenderer.act(() => {
<add> ReactTestRenderer.create(<Example />, {unstable_isConcurrent: true});
<add> });
<add> expect(marks.map(normalizeCodeLocInfo)).toEqual([
<add> '--schedule-render-512',
<add> '--render-start-512',
<add> '--render-stop',
<add> '--commit-start-512',
<add> '--layout-effects-start-512',
<add> '--layout-effects-stop',
<add> '--commit-stop',
<add> '--passive-effects-start-512',
<add> '--schedule-state-update-1024-Example-\n in Example (at **)',
<add> '--passive-effects-stop',
<add> '--render-start-1024',
<add> '--render-stop',
<add> '--commit-start-1024',
<add> '--commit-stop',
<add> ]);
<add> });
<add>
<add> // @gate enableSchedulingProfiler
<add> it('should mark render phase updates', () => {
<add> function Example() {
<add> const [didRender, setDidRender] = React.useState(false);
<add> if (!didRender) {
<add> setDidRender(true);
<add> }
<add> return didRender;
<add> }
<add>
<add> ReactTestRenderer.act(() => {
<add> ReactTestRenderer.create(<Example />, {unstable_isConcurrent: true});
<add> });
<add>
<add> expect(marks.map(normalizeCodeLocInfo)).toContain(
<add> '--schedule-state-update-1024-Example-\n in Example (at **)',
<add> );
<add> });
<add>});
<ide><path>packages/shared/ReactFeatureFlags.js
<ide> export const enableFilterEmptyStringAttributesDOM = false;
<ide> // Intended to enable React core members to more easily debug scheduling issues in DEV builds.
<ide> export const enableDebugTracing = false;
<ide>
<add>// Adds user timing marks for e.g. state updates, suspense, and work loop stuff,
<add>// for an experimental scheduling profiler tool.
<add>export const enableSchedulingProfiler = false;
<add>
<ide> // Helps identify side effects in render-phase lifecycle hooks and setState
<ide> // reducers by double invoking them in Strict Mode.
<ide> export const debugRenderPhaseSideEffectsForStrictMode = __DEV__;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js
<ide> import typeof * as ExportsType from './ReactFeatureFlags.native-fb';
<ide>
<ide> // The rest of the flags are static for better dead code elimination.
<ide> export const enableDebugTracing = false;
<add>export const enableSchedulingProfiler = false;
<ide> export const enableProfilerTimer = __PROFILE__;
<ide> export const enableProfilerCommitHooks = false;
<ide> export const enableSchedulerTracing = __PROFILE__;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js
<ide> import typeof * as ExportsType from './ReactFeatureFlags.native-oss';
<ide>
<ide> export const debugRenderPhaseSideEffectsForStrictMode = false;
<ide> export const enableDebugTracing = false;
<add>export const enableSchedulingProfiler = false;
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__;
<ide> export const warnAboutDeprecatedLifecycles = true;
<ide> export const enableProfilerTimer = __PROFILE__;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js
<ide> import typeof * as ExportsType from './ReactFeatureFlags.test-renderer';
<ide>
<ide> export const debugRenderPhaseSideEffectsForStrictMode = false;
<ide> export const enableDebugTracing = false;
<add>export const enableSchedulingProfiler = false;
<ide> export const warnAboutDeprecatedLifecycles = true;
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
<ide> export const enableProfilerTimer = __PROFILE__;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
<ide> import typeof * as ExportsType from './ReactFeatureFlags.test-renderer.www';
<ide>
<ide> export const debugRenderPhaseSideEffectsForStrictMode = false;
<ide> export const enableDebugTracing = false;
<add>export const enableSchedulingProfiler = false;
<ide> export const warnAboutDeprecatedLifecycles = true;
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
<ide> export const enableProfilerTimer = __PROFILE__;
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.js
<ide> import typeof * as ExportsType from './ReactFeatureFlags.testing';
<ide>
<ide> export const debugRenderPhaseSideEffectsForStrictMode = false;
<ide> export const enableDebugTracing = false;
<add>export const enableSchedulingProfiler = false;
<ide> export const warnAboutDeprecatedLifecycles = true;
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
<ide> export const enableProfilerTimer = __PROFILE__;
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js
<ide> import typeof * as ExportsType from './ReactFeatureFlags.testing.www';
<ide>
<ide> export const debugRenderPhaseSideEffectsForStrictMode = false;
<ide> export const enableDebugTracing = false;
<add>export const enableSchedulingProfiler = false;
<ide> export const warnAboutDeprecatedLifecycles = true;
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
<ide> export const enableProfilerTimer = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.www-dynamic.js
<ide> export const warnAboutSpreadingKeyToJSX = __VARIANT__;
<ide> export const disableInputAttributeSyncing = __VARIANT__;
<ide> export const enableFilterEmptyStringAttributesDOM = __VARIANT__;
<ide> export const enableLegacyFBSupport = __VARIANT__;
<del>export const enableDebugTracing = !__VARIANT__;
<ide> export const decoupleUpdatePriorityFromScheduler = __VARIANT__;
<ide>
<add>// TODO: These features do not currently exist in the new reconciler fork.
<add>export const enableDebugTracing = !__VARIANT__;
<add>export const enableSchedulingProfiler = !__VARIANT__ && __PROFILE__;
<add>
<ide> // This only has an effect in the new reconciler. But also, the new reconciler
<ide> // is only enabled when __VARIANT__ is true. So this is set to the opposite of
<ide> // __VARIANT__ so that it's `false` when running against the new reconciler.
<ide><path>packages/shared/forks/ReactFeatureFlags.www.js
<ide> export const {
<ide> enableLegacyFBSupport,
<ide> deferRenderPhaseUpdateToNextBatch,
<ide> decoupleUpdatePriorityFromScheduler,
<add> enableDebugTracing,
<add> enableSchedulingProfiler,
<ide> } = dynamicFeatureFlags;
<ide>
<ide> // On WWW, __EXPERIMENTAL__ is used for a new modern build.
<ide> export const warnUnstableRenderSubtreeIntoContainer = false;
<ide> // to the correct value.
<ide> export const enableNewReconciler = __VARIANT__;
<ide>
<del>// TODO: This does not currently exist in the new reconciler fork.
<del>export const enableDebugTracing = !__VARIANT__;
<del>
<ide> // Flow magic to verify the exports of this file match the original version.
<ide> // eslint-disable-next-line no-unused-vars
<ide> type Check<_X, Y: _X, X: Y = _X> = null; | 16 |
Python | Python | update boston housing dataset | 5810f7a9c78226b604be7bc167630b617cd9f3c3 | <ide><path>keras/datasets/boston_housing.py
<ide> def load_data(path='boston_housing.npz', seed=113, test_split=0.2):
<ide> Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
<ide> """
<ide> assert 0 <= test_split < 1
<del> path = get_file(path, origin='https://s3.amazonaws.com/keras-datasets/boston_housing.npz')
<add> path = get_file(path,
<add> origin='https://s3.amazonaws.com/keras-datasets/boston_housing.npz',
<add> file_hash='f553886a1f8d56431e820c5b82552d9d95cfcb96d1e678153f8839538947dff5')
<ide> f = np.load(path)
<ide> x = f['x']
<ide> y = f['y'] | 1 |
Javascript | Javascript | remove debug statement in appactions | e832c2ebc53c29e7c20d953311e49188ce6c9a16 | <ide><path>common/app/flux/Actions.js
<ide> import { Actions } from 'thundercats';
<del>import debugFactory from 'debug';
<ide>
<del>const debug = debugFactory('freecc:app:actions');
<ide>
<ide> export default Actions({
<ide> shouldBindMethods: true,
<ide> export default Actions({
<ide> return null;
<ide> }
<ide>
<del> debug('fetching user data');
<ide> return this.readService$('user', null, null)
<del> .map(function({
<add> .map(({
<ide> username,
<ide> picture,
<ide> progressTimestamps = [],
<ide> isFrontEndCert,
<ide> isFullStackCert
<del> }) {
<add> }) => {
<ide> return {
<ide> username,
<ide> picture, | 1 |
Text | Text | update the documentation | 30e3775b8b209242141357bad0a69b6cc503c6f9 | <ide><path>docs/api-guide/authentication.md
<ide> If you're using an AJAX style API with SessionAuthentication, you'll need to mak
<ide>
<ide> ## OAuth2Authentication
<ide>
<del>This authentication uses [OAuth 2.0][rfc6749] authentication scheme. It depends on optional [`django-oauth2-provider`][django-oauth2-provider]. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS` :
<add>---
<add>
<add>** Note:** This isn't available for Python 3, because the module [`django-oauth2-provider`][django-oauth2-provider] is not Python 3 ready.
<add>
<add>---
<add>
<add>This authentication uses [OAuth 2.0][rfc6749] authentication scheme. It depends on the optional [`django-oauth2-provider`][django-oauth2-provider] project. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS` :
<ide>
<ide> INSTALLED_APPS = (
<ide> #(...)
<ide> Finally, sync your database with those two new django apps.
<ide> $ python manage.py syncdb
<ide> $ python manage.py migrate
<ide>
<del>`OAuth2Authentication` class provides only token verification for requests. The *oauth 2 dance* is taken care by the [`django-oaut2-provider`][django-oauth2-provider] dependency. Unfortunately, there isn't a lot of [documentation][django-oauth2-provider--doc] currently on how to *dance* with this package on the client side.
<add>`OAuth2Authentication` class provides only token verification for requests. The *oauth 2 dance* is taken care by the [`django-oaut2-provider`][django-oauth2-provider] dependency. The official [documentation][django-oauth2-provider--doc] is being [rewritten][django-oauth2-provider--rewritten-doc].
<ide>
<ide> The Good news is, here is a minimal "How to start" because **OAuth 2** is dramatically simpler than **OAuth 1**, so no more headache with signature, cryptography on client side, and other complex things.
<ide>
<ide> Your client interface – I mean by that your iOS code, HTML code, or whatev
<ide>
<ide> ---
<ide>
<del>**Note:** Remember that you are **highly encourage** to use HTTPS for all your OAuth 2 requests. And by *highly encourage* I mean you SHOULD always use HTTPS otherwise you will expose user passwords for any person who can intercept the request (like a man in the middle attack).
<add>**Note:** Remember that you should use HTTPS in production.
<ide>
<ide> ---
<ide>
<ide> You can use the command line to test that your local configuration is working :
<ide>
<del> $ curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOU_PASSWORD" http://localhost:8000/oauth2/access_token/
<add> $ curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD" http://localhost:8000/oauth2/access_token/
<ide>
<ide> Here is the response you should get :
<ide>
<ide> The command line to test the authentication looks like :
<ide>
<ide> $ curl -H "Authorization: Bearer <your-access-token>" http://localhost:8000/api/?client_id=YOUR_CLIENT_ID\&client_secret=YOUR_CLIENT_SECRET
<ide>
<del>And hopefully, it will work like a charm.
<add>And it will work like a charm.
<ide>
<ide> # Custom authentication
<ide>
<ide> HTTP digest authentication is a widely implemented scheme that was intended to r
<ide> [djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
<ide> [django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider
<ide> [django-oauth2-provider--doc]: https://django-oauth2-provider.readthedocs.org/en/latest/
<add>[django-oauth2-provider--rewritten-doc]: http://django-oauth2-provider-dulaccc.readthedocs.org/en/latest/
<ide> [rfc6749]: http://tools.ietf.org/html/rfc6749 | 1 |
Text | Text | improve translation of spanish | bdb1376d581652090edc1943eb9e7b0357456593 | <ide><path>guide/spanish/javascript/converting-strings-to-numbers/index.md
<ide> localeTitle: Convertir cadenas a números
<ide> ---
<ide> ## Convertir cadenas a números
<ide>
<del>La `parseInt()` analiza un argumento de cadena y devuelve un número entero de la base especificada (la base en sistemas numéricos matemáticos).
<add>La función `parseInt()` analiza un argumento de tipo cadena y devuelve un número entero de la base especificada (la base en sistemas numéricos matemáticos).
<ide>
<ide> ```js
<ide> parseInt(string, radix);
<ide> La `parseInt()` analiza un argumento de cadena y devuelve un número entero de l
<ide> string
<ide> ```
<ide>
<del>El valor a analizar. Si el argumento de `string` no es una cadena, entonces se convierte en una cadena (utilizando la `ToString` abstracta `ToString` ). Los espacios en blanco iniciales en el argumento de cadena se ignoran. '= base Un número entero entre 2 y 36 que representa la raíz (la base en sistemas de numeración matemática) de la cadena mencionada anteriormente. Especifique `10` para el sistema de numeración decimal comúnmente utilizado por los humanos. Siempre especifique este parámetro para eliminar la confusión del lector y garantizar un comportamiento predecible. Las diferentes implementaciones producen resultados diferentes cuando no se especifica una raíz, por lo general, el valor predeterminado es 10. Valor de retorno Un número entero analizado de la cadena dada. Si el primer carácter no se puede convertir en un número, se devuelve `NaN` .
<add>El valor a analizar. Si el argumento `string` no es una cadena, entonces se convierte en una cadena (utilizando la operación abstracta `ToString` ). Los espacios en blanco iniciales en el argumento de cadena se ignoran. '= base Un número entero entre 2 y 36 que representa la raíz (la base en sistemas de numeración matemática) de la cadena mencionada anteriormente. Especifique `10` para el sistema de numeración decimal comúnmente utilizado por los humanos. Siempre especifique este parámetro para eliminar la confusión del lector y garantizar un comportamiento predecible. Las diferentes implementaciones producen resultados diferentes cuando no se especifica una raíz, por lo general, el valor predeterminado es 10. Valor de retorno Un número entero analizado de la cadena dada. Si el primer carácter no se puede convertir en un número, se devuelve `NaN` .
<ide>
<ide> ### Descripción
<ide>
<ide> Si `parseInt` encuentra un carácter que no es un número en el radix especifica
<ide>
<ide> Debido a que algunos números incluyen el carácter `e` en su representación de cadena (por ejemplo, `6.022e23` ), el uso de `parseInt` para truncar valores numéricos producirá resultados inesperados cuando se utiliza en números muy grandes o muy pequeños. `parseInt` no debe utilizarse como sustituto de `Math.floor()` .
<ide>
<del>Si radix `undefined` está `undefined` o es 0 (o está ausente), JavaScript asume lo siguiente:
<add>Si radix está `undefined` o es 0 (o está ausente), JavaScript asume lo siguiente:
<ide>
<del>* Si la `string` entrada comienza con "0x" o "0X", radix es 16 (hexadecimal) y se analiza el resto de la cadena.
<del>* Si la `string` entrada comienza con "0", la raíz es ocho (octal) o 10 (decimal). Exactamente qué radio se elige depende de la implementación. ECMAScript 5 especifica que se usa 10 (decimal), pero no todos los navegadores lo admiten todavía. Por este motivo, siempre especifique un radix cuando use parseInt.
<del>* Si la `string` entrada comienza con cualquier otro valor, la raíz es 10 (decimal).
<add>* Si el `string` comienza con "0x" o "0X", radix es 16 (hexadecimal) y se analiza el resto de la cadena.
<add>* Si el `string` comienza con "0", la raíz es ocho (octal) o 10 (decimal). Exactamente qué radio se elige depende de la implementación. ECMAScript 5 especifica que se usa 10 (decimal), pero no todos los navegadores lo admiten todavía. Por este motivo, siempre especifique un radix cuando use parseInt.
<add>* Si el `string` comienza con cualquier otro valor, la raíz es 10 (decimal).
<ide> * Si el primer carácter no se puede convertir en un número, parseInt devuelve NaN.
<ide>
<ide> Para fines aritméticos, el valor de NaN no es un número en ningún radix. Puede llamar a la función isNaN para determinar si el resultado de parseInt es NaN. Si NaN se pasa a operaciones aritméticas, los resultados de la operación también serán NaN.
<ide> El siguiente ejemplo devuelve `224` :
<ide> [ParseInt en MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
<ide>
<ide> * [parseInt ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) y [parseFloat ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) intentan convertir la cadena a un número si es posible. Por ejemplo, `var x = parseInt("100"); // x = 100`
<del>* [El número ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/number) se convertirá en un número por el cual se puede representar el valor. Esto incluye las fechas en el número de milisegundos desde la medianoche del 1 de enero de 1970 UTC, los valores booleanos hasta 1 o 0, y los valores que no se pueden convertir a un número reconocible se convertirán en NaN. Eso significa que no es un número y, técnicamente, también es un número.
<ide>\ No newline at end of file
<add>* [El número ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/number) se convertirá en un número por el cual se puede representar el valor. Esto incluye las fechas en el número de milisegundos desde la medianoche del 1 de enero de 1970 UTC, los valores booleanos hasta 1 o 0, y los valores que no se pueden convertir a un número reconocible se convertirán en NaN. Eso significa que no es un número y, técnicamente, también es un número. | 1 |
Python | Python | update imdb example | 5d1976c46dcd8046af45dea0e38967dc90a7104c | <ide><path>examples/imdb_lstm.py
<ide>
<ide> - RNNs are tricky. Choice of batch size is important,
<ide> choice of loss and optimizer is critical, etc.
<del> Most configurations won't converge.
<add> Some configurations won't converge.
<ide>
<del> - LSTM loss decrease during training can be quite different
<del> from what you see with CNNs/MLPs/etc. It's more or less a sigmoid
<del> instead of an inverse exponential.
<add> - LSTM loss decrease patterns during training can be quite different
<add> from what you see with CNNs/MLPs/etc.
<ide>
<ide> GPU command:
<ide> THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python imdb_lstm.py
<ide>
<del> 250s/epoch on GPU (GT 650M), vs. 400s/epoch on CPU (2.4Ghz Core i7).
<add> 250s/epoch on GPU (GT 650M), vs. 400s/epoch on CPU (2.4Ghz Core i7).
<add> Increasing the batch_size increases the GPU speedup.
<ide> '''
<ide>
<del>max_features=20000
<add>max_features = 20000
<ide> maxlen = 100 # cut texts after this number of words (among top max_features most common words)
<ide> batch_size = 16
<ide>
<add>np.random.seed(1337)
<add>
<ide> print("Loading data...")
<ide> (X_train, y_train), (X_test, y_test) = imdb.load_data(nb_words=max_features, test_split=0.2)
<ide> print(len(X_train), 'train sequences')
<ide>
<ide> print('Build model...')
<ide> model = Sequential()
<del>model.add(Embedding(max_features, 256))
<add>model.add(Embedding(max_features, 256, mask_zero=True))
<ide> model.add(LSTM(256, 128)) # try using a GRU instead, for fun
<ide> model.add(Dropout(0.5))
<ide> model.add(Dense(128, 1))
<ide> model.compile(loss='binary_crossentropy', optimizer='adam', class_mode="binary")
<ide>
<ide> print("Train...")
<del>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=5, validation_split=0.1, show_accuracy=True)
<add>model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=4, validation_split=0.1, show_accuracy=True)
<ide> score = model.evaluate(X_test, y_test, batch_size=batch_size)
<ide> print('Test score:', score)
<ide> | 1 |
Text | Text | add redux-data-structures to ecosystem | 3f5d726dc78dbdff26ca2b7ed46006433b6e7e3f | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide> * [redux-mock-store](https://github.com/arnaudbenard/redux-mock-store) — Mock redux store for testing your app
<ide> * [redux-actions-assertions](https://github.com/dmitry-zaets/redux-actions-assertions) — Assertions for Redux actions testing
<ide> * [redux-bootstrap](https://github.com/remojansen/redux-bootstrap) — Bootstrapping function for Redux applications
<add>* [redux-data-structures](https://redux-data-structures.js.org/) — Reducer factory (higher-order functions) for counters, maps, lists (queues, stacks), sets, etc.
<ide>
<ide> ### DevTools
<ide> | 1 |
PHP | PHP | add test coverage to new exception methods | f064e82b72dc32292fdd63b0d1da290f60164e16 | <ide><path>src/View/Exception/MissingCellTemplateException.php
<ide> class MissingCellTemplateException extends MissingTemplateException
<ide> /**
<ide> * @var string
<ide> */
<del> protected $type = 'Cell view';
<add> protected $type = 'Cell template';
<ide>
<ide> /**
<ide> * Constructor
<ide><path>src/View/Exception/MissingTemplateException.php
<ide> class MissingTemplateException extends Exception
<ide> */
<ide> public function __construct($file, array $paths = [], $code = null, $previous = null)
<ide> {
<del> $this->file = is_array($file) ? $file[0] : $file;
<add> $this->file = is_array($file) ? array_pop($file) : $file;
<ide> $this->paths = $paths;
<ide>
<ide> parent::__construct($this->formatMessage(), $code, $previous);
<ide><path>tests/TestCase/ExceptionsTest.php
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\Exception\PersistenceFailedException;
<ide> use Cake\TestSuite\TestCase;
<add>use Cake\View\Exception\MissingElementException;
<add>use Cake\View\Exception\MissingLayoutException;
<add>use Cake\View\Exception\MissingCellTemplateException;
<add>use Cake\View\Exception\MissingTemplateException;
<ide> use Exception;
<ide>
<ide> class ExceptionsTest extends TestCase
<ide> public function testPersistenceFailedException()
<ide> $this->assertSame($previous, $exception->getPrevious());
<ide> }
<ide>
<add> /**
<add> * Test the template exceptions
<add> *
<add> * @return void
<add> */
<add> public function testMissingTemplateExceptions()
<add> {
<add> $previous = new Exception();
<add>
<add> $error = new MissingTemplateException('view.ctp', ['path/a', 'path/b'], 100, $previous);
<add> $this->assertContains("Template file 'view.ctp' could not be found", $error->getMessage());
<add> $this->assertContains('- path/a', $error->getMessage());
<add> $this->assertSame($previous, $error->getPrevious());
<add> $this->assertSame(100, $error->getCode());
<add> $attributes = $error->getAttributes();
<add> $this->assertArrayHasKey('file', $attributes);
<add> $this->assertArrayHasKey('paths', $attributes);
<add>
<add> $error = new MissingLayoutException('default.ctp', ['path/a', 'path/b'], 100, $previous);
<add> $this->assertContains("Layout file 'default.ctp' could not be found", $error->getMessage());
<add> $this->assertContains('- path/a', $error->getMessage());
<add> $this->assertSame($previous, $error->getPrevious());
<add> $this->assertSame(100, $error->getCode());
<add>
<add> $error = new MissingElementException('view.ctp', ['path/a', 'path/b'], 100, $previous);
<add> $this->assertContains("Element file 'view.ctp' could not be found", $error->getMessage());
<add> $this->assertContains('- path/a', $error->getMessage());
<add> $this->assertSame($previous, $error->getPrevious());
<add> $this->assertSame(100, $error->getCode());
<add>
<add> $error = new MissingCellTemplateException('Articles', 'view.ctp', ['path/a', 'path/b'], 100, $previous);
<add> $this->assertContains("Cell template file 'view.ctp' could not be found", $error->getMessage());
<add> $this->assertContains('- path/a', $error->getMessage());
<add> $this->assertSame($previous, $error->getPrevious());
<add> $this->assertSame(100, $error->getCode());
<add> $attributes = $error->getAttributes();
<add> $this->assertArrayHasKey('name', $attributes);
<add> $this->assertArrayHasKey('file', $attributes);
<add> $this->assertArrayHasKey('paths', $attributes);
<add> }
<add>
<ide> /**
<ide> * Provides pairs of exception name and default code.
<ide> *
<ide> public function exceptionProvider()
<ide> ['Cake\Routing\Exception\RedirectException', 302],
<ide> ['Cake\Utility\Exception\XmlException', 0],
<ide> ['Cake\View\Exception\MissingCellException', 500],
<del> ['Cake\View\Exception\MissingCellViewException', 500],
<del> ['Cake\View\Exception\MissingElementException', 500],
<ide> ['Cake\View\Exception\MissingHelperException', 500],
<del> ['Cake\View\Exception\MissingLayoutException', 500],
<del> ['Cake\View\Exception\MissingTemplateException', 500],
<ide> ['Cake\View\Exception\MissingViewException', 500],
<ide> ];
<ide> } | 3 |
Javascript | Javascript | fix duplicate statement in todomvc test spec | 3fb712d1f0efc9102ec1764b2847b9df90a1d7ea | <ide><path>examples/todomvc/test/components/TodoTextInput.spec.js
<ide> function setup(propOverrides) {
<ide> <TodoTextInput {...props} />
<ide> )
<ide>
<del> let output = renderer.getRenderOutput()
<del>
<del> output = renderer.getRenderOutput()
<add> const output = renderer.getRenderOutput()
<ide>
<ide> return {
<ide> props: props, | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.