content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
reword exception explanation
a8ef06d60914b41dbe89abf26119a938ed4db1a7
<ide><path>src/Cache/SimpleCacheEngine.php <ide> public function setMultiple($values, $ttl = null) <ide> * <ide> * @param iterable $keys A list of string-based keys to be deleted. <ide> * @return bool True if the items were successfully removed. False if there was an error. <del> * @throws \Psr\SimpleCache\InvalidArgumentException <del> * MUST be thrown if $keys is neither an array nor a Traversable, <add> * @throws \Psr\SimpleCache\InvalidArgumentException If $keys is neither an array nor a Traversable, <ide> * or if any of the $keys are not a legal value. <ide> */ <ide> public function deleteMultiple($keys)
1
PHP
PHP
use fluent routes
ef1ef753baa7192cbceb1771d18ce6727aaaf7f5
<ide><path>app/Providers/RouteServiceProvider.php <ide> public function map() <ide> */ <ide> protected function mapWebRoutes() <ide> { <del> Route::group([ <del> 'middleware' => 'web', <del> 'namespace' => $this->namespace, <del> ], function ($router) { <del> require base_path('routes/web.php'); <del> }); <add> Route::middleware('web') <add> ->namespace($this->namespace) <add> ->group(function ($router) { <add> require base_path('routes/web.php'); <add> }); <ide> } <ide> <ide> /** <ide> protected function mapWebRoutes() <ide> */ <ide> protected function mapApiRoutes() <ide> { <del> Route::group([ <del> 'middleware' => 'api', <del> 'namespace' => $this->namespace, <del> 'prefix' => 'api', <del> ], function ($router) { <del> require base_path('routes/api.php'); <del> }); <add> Route::prefix('api') <add> ->middleware('api') <add> ->namespace($this->namespace) <add> ->group(function ($router) { <add> require base_path('routes/api.php'); <add> }); <ide> } <ide> }
1
Javascript
Javascript
set the base href of the context in parsehtml
10fc59007d717432ea126e49ce4142e6c4d5136e
<ide><path>src/core/parseHTML.js <ide> jQuery.parseHTML = function( data, context, keepScripts ) { <ide> context = false; <ide> } <ide> <del> // Stop scripts or inline event handlers from being executed immediately <del> // by using document.implementation <del> context = context || ( support.createHTMLDocument ? <del> document.implementation.createHTMLDocument( "" ) : <del> document ); <del> <del> var parsed = rsingleTag.exec( data ), <del> scripts = !keepScripts && []; <add> var base, parsed, scripts; <add> <add> if ( !context ) { <add> <add> // Stop scripts or inline event handlers from being executed immediately <add> // by using document.implementation <add> if ( support.createHTMLDocument ) { <add> context = document.implementation.createHTMLDocument( "" ); <add> <add> // Set the base href for the created document <add> // so any parsed elements with URLs <add> // are based on the document's URL (gh-2965) <add> base = context.createElement( "base" ); <add> base.href = document.location.href; <add> context.head.appendChild( base ); <add> } else { <add> context = document; <add> } <add> } <add> <add> parsed = rsingleTag.exec( data ); <add> scripts = !keepScripts && []; <ide> <ide> // Single tag <ide> if ( parsed ) { <ide><path>test/unit/core.js <ide> QUnit.test( "jQuery.parseHTML", function( assert ) { <ide> assert.ok( jQuery.parseHTML( "<#if><tr><p>This is a test.</p></tr><#/if>" ) || true, "Garbage input should not cause error" ); <ide> } ); <ide> <add>QUnit.test( "jQuery.parseHTML(<a href>) - gh-2965", function( assert ) { <add> assert.expect( 1 ); <add> <add> var html = "<a href='test.html'></a>", <add> href = jQuery.parseHTML( html )[ 0 ].href; <add> <add> assert.ok( /\/test\.html$/.test( href ), "href is not lost after parsing anchor" ); <add>} ); <add> <ide> if ( jQuery.support.createHTMLDocument ) { <ide> QUnit.asyncTest( "jQuery.parseHTML", function( assert ) { <ide> assert.expect( 1 );
2
PHP
PHP
fix coding standards
5aa3113cf8d13615ca458b174909b4dcbcc08d1c
<ide><path>Cake/ORM/Entity.php <ide> public function dirty($property, $isDirty = null) { <ide> unset($this->_dirty[$property]); <ide> return false; <ide> } <del> <add> <ide> $this->_dirty[$property] = true; <ide> return true; <ide> } <ide><path>Cake/ORM/Query.php <ide> public function first() { <ide> $this->bufferResults(); <ide> $this->_results = $this->execute(); <ide> return $this->_results->one(); <del> <ide> } <ide> <add>/** <add> * Toggle hydrating entites. <add> * <add> * If set to false array results will be returned <add> * <add> * @param boolean|null $enable Use a boolean to set the hydration mode. <add> * Null will fetch the current hydration mode. <add> * @return boolean|Query A boolean when reading, and $this when setting the mode. <add> */ <ide> public function hydrate($enable = null) { <ide> if ($enable === null) { <ide> return $this->_hydrate; <ide><path>Cake/ORM/Table.php <ide> protected function _insert($entity, $data) { <ide> * @param \Cake\ORM\Entity the subject entity from were $data was extracted <ide> * @param array $data The actual data that needs to be saved <ide> * @return \Cake\ORM\Entity|boolean <add> * @throws \InvalidArgumentException When primary key data is missing. <ide> */ <ide> protected function _update($entity, $data) { <ide> $primaryKey = $entity->extract((array)$this->primaryKey());
3
Python
Python
add test for boolean insert
1688b29fb1ea4e548762ae79522c50abce88d55b
<ide><path>numpy/lib/tests/test_function_base.py <ide> def test_basic(self): <ide> assert_equal(insert(a, [1, 1, 1], [1, 2, 3]), [1, 1, 2, 3, 2, 3]) <ide> assert_equal(insert(a, 1,[1,2,3]), [1, 1, 2, 3, 2, 3]) <ide> assert_equal(insert(a,[1,2,3],9),[1,9,2,9,3,9]) <add> b = np.array([0, 1], dtype=np.float64) <add> assert_equal(insert(b, 0, b[0]), [0., 0., 1.]) <ide> def test_multidim(self): <ide> a = [[1, 1, 1]] <ide> r = [[2, 2, 2],
1
Javascript
Javascript
note the changes to gitrepository
15b13e3ddc15d608d5c839a9ee160a3d1a6b56a8
<ide><path>src/git-repository-async.js <ide> const submoduleMode = 57344 // TODO: compose this from libgit2 constants <ide> // Just using this for _.isEqual and _.object, we should impl our own here <ide> import _ from 'underscore-plus' <ide> <add>// For the most part, this class behaves the same as `GitRepository`, with a few <add>// notable differences: <add>// * Errors are generally propagated out to the caller instead of being <add>// swallowed within `GitRepositoryAsync`. <add>// * Methods accepting a path shouldn't be given a null path, unless it is <add>// specifically allowed as noted in the method's documentation. <ide> export default class GitRepositoryAsync { <ide> static open (path, options = {}) { <ide> // QUESTION: Should this wrap Git.Repository and reject with a nicer message?
1
Javascript
Javascript
fix javascript strict warnings in driver.js
31cb9b49d502c387477e6c7f42da127243e6021b
<ide><path>test/driver.js <ide> function nextTask() { <ide> cleanup(); <ide> <ide> if (currentTaskIdx == manifest.length) { <del> return done(); <add> done(); <add> return; <ide> } <ide> var task = manifest[currentTaskIdx]; <ide> task.round = 0; <ide> function nextTask() { <ide> } <ide> <ide> function isLastPage(task) { <del> return task.pageNum > task.pdfDoc.numPages || task.pageNum > task.pageLimit; <add> return task.pageNum > (task.pageLimit || task.pdfDoc.numPages); <ide> } <ide> <ide> function canvasToDataURL() {
1
PHP
PHP
add missing options to numberhelper docblocks
730ac10ae4d54b7dfb1af211ee804df7d2910eba
<ide><path>lib/Cake/View/Helper/NumberHelper.php <ide> class NumberHelper extends AppHelper { <ide> */ <ide> protected $_currencyDefaults = array( <ide> 'wholeSymbol' => '', 'wholePosition' => 'before', 'fractionSymbol' => '', 'fractionPosition' => 'after', <del> 'zero' => '0', 'places' => 2, 'thousands' => ',', 'decimals' => '.','negative' => '()', 'escape' => true, <add> 'zero' => '0', 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true, <ide> ); <ide> <ide> /** <ide> public function format($number, $options = false) { <ide> * - `thousands` - Thousands separator ie. ',' <ide> * - `decimals` - Decimal separator symbol ie. '.' <ide> * - `negative` - Symbol for negative numbers. If equal to '()', the number will be wrapped with ( and ) <del> * - `escape` - Should the output be htmlentity escaped? Defaults to true <add> * - `escape` - Should the output be htmlentity escaped? Defaults to true. <add> * - `wholeSymbol` String to use for whole numbers ie. ' dollars'. <add> * - `wholePosition` Either 'before' or 'after' to place the whole symbol. <add> * - `fractionSymbol` String to use for fraction numbers ie. ' cents'. <add> * - `fractionPosition` Either 'before' or 'after' to place the fraction symbol. <ide> * <ide> * @param float $number <ide> * @param string $currency Shortcut to default options. Valid values are 'USD', 'EUR', 'GBP', otherwise <ide> public function currency($number, $currency = 'USD', $options = array()) { <ide> * <ide> * {{{ <ide> * array( <del> * 'before' => '$', 'after' => 'c', 'zero' => 0, 'places' => 2, 'thousands' => ',', <del> * 'decimals' => '.', 'negative' => '()', 'escape' => true <add> * 'wholeSymbol' => '', 'wholePosition' => 'before', <add> * 'fractionSymbol' => '', 'fractionPosition' => 'after', <add> * 'zero' => '0', 'places' => 2, 'thousands' => ',', <add> * 'decimals' => '.', 'negative' => '()', 'escape' => true, <ide> * ) <ide> * }}} <ide> *
1
Ruby
Ruby
remove spaces around make-style variables
fb8707df4e894e4828b6357d915326a98d81c534
<ide><path>Library/Homebrew/utils.rb <ide> module HomebrewInreplaceExtension <ide> # value with "new_value", or removes the definition entirely. <ide> # See inreplace in utils.rb <ide> def change_make_var! flag, new_value <del> new_value = "#{flag} = #{new_value}" unless new_value.to_s.empty? <add> new_value = "#{flag}=#{new_value}" unless new_value.to_s.empty? <ide> gsub! Regexp.new("^#{flag}\\s*=.*$"), new_value.to_s <ide> end <ide> def remove_make_var! flags
1
Java
Java
add support for rsocket interface client
8423b2cab77f0ecfdde93324f7a1e6a6cd0f2a2f
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Payload.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * <p>This attribute may or may not be supported depending on whether the message being <ide> * handled contains a non-primitive Object as its payload or is in serialized form and <ide> * requires message conversion. <del> * <p>When processing STOMP over WebSocket messages this attribute is not supported. <add> * <p>This attribute is not supported for: <add> * <ul> <add> * <li>STOMP over WebSocket messages</li> <add> * <li>RSocket interface client</li> <add> * </ul> <ide> * @since 4.2 <ide> */ <ide> @AliasFor("value") <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java <ide> public MimeType metadataMimeType() { <ide> return this.metadataMimeType; <ide> } <ide> <add> @Override <add> public RSocketStrategies strategies() { <add> return this.strategies; <add> } <add> <add> <ide> @Override <ide> public RequestSpec route(String route, Object... vars) { <ide> return new DefaultRequestSpec(route, vars); <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java <ide> public interface RSocketRequester extends Disposable { <ide> */ <ide> MimeType metadataMimeType(); <ide> <add> /** <add> * Return the configured {@link RSocketStrategies}. <add> */ <add> RSocketStrategies strategies(); <add> <ide> /** <ide> * Begin to specify a new request with the given route to a remote handler. <ide> * <p>The route can be a template with placeholders, e.g. <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/DestinationVariableArgumentResolver.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.util.Collection; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.lang.Nullable; <add>import org.springframework.messaging.handler.annotation.DestinationVariable; <add> <add>/** <add> * {@link RSocketServiceArgumentResolver} for a <add> * {@link DestinationVariable @DestinationVariable} annotated argument. <add> * <add> * <p>The argument is treated as a single route variable, or in case of a <add> * Collection or an array, as multiple route variables. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public class DestinationVariableArgumentResolver implements RSocketServiceArgumentResolver { <add> <add> @Override <add> public boolean resolve( <add> @Nullable Object argument, MethodParameter parameter, RSocketRequestValues.Builder requestValues) { <add> <add> DestinationVariable annot = parameter.getParameterAnnotation(DestinationVariable.class); <add> if (annot == null) { <add> return false; <add> } <add> <add> if (argument != null) { <add> if (argument instanceof Collection) { <add> ((Collection<?>) argument).forEach(requestValues::addRouteVariable); <add> return true; <add> } <add> else if (argument.getClass().isArray()) { <add> for (Object variable : (Object[]) argument) { <add> requestValues.addRouteVariable(variable); <add> } <add> return true; <add> } <add> else { <add> requestValues.addRouteVariable(argument); <add> } <add> } <add> <add> return true; <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/MetadataArgumentResolver.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.lang.Nullable; <add>import org.springframework.util.Assert; <add>import org.springframework.util.MimeType; <add> <add>/** <add> * {@link RSocketServiceArgumentResolver} for metadata entries. <add> * <add> * <p>Supports a sequence of an {@link Object} parameter for the metadata value, <add> * followed by a {@link MimeType} parameter for the metadata mime type. <add> * <add> * <p>This should be ordered last to give other, more specific resolvers a <add> * chance to resolve the argument. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public class MetadataArgumentResolver implements RSocketServiceArgumentResolver { <add> <add> @Override <add> public boolean resolve( <add> @Nullable Object argument, MethodParameter parameter, RSocketRequestValues.Builder requestValues) { <add> <add> int index = parameter.getParameterIndex(); <add> Class<?>[] paramTypes = parameter.getExecutable().getParameterTypes(); <add> <add> if (parameter.getParameterType().equals(MimeType.class)) { <add> Assert.notNull(argument, "MimeType parameter is required"); <add> Assert.state(index > 0, "MimeType parameter should have preceding metadata object parameter"); <add> requestValues.addMimeType((MimeType) argument); <add> return true; <add> } <add> <add> if (paramTypes.length > (index + 1) && MimeType.class.equals(paramTypes[index + 1])) { <add> Assert.notNull(argument, "MimeType parameter is required"); <add> requestValues.addMetadata(argument); <add> return true; <add> } <add> <add> return false; <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/PayloadArgumentResolver.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.ParameterizedTypeReference; <add>import org.springframework.core.ReactiveAdapter; <add>import org.springframework.core.ReactiveAdapterRegistry; <add>import org.springframework.lang.Nullable; <add>import org.springframework.messaging.handler.annotation.Payload; <add>import org.springframework.util.Assert; <add> <add>/** <add> * {@link RSocketServiceArgumentResolver} for {@link Payload @Payload} <add> * annotated arguments. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public class PayloadArgumentResolver implements RSocketServiceArgumentResolver { <add> <add> private final ReactiveAdapterRegistry reactiveAdapterRegistry; <add> <add> private final boolean useDefaultResolution; <add> <add> <add> public PayloadArgumentResolver(ReactiveAdapterRegistry reactiveAdapterRegistry, boolean useDefaultResolution) { <add> this.useDefaultResolution = useDefaultResolution; <add> Assert.notNull(reactiveAdapterRegistry, "ReactiveAdapterRegistry is required"); <add> this.reactiveAdapterRegistry = reactiveAdapterRegistry; <add> } <add> <add> <add> @Override <add> public boolean resolve( <add> @Nullable Object argument, MethodParameter parameter, RSocketRequestValues.Builder requestValues) { <add> <add> Payload annot = parameter.getParameterAnnotation(Payload.class); <add> if (annot == null && !this.useDefaultResolution) { <add> return false; <add> } <add> <add> if (argument != null) { <add> ReactiveAdapter reactiveAdapter = this.reactiveAdapterRegistry.getAdapter(parameter.getParameterType()); <add> if (reactiveAdapter == null) { <add> requestValues.setPayloadValue(argument); <add> } <add> else { <add> MethodParameter nestedParameter = parameter.nested(); <add> <add> String message = "Async type for @Payload should produce value(s)"; <add> Assert.isTrue(nestedParameter.getNestedParameterType() != Void.class, message); <add> Assert.isTrue(!reactiveAdapter.isNoValue(), message); <add> <add> requestValues.setPayload( <add> reactiveAdapter.toPublisher(argument), <add> ParameterizedTypeReference.forType(nestedParameter.getNestedGenericParameterType())); <add> } <add> } <add> <add> return true; <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketExchange.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.lang.annotation.Documented; <add>import java.lang.annotation.ElementType; <add>import java.lang.annotation.Retention; <add>import java.lang.annotation.RetentionPolicy; <add>import java.lang.annotation.Target; <add> <add>/** <add> * Annotation to declare a method on an RSocket service interface as an RSocket <add> * endpoint. The endpoint route is defined statically through the annotation <add> * attributes, and through the input method argument types. <add> * <add> * <p>Supported at the type level to express common attributes, to be inherited <add> * by all methods, such as a base route. <add> * <add> * <p>Supported method arguments: <add> * <table border="1"> <add> * <tr> <add> * <th>Method Argument</th> <add> * <th>Description</th> <add> * <th>Resolver</th> <add> * </tr> <add> * <tr> <add> * <td>{@link org.springframework.messaging.handler.annotation.DestinationVariable @DestinationVariable}</td> <add> * <td>Add a route variable to expand into the route</td> <add> * <td>{@link DestinationVariableArgumentResolver}</td> <add> * </tr> <add> * <tr> <add> * <td>{@link org.springframework.messaging.handler.annotation.Payload @Payload}</td> <add> * <td>Set the input payload(s) for the request</td> <add> * <td>{@link PayloadArgumentResolver}</td> <add> * </tr> <add> * <tr> <add> * <td>{@link Object} argument followed by {@link org.springframework.util.MimeType} argument</td> <add> * <td>Add a metadata value</td> <add> * <td>{@link MetadataArgumentResolver}</td> <add> * </tr> <add> * <tr> <add> * <td>{@link org.springframework.util.MimeType} argument preceded by {@link Object} argument</td> <add> * <td>Specify the mime type for the preceding metadata value</td> <add> * <td>{@link MetadataArgumentResolver}</td> <add> * </tr> <add> * </table> <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>@Target({ElementType.TYPE, ElementType.METHOD}) <add>@Retention(RetentionPolicy.RUNTIME) <add>@Documented <add>public @interface RSocketExchange { <add> <add> /** <add> * Destination-based mapping expressed by this annotation. This is either <add> * {@link org.springframework.util.AntPathMatcher AntPathMatcher} or <add> * {@link org.springframework.web.util.pattern.PathPattern PathPattern} <add> * based pattern, depending on which is configured, matched to the route of <add> * the stream request. <add> */ <add> String value() default ""; <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketRequestValues.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.LinkedHashMap; <add>import java.util.List; <add>import java.util.Map; <add> <add>import org.reactivestreams.Publisher; <add> <add>import org.springframework.core.ParameterizedTypeReference; <add>import org.springframework.lang.Nullable; <add>import org.springframework.util.Assert; <add>import org.springframework.util.MimeType; <add>import org.springframework.util.StringUtils; <add> <add>/** <add> * Container for RSocket request values extracted from an <add> * {@link RSocketExchange @RSocketExchange}-annotated <add> * method and argument values passed to it. This is then used to define a request <add> * via {@link org.springframework.messaging.rsocket.RSocketRequester}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public final class RSocketRequestValues { <add> <add> @Nullable <add> private final String route; <add> <add> private final Object[] routeVariables; <add> <add> private final Map<Object, MimeType> metadata; <add> <add> @Nullable <add> private final Object payloadValue; <add> <add> @Nullable <add> private final Publisher<?> payload; <add> <add> @Nullable <add> private final ParameterizedTypeReference<?> payloadElementType; <add> <add> <add> public RSocketRequestValues( <add> @Nullable String route, @Nullable List<Object> routeVariables, @Nullable MetadataHelper metadataHelper, <add> @Nullable Object payloadValue, @Nullable Publisher<?> payload, <add> @Nullable ParameterizedTypeReference<?> payloadElementType) { <add> <add> this.route = route; <add> this.routeVariables = (routeVariables != null ? routeVariables.toArray() : new Object[0]); <add> this.metadata = (metadataHelper != null ? metadataHelper.toMap() : Collections.emptyMap()); <add> this.payloadValue = payloadValue; <add> this.payload = payload; <add> this.payloadElementType = payloadElementType; <add> } <add> <add> <add> /** <add> * Return the route value for <add> * {@link org.springframework.messaging.rsocket.RSocketRequester#route(String, Object...) route}. <add> */ <add> @Nullable <add> public String getRoute() { <add> return this.route; <add> } <add> <add> /** <add> * Return the route variables for <add> * {@link org.springframework.messaging.rsocket.RSocketRequester#route(String, Object...) route}. <add> */ <add> public Object[] getRouteVariables() { <add> return this.routeVariables; <add> } <add> <add> /** <add> * Return the metadata entries for <add> * {@link org.springframework.messaging.rsocket.RSocketRequester.RequestSpec#metadata(Object, MimeType)}. <add> */ <add> public Map<Object, MimeType> getMetadata() { <add> return this.metadata; <add> } <add> <add> /** <add> * Return the request payload as a value to be serialized, if set. <add> * <p>This is mutually exclusive with {@link #getPayload()}. <add> * Only one of the two or neither is set. <add> */ <add> @Nullable <add> public Object getPayloadValue() { <add> return this.payloadValue; <add> } <add> <add> /** <add> * Return the request payload as a Publisher. <add> * <p>This is mutually exclusive with {@link #getPayloadValue()}. <add> * Only one of the two or neither is set. <add> */ <add> @Nullable <add> public Publisher<?> getPayload() { <add> return this.payload; <add> } <add> <add> /** <add> * Return the element type for a {@linkplain #getPayload() Publisher payload}. <add> */ <add> @Nullable <add> public ParameterizedTypeReference<?> getPayloadElementType() { <add> return this.payloadElementType; <add> } <add> <add> <add> public static Builder builder(@Nullable String route) { <add> return new Builder(route); <add> } <add> <add> <add> /** <add> * Builder for {@link RSocketRequestValues}. <add> */ <add> public final static class Builder { <add> <add> @Nullable <add> private String route; <add> <add> @Nullable <add> private List<Object> routeVariables; <add> <add> @Nullable <add> private MetadataHelper metadataHelper; <add> <add> @Nullable <add> private Object payloadValue; <add> <add> @Nullable <add> private Publisher<?> payload; <add> <add> @Nullable <add> private ParameterizedTypeReference<?> payloadElementType; <add> <add> Builder(@Nullable String route) { <add> this.route = (StringUtils.hasText(route) ? route : null); <add> } <add> <add> /** <add> * Set the route for the request. <add> */ <add> public Builder setRoute(String route) { <add> this.route = route; <add> this.routeVariables = null; <add> return this; <add> } <add> <add> /** <add> * Add a route variable. <add> */ <add> public Builder addRouteVariable(Object variable) { <add> this.routeVariables = (this.routeVariables != null ? this.routeVariables : new ArrayList<>()); <add> this.routeVariables.add(variable); <add> return this; <add> } <add> <add> /** <add> * Add a metadata entry. <add> * This must be followed by a corresponding call to {@link #addMimeType(MimeType)}. <add> */ <add> public Builder addMetadata(Object metadata) { <add> this.metadataHelper = (this.metadataHelper != null ? this.metadataHelper : new MetadataHelper()); <add> this.metadataHelper.addMetadata(metadata); <add> return this; <add> } <add> <add> /** <add> * Set the mime type for a metadata entry. <add> * This must be preceded by a call to {@link #addMetadata(Object)}. <add> */ <add> public Builder addMimeType(MimeType mimeType) { <add> this.metadataHelper = (this.metadataHelper != null ? this.metadataHelper : new MetadataHelper()); <add> this.metadataHelper.addMimeType(mimeType); <add> return this; <add> } <add> <add> /** <add> * Set the request payload as a concrete value to be serialized. <add> * <p>This is mutually exclusive with, and resets any previously set <add> * {@linkplain #setPayload(Publisher, ParameterizedTypeReference) payload Publisher}. <add> */ <add> public Builder setPayloadValue(Object payloadValue) { <add> this.payloadValue = payloadValue; <add> this.payload = null; <add> this.payloadElementType = null; <add> return this; <add> } <add> <add> /** <add> * Set the request payload value to be serialized. <add> */ <add> public <T, P extends Publisher<T>> Builder setPayload(P payload, ParameterizedTypeReference<T> elementTye) { <add> this.payload = payload; <add> this.payloadElementType = elementTye; <add> this.payloadValue = null; <add> return this; <add> } <add> <add> /** <add> * Build the {@link RSocketRequestValues} instance. <add> */ <add> public RSocketRequestValues build() { <add> return new RSocketRequestValues( <add> this.route, this.routeVariables, this.metadataHelper, <add> this.payloadValue, this.payload, this.payloadElementType); <add> } <add> <add> } <add> <add> <add> /** <add> * Class that helps to collect a map of metadata entries as a series of calls <add> * to provide each metadata and mime type pair. <add> */ <add> private static class MetadataHelper { <add> <add> private final List<Object> metadata = new ArrayList<>(); <add> <add> private final List<MimeType> mimeTypes = new ArrayList<>(); <add> <add> public void addMetadata(Object metadata) { <add> Assert.isTrue(this.metadata.size() == this.mimeTypes.size(), "Invalid state: " + this); <add> this.metadata.add(metadata); <add> } <add> <add> public void addMimeType(MimeType mimeType) { <add> Assert.isTrue(this.metadata.size() == (this.mimeTypes.size() + 1), "Invalid state: " + this); <add> this.mimeTypes.add(mimeType); <add> } <add> <add> public Map<Object, MimeType> toMap() { <add> Map<Object, MimeType> map = new LinkedHashMap<>(this.metadata.size()); <add> for (int i = 0; i < this.metadata.size(); i++) { <add> map.put(this.metadata.get(i), this.mimeTypes.get(i)); <add> } <add> return map; <add> } <add> <add> @Override <add> public String toString() { <add> return "metadata=" + this.metadata + ", mimeTypes=" + this.mimeTypes; <add> } <add> <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketServiceArgumentResolver.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.lang.Nullable; <add> <add>/** <add> * Resolve an argument from an {@link RSocketExchange @RSocketExchange}-annotated <add> * method to one or more RSocket request values. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public interface RSocketServiceArgumentResolver { <add> <add> /** <add> * Resolve the argument value. <add> * @param argument the argument value <add> * @param parameter the method parameter for the argument <add> * @param requestValues builder to add RSocket request values to <add> * @return {@code true} if the argument was resolved, {@code false} otherwise <add> */ <add> boolean resolve(@Nullable Object argument, MethodParameter parameter, RSocketRequestValues.Builder requestValues); <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketServiceMethod.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.lang.reflect.Method; <add>import java.time.Duration; <add>import java.util.Iterator; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.Optional; <add>import java.util.function.Function; <add> <add>import org.reactivestreams.Publisher; <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.core.DefaultParameterNameDiscoverer; <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.ParameterizedTypeReference; <add>import org.springframework.core.ReactiveAdapter; <add>import org.springframework.core.ReactiveAdapterRegistry; <add>import org.springframework.core.annotation.AnnotatedElementUtils; <add>import org.springframework.core.annotation.SynthesizingMethodParameter; <add>import org.springframework.lang.Nullable; <add>import org.springframework.messaging.rsocket.RSocketRequester; <add>import org.springframework.messaging.rsocket.RSocketStrategies; <add>import org.springframework.util.Assert; <add>import org.springframework.util.MimeType; <add>import org.springframework.util.StringUtils; <add>import org.springframework.util.StringValueResolver; <add> <add>/** <add> * Implements the invocation of an {@link RSocketExchange @RSocketExchange}-annotated, <add> * {@link RSocketServiceProxyFactory#createClient(Class) RSocket service proxy} method <add> * by delegating to an {@link RSocketRequester} to perform actual requests. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>final class RSocketServiceMethod { <add> <add> private final Method method; <add> <add> private final MethodParameter[] parameters; <add> <add> private final List<RSocketServiceArgumentResolver> argumentResolvers; <add> <add> @Nullable <add> private final String route; <add> <add> private final Function<RSocketRequestValues, Object> responseFunction; <add> <add> <add> RSocketServiceMethod( <add> Method method, Class<?> containingClass, List<RSocketServiceArgumentResolver> argumentResolvers, <add> RSocketRequester rsocketRequester, @Nullable StringValueResolver embeddedValueResolver, <add> ReactiveAdapterRegistry reactiveRegistry, Duration blockTimeout) { <add> <add> this.method = method; <add> this.parameters = initMethodParameters(method); <add> this.argumentResolvers = argumentResolvers; <add> this.route = initRoute(method, containingClass, rsocketRequester.strategies(), embeddedValueResolver); <add> this.responseFunction = initResponseFunction( <add> rsocketRequester, method, reactiveRegistry, blockTimeout); <add> } <add> <add> private static MethodParameter[] initMethodParameters(Method method) { <add> int count = method.getParameterCount(); <add> if (count == 0) { <add> return new MethodParameter[0]; <add> } <add> DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer(); <add> MethodParameter[] parameters = new MethodParameter[count]; <add> for (int i = 0; i < count; i++) { <add> parameters[i] = new SynthesizingMethodParameter(method, i); <add> parameters[i].initParameterNameDiscovery(nameDiscoverer); <add> } <add> return parameters; <add> } <add> <add> @Nullable <add> private static String initRoute( <add> Method method, Class<?> containingClass, RSocketStrategies strategies, <add> @Nullable StringValueResolver embeddedValueResolver) { <add> <add> RSocketExchange annot1 = AnnotatedElementUtils.findMergedAnnotation(containingClass, RSocketExchange.class); <add> RSocketExchange annot2 = AnnotatedElementUtils.findMergedAnnotation(method, RSocketExchange.class); <add> <add> Assert.notNull(annot2, "Expected RSocketExchange annotation"); <add> <add> String route1 = (annot1 != null ? annot1.value() : null); <add> String route2 = annot2.value(); <add> <add> if (embeddedValueResolver != null) { <add> route1 = (route1 != null ? embeddedValueResolver.resolveStringValue(route1) : null); <add> route2 = embeddedValueResolver.resolveStringValue(route2); <add> } <add> <add> boolean hasRoute1 = StringUtils.hasText(route1); <add> boolean hasRoute2 = StringUtils.hasText(route2); <add> <add> if (hasRoute1 && hasRoute2) { <add> return strategies.routeMatcher().combine(route1, route2); <add> } <add> <add> if (!hasRoute1 && !hasRoute2) { <add> return null; <add> } <add> <add> return (hasRoute2 ? route2 : route1); <add> } <add> <add> private static Function<RSocketRequestValues, Object> initResponseFunction( <add> RSocketRequester requester, Method method, <add> ReactiveAdapterRegistry reactiveRegistry, Duration blockTimeout) { <add> <add> MethodParameter returnParam = new MethodParameter(method, -1); <add> Class<?> returnType = returnParam.getParameterType(); <add> ReactiveAdapter reactiveAdapter = reactiveRegistry.getAdapter(returnType); <add> <add> MethodParameter actualParam = (reactiveAdapter != null ? returnParam.nested() : returnParam.nestedIfOptional()); <add> Class<?> actualType = actualParam.getNestedParameterType(); <add> <add> Function<RSocketRequestValues, Publisher<?>> responseFunction; <add> if (actualType.equals(void.class) || actualType.equals(Void.class) || <add> (reactiveAdapter != null && reactiveAdapter.isNoValue())) { <add> <add> responseFunction = values -> { <add> RSocketRequester.RetrieveSpec retrieveSpec = initRequest(requester, values); <add> return (values.getPayload() == null && values.getPayloadValue() == null ? <add> ((RSocketRequester.RequestSpec) retrieveSpec).sendMetadata() : retrieveSpec.send()); <add> }; <add> } <add> else if (reactiveAdapter == null) { <add> responseFunction = values -> initRequest(requester, values).retrieveMono(actualType); <add> } <add> else { <add> ParameterizedTypeReference<?> payloadType = <add> ParameterizedTypeReference.forType(actualParam.getNestedGenericParameterType()); <add> <add> responseFunction = values -> ( <add> reactiveAdapter.isMultiValue() ? <add> initRequest(requester, values).retrieveFlux(payloadType) : <add> initRequest(requester, values).retrieveMono(payloadType)); <add> } <add> <add> boolean blockForOptional = returnType.equals(Optional.class); <add> <add> return responseFunction.andThen(responsePublisher -> { <add> if (reactiveAdapter != null) { <add> return reactiveAdapter.fromPublisher(responsePublisher); <add> } <add> return (blockForOptional ? <add> ((Mono<?>) responsePublisher).blockOptional(blockTimeout) : <add> ((Mono<?>) responsePublisher).block(blockTimeout)); <add> }); <add> } <add> <add> @SuppressWarnings("ReactiveStreamsUnusedPublisher") <add> private static RSocketRequester.RetrieveSpec initRequest( <add> RSocketRequester requester, RSocketRequestValues requestValues) { <add> <add> RSocketRequester.RequestSpec spec; <add> String route = requestValues.getRoute(); <add> Map<Object, MimeType> metadata = requestValues.getMetadata(); <add> <add> if (StringUtils.hasText(route)) { <add> spec = requester.route(route, requestValues.getRouteVariables()); <add> for (Map.Entry<Object, MimeType> entry : metadata.entrySet()) { <add> spec.metadata(entry.getKey(), entry.getValue()); <add> } <add> } <add> else { <add> Iterator<Map.Entry<Object, MimeType>> iterator = metadata.entrySet().iterator(); <add> Assert.isTrue(iterator.hasNext(), "Neither route nor metadata provided"); <add> <add> Map.Entry<Object, MimeType> entry = iterator.next(); <add> spec = requester.metadata(entry.getKey(), entry.getValue()); <add> <add> while (iterator.hasNext()) { <add> spec.metadata(entry.getKey(), entry.getValue()); <add> } <add> } <add> <add> if (requestValues.getPayloadValue() != null) { <add> spec.data(requestValues.getPayloadValue()); <add> } <add> else if (requestValues.getPayload() != null) { <add> Assert.notNull(requestValues.getPayloadElementType(), "Publisher body element type is required"); <add> spec.data(requestValues.getPayload(), requestValues.getPayloadElementType()); <add> } <add> <add> return spec; <add> } <add> <add> <add> public Method getMethod() { <add> return this.method; <add> } <add> <add> @Nullable <add> public Object invoke(Object[] arguments) { <add> RSocketRequestValues.Builder requestValues = RSocketRequestValues.builder(this.route); <add> applyArguments(requestValues, arguments); <add> return this.responseFunction.apply(requestValues.build()); <add> } <add> <add> private void applyArguments(RSocketRequestValues.Builder requestValues, Object[] arguments) { <add> Assert.isTrue(arguments.length == this.parameters.length, "Method argument mismatch"); <add> for (int i = 0; i < arguments.length; i++) { <add> Object value = arguments[i]; <add> boolean resolved = false; <add> for (RSocketServiceArgumentResolver resolver : this.argumentResolvers) { <add> if (resolver.resolve(value, this.parameters[i], requestValues)) { <add> resolved = true; <add> break; <add> } <add> } <add> Assert.state(resolved, formatArgumentError(this.parameters[i], "No suitable resolver")); <add> } <add> } <add> <add> @SuppressWarnings("SameParameterValue") <add> private static String formatArgumentError(MethodParameter param, String message) { <add> return "Could not resolve parameter [" + param.getParameterIndex() + "] in " + <add> param.getExecutable().toGenericString() + (StringUtils.hasText(message) ? ": " + message : ""); <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketServiceProxyFactory.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.lang.reflect.InvocationHandler; <add>import java.lang.reflect.Method; <add>import java.time.Duration; <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.function.Function; <add>import java.util.stream.Collectors; <add> <add>import org.aopalliance.intercept.MethodInterceptor; <add>import org.aopalliance.intercept.MethodInvocation; <add> <add>import org.springframework.aop.framework.ProxyFactory; <add>import org.springframework.aop.framework.ReflectiveMethodInvocation; <add>import org.springframework.beans.factory.InitializingBean; <add>import org.springframework.context.EmbeddedValueResolverAware; <add>import org.springframework.core.MethodIntrospector; <add>import org.springframework.core.ReactiveAdapterRegistry; <add>import org.springframework.core.annotation.AnnotatedElementUtils; <add>import org.springframework.lang.Nullable; <add>import org.springframework.messaging.rsocket.RSocketRequester; <add>import org.springframework.util.Assert; <add>import org.springframework.util.StringValueResolver; <add> <add>/** <add> * Factory for creating a client proxy given an RSocket service interface with <add> * {@link RSocketExchange @RSocketExchange} methods. <add> * <add> * <p>This class is intended to be declared as a bean in Spring configuration. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>public final class RSocketServiceProxyFactory implements InitializingBean, EmbeddedValueResolverAware { <add> <add> private final RSocketRequester rsocketRequester; <add> <add> @Nullable <add> private List<RSocketServiceArgumentResolver> customArgumentResolvers; <add> <add> @Nullable <add> private List<RSocketServiceArgumentResolver> argumentResolvers; <add> <add> @Nullable <add> private StringValueResolver embeddedValueResolver; <add> <add> private ReactiveAdapterRegistry reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance(); <add> <add> private Duration blockTimeout = Duration.ofSeconds(5); <add> <add> <add> /** <add> * Create an instance with the underlying RSocketRequester to perform requests with. <add> * @param rsocketRequester the requester to use <add> */ <add> public RSocketServiceProxyFactory(RSocketRequester rsocketRequester) { <add> Assert.notNull(rsocketRequester, "RSocketRequester is required"); <add> this.rsocketRequester = rsocketRequester; <add> } <add> <add> <add> /** <add> * Register a custom argument resolver, invoked ahead of default resolvers. <add> * @param resolver the resolver to add <add> */ <add> public void addCustomArgumentResolver(RSocketServiceArgumentResolver resolver) { <add> if (this.customArgumentResolvers == null) { <add> this.customArgumentResolvers = new ArrayList<>(); <add> } <add> this.customArgumentResolvers.add(resolver); <add> } <add> <add> /** <add> * Set the custom argument resolvers to use, ahead of default resolvers. <add> * @param resolvers the resolvers to use <add> */ <add> public void setCustomArgumentResolvers(List<RSocketServiceArgumentResolver> resolvers) { <add> this.customArgumentResolvers = new ArrayList<>(resolvers); <add> } <add> <add> /** <add> * Set the StringValueResolver to use for resolving placeholders and <add> * expressions in {@link RSocketExchange#value()}. <add> * @param resolver the resolver to use <add> */ <add> @Override <add> public void setEmbeddedValueResolver(StringValueResolver resolver) { <add> this.embeddedValueResolver = resolver; <add> } <add> <add> /** <add> * Set the {@link ReactiveAdapterRegistry} to use to support different <add> * asynchronous types for RSocket service method return values. <add> * <p>By default this is {@link ReactiveAdapterRegistry#getSharedInstance()}. <add> */ <add> public void setReactiveAdapterRegistry(ReactiveAdapterRegistry registry) { <add> this.reactiveAdapterRegistry = registry; <add> } <add> <add> /** <add> * Configure how long to wait for a response for an RSocket service method <add> * with a synchronous (blocking) method signature. <add> * <p>By default this is 5 seconds. <add> * @param blockTimeout the timeout value <add> */ <add> public void setBlockTimeout(Duration blockTimeout) { <add> this.blockTimeout = blockTimeout; <add> } <add> <add> <add> @Override <add> public void afterPropertiesSet() throws Exception { <add> this.argumentResolvers = initArgumentResolvers(); <add> } <add> <add> private List<RSocketServiceArgumentResolver> initArgumentResolvers() { <add> List<RSocketServiceArgumentResolver> resolvers = new ArrayList<>(); <add> <add> // Custom <add> if (this.customArgumentResolvers != null) { <add> resolvers.addAll(this.customArgumentResolvers); <add> } <add> <add> // Annotation-based <add> resolvers.add(new PayloadArgumentResolver(this.reactiveAdapterRegistry, false)); <add> resolvers.add(new DestinationVariableArgumentResolver()); <add> <add> // Type-based <add> resolvers.add(new MetadataArgumentResolver()); <add> <add> // Fallback <add> resolvers.add(new PayloadArgumentResolver(this.reactiveAdapterRegistry, true)); <add> <add> return resolvers; <add> } <add> <add> <add> /** <add> * Return a proxy that implements the given RSocket service interface to <add> * perform RSocket requests and retrieve responses through the configured <add> * {@link RSocketRequester}. <add> * @param serviceType the RSocket service to create a proxy for <add> * @param <S> the RSocket service type <add> * @return the created proxy <add> */ <add> public <S> S createClient(Class<S> serviceType) { <add> <add> List<RSocketServiceMethod> serviceMethods = <add> MethodIntrospector.selectMethods(serviceType, this::isExchangeMethod).stream() <add> .map(method -> createRSocketServiceMethod(serviceType, method)) <add> .toList(); <add> <add> return ProxyFactory.getProxy(serviceType, new ServiceMethodInterceptor(serviceMethods)); <add> } <add> <add> private boolean isExchangeMethod(Method method) { <add> return AnnotatedElementUtils.hasAnnotation(method, RSocketExchange.class); <add> } <add> <add> private <S> RSocketServiceMethod createRSocketServiceMethod(Class<S> serviceType, Method method) { <add> Assert.notNull(this.argumentResolvers, <add> "No argument resolvers: afterPropertiesSet was not called"); <add> <add> return new RSocketServiceMethod( <add> method, serviceType, this.argumentResolvers, this.rsocketRequester, <add> this.embeddedValueResolver, this.reactiveAdapterRegistry, this.blockTimeout); <add> } <add> <add> <add> /** <add> * {@link MethodInterceptor} that invokes an {@link RSocketServiceMethod}. <add> */ <add> private static final class ServiceMethodInterceptor implements MethodInterceptor { <add> <add> private final Map<Method, RSocketServiceMethod> serviceMethods; <add> <add> private ServiceMethodInterceptor(List<RSocketServiceMethod> methods) { <add> this.serviceMethods = methods.stream() <add> .collect(Collectors.toMap(RSocketServiceMethod::getMethod, Function.identity())); <add> } <add> <add> @Override <add> public Object invoke(MethodInvocation invocation) throws Throwable { <add> Method method = invocation.getMethod(); <add> RSocketServiceMethod serviceMethod = this.serviceMethods.get(method); <add> if (serviceMethod != null) { <add> return serviceMethod.invoke(invocation.getArguments()); <add> } <add> if (method.isDefault()) { <add> if (invocation instanceof ReflectiveMethodInvocation reflectiveMethodInvocation) { <add> Object proxy = reflectiveMethodInvocation.getProxy(); <add> return InvocationHandler.invokeDefault(proxy, method, invocation.getArguments()); <add> } <add> } <add> throw new IllegalStateException("Unexpected method invocation: " + method); <add> } <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/package-info.java <add>/** <add> * Annotations to declare an RSocket service contract with request methods along <add> * with a proxy factory backed by an <add> * {@link org.springframework.messaging.rsocket.RSocketRequester}. <add> */ <add>@NonNullApi <add>@NonNullFields <add>package org.springframework.messaging.rsocket.service; <add> <add>import org.springframework.lang.NonNullApi; <add>import org.springframework.lang.NonNullFields; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java <ide> import io.reactivex.rxjava3.core.Observable; <ide> import io.reactivex.rxjava3.core.Single; <ide> import io.rsocket.Payload; <del>import io.rsocket.RSocket; <ide> import io.rsocket.metadata.WellKnownMimeType; <ide> import org.junit.jupiter.api.BeforeEach; <ide> import org.junit.jupiter.api.Test; <del>import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> import reactor.test.StepVerifier; <ide> <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <del>import org.springframework.lang.Nullable; <ide> import org.springframework.messaging.rsocket.RSocketRequester.RequestSpec; <ide> import org.springframework.messaging.rsocket.RSocketRequester.RetrieveSpec; <ide> import org.springframework.util.MimeType; <ide> private Payload toPayload(String value) { <ide> return PayloadUtils.createPayload(DefaultDataBufferFactory.sharedInstance.wrap(bytes)); <ide> } <ide> <del> <del> private static class TestRSocket implements RSocket { <del> <del> private Mono<Payload> payloadMonoToReturn = Mono.empty(); <del> private Flux<Payload> payloadFluxToReturn = Flux.empty(); <del> <del> @Nullable private volatile String savedMethodName; <del> @Nullable private volatile Payload savedPayload; <del> @Nullable private volatile Flux<Payload> savedPayloadFlux; <del> <del> void setPayloadMonoToReturn(Mono<Payload> payloadMonoToReturn) { <del> this.payloadMonoToReturn = payloadMonoToReturn; <del> } <del> <del> void setPayloadFluxToReturn(Flux<Payload> payloadFluxToReturn) { <del> this.payloadFluxToReturn = payloadFluxToReturn; <del> } <del> <del> @Nullable <del> String getSavedMethodName() { <del> return this.savedMethodName; <del> } <del> <del> @Nullable <del> Payload getSavedPayload() { <del> return this.savedPayload; <del> } <del> <del> @Nullable <del> Flux<Payload> getSavedPayloadFlux() { <del> return this.savedPayloadFlux; <del> } <del> <del> public void reset() { <del> this.savedMethodName = null; <del> this.savedPayload = null; <del> this.savedPayloadFlux = null; <del> } <del> <del> <del> @Override <del> public Mono<Void> fireAndForget(Payload payload) { <del> this.savedMethodName = "fireAndForget"; <del> this.savedPayload = payload; <del> return Mono.empty(); <del> } <del> <del> @Override <del> public Mono<Payload> requestResponse(Payload payload) { <del> this.savedMethodName = "requestResponse"; <del> this.savedPayload = payload; <del> return this.payloadMonoToReturn; <del> } <del> <del> @Override <del> public Flux<Payload> requestStream(Payload payload) { <del> this.savedMethodName = "requestStream"; <del> this.savedPayload = payload; <del> return this.payloadFluxToReturn; <del> } <del> <del> @Override <del> public Flux<Payload> requestChannel(Publisher<Payload> publisher) { <del> this.savedMethodName = "requestChannel"; <del> this.savedPayloadFlux = Flux.from(publisher); <del> return this.payloadFluxToReturn; <del> } <del> } <del> <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/TestRSocket.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket; <add> <add>import io.rsocket.Payload; <add>import io.rsocket.RSocket; <add>import org.reactivestreams.Publisher; <add>import reactor.core.publisher.Flux; <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.lang.Nullable; <add> <add>/** <add> * {@link RSocket} that saves the name of the invoked method and the input payload(s). <add> */ <add>public class TestRSocket implements RSocket { <add> <add> private Mono<Payload> payloadMonoToReturn = Mono.empty(); <add> <add> private Flux<Payload> payloadFluxToReturn = Flux.empty(); <add> <add> @Nullable private volatile String savedMethodName; <add> <add> @Nullable private volatile Payload savedPayload; <add> <add> @Nullable private volatile Flux<Payload> savedPayloadFlux; <add> <add> <add> public void setPayloadMonoToReturn(Mono<Payload> payloadMonoToReturn) { <add> this.payloadMonoToReturn = payloadMonoToReturn; <add> } <add> <add> public void setPayloadFluxToReturn(Flux<Payload> payloadFluxToReturn) { <add> this.payloadFluxToReturn = payloadFluxToReturn; <add> } <add> <add> @Nullable <add> public String getSavedMethodName() { <add> return this.savedMethodName; <add> } <add> <add> @Nullable <add> public Payload getSavedPayload() { <add> return this.savedPayload; <add> } <add> <add> @Nullable <add> public Flux<Payload> getSavedPayloadFlux() { <add> return this.savedPayloadFlux; <add> } <add> <add> public void reset() { <add> this.savedMethodName = null; <add> this.savedPayload = null; <add> this.savedPayloadFlux = null; <add> } <add> <add> <add> @Override <add> public Mono<Void> fireAndForget(Payload payload) { <add> this.savedMethodName = "fireAndForget"; <add> this.savedPayload = payload; <add> return Mono.empty(); <add> } <add> <add> @Override <add> public Mono<Payload> requestResponse(Payload payload) { <add> this.savedMethodName = "requestResponse"; <add> this.savedPayload = payload; <add> return this.payloadMonoToReturn; <add> } <add> <add> @Override <add> public Flux<Payload> requestStream(Payload payload) { <add> this.savedMethodName = "requestStream"; <add> this.savedPayload = payload; <add> return this.payloadFluxToReturn; <add> } <add> <add> @Override <add> public Flux<Payload> requestChannel(Publisher<Payload> publisher) { <add> this.savedMethodName = "requestChannel"; <add> this.savedPayloadFlux = Flux.from(publisher); <add> return this.payloadFluxToReturn; <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/DestinationVariableArgumentResolverTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.util.Arrays; <add>import java.util.List; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.messaging.handler.annotation.DestinationVariable; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add> <add>/** <add> * Unit tests for {@link DestinationVariableArgumentResolver}. <add> * @author Rossen Stoyanchev <add> */ <add>public class DestinationVariableArgumentResolverTests extends RSocketServiceArgumentResolverTestSupport { <add> <add> @Override <add> protected RSocketServiceArgumentResolver initResolver() { <add> return new DestinationVariableArgumentResolver(); <add> } <add> <add> @Test <add> void variable() { <add> String value = "foo"; <add> boolean resolved = execute(value, initMethodParameter(Service.class, "execute", 0)); <add> <add> assertThat(resolved).isTrue(); <add> assertThat(getRequestValues().getRouteVariables()).containsExactly(value); <add> } <add> <add> @Test <add> void variableList() { <add> List<String> values = Arrays.asList("foo", "bar", "baz"); <add> boolean resolved = execute(values, initMethodParameter(Service.class, "execute", 0)); <add> <add> assertThat(resolved).isTrue(); <add> assertThat(getRequestValues().getRouteVariables()).containsExactlyElementsOf(values); <add> } <add> <add> @Test <add> void variableArray() { <add> String[] values = new String[] {"foo", "bar", "baz"}; <add> boolean resolved = execute(values, initMethodParameter(Service.class, "execute", 0)); <add> <add> assertThat(resolved).isTrue(); <add> assertThat(getRequestValues().getRouteVariables()).containsExactlyElementsOf(Arrays.asList(values)); <add> } <add> <add> @Test <add> void notRequestBody() { <add> MethodParameter parameter = initMethodParameter(Service.class, "executeNotAnnotated", 0); <add> boolean resolved = execute("value", parameter); <add> <add> assertThat(resolved).isFalse(); <add> } <add> <add> @Test <add> void ignoreNull() { <add> boolean resolved = execute(null, initMethodParameter(Service.class, "execute", 0)); <add> <add> assertThat(resolved).isTrue(); <add> assertThat(getRequestValues().getPayloadValue()).isNull(); <add> assertThat(getRequestValues().getPayload()).isNull(); <add> assertThat(getRequestValues().getPayloadElementType()).isNull(); <add> } <add> <add> <add> @SuppressWarnings("unused") <add> private interface Service { <add> <add> void execute(@DestinationVariable String variable); <add> <add> void executeList(@DestinationVariable List<String> variables); <add> <add> void executeArray(@DestinationVariable String[] variables); <add> <add> void executeNotAnnotated(String variable); <add> <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/MetadataArgumentResolverTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.util.LinkedHashMap; <add>import java.util.Map; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.util.MimeType; <add>import org.springframework.util.MimeTypeUtils; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add> <add>/** <add> * Unit tests for {@link MetadataArgumentResolver}. <add> * @author Rossen Stoyanchev <add> */ <add>public class MetadataArgumentResolverTests extends RSocketServiceArgumentResolverTestSupport { <add> <add> @Override <add> protected RSocketServiceArgumentResolver initResolver() { <add> return new MetadataArgumentResolver(); <add> } <add> <add> @Test <add> void metadata() { <add> MethodParameter param1 = initMethodParameter(Service.class, "execute", 0); <add> MethodParameter param2 = initMethodParameter(Service.class, "execute", 1); <add> MethodParameter param3 = initMethodParameter(Service.class, "execute", 2); <add> MethodParameter param4 = initMethodParameter(Service.class, "execute", 3); <add> <add> assertThat(execute("foo", param1)).isTrue(); <add> assertThat(execute(MimeTypeUtils.APPLICATION_JSON, param2)).isTrue(); <add> <add> assertThat(execute("bar", param3)).isTrue(); <add> assertThat(execute(MimeTypeUtils.APPLICATION_XML, param4)).isTrue(); <add> <add> Map<Object, MimeType> expected = new LinkedHashMap<>(); <add> expected.put("foo", MimeTypeUtils.APPLICATION_JSON); <add> expected.put("bar", MimeTypeUtils.APPLICATION_XML); <add> <add> assertThat(getRequestValues().getMetadata()).containsExactlyEntriesOf(expected); <add> } <add> <add> <add> @SuppressWarnings("unused") <add> private interface Service { <add> <add> void execute(String metadata1, MimeType mimeType1, String metadata2, MimeType mimeType2); <add> <add> void executeNotAnnotated(String foo, String bar); <add> <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/PayloadArgumentResolverTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import io.reactivex.rxjava3.core.Completable; <add>import io.reactivex.rxjava3.core.Single; <add>import org.junit.jupiter.api.Test; <add>import org.reactivestreams.Publisher; <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.ParameterizedTypeReference; <add>import org.springframework.core.ReactiveAdapterRegistry; <add>import org.springframework.messaging.handler.annotation.Payload; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add> <add>/** <add> * Unit tests for {@link PayloadArgumentResolver}. <add> * @author Rossen Stoyanchev <add> */ <add>public class PayloadArgumentResolverTests extends RSocketServiceArgumentResolverTestSupport { <add> <add> @Override <add> protected RSocketServiceArgumentResolver initResolver() { <add> return new PayloadArgumentResolver(ReactiveAdapterRegistry.getSharedInstance(), false); <add> } <add> <add> @Test <add> void stringPayload() { <add> String payload = "payloadValue"; <add> boolean resolved = execute(payload, initMethodParameter(Service.class, "execute", 0)); <add> <add> assertThat(resolved).isTrue(); <add> assertThat(getRequestValues().getPayloadValue()).isEqualTo(payload); <add> assertThat(getRequestValues().getPayload()).isNull(); <add> } <add> <add> @Test <add> void monoPayload() { <add> Mono<String> payloadMono = Mono.just("payloadValue"); <add> boolean resolved = execute(payloadMono, initMethodParameter(Service.class, "executeMono", 0)); <add> <add> assertThat(resolved).isTrue(); <add> assertThat(getRequestValues().getPayloadValue()).isNull(); <add> assertThat(getRequestValues().getPayload()).isSameAs(payloadMono); <add> assertThat(getRequestValues().getPayloadElementType()).isEqualTo(new ParameterizedTypeReference<String>() {}); <add> } <add> <add> @Test <add> @SuppressWarnings("unchecked") <add> void singlePayload() { <add> boolean resolved = execute(Single.just("bodyValue"), initMethodParameter(Service.class, "executeSingle", 0)); <add> <add> assertThat(resolved).isTrue(); <add> assertThat(getRequestValues().getPayloadValue()).isNull(); <add> assertThat(getRequestValues().getPayloadElementType()).isEqualTo(new ParameterizedTypeReference<String>() {}); <add> <add> Publisher<?> payload = getRequestValues().getPayload(); <add> assertThat(payload).isNotNull(); <add> assertThat(((Mono<String>) payload).block()).isEqualTo("bodyValue"); <add> } <add> <add> @Test <add> void monoVoid() { <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> execute(Mono.empty(), initMethodParameter(Service.class, "executeMonoVoid", 0))) <add> .withMessage("Async type for @Payload should produce value(s)"); <add> } <add> <add> @Test <add> void completable() { <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> execute(Completable.complete(), initMethodParameter(Service.class, "executeCompletable", 0))) <add> .withMessage("Async type for @Payload should produce value(s)"); <add> } <add> <add> @Test <add> void notRequestBody() { <add> MethodParameter parameter = initMethodParameter(Service.class, "executeNotAnnotated", 0); <add> boolean resolved = execute("value", parameter); <add> <add> assertThat(resolved).isFalse(); <add> } <add> <add> @Test <add> void ignoreNull() { <add> boolean resolved = execute(null, initMethodParameter(Service.class, "execute", 0)); <add> <add> assertThat(resolved).isTrue(); <add> assertThat(getRequestValues().getPayloadValue()).isNull(); <add> assertThat(getRequestValues().getPayload()).isNull(); <add> assertThat(getRequestValues().getPayloadElementType()).isNull(); <add> } <add> <add> <add> @SuppressWarnings("unused") <add> private interface Service { <add> <add> void execute(@Payload String body); <add> <add> void executeMono(@Payload Mono<String> body); <add> <add> void executeSingle(@Payload Single<String> body); <add> <add> void executeMonoVoid(@Payload Mono<Void> body); <add> <add> void executeCompletable(@Payload Completable body); <add> <add> void executeNotAnnotated(String body); <add> <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/RSocketRequestValuesTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add> <add>import org.junit.jupiter.api.Test; <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.core.ParameterizedTypeReference; <add>import org.springframework.util.MimeTypeUtils; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <add> <add>/** <add> * Unit tests for {@link RSocketRequestValues}. <add> * @author Rossen Stoyanchev <add> */ <add>public class RSocketRequestValuesTests { <add> <add> @Test <add> void route() { <add> String myRoute = "myRoute"; <add> RSocketRequestValues values = RSocketRequestValues.builder(myRoute).build(); <add> assertThat(values.getRoute()).isEqualTo(myRoute); <add> } <add> <add> @Test <add> void routeOverride() { <add> RSocketRequestValues values = RSocketRequestValues.builder("route1").setRoute("route2").build(); <add> <add> assertThat(values.getRoute()).isEqualTo("route2"); <add> } <add> <add> @Test <add> void payloadValue() { <add> String payload = "myValue"; <add> RSocketRequestValues values = RSocketRequestValues.builder(null).setPayloadValue(payload).build(); <add> <add> assertThat(values.getPayloadValue()).isEqualTo(payload); <add> assertThat(values.getPayload()).isNull(); <add> } <add> <add> @Test <add> void payloadPublisher() { <add> Mono<String> payloadMono = Mono.just( "myValue"); <add> RSocketRequestValues values = RSocketRequestValues.builder(null) <add> .setPayload(payloadMono, new ParameterizedTypeReference<>() { }) <add> .build(); <add> <add> assertThat(values.getPayloadValue()).isNull(); <add> assertThat(values.getPayload()).isSameAs(payloadMono); <add> } <add> <add> @Test <add> void metadata() { <add> RSocketRequestValues values = RSocketRequestValues.builder(null) <add> .addMetadata("myMetadata1").addMimeType(MimeTypeUtils.TEXT_PLAIN) <add> .addMetadata("myMetadata2").addMimeType(MimeTypeUtils.TEXT_HTML) <add> .build(); <add> <add> assertThat(values.getMetadata()) <add> .hasSize(2) <add> .containsEntry("myMetadata1", MimeTypeUtils.TEXT_PLAIN) <add> .containsEntry("myMetadata2", MimeTypeUtils.TEXT_HTML); <add> } <add> <add> @Test <add> void metadataInvalidEntry() { <add> // MimeType without metadata <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> RSocketRequestValues.builder(null).addMimeType(MimeTypeUtils.TEXT_PLAIN)); <add> <add> // Metadata without MimeType <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> RSocketRequestValues.builder(null) <add> .addMetadata("metadata1") <add> .addMetadata("metadata2")); <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/RSocketServiceArgumentResolverTestSupport.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.lang.reflect.Method; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.lang.Nullable; <add>import org.springframework.util.ClassUtils; <add> <add>/** <add> * Base class for {@link RSocketServiceArgumentResolver} test fixtures. <add> * @author Rossen Stoyanchev <add> */ <add>public abstract class RSocketServiceArgumentResolverTestSupport { <add> <add> @Nullable <add> private RSocketServiceArgumentResolver resolver; <add> <add> private final RSocketRequestValues.Builder requestValuesBuilder = RSocketRequestValues.builder(null); <add> <add> @Nullable <add> private RSocketRequestValues requestValues; <add> <add> <add> protected RSocketServiceArgumentResolverTestSupport() { <add> this.resolver = initResolver(); <add> } <add> <add> protected abstract RSocketServiceArgumentResolver initResolver(); <add> <add> protected static MethodParameter initMethodParameter(Class<?> serviceClass, String methodName, int index) { <add> Method method = ClassUtils.getMethod(serviceClass, methodName, (Class<?>[]) null); <add> return new MethodParameter(method, index); <add> } <add> <add> protected boolean execute(Object payload, MethodParameter parameter) { <add> return this.resolver.resolve(payload, parameter, this.requestValuesBuilder); <add> } <add> <add> protected RSocketRequestValues getRequestValues() { <add> this.requestValues = (this.requestValues != null ? this.requestValues : this.requestValuesBuilder.build()); <add> return this.requestValues; <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/RSocketServiceIntegrationTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.time.Duration; <add> <add>import io.rsocket.SocketAcceptor; <add>import io.rsocket.core.RSocketServer; <add>import io.rsocket.metadata.WellKnownMimeType; <add>import io.rsocket.transport.netty.server.CloseableChannel; <add>import io.rsocket.transport.netty.server.TcpServerTransport; <add>import org.junit.jupiter.api.AfterAll; <add>import org.junit.jupiter.api.BeforeAll; <add>import org.junit.jupiter.api.Test; <add>import reactor.core.publisher.Flux; <add>import reactor.core.publisher.Mono; <add>import reactor.test.StepVerifier; <add> <add>import org.springframework.context.annotation.AnnotationConfigApplicationContext; <add>import org.springframework.context.annotation.Bean; <add>import org.springframework.context.annotation.Configuration; <add>import org.springframework.messaging.handler.annotation.MessageMapping; <add>import org.springframework.messaging.rsocket.RSocketRequester; <add>import org.springframework.messaging.rsocket.RSocketStrategies; <add>import org.springframework.messaging.rsocket.annotation.support.RSocketMessageHandler; <add>import org.springframework.stereotype.Controller; <add>import org.springframework.util.MimeType; <add>import org.springframework.util.MimeTypeUtils; <add> <add>/** <add> * Integration tests with RSocket Service client. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class RSocketServiceIntegrationTests { <add> <add> private static CloseableChannel server; <add> <add> private static RSocketRequester requester; <add> <add> private static Service serviceProxy; <add> <add> <add> @BeforeAll <add> @SuppressWarnings("ConstantConditions") <add> public static void setupOnce() throws Exception { <add> <add> MimeType metadataMimeType = MimeTypeUtils.parseMimeType( <add> WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); <add> <add> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ServerConfig.class); <add> RSocketMessageHandler messageHandler = context.getBean(RSocketMessageHandler.class); <add> SocketAcceptor responder = messageHandler.responder(); <add> <add> server = RSocketServer.create(responder) <add> .bind(TcpServerTransport.create("localhost", 7000)) <add> .block(); <add> <add> requester = RSocketRequester.builder() <add> .metadataMimeType(metadataMimeType) <add> .rsocketStrategies(context.getBean(RSocketStrategies.class)) <add> .tcp("localhost", 7000); <add> <add> RSocketServiceProxyFactory proxyFactory = new RSocketServiceProxyFactory(requester); <add> proxyFactory.afterPropertiesSet(); <add> <add> serviceProxy = proxyFactory.createClient(Service.class); <add> } <add> <add> @AfterAll <add> public static void tearDownOnce() { <add> requester.rsocketClient().dispose(); <add> server.dispose(); <add> } <add> <add> <add> @Test <add> public void echoAsync() { <add> Flux<String> result = Flux.range(1, 3).concatMap(i -> serviceProxy.echoAsync("Hello " + i)); <add> <add> StepVerifier.create(result) <add> .expectNext("Hello 1 async").expectNext("Hello 2 async").expectNext("Hello 3 async") <add> .expectComplete() <add> .verify(Duration.ofSeconds(5)); <add> } <add> <add> @Test <add> public void echoStream() { <add> Flux<String> result = serviceProxy.echoStream("Hello"); <add> <add> StepVerifier.create(result) <add> .expectNext("Hello 0").expectNextCount(6).expectNext("Hello 7") <add> .thenCancel() <add> .verify(Duration.ofSeconds(5)); <add> } <add> <add> <add> @Controller <add> interface Service { <add> <add> @RSocketExchange("echo-async") <add> Mono<String> echoAsync(String payload); <add> <add> @RSocketExchange("echo-stream") <add> Flux<String> echoStream(String payload); <add> <add> } <add> <add> <add> @Controller <add> static class ServerController { <add> <add> @MessageMapping("echo-async") <add> Mono<String> echoAsync(String payload) { <add> return Mono.delay(Duration.ofMillis(10)).map(aLong -> payload + " async"); <add> } <add> <add> @MessageMapping("echo-stream") <add> Flux<String> echoStream(String payload) { <add> return Flux.interval(Duration.ofMillis(10)).map(aLong -> payload + " " + aLong); <add> } <add> <add> } <add> <add> <add> @Configuration <add> static class ServerConfig { <add> <add> @Bean <add> public ServerController controller() { <add> return new ServerController(); <add> } <add> <add> @Bean <add> public RSocketMessageHandler messageHandler(RSocketStrategies rsocketStrategies) { <add> RSocketMessageHandler handler = new RSocketMessageHandler(); <add> handler.setRSocketStrategies(rsocketStrategies); <add> return handler; <add> } <add> <add> @Bean <add> public RSocketStrategies rsocketStrategies() { <add> return RSocketStrategies.create(); <add> } <add> <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/RSocketServiceMethodTests.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.rsocket.service; <add> <add>import java.time.Duration; <add>import java.util.List; <add> <add>import io.rsocket.util.DefaultPayload; <add>import org.junit.jupiter.api.BeforeEach; <add>import org.junit.jupiter.api.Test; <add>import reactor.core.publisher.Flux; <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.messaging.handler.annotation.Payload; <add>import org.springframework.messaging.rsocket.RSocketRequester; <add>import org.springframework.messaging.rsocket.RSocketStrategies; <add>import org.springframework.messaging.rsocket.TestRSocket; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add>import static org.springframework.util.MimeTypeUtils.TEXT_PLAIN; <add> <add>/** <add> * Tests for {@link RSocketServiceMethod} that create an interface client with <add> * an {@link RSocketRequester} delegating to a {@link TestRSocket}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class RSocketServiceMethodTests { <add> <add> private TestRSocket rsocket; <add> <add> private RSocketServiceProxyFactory proxyFactory; <add> <add> <add> @BeforeEach <add> public void setUp() throws Exception { <add> this.rsocket = new TestRSocket(); <add> RSocketRequester requester = RSocketRequester.wrap(this.rsocket, TEXT_PLAIN, TEXT_PLAIN, RSocketStrategies.create()); <add> this.proxyFactory = new RSocketServiceProxyFactory(requester); <add> this.proxyFactory.afterPropertiesSet(); <add> } <add> <add> <add> @Test <add> void fireAndForget() { <add> ReactorService service = this.proxyFactory.createClient(ReactorService.class); <add> <add> String payload = "p1"; <add> service.fireAndForget(Mono.just(payload)).block(Duration.ofSeconds(5)); <add> <add> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("fireAndForget"); <add> assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("ff"); <add> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(payload); <add> } <add> <add> @Test <add> void requestResponse() { <add> ReactorService service = this.proxyFactory.createClient(ReactorService.class); <add> <add> String payload1 = "p1"; <add> String payload2 = "p2"; <add> this.rsocket.setPayloadMonoToReturn( <add> Mono.just(DefaultPayload.create(payload2))); <add> <add> String response = service.requestResponse(Mono.just(payload1)).block(Duration.ofSeconds(5)); <add> <add> assertThat(response).isEqualTo(payload2); <add> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestResponse"); <add> assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("rr"); <add> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(payload1); <add> } <add> <add> @Test <add> void requestStream() { <add> ReactorService service = this.proxyFactory.createClient(ReactorService.class); <add> <add> String payload1 = "p1"; <add> String payload2 = "p2"; <add> String payload3 = "p3"; <add> this.rsocket.setPayloadFluxToReturn( <add> Flux.just(DefaultPayload.create(payload2), DefaultPayload.create(payload3))); <add> <add> List<String> response = service.requestStream(Mono.just(payload1)) <add> .collectList() <add> .block(Duration.ofSeconds(5)); <add> <add> assertThat(response).containsExactly(payload2, payload3); <add> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestStream"); <add> assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("rs"); <add> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(payload1); <add> } <add> <add> @Test <add> void requestChannel() { <add> ReactorService service = this.proxyFactory.createClient(ReactorService.class); <add> <add> String payload1 = "p1"; <add> String payload2 = "p2"; <add> String payload3 = "p3"; <add> String payload4 = "p4"; <add> this.rsocket.setPayloadFluxToReturn( <add> Flux.just(DefaultPayload.create(payload3), DefaultPayload.create(payload4))); <add> <add> List<String> response = service.requestChannel(Flux.just(payload1, payload2)) <add> .collectList() <add> .block(Duration.ofSeconds(5)); <add> <add> assertThat(response).containsExactly(payload3, payload4); <add> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestChannel"); <add> <add> List<String> savedPayloads = this.rsocket.getSavedPayloadFlux() <add> .map(io.rsocket.Payload::getDataUtf8) <add> .collectList() <add> .block(Duration.ofSeconds(5)); <add> <add> assertThat(savedPayloads).containsExactly("p1", "p2"); <add> } <add> <add> <add> private interface ReactorService { <add> <add> @RSocketExchange("ff") <add> Mono<Void> fireAndForget(@Payload Mono<String> input); <add> <add> @RSocketExchange("rr") <add> Mono<String> requestResponse(@Payload Mono<String> input); <add> <add> @RSocketExchange("rs") <add> Flux<String> requestStream(@Payload Mono<String> input); <add> <add> @RSocketExchange("rc") <add> Flux<String> requestChannel(@Payload Flux<String> input); <add> <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/RequestBodyArgumentResolver.java <ide> public boolean resolve( <ide> <ide> if (argument != null) { <ide> ReactiveAdapter reactiveAdapter = this.reactiveAdapterRegistry.getAdapter(parameter.getParameterType()); <del> if (reactiveAdapter != null) { <del> setBody(argument, parameter, reactiveAdapter, requestValues); <add> if (reactiveAdapter == null) { <add> requestValues.setBodyValue(argument); <ide> } <ide> else { <del> requestValues.setBodyValue(argument); <add> MethodParameter nestedParameter = parameter.nested(); <add> <add> String message = "Async type for @RequestBody should produce value(s)"; <add> Assert.isTrue(!reactiveAdapter.isNoValue(), message); <add> Assert.isTrue(nestedParameter.getNestedParameterType() != Void.class, message); <add> <add> requestValues.setBody( <add> reactiveAdapter.toPublisher(argument), <add> ParameterizedTypeReference.forType(nestedParameter.getNestedGenericParameterType())); <ide> } <ide> } <ide> <ide> return true; <ide> } <ide> <del> private <E> void setBody( <del> Object argument, MethodParameter parameter, ReactiveAdapter reactiveAdapter, <del> HttpRequestValues.Builder requestValues) { <del> <del> String message = "Async type for @RequestBody should produce value(s)"; <del> Assert.isTrue(!reactiveAdapter.isNoValue(), message); <del> <del> parameter = parameter.nested(); <del> Class<?> elementClass = parameter.getNestedParameterType(); <del> Assert.isTrue(elementClass != Void.class, message); <del> ParameterizedTypeReference<E> typeRef = ParameterizedTypeReference.forType(parameter.getNestedGenericParameterType()); <del> Publisher<E> publisher = reactiveAdapter.toPublisher(argument); <del> <del> requestValues.setBody(publisher, typeRef); <del> } <del> <ide> }
22
Ruby
Ruby
allow pre-releases in cask-versions
9ac31942fbf56518dc9bdf84748b3450265a1acb
<ide><path>Library/Homebrew/cask/audit.rb <ide> def check_appcast_contains_version <ide> end <ide> <ide> def check_github_prerelease_version <add> return if cask.tap == "homebrew/cask-versions" <add> <ide> odebug "Auditing GitHub prerelease" <ide> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @online <ide> return if user.nil? <ide> def check_github_prerelease_version <ide> end <ide> <ide> def check_gitlab_prerelease_version <add> return if cask.tap == "homebrew/cask-versions" <add> <ide> user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @online <ide> return if user.nil? <ide>
1
Python
Python
replace bertlayernorm with layernorm
9fd937ead17c21c671fd81abb62619893bffd200
<ide><path>examples/research_projects/movement-pruning/emmental/modeling_bert_masked.py <ide> from emmental.modules import MaskedLinear <ide> from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward <ide> from transformers.modeling_utils import PreTrainedModel, prune_linear_layer <del>from transformers.models.bert.modeling_bert import ACT2FN, BertLayerNorm, load_tf_weights_in_bert <add>from transformers.models.bert.modeling_bert import ACT2FN, load_tf_weights_in_bert <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide> def __init__(self, config): <ide> <ide> # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load <ide> # any TensorFlow checkpoint file <del> self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) <add> self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) <ide> self.dropout = nn.Dropout(config.hidden_dropout_prob) <ide> <ide> def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): <ide> def __init__(self, config): <ide> mask_init=config.mask_init, <ide> mask_scale=config.mask_scale, <ide> ) <del> self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) <add> self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) <ide> self.dropout = nn.Dropout(config.hidden_dropout_prob) <ide> <ide> def forward(self, hidden_states, input_tensor, threshold): <ide> def __init__(self, config): <ide> mask_init=config.mask_init, <ide> mask_scale=config.mask_scale, <ide> ) <del> self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) <add> self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) <ide> self.dropout = nn.Dropout(config.hidden_dropout_prob) <ide> <ide> def forward(self, hidden_states, input_tensor, threshold): <ide> def _init_weights(self, module): <ide> # Slightly different from the TF version which uses truncated_normal for initialization <ide> # cf https://github.com/pytorch/pytorch/pull/5617 <ide> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) <del> elif isinstance(module, BertLayerNorm): <add> elif isinstance(module, nn.LayerNorm): <ide> module.bias.data.zero_() <ide> module.weight.data.fill_(1.0) <ide> if isinstance(module, nn.Linear) and module.bias is not None:
1
Text
Text
update documentation for new test log format
6fe38e3947c0e744c4f6c48956044fc99a577806
<ide><path>docs/project/test-and-docs.md <ide> Run the entire test suite on your current repository: <ide> successfully, you see the output concludes with something like this: <ide> <ide> <del> [PASSED]: top - sleep process should be listed in privileged mode <del> [PASSED]: version - verify that it works and that the output is properly formatted <add> PASS: docker_cli_pull_test.go:133: DockerHubPullSuite.TestPullClientDisconnect 1.127s <add> PASS: docker_cli_pull_test.go:16: DockerHubPullSuite.TestPullFromCentralRegistry 1.049s <add> PASS: docker_cli_pull_test.go:65: DockerHubPullSuite.TestPullFromCentralRegistryImplicitRefParts 9.795s <add> PASS: docker_cli_pull_test.go:42: DockerHubPullSuite.TestPullNonExistingImage 2.158s <add> PASS: docker_cli_pull_test.go:92: DockerHubPullSuite.TestPullScratchNotAllowed 0.044s <add> OK: 918 passed, 13 skipped <ide> PASS <del> coverage: 70.8% of statements <del> ---> Making bundle: test-docker-py (in bundles/1.5.0-dev/test-docker-py) <del> +++ exec docker daemon --debug --host unix:///go/src/github.com/docker/docker/bundles/1.5.0-dev/test-docker-py/docker.sock --storage-driver vfs --exec-driver native --pidfile /go/src/github.com/docker/docker/bundles/1.5.0-dev/test-docker-py/docker.pid <del> ................................................................. <add> coverage: 72.9% of statements <add> ok github.com/docker/docker/integration-cli 1638.553s <add> ---> Making bundle: .integration-daemon-stop (in bundles/1.9.0-dev/test-integration-cli) <add> ++++ cat bundles/1.9.0-dev/test-integration-cli/docker.pid <add> +++ kill 9453 <add> +++ /etc/init.d/apparmor stop <add> * Clearing AppArmor profiles cache <add> ...done. <add> All profile caches have been cleared, but no profiles have been unloaded. <add> Unloading profiles will leave already running processes permanently <add> unconfined, which can lead to unexpected situations. <add> <add> To set a process to complain mode, use the command line tool <add> 'aa-complain'. To really tear down all profiles, run the init script <add> with the 'teardown' option." <add> <add> ---> Making bundle: test-docker-py (in bundles/1.9.0-dev/test-docker-py) <add> ---> Making bundle: .integration-daemon-start (in bundles/1.9.0-dev/test-docker-py) <add> +++ /etc/init.d/apparmor start <add> * Starting AppArmor profiles <add> Skipping profile in /etc/apparmor.d/disable: usr.sbin.rsyslogd <add> ...done. <add> +++ exec docker daemon --debug --host unix:///go/src/github.com/docker/docker/bundles/1.9.0-dev/test-docker-py/docker.sock --storage-driver overlay --exec-driver native --pidfile bundles/1.9.0-dev/test-docker-py/docker.pid --userland-proxy=true <add> ..............s..............s...................................... <ide> ---------------------------------------------------------------------- <del> Ran 65 tests in 89.266s <add> Ran 68 tests in 79.135s <ide> <ide> <ide> ### Run test targets inside the development container
1
Javascript
Javascript
add noop stub for fswatcher.prototype.start
f04810531afba30c77163fe18f4d16c540d94eb9
<ide><path>lib/internal/fs/watchers.js <ide> FSWatcher.prototype[kFSWatchStart] = function(filename, <ide> } <ide> }; <ide> <add>// To maximize backward-compatiblity for the end user, <add>// a no-op stub method has been added instead of <add>// totally removing FSWatcher.prototpye.start. <add>// This should not be documented. <add>FSWatcher.prototype.start = () => {}; <add> <ide> // This method is a noop if the watcher has not been started or <ide> // has already been closed. <ide> FSWatcher.prototype.close = function() {
1
PHP
PHP
fix failing tests in phpunit 3.7.0-rc2
d26040e3aa2173dfc3562ceb522287eb1083a5db
<ide><path>lib/Cake/Test/Case/Event/CakeEventManagerTest.php <ide> public function testDispatchReturnValue() { <ide> $manager->attach(array($anotherListener, 'listenerFunction'), 'fake.event'); <ide> $event = new CakeEvent('fake.event'); <ide> <del> $firstStep = clone $event; <del> $listener->expects($this->at(0))->method('listenerFunction') <del> ->with($firstStep) <add> $listener->expects($this->at(0)) <add> ->method('listenerFunction') <add> ->with($event) <ide> ->will($this->returnValue('something special')); <del> $anotherListener->expects($this->at(0))->method('listenerFunction')->with($event); <add> $anotherListener->expects($this->at(0)) <add> ->method('listenerFunction') <add> ->with($event); <ide> $manager->dispatch($event); <ide> $this->assertEquals('something special', $event->result); <ide> } <ide> public function testDispatchFalseStopsEvent() { <ide> $manager->attach(array($anotherListener, 'listenerFunction'), 'fake.event'); <ide> $event = new CakeEvent('fake.event'); <ide> <del> $originalEvent = clone $event; <ide> $listener->expects($this->at(0))->method('listenerFunction') <del> ->with($originalEvent) <add> ->with($event) <ide> ->will($this->returnValue(false)); <del> $anotherListener->expects($this->never())->method('listenerFunction'); <add> $anotherListener->expects($this->never()) <add> ->method('listenerFunction'); <ide> $manager->dispatch($event); <ide> $this->assertTrue($event->isStopped()); <ide> }
1
Text
Text
fix typo in the changelog
7368bbd4046a062a45704f9f7449da4987e75871
<ide><path>activerecord/CHANGELOG.md <ide> #or <ide> ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = '--no-defaults --skip-add-drop-table' <ide> ``` <del> <add> <ide> And also use it passing a hash, with one or more keys, where the key <ide> is the adapter <ide> <ide> ```ruby <ide> ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = { <ide> mysql2: ['--no-defaults', '--skip-add-drop-table'], <ide> postgres: '--no-tablespaces' <del> } <add> } <ide> ``` <ide> <ide> *Gustavo Gonzalez* <ide> # => ActiveRecord::StrictLoadingViolationError <ide> <ide> user = User.first <del> user.stict_loading!(false) <add> user.strict_loading!(false) <ide> user.articles <ide> # => #<ActiveRecord::Associations::CollectionProxy> <ide> ```
1
Python
Python
fix example docstring
ced84d53bc01e1623da671187588a63dcc9a5a11
<ide><path>examples/antirectifier.py <ide> class Antirectifier(Layer): <ide> Antirectifier allows to return all-positive outputs like ReLU, <ide> without discarding any data. <ide> <del> Further, the samplewise normalization of the output <del> allows to interpret output features as a probability distribution <del> (since they are between 0 and 1 and sum to 1 for each sample). <del> <ide> Tests on MNIST show that Antirectifier allows to train networks <ide> with twice less parameters yet with comparable <ide> classification accuracy as an equivalent ReLU-based network.
1
PHP
PHP
add a failing test
508f3be6357c24796b1a7c677664e89356c8afed
<ide><path>tests/TestCase/Routing/Route/RouteTest.php <ide> public function testMatchWithMultibytePattern() <ide> $this->assertEquals("/articles/view/\xC4\x81", $result); <ide> } <ide> <add> /** <add> * Test that match() matches explicit GET routes <add> * <add> * @return void <add> */ <add> public function testMatchWithExplicitGet() <add> { <add> $route = new Route( <add> '/anything', <add> ['controller' => 'Articles', 'action' => 'foo', '_method' => 'GET'] <add> ); <add> $result = $route->match([ <add> 'controller' => 'Articles', <add> 'action' => 'foo' <add> ]); <add> $this->assertEquals("/anything", $result); <add> } <add> <ide> /** <ide> * Test separartor. <ide> *
1
Text
Text
add supported platforms list
ef4768754c870e3a0b0d2e09c062cfbde03afb63
<ide><path>BUILDING.md <ide> If you consistently can reproduce a test failure, search for it in the <ide> [Node.js issue tracker](https://github.com/nodejs/node/issues) or <ide> file a new issue. <ide> <add>## Supported platforms <add> <add>This list of supported platforms is current as of the branch / release to <add>which it is attached. <add> <add>### Input <add> <add>Node.js relies on V8 and libuv. Therefore, we adopt a subset of their <add>supported platforms. <add> <add>### Strategy <add> <add>Support is divided into three tiers: <add> <add>* **Tier 1**: Full test coverage and maintenance by the Node.js core team and <add> the broader community. <add>* **Tier 2**: Full test coverage but more limited maintenance, <add> often provided by the vendor of the platform. <add>* **Experimental**: Known to compile but not necessarily reliably or with <add> a full passing test suite. These are often working to be promoted to Tier <add> 2 but are not quite ready. There is at least one individual actively <add> providing maintenance and the team is striving to broaden quality and <add> reliability of support. <add> <add>### Supported platforms <add> <add>| System | Support type | Version | Architectures | Notes | <add>|--------------|--------------|----------------------------------|----------------------|------------------| <add>| GNU/Linux | Tier 1 | kernel >= 2.6.18, glibc >= 2.5 | x86, x64, arm, arm64 | | <add>| macOS | Tier 1 | >= 10.10 | x64 | | <add>| Windows | Tier 1 | >= Windows 7 or >= Windows2008R2 | x86, x64 | | <add>| SmartOS | Tier 2 | >= 15 < 16.4 | x86, x64 | see note1 | <add>| FreeBSD | Tier 2 | >= 10 | x64 | | <add>| GNU/Linux | Tier 2 | kernel >= 4.2.0, glibc >= 2.19 | ppc64be | | <add>| GNU/Linux | Tier 2 | kernel >= 3.13.0, glibc >= 2.19 | ppc64le | | <add>| AIX | Tier 2 | >= 6.1 TL09 | ppc64be | | <add>| GNU/Linux | Tier 2 | kernel >= 3.10, glibc >= 2.17 | s390x | | <add>| macOS | Experimental | >= 10.8 < 10.10 | x64 | no test coverage | <add>| Linux (musl) | Experimental | musl >= 1.0 | x64 | | <add> <add>note1 - The gcc4.8-libs package needs to be installed, because node <add> binaries have been built with GCC 4.8, for which runtime libraries are not <add> installed by default. For these node versions, the recommended binaries <add> are the ones available in pkgsrc, not the one available from nodejs.org. <add> Note that the binaries downloaded from the pkgsrc repositories are not <add> officially supported by the Node.js project, and instead are supported <add> by Joyent. SmartOS images >= 16.4 are not supported because <add> GCC 4.8 runtime libraries are not available in their pkgsrc repository <add> <add>### Supported toolchains <add> <add>Depending on host platform, the selection of toolchains may vary. <add> <add>#### Unix <add> <add>* GCC 4.8.5 or newer <add>* Clang 3.4.1 or newer <add> <add>#### Windows <add> <add>* Building Node: Visual Studio 2015 or Visual C++ Build Tools 2015 or newer <add>* Building native add-ons: Visual Studio 2013 or Visual C++ Build Tools 2015 <add> or newer <add> <add>## Building Node.js on supported platforms <ide> <ide> ### Unix / OS X <ide> <ide> Prerequisites: <ide> <ide> * `gcc` and `g++` 4.8.5 or newer, or <del>* `clang` and `clang++` 3.4 or newer <add>* `clang` and `clang++` 3.4.1 or newer <ide> * Python 2.6 or 2.7 <ide> * GNU Make 3.81 or newer <ide> <ide> On OS X, you will also need: <ide> * [Xcode](https://developer.apple.com/xcode/download/) <del> * You also need to install the `Command Line Tools` via Xcode. You can find <add> - You also need to install the `Command Line Tools` via Xcode. You can find <ide> this under the menu `Xcode -> Preferences -> Downloads` <del> * This step will install `gcc` and the related toolchain containing `make` <add> - This step will install `gcc` and the related toolchain containing `make` <ide> <ide> * After building, you may want to setup [firewall rules](tools/macosx-firewall.sh) <ide> to avoid popups asking to accept incoming network connections when running tests: <ide> the `-j4` flag. See the <ide> [GNU Make Documentation](https://www.gnu.org/software/make/manual/html_node/Parallel.html) <ide> for more information. <ide> <del>Note that the above requires that `python` resolve to Python 2.6 or 2.7 and not a newer version. <add>Note that the above requires that `python` resolve to Python 2.6 or 2.7 <add>and not a newer version. <ide> <ide> To run the tests: <ide> <ide> It is possible to build Node.js with <ide> <ide> **Note**: building in this way does **not** allow you to claim that the <ide> runtime is FIPS 140-2 validated. Instead you can indicate that the runtime <del>uses a validated module. See the [security policy](http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp1747.pdf) <add>uses a validated module. See the <add>[security policy](http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp1747.pdf) <ide> page 60 for more details. In addition, the validation for the underlying module <del>is only valid if it is deployed in accordance with its [security policy](http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp1747.pdf). <add>is only valid if it is deployed in accordance with its <add>[security policy](http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp1747.pdf). <ide> If you need FIPS validated cryptography it is recommended that you read both <ide> the [security policy](http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp1747.pdf) <ide> and [user guide](https://openssl.org/docs/fips/UserGuide-2.0.pdf).
1
Text
Text
translate 02.2 to korean
a04597eaa10ecbfdd8ec8ee0885721ff534cc6eb
<ide><path>docs/docs/02.2-jsx-spread.ko-KR.md <add>--- <add>id: jsx-spread-ko-KR <add>title: JSX 스프레드 어트리뷰트 <add>permalink: jsx-spread-ko-KR.html <add>prev: jsx-in-depth-ko-KR.html <add>next: jsx-gotchas-ko-KR.html <add>--- <add> <add>미리 컴포넌트에 넣을 모든 프로퍼티를 알게 된다면, JSX를 사용하기 쉬워집니다. <add> <add>```javascript <add> var component = <Component foo={x} bar={y} />; <add>``` <add> <add>## Props의 변경은 나빠요.[^1] <add> <add>하지만 어떤 프로퍼티를 설정하고 싶은지 모른다면, 객체 레이어에 넣고 싶어질 수도 있습니다. <add> <add>```javascript <add> var component = <Component />; <add> component.props.foo = x; // 나쁨 <add> component.props.bar = y; // 역시 나쁨 <add>``` <add> <add>이것은 안티 패턴입니다. 왜냐하면 한참 뒤까지 정확한 propTypes을 체크할 수 없다는 뜻이기 때문입니다. 이것은 propTypes 에러는 알기 힘든 스택 트레이스로 끝난다는 의미입니다. <add> <add>이 시점에서 props는 불변성인 것을 고려해야 합니다. props 객체를 변경하는 것은 다른 곳에서 예기치 못한 결과가 생길 수 있기 때문에 이상적으로는 이 시점에서 frozen 객체가 되어야 합니다. <add> <add>## 스프레드 어트리뷰트 <add> <add>이제 JSX 새로운 기능 스프레드 어트리뷰트를 사용하실 수 있습니다. <add> <add>```javascript <add> var props = {}; <add> props.foo = x; <add> props.bar = y; <add> var component = <Component {...props} />; <add>``` <add> <add>전달한 객체의 프로퍼티가 컴포넌트의 props에 복사됩니다. <add> <add>이 것은 여러 번 사용하거나 다른 어트리뷰트와 조합해서 사용할 수 있습니다. 명세 순서는 중요합니다. 나중의 어트리뷰트가 이전 것보다 우선되기 때문입니다. <add> <add>```javascript <add> var props = { foo: 'default' }; <add> var component = <Component {...props} foo={'override'} />; <add> console.log(component.props.foo); // 'override' <add>``` <add> <add>## 이상한 `...` 표기법은 무엇인가요? <add> <add>`...` 연산자(스프레드 연산자)는 이미 [ES6의 배열](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)에서 지원합니다. [객체 rest와 스프레드 프로퍼티](https://github.com/sebmarkbage/ecmascript-rest-spread)에 대한 ES7의 제안도 있습니다. JSX의 구문을 더 깔끔하게 하기 위해 지원되고 개발중인 표준을 활용하고 있습니다. <add> <add>[^1]: 아무래도 좋지만, 이 제목의 원문 "Mutating Props is Bad, mkay"는 사우스 파크에 <add> 나온 대사 "[Drug is bad, mkay](https://www.youtube.com/watch?v=Uh7l8dx-h8M)"의 <add> 패러디입니다.
1
Javascript
Javascript
support ipv6 urls
b643f0d3223a627ef813f0777524e25d2dd95371
<ide><path>src/ngResource/resource.js <ide> function shallowClearAndCopy(src, dst) { <ide> */ <ide> angular.module('ngResource', ['ng']). <ide> provider('$resource', function() { <add> var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/; <ide> var provider = this; <ide> <ide> this.defaults = { <ide> angular.module('ngResource', ['ng']). <ide> var self = this, <ide> url = actionUrl || self.template, <ide> val, <del> encodedVal; <add> encodedVal, <add> protocolAndDomain = ''; <ide> <ide> var urlParams = self.urlParams = {}; <ide> forEach(url.split(/\W/), function(param) { <ide> angular.module('ngResource', ['ng']). <ide> } <ide> }); <ide> url = url.replace(/\\:/g, ':'); <add> url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) { <add> protocolAndDomain = match; <add> return ''; <add> }); <ide> <ide> params = params || {}; <ide> forEach(self.urlParams, function(_, urlParam) { <ide> angular.module('ngResource', ['ng']). <ide> // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` <ide> url = url.replace(/\/\.(?=\w+($|\?))/, '.'); <ide> // replace escaped `/\.` with `/.` <del> config.url = url.replace(/\/\\\./, '/.'); <add> config.url = protocolAndDomain + url.replace(/\/\\\./, '/.'); <ide> <ide> <ide> // set params - delegate param encoding to $http <ide><path>test/ngResource/resourceSpec.js <ide> describe("resource", function() { <ide> R.get({a: 'foo'}); <ide> }); <ide> <add> it('should support IPv6 URLs', function() { <add> var R = $resource('http://[2620:0:861:ed1a::1]/:ed1a/', {}, {}, {stripTrailingSlashes: false}); <add> $httpBackend.expect('GET', 'http://[2620:0:861:ed1a::1]/foo/').respond({}); <add> $httpBackend.expect('GET', 'http://[2620:0:861:ed1a::1]/').respond({}); <add> R.get({ed1a: 'foo'}); <add> R.get({}); <add> }); <add> <ide> it('should support overriding provider default trailing-slash stripping configuration', function() { <ide> // Set the new behavior for all new resources created by overriding the <ide> // provider configuration
2
Go
Go
remove container rootfs mountpath after umount
92e45b81e0a8b68d9567a2068247460a1ba59600
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) UnmountDevice(hash, mountPath string) error { <ide> } <ide> logrus.Debug("devmapper: Unmount done") <ide> <add> // Remove the mountpoint here. Removing the mountpoint (in newer kernels) <add> // will cause all other instances of this mount in other mount namespaces <add> // to be killed (this is an anti-DoS measure that is necessary for things <add> // like devicemapper). This is necessary to avoid cases where a libdm mount <add> // that is present in another namespace will cause subsequent RemoveDevice <add> // operations to fail. We ignore any errors here because this may fail on <add> // older kernels which don't have <add> // torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied. <add> if err := os.Remove(mountPath); err != nil { <add> logrus.Debugf("devmapper: error doing a remove on unmounted device %s: %v", mountPath, err) <add> } <add> <ide> return devices.deactivateDevice(info) <ide> } <ide> <ide><path>daemon/graphdriver/devmapper/driver.go <ide> func (d *Driver) Put(id string) error { <ide> if count := d.ctr.Decrement(mp); count > 0 { <ide> return nil <ide> } <add> <ide> err := d.DeviceSet.UnmountDevice(id, mp) <ide> if err != nil { <del> logrus.Errorf("devmapper: Error unmounting device %s: %s", id, err) <add> logrus.Errorf("devmapper: Error unmounting device %s: %v", id, err) <ide> } <add> <ide> return err <ide> } <ide>
2
Ruby
Ruby
reap the process or make zombies
fe15b9b003fbbfb4805ad2cff5bee6003bd1f749
<ide><path>Library/Homebrew/formula.rb <ide> def system cmd, *args <ide> wr.close <ide> out << rd.read until rd.eof? <ide> end <add> Process.wait <ide> unless $?.success? <ide> puts out <ide> raise
1
Text
Text
add model card for ai4bharat/indic-bert
35fd3d64e36e5dadde4a63dab75ee3b599293f18
<ide><path>model_cards/ai4bharat/indic-bert/README.md <add>--- <add>language: en <add>license: mit <add>datasets: <add>- AI4Bharat IndicNLP Corpora <add>--- <add> <add># IndicBERT <add> <add>IndicBERT is a multilingual ALBERT model pretrained exclusively on 12 major Indian languages. It is pre-trained on our novel monolingual corpus of around 9 billion tokens and subsequently evaluated on a set of diverse tasks. IndicBERT has much fewer parameters than other multilingual models (mBERT, XLM-R etc.) while it also achieves a performance on-par or better than these models. <add> <add>The 12 languages covered by IndicBERT are: Assamese, Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Oriya, Punjabi, Tamil, Telugu. <add> <add>The code can be found [here](https://github.com/divkakwani/indic-bert). For more information, checkout our [project page](https://indicnlp.ai4bharat.org/) or our [paper](https://indicnlp.ai4bharat.org/papers/arxiv2020_indicnlp_corpus.pdf). <add> <add> <add> <add>## Pretraining Corpus <add> <add>We pre-trained indic-bert on AI4Bharat's monolingual corpus. The corpus has the following distribution of languages: <add> <add> <add>| Language | as | bn | en | gu | hi | kn | | <add>| ----------------- | ------ | ------ | ------ | ------ | ------ | ------ | ------- | <add>| **No. of Tokens** | 36.9M | 815M | 1.34B | 724M | 1.84B | 712M | | <add>| **Language** | **ml** | **mr** | **or** | **pa** | **ta** | **te** | **all** | <add>| **No. of Tokens** | 767M | 560M | 104M | 814M | 549M | 671M | 8.9B | <add> <add> <add> <add>## Evaluation Results <add> <add>IndicBERT is evaluated on IndicGLUE and some additional tasks. The results are summarized below. For more details about the tasks, refer our [official repo](https://github.com/divkakwani/indic-bert) <add> <add>#### IndicGLUE <add> <add>Task | mBERT | XLM-R | IndicBERT <add>-----| ----- | ----- | ------ <add>News Article Headline Prediction | 89.58 | 95.52 | **95.87** <add>Wikipedia Section Title Prediction| **73.66** | 66.33 | 73.31 <add>Cloze-style multiple-choice QA | 39.16 | 27.98 | **41.87** <add>Article Genre Classification | 90.63 | 97.03 | **97.34** <add>Named Entity Recognition (F1-score) | **73.24** | 65.93 | 64.47 <add>Cross-Lingual Sentence Retrieval Task | 21.46 | 13.74 | **27.12** <add>Average | 64.62 | 61.09 | **66.66** <add> <add>#### Additional Tasks <add> <add> <add>Task | Task Type | mBERT | XLM-R | IndicBERT <add>-----| ----- | ----- | ------ | ----- <add>BBC News Classification | Genre Classification | 60.55 | **75.52** | 74.60 <add>IIT Product Reviews | Sentiment Analysis | 74.57 | **78.97** | 71.32 <add>IITP Movie Reviews | Sentiment Analaysis | 56.77 | **61.61** | 59.03 <add>Soham News Article | Genre Classification | 80.23 | **87.6** | 78.45 <add>Midas Discourse | Discourse Analysis | 71.20 | **79.94** | 78.44 <add>iNLTK Headlines Classification | Genre Classification | 87.95 | 93.38 | **94.52** <add>ACTSA Sentiment Analysis | Sentiment Analysis | 48.53 | 59.33 | **61.18** <add>Winograd NLI | Natural Language Inference | 56.34 | 55.87 | **56.34** <add>Choice of Plausible Alternative (COPA) | Natural Language Inference | 54.92 | 51.13 | **58.33** <add>Amrita Exact Paraphrase | Paraphrase Detection | **93.81** | 93.02 | 93.75 <add>Amrita Rough Paraphrase | Paraphrase Detection | 83.38 | 82.20 | **84.33** <add>Average | | 69.84 | **74.42** | 73.66 <add> <add> <add>\* Note: all models have been restricted to a max_seq_length of 128. <add> <add> <add> <add>## Downloads <add> <add>The model can be downloaded [here](https://storage.googleapis.com/ai4bharat-public-indic-nlp-corpora/models/indic-bert-v1.tar.gz). Both tf checkpoints and pytorch binaries are included in the archive. Alternatively, you can also download it from [Huggingface](https://huggingface.co/ai4bharat/indic-bert). <add> <add> <add> <add>## Citing <add> <add>If you are using any of the resources, please cite the following article: <add> <add>``` <add>@inproceedings{kakwani2020indicnlpsuite, <add> title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, <add> author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, <add> year={2020}, <add> booktitle={Findings of EMNLP}, <add>} <add>``` <add> <add>We would like to hear from you if: <add> <add>- You are using our resources. Please let us know how you are putting these resources to use. <add>- You have any feedback on these resources. <add> <add> <add> <add>## License <add> <add>The IndicBERT code (and models) are released under the MIT License. <add> <add>## Contributors <add> <add>- Divyanshu Kakwani <add>- Anoop Kunchukuttan <add>- Gokul NC <add>- Satish Golla <add>- Avik Bhattacharyya <add>- Mitesh Khapra <add>- Pratyush Kumar <add> <add>This work is the outcome of a volunteer effort as part of [AI4Bharat initiative](https://ai4bharat.org). <add> <add> <add> <add>## Contact <add> <add>- Anoop Kunchukuttan ([[email protected]](mailto:[email protected])) <add>- Mitesh Khapra ([[email protected]](mailto:[email protected])) <add>- Pratyush Kumar ([[email protected]](mailto:[email protected]))
1
Javascript
Javascript
use hasownproperty checks in object.assign
25d63b43efdc5a13a174b412233179bb0b79698c
<ide><path>src/vendor/stubs/Object.assign.js <ide> * @providesModule Object.assign <ide> */ <ide> <del>// This is an optimized version that fails on hasOwnProperty checks <del>// and non objects. It's not spec-compliant. It's a perf optimization. <del> <del>var hasOwnProperty = Object.prototype.hasOwnProperty; <add>// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign <ide> <ide> function assign(target, sources) { <del> if (__DEV__) { <del> if (target == null) { <del> throw new TypeError('Object.assign target cannot be null or undefined'); <del> } <del> if (typeof target !== 'object' && typeof target !== 'function') { <del> throw new TypeError( <del> 'In this environment the target of assign MUST be an object. ' + <del> 'This error is a performance optimization and not spec compliant.' <del> ); <del> } <add> if (target == null) { <add> throw new TypeError('Object.assign target cannot be null or undefined'); <ide> } <ide> <add> var to = Object(target); <add> var hasOwnProperty = Object.prototype.hasOwnProperty; <add> <ide> for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { <ide> var nextSource = arguments[nextIndex]; <ide> if (nextSource == null) { <ide> continue; <ide> } <ide> <add> var from = Object(nextSource); <add> <ide> // We don't currently support accessors nor proxies. Therefore this <ide> // copy cannot throw. If we ever supported this then we must handle <del> // exceptions and side-effects. <del> <del> for (var key in nextSource) { <del> if (__DEV__) { <del> if (!hasOwnProperty.call(nextSource, key)) { <del> throw new TypeError( <del> 'One of the sources to assign has an enumerable key on the ' + <del> 'prototype chain. This is an edge case that we do not support. ' + <del> 'This error is a performance optimization and not spec compliant.' <del> ); <del> } <add> // exceptions and side-effects. We don't support symbols so they won't <add> // be transferred. <add> <add> for (var key in from) { <add> if (hasOwnProperty.call(from, key)) { <add> to[key] = from[key]; <ide> } <del> target[key] = nextSource[key]; <ide> } <ide> } <ide> <del> return target; <add> return to; <ide> }; <ide> <ide> module.exports = assign;
1
Text
Text
add text about getting help.
fbc399d35c187110425958155dce23299932fd6e
<ide><path>guide/english/linux/10-simple-and-useful-linux-commands/index.md <ide> ifconfig allows you to see the addresses associated with each TCP/IP interface o <ide> <ide> 12. `systemctl` <ide> This is a command which allows operators to work with the Linux system services. The standard use of the command is `systemctl <OPTION> <SERVICE-NAME>` by providing an `OPTION` (e.g. `start`, `stop`, `status`) and than providing a specific Service Name to act on. You can use the command to get a general status of your Linux services (e.g `systemctl status`). Note that you will either need Administrator access or use `sudo` to elevate your rights to run the command successfully. <add> <add>### How to get help about the commands: <add>More info can be viewed about how to use each of the commands listed above right in the terminal in the following ways: <add>1. Using `man` to access the manual pages. It takes as argument another command name and returns a complete tutorial about the argument, including main options of use, syntax details and another related commands. You can search a text accross all man pages database. <add>Example: `man cd` <add>2. Using the `--help` flag to see quick options to use in command line. <add>Example: `cd --help`
1
Ruby
Ruby
rename some variables
c4458b36024a20abacc39c069444bb0ac202778a
<ide><path>activerecord/lib/active_record/associations/has_one_through_association.rb <ide> def replace(record) <ide> <ide> private <ide> <del> def create_through_record(new_value) <del> proxy = @owner.send(:association_proxy, @reflection.through_reflection.name) <del> record = proxy.send(:load_target) <add> def create_through_record(record) <add> through_proxy = @owner.send(:association_proxy, @reflection.through_reflection.name) <add> through_record = through_proxy.send(:load_target) <ide> <del> if record && !new_value <del> record.destroy <del> elsif new_value <del> attributes = construct_join_attributes(new_value) <add> if through_record && !record <add> through_record.destroy <add> elsif record <add> attributes = construct_join_attributes(record) <ide> <del> if record <del> record.update_attributes(attributes) <add> if through_record <add> through_record.update_attributes(attributes) <ide> elsif @owner.new_record? <del> proxy.build(attributes) <add> through_proxy.build(attributes) <ide> else <del> proxy.create(attributes) <add> through_proxy.create(attributes) <ide> end <ide> end <ide> end
1
PHP
PHP
fix @param doc
d74ad86b2293c4d7151b65fb370c93cc1f5153eb
<ide><path>src/Database/Type/JsonType.php <ide> public function marshal($value) <ide> /** <ide> * Set json_encode options. <ide> * <del> * @param int|null $jsonOptions Options. Use JSON_* flags <add> * @param int $jsonOptions Options. Use JSON_* flags. Set `0` to reset. <ide> * @return self <ide> * @see https://www.php.net/manual/en/function.json-encode.php <ide> */
1
Go
Go
add func to get an io.reader for tail operations
874867d4e575ef805d71759e703e4f11cce05bd3
<ide><path>pkg/tailfile/tailfile.go <ide> package tailfile // import "github.com/docker/docker/pkg/tailfile" <ide> <ide> import ( <add> "bufio" <ide> "bytes" <add> "context" <ide> "errors" <ide> "io" <ide> "os" <ide> var eol = []byte("\n") <ide> // ErrNonPositiveLinesNumber is an error returned if the lines number was negative. <ide> var ErrNonPositiveLinesNumber = errors.New("The number of lines to extract from the file must be positive") <ide> <del>//TailFile returns last n lines of reader f (could be a nil). <del>func TailFile(f io.ReadSeeker, n int) ([][]byte, error) { <del> if n <= 0 { <del> return nil, ErrNonPositiveLinesNumber <add>//TailFile returns last n lines of the passed in file. <add>func TailFile(f *os.File, n int) ([][]byte, error) { <add> size, err := f.Seek(0, io.SeekEnd) <add> if err != nil { <add> return nil, err <ide> } <del> size, err := f.Seek(0, os.SEEK_END) <add> <add> rAt := io.NewSectionReader(f, 0, size) <add> r, nLines, err := NewTailReader(context.Background(), rAt, n) <ide> if err != nil { <ide> return nil, err <ide> } <del> block := -1 <del> var data []byte <del> var cnt int <add> <add> buf := make([][]byte, 0, nLines) <add> scanner := bufio.NewScanner(r) <add> <add> for scanner.Scan() { <add> buf = append(buf, scanner.Bytes()) <add> } <add> return buf, nil <add>} <add> <add>// SizeReaderAt is an interface used to get a ReaderAt as well as the size of the underlying reader. <add>// Note that the size of the underlying reader should not change when using this interface. <add>type SizeReaderAt interface { <add> io.ReaderAt <add> Size() int64 <add>} <add> <add>// NewTailReader scopes the passed in reader to just the last N lines passed in <add>func NewTailReader(ctx context.Context, r SizeReaderAt, reqLines int) (io.Reader, int, error) { <add> return NewTailReaderWithDelimiter(ctx, r, reqLines, eol) <add>} <add> <add>// NewTailReaderWithDelimiter scopes the passed in reader to just the last N lines passed in <add>// In this case a "line" is defined by the passed in delimiter. <add>// <add>// Delimiter lengths should be generally small, no more than 12 bytes <add>func NewTailReaderWithDelimiter(ctx context.Context, r SizeReaderAt, reqLines int, delimiter []byte) (io.Reader, int, error) { <add> if reqLines < 1 { <add> return nil, 0, ErrNonPositiveLinesNumber <add> } <add> if len(delimiter) == 0 { <add> return nil, 0, errors.New("must provide a delimiter") <add> } <add> var ( <add> size = r.Size() <add> tailStart int64 <add> tailEnd = size <add> found int <add> ) <add> <add> if int64(len(delimiter)) >= size { <add> return bytes.NewReader(nil), 0, nil <add> } <add> <add> scanner := newScanner(r, delimiter) <add> for scanner.Scan(ctx) { <add> if err := scanner.Err(); err != nil { <add> return nil, 0, scanner.Err() <add> } <add> <add> found++ <add> if found == 1 { <add> tailEnd = scanner.End() <add> } <add> if found == reqLines { <add> break <add> } <add> } <add> <add> tailStart = scanner.Start(ctx) <add> <add> if found == 0 { <add> return bytes.NewReader(nil), 0, nil <add> } <add> <add> if found < reqLines && tailStart != 0 { <add> tailStart = 0 <add> } <add> return io.NewSectionReader(r, tailStart, tailEnd-tailStart), found, nil <add>} <add> <add>func newScanner(r SizeReaderAt, delim []byte) *scanner { <add> size := r.Size() <add> readSize := blockSize <add> if readSize > int(size) { <add> readSize = int(size) <add> } <add> // silly case... <add> if len(delim) >= readSize/2 { <add> readSize = len(delim)*2 + 2 <add> } <add> <add> return &scanner{ <add> r: r, <add> pos: size, <add> buf: make([]byte, readSize), <add> delim: delim, <add> } <add>} <add> <add>type scanner struct { <add> r SizeReaderAt <add> pos int64 <add> buf []byte <add> delim []byte <add> err error <add> idx int <add> done bool <add>} <add> <add>func (s *scanner) Start(ctx context.Context) int64 { <add> if s.idx > 0 { <add> idx := bytes.LastIndex(s.buf[:s.idx], s.delim) <add> if idx >= 0 { <add> return s.pos + int64(idx) + int64(len(s.delim)) <add> } <add> } <add> <add> // slow path <add> buf := make([]byte, len(s.buf)) <add> copy(buf, s.buf) <add> <add> readAhead := &scanner{ <add> r: s.r, <add> pos: s.pos, <add> delim: s.delim, <add> idx: s.idx, <add> buf: buf, <add> } <add> <add> if !readAhead.Scan(ctx) { <add> return 0 <add> } <add> return readAhead.End() <add>} <add> <add>func (s *scanner) End() int64 { <add> return s.pos + int64(s.idx) + int64(len(s.delim)) <add>} <add> <add>func (s *scanner) Err() error { <add> return s.err <add>} <add> <add>func (s *scanner) Scan(ctx context.Context) bool { <add> if s.err != nil { <add> return false <add> } <add> <ide> for { <del> var b []byte <del> step := int64(block * blockSize) <del> left := size + step // how many bytes to beginning <del> if left < 0 { <del> if _, err := f.Seek(0, os.SEEK_SET); err != nil { <del> return nil, err <del> } <del> b = make([]byte, blockSize+left) <del> if _, err := f.Read(b); err != nil { <del> return nil, err <add> select { <add> case <-ctx.Done(): <add> s.err = ctx.Err() <add> return false <add> default: <add> } <add> <add> idx := s.idx - len(s.delim) <add> if idx < 0 { <add> readSize := int(s.pos) <add> if readSize > len(s.buf) { <add> readSize = len(s.buf) <ide> } <del> data = append(b, data...) <del> break <del> } else { <del> b = make([]byte, blockSize) <del> if _, err := f.Seek(left, os.SEEK_SET); err != nil { <del> return nil, err <add> <add> if readSize < len(s.delim) { <add> return false <ide> } <del> if _, err := f.Read(b); err != nil { <del> return nil, err <add> <add> offset := s.pos - int64(readSize) <add> n, err := s.r.ReadAt(s.buf[:readSize], offset) <add> if err != nil && err != io.EOF { <add> s.err = err <add> return false <ide> } <del> data = append(b, data...) <add> <add> s.pos -= int64(n) <add> idx = n <ide> } <del> cnt += bytes.Count(b, eol) <del> if cnt > n { <del> break <add> <add> s.idx = bytes.LastIndex(s.buf[:idx], s.delim) <add> if s.idx >= 0 { <add> return true <ide> } <del> block-- <del> } <del> lines := bytes.Split(data, eol) <del> if n < len(lines) { <del> return lines[len(lines)-n-1 : len(lines)-1], nil <add> <add> if len(s.delim) > 1 && s.pos > 0 { <add> // in this case, there may be a partial delimiter at the front of the buffer, so set the position forward <add> // up to the maximum size partial that could be there so it can be read again in the next iteration with any <add> // potential remainder. <add> // An example where delimiter is `####`: <add> // [##asdfqwerty] <add> // ^ <add> // This resets the position to where the arrow is pointing. <add> // It could actually check if a partial exists and at the front, but that is pretty similar to the indexing <add> // code above though a bit more complex since each byte has to be checked (`len(delimiter)-1`) factorial). <add> // It's much simpler and cleaner to just re-read `len(delimiter)-1` bytes again. <add> s.pos += int64(len(s.delim)) - 1 <add> } <add> <ide> } <del> return lines[:len(lines)-1], nil <ide> } <ide><path>pkg/tailfile/tailfile_test.go <ide> package tailfile // import "github.com/docker/docker/pkg/tailfile" <ide> <ide> import ( <add> "bufio" <add> "bytes" <add> "context" <add> "fmt" <add> "io" <ide> "io/ioutil" <ide> "os" <add> "strings" <ide> "testing" <add> <add> "gotest.tools/assert" <ide> ) <ide> <ide> func TestTailFile(t *testing.T) { <ide> truncated line`) <ide> if _, err := f.Write(testFile); err != nil { <ide> t.Fatal(err) <ide> } <del> if _, err := f.Seek(0, os.SEEK_SET); err != nil { <add> if _, err := f.Seek(0, io.SeekStart); err != nil { <ide> t.Fatal(err) <ide> } <ide> expected := []string{"last fourth line", "last fifth line"} <ide> res, err := TailFile(f, 2) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <add> if len(res) != len(expected) { <add> t.Fatalf("\nexpected:\n%s\n\nactual:\n%s", expected, res) <add> } <ide> for i, l := range res { <del> t.Logf("%s", l) <ide> if expected[i] != string(l) { <del> t.Fatalf("Expected line %s, got %s", expected[i], l) <add> t.Fatalf("Expected line %q, got %q", expected[i], l) <ide> } <ide> } <ide> } <ide> truncated line`) <ide> if _, err := f.Write(testFile); err != nil { <ide> t.Fatal(err) <ide> } <del> if _, err := f.Seek(0, os.SEEK_SET); err != nil { <add> if _, err := f.Seek(0, io.SeekStart); err != nil { <ide> t.Fatal(err) <ide> } <ide> expected := []string{"first line", "second line"} <ide> res, err := TailFile(f, 10000) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <add> if len(expected) != len(res) { <add> t.Fatalf("\nexpected:\n%s\n\nactual:\n%s", expected, res) <add> } <ide> for i, l := range res { <del> t.Logf("%s", l) <ide> if expected[i] != string(l) { <ide> t.Fatalf("Expected line %s, got %s", expected[i], l) <ide> } <ide> truncated line`) <ide> if _, err := f.Write(testFile); err != nil { <ide> t.Fatal(err) <ide> } <del> if _, err := f.Seek(0, os.SEEK_SET); err != nil { <add> if _, err := f.Seek(0, io.SeekStart); err != nil { <ide> t.Fatal(err) <ide> } <ide> if _, err := TailFile(f, -1); err != ErrNonPositiveLinesNumber { <del> t.Fatalf("Expected ErrNonPositiveLinesNumber, got %s", err) <add> t.Fatalf("Expected ErrNonPositiveLinesNumber, got %v", err) <ide> } <ide> if _, err := TailFile(f, 0); err != ErrNonPositiveLinesNumber { <ide> t.Fatalf("Expected ErrNonPositiveLinesNumber, got %s", err) <ide> func BenchmarkTail(b *testing.B) { <ide> } <ide> } <ide> } <add> <add>func TestNewTailReader(t *testing.T) { <add> t.Parallel() <add> ctx := context.Background() <add> <add> for dName, delim := range map[string][]byte{ <add> "no delimiter": {}, <add> "single byte delimiter": {'\n'}, <add> "2 byte delimiter": []byte(";\n"), <add> "4 byte delimiter": []byte("####"), <add> "8 byte delimiter": []byte("########"), <add> "12 byte delimiter": []byte("############"), <add> } { <add> t.Run(dName, func(t *testing.T) { <add> delim := delim <add> t.Parallel() <add> <add> s1 := "Hello world." <add> s2 := "Today is a fine day." <add> s3 := "So long, and thanks for all the fish!" <add> s4 := strings.Repeat("a", blockSize/2) // same as block size <add> s5 := strings.Repeat("a", blockSize) // just to make sure <add> s6 := strings.Repeat("a", blockSize*2) // bigger than block size <add> s7 := strings.Repeat("a", blockSize-1) // single line same as block <add> <add> s8 := `{"log":"Don't panic!\n","stream":"stdout","time":"2018-04-04T20:28:44.7207062Z"}` <add> jsonTest := make([]string, 0, 20) <add> for i := 0; i < 20; i++ { <add> jsonTest = append(jsonTest, s8) <add> } <add> <add> for _, test := range []struct { <add> desc string <add> data []string <add> }{ <add> {desc: "one small entry", data: []string{s1}}, <add> {desc: "several small entries", data: []string{s1, s2, s3}}, <add> {desc: "various sizes", data: []string{s1, s2, s3, s4, s5, s1, s2, s3, s7, s6}}, <add> {desc: "multiple lines with one more than block", data: []string{s5, s5, s5, s5, s5}}, <add> {desc: "multiple lines much bigger than block", data: []string{s6, s6, s6, s6, s6}}, <add> {desc: "multiple lines same as block", data: []string{s4, s4, s4, s4, s4}}, <add> {desc: "single line same as block", data: []string{s7}}, <add> {desc: "single line half block", data: []string{s4}}, <add> {desc: "single line twice block", data: []string{s6}}, <add> {desc: "json encoded values", data: jsonTest}, <add> {desc: "no lines", data: []string{}}, <add> {desc: "same length as delimiter", data: []string{strings.Repeat("a", len(delim))}}, <add> } { <add> t.Run(test.desc, func(t *testing.T) { <add> test := test <add> t.Parallel() <add> <add> max := len(test.data) <add> if max > 10 { <add> max = 10 <add> } <add> <add> s := strings.Join(test.data, string(delim)) <add> if len(test.data) > 0 { <add> s += string(delim) <add> } <add> <add> for i := 1; i <= max; i++ { <add> t.Run(fmt.Sprintf("%d lines", i), func(t *testing.T) { <add> i := i <add> t.Parallel() <add> <add> r := strings.NewReader(s) <add> tr, lines, err := NewTailReaderWithDelimiter(ctx, r, i, delim) <add> if len(delim) == 0 { <add> assert.Assert(t, err != nil) <add> assert.Assert(t, lines == 0) <add> return <add> } <add> assert.Assert(t, err) <add> assert.Check(t, lines == i, "%d -- %d", lines, i) <add> <add> b, err := ioutil.ReadAll(tr) <add> assert.Assert(t, err) <add> <add> expectLines := test.data[len(test.data)-i:] <add> assert.Check(t, len(expectLines) == i) <add> expect := strings.Join(expectLines, string(delim)) + string(delim) <add> assert.Check(t, string(b) == expect, "\n%v\n%v", b, []byte(expect)) <add> }) <add> } <add> <add> t.Run("request more lines than available", func(t *testing.T) { <add> t.Parallel() <add> <add> r := strings.NewReader(s) <add> tr, lines, err := NewTailReaderWithDelimiter(ctx, r, len(test.data)*2, delim) <add> if len(delim) == 0 { <add> assert.Assert(t, err != nil) <add> assert.Assert(t, lines == 0) <add> return <add> } <add> if len(test.data) == 0 { <add> assert.Assert(t, err == ErrNonPositiveLinesNumber, err) <add> return <add> } <add> <add> assert.Assert(t, err) <add> assert.Check(t, lines == len(test.data), "%d -- %d", lines, len(test.data)) <add> b, err := ioutil.ReadAll(tr) <add> assert.Assert(t, err) <add> assert.Check(t, bytes.Equal(b, []byte(s)), "\n%v\n%v", b, []byte(s)) <add> }) <add> }) <add> } <add> }) <add> } <add> t.Run("truncated last line", func(t *testing.T) { <add> t.Run("more than available", func(t *testing.T) { <add> tail, nLines, err := NewTailReader(ctx, strings.NewReader("a\nb\nextra"), 3) <add> assert.Assert(t, err) <add> assert.Check(t, nLines == 2, nLines) <add> <add> rdr := bufio.NewReader(tail) <add> data, _, err := rdr.ReadLine() <add> assert.Assert(t, err) <add> assert.Check(t, string(data) == "a", string(data)) <add> <add> data, _, err = rdr.ReadLine() <add> assert.Assert(t, err) <add> assert.Check(t, string(data) == "b", string(data)) <add> <add> _, _, err = rdr.ReadLine() <add> assert.Assert(t, err == io.EOF, err) <add> }) <add> }) <add> t.Run("truncated last line", func(t *testing.T) { <add> t.Run("exact", func(t *testing.T) { <add> tail, nLines, err := NewTailReader(ctx, strings.NewReader("a\nb\nextra"), 2) <add> assert.Assert(t, err) <add> assert.Check(t, nLines == 2, nLines) <add> <add> rdr := bufio.NewReader(tail) <add> data, _, err := rdr.ReadLine() <add> assert.Assert(t, err) <add> assert.Check(t, string(data) == "a", string(data)) <add> <add> data, _, err = rdr.ReadLine() <add> assert.Assert(t, err) <add> assert.Check(t, string(data) == "b", string(data)) <add> <add> _, _, err = rdr.ReadLine() <add> assert.Assert(t, err == io.EOF, err) <add> }) <add> }) <add> <add> t.Run("truncated last line", func(t *testing.T) { <add> t.Run("one line", func(t *testing.T) { <add> tail, nLines, err := NewTailReader(ctx, strings.NewReader("a\nb\nextra"), 1) <add> assert.Assert(t, err) <add> assert.Check(t, nLines == 1, nLines) <add> <add> rdr := bufio.NewReader(tail) <add> data, _, err := rdr.ReadLine() <add> assert.Assert(t, err) <add> assert.Check(t, string(data) == "b", string(data)) <add> <add> _, _, err = rdr.ReadLine() <add> assert.Assert(t, err == io.EOF, err) <add> }) <add> }) <add>}
2
Python
Python
replace docs title. easy is a sucky word choice
4dd7b5f376be7d5f28ba8865cf4ede7ad553b8de
<ide><path>mkdocs.py <ide> toc += template + '\n' <ide> <ide> if filename == 'index.md': <del> main_title = 'Django REST framework - APIs made easy' <add> main_title = 'Django REST framework - Web APIs for Django' <ide> else: <ide> main_title = main_title + ' - Django REST framework' <ide>
1
PHP
PHP
clarify assoc array in docblock
96b7a217218e5995c703e68be52e813abee0f27e
<ide><path>src/Auth/DigestAuthenticate.php <ide> public function getUser(ServerRequest $request) <ide> * Gets the digest headers from the request/environment. <ide> * <ide> * @param \Cake\Http\ServerRequest $request Request object. <del> * @return array|null Array of digest information. <add> * @return array<string, mixed>|null Array of digest information. <ide> */ <ide> protected function _getDigest(ServerRequest $request): ?array <ide> { <ide> public function parseAuthData(string $digest): ?array <ide> /** <ide> * Generate the response hash for a given digest array. <ide> * <del> * @param array $digest Digest information containing data from DigestAuthenticate::parseAuthData(). <add> * @param array<string, mixed> $digest Digest information containing data from DigestAuthenticate::parseAuthData(). <ide> * @param string $password The digest hash password generated with DigestAuthenticate::password() <ide> * @param string $method Request method <ide> * @return string Response hash <ide><path>src/Console/ConsoleOptionParser.php <ide> public static function create(string $command, bool $defaultOptions = true) <ide> * ]; <ide> * ``` <ide> * <del> * @param array $spec The spec to build the OptionParser with. <add> * @param array<string, mixed> $spec The spec to build the OptionParser with. <ide> * @param bool $defaultOptions Whether you want the verbose and quiet options set. <ide> * @return static <ide> */ <ide> public function removeOption(string $name) <ide> * <ide> * @param \Cake\Console\ConsoleInputArgument|string $name The name of the argument. <ide> * Will also accept an instance of ConsoleInputArgument. <del> * @param array $params Parameters for the argument, see above. <add> * @param array<string, mixed> $params Parameters for the argument, see above. <ide> * @return $this <ide> */ <ide> public function addArgument($name, array $params = []) <ide> public function removeSubcommand(string $name) <ide> /** <ide> * Add multiple subcommands at once. <ide> * <del> * @param array $commands Array of subcommands. <add> * @param array<string, mixed> $commands Array of subcommands. <ide> * @return $this <ide> */ <ide> public function addSubcommands(array $commands) <ide> public function setRootName(string $name) <ide> * options with an `=` in them. <ide> * <ide> * @param string $option The option to parse. <del> * @param array $params The params to append the parsed value into <add> * @param array<string, mixed> $params The params to append the parsed value into <ide> * @return array Params with $option added in. <ide> */ <ide> protected function _parseLongOption(string $option, array $params): array <ide> protected function _parseLongOption(string $option, array $params): array <ide> * they will be shifted onto the token stack and parsed individually. <ide> * <ide> * @param string $option The option to parse. <del> * @param array $params The params to append the parsed value into <del> * @return array Params with $option added in. <add> * @param array<string, mixed> $params The params to append the parsed value into <add> * @return array<string, mixed> Params with $option added in. <ide> * @throws \Cake\Console\Exception\ConsoleException When unknown short options are encountered. <ide> */ <ide> protected function _parseShortOption(string $option, array $params): array <ide> protected function _parseShortOption(string $option, array $params): array <ide> * Parse an option by its name index. <ide> * <ide> * @param string $name The name to parse. <del> * @param array $params The params to append the parsed value into <del> * @return array Params with $option added in. <add> * @param array<string, mixed> $params The params to append the parsed value into <add> * @return array<string, mixed> Params with $option added in. <ide> * @throws \Cake\Console\Exception\ConsoleException <ide> */ <ide> protected function _parseOption(string $name, array $params): array <ide><path>src/Controller/Component/PaginatorComponent.php <ide> public function implementedEvents(): array <ide> * ``` <ide> * <ide> * @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object Table or query to paginate. <del> * @param array $settings The settings/configuration used for pagination. <add> * @param array<string, mixed> $settings The settings/configuration used for pagination. <ide> * @return \Cake\Datasource\ResultSetInterface Query results <ide> * @throws \Cake\Http\Exception\NotFoundException <ide> */ <ide> public function paginate(object $object, array $settings = []): ResultSetInterfa <ide> * <ide> * @param string $alias Model alias being paginated, if the general settings has a key with this value <ide> * that key's settings will be used for pagination instead of the general ones. <del> * @param array $settings The settings to merge with the request data. <del> * @return array Array of merged options. <add> * @param array<string, mixed> $settings The settings to merge with the request data. <add> * @return array<string, mixed> Array of merged options. <ide> */ <ide> public function mergeOptions(string $alias, array $settings): array <ide> { <ide><path>src/Controller/Component/SecurityComponent.php <ide> protected function _sortedUnlocked(array $data): string <ide> * Create a message for humans to understand why Security token is not matching <ide> * <ide> * @param \Cake\Controller\Controller $controller Instantiating controller <del> * @param array $hashParts Elements used to generate the Token hash <add> * @param array<string> $hashParts Elements used to generate the Token hash <ide> * @return string Message explaining why the tokens are not matching <ide> */ <ide> protected function _debugPostTokenNotMatching(Controller $controller, array $hashParts): string <ide><path>src/Controller/Controller.php <ide> public function referer($default = '/', bool $local = true): string <ide> * <ide> * @param \Cake\ORM\Table|\Cake\ORM\Query|string|null $object Table to paginate <ide> * (e.g: Table instance, 'TableName' or a Query object) <del> * @param array $settings The settings/configuration used for pagination. <add> * @param array<string, mixed> $settings The settings/configuration used for pagination. <ide> * @return \Cake\ORM\ResultSet|\Cake\Datasource\ResultSetInterface Query results <ide> * @link https://book.cakephp.org/4/en/controllers.html#paginating-a-model <ide> * @throws \RuntimeException When no compatible table object can be found. <ide><path>src/Database/Connection.php <ide> public function getSchemaCollection(): SchemaCollectionInterface <ide> * <ide> * @param string $table the table to insert values in <ide> * @param array $values values to be inserted <del> * @param array $types list of associative array containing the types to be used for casting <add> * @param array<string, string> $types list of associative array containing the types to be used for casting <ide> * @return \Cake\Database\StatementInterface <ide> */ <ide> public function insert(string $table, array $values, array $types = []): StatementInterface <ide><path>src/Database/Driver.php <ide> public function newTableSchema(string $table, array $columns = []): TableSchema <ide> <ide> /** <ide> * Returns the maximum alias length allowed. <del> * This can be different than the maximum identifier length for columns. <add> * This can be different from the maximum identifier length for columns. <ide> * <ide> * @return int|null Maximum alias length or null if no limit <ide> */ <ide><path>src/Database/Query.php <ide> public function unionAll($query, $overwrite = false) <ide> * with Query::values(). <ide> * <ide> * @param array $columns The columns to insert into. <del> * @param array<string> $types A map between columns & their datatypes. <add> * @param array<string, string> $types A map between columns & their datatypes. <ide> * @return $this <ide> * @throws \RuntimeException When there are 0 columns. <ide> */ <ide><path>src/Database/Schema/PostgresSchemaDialect.php <ide> public function indexSql(TableSchema $schema, string $name): string <ide> */ <ide> public function constraintSql(TableSchema $schema, string $name): string <ide> { <del> /** @var array $data */ <add> /** @var array<string, mixed> $data */ <ide> $data = $schema->getConstraint($name); <ide> $out = 'CONSTRAINT ' . $this->_driver->quoteIdentifier($name); <ide> if ($data['type'] === TableSchema::CONSTRAINT_PRIMARY) { <ide> public function constraintSql(TableSchema $schema, string $name): string <ide> * Helper method for generating key SQL snippets. <ide> * <ide> * @param string $prefix The key prefix <del> * @param array $data Key data. <add> * @param array<string, mixed> $data Key data. <ide> * @return string <ide> */ <ide> protected function _keySql(string $prefix, array $data): string <ide><path>src/Database/Schema/TableSchema.php <ide> class TableSchema implements TableSchemaInterface, SqlGeneratorInterface <ide> * Constructor. <ide> * <ide> * @param string $table The table name. <del> * @param array $columns The list of columns for the schema. <add> * @param array<string, array|string> $columns The list of columns for the schema. <ide> */ <ide> public function __construct(string $table, array $columns = []) <ide> { <ide> public function hasAutoincrement(): bool <ide> /** <ide> * Helper method to check/validate foreign keys. <ide> * <del> * @param array $attrs Attributes to set. <del> * @return array <add> * @param array<string, mixed> $attrs Attributes to set. <add> * @return array<string, mixed> <ide> * @throws \Cake\Database\Exception\DatabaseException When foreign key definition is not valid. <ide> */ <ide> protected function _checkForeignKey(array $attrs): array <ide> public function getConstraint(string $name): ?array <ide> */ <ide> public function setOptions(array $options) <ide> { <del> $this->_options = array_merge($this->_options, $options); <add> $this->_options = $options + $this->_options; <ide> <ide> return $this; <ide> } <ide><path>src/Database/Schema/TableSchemaInterface.php <ide> public function isTemporary(): bool; <ide> /** <ide> * Get the column(s) used for the primary key. <ide> * <del> * @return array Column name(s) for the primary key. An <add> * @return array<string> Column name(s) for the primary key. An <ide> * empty list will be returned when the table has no primary key. <ide> */ <ide> public function getPrimaryKey(): array; <ide> public function getPrimaryKey(): array; <ide> * - `columns` The columns in the index. <ide> * <ide> * @param string $name The name of the index. <del> * @param array|string $attrs The attributes for the index. <add> * @param array<string, mixed>|string $attrs The attributes for the index. <ide> * If string it will be used as `type`. <ide> * @return $this <ide> * @throws \Cake\Database\Exception\DatabaseException <ide> public function addIndex(string $name, $attrs); <ide> * Read information about an index based on name. <ide> * <ide> * @param string $name The name of the index. <del> * @return array|null Array of index data, or null <add> * @return array<string, mixed>|null Array of index data, or null <ide> */ <ide> public function getIndex(string $name): ?array; <ide> <ide> public function indexes(): array; <ide> * The default for 'update' & 'delete' is 'cascade'. <ide> * <ide> * @param string $name The name of the constraint. <del> * @param array|string $attrs The attributes for the constraint. <add> * @param array<string, mixed>|string $attrs The attributes for the constraint. <ide> * If string it will be used as `type`. <ide> * @return $this <ide> * @throws \Cake\Database\Exception\DatabaseException <ide> public function addConstraint(string $name, $attrs); <ide> * Read information about a constraint based on name. <ide> * <ide> * @param string $name The name of the constraint. <del> * @return array|null Array of constraint data, or null <add> * @return array<string, mixed>|null Array of constraint data, or null <ide> */ <ide> public function getConstraint(string $name): ?array; <ide> <ide><path>src/Database/Type/ColumnSchemaAwareInterface.php <ide> public function getColumnSql(TableSchemaInterface $schema, string $column, Drive <ide> * <ide> * @param array $definition The column definition. <ide> * @param \Cake\Database\DriverInterface $driver The driver instance being used. <del> * @return array|null Array of column information, or `null` in case the column isn't processed by this type. <add> * @return array<string, mixed>|null Array of column information, or `null` in case the column isn't processed by this type. <ide> */ <ide> public function convertColumnDefinition(array $definition, DriverInterface $driver): ?array; <ide> } <ide><path>src/Datasource/ConnectionManager.php <ide> class ConnectionManager <ide> * The connection will not be constructed until it is first used. <ide> * <ide> * @param array|string $key The name of the connection config, or an array of multiple configs. <del> * @param array|null $config An array of name => config data for adapter. <add> * @param array<string,mixed>|null $config An array of name => config data for adapter. <ide> * @return void <ide> * @throws \Cake\Core\Exception\CakeException When trying to modify an existing config. <ide> * @see \Cake\Core\StaticConfigTrait::config() <ide><path>src/Datasource/Paginator.php <ide> public function paginate(object $object, array $params = [], array $settings = [ <ide> * <ide> * @param \Cake\Datasource\RepositoryInterface $object Repository instance. <ide> * @param \Cake\Datasource\QueryInterface|null $query Query Instance. <del> * @param array $data Pagination data. <add> * @param array<string, mixed> $data Pagination data. <ide> * @return \Cake\Datasource\QueryInterface <ide> */ <ide> protected function getQuery(RepositoryInterface $object, ?QueryInterface $query, array $data): QueryInterface <ide> protected function getCount(QueryInterface $query, array $data): ?int <ide> * Extract pagination data needed <ide> * <ide> * @param \Cake\Datasource\RepositoryInterface $object The repository object. <del> * @param array $params Request params <del> * @param array $settings The settings/configuration used for pagination. <add> * @param array<string, mixed> $params Request params <add> * @param array<string, mixed> $settings The settings/configuration used for pagination. <ide> * @return array Array with keys 'defaults', 'options' and 'finder' <ide> */ <ide> protected function extractData(RepositoryInterface $object, array $params, array $settings): array <ide><path>src/Datasource/SchemaInterface.php <ide> public function name(): string; <ide> * - `comment` The comment for the column. <ide> * <ide> * @param string $name The name of the column <del> * @param array|string $attrs The attributes for the column or the type name. <add> * @param array<string, mixed>|string $attrs The attributes for the column or the type name. <ide> * @return $this <ide> */ <ide> public function addColumn(string $name, $attrs); <ide> public function addColumn(string $name, $attrs); <ide> * Get column data in the table. <ide> * <ide> * @param string $name The column name. <del> * @return array|null Column data or null. <add> * @return array<string, mixed>|null Column data or null. <ide> */ <ide> public function getColumn(string $name): ?array; <ide> <ide> public function isNullable(string $name): bool; <ide> * Returns an array where the keys are the column names in the schema <ide> * and the values the database type they have. <ide> * <del> * @return array <add> * @return array<string, string> <ide> */ <ide> public function typeMap(): array; <ide> <ide> /** <ide> * Get a hash of columns and their default values. <ide> * <del> * @return array <add> * @return array<string, mixed> <ide> */ <ide> public function defaultValues(): array; <ide> <ide> public function setOptions(array $options); <ide> * Table options allow you to set platform specific table level options. <ide> * For example the engine type in MySQL. <ide> * <del> * @return array An array of options. <add> * @return array<string, mixed> An array of options. <ide> */ <ide> public function getOptions(): array; <ide> } <ide><path>src/Form/FormProtector.php <ide> class FormProtector <ide> */ <ide> protected $debugMessage; <ide> <del> /** <del> * Construct. <del> * <del> * @param array $data Data array, can contain key `unlockedFields` with list of unlocked fields. <del> */ <del> public function __construct(array $data = []) <del> { <del> if (!empty($data['unlockedFields'])) { <del> $this->unlockedFields = $data['unlockedFields']; <del> } <del> } <del> <ide> /** <ide> * Validate submitted form data. <ide> * <ide> public function validate($formData, string $url, string $sessionId): bool <ide> return false; <ide> } <ide> <add> /** <add> * Construct. <add> * <add> * @param array<string, mixed> $data Data array, can contain key `unlockedFields` with list of unlocked fields. <add> */ <add> public function __construct(array $data = []) <add> { <add> if (!empty($data['unlockedFields'])) { <add> $this->unlockedFields = $data['unlockedFields']; <add> } <add> } <add> <ide> /** <ide> * Determine which fields of a form should be used for hash. <ide> * <ide><path>src/Form/Schema.php <ide> class Schema <ide> /** <ide> * The fields in this schema. <ide> * <del> * @var array<string, array> <add> * @var array<string, array<string, mixed>> <ide> */ <ide> protected $_fields = []; <ide> <ide> class Schema <ide> /** <ide> * Add multiple fields to the schema. <ide> * <del> * @param array $fields The fields to add. <add> * @param array<string, array<string, mixed>|string> $fields The fields to add. <ide> * @return $this <ide> */ <ide> public function addFields(array $fields) <ide> public function addFields(array $fields) <ide> * Adds a field to the schema. <ide> * <ide> * @param string $name The field name. <del> * @param array|string $attrs The attributes for the field, or the type <add> * @param array<string, mixed>|string $attrs The attributes for the field, or the type <ide> * as a string. <ide> * @return $this <ide> */ <ide> public function fields(): array <ide> * Get the attributes for a given field. <ide> * <ide> * @param string $name The field name. <del> * @return array|null The attributes for a field, or null. <add> * @return array<string, mixed>|null The attributes for a field, or null. <ide> */ <ide> public function field(string $name): ?array <ide> { <ide><path>src/Mailer/Message.php <ide> class Message implements JsonSerializable, Serializable <ide> /** <ide> * Constructor <ide> * <del> * @param array|null $config Array of configs, or string to load configs from app.php <add> * @param array<string,mixed>|null $config Array of configs, or string to load configs from app.php <ide> */ <ide> public function __construct(?array $config = null) <ide> { <ide> public function setConfig(array $config) <ide> /** <ide> * Set message body. <ide> * <del> * @param array $content Content array with keys "text" and/or "html" with <add> * @param array<string, string> $content Content array with keys "text" and/or "html" with <ide> * content string of respective type. <ide> * @return $this <ide> */ <ide><path>src/ORM/Association.php <ide> public function find($type = null, array $options = []): Query <ide> * Proxies the operation to the target table's exists method after <ide> * appending the default conditions for this association <ide> * <del> * @param \Cake\Database\ExpressionInterface|\Closure|array $conditions The conditions to use <add> * @param \Cake\Database\ExpressionInterface|\Closure|array|string|null $conditions The conditions to use <ide> * for checking if any record matches. <ide> * @see \Cake\ORM\Table::exists() <ide> * @return bool <ide> public function exists($conditions): bool <ide> * Proxies the update operation to the target table's updateAll method <ide> * <ide> * @param array $fields A hash of field => new value. <del> * @param mixed $conditions Conditions to be used, accepts anything Query::where() <add> * @param \Cake\Database\ExpressionInterface|\Closure|array|string|null $conditions Conditions to be used, accepts anything Query::where() <ide> * can take. <ide> * @see \Cake\ORM\Table::updateAll() <ide> * @return int Count Returns the affected rows. <ide> public function updateAll(array $fields, $conditions): int <ide> /** <ide> * Proxies the delete operation to the target table's deleteAll method <ide> * <del> * @param mixed $conditions Conditions to be used, accepts anything Query::where() <add> * @param \Cake\Database\ExpressionInterface|\Closure|array|string|null $conditions Conditions to be used, accepts anything Query::where() <ide> * can take. <ide> * @return int Returns the number of affected rows. <ide> * @see \Cake\ORM\Table::deleteAll() <ide><path>src/ORM/AssociationCollection.php <ide> protected function _saveAssociations( <ide> * <ide> * @param \Cake\ORM\Association $association The association object to save with. <ide> * @param \Cake\Datasource\EntityInterface $entity The entity to save <del> * @param array $nested Options for deeper associations <add> * @param array<string, mixed> $nested Options for deeper associations <ide> * @param array<string, mixed> $options Original options <ide> * @return bool Success <ide> */ <ide><path>src/ORM/EagerLoader.php <ide> class EagerLoader <ide> * Nested array describing the association to be fetched <ide> * and the options to apply for each of them, if any <ide> * <del> * @var array <add> * @var array<string, mixed> <ide> */ <ide> protected $_containments = []; <ide> <ide> protected function _collectKeys(array $external, Query $query, $statement): arra <ide> * defined in $collectKeys <ide> * <ide> * @param \Cake\Database\Statement\BufferedStatement $statement The statement to read from. <del> * @param array $collectKeys The keys to collect <add> * @param array<string, array> $collectKeys The keys to collect <ide> * @return array <ide> */ <ide> protected function _groupKeys(BufferedStatement $statement, array $collectKeys): array <ide><path>src/ORM/Entity.php <ide> class Entity implements EntityInterface, InvalidPropertyInterface <ide> * $entity = new Entity(['id' => 1, 'name' => 'Andrew']) <ide> * ``` <ide> * <del> * @param array $properties hash of properties to set in this entity <add> * @param array<string, mixed> $properties hash of properties to set in this entity <ide> * @param array<string, mixed> $options list of options to use when creating this entity <ide> */ <ide> public function __construct(array $properties = [], array $options = []) <ide><path>src/ORM/Query.php <ide> public function clearContain() <ide> * @param \Cake\ORM\Table $table The table instance to pluck associations from. <ide> * @param \Cake\Database\TypeMap $typeMap The typemap to check for columns in. <ide> * This typemap is indirectly mutated via Cake\ORM\Query::addDefaultTypes() <del> * @param array $associations The nested tree of associations to walk. <add> * @param array<string, array> $associations The nested tree of associations to walk. <ide> * @return void <ide> */ <ide> protected function _addAssociationsToTypeMap(Table $table, TypeMap $typeMap, array $associations): void <ide> public function delete(?string $table = null) <ide> * Can be combined with the where() method to create delete queries. <ide> * <ide> * @param array $columns The columns to insert into. <del> * @param array $types A map between columns & their datatypes. <add> * @param array<string, string> $types A map between columns & their datatypes. <ide> * @return $this <ide> */ <ide> public function insert(array $columns, array $types = []) <ide><path>src/TestSuite/TestCase.php <ide> public function assertHtml(array $expected, string $string, bool $fullDebug = fa <ide> ]; <ide> } <ide> } <add> /** <add> * @var array<string, mixed> $assertion <add> */ <ide> foreach ($regex as $i => $assertion) { <ide> $matches = false; <ide> if (isset($assertion['attrs'])) { <ide> public function assertHtml(array $expected, string $string, bool $fullDebug = fa <ide> /** <ide> * Check the attributes as part of an assertTags() check. <ide> * <del> * @param array $assertions Assertions to run. <add> * @param array<string, mixed> $assertions Assertions to run. <ide> * @param string $string The HTML string to check. <ide> * @param bool $fullDebug Whether more verbose output should be used. <ide> * @param array|string $regex Full regexp from `assertHtml` <ide><path>src/Validation/Validation.php <ide> public static function iban($check): bool <ide> * The arrays are typically sent for validation from a form generated by <ide> * the CakePHP FormHelper. <ide> * <del> * @param array $value The array representing a date or datetime. <add> * @param array<string, mixed> $value The array representing a date or datetime. <ide> * @return string <ide> */ <ide> protected static function _getDateString(array $value): string <ide><path>src/Validation/ValidationRule.php <ide> public function isLast(): bool <ide> * it is assumed that the rule failed and the error message was given as a result. <ide> * <ide> * @param mixed $value The data to validate <del> * @param array $providers associative array with objects or class names that will <add> * @param array<string, mixed> $providers Associative array with objects or class names that will <ide> * be passed as the last argument for the validation method <ide> * @param array $context A key value list of data that could be used as context <ide> * during validation. Recognized keys are: <ide><path>src/Validation/Validator.php <ide> class Validator implements ArrayAccess, IteratorAggregate, Countable <ide> * An associative array of objects or classes containing methods <ide> * used for validation <ide> * <del> * @var array <add> * @var array<string, object|string> <add> * @psalm-var array<string, object|class-string> <ide> */ <ide> protected $_providers = []; <ide> <ide> /** <ide> * An associative array of objects or classes used as a default provider list <ide> * <del> * @var array <add> * @var array<string, object|string> <add> * @psalm-var array<string, object|class-string> <ide> */ <ide> protected static $_defaultProviders = []; <ide> <ide><path>src/View/Helper/FormHelper.php <ide> protected function _csrfField(): string <ide> * <ide> * Resets some parts of the state, shared among multiple FormHelper::create() calls, to defaults. <ide> * <del> * @param array $secureAttributes Secure attributes which will be passed as HTML attributes <add> * @param array<string, mixed> $secureAttributes Secure attributes which will be passed as HTML attributes <ide> * into the hidden input elements generated for the Security Component. <ide> * @return string A closing FORM tag. <ide> * @link https://book.cakephp.org/4/en/views/helpers/form.html#closing-the-form <ide> public function end(array $secureAttributes = []): string <ide> * <ide> * @param array $fields If set specifies the list of fields to be added to <ide> * FormProtector for generating the hash. <del> * @param array $secureAttributes will be passed as HTML attributes into the hidden <add> * @param array<string, mixed> $secureAttributes will be passed as HTML attributes into the hidden <ide> * input elements generated for the Security Component. <ide> * @return string A hidden input field with a security hash, or empty string when <ide> * secured forms are not in use. <ide> public function unlockField(string $name) <ide> /** <ide> * Create FormProtector instance. <ide> * <del> * @param array $formTokenData Token data. <add> * @param array<string, mixed> $formTokenData Token data. <ide> * @return \Cake\Form\FormProtector <ide> */ <ide> protected function createFormProtector(array $formTokenData): FormProtector <ide> public function checkbox(string $fieldName, array $options = []) <ide> * <ide> * @param string $fieldName Name of a field, like this "modelname.fieldname" <ide> * @param iterable $options Radio button options array. <del> * @param array $attributes Array of attributes. <add> * @param array<string, mixed> $attributes Array of attributes. <ide> * @return string Completed radio widget set. <ide> * @link https://book.cakephp.org/4/en/views/helpers/form.html#creating-radio-buttons <ide> */ <ide> public function submit(?string $caption = null, array $options = []): string <ide> * @param string $fieldName Name attribute of the SELECT <ide> * @param iterable $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the <ide> * SELECT element <del> * @param array $attributes The HTML attributes of the select element. <add> * @param array<string, mixed> $attributes The HTML attributes of the select element. <ide> * @return string Formatted SELECT element <ide> * @see \Cake\View\Helper\FormHelper::multiCheckbox() for creating multiple checkboxes. <ide> * @link https://book.cakephp.org/4/en/views/helpers/form.html#creating-select-pickers <ide> public function select(string $fieldName, iterable $options = [], array $attribu <ide> * @param string $fieldName Name attribute of the SELECT <ide> * @param iterable $options Array of the OPTION elements <ide> * (as 'value'=>'Text' pairs) to be used in the checkboxes element. <del> * @param array $attributes The HTML attributes of the select element. <add> * @param array<string, mixed> $attributes The HTML attributes of the select element. <ide> * @return string Formatted SELECT element <ide> * @see \Cake\View\Helper\FormHelper::select() for supported option formats. <ide> */ <ide><path>src/View/Helper/HtmlHelper.php <ide> public function image($path, array $options = []): string <ide> * <ide> * @param array $names Array of tablenames. Each tablename can be string, or array with name and an array with a set <ide> * of attributes to its specific tag <del> * @param array|null $trOptions HTML options for TR elements. <del> * @param array|null $thOptions HTML options for TH elements. <add> * @param array<string, mixed>|null $trOptions HTML options for TR elements. <add> * @param array<string, mixed>|null $thOptions HTML options for TH elements. <ide> * @return string Completed table headers <ide> * @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-table-headings <ide> */ <ide> public function media($path, array $options = []): string <ide> * <ide> * @param array $list Set of elements to list <ide> * @param array<string, mixed> $options Options and additional HTML attributes of the list (ol/ul) tag. <del> * @param array $itemOptions Options and additional HTML attributes of the list item (LI) tag. <add> * @param array<string, mixed> $itemOptions Options and additional HTML attributes of the list item (LI) tag. <ide> * @return string The nested list <ide> * @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-nested-lists <ide> */ <ide> public function nestedList(array $list, array $options = [], array $itemOptions <ide> * <ide> * @param array $items Set of elements to list. <ide> * @param array<string, mixed> $options Additional HTML attributes of the list (ol/ul) tag. <del> * @param array $itemOptions Options and additional HTML attributes of the list item (LI) tag. <add> * @param array<string, mixed> $itemOptions Options and additional HTML attributes of the list item (LI) tag. <ide> * @return string The nested list element <ide> * @see \Cake\View\Helper\HtmlHelper::nestedList() <ide> */ <ide><path>src/View/Helper/PaginatorHelper.php <ide> protected function _formatNumber(StringTemplate $templater, array $options): str <ide> * Generates the numbers for the paginator numbers() method. <ide> * <ide> * @param \Cake\View\StringTemplate $templater StringTemplate instance. <del> * @param array $params Params from the numbers() method. <add> * @param array<string, mixed> $params Params from the numbers() method. <ide> * @param array<string, mixed> $options Options from the numbers() method. <ide> * @return string Markup output. <ide> */ <ide> protected function _modulusNumbers(StringTemplate $templater, array $params, arr <ide> * Generates the first number for the paginator numbers() method. <ide> * <ide> * @param string $ellipsis Ellipsis character. <del> * @param array $params Params from the numbers() method. <add> * @param array<string, mixed> $params Params from the numbers() method. <ide> * @param int $start Start number. <ide> * @param array<string, mixed> $options Options from the numbers() method. <ide> * @return string Markup output. <ide> protected function _firstNumber(string $ellipsis, array $params, int $start, arr <ide> * Generates the last number for the paginator numbers() method. <ide> * <ide> * @param string $ellipsis Ellipsis character. <del> * @param array $params Params from the numbers() method. <add> * @param array<string, mixed> $params Params from the numbers() method. <ide> * @param int $end End number. <ide> * @param array<string, mixed> $options Options from the numbers() method. <ide> * @return string Markup output. <ide> protected function _lastNumber(string $ellipsis, array $params, int $end, array <ide> * Generates the numbers for the paginator numbers() method. <ide> * <ide> * @param \Cake\View\StringTemplate $templater StringTemplate instance. <del> * @param array $params Params from the numbers() method. <add> * @param array<string, mixed> $params Params from the numbers() method. <ide> * @param array<string, mixed> $options Options from the numbers() method. <ide> * @return string Markup output. <ide> */ <ide><path>src/View/Helper/TextHelper.php <ide> protected function _insertPlaceHolder(array $matches): string <ide> * Replace placeholders with links. <ide> * <ide> * @param string $text The text to operate on. <del> * @param array $htmlOptions The options for the generated links. <add> * @param array<string, mixed> $htmlOptions The options for the generated links. <ide> * @return string The text with links inserted. <ide> */ <ide> protected function _linkUrls(string $text, array $htmlOptions): string
31
Javascript
Javascript
add test case
a45140d600e2c406e2a3baa446d6253d9f9f8357
<ide><path>test/HotTestCases.template.js <ide> const describeCases = config => { <ide> category.tests.forEach(testName => { <ide> const testDirectory = path.join(casesPath, category.name, testName); <ide> const filterPath = path.join(testDirectory, "test.filter.js"); <del> if (fs.existsSync(filterPath) && !require(filterPath)()) { <add> if (fs.existsSync(filterPath) && !require(filterPath)(config)) { <ide> describe.skip(testName, () => { <ide> it("filtered", () => {}); <ide> }); <ide><path>test/hotCases/update.js <del>module.exports = function(done, options, callback) { <del> return function(err, stats) { <add>module.exports = function (done, options, callback) { <add> return function (err, stats) { <ide> if (err) return done(err); <del> module.hot.check(options || true).then(() => { <del> if (callback) <del> callback(stats); <del> }).catch((err) => { <del> done(err); <del> }); <del> } <add> module.hot <add> .check(options || true) <add> .then(updatedModules => { <add> if (!updatedModules) return done(new Error("No update available")); <add> if (callback) callback(stats); <add> }) <add> .catch(err => { <add> done(err); <add> }); <add> }; <ide> }; <ide><path>test/hotCases/worker/remove-add-worker/compute.js <add>export default () => Promise.resolve(42); <add>--- <add>export default async () => { <add> const worker = new Worker(new URL("worker.js", import.meta.url)); <add> const result = await new Promise((resolve, reject) => { <add> worker.onmessage = ({ data }) => { <add> if(typeof data === "string") { <add> reject(new Error(data)); <add> } else { <add> resolve(data); <add> } <add> }; <add> worker.postMessage("compute"); <add> }); <add> await worker.terminate(); <add> return result; <add>} <add>--- <add>export default () => Promise.resolve(42); <add>--- <add>export default async () => { <add> const worker = new Worker(new URL("worker.js", import.meta.url)); <add> const result = await new Promise((resolve, reject) => { <add> worker.onmessage = ({ data }) => { <add> if(typeof data === "string") { <add> reject(new Error(data)); <add> } else { <add> resolve(data); <add> } <add> }; <add> worker.postMessage("compute"); <add> }); <add> await worker.terminate(); <add> return result; <add>} <add>--- <add>if(Math.random() < 0) { <add> new Worker(new URL("worker.js?1", import.meta.url)); <add>} <add>export default async () => { <add> const worker = new Worker(new URL("worker.js", import.meta.url)); <add> const result = await new Promise((resolve, reject) => { <add> worker.onmessage = ({ data }) => { <add> if(typeof data === "string") { <add> reject(new Error(data)); <add> } else { <add> resolve(data); <add> } <add> }; <add> worker.postMessage("compute"); <add> }); <add> await worker.terminate(); <add> return result; <add>} <add>--- <add>export default async () => { <add> const worker = new Worker(new URL("worker.js", import.meta.url)); <add> const result = await new Promise((resolve, reject) => { <add> worker.onmessage = ({ data }) => { <add> if(typeof data === "string") { <add> reject(new Error(data)); <add> } else { <add> resolve(data); <add> } <add> }; <add> worker.postMessage("compute"); <add> }); <add> await worker.terminate(); <add> return result; <add>} <ide><path>test/hotCases/worker/remove-add-worker/index.js <add>import compute from "./compute"; <add> <add>const update = () => <add> new Promise((resolve, reject) => { <add> NEXT(require("../../update")(reject, true, resolve)); <add> }); <add> <add>it("should support adding and removing runtimes", async () => { <add> expect(await compute()).toBe(42); <add> await update(); <add> expect(await compute()).toBe(42); <add> await update(); <add> expect(await compute()).toBe(42); <add> await update(); <add> expect(await compute()).toBe(42); <add> await update(); <add> expect(await compute()).toBe(42); <add> await update(); <add> expect(await compute()).toBe(42); <add>}); <add> <add>import.meta.webpackHot.accept("./compute"); <ide><path>test/hotCases/worker/remove-add-worker/test.filter.js <add>var supportsWorker = require("../../../helpers/supportsWorker"); <add> <add>module.exports = function (config) { <add> return supportsWorker() && config.target !== "async-node"; <add>}; <ide><path>test/hotCases/worker/remove-add-worker/worker.js <add>self.onmessage = async ({ data }) => { <add> try { <add> if (data !== "compute") throw new Error("expected compute message"); <add> self.postMessage(42); <add> } catch (e) { <add> self.postMessage("error: " + e.stack); <add> } <add>};
6
Python
Python
remove some tpu_lib not used at all
58df0dc6e1e287770bc53c6985021914d5fa422a
<ide><path>official/modeling/model_training_utils.py <ide> from absl import logging <ide> import tensorflow as tf <ide> from official.utils.misc import distribution_utils <del>from official.utils.misc import tpu_lib <ide> <ide> _SUMMARY_TXT = 'training_summary.txt' <ide> _MIN_SUMMARY_STEPS = 10 <ide><path>official/modeling/training/distributed_executor.py <ide> # pylint: disable=unused-import,g-import-not-at-top,redefined-outer-name,reimported <ide> from typing import Optional, Dict, List, Text, Callable, Union, Iterator, Any <ide> from official.modeling.hyperparams import params_dict <del>from official.utils.misc import tpu_lib <ide> from official.utils.misc import distribution_utils <ide> from official.utils import hyperparams_flags <ide>
2
Python
Python
replace double occurrences as the last step
0cbddfb190ab9b05b6575fbf818aae17bad4d24a
<ide><path>src/transformers/convert_slow_tokenizer.py <ide> def normalizer(self, proto): <ide> list_normalizers = [ <ide> normalizers.Replace("``", '"'), <ide> normalizers.Replace("''", '"'), <del> normalizers.Replace(Regex(" {2,}"), " "), <ide> ] <ide> if not self.original_tokenizer.keep_accents: <ide> list_normalizers.append(normalizers.NFKD()) <ide> def normalizer(self, proto): <ide> <ide> precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap <ide> list_normalizers.append(normalizers.Precompiled(precompiled_charsmap)) <add> list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " ")) <ide> return normalizers.Sequence(list_normalizers) <ide> <ide> def post_processor(self): <ide> def normalizer(self, proto): <ide> list_normalizers = [ <ide> normalizers.Replace("``", '"'), <ide> normalizers.Replace("''", '"'), <del> normalizers.Replace(Regex(" {2,}"), " "), <ide> ] <ide> if not self.original_tokenizer.keep_accents: <ide> list_normalizers.append(normalizers.NFKD()) <ide> def normalizer(self, proto): <ide> <ide> precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap <ide> list_normalizers.append(normalizers.Precompiled(precompiled_charsmap)) <add> list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " ")) <ide> return normalizers.Sequence(list_normalizers) <ide> <ide> def post_processor(self):
1
Java
Java
fix checkstyle violation
f1af8a6ae956f2523cb7f2f63710164babac6ddf
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java <ide> <ide> package org.springframework.web.servlet.mvc.method.annotation; <ide> <del>import java.awt.*; <add>import java.awt.Color; <ide> import java.lang.annotation.Documented; <ide> import java.lang.annotation.ElementType; <ide> import java.lang.annotation.Retention;
1
Java
Java
support @requestbody flux<part> in webflux
b5089ac09208daa12b19b06924eff95b670eb764
<ide><path>spring-web/src/main/java/org/springframework/http/codec/DefaultServerCodecConfigurer.java <ide> import org.springframework.core.codec.Encoder; <ide> import org.springframework.core.codec.StringDecoder; <ide> import org.springframework.http.codec.json.Jackson2JsonEncoder; <del>import org.springframework.http.codec.multipart.SynchronossMultipartHttpMessageReader; <add>import org.springframework.http.codec.multipart.MultipartHttpMessageReader; <add>import org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader; <ide> import org.springframework.util.ClassUtils; <ide> <ide> /** <ide> public void addTypedReadersTo(List<HttpMessageReader<?>> result) { <ide> super.addTypedReadersTo(result); <ide> addReaderTo(result, FormHttpMessageReader::new); <ide> if (synchronossMultipartPresent) { <del> addReaderTo(result, SynchronossMultipartHttpMessageReader::new); <add> SynchronossPartHttpMessageReader partReader = new SynchronossPartHttpMessageReader(); <add> addReaderTo(result, () -> partReader); <add> addReaderTo(result, () -> new MultipartHttpMessageReader(partReader)); <ide> } <ide> } <ide> <ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageReader.java <add>/* <add> * Copyright 2002-2017 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.http.codec.multipart; <add> <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.Collections; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.stream.Collectors; <add> <add>import reactor.core.publisher.Flux; <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.core.ResolvableType; <add>import org.springframework.http.MediaType; <add>import org.springframework.http.ReactiveHttpInputMessage; <add>import org.springframework.http.codec.HttpMessageReader; <add>import org.springframework.util.Assert; <add>import org.springframework.util.LinkedMultiValueMap; <add>import org.springframework.util.MultiValueMap; <add> <add>/** <add> * {@code HttpMessageReader} for reading {@code "multipart/form-data"} requests <add> * into a {@code MultiValueMap<String, Part>}. <add> * <add> * <p>Note that this reader depends on access to an <add> * {@code HttpMessageReader<Part>} for the actual parsing of multipart content. <add> * The purpose of this reader is to collect the parts into a map. <add> * <add> * @author Rossen Stoyanchev <add> * @since 5.0 <add> */ <add>public class MultipartHttpMessageReader implements HttpMessageReader<MultiValueMap<String, Part>> { <add> <add> private static final ResolvableType MULTIPART_VALUE_TYPE = ResolvableType.forClassWithGenerics( <add> MultiValueMap.class, String.class, Part.class); <add> <add> <add> private final HttpMessageReader<Part> partReader; <add> <add> <add> public MultipartHttpMessageReader(HttpMessageReader<Part> partReader) { <add> Assert.notNull(partReader, "'partReader' is required"); <add> this.partReader = partReader; <add> } <add> <add> <add> @Override <add> public List<MediaType> getReadableMediaTypes() { <add> return Collections.singletonList(MediaType.MULTIPART_FORM_DATA); <add> } <add> <add> @Override <add> public boolean canRead(ResolvableType elementType, MediaType mediaType) { <add> return MULTIPART_VALUE_TYPE.isAssignableFrom(elementType) && <add> (mediaType == null || MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType)); <add> } <add> <add> <add> @Override <add> public Flux<MultiValueMap<String, Part>> read(ResolvableType elementType, <add> ReactiveHttpInputMessage message, Map<String, Object> hints) { <add> <add> return Flux.from(readMono(elementType, message, hints)); <add> } <add> <add> <add> @Override <add> public Mono<MultiValueMap<String, Part>> readMono(ResolvableType elementType, <add> ReactiveHttpInputMessage inputMessage, Map<String, Object> hints) { <add> <add> return this.partReader.read(elementType, inputMessage, hints) <add> .collectMultimap(Part::getName).map(this::toMultiValueMap); <add> } <add> <add> private LinkedMultiValueMap<String, Part> toMultiValueMap(Map<String, Collection<Part>> map) { <add> return new LinkedMultiValueMap<>(map.entrySet().stream() <add> .collect(Collectors.toMap(Map.Entry::getKey, e -> toList(e.getValue())))); <add> } <add> <add> private List<Part> toList(Collection<Part> collection) { <add> return collection instanceof List ? (List<Part>) collection : new ArrayList<>(collection); <add> } <add> <add>} <add><path>spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java <del><path>spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossMultipartHttpMessageReader.java <ide> import java.nio.channels.ReadableByteChannel; <ide> import java.nio.charset.Charset; <ide> import java.nio.charset.StandardCharsets; <del>import java.util.ArrayList; <del>import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Optional; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> import java.util.function.Consumer; <del>import java.util.stream.Collectors; <ide> <ide> import org.synchronoss.cloud.nio.multipart.Multipart; <ide> import org.synchronoss.cloud.nio.multipart.MultipartContext; <ide> import org.springframework.http.ReactiveHttpInputMessage; <ide> import org.springframework.http.codec.HttpMessageReader; <ide> import org.springframework.util.Assert; <del>import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MimeType; <del>import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.StreamUtils; <ide> <ide> /** <del> * {@code HttpMessageReader} for {@code "multipart/form-data"} requests based <del> * on the Synchronoss NIO Multipart library. <add> * {@code HttpMessageReader} for parsing {@code "multipart/form-data"} requests <add> * to a stream of {@link Part}'s using the Synchronoss NIO Multipart library. <add> * <add> * <p>This reader can be provided to {@link MultipartHttpMessageReader} in order <add> * to aggregate all parts into a Map. <ide> * <ide> * @author Sebastien Deleuze <ide> * @author Rossen Stoyanchev <ide> * @author Arjen Poutsma <ide> * @since 5.0 <ide> * @see <a href="https://github.com/synchronoss/nio-multipart">Synchronoss NIO Multipart</a> <add> * @see MultipartHttpMessageReader <ide> */ <del>public class SynchronossMultipartHttpMessageReader implements HttpMessageReader<MultiValueMap<String, Part>> { <del> <del> private static final ResolvableType MULTIPART_VALUE_TYPE = ResolvableType.forClassWithGenerics( <del> MultiValueMap.class, String.class, Part.class); <add>public class SynchronossPartHttpMessageReader implements HttpMessageReader<Part> { <ide> <ide> <ide> @Override <ide> public List<MediaType> getReadableMediaTypes() { <ide> <ide> @Override <ide> public boolean canRead(ResolvableType elementType, MediaType mediaType) { <del> return MULTIPART_VALUE_TYPE.isAssignableFrom(elementType) && <add> return Part.class.equals(elementType.resolve(Object.class)) && <ide> (mediaType == null || MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType)); <ide> } <ide> <ide> <ide> @Override <del> public Flux<MultiValueMap<String, Part>> read(ResolvableType elementType, <del> ReactiveHttpInputMessage message, Map<String, Object> hints) { <add> public Flux<Part> read(ResolvableType elementType, ReactiveHttpInputMessage message, <add> Map<String, Object> hints) { <ide> <del> return Flux.from(readMono(elementType, message, hints)); <add> return Flux.create(new SynchronossPartGenerator(message)); <ide> } <ide> <ide> <ide> @Override <del> public Mono<MultiValueMap<String, Part>> readMono(ResolvableType elementType, <del> ReactiveHttpInputMessage inputMessage, Map<String, Object> hints) { <del> <del> return Flux.create(new SynchronossPartGenerator(inputMessage)) <del> .collectMultimap(Part::getName).map(this::toMultiValueMap); <del> } <del> <del> private LinkedMultiValueMap<String, Part> toMultiValueMap(Map<String, Collection<Part>> map) { <del> return new LinkedMultiValueMap<>(map.entrySet().stream() <del> .collect(Collectors.toMap(Map.Entry::getKey, e -> toList(e.getValue())))); <del> } <add> public Mono<Part> readMono(ResolvableType elementType, ReactiveHttpInputMessage message, <add> Map<String, Object> hints) { <ide> <del> private List<Part> toList(Collection<Part> collection) { <del> return collection instanceof List ? (List<Part>) collection : new ArrayList<>(collection); <add> return Mono.error(new UnsupportedOperationException( <add> "This reader does not support reading a single element.")); <ide> } <ide> <ide> <ide><path>spring-web/src/test/java/org/springframework/http/codec/ServerCodecConfigurerTests.java <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.codec.json.Jackson2JsonDecoder; <ide> import org.springframework.http.codec.json.Jackson2JsonEncoder; <del>import org.springframework.http.codec.multipart.SynchronossMultipartHttpMessageReader; <add>import org.springframework.http.codec.multipart.MultipartHttpMessageReader; <add>import org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader; <ide> import org.springframework.http.codec.xml.Jaxb2XmlDecoder; <ide> import org.springframework.http.codec.xml.Jaxb2XmlEncoder; <ide> import org.springframework.util.MimeTypeUtils; <ide> public class ServerCodecConfigurerTests { <ide> @Test <ide> public void defaultReaders() throws Exception { <ide> List<HttpMessageReader<?>> readers = this.configurer.getReaders(); <del> assertEquals(10, readers.size()); <add> assertEquals(11, readers.size()); <ide> assertEquals(ByteArrayDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(ByteBufferDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(DataBufferDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(ResourceDecoder.class, getNextDecoder(readers).getClass()); <ide> assertStringDecoder(getNextDecoder(readers), true); <ide> assertEquals(FormHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); <del> assertEquals(SynchronossMultipartHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); <add> assertEquals(SynchronossPartHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); <add> assertEquals(MultipartHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); <ide> assertEquals(Jaxb2XmlDecoder.class, getNextDecoder(readers).getClass()); <ide> assertEquals(Jackson2JsonDecoder.class, getNextDecoder(readers).getClass()); <ide> assertStringDecoder(getNextDecoder(readers), false); <ide><path>spring-web/src/test/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriterTests.java <ide> public String getFilename() { <ide> assertNotNull("No boundary found", contentType.getParameter("boundary")); <ide> <ide> // see if Synchronoss NIO Multipart can read what we wrote <del> SynchronossMultipartHttpMessageReader reader = new SynchronossMultipartHttpMessageReader(); <add> SynchronossPartHttpMessageReader synchronossReader = new SynchronossPartHttpMessageReader(); <add> MultipartHttpMessageReader reader = new MultipartHttpMessageReader(synchronossReader); <add> <ide> MockServerHttpRequest request = MockServerHttpRequest.post("/foo") <ide> .header(HttpHeaders.CONTENT_TYPE, contentType.toString()) <ide> .body(response.getBody()); <add><path>spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java <del><path>spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossMultipartHttpMessageReaderTests.java <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.MockHttpOutputMessage; <del>import org.springframework.http.codec.HttpMessageReader; <ide> import org.springframework.http.converter.FormHttpMessageConverter; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> <del>import static java.util.Collections.*; <del>import static org.junit.Assert.*; <del>import static org.springframework.http.HttpHeaders.*; <del>import static org.springframework.http.MediaType.*; <add>import static java.util.Collections.emptyMap; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertTrue; <add>import static org.springframework.core.ResolvableType.forClassWithGenerics; <add>import static org.springframework.http.HttpHeaders.CONTENT_LENGTH; <add>import static org.springframework.http.HttpHeaders.CONTENT_TYPE; <add>import static org.springframework.http.MediaType.MULTIPART_FORM_DATA; <ide> <ide> /** <ide> * @author Sebastien Deleuze <ide> */ <del>public class SynchronossMultipartHttpMessageReaderTests { <add>public class SynchronossPartHttpMessageReaderTests { <ide> <del> private final HttpMessageReader<MultiValueMap<String, Part>> reader = new SynchronossMultipartHttpMessageReader(); <add> private final MultipartHttpMessageReader reader = <add> new MultipartHttpMessageReader(new SynchronossPartHttpMessageReader()); <ide> <ide> <ide> @Test <ide> public void canRead() { <ide> assertTrue(this.reader.canRead( <del> ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Part.class), <add> forClassWithGenerics(MultiValueMap.class, String.class, Part.class), <ide> MediaType.MULTIPART_FORM_DATA)); <ide> <ide> assertFalse(this.reader.canRead( <del> ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Object.class), <add> forClassWithGenerics(MultiValueMap.class, String.class, Object.class), <ide> MediaType.MULTIPART_FORM_DATA)); <ide> <ide> assertFalse(this.reader.canRead( <del> ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class), <add> forClassWithGenerics(MultiValueMap.class, String.class, String.class), <ide> MediaType.MULTIPART_FORM_DATA)); <ide> <ide> assertFalse(this.reader.canRead( <del> ResolvableType.forClassWithGenerics(Map.class, String.class, String.class), <add> forClassWithGenerics(Map.class, String.class, String.class), <ide> MediaType.MULTIPART_FORM_DATA)); <ide> <ide> assertFalse(this.reader.canRead( <del> ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Part.class), <add> forClassWithGenerics(MultiValueMap.class, String.class, Part.class), <ide> MediaType.APPLICATION_FORM_URLENCODED)); <ide> } <ide> <ide> @Test <ide> public void resolveParts() throws IOException { <ide> ServerHttpRequest request = generateMultipartRequest(); <del> ResolvableType elementType = ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Part.class); <add> ResolvableType elementType = forClassWithGenerics(MultiValueMap.class, String.class, Part.class); <ide> MultiValueMap<String, Part> parts = this.reader.readMono(elementType, request, emptyMap()).block(); <ide> assertEquals(2, parts.size()); <ide> <ide> public void resolveParts() throws IOException { <ide> @Test <ide> public void bodyError() { <ide> ServerHttpRequest request = generateErrorMultipartRequest(); <del> ResolvableType elementType = ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Part.class); <add> ResolvableType elementType = forClassWithGenerics(MultiValueMap.class, String.class, Part.class); <ide> StepVerifier.create(this.reader.readMono(elementType, request, emptyMap())).verifyError(); <ide> } <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/config/DelegatingWebFluxConfigurationTests.java <ide> public void requestMappingHandlerAdapter() throws Exception { <ide> verify(webFluxConfigurer).configureArgumentResolvers(any()); <ide> <ide> assertSame(formatterRegistry.getValue(), initializerConversionService); <del> assertEquals(10, codecsConfigurer.getValue().getReaders().size()); <add> assertEquals(11, codecsConfigurer.getValue().getReaders().size()); <ide> } <ide> <ide> @Test <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/config/WebFluxConfigurationSupportTests.java <ide> public void requestMappingHandlerAdapter() throws Exception { <ide> assertNotNull(adapter); <ide> <ide> List<HttpMessageReader<?>> readers = adapter.getMessageCodecConfigurer().getReaders(); <del> assertEquals(10, readers.size()); <add> assertEquals(11, readers.size()); <ide> <ide> assertHasMessageReader(readers, forClass(byte[].class), APPLICATION_OCTET_STREAM); <ide> assertHasMessageReader(readers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM); <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartIntegrationTests.java <ide> <ide> package org.springframework.web.reactive.result.method.annotation; <ide> <add>import java.util.Map; <add>import java.util.stream.Collectors; <add> <ide> import org.junit.Before; <ide> import org.junit.Test; <add>import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> import reactor.test.StepVerifier; <ide> <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> import org.springframework.web.bind.annotation.PostMapping; <add>import org.springframework.web.bind.annotation.RequestBody; <ide> import org.springframework.web.bind.annotation.RequestPart; <ide> import org.springframework.web.bind.annotation.RestController; <ide> import org.springframework.web.reactive.DispatcherHandler; <ide> protected HttpHandler createHttpHandler() { <ide> } <ide> <ide> @Test <del> public void part() { <del> test("/part"); <del> } <del> <del> private void test(String uri) { <add> public void requestPart() { <ide> Mono<ClientResponse> result = webClient <ide> .post() <del> .uri(uri) <add> .uri("/requestPart") <ide> .contentType(MediaType.MULTIPART_FORM_DATA) <ide> .body(BodyInserters.fromMultipartData(generateBody())) <ide> .exchange(); <ide> private void test(String uri) { <ide> .verifyComplete(); <ide> } <ide> <add> @Test <add> public void requestBodyMap() { <add> Mono<String> result = webClient <add> .post() <add> .uri("/requestBodyMap") <add> .contentType(MediaType.MULTIPART_FORM_DATA) <add> .body(BodyInserters.fromMultipartData(generateBody())) <add> .retrieve() <add> .bodyToMono(String.class); <add> <add> StepVerifier.create(result) <add> .consumeNextWith(body -> assertEquals("Map[barPart,fooPart]", body)) <add> .verifyComplete(); <add> } <add> <add> @Test <add> public void requestBodyFlux() { <add> Mono<String> result = webClient <add> .post() <add> .uri("/requestBodyFlux") <add> .contentType(MediaType.MULTIPART_FORM_DATA) <add> .body(BodyInserters.fromMultipartData(generateBody())) <add> .retrieve() <add> .bodyToMono(String.class); <add> <add> StepVerifier.create(result) <add> .consumeNextWith(body -> assertEquals("Flux[barPart,fooPart]", body)) <add> .verifyComplete(); <add> } <add> <add> <ide> private MultiValueMap<String, Object> generateBody() { <ide> HttpHeaders fooHeaders = new HttpHeaders(); <ide> fooHeaders.setContentType(MediaType.TEXT_PLAIN); <ide> private MultiValueMap<String, Object> generateBody() { <ide> @SuppressWarnings("unused") <ide> static class MultipartController { <ide> <del> @PostMapping("/part") <add> @PostMapping("/requestPart") <ide> void part(@RequestPart Part fooPart) { <ide> assertEquals("foo.txt", fooPart.getFilename().get()); <ide> } <ide> <add> @PostMapping("/requestBodyMap") <add> Mono<String> part(@RequestBody Mono<MultiValueMap<String, Part>> parts) { <add> return parts.map(map -> map.toSingleValueMap().entrySet().stream() <add> .map(Map.Entry::getKey).sorted().collect(Collectors.joining(",", "Map[", "]"))); <add> } <add> <add> @PostMapping("/requestBodyFlux") <add> Mono<String> part(@RequestBody Flux<Part> parts) { <add> return parts.map(Part::getName).collectList() <add> .map(names -> names.stream().sorted().collect(Collectors.joining(",", "Flux[", "]"))); <add> } <ide> } <ide> <ide> @Configuration
9
Python
Python
add option to disable ansi background colours
ed83538ee13b1156dae73a7b06ff94be057a37b5
<ide><path>glances/main.py <ide> def init_args(self): <ide> dest='disable_log', help='disable log module') <ide> parser.add_argument('--disable-bold', action='store_false', default=True, <ide> dest='disable_bold', help='disable bold mode in the terminal') <add> parser.add_argument('--disable-bg', action='store_false', default=True, <add> dest='disable_bg', help='disable background colors in the terminal') <ide> parser.add_argument('--enable-process-extended', action='store_true', default=False, <ide> dest='enable_process_extended', help='enable extended stats on top process') <ide> parser.add_argument('--enable-history', action='store_true', default=False, <ide><path>glances/outputs/glances_curses.py <ide> def _init_colors(self): <ide> curses.init_pair(1, curses.COLOR_BLACK, -1) <ide> else: <ide> curses.init_pair(1, curses.COLOR_WHITE, -1) <del> curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) <del> curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN) <del> curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE) <del> curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA) <add> if args.disable_bg: <add> curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) <add> curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN) <add> curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE) <add> curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA) <add> else: <add> curses.init_pair(2, curses.COLOR_RED, -1) <add> curses.init_pair(3, curses.COLOR_GREEN, -1) <add> curses.init_pair(4, curses.COLOR_BLUE, -1) <add> curses.init_pair(5, curses.COLOR_MAGENTA, -1) <ide> curses.init_pair(6, curses.COLOR_RED, -1) <ide> curses.init_pair(7, curses.COLOR_GREEN, -1) <ide> curses.init_pair(8, curses.COLOR_BLUE, -1)
2
Text
Text
retire lead maintainer position in febuary
a9d363fdfed53803955903374ae2cc8bf76251bd
<ide><path>docs/Maintainer-Guidelines.md <ide> In the same way that Homebrew maintainers are expected to be spending more of th <ide> Individual Homebrew repositories should not have formal lead maintainers (although those who do the most work will have the loudest voices). <ide> <ide> Maintainers should feel even more free to pleasantly disagree with the work and decisions of the lead maintainer: with greater authority comes greater responsibility to handle and moderate technical disagreements. <add> <add>Homebrew's last lead maintainer will be Mike McQuaid. On February 1st, Mike will step down as lead maintainer of Homebrew and his responsibilities will be passed on to the project leadership committee and/or a new, technical steering committee and/or something else. <add> <add>Some food for thought and discussion before those dates: <add> <add>- [How the Apache Software Foundation Works](https://www.apache.org/foundation/how-it-works.html) <add>- [Debian Project Leader documentation]() <add>- [Debian Technical Committee documentation](https://www.debian.org/devel/tech-ctte) <add>- [Debian's Organizational Structure](https://www.debian.org/intro/organization) <add>- [QEMU SFC PLC documentation](https://wiki.qemu.org/Conservancy) <add>- [libgit2 SFC PLC creation discussion](https://github.com/libgit2/discussions/issues/9) <add> <add>Some essential TODO before these dates: <add> <add>- Decide how to spend more of Homebrew's money to be useful for the project <add>- Decide how technical and non-technical decisions are reached and conflicts resolved <add>- Move Homebrew to a new CI system which does not require ideally any manual system administration <add>- Onboard as many new maintainers as possible <add>- Generally hand off and document any other responsibilities that are (and always have been) done by Mike McQuaid alone onto other groups of people
1
Go
Go
remove deprecated endpoint test
a34d804572882e2251de7769efd075886c76ea10
<ide><path>integration/container/container_test.go <ide> func TestContainerInvalidJSON(t *testing.T) { <ide> defer setupTest(t)() <ide> <ide> endpoints := []string{ <del> "/containers/foobar/copy", <ide> "/containers/foobar/exec", <ide> "/exec/foobar/start", <ide> }
1
Text
Text
create model card
8f7c1c7672386c8bab64c5452f8599f32ec7d8a0
<ide><path>model_cards/mrm8488/bert-italian-finedtuned-squadv1-it-alfa/README.md <add>--- <add>language: italian <add>thumbnail: <add>--- <add> <add># Italian BERT :it: fine-tuned on SQuAD_it v1 :book: :mag: :question: <add> <add>[Italian BERT base cased](https://huggingface.co/dbmdz/bert-base-italian-cased) fine-tuned on [italian SQuAD](https://github.com/crux82/squad-it) for **Q&A** downstream task. <add> <add>## Details of Italian BERT :hugs: :it: <add> <add>The source data for the Italian BERT model consists of a recent Wikipedia dump and various texts from the OPUS corpora collection. The final training corpus has a size of 13GB and 2,050,057,573 tokens. <add> <add>For sentence splitting, we use NLTK (faster compared to spacy). Our cased and uncased models are training with an initial sequence length of 512 subwords for ~2-3M steps. <add> <add>For the XXL Italian models, we use the same training data from OPUS and extend it with data from the Italian part of the OSCAR corpus. Thus, the final training corpus has a size of 81GB and 13,138,379,147 tokens. <add>More in its official [model card](https://huggingface.co/dbmdz/bert-base-italian-cased) <add> <add>Created by [Stefan](https://huggingface.co/stefan-it) at [MDZ](https://huggingface.co/dbmdz) <add> <add>## Details of the downstream task (Q&A) - Dataset :books: <add> <add>[Italian SQuAD v1.1](https://rajpurkar.github.io/SQuAD-explorer/) is derived from the SQuAD dataset and it is obtained through semi-automatic translation of the SQuAD dataset <add>into Italian. It represents a large-scale dataset for open question answering processes on factoid questions in Italian. <add>**The dataset contains more than 60,000 question/answer pairs derived from the original English dataset.** The dataset is split into training and test sets to support the replicability of the benchmarking of QA systems: <add> <add>- `SQuAD_it-train.json`: it contains training examples derived from the original SQuAD 1.1 trainig material. <add>- `SQuAD_it-test.json`: it contains test/benchmarking examples derived from the origial SQuAD 1.1 development material. <add> <add>More details about SQuAD-it can be found in [Croce et al. 2018]. The original paper can be found at this [link](https://link.springer.com/chapter/10.1007/978-3-030-03840-3_29). <add> <add>## Model training :gear: <add> <add>The model was trained on a Tesla P100 GPU and 25GB of RAM. <add>The script for fine tuning can be found [here](https://github.com/huggingface/transformers/blob/master/examples/question-answering/run_squad.py) <add> <add>## Results :chart_with_upwards_trend: <add> <add>| Metric | # Value | <add>| ------ | --------- | <add>| **EM** | **62.51** | <add>| **F1** | **74.16** | <add> <add>### Raw metrics <add> <add>```json <add>{ <add> "exact": 62.5180707057432, <add> "f1": 74.16038329042492, <add> "total": 7609, <add> "HasAns_exact": 62.5180707057432, <add> "HasAns_f1": 74.16038329042492, <add> "HasAns_total": 7609, <add> "best_exact": 62.5180707057432, <add> "best_exact_thresh": 0.0, <add> "best_f1": 74.16038329042492, <add> "best_f1_thresh": 0.0 <add>} <add>``` <add> <add>## Comparison :balance_scale: <add> <add>| Model | EM | F1 score | <add>| -------------------------------------------------------------------------------------------------------------------------------- | --------- | --------- | <add>| [DrQA-it trained on SQuAD-it ](https://github.com/crux82/squad-it/blob/master/README.md#evaluating-a-neural-model-over-squad-it) | 56.1 | 65.9 | <add>| This one | **62.51** | **74.16** | <add> <add>## Model in action :rocket: <add> <add>Fast usage with **pipelines** 🧪 <add> <add>```python <add>from transformers import pipeline <add> <add>nlp_qa = pipeline( <add> 'question-answering', <add> model='mrm8488/bert-italian-finedtuned-squadv1-it-alfa', <add> tokenizer='mrm8488/bert-italian-finedtuned-squadv1-it-alfa' <add>) <add> <add>nlp_qa( <add> { <add> 'question': 'Per quale lingua stai lavorando?', <add> 'context': 'Manuel Romero è colaborando attivamente con HF / trasformatori per il trader del poder de las últimas ' + <add> 'técnicas di procesamiento de lenguaje natural al idioma español' <add> } <add>) <add> <add># Output: {'answer': 'español', 'end': 174, 'score': 0.9925341537498156, 'start': 168} <add>``` <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) | [LinkedIn](https://www.linkedin.com/in/manuel-romero-cs/) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain <add> <add>Dataset citation <add> <add><details> <add>@InProceedings{10.1007/978-3-030-03840-3_29, <add> author="Croce, Danilo and Zelenanska, Alexandra and Basili, Roberto", <add> editor="Ghidini, Chiara and Magnini, Bernardo and Passerini, Andrea and Traverso, Paolo", <add> title="Neural Learning for Question Answering in Italian", <add> booktitle="AI*IA 2018 -- Advances in Artificial Intelligence", <add> year="2018", <add> publisher="Springer International Publishing", <add> address="Cham", <add> pages="389--402", <add> isbn="978-3-030-03840-3" <add>} <add></detail>
1
Python
Python
handle leading slash in samba path
d17ae60be4d83e0bdfa6cb3c2c41e2bb1fcbf1b6
<ide><path>airflow/providers/samba/hooks/samba.py <ide> def __exit__(self, exc_type, exc_value, traceback): <ide> self._connection_cache.clear() <ide> <ide> def _join_path(self, path): <del> return f"//{posixpath.join(self._host, self._share, path)}" <add> return f"//{posixpath.join(self._host, self._share, path.lstrip('/'))}" <ide> <ide> @wraps(smbclient.link) <ide> def link(self, src, dst, follow_symlinks=True): <ide><path>tests/providers/samba/hooks/test_samba.py <ide> def test_method(self, name, get_conn_mock): <ide> <ide> # We expect keyword arguments to include the connection settings. <ide> assert dict(kwargs, **connection_settings) == p_kwargs <add> <add> @parameterized.expand( <add> [ <add> ("/start/path/with/slash", "//ip/share/start/path/with/slash"), <add> ("start/path/without/slash", "//ip/share/start/path/without/slash"), <add> ], <add> ) <add> @mock.patch('airflow.hooks.base.BaseHook.get_connection') <add> def test__join_path(self, path, full_path, get_conn_mock): <add> get_conn_mock.return_value = CONNECTION <add> hook = SambaHook('samba_default') <add> assert hook._join_path(path) == full_path
2
Javascript
Javascript
check canusedom before calling iseventsupported
932c45a7ab83746f9a6e1a2f21919492b18e7ba0
<ide><path>src/eventPlugins/TextChangeEventPlugin.js <ide> var AbstractEvent = require('AbstractEvent'); <ide> var EventConstants = require('EventConstants'); <ide> var EventPluginHub = require('EventPluginHub'); <ide> var EventPropagators = require('EventPropagators'); <add>var ExecutionEnvironment = require('ExecutionEnvironment'); <ide> <ide> var isEventSupported = require('isEventSupported'); <ide> var keyOf = require('keyOf'); <ide> var abstractEventTypes = { <ide> <ide> // IE9 claims to support the input event but fails to trigger it when deleting <ide> // text, so we ignore its input events <del>var isInputSupported = isEventSupported('input') && ( <del> !("documentMode" in document) || document.documentMode > 9 <del>); <add>var isInputSupported; <add>if (ExecutionEnvironment.canUseDOM) { <add> isInputSupported = isEventSupported('input') && ( <add> !("documentMode" in document) || document.documentMode > 9 <add> ); <add>} <ide> <ide> var hasInputCapabilities = function(elem) { <ide> // The HTML5 spec lists many more types than `text` and `password` on which
1
Javascript
Javascript
remove more function keywords
566aca3ce07e6af92e419b1e61f930bc796703e9
<ide><path>spec/config-spec.js <ide> describe('Config', () => { <ide> atom.config.configFilePath = path.join(atom.config.configDirPath, 'atom.config.cson') <ide> }) <ide> <del> afterEach(function () { <add> afterEach(() => { <ide> atom.config.enablePersistence = false <ide> fs.removeSync(dotAtomPath) <ide> }) <ide> <del> describe('.get(keyPath, {scope, sources, excludeSources})', function () { <del> it("allows a key path's value to be read", function () { <add> describe('.get(keyPath, {scope, sources, excludeSources})', () => { <add> it("allows a key path's value to be read", () => { <ide> expect(atom.config.set('foo.bar.baz', 42)).toBe(true) <ide> expect(atom.config.get('foo.bar.baz')).toBe(42) <ide> expect(atom.config.get('foo.quux')).toBeUndefined() <ide> }) <ide> <del> it("returns a deep clone of the key path's value", function () { <add> it("returns a deep clone of the key path's value", () => { <ide> atom.config.set('value', {array: [1, {b: 2}, 3]}) <ide> const retrievedValue = atom.config.get('value') <ide> retrievedValue.array[0] = 4 <ide> retrievedValue.array[1].b = 2.1 <ide> expect(atom.config.get('value')).toEqual({array: [1, {b: 2}, 3]}) <ide> }) <ide> <del> it('merges defaults into the returned value if both the assigned value and the default value are objects', function () { <add> it('merges defaults into the returned value if both the assigned value and the default value are objects', () => { <ide> atom.config.setDefaults('foo.bar', {baz: 1, ok: 2}) <ide> atom.config.set('foo.bar', {baz: 3}) <ide> expect(atom.config.get('foo.bar')).toEqual({baz: 3, ok: 2}) <ide> describe('Config', () => { <ide> }) <ide> <ide> describe("when a 'sources' option is specified", () => <del> it('only retrieves values from the specified sources', function () { <add> it('only retrieves values from the specified sources', () => { <ide> atom.config.set('x.y', 1, {scopeSelector: '.foo', source: 'a'}) <ide> atom.config.set('x.y', 2, {scopeSelector: '.foo', source: 'b'}) <ide> atom.config.set('x.y', 3, {scopeSelector: '.foo', source: 'c'}) <ide> describe('Config', () => { <ide> ) <ide> <ide> describe("when a 'scope' option is given", () => { <del> it('returns the property with the most specific scope selector', function () { <add> it('returns the property with the most specific scope selector', () => { <ide> atom.config.set('foo.bar.baz', 42, {scopeSelector: '.source.coffee .string.quoted.double.coffee'}) <ide> atom.config.set('foo.bar.baz', 22, {scopeSelector: '.source .string.quoted.double'}) <ide> atom.config.set('foo.bar.baz', 11, {scopeSelector: '.source'}) <ide> describe('Config', () => { <ide> expect(atom.config.get('foo.bar.baz', {scope: ['.text']})).toBeUndefined() <ide> }) <ide> <del> it('favors the most recently added properties in the event of a specificity tie', function () { <add> it('favors the most recently added properties in the event of a specificity tie', () => { <ide> atom.config.set('foo.bar.baz', 42, {scopeSelector: '.source.coffee .string.quoted.single'}) <ide> atom.config.set('foo.bar.baz', 22, {scopeSelector: '.source.coffee .string.quoted.double'}) <ide> <ide> describe('Config', () => { <ide> }) <ide> <ide> describe('when there are global defaults', () => <del> it('falls back to the global when there is no scoped property specified', function () { <add> it('falls back to the global when there is no scoped property specified', () => { <ide> atom.config.setDefaults('foo', {hasDefault: 'ok'}) <ide> expect(atom.config.get('foo.hasDefault', {scope: ['.source.coffee', '.string.quoted.single']})).toBe('ok') <ide> }) <ide> ) <ide> <ide> describe('when package settings are added after user settings', () => <del> it("returns the user's setting because the user's setting has higher priority", function () { <add> it("returns the user's setting because the user's setting has higher priority", () => { <ide> atom.config.set('foo.bar.baz', 100, {scopeSelector: '.source.coffee'}) <ide> atom.config.set('foo.bar.baz', 1, {scopeSelector: '.source.coffee', source: 'some-package'}) <ide> expect(atom.config.get('foo.bar.baz', {scope: ['.source.coffee']})).toBe(100) <ide> }) <ide> ) <ide> <ide> describe('when the first component of the scope descriptor matches a legacy scope alias', () => <del> it('falls back to properties defined for the legacy scope if no value is found for the original scope descriptor', function () { <add> it('falls back to properties defined for the legacy scope if no value is found for the original scope descriptor', () => { <ide> atom.config.addLegacyScopeAlias('javascript', '.source.js') <ide> atom.config.set('foo', 100, {scopeSelector: '.source.js'}) <ide> atom.config.set('foo', 200, {scopeSelector: 'javascript for_statement'}) <ide> describe('Config', () => { <ide> expect(bazCatHandler).not.toHaveBeenCalled() <ide> }) <ide> <del> return describe("when a 'scope' is given", () => { <add> describe("when a 'scope' is given", () => { <ide> let otherHandler = null <ide> <ide> beforeEach(() => { <ide> describe('Config', () => { <ide> atom.config.onDidChange('foo.bar.baz', changeSpy) <ide> }) <ide> <del> it('allows only one change event for the duration of the given callback', function () { <add> it('allows only one change event for the duration of the given callback', () => { <ide> atom.config.transact(() => { <ide> atom.config.set('foo.bar.baz', 1) <ide> atom.config.set('foo.bar.baz', 2) <ide> describe('Config', () => { <ide> }) <ide> }) <ide> <del> it('allows only one change event for the duration of the given promise if it gets rejected', function () { <add> it('allows only one change event for the duration of the given promise if it gets rejected', () => { <ide> let promiseError = null <del> const transactionPromise = atom.config.transactAsync(function () { <add> const transactionPromise = atom.config.transactAsync(() => { <ide> atom.config.set('foo.bar.baz', 1) <ide> atom.config.set('foo.bar.baz', 2) <ide> atom.config.set('foo.bar.baz', 3) <ide> describe('Config', () => { <ide> <ide> waitsForPromise(() => transactionPromise.catch(e => promiseError = e)) <ide> <del> runs(function () { <add> runs(() => { <ide> expect(promiseError).toBe('an error') <ide> expect(changeSpy.callCount).toBe(1) <ide> expect(changeSpy.argsForCall[0][0]).toEqual({newValue: 3, oldValue: undefined}) <ide> describe('Config', () => { <ide> fs.writeFileSync(atom.config.configFilePath, '{{{{{') <ide> }) <ide> <del> it('logs an error to the console and does not overwrite the config file on a subsequent save', function () { <add> it('logs an error to the console and does not overwrite the config file on a subsequent save', () => { <ide> atom.config.loadUserConfig() <ide> expect(addErrorHandler.callCount).toBe(1) <ide> atom.config.set('hair', 'blonde') // trigger a save <ide> describe('Config', () => { <ide> }) <ide> }) <ide> <del> return it('creates a notification and does not try to save later changes to disk', function () { <add> it('creates a notification and does not try to save later changes to disk', () => { <ide> const load = () => atom.config.loadUserConfig() <ide> expect(load).not.toThrow() <ide> expect(addErrorHandler.callCount).toBe(1) <ide> <ide> atom.config.set('foo.bar', 'baz') <ide> advanceClock(100) <ide> expect(atom.config.save).not.toHaveBeenCalled() <del> return expect(atom.config.get('foo.bar')).toBe('baz') <add> expect(atom.config.get('foo.bar')).toBe('baz') <ide> }) <ide> }) <ide> }) <ide> describe('Config', () => { <ide> fs.writeFileSync(atom.config.configFilePath, data) <ide> <ide> const future = (Date.now() / 1000) + secondsInFuture <del> return fs.utimesSync(atom.config.configFilePath, future, future) <add> fs.utimesSync(atom.config.configFilePath, future, future) <ide> } <ide> <ide> beforeEach(() => { <ide> describe('Config', () => { <ide> expect(atom.config.save).not.toHaveBeenCalled() <ide> }) <ide> <del> describe('when the config file subsequently changes again to contain valid cson', function () { <add> describe('when the config file subsequently changes again to contain valid cson', () => { <ide> beforeEach(() => { <ide> updatedHandler.reset() <ide> writeConfigFile("foo: bar: 'newVal'", 6) <ide> describe('Config', () => { <ide> }) <ide> <ide> describe('.pushAtKeyPath(keyPath, value)', () => <del> it('pushes the given value to the array at the key path and updates observers', function () { <add> it('pushes the given value to the array at the key path and updates observers', () => { <ide> atom.config.set('foo.bar.baz', ['a']) <ide> const observeHandler = jasmine.createSpy('observeHandler') <ide> atom.config.observe('foo.bar.baz', observeHandler) <ide> describe('Config', () => { <ide> ) <ide> <ide> describe('.setDefaults(keyPath, defaults)', () => { <del> it('assigns any previously-unassigned keys to the object at the key path', function () { <add> it('assigns any previously-unassigned keys to the object at the key path', () => { <ide> atom.config.set('foo.bar.baz', {a: 1}) <ide> atom.config.setDefaults('foo.bar.baz', {a: 2, b: 3, c: 4}) <ide> expect(atom.config.get('foo.bar.baz.a')).toBe(1) <ide> describe('Config', () => { <ide> expect(atom.config.get('foo.bar.aBool')).toBe(false) <ide> }) <ide> <del> it('reverts back to the default value when undefined is passed to set', function () { <add> it('reverts back to the default value when undefined is passed to set', () => { <ide> atom.config.set('foo.bar.aBool', 'false') <ide> expect(atom.config.get('foo.bar.aBool')).toBe(false) <ide> <ide> describe('Config', () => { <ide> atom.config.setSchema('foo.bar', schema) <ide> }) <ide> <del> it('will only set a string when the string is in the enum values', function () { <add> it('will only set a string when the string is in the enum values', () => { <ide> expect(atom.config.set('foo.bar.str', 'nope')).toBe(false) <ide> expect(atom.config.get('foo.bar.str')).toBe('ok') <ide> <ide> expect(atom.config.set('foo.bar.str', 'one')).toBe(true) <ide> expect(atom.config.get('foo.bar.str')).toBe('one') <ide> }) <ide> <del> it('will only set an integer when the integer is in the enum values', function () { <add> it('will only set an integer when the integer is in the enum values', () => { <ide> expect(atom.config.set('foo.bar.int', '400')).toBe(false) <ide> expect(atom.config.get('foo.bar.int')).toBe(2) <ide> <ide> expect(atom.config.set('foo.bar.int', '3')).toBe(true) <ide> expect(atom.config.get('foo.bar.int')).toBe(3) <ide> }) <ide> <del> it('will only set an array when the array values are in the enum values', function () { <add> it('will only set an array when the array values are in the enum values', () => { <ide> expect(atom.config.set('foo.bar.arr', ['one', 'five'])).toBe(true) <ide> expect(atom.config.get('foo.bar.arr')).toEqual(['one']) <ide> <ide> describe('Config', () => { <ide> }) <ide> }) <ide> <del> return describe('when .set/.unset is called prior to .loadUserConfig', () => { <add> describe('when .set/.unset is called prior to .loadUserConfig', () => { <ide> beforeEach(() => { <ide> atom.config.settingsLoaded = false <ide> fs.writeFileSync(atom.config.configFilePath, <ide> describe('Config', () => { <ide> ) <ide> }) <ide> <del> it('ensures that early set and unset calls are replayed after the config is loaded from disk', function () { <add> it('ensures that early set and unset calls are replayed after the config is loaded from disk', () => { <ide> atom.config.unset('foo.bar') <ide> atom.config.set('foo.qux', 'boo') <ide>
1
Javascript
Javascript
fix crossorigin propagation in objmtl loader
4e1beb0b4861c54968c22cee0e40aac8b2247a81
<ide><path>examples/js/loaders/MTLLoader.js <ide> THREE.MTLLoader.prototype = { <ide> } <ide> <ide> var materialCreator = new THREE.MTLLoader.MaterialCreator( this.baseUrl, this.options ); <add> materialCreator.crossOrigin = this.crossOrigin <ide> materialCreator.setMaterials( materialsInfo ); <ide> return materialCreator; <ide> <ide><path>examples/js/loaders/OBJMTLLoader.js <ide> THREE.OBJMTLLoader.prototype = { <ide> var scope = this; <ide> <ide> var mtlLoader = new THREE.MTLLoader( url.substr( 0, url.lastIndexOf( "/" ) + 1 ) ); <add> mtlLoader.crossOrigin = scope.crossOrigin; <ide> mtlLoader.load( mtlurl, function ( materials ) { <ide> <ide> var materialsCreator = materials;
2
Text
Text
remove rdoc formatting from markdown [ci skip]
abefa2f635c09fc51c0f63058acd0d1a46f30f60
<ide><path>guides/source/active_support_core_extensions.md <ide> NOTE: Defined in `active_support/core_ext/object/with_options.rb`. <ide> <ide> ### JSON support <ide> <del>Active Support provides a better implementation of `to_json` than the +json+ gem ordinarily provides for Ruby objects. This is because some classes, like +Hash+, +OrderedHash+, and +Process::Status+ need special handling in order to provide a proper JSON representation. <add>Active Support provides a better implementation of `to_json` than the `json` gem ordinarily provides for Ruby objects. This is because some classes, like `Hash`, `OrderedHash` and `Process::Status` need special handling in order to provide a proper JSON representation. <ide> <ide> NOTE: Defined in `active_support/core_ext/object/json.rb`. <ide>
1
Javascript
Javascript
use native array.isarray
751ebc17f7fc7be26613db0a3cdee05fc401318b
<ide><path>src/Angular.js <ide> function isDate(value) { <ide> * @param {*} value Reference to check. <ide> * @returns {boolean} True if `value` is an `Array`. <ide> */ <del>function isArray(value) { <del> return toString.call(value) === '[object Array]'; <del>} <del> <add>var isArray = (function() { <add> if (!isFunction(Array.isArray)) { <add> return function(value) { <add> return toString.call(value) === '[object Array]'; <add> }; <add> } <add> return Array.isArray; <add>})(); <ide> <ide> /** <ide> * @ngdoc function
1
Python
Python
fix endline in the signal.py
1fbeb337c467a2be0f999606373fd1ba0e200908
<ide><path>flask/signals.py <ide> def _fail(self, *args, **kwargs): <ide> appcontext_tearing_down = _signals.signal('appcontext-tearing-down') <ide> appcontext_pushed = _signals.signal('appcontext-pushed') <ide> appcontext_popped = _signals.signal('appcontext-popped') <del>message_flashed = _signals.signal('message-flashed') <ide>\ No newline at end of file <add>message_flashed = _signals.signal('message-flashed') <ide><path>tests/test_signals.py <ide> def record(sender, template, context): <ide> context['whiskey'] = 43 <ide> recorded.append((template, context)) <ide> <del> flask.before_render_template.connect(record, app) <del> try: <add> with flask.before_render_template.connected_to(record): <ide> rv = app.test_client().get('/') <ide> assert len(recorded) == 1 <ide> template, context = recorded[0] <ide> assert template.name == 'simple_template.html' <ide> assert context['whiskey'] == 43 <ide> assert rv.data == b'<h1>43</h1>' <del> finally: <del> flask.before_render_template.disconnect(record, app) <add> <ide> <ide> def test_request_signals(): <ide> app = flask.Flask(__name__)
2
Java
Java
add test case based on spr-16615
2ff35daf9bc83a89c6ca579e4440e48627b9a56a
<ide><path>spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java <ide> import static org.junit.Assert.*; <ide> <ide> /** <add> * Unit tests for {@link StringDecoder}. <ide> * @author Sebastien Deleuze <ide> * @author Brian Clozel <ide> * @author Mark Paluch <ide> public class StringDecoderTests extends AbstractDataBufferAllocatingTestCase { <ide> <ide> @Test <ide> public void canDecode() { <del> assertTrue(this.decoder.canDecode(ResolvableType.forClass(String.class), <del> MimeTypeUtils.TEXT_PLAIN)); <del> assertTrue(this.decoder.canDecode(ResolvableType.forClass(String.class), <del> MimeTypeUtils.TEXT_HTML)); <del> assertTrue(this.decoder.canDecode(ResolvableType.forClass(String.class), <del> MimeTypeUtils.APPLICATION_JSON)); <del> assertFalse(this.decoder.canDecode(ResolvableType.forClass(Integer.class), <del> MimeTypeUtils.TEXT_PLAIN)); <del> assertFalse(this.decoder.canDecode(ResolvableType.forClass(Object.class), <del> MimeTypeUtils.APPLICATION_JSON)); <add> <add> assertTrue(this.decoder.canDecode( <add> ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); <add> <add> assertTrue(this.decoder.canDecode( <add> ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_HTML)); <add> <add> assertTrue(this.decoder.canDecode( <add> ResolvableType.forClass(String.class), MimeTypeUtils.APPLICATION_JSON)); <add> <add> assertTrue(this.decoder.canDecode( <add> ResolvableType.forClass(String.class), MimeTypeUtils.parseMimeType("text/plain;charset=utf-8"))); <add> <add> <add> assertFalse(this.decoder.canDecode( <add> ResolvableType.forClass(Integer.class), MimeTypeUtils.TEXT_PLAIN)); <add> <add> assertFalse(this.decoder.canDecode( <add> ResolvableType.forClass(Object.class), MimeTypeUtils.APPLICATION_JSON)); <ide> } <ide> <ide> @Test
1
PHP
PHP
fix bug with chaining
434245f73e694f90476437da8554b58d54ced25c
<ide><path>src/Illuminate/Bus/Queueable.php <ide> public function chain($chain) <ide> public function dispatchNextJobInChain() <ide> { <ide> if (! empty($this->chained)) { <del> dispatch(unserialize(array_shift($this->chained))->chain($this->chained)); <add> dispatch(tap(unserialize(array_shift($this->chained)), function ($next) { <add> $next->chained = $this->chained; <add> })); <ide> } <ide> } <ide> } <ide><path>tests/Integration/Queue/JobChainingTest.php <ide> public function tearDown() <ide> { <ide> JobChainingTestFirstJob::$ran = false; <ide> JobChainingTestSecondJob::$ran = false; <add> JobChainingTestThirdJob::$ran = false; <ide> } <ide> <ide> public function test_jobs_can_be_chained_on_success() <ide> public function test_jobs_can_be_chained_on_success() <ide> $this->assertTrue(JobChainingTestSecondJob::$ran); <ide> } <ide> <add> public function test_jobs_can_be_chained_on_success_with_several_jobs() <add> { <add> JobChainingTestFirstJob::dispatch()->chain([ <add> new JobChainingTestSecondJob, <add> new JobChainingTestThirdJob, <add> ]); <add> <add> $this->assertTrue(JobChainingTestFirstJob::$ran); <add> $this->assertTrue(JobChainingTestSecondJob::$ran); <add> $this->assertTrue(JobChainingTestThirdJob::$ran); <add> } <add> <ide> public function test_jobs_can_be_chained_on_success_using_helper() <ide> { <ide> dispatch(new JobChainingTestFirstJob)->chain([ <ide> public function handle() <ide> } <ide> } <ide> <add>class JobChainingTestThirdJob implements ShouldQueue <add>{ <add> use Dispatchable, Queueable; <add> <add> public static $ran = false; <add> <add> public function handle() <add> { <add> static::$ran = true; <add> } <add>} <add> <ide> class JobChainingTestFailingJob implements ShouldQueue <ide> { <ide> use Dispatchable, InteractsWithQueue, Queueable;
2
PHP
PHP
provide a path to view in compiled view
db774be8588f9d30ce4577bc06fac9711e08d9cb
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php <ide> public function compile($path = null) <ide> } <ide> <ide> if (! is_null($this->cachePath)) { <del> $contents = $this->compileString($this->files->get($this->getPath())); <add> $contents = "<?php/* {$this->getPath()} */?>\n"; <add> $contents .= $this->compileString($this->files->get($this->getPath())); <ide> <ide> $this->files->put($this->getCompiledPath($this->getPath()), $contents); <ide> } <ide><path>tests/View/ViewBladeCompilerTest.php <ide> public function testCompileCompilesFileAndReturnsContents() <ide> { <ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); <ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); <del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); <add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "<?php/* foo */?>\nHello World"); <ide> $compiler->compile('foo'); <ide> } <ide> <ide> public function testCompileCompilesAndGetThePath() <ide> { <ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); <ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); <del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); <add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "<?php/* foo */?>\nHello World"); <ide> $compiler->compile('foo'); <ide> $this->assertEquals('foo', $compiler->getPath()); <ide> } <ide> public function testCompileWithPathSetBefore() <ide> { <ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); <ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); <del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); <add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "<?php/* foo */?>\nHello World"); <ide> // set path before compilation <ide> $compiler->setPath('foo'); <ide> // trigger compilation with null $path <ide> public function testRawTagsCanBeSetToLegacyValues() <ide> }}')); <ide> } <ide> <add> public function testIncludePathToTemplate() <add> { <add> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); <add> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); <add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "<?php/* foo */?>\nHello World"); <add> $compiler->compile('foo'); <add> } <add> <ide> protected function getFiles() <ide> { <ide> return m::mock(Filesystem::class);
2
PHP
PHP
allow default value in find method
99d0fd9819b8a0a972a7b535d175e960ff50d14c
<ide><path>src/Illuminate/Database/Eloquent/Collection.php <ide> class Collection extends BaseCollection { <ide> * Find a model in the collection by key. <ide> * <ide> * @param mixed $key <add> * @param mixed $default <ide> * @return Illuminate\Database\Eloquent\Model <ide> */ <del> public function find($key) <add> public function find($key, $default = null) <ide> { <ide> if (count($this->dictionary) == 0) <ide> { <ide> $this->buildDictionary(); <ide> } <ide> <del> return $this->dictionary[$key]; <add> return array_get($this->dictionary, $key, $default); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentCollectionTest.php <ide> public function testFindMethodFindsModelById() <ide> $c = new Collection(array($mockModel)); <ide> <ide> $this->assertTrue($mockModel === $c->find(1)); <add> $this->assertTrue('taylor' === $c->find(2, 'taylor')); <ide> } <ide> <ide>
2
Ruby
Ruby
fix tests on sqlite3
7312b8318f0c770d363a62d679aa8f67a18e549b
<ide><path>activerecord/test/cases/migration_test.rb <ide> class MigrationTest < ActiveRecord::TestCase <ide> <ide> def setup <ide> super <add> %w(reminders people_reminders prefix_reminders_suffix).each do |table| <add> Reminder.connection.drop_table(table) rescue nil <add> end <add> Reminder.reset_column_information <ide> ActiveRecord::Migration.verbose = true <ide> ActiveRecord::Migration.message_count = 0 <ide> end
1
PHP
PHP
fix locale matcher
91a632f98351ba0e1c033b9e597eac2e5ca5b244
<ide><path>src/Illuminate/Http/Request.php <ide> public function handleUriLocales(array $locales) <ide> <ide> foreach ($locales as $locale) <ide> { <del> if (starts_with($path, '/'.$locale)) return $this->removeLocaleFromUri($locale); <add> if (preg_match("#^\/{$locale}(?:$|/)#i", $path)) <add> { <add> return $this->removeLocaleFromUri($locale); <add> } <ide> } <ide> } <ide>
1
PHP
PHP
convert spaces to tabs
6f847732a4414dbb82ad31aa90f05e884e8f577c
<ide><path>system/str.php <ide> class Str { <ide> */ <ide> public static function entities($value) <ide> { <del> return htmlentities($value, ENT_QUOTES, Config::get('application.encoding'), false); <add> return htmlentities($value, ENT_QUOTES, Config::get('application.encoding'), false); <ide> } <ide> <del> /** <del> * Convert a string to lowercase. <del> * <del> * @param string $value <del> * @return string <del> */ <del> public static function lower($value) <del> { <del> return function_exists('mb_strtolower') ? mb_strtolower($value, Config::get('application.encoding')) : strtolower($value); <del> } <add> /** <add> * Convert a string to lowercase. <add> * <add> * @param string $value <add> * @return string <add> */ <add> public static function lower($value) <add> { <add> return function_exists('mb_strtolower') ? mb_strtolower($value, Config::get('application.encoding')) : strtolower($value); <add> } <ide> <del> /** <del> * Convert a string to uppercase. <del> * <del> * @param string $value <del> * @return string <del> */ <del> public static function upper($value) <del> { <del> return function_exists('mb_strtoupper') ? mb_strtoupper($value, Config::get('application.encoding')) : strtoupper($value); <del> } <add> /** <add> * Convert a string to uppercase. <add> * <add> * @param string $value <add> * @return string <add> */ <add> public static function upper($value) <add> { <add> return function_exists('mb_strtoupper') ? mb_strtoupper($value, Config::get('application.encoding')) : strtoupper($value); <add> } <ide> <del> /** <del> * Convert a string to title case (ucwords). <del> * <del> * @param string $value <del> * @return string <del> */ <del> public static function title($value) <del> { <del> return (function_exists('mb_convert_case')) ? mb_convert_case($value, MB_CASE_TITLE, Config::get('application.encoding')) : ucwords(strtolower($value)); <del> } <add> /** <add> * Convert a string to title case (ucwords). <add> * <add> * @param string $value <add> * @return string <add> */ <add> public static function title($value) <add> { <add> return (function_exists('mb_convert_case')) ? mb_convert_case($value, MB_CASE_TITLE, Config::get('application.encoding')) : ucwords(strtolower($value)); <add> } <ide> <del> /** <del> * Get the length of a string. <del> * <del> * @param string $value <del> * @return int <del> */ <del> public static function length($value) <del> { <del> return function_exists('mb_strlen') ? mb_strlen($value, Config::get('application.encoding')) : strlen($value); <del> } <add> /** <add> * Get the length of a string. <add> * <add> * @param string $value <add> * @return int <add> */ <add> public static function length($value) <add> { <add> return function_exists('mb_strlen') ? mb_strlen($value, Config::get('application.encoding')) : strlen($value); <add> } <ide> <del> /** <del> * Convert a string to 7-bit ASCII. <del> * <del> * @param string $value <del> * @return string <del> */ <del> public static function ascii($value) <del> { <del> $foreign = Config::get('ascii'); <add> /** <add> * Convert a string to 7-bit ASCII. <add> * <add> * @param string $value <add> * @return string <add> */ <add> public static function ascii($value) <add> { <add> $foreign = Config::get('ascii'); <ide> <del> $value = preg_replace(array_keys($foreign), array_values($foreign), $value); <add> $value = preg_replace(array_keys($foreign), array_values($foreign), $value); <ide> <del> return preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '', $value); <del> } <add> return preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '', $value); <add> } <ide> <del> /** <del> * Generate a random alpha or alpha-numeric string. <del> * <del> * Supported types: 'alpha_num' and 'alpha'. <del> * <del> * @param int $length <del> * @param string $type <del> * @return string <del> */ <del> public static function random($length = 16, $type = 'alpha_num') <del> { <del> $value = ''; <add> /** <add> * Generate a random alpha or alpha-numeric string. <add> * <add> * Supported types: 'alpha_num' and 'alpha'. <add> * <add> * @param int $length <add> * @param string $type <add> * @return string <add> */ <add> public static function random($length = 16, $type = 'alpha_num') <add> { <add> $value = ''; <ide> <del> $pool_length = strlen($pool = static::pool($type)) - 1; <add> $pool_length = strlen($pool = static::pool($type)) - 1; <ide> <del> for ($i = 0; $i < $length; $i++) <del> { <del> $value .= $pool[mt_rand(0, $pool_length)]; <del> } <add> for ($i = 0; $i < $length; $i++) <add> { <add> $value .= $pool[mt_rand(0, $pool_length)]; <add> } <ide> <del> return $value; <del> } <add> return $value; <add> } <ide> <del> /** <del> * Get a chracter pool. <del> * <del> * @param string $type <del> * @return string <del> */ <del> private static function pool($type = 'alpha_num') <del> { <del> switch ($type) <del> { <del> case 'alpha_num': <del> return '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; <del> <del> default: <del> return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; <del> } <del> } <add> /** <add> * Get a chracter pool. <add> * <add> * @param string $type <add> * @return string <add> */ <add> private static function pool($type = 'alpha_num') <add> { <add> switch ($type) <add> { <add> case 'alpha_num': <add> return '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; <add> <add> default: <add> return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; <add> } <add> } <ide> <ide> } <ide>\ No newline at end of file
1
Javascript
Javascript
remove duplicate encoding tests in favor of wpt
dce2f3ed93ffd3a6374a4e578f686343494519ad
<ide><path>test/parallel/test-whatwg-encoding-api-basics.js <del>'use strict'; <del> <del>// From: https://github.com/w3c/web-platform-tests/blob/master/encoding/api-basics.html <del>// TODO(joyeecheung): replace this with WPT <del> <del>const common = require('../common'); <del> <del>if (!common.hasIntl) <del> common.skip('missing Intl'); <del> <del>const assert = require('assert'); <del> <del>function testDecodeSample(encoding, string, bytes) { <del> assert.strictEqual( <del> new TextDecoder(encoding).decode(new Uint8Array(bytes)), <del> string); <del> assert.strictEqual( <del> new TextDecoder(encoding).decode(new Uint8Array(bytes).buffer), <del> string); <del>} <del> <del>// `z` (ASCII U+007A), cent (Latin-1 U+00A2), CJK water (BMP U+6C34), <del>// G-Clef (non-BMP U+1D11E), PUA (BMP U+F8FF), PUA (non-BMP U+10FFFD) <del>// byte-swapped BOM (non-character U+FFFE) <del>const sample = 'z\xA2\u6C34\uD834\uDD1E\uF8FF\uDBFF\uDFFD\uFFFE'; <del> <del>{ <del> const encoding = 'utf-8'; <del> const string = sample; <del> const bytes = [ <del> 0x7A, 0xC2, 0xA2, 0xE6, 0xB0, 0xB4, <del> 0xF0, 0x9D, 0x84, 0x9E, 0xEF, 0xA3, <del> 0xBF, 0xF4, 0x8F, 0xBF, 0xBD, 0xEF, <del> 0xBF, 0xBE <del> ]; <del> const encoded = new TextEncoder().encode(string); <del> assert.deepStrictEqual([].slice.call(encoded), bytes); <del> assert.strictEqual( <del> new TextDecoder(encoding).decode(new Uint8Array(bytes)), <del> string); <del> assert.strictEqual( <del> new TextDecoder(encoding).decode(new Uint8Array(bytes).buffer), <del> string); <del>} <del> <del>testDecodeSample( <del> 'utf-16le', <del> sample, <del> [ <del> 0x7A, 0x00, 0xA2, 0x00, 0x34, 0x6C, <del> 0x34, 0xD8, 0x1E, 0xDD, 0xFF, 0xF8, <del> 0xFF, 0xDB, 0xFD, 0xDF, 0xFE, 0xFF <del> ] <del>); <del> <del>testDecodeSample( <del> 'utf-16be', <del> sample, <del> [ <del> 0x00, 0x7A, 0x00, 0xA2, 0x6C, 0x34, <del> 0xD8, 0x34, 0xDD, 0x1E, 0xF8, 0xFF, <del> 0xDB, 0xFF, 0xDF, 0xFD, 0xFF, 0xFE <del> ] <del>); <del> <del>testDecodeSample( <del> 'utf-16', <del> sample, <del> [ <del> 0x7A, 0x00, 0xA2, 0x00, 0x34, 0x6C, <del> 0x34, 0xD8, 0x1E, 0xDD, 0xFF, 0xF8, <del> 0xFF, 0xDB, 0xFD, 0xDF, 0xFE, 0xFF <del> ] <del>); <ide><path>test/parallel/test-whatwg-encoding-custom-fatal-streaming.js <ide> const common = require('../common'); <ide> if (!common.hasIntl) <ide> common.skip('missing Intl'); <ide> <del>const assert = require('assert'); <del> <ide> { <ide> [ <ide> { encoding: 'utf-8', sequence: [0xC0] }, <ide> const assert = require('assert'); <ide> `The encoded data was not valid for encoding ${testCase.encoding}` <ide> } <ide> ); <del> <del> // TODO(joyeecheung): remove this when WPT is ported <del> assert.strictEqual( <del> new TextDecoder(testCase.encoding).decode(data), <del> '\uFFFD' <del> ); <ide> }); <ide> } <ide> <ide> const assert = require('assert'); <ide> const odd = new Uint8Array([0x00]); <ide> const even = new Uint8Array([0x00, 0x00]); <ide> <del> // TODO(joyeecheung): remove this when WPT is ported <del> assert.strictEqual(decoder.decode(odd, { stream: true }), ''); <del> assert.strictEqual(decoder.decode(odd), '\u0000'); <del> <ide> common.expectsError( <ide> () => { <ide> decoder.decode(even, { stream: true }); <ide> const assert = require('assert'); <ide> 'The encoded data was not valid for encoding utf-16le' <ide> } <ide> ); <del> <del> // TODO(joyeecheung): remove this when WPT is ported <del> assert.strictEqual(decoder.decode(even, { stream: true }), '\u0000'); <del> assert.strictEqual(decoder.decode(even), '\u0000'); <ide> } <ide><path>test/parallel/test-whatwg-encoding-custom-textdecoder-fatal.js <ide> const common = require('../common'); <ide> if (!common.hasIntl) <ide> common.skip('missing Intl'); <ide> <del>const assert = require('assert'); <del> <ide> const bad = [ <ide> { encoding: 'utf-8', input: [0xFF], name: 'invalid code' }, <ide> { encoding: 'utf-8', input: [0xC0], name: 'ends early' }, <ide> bad.forEach((t) => { <ide> } <ide> ); <ide> }); <del> <del>// TODO(joyeecheung): remove this when WPT is ported <del>{ <del> assert('fatal' in new TextDecoder()); <del> assert.strictEqual(typeof new TextDecoder().fatal, 'boolean'); <del> assert(!new TextDecoder().fatal); <del> assert(new TextDecoder('utf-8', { fatal: true }).fatal); <del>} <ide><path>test/parallel/test-whatwg-encoding-custom-textdecoder-utf16-surrogates.js <ide> const common = require('../common'); <ide> if (!common.hasIntl) <ide> common.skip('missing Intl'); <ide> <del>const assert = require('assert'); <del> <ide> const bad = [ <ide> { <ide> encoding: 'utf-16le', <ide> const bad = [ <ide> ]; <ide> <ide> bad.forEach((t) => { <del> // TODO(joyeecheung): remove this when WPT is ported <del> assert.strictEqual( <del> new TextDecoder(t.encoding).decode(new Uint8Array(t.input)), <del> t.expected); <del> <ide> common.expectsError( <ide> () => { <ide> new TextDecoder(t.encoding, { fatal: true }) <ide><path>test/parallel/test-whatwg-encoding-surrogates-utf8.js <del>'use strict'; <del> <del>// From: https://github.com/w3c/web-platform-tests/blob/fa9436d12c/encoding/api-surrogates-utf8.html <del>// TODO(joyeecheung): replace this with WPT <del> <del>require('../common'); <del> <del>const assert = require('assert'); <del> <del>const badStrings = [ <del> { <del> input: 'abc123', <del> expected: [0x61, 0x62, 0x63, 0x31, 0x32, 0x33], <del> decoded: 'abc123', <del> name: 'Sanity check' <del> }, <del> { <del> input: '\uD800', <del> expected: [0xef, 0xbf, 0xbd], <del> decoded: '\uFFFD', <del> name: 'Surrogate half (low)' <del> }, <del> { <del> input: '\uDC00', <del> expected: [0xef, 0xbf, 0xbd], <del> decoded: '\uFFFD', <del> name: 'Surrogate half (high)' <del> }, <del> { <del> input: 'abc\uD800123', <del> expected: [0x61, 0x62, 0x63, 0xef, 0xbf, 0xbd, 0x31, 0x32, 0x33], <del> decoded: 'abc\uFFFD123', <del> name: 'Surrogate half (low), in a string' <del> }, <del> { <del> input: 'abc\uDC00123', <del> expected: [0x61, 0x62, 0x63, 0xef, 0xbf, 0xbd, 0x31, 0x32, 0x33], <del> decoded: 'abc\uFFFD123', <del> name: 'Surrogate half (high), in a string' <del> }, <del> { <del> input: '\uDC00\uD800', <del> expected: [0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd], <del> decoded: '\uFFFD\uFFFD', <del> name: 'Wrong order' <del> } <del>]; <del> <del>badStrings.forEach((t) => { <del> const encoded = new TextEncoder().encode(t.input); <del> assert.deepStrictEqual([].slice.call(encoded), t.expected); <del> assert.strictEqual(new TextDecoder('utf-8').decode(encoded), t.decoded); <del>}); <ide><path>test/parallel/test-whatwg-encoding-textdecoder-ignorebom.js <del>'use strict'; <del> <del>// From: https://github.com/w3c/web-platform-tests/blob/7f567fa29c/encoding/textdecoder-ignorebom.html <del>// TODO(joyeecheung): replace this with WPT <del> <del>const common = require('../common'); <del> <del>if (!common.hasIntl) <del> common.skip('missing Intl'); <del> <del>const assert = require('assert'); <del> <del>const cases = [ <del> { <del> encoding: 'utf-8', <del> bytes: [0xEF, 0xBB, 0xBF, 0x61, 0x62, 0x63] <del> }, <del> { <del> encoding: 'utf-16le', <del> bytes: [0xFF, 0xFE, 0x61, 0x00, 0x62, 0x00, 0x63, 0x00] <del> }, <del> { <del> encoding: 'utf-16be', <del> bytes: [0xFE, 0xFF, 0x00, 0x61, 0x00, 0x62, 0x00, 0x63] <del> } <del>]; <del> <del>cases.forEach((testCase) => { <del> const BOM = '\uFEFF'; <del> let decoder = new TextDecoder(testCase.encoding, { ignoreBOM: true }); <del> const bytes = new Uint8Array(testCase.bytes); <del> assert.strictEqual(decoder.decode(bytes), `${BOM}abc`); <del> decoder = new TextDecoder(testCase.encoding, { ignoreBOM: false }); <del> assert.strictEqual(decoder.decode(bytes), 'abc'); <del> decoder = new TextDecoder(testCase.encoding); <del> assert.strictEqual(decoder.decode(bytes), 'abc'); <del>}); <del> <del>{ <del> assert('ignoreBOM' in new TextDecoder()); <del> assert.strictEqual(typeof new TextDecoder().ignoreBOM, 'boolean'); <del> assert(!new TextDecoder().ignoreBOM); <del> assert(new TextDecoder('utf-8', { ignoreBOM: true }).ignoreBOM); <del>} <ide><path>test/parallel/test-whatwg-encoding-textdecoder-streaming.js <del>'use strict'; <del> <del>// From: https://github.com/w3c/web-platform-tests/blob/fa9436d12c/encoding/textdecoder-streaming.html <del>// TODO(joyeecheung): replace this with WPT <del> <del>const common = require('../common'); <del> <del>if (!common.hasIntl) <del> common.skip('missing Intl'); <del> <del>const assert = require('assert'); <del> <del>const string = <del> '\x00123ABCabc\x80\xFF\u0100\u1000\uFFFD\uD800\uDC00\uDBFF\uDFFF'; <del>const octets = { <del> 'utf-8': [ <del> 0x00, 0x31, 0x32, 0x33, 0x41, 0x42, 0x43, 0x61, 0x62, 0x63, 0xc2, 0x80, <del> 0xc3, 0xbf, 0xc4, 0x80, 0xe1, 0x80, 0x80, 0xef, 0xbf, 0xbd, 0xf0, 0x90, <del> 0x80, 0x80, 0xf4, 0x8f, 0xbf, 0xbf], <del> 'utf-16le': [ <del> 0x00, 0x00, 0x31, 0x00, 0x32, 0x00, 0x33, 0x00, 0x41, 0x00, 0x42, 0x00, <del> 0x43, 0x00, 0x61, 0x00, 0x62, 0x00, 0x63, 0x00, 0x80, 0x00, 0xFF, 0x00, <del> 0x00, 0x01, 0x00, 0x10, 0xFD, 0xFF, 0x00, 0xD8, 0x00, 0xDC, 0xFF, 0xDB, <del> 0xFF, 0xDF], <del> 'utf-16be': [ <del> 0x00, 0x00, 0x00, 0x31, 0x00, 0x32, 0x00, 0x33, 0x00, 0x41, 0x00, 0x42, <del> 0x00, 0x43, 0x00, 0x61, 0x00, 0x62, 0x00, 0x63, 0x00, 0x80, 0x00, 0xFF, <del> 0x01, 0x00, 0x10, 0x00, 0xFF, 0xFD, 0xD8, 0x00, 0xDC, 0x00, 0xDB, 0xFF, <del> 0xDF, 0xFF] <del>}; <del> <del>Object.keys(octets).forEach((encoding) => { <del> if (encoding === 'utf-16be' && !common.hasIntl) { <del> console.log('skipping utf-16be because missing Intl'); <del> return; <del> } <del> for (let len = 1; len <= 5; ++len) { <del> const encoded = octets[encoding]; <del> const decoder = new TextDecoder(encoding); <del> let out = ''; <del> for (let i = 0; i < encoded.length; i += len) { <del> const sub = []; <del> for (let j = i; j < encoded.length && j < i + len; ++j) <del> sub.push(encoded[j]); <del> out += decoder.decode(new Uint8Array(sub), { stream: true }); <del> } <del> out += decoder.decode(); <del> assert.strictEqual(out, string); <del> } <del>}); <ide><path>test/parallel/test-whatwg-encoding-textencoder-utf16-surrogates.js <del>'use strict'; <del> <del>// From: https://github.com/w3c/web-platform-tests/blob/fa9436d12c/encoding/textencoder-utf16-surrogates.html <del>// TODO(joyeecheung): replace this with WPT <del> <del>require('../common'); <del> <del>const assert = require('assert'); <del> <del>const bad = [ <del> { <del> input: '\uD800', <del> expected: '\uFFFD', <del> name: 'lone surrogate lead' <del> }, <del> { <del> input: '\uDC00', <del> expected: '\uFFFD', <del> name: 'lone surrogate trail' <del> }, <del> { <del> input: '\uD800\u0000', <del> expected: '\uFFFD\u0000', <del> name: 'unmatched surrogate lead' <del> }, <del> { <del> input: '\uDC00\u0000', <del> expected: '\uFFFD\u0000', <del> name: 'unmatched surrogate trail' <del> }, <del> { <del> input: '\uDC00\uD800', <del> expected: '\uFFFD\uFFFD', <del> name: 'swapped surrogate pair' <del> }, <del> { <del> input: '\uD834\uDD1E', <del> expected: '\uD834\uDD1E', <del> name: 'properly encoded MUSICAL SYMBOL G CLEF (U+1D11E)' <del> } <del>]; <del> <del>bad.forEach((t) => { <del> const encoded = new TextEncoder().encode(t.input); <del> const decoded = new TextDecoder().decode(encoded); <del> assert.strictEqual(decoded, t.expected); <del>}); <del> <del>assert.strictEqual(new TextEncoder().encode().length, 0);
8
Python
Python
reduce indentation (#741)
8b8a6d881cbda0e6d64aacf5284fbccf27772eec
<ide><path>file_transfer_protocol/ftp_send_receive.py <ide> """ <del> File transfer protocol used to send and receive files using FTP server. <del> Use credentials to provide access to the FTP client <add>File transfer protocol used to send and receive files using FTP server. <add>Use credentials to provide access to the FTP client <ide> <del> Note: Do not use root username & password for security reasons <del> Create a seperate user and provide access to a home directory of the user <del> Use login id and password of the user created <del> cwd here stands for current working directory <add>Note: Do not use root username & password for security reasons <add>Create a seperate user and provide access to a home directory of the user <add>Use login id and password of the user created <add>cwd here stands for current working directory <ide> """ <ide> <ide> from ftplib import FTP <ide> ftp.cwd('/Enter the directory here/') <ide> <ide> """ <del> The file which will be received via the FTP server <del> Enter the location of the file where the file is received <add>The file which will be received via the FTP server <add>Enter the location of the file where the file is received <ide> """ <ide> <ide> def ReceiveFile(): <ide> def ReceiveFile(): <ide> ftp.quit() <ide> <ide> """ <del> The file which will be sent via the FTP server <del> The file send will be send to the current working directory <add>The file which will be sent via the FTP server <add>The file send will be send to the current working directory <ide> """ <ide> <ide> def SendFile():
1
PHP
PHP
improve tests for arguments in ability checks
7ea01d451274e7851e6f3292a84d078cdd06a12a
<ide><path>tests/Auth/AuthAccessGateTest.php <ide> public function test_a_single_argument_can_be_passed_when_checking_abilities() <ide> }); <ide> <ide> $gate->define('foo', function ($user, $x) use ($dummy) { <del> $this->assertEquals($dummy, $x); <add> $this->assertSame($dummy, $x); <ide> <ide> return true; <ide> }); <ide> <add> $gate->after(function ($user, $ability, $result, array $arguments) use ($dummy) { <add> $this->assertCount(1, $arguments); <add> $this->assertSame($dummy, $arguments[0]); <add> }); <add> <ide> $this->assertTrue($gate->check('foo', $dummy)); <ide> } <ide> <ide> public function test_multiple_arguments_can_be_passed_when_checking_abilities() <ide> }); <ide> <ide> $gate->define('foo', function ($user, $x, $y) use ($dummy1, $dummy2) { <del> $this->assertEquals($dummy1, $x); <del> $this->assertEquals($dummy2, $y); <add> $this->assertSame($dummy1, $x); <add> $this->assertSame($dummy2, $y); <ide> <ide> return true; <ide> }); <ide> <add> $gate->after(function ($user, $ability, $result, array $arguments) use ($dummy1, $dummy2) { <add> $this->assertCount(2, $arguments); <add> $this->assertSame([$dummy1, $dummy2], $arguments); <add> }); <add> <ide> $this->assertTrue($gate->check('foo', [$dummy1, $dummy2])); <ide> } <ide>
1
Go
Go
switch skipping from error to debug
af6ab357e8db8888429a28014f629af19a2250b8
<ide><path>server/server.go <ide> func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin <ide> <ide> // ensure no two downloads of the same layer happen at the same time <ide> if c, err := srv.poolAdd("pull", "layer:"+id); err != nil { <del> utils.Errorf("Image (id: %s) pull is already running, skipping: %v", id, err) <add> utils.Debugf("Image (id: %s) pull is already running, skipping: %v", id, err) <ide> <-c <ide> } <ide> defer srv.poolRemove("pull", "layer:"+id) <ide> func (srv *Server) pullRepository(r *registry.Registry, out io.Writer, localName <ide> <-c <ide> out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Download complete", nil)) <ide> } else { <del> utils.Errorf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) <add> utils.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) <ide> } <ide> if parallel { <ide> errors <- nil
1
Ruby
Ruby
compare base with http
bdb61c1dadd64ad4e146228ac8048fd0034fa8cc
<ide><path>actionpack/examples/minimal.rb <ide> require 'action_controller/new_base' if ENV['NEW'] <ide> require 'benchmark' <ide> <del>class BaseController < ActionController::Base <del> def index <del> render :text => '' <del> end <del>end <del> <ide> class Runner <ide> def initialize(app) <ide> @app = app <ide> def report(env, response) <ide> response[2].each { |part| out.puts part } <ide> out.puts '---' <ide> end <add> <add> def self.run(app, n) <add> env = { 'n' => n, 'rack.input' => StringIO.new(''), 'rack.errors' => $stdout } <add> t = Benchmark.realtime { new(app).call(env) } <add> puts "%d ms / %d req = %d usec/req" % [10**3 * t, n, 10**6 * t / n] <add> end <add>end <add> <add> <add>N = (ENV['N'] || 1000).to_i <add> <add>class BasePostController < ActionController::Base <add> def index <add> render :text => '' <add> end <add> <add> Runner.run(action(:index), N) <ide> end <ide> <del>n = (ENV['N'] || 1000).to_i <del>input = StringIO.new('') <add>if ActionController.const_defined?(:Http) <add> class HttpPostController < ActionController::Http <add> def index <add> self.response_body = '' <add> end <ide> <del>elapsed = Benchmark.realtime do <del> Runner.new(BaseController.action(:index)). <del> call('n' => n, 'rack.input' => input, 'rack.errors' => $stdout) <add> Runner.run(action(:index), N) <add> end <ide> end <del>puts "%dms elapsed, %d req/sec, %.2f msec/req" % <del> [1000 * elapsed, n / elapsed, 1000 * elapsed / n]
1
Text
Text
fix a typo [ci skip]
5fc50c20874d4ae5310dc54a3727d70a1ca412b1
<ide><path>guides/source/constant_autoloading_and_reloading.md <ide> role.rb <ide> <ide> modulus some additional directory lookups we are going to cover soon. <ide> <del>INFO. 'Constant::Name'.underscore gives the relative path without extension of <add>INFO. `'Constant::Name'.underscore` gives the relative path without extension of <ide> the file name where `Constant::Name` is expected to be defined. <ide> <ide> Let's see how does Rails autoload the `Post` constant in the `PostsController`
1
Python
Python
remove u from literals
6af31ed3945fd051a6e8c08851d7a656637d1f00
<ide><path>rest_framework/tests/test_renderers.py <ide> def keys(self): <ide> x['a'] = 1 <ide> x['b'] = "string value" <ide> ret = JSONRenderer().render(x) <del> self.assertEquals(json.loads(ret), {u'a': 1, u'b': u'string value'}) <add> self.assertEquals(json.loads(ret), {'a': 1, 'b': 'string value'}) <ide> <ide> def test_render_dict_abc_obj(self): <ide> class Dict(collections.MutableMapping): <ide> def __len__(self): <ide> x['key'] = 'string value' <ide> x[2] = 3 <ide> ret = JSONRenderer().render(x) <del> self.assertEquals(json.loads(ret), {u'key': 'string value', u'2': 3}) <add> self.assertEquals(json.loads(ret), {'key': 'string value', '2': 3}) <ide> <ide> <ide> def test_render_obj_with_getitem(self):
1
PHP
PHP
add $path param for docblock
8c45fba521d318a22387404442e3daa1b2e3e426
<ide><path>src/Illuminate/Support/helpers.php <ide> function asset($path, $secure = null) <ide> /** <ide> * Get the path to the base of the install. <ide> * <add> * @param string $path <ide> * @return string <ide> */ <ide> function base_path($path = '') <ide> function preg_replace_sub($pattern, &$replacements, $subject) <ide> /** <ide> * Get the path to the public folder. <ide> * <add> * @param string $path <ide> * @return string <ide> */ <ide> function public_path($path = '') <ide> function public_path($path = '') <ide> * Generate a URL to a named route. <ide> * <ide> * @param string $route <del> * @param string $parameters <add> * @param array $parameters <ide> * @return string <ide> */ <ide> function route($route, $parameters = array()) <ide> function starts_with($haystack, $needle) <ide> /** <ide> * Get the path to the storage folder. <ide> * <add> * @param string $path <ide> * @return string <ide> */ <ide> function storage_path($path = '')
1
Text
Text
add 2.9.0-beta.4 to changelog.md
9449635a147c4761276e63178a03eb62d5b8a4fe
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### 2.9.0-beta.4 (September 28, 2016) <add> <add>- [#14361](https://github.com/emberjs/ember.js/pull/14361) [BUGFIX] Prevent usage of `this.element` when running in a non-interactive environment (i.e. FastBoot). <add>- [#14361](https://github.com/emberjs/ember.js/pull/14361) [BUGFIX] Prevent `willRender` and `willUpdate` from running in FastBoot. <add>- [#14344](https://github.com/emberjs/ember.js/pull/14344) [BUGFIX] Ensure `element` is present in `willInsertElement` hook. <add>- [#14345](https://github.com/emberjs/ember.js/pull/14345) [BUGFIX] Fix an issue causing unneeded rerenders with closure actions. <add>- [#14363](https://github.com/emberjs/ember.js/pull/14363) [BUGFIX] Always use `guidFor` for tagless component's with an `id`. <add>- [#14365](https://github.com/emberjs/ember.js/pull/14365) [BUGFIX] Bump route-recognizer to fix an issue with encoding `/` in a dynamic segment. <add>- [#14366](https://github.com/emberjs/ember.js/pull/14366) [BUGFIX] Fix `Ember.assign` export. <add>- [#14367](https://github.com/emberjs/ember.js/pull/14367) [BUGFIX] Ensure feature flags are properly stripped. <add>- [#14371](https://github.com/emberjs/ember.js/pull/14371) [BUGFIX] Lazily add `alias` dependent keys (correct a slight performance regression from [#14319](https://github.com/emberjs/ember.js/pull/14319)). <add> <ide> ### 2.9.0-beta.3 (September 20, 2016) <ide> <ide> - [#14313](https://github.com/emberjs/ember.js/pull/14313) [BUGFIX] Ensure `id` attribute bindings of `undefined` are handled properly.
1
Python
Python
fix issue with docutils < 0.5
2951b794d0b6498c5d6b2fd8c0f188a447bd8d14
<ide><path>doc/sphinxext/numpydoc.py <ide> def setup(app, get_doc_object_=get_doc_object): <ide> from docutils.statemachine import ViewList <ide> <ide> def get_directive(name): <del> from docutils.parsers.rst.directives import directive <add> from docutils.parsers.rst import directives <ide> try: <del> return directive(name, None, None)[0] <add> # docutils 0.4 <add> return directives._directives[name] <add> except (AttributeError, KeyError): <add> pass <add> try: <add> return directives.directive(name, None, None)[0] <ide> except AttributeError: <del> return None <del> <add> raise RuntimeError("No directive named '%s' found" % name) <add> <ide> def wrap_mangling_directive(base_directive_name, objtype): <ide> base_directive = get_directive(base_directive_name) <ide>
1
Go
Go
use event functions from golang.org/x/sys/windows
e942513ac46656c3f54cd103e990e2b7bd5c2b14
<ide><path>cmd/dockerd/daemon_windows.go <ide> import ( <ide> "path/filepath" <ide> <ide> "github.com/docker/docker/libcontainerd" <del> "github.com/docker/docker/pkg/system" <ide> "github.com/sirupsen/logrus" <ide> "golang.org/x/sys/windows" <ide> ) <ide> func (cli *DaemonCli) setupConfigReloadTrap() { <ide> sa := windows.SecurityAttributes{ <ide> Length: 0, <ide> } <del> ev := "Global\\docker-daemon-config-" + fmt.Sprint(os.Getpid()) <del> if h, _ := system.CreateEvent(&sa, false, false, ev); h != 0 { <add> ev, _ := windows.UTF16PtrFromString("Global\\docker-daemon-config-" + fmt.Sprint(os.Getpid())) <add> if h, _ := windows.CreateEvent(&sa, 0, 0, ev); h != 0 { <ide> logrus.Debugf("Config reload - waiting signal at %s", ev) <ide> for { <ide> windows.WaitForSingleObject(h, windows.INFINITE) <ide><path>daemon/debugtrap_windows.go <ide> import ( <ide> <ide> winio "github.com/Microsoft/go-winio" <ide> "github.com/docker/docker/pkg/signal" <del> "github.com/docker/docker/pkg/system" <ide> "github.com/sirupsen/logrus" <ide> "golang.org/x/sys/windows" <ide> ) <ide> func (d *Daemon) setupDumpStackTrap(root string) { <ide> // Windows does not support signals like *nix systems. So instead of <ide> // trapping on SIGUSR1 to dump stacks, we wait on a Win32 event to be <ide> // signaled. ACL'd to builtin administrators and local system <del> ev := "Global\\docker-daemon-" + fmt.Sprint(os.Getpid()) <add> ev, _ := windows.UTF16PtrFromString("Global\\docker-daemon-" + fmt.Sprint(os.Getpid())) <ide> sd, err := winio.SddlToSecurityDescriptor("D:P(A;;GA;;;BA)(A;;GA;;;SY)") <ide> if err != nil { <ide> logrus.Errorf("failed to get security descriptor for debug stackdump event %s: %s", ev, err.Error()) <ide> func (d *Daemon) setupDumpStackTrap(root string) { <ide> sa.Length = uint32(unsafe.Sizeof(sa)) <ide> sa.InheritHandle = 1 <ide> sa.SecurityDescriptor = uintptr(unsafe.Pointer(&sd[0])) <del> h, err := system.CreateEvent(&sa, false, false, ev) <add> h, err := windows.CreateEvent(&sa, 0, 0, ev) <ide> if h == 0 || err != nil { <ide> logrus.Errorf("failed to create debug stackdump event %s: %s", ev, err.Error()) <ide> return <ide><path>integration-cli/daemon/daemon_windows.go <ide> package daemon <ide> import ( <ide> "fmt" <ide> "strconv" <del> "syscall" <del> "unsafe" <ide> <ide> "github.com/go-check/check" <ide> "golang.org/x/sys/windows" <ide> ) <ide> <del>func openEvent(desiredAccess uint32, inheritHandle bool, name string, proc *windows.LazyProc) (handle windows.Handle, err error) { <del> namep, _ := windows.UTF16PtrFromString(name) <del> var _p2 uint32 <del> if inheritHandle { <del> _p2 = 1 <del> } <del> r0, _, e1 := proc.Call(uintptr(desiredAccess), uintptr(_p2), uintptr(unsafe.Pointer(namep))) <del> handle = windows.Handle(r0) <del> if handle == windows.InvalidHandle { <del> err = e1 <del> } <del> return <del>} <del> <del>func pulseEvent(handle windows.Handle, proc *windows.LazyProc) (err error) { <del> r0, _, _ := proc.Call(uintptr(handle)) <del> if r0 != 0 { <del> err = syscall.Errno(r0) <del> } <del> return <del>} <del> <ide> // SignalDaemonDump sends a signal to the daemon to write a dump file <ide> func SignalDaemonDump(pid int) { <del> modkernel32 := windows.NewLazySystemDLL("kernel32.dll") <del> procOpenEvent := modkernel32.NewProc("OpenEventW") <del> procPulseEvent := modkernel32.NewProc("PulseEvent") <del> <del> ev := "Global\\docker-daemon-" + strconv.Itoa(pid) <del> h2, _ := openEvent(0x0002, false, ev, procOpenEvent) <del> if h2 == 0 { <add> ev, _ := windows.UTF16PtrFromString("Global\\docker-daemon-" + strconv.Itoa(pid)) <add> h2, err := windows.OpenEvent(0x0002, false, ev) <add> if h2 == 0 || err != nil { <ide> return <ide> } <del> pulseEvent(h2, procPulseEvent) <add> windows.PulseEvent(h2) <ide> } <ide> <ide> func signalDaemonReload(pid int) error { <ide><path>pkg/system/events_windows.go <del>package system <del> <del>// This file implements syscalls for Win32 events which are not implemented <del>// in golang. <del> <del>import ( <del> "syscall" <del> "unsafe" <del> <del> "golang.org/x/sys/windows" <del>) <del> <del>var ( <del> procCreateEvent = modkernel32.NewProc("CreateEventW") <del> procOpenEvent = modkernel32.NewProc("OpenEventW") <del> procSetEvent = modkernel32.NewProc("SetEvent") <del> procResetEvent = modkernel32.NewProc("ResetEvent") <del> procPulseEvent = modkernel32.NewProc("PulseEvent") <del>) <del> <del>// CreateEvent implements win32 CreateEventW func in golang. It will create an event object. <del>func CreateEvent(eventAttributes *windows.SecurityAttributes, manualReset bool, initialState bool, name string) (handle windows.Handle, err error) { <del> namep, _ := windows.UTF16PtrFromString(name) <del> var _p1 uint32 <del> if manualReset { <del> _p1 = 1 <del> } <del> var _p2 uint32 <del> if initialState { <del> _p2 = 1 <del> } <del> r0, _, e1 := procCreateEvent.Call(uintptr(unsafe.Pointer(eventAttributes)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(namep))) <del> use(unsafe.Pointer(namep)) <del> handle = windows.Handle(r0) <del> if handle == windows.InvalidHandle { <del> err = e1 <del> } <del> return <del>} <del> <del>// OpenEvent implements win32 OpenEventW func in golang. It opens an event object. <del>func OpenEvent(desiredAccess uint32, inheritHandle bool, name string) (handle windows.Handle, err error) { <del> namep, _ := windows.UTF16PtrFromString(name) <del> var _p1 uint32 <del> if inheritHandle { <del> _p1 = 1 <del> } <del> r0, _, e1 := procOpenEvent.Call(uintptr(desiredAccess), uintptr(_p1), uintptr(unsafe.Pointer(namep))) <del> use(unsafe.Pointer(namep)) <del> handle = windows.Handle(r0) <del> if handle == windows.InvalidHandle { <del> err = e1 <del> } <del> return <del>} <del> <del>// SetEvent implements win32 SetEvent func in golang. <del>func SetEvent(handle windows.Handle) (err error) { <del> return setResetPulse(handle, procSetEvent) <del>} <del> <del>// ResetEvent implements win32 ResetEvent func in golang. <del>func ResetEvent(handle windows.Handle) (err error) { <del> return setResetPulse(handle, procResetEvent) <del>} <del> <del>// PulseEvent implements win32 PulseEvent func in golang. <del>func PulseEvent(handle windows.Handle) (err error) { <del> return setResetPulse(handle, procPulseEvent) <del>} <del> <del>func setResetPulse(handle windows.Handle, proc *windows.LazyProc) (err error) { <del> r0, _, _ := proc.Call(uintptr(handle)) <del> if r0 != 0 { <del> err = syscall.Errno(r0) <del> } <del> return <del>} <del> <del>var temp unsafe.Pointer <del> <del>// use ensures a variable is kept alive without the GC freeing while still needed <del>func use(p unsafe.Pointer) { <del> temp = p <del>}
4
Python
Python
change version to 2.8
29298a4f9a8bd2712a1f754595066c478d2b75ee
<ide><path>glances/__init__.py <ide> import sys <ide> <ide> # Global name <del>__version__ = '2.8_DEVELOP' <add>__version__ = '2.8' <ide> __author__ = 'Nicolas Hennion <[email protected]>' <ide> __license__ = 'LGPL' <ide>
1
PHP
PHP
apply fixes from styleci
bfa6e3c948ec2aaf41486da6021061d1ea09e24c
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php <ide> namespace Illuminate\Foundation\Testing; <ide> <ide> use Closure; <del>use Illuminate\Support\Str; <ide> use Illuminate\Http\Response; <ide> use Illuminate\Contracts\View\View; <ide> use PHPUnit_Framework_Assert as PHPUnit;
1
Ruby
Ruby
use temporary_path accessor
4a2fc89c4699f3c5e4ad93f9d7c26698c4a0c989
<ide><path>Library/Homebrew/download_strategy.rb <ide> def _fetch <ide> s3url = obj.public_url <ide> end <ide> <del> curl s3url, '-C', downloaded_size, '-o', @temporary_path <add> curl s3url, '-C', downloaded_size, '-o', temporary_path <ide> end <ide> end <ide>
1
Go
Go
return error when listnode fails
8e04e9902a9739a13e5e824339082cc3d361d097
<ide><path>cli/command/system/info.go <ide> func prettyPrintInfo(dockerCli *command.DockerCli, info types.Info) error { <ide> fmt.Fprintf(dockerCli.Out(), " Error: %v\n", info.Swarm.Error) <ide> } <ide> fmt.Fprintf(dockerCli.Out(), " Is Manager: %v\n", info.Swarm.ControlAvailable) <del> if info.Swarm.ControlAvailable { <add> if info.Swarm.ControlAvailable && info.Swarm.Error == "" && info.Swarm.LocalNodeState != swarm.LocalNodeStateError { <ide> fmt.Fprintf(dockerCli.Out(), " ClusterID: %s\n", info.Swarm.Cluster.ID) <ide> fmt.Fprintf(dockerCli.Out(), " Managers: %d\n", info.Swarm.Managers) <ide> fmt.Fprintf(dockerCli.Out(), " Nodes: %d\n", info.Swarm.Nodes) <ide><path>daemon/cluster/cluster.go <ide> func (c *Cluster) Info() types.Info { <ide> // Strip JoinTokens <ide> info.Cluster = swarm.ClusterInfo <ide> <del> if r, err := state.controlClient.ListNodes(ctx, &swarmapi.ListNodesRequest{}); err == nil { <add> if r, err := state.controlClient.ListNodes(ctx, &swarmapi.ListNodesRequest{}); err != nil { <add> info.Error = err.Error() <add> } else { <ide> info.Nodes = len(r.Nodes) <ide> for _, n := range r.Nodes { <ide> if n.ManagerStatus != nil {
2
Ruby
Ruby
fix build error caused by
5c6e11d6b89444eefcb12e24d5419dadefdea1ba
<ide><path>railties/test/application/rake/notes_test.rb <ide> def teardown <ide> assert_match(/note in less/, output) <ide> assert_match(/note in rake/, output) <ide> <del> assert_equal 10, lines.size <add> assert_equal 11, lines.size <ide> <ide> lines.each do |line| <ide> assert_equal 4, line[0].size
1
Python
Python
use nvidia-ml-py3 for python3 compatibility
1cf84dfcef7f59435ccf10d2e4afd7bb8aeef948
<ide><path>setup.py <ide> def run(self): <ide> 'influxdb>=1.0.0', 'kafka-python', 'pika', 'potsdb', <ide> 'prometheus_client', 'pyzmq', 'statsd'], <ide> 'folders': ['scandir'], # python_version<"3.5" <del> 'gpu': ['nvidia-ml-py'], # python_version=="2.7" <add> 'gpu': ['nvidia-ml-py3'], # python_version=="2.7" <ide> 'graph': ['pygal'], <ide> 'ip': ['netifaces'], <ide> 'raid': ['pymdstat'],
1
Go
Go
show usage when global --help present
4d55877e278ea62b98927c6b9fb23b4b935431c1
<ide><path>docker/daemon.go <ide> func handleGlobalDaemonFlag() { <ide> } <ide> <ide> if *flDaemon { <del> if *flHelp { <del> // We do not show the help output here, instead, we tell the user about the new daemon command, <del> // because the help output is so long they would not see the warning anyway. <del> fmt.Fprintln(os.Stderr, "Please use 'docker daemon --help' instead.") <del> os.Exit(0) <del> } <ide> daemonCli.(*DaemonCli).CmdDaemon(flag.Args()...) <ide> os.Exit(0) <ide> } <ide><path>docker/docker.go <ide> func main() { <ide> return <ide> } <ide> <del> clientCli := client.NewDockerCli(stdin, stdout, stderr, clientFlags) <del> // TODO: remove once `-d` is retired <del> handleGlobalDaemonFlag() <del> <ide> if *flHelp { <ide> // if global flag --help is present, regardless of what other options and commands there are, <ide> // just print the usage. <ide> flag.Usage() <ide> return <ide> } <ide> <add> // TODO: remove once `-d` is retired <add> handleGlobalDaemonFlag() <add> clientCli := client.NewDockerCli(stdin, stdout, stderr, clientFlags) <add> <ide> c := cli.New(clientCli, daemonCli) <ide> if err := c.Run(flag.Args()...); err != nil { <ide> if sterr, ok := err.(cli.StatusError); ok {
2
Text
Text
fix broken url to event loop guide
0674771f233bd79ea2d9c61e072a89487321f533
<ide><path>doc/api/timers.md <ide> added: v0.0.1 <ide> Cancels a `Timeout` object created by [`setTimeout()`][]. <ide> <ide> <del>[the Node.js Event Loop]: https://github.com/nodejs/node/blob/master/doc/topics/event-loop-timers-and-nexttick.md <add>[the Node.js Event Loop]: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick <ide> [`TypeError`]: errors.html#errors_class_typeerror <ide> [`clearImmediate()`]: timers.html#timers_clearimmediate_immediate <ide> [`clearInterval()`]: timers.html#timers_clearinterval_timeout
1
PHP
PHP
has/get
41aec8abcc86e1bee4d72c3bb86173368458df11
<ide><path>src/Illuminate/Support/Arr.php <ide> public static function get($array, $key, $default = null) <ide> return $array; <ide> } <ide> <del> if (isset($array[$key])) { <add> if (static::exists($array, $key)) { <ide> return $array[$key]; <ide> } <ide> <ide> public static function has($array, $key) <ide> return false; <ide> } <ide> <del> if (array_key_exists($key, $array)) { <add> if (static::exists($array, $key)) { <ide> return true; <ide> } <ide>
1
Python
Python
fix mkl for linux
7cebe883b612efe2a3bf51b83917ea6cdb8f679f
<ide><path>numpy/distutils/fcompiler/intel.py <ide> def get_flags(self): <ide> return ['-fPIC'] <ide> <ide> def get_flags_opt(self): <del> return ['-xhost -openmp -fp-model strict'] <add> return ['-xhost -openmp -fp-model strict -O1'] <ide> <ide> def get_flags_arch(self): <ide> return [] <ide> def get_flags(self): <ide> return ['-fPIC'] <ide> <ide> def get_flags_opt(self): <del> return ['-openmp -fp-model strict'] <add> return ['-openmp -fp-model strict -O1'] <ide> <ide> def get_flags_arch(self): <ide> return ['-xSSE4.2']
1
Text
Text
update infobox [ci skip]
2a3a4565cdc5c18725673484a493d03836f3a149
<ide><path>website/docs/usage/index.md <ide> $ pip install -U spacy <ide> <ide> <Infobox variant="warning"> <ide> <del>To install additional data tables for lemmatization in **spaCy v2.2+** (to <del>create blank models or lemmatize in languages that don't yet come with <del>pre-trained models), you can run `pip install spacy[lookups]` or install <add>To install additional data tables for lemmatization in **spaCy v2.2+** you can <add>run `pip install spacy[lookups]` or install <ide> [`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data) <del>separately. <add>separately. The lookups package is needed to create blank models with <add>lemmatization data, or to lemmatize in languages that don't yet come with <add>pre-trained models and aren't powered by third-party libraries. <ide> <ide> </Infobox> <ide>
1
Go
Go
normalize values for pids-limit
ffa1728d4bc7c9c662c6090e48d438bc728df5dc
<ide><path>api/server/router/container/container_routes.go <ide> func (s *containerRouter) postContainerUpdate(ctx context.Context, w http.Respon <ide> if versions.LessThan(httputils.VersionFromContext(ctx), "1.40") { <ide> updateConfig.PidsLimit = nil <ide> } <add> if updateConfig.PidsLimit != nil && *updateConfig.PidsLimit <= 0 { <add> // Both `0` and `-1` are accepted to set "unlimited" when updating. <add> // Historically, any negative value was accepted, so treat them as <add> // "unlimited" as well. <add> var unlimited int64 <add> updateConfig.PidsLimit = &unlimited <add> } <ide> <ide> hostConfig := &container.HostConfig{ <ide> Resources: updateConfig.Resources, <ide> func (s *containerRouter) postContainersCreate(ctx context.Context, w http.Respo <ide> hostConfig.Capabilities = nil <ide> } <ide> <add> if hostConfig != nil && hostConfig.PidsLimit != nil && *hostConfig.PidsLimit <= 0 { <add> // Don't set a limit if either no limit was specified, or "unlimited" was <add> // explicitly set. <add> // Both `0` and `-1` are accepted as "unlimited", and historically any <add> // negative value was accepted, so treat those as "unlimited" as well. <add> hostConfig.PidsLimit = nil <add> } <add> <ide> ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{ <ide> Name: name, <ide> Config: config, <ide><path>daemon/daemon_unix.go <ide> func getMemoryResources(config containertypes.Resources) *specs.LinuxMemory { <ide> } <ide> <ide> func getPidsLimit(config containertypes.Resources) *specs.LinuxPids { <del> limit := &specs.LinuxPids{} <del> if config.PidsLimit != nil { <del> limit.Limit = *config.PidsLimit <del> if limit.Limit == 0 { <del> // docker API allows 0 to unset this to be consistent with default values. <del> // when updating values, runc requires -1 <del> limit.Limit = -1 <del> } <add> if config.PidsLimit == nil { <add> return nil <ide> } <del> return limit <add> if *config.PidsLimit <= 0 { <add> // docker API allows 0 and negative values to unset this to be consistent <add> // with default values. When updating values, runc requires -1 to unset <add> // the previous limit. <add> return &specs.LinuxPids{Limit: -1} <add> } <add> return &specs.LinuxPids{Limit: *config.PidsLimit} <ide> } <ide> <ide> func getCPUResources(config containertypes.Resources) (*specs.LinuxCPU, error) { <ide> func verifyPlatformContainerResources(resources *containertypes.Resources, sysIn <ide> if resources.OomKillDisable != nil && *resources.OomKillDisable && resources.Memory == 0 { <ide> warnings = append(warnings, "OOM killer is disabled for the container, but no memory limit is set, this can result in the system running out of resources.") <ide> } <del> if resources.PidsLimit != nil && *resources.PidsLimit != 0 && !sysInfo.PidsLimit { <del> warnings = append(warnings, "Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.") <del> var limit int64 <del> resources.PidsLimit = &limit <add> if resources.PidsLimit != nil && !sysInfo.PidsLimit { <add> if *resources.PidsLimit > 0 { <add> warnings = append(warnings, "Your kernel does not support PIDs limit capabilities or the cgroup is not mounted. PIDs limit discarded.") <add> } <add> resources.PidsLimit = nil <ide> } <ide> <ide> // cpu subsystem checks and adjustments <ide><path>integration/container/update_linux_test.go <ide> func TestUpdatePidsLimit(t *testing.T) { <ide> {desc: "update lower", update: intPtr(16), expect: 16, expectCg: "16"}, <ide> {desc: "update on old api ignores value", oldAPI: true, update: intPtr(10), expect: 16, expectCg: "16"}, <ide> {desc: "unset limit", update: intPtr(0), expect: 0, expectCg: "max"}, <add> {desc: "reset", update: intPtr(32), expect: 32, expectCg: "32"}, <add> {desc: "unset limit with minus one", update: intPtr(-1), expect: 0, expectCg: "max"}, <add> {desc: "reset", update: intPtr(32), expect: 32, expectCg: "32"}, <add> {desc: "unset limit with minus two", update: intPtr(-2), expect: 0, expectCg: "max"}, <ide> } { <ide> c := apiClient <ide> if test.oldAPI {
3
Go
Go
replace string.contains* with net.ip.to4() check
ec7df9373108899ba8472cdb0a8fefccd25a04c0
<ide><path>libnetwork/drivers/bridge/port_mapping.go <ide> import ( <ide> "errors" <ide> "fmt" <ide> "net" <del> "strings" <ide> <ide> "github.com/docker/libnetwork/types" <ide> "github.com/ishidawataru/sctp" <ide> func (n *bridgeNetwork) releasePort(bnd types.PortBinding) error { <ide> <ide> portmapper := n.portMapper <ide> <del> if strings.ContainsAny(host.String(), "]") == true { <add> if bnd.HostIP.To4() == nil { <ide> portmapper = n.portMapperV6 <ide> } <ide> <ide><path>libnetwork/drivers/bridge/setup_ip_tables.go <ide> import ( <ide> "errors" <ide> "fmt" <ide> "net" <del> "strings" <ide> <ide> "github.com/docker/libnetwork/iptables" <ide> "github.com/sirupsen/logrus" <ide> type iptRule struct { <ide> args []string <ide> } <ide> <del>func setupIPTablesInternal(hostIP net.IP, bridgeIface string, addr net.Addr, icc, ipmasq, hairpin, enable bool) error { <add>func setupIPTablesInternal(hostIP net.IP, bridgeIface string, addr *net.IPNet, icc, ipmasq, hairpin, enable bool) error { <ide> <ide> var ( <ide> address = addr.String() <ide> func setupIPTablesInternal(hostIP net.IP, bridgeIface string, addr net.Addr, icc <ide> <ide> ipVersion := iptables.IPv4 <ide> <del> if strings.Contains(address, ":") { <add> if addr.IP.To4() == nil { <ide> ipVersion = iptables.IPv6 <ide> } <ide> <ide> func removeIPChains(version iptables.IPVersion) { <ide> } <ide> } <ide> <del>func setupInternalNetworkRules(bridgeIface string, addr net.Addr, icc, insert bool) error { <add>func setupInternalNetworkRules(bridgeIface string, addr *net.IPNet, icc, insert bool) error { <ide> var ( <ide> inDropRule = iptRule{table: iptables.Filter, chain: IsolationChain1, args: []string{"-i", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"}} <ide> outDropRule = iptRule{table: iptables.Filter, chain: IsolationChain1, args: []string{"-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"}} <ide> ) <ide> <ide> version := iptables.IPv4 <ide> <del> if strings.Contains(addr.String(), ":") { <add> if addr.IP.To4() == nil { <ide> version = iptables.IPv6 <ide> } <ide>
2
Javascript
Javascript
add test for getmixer, getclip & getroot
c802a474795da6d60ae82533e57e138e76d0f5c4
<ide><path>test/unit/src/animation/AnimationAction.tests.js <ide> import { LoopOnce, LoopRepeat, LoopPingPong } from '../../../../src/constants'; <ide> <ide> function createAnimation(){ <ide> <del> <del> var mixer = new AnimationMixer(new Object3D()); <add> var root = new Object3D(); <add> var mixer = new AnimationMixer(root); <ide> var track = new NumberKeyframeTrack( ".rotation[x]", [ 0, 1000 ], [ 0, 360 ] ); <ide> var clip = new AnimationClip( "clip1", 1000, [track] ); <ide> <del> var animationAction = new AnimationAction( mixer, clip ); <del> return { mixer :mixer,track:track,clip:clip,animationAction:animationAction}; <add> var animationAction = mixer.clipAction( clip ); <add> return { <add> root: root, <add> mixer: mixer, <add> track: track, <add> clip: clip, <add> animationAction: animationAction <add> }; <ide> <ide> } <ide> <ide> export default QUnit.module( 'Animation', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( "getMixer", ( assert ) => { <add> QUnit.test( "getMixer", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var { mixer, animationAction } = createAnimation(); <add> var mixer2 = animationAction.getMixer(); <add> assert.equal( mixer, mixer2, "mixer should be returned by getMixer." ); <ide> <ide> } ); <ide> <del> QUnit.todo( "getClip", ( assert ) => { <add> QUnit.test("getClip", (assert) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var { clip, animationAction } = createAnimation(); <add> var clip2 = animationAction.getClip(); <add> assert.equal( clip, clip2, "clip should be returned by getClip." ); <ide> <ide> } ); <ide> <del> QUnit.todo( "getRoot", ( assert ) => { <add> QUnit.test( "getRoot", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var { root, animationAction } = createAnimation(); <add> var root2 = animationAction.getRoot(); <add> assert.equal(root, root2, "root should be returned by getRoot." ); <ide> <ide> } ); <ide>
1
Python
Python
use closing context on mp pool
d5a242e9f6c17a60bbbc7bd114b34ba59dfcca29
<ide><path>keras/utils/data_utils.py <ide> import traceback <ide> import zipfile <ide> from abc import abstractmethod <add>from contextlib import closing <ide> from multiprocessing.pool import ThreadPool <ide> <ide> import numpy as np <ide> def __init__(self, sequence, <ide> self.use_multiprocessing = use_multiprocessing <ide> self.shuffle = shuffle <ide> self.workers = 0 <del> self.executor = None <add> self.executor_fn = None <ide> self.queue = None <ide> self.run_thread = None <ide> self.stop_signal = None <ide> def start(self, workers=1, max_queue_size=10): <ide> (when full, workers could block on `put()`) <ide> """ <ide> if self.use_multiprocessing: <del> self.executor = multiprocessing.Pool(workers) <add> self.executor_fn = lambda: multiprocessing.Pool(workers) <ide> else: <del> self.executor = ThreadPool(workers) <add> self.executor_fn = lambda: ThreadPool(workers) <ide> self.workers = workers <ide> self.queue = queue.Queue(max_queue_size) <ide> self.stop_signal = threading.Event() <ide> def _run(self): <ide> while True: <ide> if self.shuffle: <ide> random.shuffle(sequence) <del> for i in sequence: <del> if self.stop_signal.is_set(): <del> return <del> self.queue.put( <del> self.executor.apply_async(get_index, (self.uid, i)), block=True) <ide> <del> # Done with the current epoch, waiting for the final batches <del> self._wait_queue() <add> with closing(self.executor_fn()) as executor: <add> for i in sequence: <add> if self.stop_signal.is_set(): <add> return <add> self.queue.put( <add> executor.apply_async(get_index, (self.uid, i)), block=True) <ide> <del> if self.stop_signal.is_set(): <del> # We're done <del> return <add> # Done with the current epoch, waiting for the final batches <add> self._wait_queue() <add> <add> if self.stop_signal.is_set(): <add> # We're done <add> return <ide> <ide> # Call the internal on epoch end. <ide> self.sequence.on_epoch_end() <ide> def _send_sequence(self): <ide> global _SHARED_SEQUENCES <ide> _SHARED_SEQUENCES[self.uid] = self.sequence # For new processes that may spawn <ide> <del> self._close_pool() <del> if self.use_multiprocessing: <del> self.executor = multiprocessing.Pool(self.workers) <del> else: <del> self.executor = ThreadPool(self.workers) <del> <ide> def stop(self, timeout=None): <ide> """Stops running threads and wait for them to exit, if necessary. <ide> <ide> def stop(self, timeout=None): <ide> self.queue.queue.clear() <ide> self.queue.unfinished_tasks = 0 <ide> self.queue.not_full.notify() <del> self._close_pool() <ide> self.run_thread.join(timeout) <ide> _SHARED_SEQUENCES[self.uid] = None <ide> <del> def _close_pool(self): <del> self.executor.close() <del> self.executor.join() <del> <ide> <ide> class GeneratorEnqueuer(SequenceEnqueuer): <ide> """Builds a queue out of a data generator.
1
PHP
PHP
move deprecation closer to where it happens
da4b8bc89788898426e77fdfd2e524160ea5d631
<ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> public function __construct($errorHandler = []) <ide> return; <ide> } <ide> if ($errorHandler instanceof ErrorHandler) { <add> deprecationWarning( <add> 'Using an `ErrorHandler` is deprecated. You should migate to the `ExceptionTrap` sub-system instead.' <add> ); <ide> $this->errorHandler = $errorHandler; <ide> <ide> return; <ide> public function __construct($errorHandler = []) <ide> return; <ide> } <ide> throw new InvalidArgumentException(sprintf( <del> '$errorHandler argument must be a config array, ExceptionTrap or ErrorHandler instance. Got `%s` instead.', <add> '$errorHandler argument must be a config array or ExceptionTrap instance. Got `%s` instead.', <ide> getTypeName($errorHandler) <ide> )); <ide> } <ide> protected function handleInternalError(): ResponseInterface <ide> protected function getErrorHandler(): ErrorHandler <ide> { <ide> if ($this->errorHandler === null) { <del> deprecationWarning( <del> 'Using an `ErrorHandler` is deprecated. You should migate to the `ExceptionTrap` sub-system instead.' <del> ); <ide> /** @var class-string<\Cake\Error\ErrorHandler> $className */ <ide> $className = App::className('ErrorHandler', 'Error'); <ide> $this->errorHandler = new $className($this->getConfig()); <ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php <ide> public function testConstructorInvalid(): void <ide> { <ide> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage( <del> '$errorHandler argument must be a config array, ExceptionTrap or ErrorHandler' <add> '$errorHandler argument must be a config array or ExceptionTrap' <ide> ); <ide> new ErrorHandlerMiddleware('nope'); <ide> } <ide> public function testNoErrorResponse(): void <ide> */ <ide> public function testRendererFactory(): void <ide> { <del> $request = ServerRequestFactory::fromGlobals(); <del> <del> $factory = function ($exception) { <del> $this->assertInstanceOf('LogicException', $exception); <del> $response = new Response(); <del> $mock = $this->getMockBuilder(ExceptionRendererInterface::class) <del> ->onlyMethods(['render']) <del> ->getMock(); <del> $mock->expects($this->once()) <del> ->method('render') <del> ->will($this->returnValue($response)); <del> <del> return $mock; <del> }; <del> $middleware = new ErrorHandlerMiddleware(new ErrorHandler([ <del> 'exceptionRenderer' => $factory, <del> ])); <del> $handler = new TestRequestHandler(function (): void { <del> throw new LogicException('Something bad'); <add> $this->deprecated(function () { <add> $request = ServerRequestFactory::fromGlobals(); <add> <add> $factory = function ($exception) { <add> $this->assertInstanceOf('LogicException', $exception); <add> $response = new Response(); <add> $mock = $this->getMockBuilder(ExceptionRendererInterface::class) <add> ->onlyMethods(['render']) <add> ->getMock(); <add> $mock->expects($this->once()) <add> ->method('render') <add> ->will($this->returnValue($response)); <add> <add> return $mock; <add> }; <add> $middleware = new ErrorHandlerMiddleware(new ErrorHandler([ <add> 'exceptionRenderer' => $factory, <add> ])); <add> $handler = new TestRequestHandler(function (): void { <add> throw new LogicException('Something bad'); <add> }); <add> $middleware->process($request, $handler); <ide> }); <del> $middleware->process($request, $handler); <ide> } <ide> <ide> /** <ide> public function testHandleExceptionLogAttributes(): void <ide> */ <ide> public function testHandleExceptionRenderingFails(): void <ide> { <del> $request = ServerRequestFactory::fromGlobals(); <del> <del> $factory = function ($exception) { <del> $mock = $this->getMockBuilder(ExceptionRendererInterface::class) <del> ->onlyMethods(['render']) <del> ->getMock(); <del> $mock->expects($this->once()) <del> ->method('render') <del> ->will($this->throwException(new LogicException('Rendering failed'))); <del> <del> return $mock; <del> }; <del> $middleware = new ErrorHandlerMiddleware(new ErrorHandler([ <del> 'exceptionRenderer' => $factory, <del> ])); <del> $handler = new TestRequestHandler(function (): void { <del> throw new ServiceUnavailableException('whoops'); <add> $this->deprecated(function () { <add> $request = ServerRequestFactory::fromGlobals(); <add> <add> $factory = function ($exception) { <add> $mock = $this->getMockBuilder(ExceptionRendererInterface::class) <add> ->onlyMethods(['render']) <add> ->getMock(); <add> $mock->expects($this->once()) <add> ->method('render') <add> ->will($this->throwException(new LogicException('Rendering failed'))); <add> <add> return $mock; <add> }; <add> $middleware = new ErrorHandlerMiddleware(new ErrorHandler([ <add> 'exceptionRenderer' => $factory, <add> ])); <add> $handler = new TestRequestHandler(function (): void { <add> throw new ServiceUnavailableException('whoops'); <add> }); <add> $response = $middleware->process($request, $handler); <add> $this->assertSame(500, $response->getStatusCode()); <add> $this->assertSame('An Internal Server Error Occurred', '' . $response->getBody()); <ide> }); <del> $response = $middleware->process($request, $handler); <del> $this->assertSame(500, $response->getStatusCode()); <del> $this->assertSame('An Internal Server Error Occurred', '' . $response->getBody()); <ide> } <ide> <ide> /**
2
Go
Go
move docker build to client
0f312113d3ce37d57fb28eb98c8abcdcbfcd39a3
<ide><path>api.go <ide> func postImagesPush(srv *Server, w http.ResponseWriter, r *http.Request, vars ma <ide> return nil <ide> } <ide> <del>func postBuild(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> in, out, err := hijackServer(w) <del> if err != nil { <del> return err <del> } <del> defer in.Close() <del> fmt.Fprintf(out, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") <del> if err := srv.ImageCreateFromFile(in, out); err != nil { <del> fmt.Fprintf(out, "Error: %s\n", err) <del> } <del> return nil <del>} <del> <ide> func postContainersCreate(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> config := &Config{} <ide> if err := json.NewDecoder(r.Body).Decode(config); err != nil { <ide> func getImagesByName(srv *Server, w http.ResponseWriter, r *http.Request, vars m <ide> return nil <ide> } <ide> <add>func postImagesGetCache(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add> apiConfig := &ApiImageConfig{} <add> if err := json.NewDecoder(r.Body).Decode(apiConfig); err != nil { <add> return err <add> } <add> <add> image, err := srv.ImageGetCached(apiConfig.Id, apiConfig.Config) <add> if err != nil { <add> return err <add> } <add> apiId := &ApiId{Id: image.Id} <add> b, err := json.Marshal(apiId) <add> if err != nil { <add> return err <add> } <add> writeJson(w, b) <add> return nil <add>} <add> <ide> func ListenAndServe(addr string, srv *Server, logging bool) error { <ide> r := mux.NewRouter() <ide> log.Printf("Listening for HTTP on %s\n", addr) <ide> func ListenAndServe(addr string, srv *Server, logging bool) error { <ide> "POST": { <ide> "/auth": postAuth, <ide> "/commit": postCommit, <del> "/build": postBuild, <ide> "/images/create": postImagesCreate, <ide> "/images/{name:.*}/insert": postImagesInsert, <ide> "/images/{name:.*}/push": postImagesPush, <ide> "/images/{name:.*}/tag": postImagesTag, <add> "/images/getCache": postImagesGetCache, <ide> "/containers/create": postContainersCreate, <ide> "/containers/{name:.*}/kill": postContainersKill, <ide> "/containers/{name:.*}/restart": postContainersRestart, <ide><path>api_params.go <ide> type ApiWait struct { <ide> type ApiAuth struct { <ide> Status string <ide> } <add> <add>type ApiImageConfig struct { <add> Id string <add> *Config <add>} <ide><path>builder.go <ide> package docker <ide> <ide> import ( <del> "bufio" <del> "encoding/json" <ide> "fmt" <del> "github.com/dotcloud/docker/utils" <del> "io" <ide> "os" <ide> "path" <del> "strings" <ide> "time" <ide> ) <ide> <ide> type Builder struct { <ide> runtime *Runtime <ide> repositories *TagStore <ide> graph *Graph <add> <add> config *Config <add> image *Image <ide> } <ide> <ide> func NewBuilder(runtime *Runtime) *Builder { <ide> func NewBuilder(runtime *Runtime) *Builder { <ide> } <ide> } <ide> <del>func (builder *Builder) mergeConfig(userConf, imageConf *Config) { <del> if userConf.Hostname != "" { <del> userConf.Hostname = imageConf.Hostname <del> } <del> if userConf.User != "" { <del> userConf.User = imageConf.User <del> } <del> if userConf.Memory == 0 { <del> userConf.Memory = imageConf.Memory <del> } <del> if userConf.MemorySwap == 0 { <del> userConf.MemorySwap = imageConf.MemorySwap <del> } <del> if userConf.CpuShares == 0 { <del> userConf.CpuShares = imageConf.CpuShares <del> } <del> if userConf.PortSpecs == nil || len(userConf.PortSpecs) == 0 { <del> userConf.PortSpecs = imageConf.PortSpecs <del> } <del> if !userConf.Tty { <del> userConf.Tty = imageConf.Tty <del> } <del> if !userConf.OpenStdin { <del> userConf.OpenStdin = imageConf.OpenStdin <del> } <del> if !userConf.StdinOnce { <del> userConf.StdinOnce = imageConf.StdinOnce <del> } <del> if userConf.Env == nil || len(userConf.Env) == 0 { <del> userConf.Env = imageConf.Env <del> } <del> if userConf.Cmd == nil || len(userConf.Cmd) == 0 { <del> userConf.Cmd = imageConf.Cmd <del> } <del> if userConf.Dns == nil || len(userConf.Dns) == 0 { <del> userConf.Dns = imageConf.Dns <del> } <del>} <del> <ide> func (builder *Builder) Create(config *Config) (*Container, error) { <ide> // Lookup image <ide> img, err := builder.repositories.LookupImage(config.Image) <ide> func (builder *Builder) Create(config *Config) (*Container, error) { <ide> } <ide> <ide> if img.Config != nil { <del> builder.mergeConfig(config, img.Config) <add> MergeConfig(config, img.Config) <ide> } <ide> <ide> if config.Cmd == nil || len(config.Cmd) == 0 { <ide> func (builder *Builder) Commit(container *Container, repository, tag, comment, a <ide> } <ide> return img, nil <ide> } <del> <del>func (builder *Builder) clearTmp(containers, images map[string]struct{}) { <del> for c := range containers { <del> tmp := builder.runtime.Get(c) <del> builder.runtime.Destroy(tmp) <del> utils.Debugf("Removing container %s", c) <del> } <del> for i := range images { <del> builder.runtime.graph.Delete(i) <del> utils.Debugf("Removing image %s", i) <del> } <del>} <del> <del>func (builder *Builder) getCachedImage(image *Image, config *Config) (*Image, error) { <del> // Retrieve all images <del> images, err := builder.graph.All() <del> if err != nil { <del> return nil, err <del> } <del> <del> // Store the tree in a map of map (map[parentId][childId]) <del> imageMap := make(map[string]map[string]struct{}) <del> for _, img := range images { <del> if _, exists := imageMap[img.Parent]; !exists { <del> imageMap[img.Parent] = make(map[string]struct{}) <del> } <del> imageMap[img.Parent][img.Id] = struct{}{} <del> } <del> <del> // Loop on the children of the given image and check the config <del> for elem := range imageMap[image.Id] { <del> img, err := builder.graph.Get(elem) <del> if err != nil { <del> return nil, err <del> } <del> if CompareConfig(&img.ContainerConfig, config) { <del> return img, nil <del> } <del> } <del> return nil, nil <del>} <del> <del>func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, error) { <del> var ( <del> image, base *Image <del> config *Config <del> maintainer string <del> env map[string]string = make(map[string]string) <del> tmpContainers map[string]struct{} = make(map[string]struct{}) <del> tmpImages map[string]struct{} = make(map[string]struct{}) <del> ) <del> defer builder.clearTmp(tmpContainers, tmpImages) <del> <del> file := bufio.NewReader(dockerfile) <del> for { <del> line, err := file.ReadString('\n') <del> if err != nil { <del> if err == io.EOF { <del> break <del> } <del> return nil, err <del> } <del> line = strings.Replace(strings.TrimSpace(line), " ", " ", 1) <del> // Skip comments and empty line <del> if len(line) == 0 || line[0] == '#' { <del> continue <del> } <del> tmp := strings.SplitN(line, " ", 2) <del> if len(tmp) != 2 { <del> return nil, fmt.Errorf("Invalid Dockerfile format") <del> } <del> instruction := strings.Trim(tmp[0], " ") <del> arguments := strings.Trim(tmp[1], " ") <del> switch strings.ToLower(instruction) { <del> case "from": <del> fmt.Fprintf(stdout, "FROM %s\n", arguments) <del> image, err = builder.runtime.repositories.LookupImage(arguments) <del> if err != nil { <del> // if builder.runtime.graph.IsNotExist(err) { <del> <del> // var tag, remote string <del> // if strings.Contains(arguments, ":") { <del> // remoteParts := strings.Split(arguments, ":") <del> // tag = remoteParts[1] <del> // remote = remoteParts[0] <del> // } else { <del> // remote = arguments <del> // } <del> <del> // panic("TODO: reimplement this") <del> // // if err := builder.runtime.graph.PullRepository(stdout, remote, tag, builder.runtime.repositories, builder.runtime.authConfig); err != nil { <del> // // return nil, err <del> // // } <del> <del> // image, err = builder.runtime.repositories.LookupImage(arguments) <del> // if err != nil { <del> // return nil, err <del> // } <del> // } else { <del> return nil, err <del> // } <del> } <del> config = &Config{} <del> <del> break <del> case "maintainer": <del> fmt.Fprintf(stdout, "MAINTAINER %s\n", arguments) <del> maintainer = arguments <del> break <del> case "run": <del> fmt.Fprintf(stdout, "RUN %s\n", arguments) <del> if image == nil { <del> return nil, fmt.Errorf("Please provide a source image with `from` prior to run") <del> } <del> config, _, err := ParseRun([]string{image.Id, "/bin/sh", "-c", arguments}, builder.runtime.capabilities) <del> if err != nil { <del> return nil, err <del> } <del> <del> for key, value := range env { <del> config.Env = append(config.Env, fmt.Sprintf("%s=%s", key, value)) <del> } <del> <del> if cache, err := builder.getCachedImage(image, config); err != nil { <del> return nil, err <del> } else if cache != nil { <del> image = cache <del> fmt.Fprintf(stdout, "===> %s\n", image.ShortId()) <del> break <del> } <del> <del> utils.Debugf("Env -----> %v ------ %v\n", config.Env, env) <del> <del> // Create the container and start it <del> c, err := builder.Create(config) <del> if err != nil { <del> return nil, err <del> } <del> <del> if os.Getenv("DEBUG") != "" { <del> out, _ := c.StdoutPipe() <del> err2, _ := c.StderrPipe() <del> go io.Copy(os.Stdout, out) <del> go io.Copy(os.Stdout, err2) <del> } <del> <del> if err := c.Start(); err != nil { <del> return nil, err <del> } <del> tmpContainers[c.Id] = struct{}{} <del> <del> // Wait for it to finish <del> if result := c.Wait(); result != 0 { <del> return nil, fmt.Errorf("!!! '%s' return non-zero exit code '%d'. Aborting.", arguments, result) <del> } <del> <del> // Commit the container <del> base, err = builder.Commit(c, "", "", "", maintainer, nil) <del> if err != nil { <del> return nil, err <del> } <del> tmpImages[base.Id] = struct{}{} <del> <del> fmt.Fprintf(stdout, "===> %s\n", base.ShortId()) <del> <del> // use the base as the new image <del> image = base <del> <del> break <del> case "env": <del> tmp := strings.SplitN(arguments, " ", 2) <del> if len(tmp) != 2 { <del> return nil, fmt.Errorf("Invalid ENV format") <del> } <del> key := strings.Trim(tmp[0], " ") <del> value := strings.Trim(tmp[1], " ") <del> fmt.Fprintf(stdout, "ENV %s %s\n", key, value) <del> env[key] = value <del> if image != nil { <del> fmt.Fprintf(stdout, "===> %s\n", image.ShortId()) <del> } else { <del> fmt.Fprintf(stdout, "===> <nil>\n") <del> } <del> break <del> case "cmd": <del> fmt.Fprintf(stdout, "CMD %s\n", arguments) <del> <del> // Create the container and start it <del> c, err := builder.Create(&Config{Image: image.Id, Cmd: []string{"", ""}}) <del> if err != nil { <del> return nil, err <del> } <del> if err := c.Start(); err != nil { <del> return nil, err <del> } <del> tmpContainers[c.Id] = struct{}{} <del> <del> cmd := []string{} <del> if err := json.Unmarshal([]byte(arguments), &cmd); err != nil { <del> return nil, err <del> } <del> config.Cmd = cmd <del> <del> // Commit the container <del> base, err = builder.Commit(c, "", "", "", maintainer, config) <del> if err != nil { <del> return nil, err <del> } <del> tmpImages[base.Id] = struct{}{} <del> <del> fmt.Fprintf(stdout, "===> %s\n", base.ShortId()) <del> image = base <del> break <del> case "expose": <del> ports := strings.Split(arguments, " ") <del> <del> fmt.Fprintf(stdout, "EXPOSE %v\n", ports) <del> if image == nil { <del> return nil, fmt.Errorf("Please provide a source image with `from` prior to copy") <del> } <del> <del> // Create the container and start it <del> c, err := builder.Create(&Config{Image: image.Id, Cmd: []string{"", ""}}) <del> if err != nil { <del> return nil, err <del> } <del> if err := c.Start(); err != nil { <del> return nil, err <del> } <del> tmpContainers[c.Id] = struct{}{} <del> <del> config.PortSpecs = append(ports, config.PortSpecs...) <del> <del> // Commit the container <del> base, err = builder.Commit(c, "", "", "", maintainer, config) <del> if err != nil { <del> return nil, err <del> } <del> tmpImages[base.Id] = struct{}{} <del> <del> fmt.Fprintf(stdout, "===> %s\n", base.ShortId()) <del> image = base <del> break <del> case "insert": <del> if image == nil { <del> return nil, fmt.Errorf("Please provide a source image with `from` prior to copy") <del> } <del> tmp = strings.SplitN(arguments, " ", 2) <del> if len(tmp) != 2 { <del> return nil, fmt.Errorf("Invalid INSERT format") <del> } <del> sourceUrl := strings.Trim(tmp[0], " ") <del> destPath := strings.Trim(tmp[1], " ") <del> fmt.Fprintf(stdout, "COPY %s to %s in %s\n", sourceUrl, destPath, base.ShortId()) <del> <del> file, err := utils.Download(sourceUrl, stdout) <del> if err != nil { <del> return nil, err <del> } <del> defer file.Body.Close() <del> <del> config, _, err := ParseRun([]string{base.Id, "echo", "insert", sourceUrl, destPath}, builder.runtime.capabilities) <del> if err != nil { <del> return nil, err <del> } <del> c, err := builder.Create(config) <del> if err != nil { <del> return nil, err <del> } <del> <del> if err := c.Start(); err != nil { <del> return nil, err <del> } <del> <del> // Wait for echo to finish <del> if result := c.Wait(); result != 0 { <del> return nil, fmt.Errorf("!!! '%s' return non-zero exit code '%d'. Aborting.", arguments, result) <del> } <del> <del> if err := c.Inject(file.Body, destPath); err != nil { <del> return nil, err <del> } <del> <del> base, err = builder.Commit(c, "", "", "", maintainer, nil) <del> if err != nil { <del> return nil, err <del> } <del> fmt.Fprintf(stdout, "===> %s\n", base.ShortId()) <del> <del> image = base <del> <del> break <del> default: <del> fmt.Fprintf(stdout, "Skipping unknown instruction %s\n", strings.ToUpper(instruction)) <del> } <del> } <del> if image != nil { <del> // The build is successful, keep the temporary containers and images <del> for i := range tmpImages { <del> delete(tmpImages, i) <del> } <del> for i := range tmpContainers { <del> delete(tmpContainers, i) <del> } <del> fmt.Fprintf(stdout, "Build finished. image id: %s\n", image.ShortId()) <del> return image, nil <del> } <del> return nil, fmt.Errorf("An error occured during the build\n") <del>} <ide><path>builder_client.go <add>package docker <add> <add>import ( <add> "bufio" <add> "encoding/json" <add> "fmt" <add> "github.com/dotcloud/docker/utils" <add> "io" <add> "net/url" <add> "os" <add> "reflect" <add> "strings" <add>) <add> <add>type BuilderClient struct { <add> builder *Builder <add> cli *DockerCli <add> <add> image string <add> maintainer string <add> config *Config <add> <add> tmpContainers map[string]struct{} <add> tmpImages map[string]struct{} <add> <add> needCommit bool <add>} <add> <add>func (b *BuilderClient) clearTmp(containers, images map[string]struct{}) { <add> for c := range containers { <add> tmp := b.builder.runtime.Get(c) <add> b.builder.runtime.Destroy(tmp) <add> utils.Debugf("Removing container %s", c) <add> } <add> for i := range images { <add> b.builder.runtime.graph.Delete(i) <add> utils.Debugf("Removing image %s", i) <add> } <add>} <add> <add>func (b *BuilderClient) From(name string) error { <add> obj, statusCode, err := b.cli.call("GET", "/images/"+name+"/json", nil) <add> if statusCode == 404 { <add> if err := b.cli.hijack("POST", "/images/create?fromImage="+name, false); err != nil { <add> return err <add> } <add> obj, _, err = b.cli.call("GET", "/images/"+name+"/json", nil) <add> if err != nil { <add> return err <add> } <add> } <add> if err != nil { <add> return err <add> } <add> <add> img := &ApiImages{} <add> if err := json.Unmarshal(obj, img); err != nil { <add> return err <add> } <add> b.image = img.Id <add> return nil <add>} <add> <add>func (b *BuilderClient) Maintainer(name string) error { <add> b.needCommit = true <add> b.maintainer = name <add> return nil <add>} <add> <add>func (b *BuilderClient) Run(args string) error { <add> if b.image == "" { <add> return fmt.Errorf("Please provide a source image with `from` prior to run") <add> } <add> config, _, err := ParseRun([]string{b.image, "/bin/sh", "-c", args}, b.builder.runtime.capabilities) <add> if err != nil { <add> return err <add> } <add> MergeConfig(b.config, config) <add> body, statusCode, err := b.cli.call("POST", "/images/getCache", &ApiImageConfig{Id: b.image, Config: b.config}) <add> if err != nil { <add> if statusCode != 404 { <add> return err <add> } <add> } <add> if statusCode != 404 { <add> apiId := &ApiId{} <add> if err := json.Unmarshal(body, apiId); err != nil { <add> return err <add> } <add> b.image = apiId.Id <add> return nil <add> } <add> <add> body, _, err = b.cli.call("POST", "/containers/create", b.config) <add> if err != nil { <add> return err <add> } <add> <add> out := &ApiRun{} <add> err = json.Unmarshal(body, out) <add> if err != nil { <add> return err <add> } <add> <add> for _, warning := range out.Warnings { <add> fmt.Fprintln(os.Stderr, "WARNING: ", warning) <add> } <add> <add> //start the container <add> _, _, err = b.cli.call("POST", "/containers/"+out.Id+"/start", nil) <add> if err != nil { <add> return err <add> } <add> b.tmpContainers[out.Id] = struct{}{} <add> <add> // Wait for it to finish <add> _, _, err = b.cli.call("POST", "/containers/"+out.Id+"/wait", nil) <add> if err != nil { <add> return err <add> } <add> <add> // Commit the container <add> v := url.Values{} <add> v.Set("container", out.Id) <add> v.Set("author", b.maintainer) <add> body, _, err = b.cli.call("POST", "/commit?"+v.Encode(), b.config) <add> if err != nil { <add> return err <add> } <add> apiId := &ApiId{} <add> err = json.Unmarshal(body, apiId) <add> if err != nil { <add> return err <add> } <add> b.tmpImages[apiId.Id] = struct{}{} <add> b.image = apiId.Id <add> b.needCommit = false <add> return nil <add>} <add> <add>func (b *BuilderClient) Env(args string) error { <add> b.needCommit = true <add> tmp := strings.SplitN(args, " ", 2) <add> if len(tmp) != 2 { <add> return fmt.Errorf("Invalid ENV format") <add> } <add> key := strings.Trim(tmp[0], " ") <add> value := strings.Trim(tmp[1], " ") <add> <add> for i, elem := range b.config.Env { <add> if strings.HasPrefix(elem, key+"=") { <add> b.config.Env[i] = key + "=" + value <add> return nil <add> } <add> } <add> b.config.Env = append(b.config.Env, key+"="+value) <add> return nil <add>} <add> <add>func (b *BuilderClient) Cmd(args string) error { <add> b.needCommit = true <add> b.config.Cmd = []string{"/bin/sh", "-c", args} <add> return nil <add>} <add> <add>func (b *BuilderClient) Expose(args string) error { <add> ports := strings.Split(args, " ") <add> b.config.PortSpecs = append(ports, b.config.PortSpecs...) <add> return nil <add>} <add> <add>func (b *BuilderClient) Insert(args string) error { <add> // FIXME: Reimplement this once the remove_hijack branch gets merged. <add> // We need to retrieve the resulting Id <add> return fmt.Errorf("INSERT not implemented") <add>} <add> <add>func NewBuilderClient(dockerfile io.Reader) (string, error) { <add> // defer b.clearTmp(tmpContainers, tmpImages) <add> <add> b := &BuilderClient{ <add> cli: NewDockerCli("0.0.0.0", 4243), <add> } <add> file := bufio.NewReader(dockerfile) <add> for { <add> line, err := file.ReadString('\n') <add> if err != nil { <add> if err == io.EOF { <add> break <add> } <add> return "", err <add> } <add> line = strings.Replace(strings.TrimSpace(line), " ", " ", 1) <add> // Skip comments and empty line <add> if len(line) == 0 || line[0] == '#' { <add> continue <add> } <add> tmp := strings.SplitN(line, " ", 2) <add> if len(tmp) != 2 { <add> return "", fmt.Errorf("Invalid Dockerfile format") <add> } <add> instruction := strings.ToLower(strings.Trim(tmp[0], " ")) <add> arguments := strings.Trim(tmp[1], " ") <add> <add> fmt.Printf("%s %s\n", strings.ToUpper(instruction), arguments) <add> <add> method, exists := reflect.TypeOf(b).MethodByName(strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:])) <add> if !exists { <add> fmt.Printf("Skipping unknown instruction %s\n", strings.ToUpper(instruction)) <add> } <add> ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface() <add> if ret != nil { <add> return "", ret.(error) <add> } <add> <add> fmt.Printf("===> %v\n", b.image) <add> } <add> if b.needCommit { <add> body, _, err = b.cli.call("POST", "/containers/create", b.config) <add> if err != nil { <add> return err <add> } <add> <add> out := &ApiRun{} <add> err = json.Unmarshal(body, out) <add> if err != nil { <add> return err <add> } <add> <add> for _, warning := range out.Warnings { <add> fmt.Fprintln(os.Stderr, "WARNING: ", warning) <add> } <add> <add> //start the container <add> _, _, err = b.cli.call("POST", "/containers/"+out.Id+"/start", nil) <add> if err != nil { <add> return err <add> } <add> b.tmpContainers[out.Id] = struct{}{} <add> <add> // Wait for it to finish <add> _, _, err = b.cli.call("POST", "/containers/"+out.Id+"/wait", nil) <add> if err != nil { <add> return err <add> } <add> <add> // Commit the container <add> v := url.Values{} <add> v.Set("container", out.Id) <add> v.Set("author", b.maintainer) <add> body, _, err = b.cli.call("POST", "/commit?"+v.Encode(), b.config) <add> if err != nil { <add> return err <add> } <add> apiId := &ApiId{} <add> err = json.Unmarshal(body, apiId) <add> if err != nil { <add> return err <add> } <add> b.tmpImages[apiId.Id] = struct{}{} <add> b.image = apiId.Id <add> } <add> if b.image != "" { <add> // The build is successful, keep the temporary containers and images <add> for i := range b.tmpImages { <add> delete(b.tmpImages, i) <add> } <add> for i := range b.tmpContainers { <add> delete(b.tmpContainers, i) <add> } <add> fmt.Printf("Build finished. image id: %s\n", b.image) <add> return b.image, nil <add> } <add> return "", fmt.Errorf("An error occured during the build\n") <add>} <ide><path>commands.go <ide> func ParseCommands(args ...string) error { <ide> <ide> func (cli *DockerCli) CmdHelp(args ...string) error { <ide> help := "Usage: docker COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n" <del> for _, cmd := range [][]string{ <del> {"attach", "Attach to a running container"}, <del> {"build", "Build a container from Dockerfile via stdin"}, <del> {"commit", "Create a new image from a container's changes"}, <del> {"diff", "Inspect changes on a container's filesystem"}, <del> {"export", "Stream the contents of a container as a tar archive"}, <del> {"history", "Show the history of an image"}, <del> {"images", "List images"}, <del> {"import", "Create a new filesystem image from the contents of a tarball"}, <del> {"info", "Display system-wide information"}, <del> {"insert", "Insert a file in an image"}, <del> {"inspect", "Return low-level information on a container"}, <del> {"kill", "Kill a running container"}, <del> {"login", "Register or Login to the docker registry server"}, <del> {"logs", "Fetch the logs of a container"}, <del> {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"}, <del> {"ps", "List containers"}, <del> {"pull", "Pull an image or a repository from the docker registry server"}, <del> {"push", "Push an image or a repository to the docker registry server"}, <del> {"restart", "Restart a running container"}, <del> {"rm", "Remove a container"}, <del> {"rmi", "Remove an image"}, <del> {"run", "Run a command in a new container"}, <del> {"search", "Search for an image in the docker index"}, <del> {"start", "Start a stopped container"}, <del> {"stop", "Stop a running container"}, <del> {"tag", "Tag an image into a repository"}, <del> {"version", "Show the docker version information"}, <del> {"wait", "Block until a container stops, then print its exit code"}, <add> for cmd, description := range map[string]string{ <add> "attach": "Attach to a running container", <add> "build": "Build a container from Dockerfile or via stdin", <add> "commit": "Create a new image from a container's changes", <add> "diff": "Inspect changes on a container's filesystem", <add> "export": "Stream the contents of a container as a tar archive", <add> "history": "Show the history of an image", <add> "images": "List images", <add> "import": "Create a new filesystem image from the contents of a tarball", <add> "info": "Display system-wide information", <add> "insert": "Insert a file in an image", <add> "inspect": "Return low-level information on a container", <add> "kill": "Kill a running container", <add> "login": "Register or Login to the docker registry server", <add> "logs": "Fetch the logs of a container", <add> "port": "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT", <add> "ps": "List containers", <add> "pull": "Pull an image or a repository from the docker registry server", <add> "push": "Push an image or a repository to the docker registry server", <add> "restart": "Restart a running container", <add> "rm": "Remove a container", <add> "rmi": "Remove an image", <add> "run": "Run a command in a new container", <add> "search": "Search for an image in the docker index", <add> "start": "Start a stopped container", <add> "stop": "Stop a running container", <add> "tag": "Tag an image into a repository", <add> "version": "Show the docker version information", <add> "wait": "Block until a container stops, then print its exit code", <ide> } { <del> help += fmt.Sprintf(" %-10.10s%s\n", cmd[0], cmd[1]) <add> help += fmt.Sprintf(" %-10.10s%s\n", cmd, description) <ide> } <ide> fmt.Println(help) <ide> return nil <ide> func (cli *DockerCli) CmdInsert(args ...string) error { <ide> } <ide> <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <del> cmd := Subcmd("build", "-", "Build an image from Dockerfile via stdin") <add> cmd := Subcmd("build", "-|Dockerfile", "Build an image from Dockerfile or via stdin") <ide> if err := cmd.Parse(args); err != nil { <ide> return nil <ide> } <add> var ( <add> file io.ReadCloser <add> err error <add> ) <ide> <del> err := cli.hijack("POST", "/build", false) <del> if err != nil { <del> return err <add> if cmd.NArg() == 0 { <add> file, err = os.Open("Dockerfile") <add> if err != nil { <add> return err <add> } <add> } else if cmd.Arg(0) == "-" { <add> file = os.Stdin <add> } else { <add> file, err = os.Open(cmd.Arg(0)) <add> if err != nil { <add> return err <add> } <ide> } <add> NewBuilderClient(file) <ide> return nil <ide> } <ide> <ide><path>server.go <ide> func (srv *Server) ImagesViz(out io.Writer) error { <ide> } <ide> <ide> func (srv *Server) Images(all bool, filter string) ([]ApiImages, error) { <del> var allImages map[string]*Image <del> var err error <add> var ( <add> allImages map[string]*Image <add> err error <add> ) <ide> if all { <ide> allImages, err = srv.runtime.graph.Map() <ide> } else { <ide> func (srv *Server) Images(all bool, filter string) ([]ApiImages, error) { <ide> if err != nil { <ide> return nil, err <ide> } <del> var outs []ApiImages = []ApiImages{} //produce [] when empty instead of 'null' <add> outs := []ApiImages{} //produce [] when empty instead of 'null' <ide> for name, repository := range srv.runtime.repositories.Repositories { <ide> if filter != "" && name != filter { <ide> continue <ide> func (srv *Server) ContainerCreate(config *Config) (string, error) { <ide> return container.ShortId(), nil <ide> } <ide> <del>func (srv *Server) ImageCreateFromFile(dockerfile io.Reader, out io.Writer) error { <del> img, err := NewBuilder(srv.runtime).Build(dockerfile, out) <del> if err != nil { <del> return err <del> } <del> fmt.Fprintf(out, "%s\n", img.ShortId()) <del> return nil <del>} <del> <ide> func (srv *Server) ContainerRestart(name string, t int) error { <ide> if container := srv.runtime.Get(name); container != nil { <ide> if err := container.Restart(t); err != nil { <ide> func (srv *Server) ImageDelete(name string) error { <ide> return nil <ide> } <ide> <add>func (srv *Server) ImageGetCached(imgId string, config *Config) (*Image, error) { <add> <add> // Retrieve all images <add> images, err := srv.runtime.graph.All() <add> if err != nil { <add> return nil, err <add> } <add> <add> // Store the tree in a map of map (map[parentId][childId]) <add> imageMap := make(map[string]map[string]struct{}) <add> for _, img := range images { <add> if _, exists := imageMap[img.Parent]; !exists { <add> imageMap[img.Parent] = make(map[string]struct{}) <add> } <add> imageMap[img.Parent][img.Id] = struct{}{} <add> } <add> <add> // Loop on the children of the given image and check the config <add> for elem := range imageMap[imgId] { <add> img, err := srv.runtime.graph.Get(elem) <add> if err != nil { <add> return nil, err <add> } <add> if CompareConfig(&img.ContainerConfig, config) { <add> return img, nil <add> } <add> } <add> return nil, nil <add>} <add> <ide> func (srv *Server) ContainerStart(name string) error { <ide> if container := srv.runtime.Get(name); container != nil { <ide> if err := container.Start(); err != nil { <ide><path>utils.go <ide> func CompareConfig(a, b *Config) bool { <ide> <ide> return true <ide> } <add> <add>func MergeConfig(userConf, imageConf *Config) { <add> if userConf.Hostname != "" { <add> userConf.Hostname = imageConf.Hostname <add> } <add> if userConf.User != "" { <add> userConf.User = imageConf.User <add> } <add> if userConf.Memory == 0 { <add> userConf.Memory = imageConf.Memory <add> } <add> if userConf.MemorySwap == 0 { <add> userConf.MemorySwap = imageConf.MemorySwap <add> } <add> if userConf.CpuShares == 0 { <add> userConf.CpuShares = imageConf.CpuShares <add> } <add> if userConf.PortSpecs == nil || len(userConf.PortSpecs) == 0 { <add> userConf.PortSpecs = imageConf.PortSpecs <add> } <add> if !userConf.Tty { <add> userConf.Tty = imageConf.Tty <add> } <add> if !userConf.OpenStdin { <add> userConf.OpenStdin = imageConf.OpenStdin <add> } <add> if !userConf.StdinOnce { <add> userConf.StdinOnce = imageConf.StdinOnce <add> } <add> if userConf.Env == nil || len(userConf.Env) == 0 { <add> userConf.Env = imageConf.Env <add> } <add> if userConf.Cmd == nil || len(userConf.Cmd) == 0 { <add> userConf.Cmd = imageConf.Cmd <add> } <add> if userConf.Dns == nil || len(userConf.Dns) == 0 { <add> userConf.Dns = imageConf.Dns <add> } <add>}
7
Python
Python
add python 3 compatibility
8f3230a61913e7884dca244d853f0eadc9b4f1e1
<ide><path>glances/glances.py <ide> import time <ide> from datetime import datetime, timedelta <ide> import gettext <del>from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler <add>try: <add> # For Python v2.x <add> from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler <add>except: <add> # For Python v3.x <add> from xmlrpc.server import SimpleXMLRPCRequestHandler <add> <ide> <ide> # International <ide> #============== <ide> def __init__(self, server_address, server_port = 61209): <ide> try: <ide> self.client = xmlrpclib.ServerProxy('http://%s:%d' % (server_address, server_port)) <ide> except: <del> print _("Error: creating client socket http://%s:%d") % (server_address, server_port) <add> print(_("Error: creating client socket http://%s:%d") % (server_address, server_port)) <add> pass <ide> return <ide> <ide> def client_init(self): <ide> try: <ide> client_version = self.client.init()[:3] <ide> except: <del> print _("Error: Connection to server failed") <add> print(_("Error: Connection to server failed")) <ide> sys.exit(-1) <ide> else: <ide> return __version__[:3] == client_version <ide> def signal_handler(signal, frame): <ide> <ide> # Init Glances depending of the mode (standalone, client, server) <ide> if server_tag: <del> from SimpleXMLRPCServer import SimpleXMLRPCServer <add> try: <add> # For Python v2.x <add> from SimpleXMLRPCServer import SimpleXMLRPCServer <add> except: <add> # For Python v3.x <add> from xmlrpc.server import SimpleXMLRPCServer <ide> import json <ide> import collections <ide>
1
PHP
PHP
remove old comment tags
dd1b8eeb21fe8e642054bf777f996cbf0a7c38ec
<ide><path>lib/Cake/Core/Plugin.php <ide> <?php <ide> /** <del> * Plugin class <del> * <ide> * PHP 5 <ide> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Core <ide> * @since CakePHP(tm) v 2.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> use Cake\Utility\Inflector; <ide> <ide> /** <del> * Cake Plugin is responsible for loading and unloading plugins. It also can <add> * Plugin is responsible for loading and unloading plugins. It also can <ide> * retrieve plugin paths and load their bootstrap and routes files. <ide> * <del> * @package Cake.Core <ide> * @link http://book.cakephp.org/2.0/en/plugins.html <ide> */ <ide> class Plugin {
1
Go
Go
hide updatestatus when it is not present
0e70d96a6813704498a3ce9cc2786648c84daa3a
<ide><path>api/types/swarm/service.go <ide> import "time" <ide> type Service struct { <ide> ID string <ide> Meta <del> Spec ServiceSpec `json:",omitempty"` <del> PreviousSpec *ServiceSpec `json:",omitempty"` <del> Endpoint Endpoint `json:",omitempty"` <del> UpdateStatus UpdateStatus `json:",omitempty"` <add> Spec ServiceSpec `json:",omitempty"` <add> PreviousSpec *ServiceSpec `json:",omitempty"` <add> Endpoint Endpoint `json:",omitempty"` <add> UpdateStatus *UpdateStatus `json:",omitempty"` <ide> } <ide> <ide> // ServiceSpec represents the spec of a service. <ide> const ( <ide> // UpdateStatus reports the status of a service update. <ide> type UpdateStatus struct { <ide> State UpdateState `json:",omitempty"` <del> StartedAt time.Time `json:",omitempty"` <del> CompletedAt time.Time `json:",omitempty"` <add> StartedAt *time.Time `json:",omitempty"` <add> CompletedAt *time.Time `json:",omitempty"` <ide> Message string `json:",omitempty"` <ide> } <ide> <ide><path>cli/command/formatter/service.go <ide> Service Mode: <ide> {{- if .HasUpdateStatus }} <ide> UpdateStatus: <ide> State: {{ .UpdateStatusState }} <add>{{- if .HasUpdateStatusStarted }} <ide> Started: {{ .UpdateStatusStarted }} <add>{{- end }} <ide> {{- if .UpdateIsCompleted }} <ide> Completed: {{ .UpdateStatusCompleted }} <ide> {{- end }} <ide> func (ctx *serviceInspectContext) ModeReplicatedReplicas() *uint64 { <ide> } <ide> <ide> func (ctx *serviceInspectContext) HasUpdateStatus() bool { <del> return ctx.Service.UpdateStatus.State != "" <add> return ctx.Service.UpdateStatus != nil && ctx.Service.UpdateStatus.State != "" <ide> } <ide> <ide> func (ctx *serviceInspectContext) UpdateStatusState() swarm.UpdateState { <ide> return ctx.Service.UpdateStatus.State <ide> } <ide> <add>func (ctx *serviceInspectContext) HasUpdateStatusStarted() bool { <add> return ctx.Service.UpdateStatus.StartedAt != nil <add>} <add> <ide> func (ctx *serviceInspectContext) UpdateStatusStarted() string { <del> return units.HumanDuration(time.Since(ctx.Service.UpdateStatus.StartedAt)) <add> return units.HumanDuration(time.Since(*ctx.Service.UpdateStatus.StartedAt)) <ide> } <ide> <ide> func (ctx *serviceInspectContext) UpdateIsCompleted() bool { <del> return ctx.Service.UpdateStatus.State == swarm.UpdateStateCompleted <add> return ctx.Service.UpdateStatus.State == swarm.UpdateStateCompleted && ctx.Service.UpdateStatus.CompletedAt != nil <ide> } <ide> <ide> func (ctx *serviceInspectContext) UpdateStatusCompleted() string { <del> return units.HumanDuration(time.Since(ctx.Service.UpdateStatus.CompletedAt)) <add> return units.HumanDuration(time.Since(*ctx.Service.UpdateStatus.CompletedAt)) <ide> } <ide> <ide> func (ctx *serviceInspectContext) UpdateStatusMessage() string { <ide><path>cli/command/service/inspect_test.go <ide> func formatServiceInspect(t *testing.T, format formatter.Format, now time.Time) <ide> }, <ide> }, <ide> }, <del> UpdateStatus: swarm.UpdateStatus{ <del> StartedAt: now, <del> CompletedAt: now, <add> UpdateStatus: &swarm.UpdateStatus{ <add> StartedAt: &now, <add> CompletedAt: &now, <ide> }, <ide> } <ide> <ide><path>daemon/cluster/convert/service.go <ide> func ServiceFromGRPC(s swarmapi.Service) types.Service { <ide> service.UpdatedAt, _ = ptypes.Timestamp(s.Meta.UpdatedAt) <ide> <ide> // UpdateStatus <del> service.UpdateStatus = types.UpdateStatus{} <ide> if s.UpdateStatus != nil { <add> service.UpdateStatus = &types.UpdateStatus{} <ide> switch s.UpdateStatus.State { <ide> case swarmapi.UpdateStatus_UPDATING: <ide> service.UpdateStatus.State = types.UpdateStateUpdating <ide> func ServiceFromGRPC(s swarmapi.Service) types.Service { <ide> service.UpdateStatus.State = types.UpdateStateCompleted <ide> } <ide> <del> service.UpdateStatus.StartedAt, _ = ptypes.Timestamp(s.UpdateStatus.StartedAt) <del> service.UpdateStatus.CompletedAt, _ = ptypes.Timestamp(s.UpdateStatus.CompletedAt) <add> startedAt, _ := ptypes.Timestamp(s.UpdateStatus.StartedAt) <add> if !startedAt.IsZero() { <add> service.UpdateStatus.StartedAt = &startedAt <add> } <add> <add> completedAt, _ := ptypes.Timestamp(s.UpdateStatus.CompletedAt) <add> if !completedAt.IsZero() { <add> service.UpdateStatus.CompletedAt = &completedAt <add> } <add> <ide> service.UpdateStatus.Message = s.UpdateStatus.Message <ide> } <ide> <ide><path>integration-cli/daemon_swarm.go <ide> func (d *SwarmDaemon) checkServiceRunningTasks(service string) func(*check.C) (i <ide> func (d *SwarmDaemon) checkServiceUpdateState(service string) func(*check.C) (interface{}, check.CommentInterface) { <ide> return func(c *check.C) (interface{}, check.CommentInterface) { <ide> service := d.getService(c, service) <add> if service.UpdateStatus == nil { <add> return "", nil <add> } <ide> return service.UpdateStatus.State, nil <ide> } <ide> }
5
PHP
PHP
reduce logic duplication
7d1cddead17e106b343570580f6c1e63bba3f1a9
<ide><path>src/Database/ValueBinder.php <ide> public function generateManyNamed($values, $type = 'string') <ide> { <ide> $placeholders = []; <ide> foreach ($values as $k => $value) { <del> $param = ":c" . $this->_bindingsCount; <add> $param = $this->placeholder('c'); <ide> $this->_bindings[$param] = [ <ide> 'value' => $value, <ide> 'type' => $type, <ide> 'placeholder' => substr($param, 1), <ide> ]; <ide> $placeholders[$k] = $param; <del> $this->_bindingsCount++; <ide> } <ide> <ide> return $placeholders;
1
Go
Go
expose endpoints api for a sandbox
7a769684855a6559be0e72aad40afb09cbbc6f0e
<ide><path>libnetwork/libnetwork_test.go <ide> func (f *fakeSandbox) ResolveIP(ip string) string { <ide> return "" <ide> } <ide> <add>func (f *fakeSandbox) Endpoints() []libnetwork.Endpoint { <add> return nil <add>} <add> <ide> func TestExternalKey(t *testing.T) { <ide> externalKeyTest(t, false) <ide> } <ide><path>libnetwork/sandbox.go <ide> type Sandbox interface { <ide> // ResolveIP returns the service name for the passed in IP. IP is in reverse dotted <ide> // notation; the format used for DNS PTR records <ide> ResolveIP(name string) string <add> // Endpoints returns all the endpoints connected to the sandbox <add> Endpoints() []Endpoint <ide> } <ide> <ide> // SandboxOption is an option setter function type used to pass various options to <ide> func (sb *sandbox) setupResolutionFiles() error { <ide> return nil <ide> } <ide> <add>func (sb *sandbox) Endpoints() []Endpoint { <add> sb.Lock() <add> defer sb.Unlock() <add> <add> endpoints := make([]Endpoint, len(sb.endpoints)) <add> for i, ep := range sb.endpoints { <add> endpoints[i] = ep <add> } <add> return endpoints <add>} <add> <ide> func (sb *sandbox) getConnectedEndpoints() []*endpoint { <ide> sb.Lock() <ide> defer sb.Unlock() <ide><path>libnetwork/sandbox_test.go <ide> func TestSandboxAddMultiPrio(t *testing.T) { <ide> t.Fatal("Expected ep3 to be at the top of the heap. But did not find ep3 at the top of the heap") <ide> } <ide> <add> if len(sbx.Endpoints()) != 3 { <add> t.Fatal("Expected 3 endpoints to be connected to the sandbox.") <add> } <add> <ide> if err := ep3.Leave(sbx); err != nil { <ide> t.Fatal(err) <ide> }
3
Mixed
Ruby
allow resetting singular associations
725ee799712e551c1e5a1687036d9a0c18ad2fb8
<ide><path>activerecord/CHANGELOG.md <add>* `has_one` and `belongs_to` associations now define a `reset_association` method <add> on the owner model (where `association` is the name of the association). This <add> method unloads the cached associate record, if any, and causes the next access <add> to query it from the database. <add> <add> *George Claghorn* <add> <ide> * Allow per attribute setting of YAML permitted classes (safe load) and unsafe load. <ide> <ide> *Carlos Palhares* <ide><path>activerecord/lib/active_record/associations.rb <ide> def has_many(name, scope = nil, **options, &extension) <ide> # if the record is invalid. <ide> # [reload_association] <ide> # Returns the associated object, forcing a database read. <add> # [reset_association] <add> # Unloads the associated object. The next access will query it from the database. <ide> # <ide> # === Example <ide> # <ide> def has_many(name, scope = nil, **options, &extension) <ide> # * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new(account_id: id); b.save; b</tt>) <ide> # * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new(account_id: id); b.save!; b</tt>) <ide> # * <tt>Account#reload_beneficiary</tt> <add> # * <tt>Account#reset_beneficiary</tt> <ide> # <ide> # === Scopes <ide> # <ide> def has_one(name, scope = nil, **options) <ide> # if the record is invalid. <ide> # [reload_association] <ide> # Returns the associated object, forcing a database read. <add> # [reset_association] <add> # Unloads the associated object. The next access will query it from the database. <ide> # [association_changed?] <ide> # Returns true if a new associate object has been assigned and the next save will update the foreign key. <ide> # [association_previously_changed?] <ide> def has_one(name, scope = nil, **options) <ide> # * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>) <ide> # * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>) <ide> # * <tt>Post#reload_author</tt> <add> # * <tt>Post#reset_author</tt> <ide> # * <tt>Post#author_changed?</tt> <ide> # * <tt>Post#author_previously_changed?</tt> <del> # The declaration can also include an +options+ hash to specialize the behavior of the association. <ide> # <ide> # === Scopes <ide> # <ide> def has_one(name, scope = nil, **options) <ide> # <ide> # === Options <ide> # <add> # The declaration can also include an +options+ hash to specialize the behavior of the association. <add> # <ide> # [:class_name] <ide> # Specify the class name of the association. Use it only if that name can't be inferred <ide> # from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but <ide><path>activerecord/lib/active_record/associations/builder/singular_association.rb <ide> def self.define_accessors(model, reflection) <ide> def reload_#{name} <ide> association(:#{name}).force_reload_reader <ide> end <add> <add> def reset_#{name} <add> association(:#{name}).reset <add> end <ide> CODE <ide> end <ide> <ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb <ide> def test_reloading_the_belonging_object <ide> Company.where(id: odegy_account.firm_id).update_all(name: "ODEGY") <ide> assert_equal "Odegy", odegy_account.firm.name <ide> <del> assert_equal "ODEGY", odegy_account.reload_firm.name <add> assert_queries(1) { odegy_account.reload_firm } <add> <add> assert_no_queries { odegy_account.firm } <add> assert_equal "ODEGY", odegy_account.firm.name <ide> end <ide> <ide> def test_reload_the_belonging_object_with_query_cache <ide> def test_reload_the_belonging_object_with_query_cache <ide> ActiveRecord::Base.connection.disable_query_cache! <ide> end <ide> <add> def test_resetting_the_association <add> odegy_account = accounts(:odegy_account) <add> <add> assert_equal "Odegy", odegy_account.firm.name <add> Company.where(id: odegy_account.firm_id).update_all(name: "ODEGY") <add> assert_equal "Odegy", odegy_account.firm.name <add> <add> assert_no_queries { odegy_account.reset_firm } <add> assert_queries(1) { odegy_account.firm } <add> assert_equal "ODEGY", odegy_account.firm.name <add> end <add> <ide> def test_natural_assignment_to_nil <ide> client = Client.find(3) <ide> client.firm = nil <ide><path>activerecord/test/cases/associations/has_one_associations_test.rb <ide> def test_reload_association <ide> Account.where(id: odegy.account.id).update_all(credit_limit: 80) <ide> assert_equal 53, odegy.account.credit_limit <ide> <del> assert_equal 80, odegy.reload_account.credit_limit <add> assert_queries(1) { odegy.reload_account } <add> assert_no_queries { odegy.account } <add> assert_equal 80, odegy.account.credit_limit <ide> end <ide> <ide> def test_reload_association_with_query_cache <ide> def test_reload_association_with_query_cache <ide> ActiveRecord::Base.connection.disable_query_cache! <ide> end <ide> <add> def test_reset_assocation <add> odegy = companies(:odegy) <add> <add> assert_equal 53, odegy.account.credit_limit <add> Account.where(id: odegy.account.id).update_all(credit_limit: 80) <add> assert_equal 53, odegy.account.credit_limit <add> <add> assert_no_queries { odegy.reset_account } <add> <add> assert_queries(1) { odegy.account } <add> assert_equal 80, odegy.account.credit_limit <add> end <add> <ide> def test_build <ide> firm = Firm.new("name" => "GlobalMegaCorp") <ide> firm.save <ide><path>guides/source/association_basics.md <ide> When you declare a `belongs_to` association, the declaring class automatically g <ide> * `create_association(attributes = {})` <ide> * `create_association!(attributes = {})` <ide> * `reload_association` <add>* `reset_association` <ide> * `association_changed?` <ide> * `association_previously_changed?` <ide> <ide> build_author <ide> create_author <ide> create_author! <ide> reload_author <add>reset_author <ide> author_changed? <ide> author_previously_changed? <ide> ``` <ide> If the associated object has already been retrieved from the database for this o <ide> @author = @book.reload_author <ide> ``` <ide> <add>To unload the cached version of the associated object—causing the next access, if any, to query it from the database—call `#reset_association` on the parent object. <add> <add>```ruby <add>@book.reset_author <add>``` <add> <ide> ##### `association=(associate)` <ide> <ide> The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associated object and setting this object's foreign key to the same value. <ide> When you declare a `has_one` association, the declaring class automatically gain <ide> * `create_association(attributes = {})` <ide> * `create_association!(attributes = {})` <ide> * `reload_association` <add>* `reset_assocation` <ide> <ide> In all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration: <ide> <ide> build_account <ide> create_account <ide> create_account! <ide> reload_account <add>reset_account <ide> ``` <ide> <ide> NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix. <ide> If the associated object has already been retrieved from the database for this o <ide> @account = @supplier.reload_account <ide> ``` <ide> <add>To unload the cached version of the associated object—forcing the next access, if any, to query it from the database—call `#reset_association` on the parent object. <add> <add>```ruby <add>@supplier.reset_account <add>``` <add> <ide> ##### `association=(associate)` <ide> <ide> The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associated object's foreign key to the same value.
6
PHP
PHP
fix missing argument on missingmethod
52ade3b85c5f6425f1a3b4911fc892f5caf1c05c
<ide><path>src/Illuminate/Routing/Controller.php <ide> public function callAction($method, $parameters) <ide> * @param array $parameters <ide> * @return mixed <ide> */ <del> public function missingMethod($method, $parameters) <add> public function missingMethod($method, $parameters = array()) <ide> { <ide> throw new NotFoundHttpException("Controller method [{$method}] not found."); <ide> }
1
Mixed
Ruby
remove more uses of eos.undent
4d4722c97c2e92f1fd17ed056f5a700e881eab4d
<ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb <ide> class Foo < Formula <ide> describe "a dependency on a macOS-provided keg-only formula" do <ide> describe "which is whitelisted" do <ide> let(:fa) do <del> formula_auditor "foo", <<-EOS.undent, new_formula: true <add> formula_auditor "foo", <<~EOS, new_formula: true <ide> class Foo < Formula <ide> url "http://example.com/foo-1.0.tgz" <ide> homepage "http://example.com" <ide> class Foo < Formula <ide> <ide> describe "which is not whitelisted" do <ide> let(:fa) do <del> formula_auditor "foo", <<-EOS.undent, new_formula: true <add> formula_auditor "foo", <<~EOS, new_formula: true <ide> class Foo < Formula <ide> url "http://example.com/foo-1.0.tgz" <ide> homepage "http://example.com" <ide><path>docs/Formula-Cookbook.md <ide> Sometimes a package fails to build when using a certain compiler. Since recent [ <ide> ```ruby <ide> fails_with :llvm do <ide> build 2335 <del> cause <<-EOS.undent <add> cause <<~EOS <ide> The "cause" field should include a short summary of the error. Include <ide> the URLs of any relevant information, such as upstream bug reports. Wrap <ide> the text at a sensible boundary (~72-80 characters), but do not break
2
Javascript
Javascript
bring voroboids examples up-to-date
29ece588f0581eb1f7397017056cba18cb57b2b2
<ide><path>examples/voroboids/boid.js <ide> var boid = (function() { <ide> } <ide> <ide> function d3_ai_boidWrap(position) { <del> if (position[0] > w) position[0] = 0; <del> else if (position[0] < 0) position[0] = w; <del> if (position[1] > h) position[1] = 0; <del> else if (position[1] < 0) position[1] = h; <add> if (position[0] > width) position[0] = 0; <add> else if (position[0] < 0) position[0] = width; <add> if (position[1] > height) position[1] = 0; <add> else if (position[1] < 0) position[1] = height; <ide> } <ide> <ide> function d3_ai_boidGravity(center, position, neighborRadius) { <ide> var boid = (function() { <ide> function d3_ai_boidDistance(a, b) { <ide> var dx = a[0] - b[0], <ide> dy = a[1] - b[1]; <del> if (dx > w / 2) dx = w - dx; <del> if (dy > h / 2) dy = h - dy; <add> if (dx > width / 2) dx = width - dx; <add> if (dy > height / 2) dy = height - dy; <ide> return Math.sqrt(dx * dx + dy * dy); <ide> } <ide> <ide><path>examples/voroboids/voroboids.js <del>var w = 960, <del> h = 500, <del> mouse = [null, null], <del> fill = d3.scale.linear().domain([0, 1e4]).range(["brown", "steelblue"]); <add>var width = 960, <add> height = 500, <add> mouse = [null, null]; <add> <add>var fill = d3.scale.linear() <add> .domain([0, 1e4]) <add> .range(["brown", "steelblue"]); <ide> <ide> // Initialise boids. <ide> var boids = d3.range(100).map(function() { <ide> return boid() <del> .position([Math.random() * w, Math.random() * h]) <add> .position([Math.random() * width, Math.random() * height]) <ide> .velocity([Math.random() * 2 - 1, Math.random() * 2 - 1]) <ide> .gravityCenter(mouse); <ide> }); <ide> d3.select(window).on("blur", nullGravity); <ide> <ide> var svg = d3.select("#vis") <ide> .append("svg") <del> .attr("width", w) <del> .attr("height", h) <add> .attr("width", width) <add> .attr("height", height) <ide> .attr("class", "PiYG") <ide> .on("mousemove", function() { <ide> var m = d3.mouse(this);
2
Javascript
Javascript
expose errors correctly
e56b5be904e097bf2b95cdac5922675bf3452e6a
<ide><path>packager/src/lib/JsonReporter.js <ide> <ide> import {Writable} from 'stream'; <ide> <del>class JsonReporter<TEvent> { <add>class JsonReporter<TEvent: {}> { <ide> <ide> _stream: Writable; <ide> <ide> constructor(stream: Writable) { <ide> this._stream = stream; <ide> } <ide> <add> /** <add> * There is a special case for errors because they have non-enumerable fields. <add> * (Perhaps we should switch in favor of plain object?) <add> */ <ide> update(event: TEvent) { <add> /* $FlowFixMe: fine to call on `undefined`. */ <add> if (Object.prototype.toString.call(event.error) === '[object Error]') { <add> event = {...event}; <add> event.error = { <add> ...event.error, <add> message: event.error.message, <add> stack: event.error.stack, <add> }; <add> } <ide> this._stream.write(JSON.stringify(event) + '\n'); <ide> } <ide>
1
Javascript
Javascript
expect 0 assertions to fix
7e40b5342af6a523608501dfefe3defe11564733
<ide><path>src/test/moment/add_subtract.js <ide> test('add across DST', function (assert) { <ide> // Detect Safari bug and bail. Hours on 13th March 2011 are shifted <ide> // with 1 ahead. <ide> if (new Date(2011, 2, 13, 5, 0, 0).getHours() !== 5) { <add> assert.expect(0); <ide> return; <ide> } <ide>
1
PHP
PHP
use unix socket or host and port
b9586cc46d55451e24ead6adea7eeb7246a57817
<ide><path>src/Illuminate/Database/Connectors/MySqlConnector.php <ide> protected function getDsn(array $config) <ide> // need to establish the PDO connections and return them back for use. <ide> extract($config); <ide> <del> $dsn = "mysql:host={$host};dbname={$database}"; <del> <del> if (isset($config['port'])) <add> $dsn = "mysql:dbname={$database}"; <add> <add> if (isset($config['unix_socket'])) <ide> { <del> $dsn .= ";port={$port}"; <del> } <del> <del> // Sometimes the developer may specify the specific UNIX socket that should <del> // be used. If that is the case we will add that option to the string we <del> // have created so that it gets utilized while the connection is made. <del> if (isset($config['unix_socket'])) <add> $dsn .= ";host={$host}"; <add> <add> if (isset($config['port'])) <add> { <add> $dsn .= ";port={$port}"; <add> } <add> } <add> else <ide> { <ide> $dsn .= ";unix_socket={$config['unix_socket']}"; <ide> }
1
PHP
PHP
implement interface on integration stub
f2357580ecf3746f5e17d1ddbf3271b7c31b0e39
<ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> class ErrorHandlerMiddleware implements MiddlewareInterface <ide> * <ide> * @var \Cake\Error\ErrorHandler|null <ide> */ <del> protected $errorHandler; <add> protected $errorHandler = null; <ide> <ide> /** <ide> * ExceptionTrap instance <ide> * <ide> * @var \Cake\Error\ExceptionTrap|null <ide> */ <del> protected $exceptionTrap; <add> protected $exceptionTrap = null; <ide> <ide> /** <ide> * Constructor <ide><path>src/TestSuite/Stub/TestExceptionRenderer.php <ide> */ <ide> namespace Cake\TestSuite\Stub; <ide> <add>use Cake\Error\ExceptionRendererInterface; <add>use LogicException; <add>use Psr\Http\Message\ResponseInterface; <ide> use Throwable; <ide> <ide> /** <ide> * @see \Cake\TestSuite\IntegrationTestCase::disableErrorHandlerMiddleware() <ide> * @internal <ide> */ <del>class TestExceptionRenderer <add>class TestExceptionRenderer implements ExceptionRendererInterface <ide> { <ide> /** <ide> * Simply rethrow the given exception <ide> public function __construct(Throwable $exception) <ide> { <ide> throw $exception; <ide> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public function render(): ResponseInterface <add> { <add> throw new LogicException('You cannot use this class to render exceptions.'); <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public function write($output): void <add> { <add> echo $output; <add> } <ide> }
2
PHP
PHP
link command
0b8f550419baa95c32f5d0f3005023f1cd58a47c
<ide><path>src/Illuminate/Foundation/Console/StorageLinkCommand.php <add><?php <add> <add>namespace Illuminate\Foundation\Console; <add> <add>use Illuminate\Console\Command; <add> <add>class StorageLinkCommand extends Command <add>{ <add> /** <add> * The console command signature. <add> * <add> * @var string <add> */ <add> protected $signature = 'storage:link'; <add> <add> /** <add> * The console command description. <add> * <add> * @var string <add> */ <add> protected $description = 'Create a symbolic link from "public/storage" to "storage/app/public"'; <add> <add> /** <add> * Execute the console command. <add> * <add> * @return void <add> */ <add> public function fire() <add> { <add> if (file_exists(public_path('storage'))) { <add> return $this->error('The "public/storage" directory already exists.'); <add> } <add> <add> symlink(storage_path('app/public'), public_path('storage')); <add> <add> $this->info('The [public/storage] directory has been successfully linked.'); <add> } <add>} <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> use Illuminate\Foundation\Console\PolicyMakeCommand; <ide> use Illuminate\Foundation\Console\RouteCacheCommand; <ide> use Illuminate\Foundation\Console\RouteClearCommand; <add>use Illuminate\Foundation\Console\StorageLinkCommand; <ide> use Illuminate\Routing\Console\ControllerMakeCommand; <ide> use Illuminate\Routing\Console\MiddlewareMakeCommand; <ide> use Illuminate\Foundation\Console\ConfigCacheCommand; <ide> class ArtisanServiceProvider extends ServiceProvider <ide> 'RouteCache' => 'command.route.cache', <ide> 'RouteClear' => 'command.route.clear', <ide> 'RouteList' => 'command.route.list', <add> 'StorageLink' => 'command.storage.link', <ide> 'Tinker' => 'command.tinker', <ide> 'Up' => 'command.up', <ide> 'ViewClear' => 'command.view.clear', <ide> protected function registerSessionTableCommand() <ide> }); <ide> } <ide> <add> /** <add> * Register the command. <add> * <add> * @return void <add> */ <add> protected function registerStorageLinkCommand() <add> { <add> $this->app->singleton('command.storage.link', function () { <add> return new StorageLinkCommand; <add> }); <add> } <add> <ide> /** <ide> * Register the command. <ide> *
2
Javascript
Javascript
open plnkr.co with https
56861c0ae9fd52a8d47d4cc5c1db7f4c9b60526b
<ide><path>docs/app/src/examples.js <ide> angular.module('examples', []) <ide> <ide> postData.description = ctrl.example.name; <ide> <del> formPostData('http://plnkr.co/edit/?p=preview', newWindow, postData); <add> formPostData('https://plnkr.co/edit/?p=preview', newWindow, postData); <ide> }); <ide> <ide> };
1
Ruby
Ruby
fix a nomethoderror schema_statements.rb
01fbdb311d0661b4db89024a9b1c9fafcaceaafd
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def index_name_for_remove(table_name, options = {}) <ide> checks << lambda { |i| i.columns.join("_and_") == column_names.join("_and_") } <ide> end <ide> <del> raise ArgumentError "No name or columns specified" if checks.none? <add> raise ArgumentError, "No name or columns specified" if checks.none? <ide> <ide> matching_indexes = indexes(table_name).select { |i| checks.all? { |check| check[i] } } <ide> <ide><path>activerecord/test/cases/adapters/postgresql/active_schema_test.rb <ide> def test_remove_index_when_name_is_specified <ide> assert_equal expected, remove_index(:people, name: "index_people_on_last_name", algorithm: :concurrently) <ide> end <ide> <add> def test_remove_index_with_wrong_option <add> assert_raises ArgumentError do <add> remove_index(:people, coulmn: :last_name) <add> end <add> end <add> <ide> private <ide> def method_missing(method_symbol, *arguments) <ide> ActiveRecord::Base.connection.send(method_symbol, *arguments)
2
Text
Text
remove duplicated test
09b62480f280d31c7be2b082dec546c1c73826ea
<ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/sum-to-100.md <ide> assert.deepEqual(sumTo100(243), [ <ide> ]); <ide> ``` <ide> <del>`sumTo100(199)` should return `["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]`. <del> <del>```js <del>assert.deepEqual(sumTo100(199), [ <del> '-1+2-3+45+67+89', <del> '123-4+5+6+78-9', <del> '123-4+56+7+8+9' <del>]); <del>``` <del> <ide> `sumTo100(197)` should return `["1-2-3+45+67+89", "12+34-5+67+89", "123+4-5+6+78-9"]`. <ide> <ide> ```js
1
Go
Go
fix basicauth function not in go1.3.3
4a2ef6c8053d5b0eb768297af8609505198c7187
<ide><path>pkg/requestdecorator/requestdecorator_test.go <ide> package requestdecorator <ide> <ide> import ( <add> "encoding/base64" <ide> "net/http" <ide> "strings" <ide> "testing" <ide> ) <ide> <add>// The following 2 functions are here for 1.3.3 support <add>// After we drop 1.3.3 support we can use the functions supported <add>// in go v1.4.0 + <add>// BasicAuth returns the username and password provided in the request's <add>// Authorization header, if the request uses HTTP Basic Authentication. <add>// See RFC 2617, Section 2. <add>func basicAuth(r *http.Request) (username, password string, ok bool) { <add> auth := r.Header.Get("Authorization") <add> if auth == "" { <add> return <add> } <add> return parseBasicAuth(auth) <add>} <add> <add>// parseBasicAuth parses an HTTP Basic Authentication string. <add>// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true). <add>func parseBasicAuth(auth string) (username, password string, ok bool) { <add> const prefix = "Basic " <add> if !strings.HasPrefix(auth, prefix) { <add> return <add> } <add> c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) <add> if err != nil { <add> return <add> } <add> cs := string(c) <add> s := strings.IndexByte(cs, ':') <add> if s < 0 { <add> return <add> } <add> return cs[:s], cs[s+1:], true <add>} <add> <ide> func TestUAVersionInfo(t *testing.T) { <ide> uavi := NewUAVersionInfo("foo", "bar") <ide> if !uavi.isValid() { <ide> func TestAuthDecorator(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> username, password, ok := reqDecorated.BasicAuth() <add> username, password, ok := basicAuth(reqDecorated) <ide> if !ok { <ide> t.Fatalf("Cannot retrieve basic auth info from request") <ide> } <ide> func TestRequestFactory(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> username, password, ok := req.BasicAuth() <add> username, password, ok := basicAuth(req) <ide> if !ok { <ide> t.Fatalf("Cannot retrieve basic auth info from request") <ide> } <ide> func TestRequestFactoryNewRequestWithDecorators(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> username, password, ok := req.BasicAuth() <add> username, password, ok := basicAuth(req) <ide> if !ok { <ide> t.Fatalf("Cannot retrieve basic auth info from request") <ide> }
1