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 |
|---|---|---|---|---|---|
Javascript | Javascript | allow setting map of controllers | cef3535c16d5b7825f797adc6705d61dad759796 | <ide><path>src/ng/controller.js
<ide> function $ControllerProvider() {
<ide> * annotations in the array notation).
<ide> */
<ide> this.register = function(name, constructor) {
<del> controllers[name] = constructor;
<add> if (isObject(name)) {
<add> extend(controllers, name)
<add> } else {
<add> controllers[name] = constructor;
<add> }
<ide> };
<ide>
<ide>
<ide><path>test/ng/controllerSpec.js
<ide> describe('$controller', function() {
<ide>
<ide> it('should allow registration of controllers', function() {
<ide> var FooCtrl = function($scope) { $scope.foo = 'bar' },
<del> scope = {},
<del> ctrl;
<add> scope = {},
<add> ctrl;
<ide>
<ide> $controllerProvider.register('FooCtrl', FooCtrl);
<ide> ctrl = $controller('FooCtrl', {$scope: scope});
<ide> describe('$controller', function() {
<ide> });
<ide>
<ide>
<add> it('should allow registration of map of controllers', function() {
<add> var FooCtrl = function($scope) { $scope.foo = 'foo' },
<add> BarCtrl = function($scope) { $scope.bar = 'bar' },
<add> scope = {},
<add> ctrl;
<add>
<add> $controllerProvider.register({FooCtrl: FooCtrl, BarCtrl: BarCtrl} );
<add>
<add> ctrl = $controller('FooCtrl', {$scope: scope});
<add> expect(scope.foo).toBe('foo');
<add> expect(ctrl instanceof FooCtrl).toBe(true);
<add>
<add> ctrl = $controller('BarCtrl', {$scope: scope});
<add> expect(scope.bar).toBe('bar');
<add> expect(ctrl instanceof BarCtrl).toBe(true);
<add> });
<add>
<add>
<ide> it('should allow registration of controllers annotated with arrays', function() {
<ide> var FooCtrl = function($scope) { $scope.foo = 'bar' },
<ide> scope = {}, | 2 |
Java | Java | fix minor issue and polish | 34c95034d8437249b573912aaf275c0a734b15a7 | <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/AbstractSockJsSession.java
<ide> public void delegateMessages(String[] messages) throws Exception {
<ide> }
<ide> }
<ide>
<del> public void delegateError(Throwable ex) {
<add> public void delegateError(Throwable ex) throws Exception {
<ide> this.handler.handleError(ex, this);
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/support/DefaultSockJsService.java
<ide> import org.springframework.sockjs.SockJsSessionFactory;
<ide> import org.springframework.sockjs.server.AbstractSockJsService;
<ide> import org.springframework.sockjs.server.ConfigurableTransportHandler;
<add>import org.springframework.sockjs.server.SockJsService;
<ide> import org.springframework.sockjs.server.TransportHandler;
<ide> import org.springframework.sockjs.server.TransportType;
<ide> import org.springframework.sockjs.server.transport.EventSourceTransportHandler;
<ide>
<ide>
<ide> /**
<del> * TODO
<add> * A default implementation of {@link SockJsService} adding support for transport handling
<add> * and session management.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> public class DefaultSockJsService extends AbstractSockJsService {
<ide> private ScheduledFuture sessionCleanupTask;
<ide>
<ide>
<add> /**
<add> * Create an instance with default {@link TransportHandler transport handler} types.
<add> *
<add> * @param taskScheduler a task scheduler for heart-beat messages and removing
<add> * timed-out sessions; the provided TaskScheduler should be declared as a
<add> * Spring bean to ensure it is initialized at start up and shut down when the
<add> * application stops.
<add> */
<ide> public DefaultSockJsService(TaskScheduler taskScheduler) {
<ide> this(taskScheduler, null);
<ide> }
<ide>
<add> /**
<add> * Create an instance by overriding or replacing completely the default
<add> * {@link TransportHandler transport handler} types.
<add> *
<add> * @param taskScheduler a task scheduler for heart-beat messages and removing
<add> * timed-out sessions; the provided TaskScheduler should be declared as a
<add> * Spring bean to ensure it is initialized at start up and shut down when the
<add> * application stops.
<add> * @param transportHandlers the transport handlers to use (replaces the default ones);
<add> * can be {@code null}.
<add> * @param transportHandlerOverrides zero or more overrides to the default transport
<add> * handler types.
<add> */
<ide> public DefaultSockJsService(TaskScheduler taskScheduler, Set<TransportHandler> transportHandlers,
<ide> TransportHandler... transportHandlerOverrides) {
<ide>
<ide> public DefaultSockJsService(TaskScheduler taskScheduler, Set<TransportHandler> t
<ide> addTransportHandlers(Arrays.asList(transportHandlerOverrides));
<ide> }
<ide>
<del> protected Set<TransportHandler> getDefaultTransportHandlers() {
<add> protected final Set<TransportHandler> getDefaultTransportHandlers() {
<ide> Set<TransportHandler> result = new HashSet<TransportHandler>();
<ide> result.add(new XhrPollingTransportHandler());
<ide> result.add(new XhrTransportHandler());
<ide> protected Set<TransportHandler> getDefaultTransportHandlers() {
<ide> result.add(new XhrStreamingTransportHandler());
<ide> result.add(new EventSourceTransportHandler());
<ide> result.add(new HtmlFileTransportHandler());
<del> if (isWebSocketEnabled()) {
<del> try {
<del> result.add(new WebSocketTransportHandler(new DefaultHandshakeHandler()));
<del> }
<del> catch (Exception ex) {
<del> if (logger.isWarnEnabled()) {
<del> logger.warn("Failed to add default WebSocketTransportHandler: " + ex.getMessage());
<del> }
<add> try {
<add> result.add(new WebSocketTransportHandler(new DefaultHandshakeHandler()));
<add> }
<add> catch (Exception ex) {
<add> if (logger.isWarnEnabled()) {
<add> logger.warn("Failed to add default WebSocketTransportHandler: " + ex.getMessage());
<ide> }
<ide> }
<ide> return result;
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/SockJsWebSocketHandler.java
<ide> public void afterConnectionClosed(CloseStatus status, WebSocketSession wsSession
<ide> }
<ide>
<ide> @Override
<del> public void handleError(Throwable exception, WebSocketSession webSocketSession) {
<add> public void handleError(Throwable exception, WebSocketSession webSocketSession) throws Exception {
<ide> this.session.delegateError(exception);
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/CloseStatus.java
<ide> public final class CloseStatus {
<ide> public static final CloseStatus SERVER_ERROR = new CloseStatus(1011);
<ide>
<ide> /**
<del> * 1012 indicates that the service is restarted. A client may reconnect, and if it
<del> * choses to do, should reconnect using a randomized delay of 5 - 30s.
<del> * <p>See <a href="https://www.ietf.org/mail-archive/web/hybi/current/msg09649.html">
<del> * [hybi] Additional WebSocket Close Error Codes</a>
<add> * "1012 indicates that the service is restarted. A client may reconnect, and if it
<add> * chooses to do, should reconnect using a randomized delay of 5 - 30s."
<ide> */
<ide> public static final CloseStatus SERVICE_RESTARTED = new CloseStatus(1012);
<ide>
<ide> /**
<del> * 1013 indicates that the service is experiencing overload. A client should only
<add> * "1013 indicates that the service is experiencing overload. A client should only
<ide> * connect to a different IP (when there are multiple for the target) or reconnect to
<del> * the same IP upon user action.
<del> * <p>See <a href="https://www.ietf.org/mail-archive/web/hybi/current/msg09649.html">
<del> * [hybi] Additional WebSocket Close Error Codes</a>
<add> * the same IP upon user action."
<ide> */
<ide> public static final CloseStatus SERVICE_OVERLOAD = new CloseStatus(1013);
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/WebSocketHandler.java
<ide> public interface WebSocketHandler {
<ide> /**
<ide> * TODO
<ide> */
<del> void handleError(Throwable exception, WebSocketSession session);
<add> void handleError(Throwable exception, WebSocketSession session) throws Exception;
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketClient.java
<ide> public interface WebSocketClient {
<ide>
<ide>
<add> WebSocketSession doHandshake(WebSocketHandler handler,
<add> String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException;
<add>
<ide> WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler,
<ide> String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException;
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/StandardWebSocketClient.java
<ide> import org.springframework.websocket.client.WebSocketConnectFailureException;
<ide> import org.springframework.websocket.endpoint.StandardWebSocketSession;
<ide> import org.springframework.websocket.endpoint.WebSocketHandlerEndpoint;
<add>import org.springframework.websocket.support.SimpleHandlerProvider;
<ide>
<ide>
<ide> /**
<ide> public void setWebSocketContainer(WebSocketContainer container) {
<ide> this.webSocketContainer = container;
<ide> }
<ide>
<add> @Override
<add> public WebSocketSession doHandshake(WebSocketHandler handler, String uriTemplate, Object... uriVariables)
<add> throws WebSocketConnectFailureException {
<add>
<add> return doHandshake(new SimpleHandlerProvider<WebSocketHandler>(handler), uriTemplate, uriVariables);
<add> }
<add>
<ide> public WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler,
<ide> String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException {
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/endpoint/WebSocketHandlerEndpoint.java
<ide> public void onOpen(final javax.websocket.Session session, EndpointConfig config)
<ide> Assert.isTrue(this.sessionCount.compareAndSet(0, 1), "Unexpected connection");
<ide>
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("Client connected, javax.websocket.Session id="
<add> logger.debug("Connection established, javax.websocket.Session id="
<ide> + session.getId() + ", uri=" + session.getRequestURI());
<ide> }
<ide>
<ide> public void onMessage(byte[] message) {
<ide> this.handler.afterConnectionEstablished(this.webSocketSession);
<ide> }
<ide> catch (Throwable ex) {
<del> this.handler.handleError(ex, this.webSocketSession);
<add> onError(session, ex);
<ide> }
<ide> }
<ide>
<ide> private void handleTextMessage(javax.websocket.Session session, String message)
<ide> ((TextMessageHandler) handler).handleTextMessage(textMessage, this.webSocketSession);
<ide> }
<ide> catch (Throwable ex) {
<del> this.handler.handleError(ex, this.webSocketSession);
<add> onError(session, ex);
<ide> }
<ide> }
<ide>
<ide> private void handleBinaryMessage(javax.websocket.Session session, byte[] message
<ide> ((BinaryMessageHandler) handler).handleBinaryMessage(binaryMessage, this.webSocketSession);
<ide> }
<ide> catch (Throwable ex) {
<del> this.handler.handleError(ex, this.webSocketSession);
<add> onError(session, ex);
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void onClose(javax.websocket.Session session, CloseReason reason) {
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("Client disconnected, WebSocket session id=" + session.getId() + ", " + reason);
<add> logger.debug("Connection closed, WebSocket session id=" + session.getId() + ", " + reason);
<ide> }
<ide> try {
<ide> CloseStatus closeStatus = new CloseStatus(reason.getCloseCode().getCode(), reason.getReasonPhrase());
<ide> this.handler.afterConnectionClosed(closeStatus, this.webSocketSession);
<ide> }
<ide> catch (Throwable ex) {
<del> logger.error("Error while processing session closing", ex);
<add> onError(session, ex);
<ide> }
<ide> finally {
<ide> this.handlerProvider.destroy(this.handler);
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/support/JettyRequestUpgradeStrategy.java
<ide> public void onWebSocketConnect(Session session) {
<ide> try {
<ide> this.session = new WebSocketSessionAdapter(session);
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("Client connected, WebSocket session id="
<add> logger.debug("Connection established, WebSocket session id="
<ide> + this.session.getId() + ", uri=" + this.session.getURI());
<ide> }
<ide> this.handler = this.provider.getHandler();
<ide> public void onWebSocketClose(int statusCode, String reason) {
<ide> try {
<ide> CloseStatus closeStatus = new CloseStatus(statusCode, reason);
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("Client disconnected, WebSocket session id="
<add> logger.debug("Connection closed, WebSocket session id="
<ide> + this.session.getId() + ", " + closeStatus);
<ide> }
<ide> this.handler.afterConnectionClosed(closeStatus, this.session);
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/support/WebSocketHttpRequestHandler.java
<ide> */
<ide> public class WebSocketHttpRequestHandler implements HttpRequestHandler {
<ide>
<del> private HandshakeHandler handshakeHandler;
<add> private final HandshakeHandler handshakeHandler;
<ide>
<ide> private final HandlerProvider<WebSocketHandler> handlerProvider;
<ide>
<ide>
<ide> public WebSocketHttpRequestHandler(WebSocketHandler webSocketHandler) {
<del> Assert.notNull(webSocketHandler, "webSocketHandler is required");
<del> this.handlerProvider = new SimpleHandlerProvider<WebSocketHandler>(webSocketHandler);
<del> this.handshakeHandler = new DefaultHandshakeHandler();
<add> this(new SimpleHandlerProvider<WebSocketHandler>(webSocketHandler));
<ide> }
<ide>
<ide> public WebSocketHttpRequestHandler( HandlerProvider<WebSocketHandler> handlerProvider) {
<del> Assert.notNull(handlerProvider, "handlerProvider is required");
<del> this.handlerProvider = handlerProvider;
<add> this(handlerProvider, new DefaultHandshakeHandler());
<ide> }
<ide>
<del> public void setHandshakeHandler(HandshakeHandler handshakeHandler) {
<add> public WebSocketHttpRequestHandler( HandlerProvider<WebSocketHandler> handlerProvider,
<add> HandshakeHandler handshakeHandler) {
<add>
<add> Assert.notNull(handlerProvider, "handlerProvider is required");
<ide> Assert.notNull(handshakeHandler, "handshakeHandler is required");
<del> this.handshakeHandler = handshakeHandler;
<add> this.handlerProvider = handlerProvider;
<add> this.handshakeHandler = new DefaultHandshakeHandler();
<ide> }
<ide>
<ide> @Override | 10 |
Javascript | Javascript | remove unit tests | 30e24e69a852e9efcdbb7c64e8e30d9370d44e70 | <ide><path>test/unit/src/core/BufferAttribute.tests.js
<ide> export default QUnit.module( 'Core', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.test( "setArray", ( assert ) => {
<del>
<del> var f32a = new Float32Array( [ 1, 2, 3, 4 ] );
<del> var a = new BufferAttribute( f32a, 2, false );
<del>
<del> a.setArray( f32a, 2 );
<del>
<del> assert.strictEqual( a.count, 2, "Check item count" );
<del> assert.strictEqual( a.array, f32a, "Check array" );
<del>
<del> assert.throws(
<del> function () {
<del>
<del> a.setArray( [ 1, 2, 3, 4 ] );
<del>
<del> },
<del> /array should be a Typed Array/,
<del> "Calling setArray with a simple array throws Error"
<del> );
<del>
<del> } );
<del>
<ide> QUnit.todo( "setDynamic", ( assert ) => {
<ide>
<ide> assert.ok( false, "everything's gonna be alright" );
<ide><path>test/unit/src/core/InterleavedBuffer.tests.js
<ide> export default QUnit.module( 'Core', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.test( "setArray", ( assert ) => {
<del>
<del> var f32a = new Float32Array( [ 1, 2, 3, 4 ] );
<del> var f32b = new Float32Array( [] );
<del> var a = new InterleavedBuffer( f32a, 2, false );
<del>
<del> a.setArray( f32a );
<del>
<del> assert.strictEqual( a.count, 2, "Check item count for non-empty array" );
<del> assert.strictEqual( a.array, f32a, "Check array itself" );
<del>
<del> a.setArray( f32b );
<del>
<del> assert.strictEqual( a.count, 0, "Check item count for empty array" );
<del> assert.strictEqual( a.array, f32b, "Check array itself" );
<del>
<del> assert.throws(
<del> function () {
<del>
<del> a.setArray( [ 1, 2, 3, 4 ] );
<del>
<del> },
<del> /array should be a Typed Array/,
<del> "Calling setArray with a non-typed array throws Error"
<del> );
<del>
<del> } );
<del>
<ide> QUnit.todo( "setDynamic", ( assert ) => {
<ide>
<ide> assert.ok( false, "everything's gonna be alright" ); | 2 |
Ruby | Ruby | require gpg and make it a module | 51114139e1c6b442890adec620ffc42975e8fd30 | <ide><path>Library/Homebrew/formula.rb
<ide> require "tap"
<ide> require "keg"
<ide> require "migrator"
<add>require "gpg"
<ide> require "extend/ENV"
<ide>
<ide> # A formula provides instructions and metadata for Homebrew to install a piece
<ide><path>Library/Homebrew/gpg.rb
<ide> require "utils"
<ide>
<del>class Gpg
<add>module Gpg
<ide> module_function
<ide>
<ide> def executable | 2 |
Javascript | Javascript | fix profilingplugin for watch scenarios | 718bd9bc1e8621146f7466e99cbab90b75a95b14 | <ide><path>lib/debug/ProfilingPlugin.js
<ide> class Profiler {
<ide> * @returns {Trace} The trace object
<ide> */
<ide> const createTrace = (fs, outputPath) => {
<del> const trace = new Tracer({
<del> noStream: true
<del> });
<add> const trace = new Tracer();
<ide> const profiler = new Profiler(inspector);
<ide> if (/\/|\\/.test(outputPath)) {
<ide> const dirPath = dirname(fs, outputPath);
<ide> const createTrace = (fs, outputPath) => {
<ide> counter,
<ide> profiler,
<ide> end: callback => {
<add> trace.push("]");
<ide> // Wait until the write stream finishes.
<ide> fsStream.on("close", () => {
<ide> callback();
<ide> class ProfilingPlugin {
<ide> stage: Infinity
<ide> },
<ide> (stats, callback) => {
<add> if (compiler.watchMode) return callback();
<ide> tracer.profiler.stopProfiling().then(parsedResults => {
<ide> if (parsedResults === undefined) {
<ide> tracer.profiler.destroy();
<del> tracer.trace.flush();
<ide> tracer.end(callback);
<ide> return;
<ide> }
<ide> class ProfilingPlugin {
<ide> });
<ide>
<ide> tracer.profiler.destroy();
<del> tracer.trace.flush();
<ide> tracer.end(callback);
<ide> });
<ide> }
<ide><path>test/WatchTestCases.template.js
<ide> const describeCases = config => {
<ide> done
<ide> )
<ide> ) {
<del> compiler.close();
<add> compiler.close(() => {});
<ide> return;
<ide> }
<ide> compiler.close(done);
<ide><path>test/watchCases/plugins/profiling-plugin/0/index.js
<add>it("compiles", function() {
<add> expect(WATCH_STEP).toBe("0");
<add>})
<ide>\ No newline at end of file
<ide><path>test/watchCases/plugins/profiling-plugin/1/index.js
<add>it("should not crash on recompile", function() {
<add> expect(WATCH_STEP).toBe("1");
<add>})
<ide><path>test/watchCases/plugins/profiling-plugin/deprecations.js
<add>module.exports = [
<add> { code: /DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK/ }
<add>];
<ide><path>test/watchCases/plugins/profiling-plugin/webpack.config.js
<add>var webpack = require("../../../../");
<add>
<add>/** @type {import("../../../../").Configuration} */
<add>module.exports = {
<add> plugins: [new webpack.debug.ProfilingPlugin()]
<add>}; | 6 |
Python | Python | remove use of static link in rest api test | c8cea8e49b7327fc03dcf20419faf3012b1b9c45 | <ide><path>tests/api_connexion/endpoints/test_mapped_task_instance_endpoint.py
<ide>
<ide> import pytest
<ide>
<add>from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP
<ide> from airflow.models import TaskInstance
<ide> from airflow.models.baseoperator import BaseOperator
<ide> from airflow.models.dagbag import DagBag
<ide> def test_without_map_index_returns_custom_404(self, one_task_with_mapped_tis):
<ide> 'detail': 'Task instance is mapped, add the map_index value to the URL',
<ide> 'status': 404,
<ide> 'title': 'Task instance not found',
<del> 'type': 'http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/'
<del> 'apache-airflow/latest/stable-rest-api-ref.html#section/Errors/NotFound',
<add> 'type': EXCEPTIONS_LINK_MAP[404],
<ide> }
<ide>
<ide> def test_one_mapped_task_works(self, one_task_with_single_mapped_ti):
<ide> def test_one_mapped_task_works(self, one_task_with_single_mapped_ti):
<ide> 'detail': 'Task instance is mapped, add the map_index value to the URL',
<ide> 'status': 404,
<ide> 'title': 'Task instance not found',
<del> 'type': 'http://apache-airflow-docs.s3-website.eu-central-1.amazonaws.com/docs/'
<del> 'apache-airflow/latest/stable-rest-api-ref.html#section/Errors/NotFound',
<add> 'type': EXCEPTIONS_LINK_MAP[404],
<ide> }
<ide>
<ide> | 1 |
Mixed | Ruby | handle nil translation key | b8b18bbfadd4339fc153d3749f3068cf5c697870 | <ide><path>actionview/CHANGELOG.md
<add>* The `translate` helper now resolves `default` values when a `nil` key is
<add> specified, instead of always returning `nil`.
<add>
<add> *Jonathan Hefner*
<add>
<ide> * Add `config.action_view.image_loading` to configure the default value of
<ide> the `image_tag` `:loading` option.
<ide>
<ide><path>actionview/lib/action_view/helpers/translation_helper.rb
<ide> module TranslationHelper
<ide> #
<ide> def translate(key, **options)
<ide> return key.map { |k| translate(k, **options) } if key.is_a?(Array)
<del> key = key.to_s unless key.is_a?(Symbol)
<add> key = key&.to_s unless key.is_a?(Symbol)
<ide>
<ide> alternatives = if options.key?(:default)
<ide> options[:default].is_a?(Array) ? options.delete(:default).compact : [options.delete(:default)]
<ide> def translate(key, **options)
<ide> options[:raise] = true if options[:raise].nil? && ActionView::Base.raise_on_missing_translations
<ide> default = MISSING_TRANSLATION
<ide>
<del> translation = while key
<add> translation = while key || alternatives.present?
<ide> if alternatives.blank? && !options[:raise].nil?
<ide> default = NO_DEFAULT # let I18n handle missing translation
<ide> end
<ide>
<ide> key = scope_key_by_partial(key)
<del> first_key ||= key
<ide>
<ide> if html_safe_translation_key?(key)
<ide> html_safe_options ||= html_escape_translation_options(options)
<ide> def translate(key, **options)
<ide>
<ide> break alternatives.first if alternatives.present? && !alternatives.first.is_a?(Symbol)
<ide>
<add> first_key ||= key
<ide> key = alternatives&.shift
<ide> end
<ide>
<del> if key.nil?
<add> if key.nil? && !first_key.nil?
<ide> translation = missing_translation(first_key, options)
<ide> key = first_key
<ide> end
<ide> def self.i18n_option?(name)
<ide> end
<ide>
<ide> def scope_key_by_partial(key)
<del> if key.start_with?(".")
<add> if key&.start_with?(".")
<ide> if @current_template&.virtual_path
<ide> @_scope_key_by_partial_cache ||= {}
<ide> @_scope_key_by_partial_cache[@current_template.virtual_path] ||= @current_template.virtual_path.gsub(%r{/_?}, ".")
<ide><path>actionview/test/template/translation_helper_test.rb
<ide> def test_converts_key_to_string_as_necessary
<ide> assert_equal key, translate(:"translations.missing", default: key)
<ide> end
<ide>
<add> def test_returns_nil_for_nil_key_without_default
<add> assert_nil translate(nil)
<add> end
<add>
<add> def test_returns_default_for_nil_key_with_default
<add> assert_equal "Foo", translate(nil, default: "Foo")
<add> assert_equal "Foo", translate(nil, default: :"translations.foo")
<add> assert_predicate translate(nil, default: :"translations.html"), :html_safe?
<add> end
<add>
<ide> def test_returns_missing_translation_message_without_span_wrap
<ide> old_value = ActionView::Base.debug_missing_translation
<ide> ActionView::Base.debug_missing_translation = false | 3 |
Python | Python | fix experiment name | f296795268d1bf34af0d7ebbf2654dd65c653ba4 | <ide><path>official/projects/longformer/longformer_experiments.py
<ide> from official.nlp.data import sentence_prediction_dataloader
<ide> from official.nlp.configs import bert
<ide> from official.nlp.configs import encoders
<del>import official.projects.longformer.sentence_prediction_with_load as sentence_prediction
<add>import official.projects.longformer.sentence_prediction_with_checkpoint_convert as sentence_prediction
<ide>
<ide> from official.projects.longformer.longformer import LongformerEncoderConfig
<ide> | 1 |
PHP | PHP | fix cs error | 311d7dc409dc189b0ab9c24d395f3d95f4565f68 | <ide><path>src/Controller/Component/AuthComponent.php
<ide> public function initialize(array $config)
<ide> /**
<ide> * Callback for Controller.startup event.
<ide> *
<del> * @param \Cake\Event\Event $event
<del> * @return void
<add> * @param \Cake\Event\Event $event Event instance.
<add> * @return void|\Cake\Network\Response
<ide> */
<ide> public function startup(Event $event)
<ide> { | 1 |
Javascript | Javascript | fix reference to distancebetweenpoints | 02279b38fcf561224cca02f8eb5fc3131081f48a | <ide><path>src/core/core.tooltip.js
<ide> var positioners = {
<ide> var el = elements[i].element;
<ide> if (el && el.hasValue()) {
<ide> var center = el.getCenterPoint();
<del> var d = helpers.distanceBetweenPoints(eventPosition, center);
<add> var d = helpers.math.distanceBetweenPoints(eventPosition, center);
<ide>
<ide> if (d < minDistance) {
<ide> minDistance = d; | 1 |
Ruby | Ruby | remove incorrect comments | e38aa9d7464c6cfd851dd4436b67a858e4e899f3 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def #{column_type}(*args, **options)
<ide> # end
<ide> # end
<ide> #
<del> # The table definitions
<del> # The Columns are stored as a ColumnDefinition in the #columns attribute.
<ide> class TableDefinition
<ide> include ColumnMethods
<ide>
<del> # An array of ColumnDefinition objects, representing the column changes
<del> # that have been defined.
<ide> attr_accessor :indexes
<ide> attr_reader :name, :temporary, :options, :as, :foreign_keys, :native
<ide> | 1 |
Javascript | Javascript | allow small differences in offset.top | 9f9e204bba41b7a9cde5ba7e065d817ef8b18c41 | <ide><path>test/unit/offset.js
<ide> QUnit.test( "fractions (see #7730 and #7885)", function( assert ) {
<ide>
<ide> result = div.offset();
<ide>
<del> assert.equal( result.top, expected.top, "Check top" );
<add> // Support: Chrome 45-46+
<add> // In recent Chrome these values differ a little.
<add> assert.ok( Math.abs( result.top - expected.top ) < 0.25, "Check top within 0.25 of expected" );
<ide> assert.equal( result.left, expected.left, "Check left" );
<ide>
<ide> div.remove(); | 1 |
PHP | PHP | apply locatorawaretrait setter and getter | 0cde5f8cf8568d3158216bd514a8348c9ca7031b | <ide><path>src/Console/Shell.php
<ide> public function __construct(ConsoleIo $io = null)
<ide> }
<ide> $this->_io = $io ?: new ConsoleIo();
<ide>
<del> $locator = $this->tableLocator() ? : 'Cake\ORM\TableRegistry';
<add> $locator = $this->getTableLocator() ? : 'Cake\ORM\TableRegistry';
<ide> $this->modelFactory('Table', [$locator, 'get']);
<ide> $this->Tasks = new TaskRegistry($this);
<ide>
<ide><path>src/Controller/Controller.php
<ide> public function __construct(ServerRequest $request = null, Response $response =
<ide> $this->eventManager($eventManager);
<ide> }
<ide>
<del> $this->modelFactory('Table', [$this->tableLocator(), 'get']);
<add> $this->modelFactory('Table', [$this->getTableLocator(), 'get']);
<ide> $modelClass = ($this->plugin ? $this->plugin . '.' : '') . $this->name;
<ide> $this->_setModelClass($modelClass);
<ide>
<ide><path>src/ORM/Association.php
<ide> public function getTarget()
<ide> $registryAlias = $this->_name;
<ide> }
<ide>
<del> $tableLocator = $this->tableLocator();
<add> $tableLocator = $this->getTableLocator();
<ide>
<ide> $config = [];
<ide> $exists = $tableLocator->exists($registryAlias);
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> public function junction($table = null)
<ide> return $this->_junctionTable;
<ide> }
<ide>
<del> $tableLocator = $this->tableLocator();
<add> $tableLocator = $this->getTableLocator();
<ide> if ($table === null && $this->_through) {
<ide> $table = $this->_through;
<ide> } elseif ($table === null) {
<ide><path>src/ORM/Behavior/TranslateBehavior.php
<ide> public function __construct(Table $table, array $config = [])
<ide> */
<ide> public function initialize(array $config)
<ide> {
<del> $this->_translationTable = $this->tableLocator()->get($this->_config['translationTable']);
<add> $this->_translationTable = $this->getTableLocator()->get($this->_config['translationTable']);
<ide>
<ide> $this->setupFieldAssociations(
<ide> $this->_config['fields'],
<ide> public function setupFieldAssociations($fields, $table, $model, $strategy)
<ide> $targetAlias = $this->_translationTable->getAlias();
<ide> $alias = $this->_table->getAlias();
<ide> $filter = $this->_config['onlyTranslated'];
<del> $tableLocator = $this->tableLocator();
<add> $tableLocator = $this->getTableLocator();
<ide>
<ide> foreach ($fields as $field) {
<ide> $name = $alias . '_' . $field . '_translation';
<ide><path>src/View/Cell.php
<ide> public function __construct(
<ide> $this->eventManager($eventManager);
<ide> $this->request = $request;
<ide> $this->response = $response;
<del> $this->modelFactory('Table', [$this->tableLocator(), 'get']);
<add> $this->modelFactory('Table', [$this->getTableLocator(), 'get']);
<ide>
<ide> $this->_validCellOptions = array_merge(['action', 'args'], $this->_validCellOptions);
<ide> foreach ($this->_validCellOptions as $var) {
<ide><path>tests/TestCase/ORM/Locator/LocatorAwareTraitTest.php
<ide> public function setUp()
<ide> */
<ide> public function testTableLocator()
<ide> {
<del> $tableLocator = $this->subject->tableLocator();
<add> $tableLocator = $this->subject->getTableLocator();
<ide> $this->assertSame(TableRegistry::getTableLocator(), $tableLocator);
<ide>
<ide> $newLocator = $this->getMockBuilder('Cake\ORM\Locator\LocatorInterface')->getMock();
<del> $subjectLocator = $this->subject->tableLocator($newLocator);
<add> $this->subject->setTableLocator($newLocator);
<add> $subjectLocator = $this->subject->getTableLocator();
<ide> $this->assertSame($newLocator, $subjectLocator);
<ide> }
<ide> } | 7 |
Javascript | Javascript | use regex error check in test-crypto-random | c3cb0edd8d4202270d59c94083be5007f7870416 | <ide><path>test/parallel/test-crypto-random.js
<ide> const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
<ide> // length exceeds max acceptable value"
<ide> assert.throws(function() {
<ide> crypto.randomBytes((-1 >>> 0) + 1);
<del>}, TypeError);
<add>}, /^TypeError: size must be a number >= 0$/); | 1 |
Python | Python | remove use of kwdict workaround fixed in py2.7 | 3ff387099dac98bc78d20f79b168ecc03f78327a | <ide><path>celery/canvas.py
<ide> from operator import itemgetter
<ide> from itertools import chain as _chain
<ide>
<del>from kombu.utils import cached_property, fxrange, kwdict, reprcall, uuid
<add>from kombu.utils import cached_property, fxrange, reprcall, uuid
<ide>
<ide> from celery._state import current_app, get_current_worker_task
<ide> from celery.utils.functional import (
<ide> def register_type(cls, subclass, name=None):
<ide> def from_dict(self, d, app=None):
<ide> typ = d.get('subtask_type')
<ide> if typ:
<del> return self.TYPES[typ].from_dict(kwdict(d), app=app)
<add> return self.TYPES[typ].from_dict(d, app=app)
<ide> return Signature(d, app=app)
<ide>
<ide> def __init__(self, task=None, args=None, kwargs=None, options=None,
<ide> def from_dict(self, d, app=None):
<ide> if d['args'] and tasks:
<ide> # partial args passed on to first task in chain (Issue #1057).
<ide> tasks[0]['args'] = tasks[0]._merge(d['args'])[0]
<del> return chain(*d['kwargs']['tasks'], app=app, **kwdict(d['options']))
<add> return chain(*d['kwargs']['tasks'], app=app, **d['options'])
<ide>
<ide> @property
<ide> def app(self):
<ide> def from_dict(self, d, app=None):
<ide> # partial args passed on to all tasks in the group (Issue #1057).
<ide> for task in tasks:
<ide> task['args'] = task._merge(d['args'])[0]
<del> return group(tasks, app=app, **kwdict(d['options']))
<add> return group(tasks, app=app, **d['options'])
<ide>
<ide> def _prepared(self, tasks, partial_args, group_id, root_id, dict=dict,
<ide> Signature=Signature, from_dict=Signature.from_dict):
<ide> def freeze(self, *args, **kwargs):
<ide>
<ide> @classmethod
<ide> def from_dict(self, d, app=None):
<del> args, d['kwargs'] = self._unpack_args(**kwdict(d['kwargs']))
<del> return self(*args, app=app, **kwdict(d))
<add> args, d['kwargs'] = self._unpack_args(**d['kwargs'])
<add> return self(*args, app=app, **d)
<ide>
<ide> @staticmethod
<ide> def _unpack_args(header=None, body=None, **kwargs):
<ide><path>celery/utils/__init__.py
<ide> def resolve(match):
<ide> instantiate, import_from_cwd
<ide> )
<ide> from .functional import chunks, noop # noqa
<del>from kombu.utils import cached_property, kwdict, uuid # noqa
<add>from kombu.utils import cached_property, uuid # noqa
<ide> gen_unique_id = uuid | 2 |
Python | Python | assign ips upon machine creation | 92828734fc9576d943ae2d86397d90a70d12c88c | <ide><path>libcloud/compute/drivers/packet.py
<ide> def create_node(self, name, size, image, location,
<ide> # if project has been specified on initialization of driver, then
<ide> # create on this project
<ide>
<del> import ipdb; ipdb.set_trace();
<ide> if self.project_id:
<ide> ex_project_id = self.project_id
<ide> else: | 1 |
Python | Python | use import to find data package | 797f286c388b4527e44d2e3513a69724f4cc7155 | <ide><path>spacy/cli/link.py
<ide>
<ide> import pip
<ide> from pathlib import Path
<del>from distutils.sysconfig import get_python_lib
<add>import importlib
<ide> from .. import util
<ide>
<ide>
<ide> def link(origin, link_name, force=False):
<ide> symlink(origin, link_name, force)
<ide>
<ide>
<del>def link_package(origin, link_name, force=False):
<del> package_path = get_python_lib()
<del> meta = get_meta(package_path, origin)
<del> data_dir = origin + '-' + meta['version']
<del> model_path = Path(package_path) / origin / data_dir
<add>def link_package(package_name, link_name, force=False):
<add> # Here we're importing the module just to find it. This is worryingly
<add> # indirect, but it's otherwise very difficult to find the package.
<add> # Python's installation and import rules are very complicated.
<add> pkg = importlib.import_module(package_name)
<add> package_path = Path(pkg.__file__).parent.parent
<add>
<add> meta = get_meta(package_path, package_name)
<add> model_name = package_name + '-' + meta['version']
<add> model_path = package_path / package_name / model_name
<ide> symlink(model_path, link_name, force)
<ide>
<ide> | 1 |
Ruby | Ruby | add cpu family for apple’s m1 soc | 2a197af07610bb399ed87156062b13cd52e94b48 | <ide><path>Library/Homebrew/extend/os/mac/hardware/cpu.rb
<ide> def type
<ide> end
<ide>
<ide> def family
<del> case sysctl_int("hw.cpufamily")
<del> when 0x73d67300 # Yonah: Core Solo/Duo
<del> :core
<del> when 0x426f69ef # Merom: Core 2 Duo
<del> :core2
<del> when 0x78ea4fbc # Penryn
<del> :penryn
<del> when 0x6b5a4cd2 # Nehalem
<del> :nehalem
<del> when 0x573B5EEC # Arrandale
<del> :arrandale
<del> when 0x5490B78C # Sandy Bridge
<del> :sandybridge
<del> when 0x1F65E835 # Ivy Bridge
<del> :ivybridge
<del> when 0x10B282DC # Haswell
<del> :haswell
<del> when 0x582ed09c # Broadwell
<del> :broadwell
<del> when 0x37fc219f # Skylake
<del> :skylake
<del> when 0x0f817246 # Kaby Lake
<del> :kabylake
<del> when 0x38435547 # Ice Lake
<del> :icelake
<del> when 0x07d34b9f # ARMv8.3-A (Vortex, Tempest)
<del> :arm_vortex_tempest
<add> if arm?
<add> arm_family
<add> elsif intel?
<add> intel_family
<ide> else
<ide> :dunno
<ide> end
<ide> def physical_cpu_arm64?
<ide>
<ide> private
<ide>
<add> def arm_family
<add> case sysctl_int("hw.cpufamily")
<add> when 0x07d34b9f # ARMv8.3-A (Vortex, Tempest)
<add> :arm_vortex_tempest
<add> when 0x573b5eec, 0x1b588bb3 # ARMv8.4-A (Firestorm, Icestorm)
<add> :arm_firestorm_icestorm
<add> else
<add> :dunno
<add> end
<add> end
<add>
<add> def intel_family
<add> case sysctl_int("hw.cpufamily")
<add> when 0x73d67300 # Yonah: Core Solo/Duo
<add> :core
<add> when 0x426f69ef # Merom: Core 2 Duo
<add> :core2
<add> when 0x78ea4fbc # Penryn
<add> :penryn
<add> when 0x6b5a4cd2 # Nehalem
<add> :nehalem
<add> when 0x573b5eec # Arrandale
<add> :arrandale
<add> when 0x5490b78c # Sandy Bridge
<add> :sandybridge
<add> when 0x1f65e835 # Ivy Bridge
<add> :ivybridge
<add> when 0x10b282dc # Haswell
<add> :haswell
<add> when 0x582ed09c # Broadwell
<add> :broadwell
<add> when 0x37fc219f # Skylake
<add> :skylake
<add> when 0x0f817246 # Kaby Lake
<add> :kabylake
<add> when 0x38435547 # Ice Lake
<add> :icelake
<add> else
<add> :dunno
<add> end
<add> end
<add>
<ide> def sysctl_bool(key)
<ide> sysctl_int(key) == 1
<ide> end
<ide><path>Library/Homebrew/test/hardware/cpu_spec.rb
<ide> describe "::family" do
<ide> let(:cpu_families) {
<ide> [
<add> :arm_firestorm_icestorm,
<ide> :arm_vortex_tempest,
<ide> :arrandale,
<ide> :atom,
<ide> it "returns the current CPU's family name as a symbol, or :dunno if it cannot be detected" do
<ide> expect(cpu_families).to include described_class.family
<ide> end
<add>
<add> context "when hw.cpufamily is 0x573b5eec on a Mac", :needs_macos do
<add> before do
<add> allow(described_class)
<add> .to receive(:sysctl_int)
<add> .with("hw.cpufamily")
<add> .and_return(0x573b5eec)
<add> end
<add>
<add> it "returns :arm_firestorm_icestorm on ARM" do
<add> allow(described_class).to receive(:arm?).and_return(true)
<add> allow(described_class).to receive(:intel?).and_return(false)
<add>
<add> expect(described_class.family).to eq(:arm_firestorm_icestorm)
<add> end
<add>
<add> it "returns :westmere on Intel" do
<add> allow(described_class).to receive(:arm?).and_return(false)
<add> allow(described_class).to receive(:intel?).and_return(true)
<add>
<add> expect(described_class.family).to eq(:westmere)
<add> end
<add> end
<ide> end
<ide> end | 2 |
Javascript | Javascript | add post-commit hook | b38ac13f946ad305ead05a6a83511549db27322e | <ide><path>packages/react-devtools-shared/src/__tests__/profilingHostRoot-test.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> */
<add>
<add>describe('profiling HostRoot', () => {
<add> let React;
<add> let ReactDOM;
<add> let Scheduler;
<add> let store: Store;
<add> let utils;
<add> let getEffectDurations;
<add>
<add> let effectDurations;
<add> let passiveEffectDurations;
<add>
<add> beforeEach(() => {
<add> utils = require('./utils');
<add> utils.beforeEachProfiling();
<add>
<add> getEffectDurations = require('../backend/utils').getEffectDurations;
<add>
<add> store = global.store;
<add>
<add> React = require('react');
<add> ReactDOM = require('react-dom');
<add> Scheduler = require('scheduler');
<add>
<add> effectDurations = [];
<add> passiveEffectDurations = [];
<add>
<add> // This is the DevTools hook installed by the env.beforEach()
<add> // The hook is installed as a read-only property on the window,
<add> // so for our test purposes we can just override the commit hook.
<add> const hook = global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
<add> hook.onPostCommitFiberRoot = function onPostCommitFiberRoot(
<add> rendererID,
<add> root,
<add> ) {
<add> const {effectDuration, passiveEffectDuration} = getEffectDurations(root);
<add> effectDurations.push(effectDuration);
<add> passiveEffectDurations.push(passiveEffectDuration);
<add> };
<add> });
<add>
<add> it('should expose passive and layout effect durations for render()', () => {
<add> function App() {
<add> React.useEffect(() => {
<add> Scheduler.unstable_advanceTime(10);
<add> });
<add> React.useLayoutEffect(() => {
<add> Scheduler.unstable_advanceTime(100);
<add> });
<add> return null;
<add> }
<add>
<add> utils.act(() => store.profilerStore.startProfiling());
<add> utils.act(() => {
<add> const container = document.createElement('div');
<add> ReactDOM.render(<App />, container);
<add> });
<add> utils.act(() => store.profilerStore.stopProfiling());
<add>
<add> expect(effectDurations).toHaveLength(1);
<add> const effectDuration = effectDurations[0];
<add> expect(effectDuration === null || effectDuration === 100).toBe(true);
<add> expect(passiveEffectDurations).toHaveLength(1);
<add> const passiveEffectDuration = passiveEffectDurations[0];
<add> expect(passiveEffectDuration === null || passiveEffectDuration === 10).toBe(
<add> true,
<add> );
<add> });
<add>
<add> it('should expose passive and layout effect durations for createRoot()', () => {
<add> function App() {
<add> React.useEffect(() => {
<add> Scheduler.unstable_advanceTime(10);
<add> });
<add> React.useLayoutEffect(() => {
<add> Scheduler.unstable_advanceTime(100);
<add> });
<add> return null;
<add> }
<add>
<add> utils.act(() => store.profilerStore.startProfiling());
<add> utils.act(() => {
<add> const container = document.createElement('div');
<add> const root = ReactDOM.unstable_createRoot(container);
<add> root.render(<App />);
<add> });
<add> utils.act(() => store.profilerStore.stopProfiling());
<add>
<add> expect(effectDurations).toHaveLength(1);
<add> const effectDuration = effectDurations[0];
<add> expect(effectDuration === null || effectDuration === 100).toBe(true);
<add> expect(passiveEffectDurations).toHaveLength(1);
<add> const passiveEffectDuration = passiveEffectDurations[0];
<add> expect(passiveEffectDuration === null || passiveEffectDuration === 10).toBe(
<add> true,
<add> );
<add> });
<add>
<add> it('should properly reset passive and layout effect durations between commits', () => {
<add> function App({shouldCascade}) {
<add> const [, setState] = React.useState(false);
<add> React.useEffect(() => {
<add> Scheduler.unstable_advanceTime(10);
<add> });
<add> React.useLayoutEffect(() => {
<add> Scheduler.unstable_advanceTime(100);
<add> });
<add> React.useLayoutEffect(() => {
<add> if (shouldCascade) {
<add> setState(true);
<add> }
<add> }, [shouldCascade]);
<add> return null;
<add> }
<add>
<add> const container = document.createElement('div');
<add> const root = ReactDOM.unstable_createRoot(container);
<add>
<add> utils.act(() => store.profilerStore.startProfiling());
<add> utils.act(() => root.render(<App />));
<add> utils.act(() => root.render(<App shouldCascade={true} />));
<add> utils.act(() => store.profilerStore.stopProfiling());
<add>
<add> expect(effectDurations).toHaveLength(3);
<add> expect(passiveEffectDurations).toHaveLength(3);
<add>
<add> for (let i = 0; i < effectDurations.length; i++) {
<add> const effectDuration = effectDurations[i];
<add> expect(effectDuration === null || effectDuration === 100).toBe(true);
<add> const passiveEffectDuration = passiveEffectDurations[i];
<add> expect(
<add> passiveEffectDuration === null || passiveEffectDuration === 10,
<add> ).toBe(true);
<add> }
<add> });
<add>});
<ide><path>packages/react-devtools-shared/src/backend/legacy/renderer.js
<ide> export function attach(
<ide> const handleCommitFiberUnmount = () => {
<ide> throw new Error('handleCommitFiberUnmount not supported by this renderer');
<ide> };
<add> const handlePostCommitFiberRoot = () => {
<add> throw new Error('handlePostCommitFiberRoot not supported by this renderer');
<add> };
<ide> const overrideSuspense = () => {
<ide> throw new Error('overrideSuspense not supported by this renderer');
<ide> };
<ide> export function attach(
<ide> getProfilingData,
<ide> handleCommitFiberRoot,
<ide> handleCommitFiberUnmount,
<add> handlePostCommitFiberRoot,
<ide> inspectElement,
<ide> logElementToConsole,
<ide> overrideSuspense,
<ide><path>packages/react-devtools-shared/src/backend/renderer.js
<ide> import {
<ide> copyWithDelete,
<ide> copyWithRename,
<ide> copyWithSet,
<add> getEffectDurations,
<ide> } from './utils';
<ide> import {
<ide> __DEBUG__,
<ide> export function getInternalReactConstants(
<ide> LegacyHiddenComponent,
<ide> MemoComponent,
<ide> OffscreenComponent,
<add> Profiler,
<ide> ScopeComponent,
<ide> SimpleMemoComponent,
<ide> SuspenseComponent,
<ide> export function getInternalReactConstants(
<ide> return 'Scope';
<ide> case SuspenseListComponent:
<ide> return 'SuspenseList';
<add> case Profiler:
<add> return 'Profiler';
<ide> default:
<ide> const typeSymbol = getTypeSymbol(type);
<ide>
<ide> export function attach(
<ide> // Checking root.memoizedInteractions handles multi-renderer edge-case-
<ide> // where some v16 renderers support profiling and others don't.
<ide> if (isProfiling && root.memoizedInteractions != null) {
<del> // Profiling durations are only available for certain builds.
<del> // If available, they'll be stored on the HostRoot.
<del> let effectDuration = null;
<del> let passiveEffectDuration = null;
<del> const hostRoot = root.current;
<del> if (hostRoot != null) {
<del> const stateNode = hostRoot.stateNode;
<del> if (stateNode != null) {
<del> effectDuration =
<del> stateNode.effectDuration != null
<del> ? stateNode.effectDuration
<del> : null;
<del> passiveEffectDuration =
<del> stateNode.passiveEffectDuration != null
<del> ? stateNode.passiveEffectDuration
<del> : null;
<del> }
<del> }
<del>
<ide> // If profiling is active, store commit time and duration, and the current interactions.
<ide> // The frontend may request this information after profiling has stopped.
<ide> currentCommitProfilingMetadata = {
<ide> export function attach(
<ide> ),
<ide> maxActualDuration: 0,
<ide> priorityLevel: null,
<del> effectDuration,
<del> passiveEffectDuration,
<add> effectDuration: null,
<add> passiveEffectDuration: null,
<ide> };
<ide> }
<ide>
<ide> export function attach(
<ide> recordUnmount(fiber, false);
<ide> }
<ide>
<add> function handlePostCommitFiberRoot(root) {
<add> const isProfilingSupported = root.memoizedInteractions != null;
<add> if (isProfiling && isProfilingSupported) {
<add> if (currentCommitProfilingMetadata !== null) {
<add> const {effectDuration, passiveEffectDuration} = getEffectDurations(
<add> root,
<add> );
<add> currentCommitProfilingMetadata.effectDuration = effectDuration;
<add> currentCommitProfilingMetadata.passiveEffectDuration = passiveEffectDuration;
<add> }
<add> }
<add> }
<add>
<ide> function handleCommitFiberRoot(root, priorityLevel) {
<ide> const current = root.current;
<ide> const alternate = current.alternate;
<ide> export function attach(
<ide> const isProfilingSupported = root.memoizedInteractions != null;
<ide>
<ide> if (isProfiling && isProfilingSupported) {
<del> // Profiling durations are only available for certain builds.
<del> // If available, they'll be stored on the HostRoot.
<del> let effectDuration = null;
<del> let passiveEffectDuration = null;
<del> const hostRoot = root.current;
<del> if (hostRoot != null) {
<del> const stateNode = hostRoot.stateNode;
<del> if (stateNode != null) {
<del> effectDuration =
<del> stateNode.effectDuration != null ? stateNode.effectDuration : null;
<del> passiveEffectDuration =
<del> stateNode.passiveEffectDuration != null
<del> ? stateNode.passiveEffectDuration
<del> : null;
<del> }
<del> }
<del>
<ide> // If profiling is active, store commit time and duration, and the current interactions.
<ide> // The frontend may request this information after profiling has stopped.
<ide> currentCommitProfilingMetadata = {
<ide> export function attach(
<ide> maxActualDuration: 0,
<ide> priorityLevel:
<ide> priorityLevel == null ? null : formatPriorityLevel(priorityLevel),
<del> effectDuration,
<del> passiveEffectDuration,
<add>
<add> // Initialize to null; if new enough React version is running,
<add> // these values will be read during separate handlePostCommitFiberRoot() call.
<add> effectDuration: null,
<add> passiveEffectDuration: null,
<ide> };
<ide> }
<ide>
<ide> export function attach(
<ide> getProfilingData,
<ide> handleCommitFiberRoot,
<ide> handleCommitFiberUnmount,
<add> handlePostCommitFiberRoot,
<ide> inspectElement,
<ide> logElementToConsole,
<ide> prepareViewAttributeSource,
<ide><path>packages/react-devtools-shared/src/backend/types.js
<ide> export type RendererInterface = {
<ide> getPathForElement: (id: number) => Array<PathFrame> | null,
<ide> handleCommitFiberRoot: (fiber: Object, commitPriority?: number) => void,
<ide> handleCommitFiberUnmount: (fiber: Object) => void,
<add> handlePostCommitFiberRoot: (fiber: Object) => void,
<ide> inspectElement: (
<ide> requestID: number,
<ide> id: number,
<ide><path>packages/react-devtools-shared/src/backend/utils.js
<ide> export function copyWithSet(
<ide> return updated;
<ide> }
<ide>
<add>export function getEffectDurations(root: Object) {
<add> // Profiling durations are only available for certain builds.
<add> // If available, they'll be stored on the HostRoot.
<add> let effectDuration = null;
<add> let passiveEffectDuration = null;
<add> const hostRoot = root.current;
<add> if (hostRoot != null) {
<add> const stateNode = hostRoot.stateNode;
<add> if (stateNode != null) {
<add> effectDuration =
<add> stateNode.effectDuration != null ? stateNode.effectDuration : null;
<add> passiveEffectDuration =
<add> stateNode.passiveEffectDuration != null
<add> ? stateNode.passiveEffectDuration
<add> : null;
<add> }
<add> }
<add> return {effectDuration, passiveEffectDuration};
<add>}
<add>
<ide> export function serializeToString(data: any): string {
<ide> const cache = new Set();
<ide> // Use a custom replacer function to protect against circular references.
<ide><path>packages/react-devtools-shared/src/hook.js
<ide> export function installHook(target: any): DevToolsHook | null {
<ide> }
<ide> }
<ide>
<add> function onPostCommitFiberRoot(rendererID, root) {
<add> const rendererInterface = rendererInterfaces.get(rendererID);
<add> if (rendererInterface != null) {
<add> rendererInterface.handlePostCommitFiberRoot(root);
<add> }
<add> }
<add>
<ide> // TODO: More meaningful names for "rendererInterfaces" and "renderers".
<ide> const fiberRoots = {};
<ide> const rendererInterfaces = new Map();
<ide> export function installHook(target: any): DevToolsHook | null {
<ide> checkDCE,
<ide> onCommitFiberUnmount,
<ide> onCommitFiberRoot,
<add> onPostCommitFiberRoot,
<ide> };
<ide>
<ide> Object.defineProperty(
<ide><path>packages/react-devtools-shell/src/app/InteractionTracing/index.js
<ide> import {
<ide> unstable_wrap as wrap,
<ide> } from 'scheduler/tracing';
<ide>
<add>function sleep(ms) {
<add> const start = performance.now();
<add> let now;
<add> do {
<add> now = performance.now();
<add> } while (now - ms < start);
<add>}
<add>
<ide> export default function InteractionTracing() {
<ide> const [count, setCount] = useState(0);
<ide> const [shouldCascade, setShouldCascade] = useState(false);
<ide> export default function InteractionTracing() {
<ide> }, [count, shouldCascade]);
<ide>
<ide> useLayoutEffect(() => {
<del> Math.sqrt(100 * 100 * 100 * 100 * 100);
<add> sleep(150);
<add> });
<add>
<add> useEffect(() => {
<add> sleep(300);
<ide> });
<ide>
<ide> return (
<ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.new.js
<ide> export function onCommitRoot(root: FiberRoot, eventPriority: EventPriority) {
<ide> }
<ide> }
<ide>
<add>export function onPostCommitRoot(root: FiberRoot) {
<add> if (
<add> injectedHook &&
<add> typeof injectedHook.onPostCommitFiberRoot === 'function'
<add> ) {
<add> try {
<add> injectedHook.onPostCommitFiberRoot(rendererID, root);
<add> } catch (err) {
<add> if (__DEV__) {
<add> if (!hasLoggedError) {
<add> hasLoggedError = true;
<add> console.error('React instrumentation encountered an error: %s', err);
<add> }
<add> }
<add> }
<add> }
<add>}
<add>
<ide> export function onCommitUnmount(fiber: Fiber) {
<ide> if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
<ide> try {
<ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.old.js
<ide> export function onCommitRoot(root: FiberRoot, eventPriority: EventPriority) {
<ide> }
<ide> }
<ide>
<add>export function onPostCommitRoot(root: FiberRoot) {
<add> if (
<add> injectedHook &&
<add> typeof injectedHook.onPostCommitFiberRoot === 'function'
<add> ) {
<add> try {
<add> injectedHook.onPostCommitFiberRoot(rendererID, root);
<add> } catch (err) {
<add> if (__DEV__) {
<add> if (!hasLoggedError) {
<add> hasLoggedError = true;
<add> console.error('React instrumentation encountered an error: %s', err);
<add> }
<add> }
<add> }
<add> }
<add>}
<add>
<ide> export function onCommitUnmount(fiber: Fiber) {
<ide> if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
<ide> try {
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> hasCaughtError,
<ide> clearCaughtError,
<ide> } from 'shared/ReactErrorUtils';
<del>import {onCommitRoot as onCommitRootDevTools} from './ReactFiberDevToolsHook.new';
<add>import {
<add> onCommitRoot as onCommitRootDevTools,
<add> onPostCommitRoot as onPostCommitRootDevTools,
<add>} from './ReactFiberDevToolsHook.new';
<ide> import {onCommitRoot as onCommitRootTestSelector} from './ReactTestSelectors';
<ide>
<ide> // Used by `act`
<ide> function flushPassiveEffectsImpl() {
<ide> nestedPassiveUpdateCount =
<ide> rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
<ide>
<add> // TODO: Move to commitPassiveMountEffects
<add> onPostCommitRootDevTools(root);
<add> if (enableProfilerTimer && enableProfilerCommitHooks) {
<add> const stateNode = root.current.stateNode;
<add> stateNode.effectDuration = 0;
<add> stateNode.passiveEffectDuration = 0;
<add> }
<add>
<ide> return true;
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> hasCaughtError,
<ide> clearCaughtError,
<ide> } from 'shared/ReactErrorUtils';
<del>import {onCommitRoot as onCommitRootDevTools} from './ReactFiberDevToolsHook.old';
<add>import {
<add> onCommitRoot as onCommitRootDevTools,
<add> onPostCommitRoot as onPostCommitRootDevTools,
<add>} from './ReactFiberDevToolsHook.old';
<ide> import {onCommitRoot as onCommitRootTestSelector} from './ReactTestSelectors';
<ide>
<ide> // Used by `act`
<ide> function flushPassiveEffectsImpl() {
<ide> nestedPassiveUpdateCount =
<ide> rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
<ide>
<add> // TODO: Move to commitPassiveMountEffects
<add> onPostCommitRootDevTools(root);
<add> if (enableProfilerTimer && enableProfilerCommitHooks) {
<add> const stateNode = root.current.stateNode;
<add> stateNode.effectDuration = 0;
<add> stateNode.passiveEffectDuration = 0;
<add> }
<add>
<ide> return true;
<ide> }
<ide> | 11 |
Python | Python | fix a minor typo in dispatch documentation | 8ec4c73e9e9268e0c9e42ed000799f32b92745e8 | <ide><path>numpy/doc/dispatch.py
<ide> class to indicate that it would like to handle computations in a custom-defined
<ide> ... return arr._i * arr._N
<ide> ...
<ide> >>> @implements(np.mean)
<del>... def sum(arr):
<add>... def mean(arr):
<ide> ... "Implementation of np.mean for DiagonalArray objects"
<ide> ... return arr._i / arr._N
<ide> ... | 1 |
Python | Python | use hints for sizeof checks, to speed things up | e122cedce5154ac7c4e9fb6cc8316d4574b7f071 | <ide><path>numpy/core/setup.py
<ide> def check_types(config_cmd, ext, build_dir):
<ide> private_defines = []
<ide> public_defines = []
<ide>
<add> # Expected size (in number of bytes) for each type. This is an
<add> # optimization: those are only hints, and an exhaustive search for the size
<add> # is done if the hints are wrong.
<add> expected = {}
<add> expected['short'] = [2]
<add> expected['int'] = [4]
<add> expected['long'] = [8, 4]
<add> expected['float'] = [4]
<add> expected['double'] = [8]
<add> expected['long double'] = [8, 12, 16]
<add> expected['Py_intptr_t'] = [4, 8]
<add> expected['PY_LONG_LONG'] = [8]
<add> expected['long long'] = [8]
<add>
<ide> # Check we have the python header (-dev* packages on Linux)
<ide> result = config_cmd.check_header('Python.h')
<ide> if not result:
<ide> def check_types(config_cmd, ext, build_dir):
<ide>
<ide> # Check basic types sizes
<ide> for type in ('short', 'int', 'long', 'float', 'double', 'long double'):
<del> res = config_cmd.check_type_size(type)
<add> res = config_cmd.check_type_size(type, expected=expected[type])
<ide> if res >= 0:
<ide> if not type == 'long double':
<ide> private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))
<ide> def check_types(config_cmd, ext, build_dir):
<ide>
<ide> for type in ('Py_intptr_t',):
<ide> res = config_cmd.check_type_size(type, headers=["Python.h"],
<del> library_dirs=[pythonlib_dir()])
<add> library_dirs=[pythonlib_dir()],
<add> expected=expected[type])
<add>
<ide> if res >= 0:
<ide> private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))
<ide> public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
<ide> def check_types(config_cmd, ext, build_dir):
<ide> # We check declaration AND type because that's how distutils does it.
<ide> if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']):
<ide> res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'],
<del> library_dirs=[pythonlib_dir()])
<add> library_dirs=[pythonlib_dir()],
<add> expected=expected['PY_LONG_LONG'])
<ide> if res >= 0:
<ide> private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))
<ide> public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))
<ide> else:
<ide> raise SystemError("Checking sizeof (%s) failed !" % 'PY_LONG_LONG')
<ide>
<del> res = config_cmd.check_type_size('long long')
<add> res = config_cmd.check_type_size('long long',
<add> expected=expected['long long'])
<ide> if res >= 0:
<ide> #private_defines.append(('SIZEOF_%s' % sym2def('long long'), '%d' % res))
<ide> public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res)) | 1 |
Text | Text | add note about error banner on sign in | 7e835bae1b442e059dea692a0525fe2885889fc1 | <ide><path>docs/how-to-setup-freecodecamp-locally.md
<ide> npm run seed
<ide> # Restart the application
<ide> npm run develop
<ide> ```
<add>
<add>If you can't sign in, and instead, you see a banner with an error message saying that it'll be reported to freeCodeCamp, please double-check that your local port 3000 is not in use by a different program. | 1 |
Text | Text | improve language in python/commenting-code | 1ce0aba1844edacba2a49f10b2f28ddb1c5d8c4e | <ide><path>guide/english/python/commenting-code/index.md
<ide> ---
<ide> title: Python Commenting Code
<ide> ---
<add>
<ide> Comments are used to annotate, describe, or explain code that is complex or difficult to understand. Python will intentionally ignore comments when it compiles to bytecode by the interpreter. <a href='https://www.python.org/dev/peps/pep-0008/#comments' target='_blank' rel='nofollow'>`PEP 8`</a> has a section dealing with comments. They also increase the readablity of code by adding easy and descriptive language for better understanding.
<ide>
<ide> **Block** and **inline** comments start with a `#`, followed by a space before the comment:
<ide> Comments are used to annotate, describe, or explain code that is complex or diff
<ide> print('Hello world!') # This is an inline commment.
<ide> ```
<ide>
<del>Python does not include a formal way to write multiline comments. Each line of a comment spanning multiple lines should start with `#` and a space:
<add>Python does not include a formal way to write multiline comments. Instead, each line of a comment spanning multiple lines should start with `#` and a space:
<ide> ```python
<ide> # This is the first line of a multiline comment.
<ide> # This is the second line. | 1 |
Ruby | Ruby | avoid extra `show variables` in migration | 57604cf24ce40a23de0e8d75fc366c24c9fe3aac | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def column_exists?(table_name, column_name, type = nil, options = {})
<ide> checks = []
<ide> checks << lambda { |c| c.name == column_name }
<ide> checks << lambda { |c| c.type == type } if type
<del> [:limit, :precision, :scale, :default, :null].each do |attr|
<add> (migration_keys - [:name]).each do |attr|
<ide> checks << lambda { |c| c.send(attr) == options[attr] } if options.key?(attr)
<ide> end
<ide>
<ide> def initialize_internal_metadata_table
<ide> ActiveRecord::InternalMetadata.create_table
<ide> end
<ide>
<add> def internal_string_options_for_primary_key # :nodoc:
<add> { primary_key: true }
<add> end
<add>
<ide> def assume_migrated_upto_version(version, migrations_paths)
<ide> migrations_paths = Array(migrations_paths)
<ide> version = version.to_i
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def initialize(connection, logger, connection_options, config)
<ide> end
<ide> end
<ide>
<del> MAX_INDEX_LENGTH_FOR_CHARSETS_OF_4BYTES_MAXLEN = 191
<ide> CHARSETS_OF_4BYTES_MAXLEN = ['utf8mb4', 'utf16', 'utf16le', 'utf32']
<del> def initialize_schema_migrations_table
<del> if CHARSETS_OF_4BYTES_MAXLEN.include?(charset)
<del> ActiveRecord::SchemaMigration.create_table(MAX_INDEX_LENGTH_FOR_CHARSETS_OF_4BYTES_MAXLEN)
<del> else
<del> ActiveRecord::SchemaMigration.create_table
<del> end
<add>
<add> def internal_string_options_for_primary_key # :nodoc:
<add> super.tap { |options|
<add> options[:collation] = collation.sub(/\A[^_]+/, 'utf8') if CHARSETS_OF_4BYTES_MAXLEN.include?(charset)
<add> }
<ide> end
<ide>
<ide> def version
<ide><path>activerecord/lib/active_record/internal_metadata.rb
<ide> module ActiveRecord
<ide> # This class is used to create a table that keeps track of values and keys such
<ide> # as which environment migrations were run in.
<ide> class InternalMetadata < ActiveRecord::Base # :nodoc:
<del> # Keys in mysql are limited to 191 characters, due to this no adapter can
<del> # use a longer key
<del> KEY_LIMIT = 191
<del>
<ide> class << self
<ide> def primary_key
<ide> "key"
<ide> def table_exists?
<ide> # Creates an internal metadata table with columns +key+ and +value+
<ide> def create_table
<ide> unless table_exists?
<add> key_options = connection.internal_string_options_for_primary_key
<add>
<ide> connection.create_table(table_name, id: false) do |t|
<del> t.string :key, primary_key: true, limit: KEY_LIMIT
<add> t.string :key, key_options
<ide> t.string :value
<ide> t.timestamps
<ide> end
<ide><path>activerecord/lib/active_record/schema_migration.rb
<ide> def table_exists?
<ide> ActiveSupport::Deprecation.silence { connection.table_exists?(table_name) }
<ide> end
<ide>
<del> def create_table(limit=nil)
<add> def create_table
<ide> unless table_exists?
<del> version_options = { primary_key: true }
<del> version_options[:limit] = limit if limit
<add> version_options = connection.internal_string_options_for_primary_key
<ide>
<ide> connection.create_table(table_name, id: false) do |t|
<ide> t.string :version, version_options
<ide><path>activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb
<ide> def test_initializes_internal_metadata_for_encoding_utf8mb4
<ide> end
<ide> end
<ide>
<del> def test_key_limit_max_matches_max
<del> assert_equal ActiveRecord::InternalMetadata::KEY_LIMIT ,ActiveRecord::ConnectionAdapters::Mysql2Adapter::MAX_INDEX_LENGTH_FOR_CHARSETS_OF_4BYTES_MAXLEN
<del> end
<del>
<del>
<ide> private
<ide>
<ide> def with_encoding_utf8mb4 | 5 |
Go | Go | move base image selection to a utility function | 96c522162634ff4d5e55ddf2ff841921a99b7b09 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementUser(c *check.C) {
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *check.C) {
<ide> name := "testbuildenvironmentreplacement"
<ide>
<del> var baseImage, volumePath string
<add> var volumePath string
<ide>
<ide> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<ide> volumePath = "c:/quux"
<ide> } else {
<del> baseImage = "scratch"
<ide> volumePath = "/quux"
<ide> }
<ide>
<ide> _, err := buildImage(name, `
<del> FROM `+baseImage+`
<add> FROM `+minimalBaseImage()+`
<ide> ENV volume `+volumePath+`
<ide> VOLUME ${volume}
<ide> `, true)
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *check.C) {
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementAddCopy(c *check.C) {
<ide> name := "testbuildenvironmentreplacement"
<ide>
<del> var baseImage string
<del>
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<ide> ctx, err := fakeContext(`
<del> FROM `+baseImage+`
<add> FROM `+minimalBaseImage()+`
<ide> ENV baz foo
<ide> ENV quux bar
<ide> ENV dot .
<ide> func (s *DockerSuite) TestBuildSixtySteps(c *check.C) {
<ide> // TP5 timeframe when perf is better.
<ide> name := "foobuildsixtysteps"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext("FROM "+baseImage+"\n"+strings.Repeat("ADD foo /\n", 60),
<add> ctx, err := fakeContext("FROM "+minimalBaseImage()+"\n"+strings.Repeat("ADD foo /\n", 60),
<ide> map[string]string{
<ide> "foo": "test1",
<ide> })
<ide> RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio'
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFile(c *check.C) {
<ide> name := "testaddmultiplefilestofile"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext(`FROM `+baseImage+`
<add> ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
<ide> ADD file1.txt file2.txt test
<ide> `,
<ide> map[string]string{
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFile(c *check.C) {
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFile(c *check.C) {
<ide> name := "testjsonaddmultiplefilestofile"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext(`FROM `+baseImage+`
<add> ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
<ide> ADD ["file1.txt", "file2.txt", "test"]
<ide> `,
<ide> map[string]string{
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFile(c *check.C) {
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFileWild(c *check.C) {
<ide> name := "testaddmultiplefilestofilewild"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext(`FROM `+baseImage+`
<add> ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
<ide> ADD file*.txt test
<ide> `,
<ide> map[string]string{
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFileWild(c *check.C) {
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFileWild(c *check.C) {
<ide> name := "testjsonaddmultiplefilestofilewild"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext(`FROM `+baseImage+`
<add> ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
<ide> ADD ["file*.txt", "test"]
<ide> `,
<ide> map[string]string{
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFileWild(c *check.C) {
<ide> func (s *DockerSuite) TestBuildCopyMultipleFilesToFile(c *check.C) {
<ide> name := "testcopymultiplefilestofile"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext(`FROM `+baseImage+`
<add> ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
<ide> COPY file1.txt file2.txt test
<ide> `,
<ide> map[string]string{
<ide> func (s *DockerSuite) TestBuildCopyMultipleFilesToFile(c *check.C) {
<ide> func (s *DockerSuite) TestBuildJSONCopyMultipleFilesToFile(c *check.C) {
<ide> name := "testjsoncopymultiplefilestofile"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext(`FROM `+baseImage+`
<add> ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
<ide> COPY ["file1.txt", "file2.txt", "test"]
<ide> `,
<ide> map[string]string{
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expecte
<ide> func (s *DockerSuite) TestBuildAddEtcToRoot(c *check.C) {
<ide> name := "testaddetctoroot"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext(`FROM `+baseImage+`
<add> ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
<ide> ADD . /`,
<ide> map[string]string{
<ide> "etc/test_file": "test1",
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expecte
<ide> func (s *DockerSuite) TestBuildCopyEtcToRoot(c *check.C) {
<ide> name := "testcopyetctoroot"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> ctx, err := fakeContext(`FROM `+baseImage+`
<add> ctx, err := fakeContext(`FROM `+minimalBaseImage()+`
<ide> COPY . /`,
<ide> map[string]string{
<ide> "etc/test_file": "test1",
<ide> COPY . /`,
<ide> func (s *DockerSuite) TestBuildCopyDisallowRemote(c *check.C) {
<ide> name := "testcopydisallowremote"
<ide>
<del> var baseImage string
<del> if daemonPlatform == "windows" {
<del> baseImage = "windowsservercore"
<del> } else {
<del> baseImage = "scratch"
<del> }
<del>
<del> _, out, err := buildImageWithOut(name, `FROM `+baseImage+`
<add> _, out, err := buildImageWithOut(name, `FROM `+minimalBaseImage()+`
<ide> COPY https://index.docker.io/robots.txt /`,
<ide> true)
<ide> if err == nil || !strings.Contains(out, "Source can't be a URL for COPY") {
<ide><path>integration-cli/docker_utils.go
<ide> func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string)
<ide> args = append(args, defaultSleepCommand...)
<ide> return dockerCmd(c, args...)
<ide> }
<add>
<add>// minimalBaseImage returns the name of the minimal base image for the current
<add>// daemon platform.
<add>func minimalBaseImage() string {
<add> if daemonPlatform == "windows" {
<add> return WindowsBaseImage
<add> }
<add> return "scratch"
<add>} | 2 |
Python | Python | release version 1.0 | ed7549bb1af73a90d70d302806cd343805471a58 | <ide><path>pytorch_transformers/__init__.py
<del>__version__ = "0.7.0"
<add>__version__ = "1.0.0"
<ide> from .tokenization_bert import BertTokenizer, BasicTokenizer, WordpieceTokenizer
<ide> from .tokenization_openai import OpenAIGPTTokenizer
<ide> from .tokenization_transfo_xl import (TransfoXLTokenizer, TransfoXLCorpus)
<ide><path>setup.py
<ide>
<ide> setup(
<ide> name="pytorch_transformers",
<del> version="0.7.0",
<add> version="1.0.0",
<ide> author="Thomas Wolf, Lysandre Debut, Victor Sanh, Tim Rault, Google AI Language Team Authors, Open AI team Authors",
<ide> author_email="thomas@huggingface.co",
<ide> description="Repository of pre-trained NLP Transformer models: BERT, GPT & GPT-2, Transformer-XL, XLNet and XLM", | 2 |
Python | Python | use best pickle protocol | 847a39da9c7e214bdeef18fa3812218b53b37271 | <ide><path>celery/worker/state.py
<ide>
<ide> from collections import defaultdict
<ide>
<add>from kombu.serialization import pickle_protocol
<ide> from kombu.utils import cached_property
<ide>
<ide> from celery import __version__
<ide> class Persistent(object):
<ide>
<ide> """
<ide> storage = shelve
<add> protocol = pickle_protocol
<ide> _is_open = False
<ide>
<ide> def __init__(self, filename):
<ide> def sync(self, d):
<ide> return d
<ide>
<ide> def open(self):
<del> return self.storage.open(self.filename, writeback=True)
<add> return self.storage.open(
<add> self.filename, protocol=self.protocol, writeback=True,
<add> )
<ide>
<ide> def close(self):
<ide> if self._is_open: | 1 |
Text | Text | add missing period | a3c0c8fb90f084d494cdf46551c8a6228ca5ffd0 | <ide><path>docs/api-guide/generic-views.md
<ide> You can then simply apply this mixin to a view or viewset anytime you need to ap
<ide> serializer_class = UserSerializer
<ide> lookup_fields = ('account', 'username')
<ide>
<del>Using custom mixins is a good option if you have custom behavior that needs to be used
<add>Using custom mixins is a good option if you have custom behavior that needs to be used.
<ide>
<ide> ## Creating custom base classes
<ide> | 1 |
Java | Java | add native module overriding | 9e30c3b218c08afb51ae0e274f15422b9bcca480 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java
<ide> public void initialize() {
<ide> // do nothing
<ide> }
<ide>
<add> @Override
<add> public boolean canOverrideExistingModule() {
<add> return false;
<add> }
<add>
<ide> @Override
<ide> public void onCatalystInstanceDestroy() {
<ide> // do nothing
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModule.java
<ide> * register themselves using {@link CxxModuleWrapper}.
<ide> */
<ide> public interface NativeModule {
<del> public static interface NativeMethod {
<add> interface NativeMethod {
<ide> void invoke(CatalystInstance catalystInstance, ReadableNativeArray parameters);
<ide> String getType();
<ide> }
<ide> public static interface NativeMethod {
<ide> * @return the name of this module. This will be the name used to {@code require()} this module
<ide> * from javascript.
<ide> */
<del> public String getName();
<add> String getName();
<ide>
<ide> /**
<ide> * @return methods callable from JS on this module
<ide> */
<del> public Map<String, NativeMethod> getMethods();
<add> Map<String, NativeMethod> getMethods();
<ide>
<ide> /**
<ide> * Append a field which represents the constants this module exports
<ide> * to JS. If no constants are exported this should do nothing.
<ide> */
<del> public void writeConstantsField(JsonGenerator jg, String fieldName) throws IOException;
<add> void writeConstantsField(JsonGenerator jg, String fieldName) throws IOException;
<ide>
<ide> /**
<ide> * This is called at the end of {@link CatalystApplicationFragment#createCatalystInstance()}
<ide> * after the CatalystInstance has been created, in order to initialize NativeModules that require
<ide> * the CatalystInstance or JS modules.
<ide> */
<del> public void initialize();
<add> void initialize();
<add>
<add> /**
<add> * Return true if you intend to override some other native module that was registered e.g. as part
<add> * of a different package (such as the core one). Trying to override without returning true from
<add> * this method is considered an error and will throw an exception during initialization. By
<add> * default all modules return false.
<add> */
<add> boolean canOverrideExistingModule();
<ide>
<ide> /**
<ide> * Called before {CatalystInstance#onHostDestroy}
<ide> */
<del> public void onCatalystInstanceDestroy();
<add> void onCatalystInstanceDestroy();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/NativeModuleRegistry.java
<ide> import java.io.StringWriter;
<ide> import java.util.ArrayList;
<ide> import java.util.Collection;
<add>import java.util.HashMap;
<ide> import java.util.Map;
<del>import java.util.Set;
<ide>
<ide> import com.facebook.react.common.MapBuilder;
<del>import com.facebook.react.common.SetBuilder;
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.systrace.Systrace;
<ide>
<ide> public class NativeModuleRegistry {
<ide>
<ide> private final ArrayList<ModuleDefinition> mModuleTable;
<del> private final Map<Class<NativeModule>, NativeModule> mModuleInstances;
<add> private final Map<Class<? extends NativeModule>, NativeModule> mModuleInstances;
<ide> private final String mModuleDescriptions;
<ide> private final ArrayList<OnBatchCompleteListener> mBatchCompleteListenerModules;
<ide>
<ide> private NativeModuleRegistry(
<ide> ArrayList<ModuleDefinition> moduleTable,
<del> Map<Class<NativeModule>, NativeModule> moduleInstances,
<add> Map<Class<? extends NativeModule>, NativeModule> moduleInstances,
<ide> String moduleDescriptions) {
<ide> mModuleTable = moduleTable;
<ide> mModuleInstances = moduleInstances;
<ide> public MethodRegistration(String name, String tracingName, NativeModule.NativeMe
<ide>
<ide> public static class Builder {
<ide>
<del> private ArrayList<ModuleDefinition> mModuleDefinitions;
<del> private Map<Class<NativeModule>, NativeModule> mModuleInstances;
<del> private Set<String> mSeenModuleNames;
<del>
<del> public Builder() {
<del> mModuleDefinitions = new ArrayList<ModuleDefinition>();
<del> mModuleInstances = MapBuilder.newHashMap();
<del> mSeenModuleNames = SetBuilder.newHashSet();
<del> }
<add> private final HashMap<String, NativeModule> mModules = MapBuilder.newHashMap();
<ide>
<ide> public Builder add(NativeModule module) {
<del> ModuleDefinition registration = new ModuleDefinition(
<del> mModuleDefinitions.size(),
<del> module.getName(),
<del> module);
<del> Assertions.assertCondition(
<del> !mSeenModuleNames.contains(module.getName()),
<del> "Module " + module.getName() + " was already registered!");
<del> mSeenModuleNames.add(module.getName());
<del> mModuleDefinitions.add(registration);
<del> mModuleInstances.put((Class<NativeModule>) module.getClass(), module);
<add> NativeModule existing = mModules.get(module.getName());
<add> if (existing != null && !module.canOverrideExistingModule()) {
<add> throw new IllegalStateException("Native module " + module.getClass().getSimpleName() +
<add> " tried to override " + existing.getClass().getSimpleName() + " for module name " +
<add> module.getName() + ". If this was your intention, return true from " +
<add> module.getClass().getSimpleName() + "#canOverrideExistingModule()");
<add> }
<add> mModules.put(module.getName(), module);
<ide> return this;
<ide> }
<ide>
<ide> public NativeModuleRegistry build() {
<ide> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateJSON");
<add> ArrayList<ModuleDefinition> moduleTable = new ArrayList<>();
<add> Map<Class<? extends NativeModule>, NativeModule> moduleInstances = MapBuilder.newHashMap();
<ide> String moduleDefinitionJson;
<ide> try {
<ide> JsonFactory jsonFactory = new JsonFactory();
<ide> StringWriter writer = new StringWriter();
<ide> try {
<ide> JsonGenerator jg = jsonFactory.createGenerator(writer);
<ide> jg.writeStartObject();
<del> for (ModuleDefinition module : mModuleDefinitions) {
<del> jg.writeObjectFieldStart(module.name);
<del> jg.writeNumberField("moduleID", module.id);
<add> int idx = 0;
<add> for (NativeModule module : mModules.values()) {
<add> ModuleDefinition moduleDef = new ModuleDefinition(idx++, module.getName(), module);
<add> moduleTable.add(moduleDef);
<add> moduleInstances.put(module.getClass(), module);
<add> jg.writeObjectFieldStart(moduleDef.name);
<add> jg.writeNumberField("moduleID", moduleDef.id);
<ide> jg.writeObjectFieldStart("methods");
<del> for (int i = 0; i < module.methods.size(); i++) {
<del> MethodRegistration method = module.methods.get(i);
<add> for (int i = 0; i < moduleDef.methods.size(); i++) {
<add> MethodRegistration method = moduleDef.methods.get(i);
<ide> jg.writeObjectFieldStart(method.name);
<ide> jg.writeNumberField("methodID", i);
<ide> jg.writeStringField("type", method.method.getType());
<ide> jg.writeEndObject();
<ide> }
<ide> jg.writeEndObject();
<del> module.target.writeConstantsField(jg, "constants");
<add> moduleDef.target.writeConstantsField(jg, "constants");
<ide> jg.writeEndObject();
<ide> }
<ide> jg.writeEndObject();
<ide> public NativeModuleRegistry build() {
<ide> } finally {
<ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
<ide> }
<del> return new NativeModuleRegistry(mModuleDefinitions, mModuleInstances, moduleDefinitionJson);
<add> return new NativeModuleRegistry(moduleTable, moduleInstances, moduleDefinitionJson);
<ide> }
<ide> }
<ide> } | 3 |
Text | Text | add bit about the engines field | ab9cc75f8b09b5b167dbc02c63d8223e3d0f257b | <ide><path>docs/upgrading/upgrading-your-package.md
<ide> Would be replaced by this:
<ide>
<ide> You wrote specs, right!? Here's where they shine. Run them with `cmd-shift-P`, and search for `run package specs`. It will show all the deprecation messages and errors.
<ide>
<add>### Update the engines field in package.json
<add>
<add>When you are deprecation free and all done converting, upgrade the `engines` field in your package.json:
<add>
<add>```json
<add>{
<add> "engines": {
<add> "atom": ">=0.x.0, <2.0.0"
<add> }
<add>}
<add>```
<add>
<ide> ### Examples
<ide>
<ide> We have upgraded all the core packages. Please see [this issue](https://github.com/atom/atom/issues/4011) for a link to all the upgrade PRs. | 1 |
PHP | PHP | add more quotes | 9693cedbfc1fb0e38a8e688375e5b2ce5273b75f | <ide><path>src/Illuminate/Foundation/Inspiring.php
<ide> public static function quote()
<ide> 'I begin to speak only when I am certain what I will say is not better left unsaid - Cato the Younger',
<ide> 'Order your soul. Reduce your wants. - Augustine',
<ide> 'Be present above all else. - Naval Ravikant',
<add> 'Let all your things have their places; let each part of your business have its time. - Benjamin Franklin',
<add> 'If you do not have a consistent goal in life, you can not live it in a consistent way. - Marcus Aurelius',
<add> 'No surplus words or unnecessary actions. - Marcus Aurelius',
<add> 'People find pleasure in different ways. I find it in keeping my mind clear. - Marcus Aurelius',
<ide> ])->random();
<ide> }
<ide> } | 1 |
Javascript | Javascript | add another test for | 432578ef03fc1dbae8b00eae3e96bfb541f8efa3 | <ide><path>src/renderers/dom/client/wrappers/__tests__/ReactDOMInput-test.js
<ide> describe('ReactDOMInput', function() {
<ide> 'set value',
<ide> ]);
<ide> });
<add>
<add> it('sets value properly with type coming later in props', function() {
<add> var input = ReactTestUtils.renderIntoDocument(
<add> <input value="hi" type="radio" />
<add> );
<add> expect(input.value).toBe('hi');
<add> });
<ide> }); | 1 |
Python | Python | add kubernetesnamespace class | c863fd688679fb1ee03546268b6f100e335f8af7 | <ide><path>libcloud/container/drivers/kubernetes.py
<ide> def __init__(
<ide> self.extra = extra
<ide>
<ide>
<add>class KubernetesNamespace(ContainerCluster):
<add> """
<add> A Kubernetes namespace
<add> """
<add>
<add>
<ide> class KubernetesContainerDriver(KubernetesDriverMixin, ContainerDriver):
<ide> type = Provider.KUBERNETES
<ide> name = "Kubernetes"
<ide> def get_container(self, id):
<ide> match = [container for container in containers if container.id == id]
<ide> return match[0]
<ide>
<del> def list_clusters(self):
<add> def list_namespaces(self):
<ide> """
<ide> Get a list of namespaces that pods can be deployed into
<ide>
<del> :param location: The location to search in
<del> :type location: :class:`libcloud.container.base.ClusterLocation`
<del>
<del> :rtype: ``list`` of :class:`libcloud.container.base.ContainerCluster`
<add> :rtype: ``list`` of :class:`.KubernetesNamespace`
<ide> """
<ide> try:
<ide> result = self.connection.request(ROOT_URL + "v1/namespaces/").object
<ide> def list_clusters(self):
<ide> )
<ide> raise
<ide>
<del> clusters = [self._to_cluster(value) for value in result["items"]]
<del> return clusters
<add> namespaces = [self._to_namespace(value) for value in result["items"]]
<add> return namespaces
<ide>
<del> def get_cluster(self, id):
<add> def get_namespace(self, id):
<ide> """
<del> Get a cluster by ID
<add> Get a namespace by ID
<ide>
<del> :param id: The ID of the cluster to get
<add> :param id: The ID of the namespace to get
<ide> :type id: ``str``
<ide>
<del> :rtype: :class:`libcloud.container.base.ContainerCluster`
<add> :rtype: :class:`.KubernetesNamespace`
<ide> """
<ide> result = self.connection.request(ROOT_URL + "v1/namespaces/%s" % id).object
<ide>
<del> return self._to_cluster(result)
<add> return self._to_namespace(result)
<ide>
<del> def destroy_cluster(self, cluster):
<add> def delete_namespace(self, namespace):
<ide> """
<del> Delete a cluster (namespace)
<add> Delete a namespace
<ide>
<ide> :return: ``True`` if the destroy was successful, otherwise ``False``.
<ide> :rtype: ``bool``
<ide> """
<ide> self.connection.request(
<del> ROOT_URL + "v1/namespaces/%s" % cluster.id, method="DELETE"
<add> ROOT_URL + "v1/namespaces/%s" % namespace.id, method="DELETE"
<ide> ).object
<ide> return True
<ide>
<del> def create_cluster(self, name, location=None):
<add> def create_namespace(self, name, location=None):
<ide> """
<del> Create a container cluster (a namespace)
<add> Create a namespace
<ide>
<del> :param name: The name of the cluster
<add> :param name: The name of the namespace
<ide> :type name: ``str``
<ide>
<del> :param location: The location to create the cluster in
<add> :param location: The location to create the namespace in
<ide> :type location: :class:`.ClusterLocation`
<ide>
<del> :rtype: :class:`.ContainerCluster`
<add> :rtype: :class:`.KubernetesNamespace`
<ide> """
<ide> request = {"metadata": {"name": name}}
<ide> result = self.connection.request(
<ide> ROOT_URL + "v1/namespaces", method="POST", data=json.dumps(request)
<ide> ).object
<del> return self._to_cluster(result)
<add> return self._to_namespace(result)
<ide>
<ide> def list_nodes_metrics(self):
<ide> return self.connection.request("/apis/metrics.k8s.io/v1beta1/nodes").object[
<ide> "items"
<ide> ]
<ide>
<del> def deploy_container(self, name, image, cluster=None, parameters=None, start=True):
<add> def deploy_container(
<add> self, name, image, namespace=None, parameters=None, start=True
<add> ):
<ide> """
<ide> Deploy an installed container image.
<ide> In kubernetes this deploys a single container Pod.
<ide> def deploy_container(self, name, image, cluster=None, parameters=None, start=Tru
<ide> :param image: The container image to deploy
<ide> :type image: :class:`.ContainerImage`
<ide>
<del> :param cluster: The cluster to deploy to, None is default
<del> :type cluster: :class:`.ContainerCluster`
<add> :param namespace: The namespace to deploy to, None is default
<add> :type namespace: :class:`.KubernetesNamespace`
<ide>
<ide> :param parameters: Container Image parameters
<ide> :type parameters: ``str``
<ide> def deploy_container(self, name, image, cluster=None, parameters=None, start=Tru
<ide>
<ide> :rtype: :class:`.Container`
<ide> """
<del> if cluster is None:
<add> if namespace is None:
<ide> namespace = "default"
<ide> else:
<del> namespace = cluster.id
<add> namespace = namespace.id
<ide> request = {
<ide> "metadata": {"name": name},
<ide> "spec": {"containers": [{"name": name, "image": image.name}]},
<ide> def deploy_container(self, name, image, cluster=None, parameters=None, start=Tru
<ide> method="POST",
<ide> data=json.dumps(request),
<ide> ).object
<del> return self._to_cluster(result)
<add> return self._to_namespace(result)
<ide>
<ide> def destroy_container(self, container):
<ide> """
<ide> def _to_container(self, data, container_status, pod_data):
<ide> extra=extra,
<ide> )
<ide>
<del> def _to_cluster(self, data):
<add> def _to_namespace(self, data):
<ide> """
<del> Convert namespace to a cluster
<add> Convert an API node data object to a `KubernetesNamespace` object
<ide> """
<del> metadata = data["metadata"]
<del> status = data["status"]
<del> return ContainerCluster(
<del> id=metadata["name"],
<del> name=metadata["name"],
<add> return KubernetesNamespace(
<add> id=data["metadata"]["name"],
<add> name=data["metadata"]["name"],
<ide> driver=self.connection.driver,
<del> extra={"phase": status["phase"]},
<add> extra={"phase": data["status"]["phase"]},
<ide> )
<ide>
<ide> | 1 |
Text | Text | fix code indentation and improve formatting | 1365af18369ba8b80bac94a0a2e15bb55d843741 | <ide><path>guides/source/getting_started.md
<ide> something went wrong. To do that, you'll modify
<ide>
<ide> ```html+erb
<ide> <%= form_for :article, url: articles_path do |f| %>
<add>
<ide> <% if @article.errors.any? %>
<del> <div id="error_explanation">
<del> <h2><%= pluralize(@article.errors.count, "error") %> prohibited
<del> this article from being saved:</h2>
<del> <ul>
<del> <% @article.errors.full_messages.each do |msg| %>
<del> <li><%= msg %></li>
<del> <% end %>
<del> </ul>
<del> </div>
<add> <div id="error_explanation">
<add> <h2>
<add> <%= pluralize(@article.errors.count, "error") %> prohibited
<add> this article from being saved:
<add> </h2>
<add> <ul>
<add> <% @article.errors.full_messages.each do |msg| %>
<add> <li><%= msg %></li>
<add> <% end %>
<add> </ul>
<add> </div>
<ide> <% end %>
<add>
<ide> <p>
<ide> <%= f.label :title %><br>
<ide> <%= f.text_field :title %>
<ide> something went wrong. To do that, you'll modify
<ide> <p>
<ide> <%= f.submit %>
<ide> </p>
<add>
<ide> <% end %>
<ide>
<ide> <%= link_to 'Back', articles_path %>
<ide> it look as follows:
<ide> <h1>Editing article</h1>
<ide>
<ide> <%= form_for :article, url: article_path(@article), method: :patch do |f| %>
<add>
<ide> <% if @article.errors.any? %>
<del> <div id="error_explanation">
<del> <h2><%= pluralize(@article.errors.count, "error") %> prohibited
<del> this article from being saved:</h2>
<del> <ul>
<del> <% @article.errors.full_messages.each do |msg| %>
<del> <li><%= msg %></li>
<del> <% end %>
<del> </ul>
<del> </div>
<add> <div id="error_explanation">
<add> <h2>
<add> <%= pluralize(@article.errors.count, "error") %> prohibited
<add> this article from being saved:
<add> </h2>
<add> <ul>
<add> <% @article.errors.full_messages.each do |msg| %>
<add> <li><%= msg %></li>
<add> <% end %>
<add> </ul>
<add> </div>
<ide> <% end %>
<add>
<ide> <p>
<ide> <%= f.label :title %><br>
<ide> <%= f.text_field :title %>
<ide> it look as follows:
<ide> <p>
<ide> <%= f.submit %>
<ide> </p>
<add>
<ide> <% end %>
<ide>
<ide> <%= link_to 'Back', articles_path %>
<ide> it appear next to the "Show" link:
<ide> <th colspan="2"></th>
<ide> </tr>
<ide>
<del><% @articles.each do |article| %>
<del> <tr>
<del> <td><%= article.title %></td>
<del> <td><%= article.text %></td>
<del> <td><%= link_to 'Show', article_path(article) %></td>
<del> <td><%= link_to 'Edit', edit_article_path(article) %></td>
<del> </tr>
<del><% end %>
<add> <% @articles.each do |article| %>
<add> <tr>
<add> <td><%= article.title %></td>
<add> <td><%= article.text %></td>
<add> <td><%= link_to 'Show', article_path(article) %></td>
<add> <td><%= link_to 'Edit', edit_article_path(article) %></td>
<add> </tr>
<add> <% end %>
<ide> </table>
<ide> ```
<ide>
<ide> content:
<ide>
<ide> ```html+erb
<ide> <%= form_for @article do |f| %>
<add>
<ide> <% if @article.errors.any? %>
<del> <div id="error_explanation">
<del> <h2><%= pluralize(@article.errors.count, "error") %> prohibited
<del> this article from being saved:</h2>
<del> <ul>
<del> <% @article.errors.full_messages.each do |msg| %>
<del> <li><%= msg %></li>
<del> <% end %>
<del> </ul>
<del> </div>
<add> <div id="error_explanation">
<add> <h2>
<add> <%= pluralize(@article.errors.count, "error") %> prohibited
<add> this article from being saved:
<add> </h2>
<add> <ul>
<add> <% @article.errors.full_messages.each do |msg| %>
<add> <li><%= msg %></li>
<add> <% end %>
<add> </ul>
<add> </div>
<ide> <% end %>
<add>
<ide> <p>
<ide> <%= f.label :title %><br>
<ide> <%= f.text_field :title %>
<ide> content:
<ide> <p>
<ide> <%= f.submit %>
<ide> </p>
<add>
<ide> <% end %>
<ide> ```
<ide>
<ide> together.
<ide> <th colspan="3"></th>
<ide> </tr>
<ide>
<del><% @articles.each do |article| %>
<del> <tr>
<del> <td><%= article.title %></td>
<del> <td><%= article.text %></td>
<del> <td><%= link_to 'Show', article_path(article) %></td>
<del> <td><%= link_to 'Edit', edit_article_path(article) %></td>
<del> <td><%= link_to 'Destroy', article_path(article),
<del> method: :delete, data: { confirm: 'Are you sure?' } %></td>
<del> </tr>
<del><% end %>
<add> <% @articles.each do |article| %>
<add> <tr>
<add> <td><%= article.title %></td>
<add> <td><%= article.text %></td>
<add> <td><%= link_to 'Show', article_path(article) %></td>
<add> <td><%= link_to 'Edit', edit_article_path(article) %></td>
<add> <td><%= link_to 'Destroy', article_path(article),
<add> method: :delete,
<add> data: { confirm: 'Are you sure?' } %></td>
<add> </tr>
<add> <% end %>
<ide> </table>
<ide> ```
<ide>
<ide> So first, we'll wire up the Article show template
<ide> </p>
<ide> <% end %>
<ide>
<del><%= link_to 'Back', articles_path %>
<del>| <%= link_to 'Edit', edit_article_path(@article) %>
<add><%= link_to 'Back', articles_path %> |
<add><%= link_to 'Edit', edit_article_path(@article) %>
<ide> ```
<ide>
<ide> This adds a form on the `Article` show page that creates a new comment by | 1 |
Go | Go | fix some typos | c8c7a3ff2112a1b17a06fc02633ed7b49a8aebf3 | <ide><path>cli/command/registry/search.go
<ide> func runSearch(dockerCli *command.DockerCli, opts searchOptions) error {
<ide> return nil
<ide> }
<ide>
<del>// SearchResultsByStars sorts search results in descending order by number of stars.
<add>// searchResultsByStars sorts search results in descending order by number of stars.
<ide> type searchResultsByStars []registrytypes.SearchResult
<ide>
<ide> func (r searchResultsByStars) Len() int { return len(r) }
<ide><path>layer/ro_layer.go
<ide> type roLayer struct {
<ide> references map[Layer]struct{}
<ide> }
<ide>
<del>// TarStream for roLayer guarentees that the data that is produced is the exact
<add>// TarStream for roLayer guarantees that the data that is produced is the exact
<ide> // data that the layer was registered with.
<ide> func (rl *roLayer) TarStream() (io.ReadCloser, error) {
<ide> r, err := rl.layerStore.store.TarSplitReader(rl.chainID)
<ide> func (rl *roLayer) TarStream() (io.ReadCloser, error) {
<ide> return rc, nil
<ide> }
<ide>
<del>// TarStreamFrom does not make any guarentees to the correctness of the produced
<add>// TarStreamFrom does not make any guarantees to the correctness of the produced
<ide> // data. As such it should not be used when the layer content must be verified
<ide> // to be an exact match to the registered layer.
<ide> func (rl *roLayer) TarStreamFrom(parent ChainID) (io.ReadCloser, error) { | 2 |
Ruby | Ruby | fix typo in collection proxy | 7dae39a743c4592cfce31152d501d1d2f30bb55c | <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb
<ide> class CollectionProxy < Relation
<ide> # :call-seq:
<ide> # delete_all()
<ide> #
<del> # Deletes all the records from the collection. For +has_many+ asssociations,
<add> # Deletes all the records from the collection. For +has_many+ associations,
<ide> # the deletion is done according to the strategy specified by the <tt>:dependent</tt>
<ide> # option. Returns an array with the deleted records.
<ide> # | 1 |
Go | Go | add a new request package in integration-cli | d69d4799a312dfcae63442e290ae6667afd1a038 | <ide><path>integration-cli/daemon/daemon.go
<ide> package daemon
<ide>
<ide> import (
<ide> "bytes"
<del> "crypto/tls"
<ide> "encoding/json"
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<del> "net"
<ide> "net/http"
<del> "net/http/httputil"
<del> "net/url"
<ide> "os"
<ide> "os/exec"
<ide> "path/filepath"
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/opts"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> func (d *Daemon) SockRequest(method, endpoint string, data interface{}) (int, []
<ide> // SockRequestRaw executes a socket request on a daemon and returns an http
<ide> // response and a reader for the output data.
<ide> func (d *Daemon) SockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
<del> return SockRequestRawToDaemon(method, endpoint, data, ct, d.Sock())
<add> return request.SockRequestRaw(method, endpoint, data, ct, d.Sock())
<ide> }
<ide>
<ide> // LogFileName returns the path the daemon's log file
<ide> func (d *Daemon) ReloadConfig() error {
<ide> errCh := make(chan error)
<ide> started := make(chan struct{})
<ide> go func() {
<del> _, body, err := SockRequestRawToDaemon("GET", "/events", nil, "", d.Sock())
<add> _, body, err := request.SockRequestRaw("GET", "/events", nil, "", d.Sock())
<ide> close(started)
<ide> if err != nil {
<ide> errCh <- err
<ide> func WaitInspectWithArgs(dockerBinary, name, expr, expected string, timeout time
<ide> return nil
<ide> }
<ide>
<del>// SockRequestRawToDaemon creates an http request against the specified daemon socket
<del>// FIXME(vdemeester) attach this to daemon ?
<del>func SockRequestRawToDaemon(method, endpoint string, data io.Reader, ct, daemon string) (*http.Response, io.ReadCloser, error) {
<del> req, client, err := newRequestClient(method, endpoint, data, ct, daemon)
<del> if err != nil {
<del> return nil, nil, err
<del> }
<del>
<del> resp, err := client.Do(req)
<del> if err != nil {
<del> client.Close()
<del> return nil, nil, err
<del> }
<del> body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
<del> defer resp.Body.Close()
<del> return client.Close()
<del> })
<del>
<del> return resp, body, nil
<del>}
<del>
<del>func getTLSConfig() (*tls.Config, error) {
<del> dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
<del>
<del> if dockerCertPath == "" {
<del> return nil, errors.New("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
<del> }
<del>
<del> option := &tlsconfig.Options{
<del> CAFile: filepath.Join(dockerCertPath, "ca.pem"),
<del> CertFile: filepath.Join(dockerCertPath, "cert.pem"),
<del> KeyFile: filepath.Join(dockerCertPath, "key.pem"),
<del> }
<del> tlsConfig, err := tlsconfig.Client(*option)
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> return tlsConfig, nil
<del>}
<del>
<del>// SockConn opens a connection on the specified socket
<del>func SockConn(timeout time.Duration, daemon string) (net.Conn, error) {
<del> daemonURL, err := url.Parse(daemon)
<del> if err != nil {
<del> return nil, errors.Wrapf(err, "could not parse url %q", daemon)
<del> }
<del>
<del> var c net.Conn
<del> switch daemonURL.Scheme {
<del> case "npipe":
<del> return npipeDial(daemonURL.Path, timeout)
<del> case "unix":
<del> return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
<del> case "tcp":
<del> if os.Getenv("DOCKER_TLS_VERIFY") != "" {
<del> // Setup the socket TLS configuration.
<del> tlsConfig, err := getTLSConfig()
<del> if err != nil {
<del> return nil, err
<del> }
<del> dialer := &net.Dialer{Timeout: timeout}
<del> return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
<del> }
<del> return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
<del> default:
<del> return c, errors.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
<del> }
<del>}
<del>
<del>func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string) (*http.Request, *httputil.ClientConn, error) {
<del> c, err := SockConn(time.Duration(10*time.Second), daemon)
<del> if err != nil {
<del> return nil, nil, errors.Errorf("could not dial docker daemon: %v", err)
<del> }
<del>
<del> client := httputil.NewClientConn(c, nil)
<del>
<del> req, err := http.NewRequest(method, endpoint, data)
<del> if err != nil {
<del> client.Close()
<del> return nil, nil, errors.Errorf("could not create new request: %v", err)
<del> }
<del>
<del> if ct != "" {
<del> req.Header.Set("Content-Type", ct)
<del> }
<del> return req, client, nil
<del>}
<del>
<ide> // BuildImageCmdWithHost create a build command with the specified arguments.
<ide> // FIXME(vdemeester) move this away
<ide> func BuildImageCmdWithHost(dockerBinary, name, dockerfile, host string, useCache bool, buildFlags ...string) *exec.Cmd {
<ide><path>integration-cli/docker_api_attach_test.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/client"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/stdcopy"
<ide> "github.com/docker/docker/pkg/testutil"
<ide> "github.com/go-check/check"
<ide> func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat")
<ide>
<del> rwc, err := sockConn(time.Duration(10*time.Second), "")
<add> rwc, err := request.SockConn(time.Duration(10*time.Second), daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide> func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) {
<ide>
<ide> // regression gh14320
<ide> func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *check.C) {
<del> req, client, err := newRequestClient("POST", "/containers/doesnotexist/attach", nil, "", "")
<add> client, err := request.NewClient(daemonHost())
<ide> c.Assert(err, checker.IsNil)
<del>
<add> req, err := request.New(daemonHost(), "/containers/doesnotexist/attach", request.Method(http.MethodPost))
<ide> resp, err := client.Do(req)
<ide> // connection will shutdown, err should be "persistent connection closed"
<del> c.Assert(err, checker.NotNil) // Server shutdown connection
<del>
<del> body, err := testutil.ReadBody(resp.Body)
<del> c.Assert(err, checker.IsNil)
<ide> c.Assert(resp.StatusCode, checker.Equals, http.StatusNotFound)
<add> content, err := testutil.ReadBody(resp.Body)
<add> c.Assert(err, checker.IsNil)
<ide> expected := "No such container: doesnotexist\r\n"
<del> c.Assert(string(body), checker.Equals, expected)
<add> c.Assert(string(content), checker.Equals, expected)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *check.C) {
<del> status, body, err := sockRequest("GET", "/containers/doesnotexist/attach/ws", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/doesnotexist/attach/ws", nil, daemonHost())
<ide> c.Assert(status, checker.Equals, http.StatusNotFound)
<ide> c.Assert(err, checker.IsNil)
<ide> expected := "No such container: doesnotexist"
<ide> func (s *DockerSuite) TestPostContainersAttach(c *check.C) {
<ide> cid, _ := dockerCmd(c, "run", "-di", "busybox", "cat")
<ide> cid = strings.TrimSpace(cid)
<ide> // Attach to the container's stdout stream.
<del> conn, br, err := sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain")
<add> conn, br, err := request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> // Check if the data from stdout can be received.
<ide> expectSuccess(conn, br, "stdout", false)
<ide> // Attach to the container's stderr stream.
<del> conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain")
<add> conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> // Since the container only emits stdout, attaching to stderr should return nothing.
<ide> expectTimeout(conn, br, "stdout")
<ide>
<ide> // Test the similar functions of the stderr stream.
<ide> cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2")
<ide> cid = strings.TrimSpace(cid)
<del> conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain")
<add> conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> expectSuccess(conn, br, "stderr", false)
<del> conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain")
<add> conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> expectTimeout(conn, br, "stderr")
<ide>
<ide> // Test with tty.
<ide> cid, _ = dockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2")
<ide> cid = strings.TrimSpace(cid)
<ide> // Attach to stdout only.
<del> conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain")
<add> conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> expectSuccess(conn, br, "stdout", true)
<ide>
<ide> // Attach without stdout stream.
<del> conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain")
<add> conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> // Nothing should be received because both the stdout and stderr of the container will be
<ide> // sent to the client as stdout when tty is enabled.
<ide><path>integration-cli/docker_api_auth_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestAuthAPI(c *check.C) {
<ide> }
<ide>
<ide> expected := "Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password"
<del> status, body, err := sockRequest("POST", "/auth", config)
<add> status, body, err := request.SockRequest("POST", "/auth", config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusUnauthorized)
<ide> msg := getErrorMessage(c, body)
<ide><path>integration-cli/docker_api_build_test.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/testutil"
<ide> "github.com/go-check/check"
<ide> )
<ide> RUN find /tmp/`
<ide> c.Assert(err, checker.IsNil)
<ide> defer server.Close()
<ide>
<del> res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestBuildAPIRemoteTarballContext(c *check.C) {
<ide>
<ide> defer server.Close()
<ide>
<del> res, b, err := sockRequestRaw("POST", "/build?remote="+server.URL()+"/testT.tar", nil, "application/tar")
<add> res, b, err := request.SockRequestRaw("POST", "/build?remote="+server.URL()+"/testT.tar", nil, "application/tar", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide> b.Close()
<ide> RUN echo 'right'
<ide>
<ide> defer server.Close()
<ide> url := "/build?dockerfile=custom&remote=" + server.URL() + "/testT.tar"
<del> res, body, err := sockRequestRaw("POST", url, nil, "application/tar")
<add> res, body, err := request.SockRequestRaw("POST", url, nil, "application/tar", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide>
<ide> RUN echo from dockerfile`,
<ide> c.Assert(err, checker.IsNil)
<ide> defer git.Close()
<ide>
<del> res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide>
<ide> RUN echo from Dockerfile`,
<ide> defer git.Close()
<ide>
<ide> // Make sure it tries to 'dockerfile' query param value
<del> res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide>
<ide> RUN echo from dockerfile`,
<ide> defer git.Close()
<ide>
<ide> // Make sure it tries to 'dockerfile' query param value
<del> res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestBuildAPIUnnormalizedTarPaths(c *check.C) {
<ide> // failed to close tar archive
<ide> c.Assert(tw.Close(), checker.IsNil)
<ide>
<del> res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
<add> res, body, err := request.SockRequestRaw("POST", "/build", buffer, "application/x-tar", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide>
<ide><path>integration-cli/docker_api_containers_test.go
<ide> import (
<ide> "io"
<ide> "io/ioutil"
<ide> "net/http"
<del> "net/http/httputil"
<ide> "net/url"
<ide> "os"
<ide> "path/filepath"
<ide> import (
<ide> mounttypes "github.com/docker/docker/api/types/mount"
<ide> networktypes "github.com/docker/docker/api/types/network"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/mount"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> func (s *DockerSuite) TestContainerAPIGetAll(c *check.C) {
<ide> name := "getall"
<ide> dockerCmd(c, "run", "--name", name, "busybox", "true")
<ide>
<del> status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/json?all=1", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIGetAll(c *check.C) {
<ide> func (s *DockerSuite) TestContainerAPIGetJSONNoFieldsOmitted(c *check.C) {
<ide> dockerCmd(c, "run", "busybox", "true")
<ide>
<del> status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/json?all=1", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIPsOmitFields(c *check.C) {
<ide> port := 80
<ide> runSleepingContainer(c, "--name", name, "--expose", strconv.Itoa(port))
<ide>
<del> status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/json?all=1", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIGetExport(c *check.C) {
<ide> name := "exportcontainer"
<ide> dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test")
<ide>
<del> status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/"+name+"/export", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIGetChanges(c *check.C) {
<ide> name := "changescontainer"
<ide> dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd")
<ide>
<del> status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/"+name+"/changes", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestGetContainerStats(c *check.C) {
<ide> }
<ide> bc := make(chan b, 1)
<ide> go func() {
<del> status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/"+name+"/stats", nil, daemonHost())
<ide> bc <- b{status, body, err}
<ide> }()
<ide>
<ide> func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) {
<ide> buf := &testutil.ChannelBuffer{make(chan []byte, 1)}
<ide> defer buf.Close()
<ide>
<del> _, body, err := sockRequestRaw("GET", "/containers/"+id+"/stats?stream=1", nil, "application/json")
<add> _, body, err := request.SockRequestRaw("GET", "/containers/"+id+"/stats?stream=1", nil, "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> defer body.Close()
<ide>
<ide> func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) {
<ide> }
<ide> bc := make(chan b, 1)
<ide> go func() {
<del> status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/"+name+"/stats", nil, daemonHost())
<ide> bc <- b{status, body, err}
<ide> }()
<ide>
<ide> func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) {
<ide> }
<ide> bc := make(chan b, 1)
<ide> go func() {
<del> status, body, err := sockRequest("GET", "/containers/"+name+"/stats?stream=0", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/"+name+"/stats?stream=0", nil, daemonHost())
<ide> bc <- b{status, body, err}
<ide> }()
<ide>
<ide> func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
<ide> // We expect an immediate response, but if it's not immediate, the test would hang, so put it in a goroutine
<ide> // below we'll check this on a timeout.
<ide> go func() {
<del> resp, body, err := sockRequestRaw("GET", "/containers/"+name+"/stats", nil, "")
<add> resp, body, err := request.SockRequestRaw("GET", "/containers/"+name+"/stats", nil, "", daemonHost())
<ide> body.Close()
<ide> chResp <- stats{resp.StatusCode, err}
<ide> }()
<ide> func (s *DockerSuite) TestContainerAPIPause(c *check.C) {
<ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "30")
<ide> ContainerID := strings.TrimSpace(out)
<ide>
<del> status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
<add> status, _, err := request.SockRequest("POST", "/containers/"+ContainerID+"/pause", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIPause(c *check.C) {
<ide> c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
<ide> }
<ide>
<del> status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
<add> status, _, err = request.SockRequest("POST", "/containers/"+ContainerID+"/unpause", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide>
<ide> func (s *DockerSuite) TestContainerAPITop(c *check.C) {
<ide> Processes [][]string
<ide> }
<ide> var top topResp
<del> status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
<add> status, b, err := request.SockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> c.Assert(json.Unmarshal(b, &top), checker.IsNil)
<ide> func (s *DockerSuite) TestContainerAPITopWindows(c *check.C) {
<ide> Processes [][]string
<ide> }
<ide> var top topResp
<del> status, b, err := sockRequest("GET", "/containers/"+id+"/top", nil)
<add> status, b, err := request.SockRequest("GET", "/containers/"+id+"/top", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> c.Assert(json.Unmarshal(b, &top), checker.IsNil)
<ide> func (s *DockerSuite) TestContainerAPICommit(c *check.C) {
<ide> dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
<ide>
<ide> name := "testcontainerapicommit"
<del> status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
<add> status, b, err := request.SockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> func (s *DockerSuite) TestContainerAPICommitWithLabelInConfig(c *check.C) {
<ide> }
<ide>
<ide> name := "testcontainerapicommitwithconfig"
<del> status, b, err := sockRequest("POST", "/commit?repo="+name+"&container="+cName, config)
<add> status, b, err := request.SockRequest("POST", "/commit?repo="+name+"&container="+cName, config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIBadPort(c *check.C) {
<ide> jsonData := bytes.NewBuffer(nil)
<ide> json.NewEncoder(jsonData).Encode(config)
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide> c.Assert(getErrorMessage(c, body), checker.Equals, `invalid port specification: "aa80"`, check.Commentf("Incorrect error msg: %s", body))
<ide> func (s *DockerSuite) TestContainerAPICreate(c *check.C) {
<ide> "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
<ide> }
<ide>
<del> status, b, err := sockRequest("POST", "/containers/create", config)
<add> status, b, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> func (s *DockerSuite) TestContainerAPICreate(c *check.C) {
<ide> func (s *DockerSuite) TestContainerAPICreateEmptyConfig(c *check.C) {
<ide> config := map[string]interface{}{}
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide>
<ide> func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *check.C) {
<ide> },
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusBadRequest)
<ide> msg := getErrorMessage(c, body)
<ide> func (s *DockerSuite) TestContainerAPICreateWithHostName(c *check.C) {
<ide> "Hostname": hostName,
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> var container containertypes.ContainerCreateCreatedBody
<ide> c.Assert(json.Unmarshal(body, &container), checker.IsNil)
<ide>
<del> status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
<add> status, body, err = request.SockRequest("GET", "/containers/"+container.ID+"/json", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestContainerAPICreateWithDomainName(c *check.C) {
<ide> "Domainname": domainName,
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> var container containertypes.ContainerCreateCreatedBody
<ide> c.Assert(json.Unmarshal(body, &container), checker.IsNil)
<ide>
<del> status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
<add> status, body, err = request.SockRequest("GET", "/containers/"+container.ID+"/json", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func UtilCreateNetworkMode(c *check.C, networkMode string) {
<ide> "HostConfig": map[string]interface{}{"NetworkMode": networkMode},
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> var container containertypes.ContainerCreateCreatedBody
<ide> c.Assert(json.Unmarshal(body, &container), checker.IsNil)
<ide>
<del> status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
<add> status, body, err = request.SockRequest("GET", "/containers/"+container.ID+"/json", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *check.C) {
<ide> "CpusetCpus": "0",
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> var container containertypes.ContainerCreateCreatedBody
<ide> c.Assert(json.Unmarshal(body, &container), checker.IsNil)
<ide>
<del> status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
<add> status, body, err = request.SockRequest("GET", "/containers/"+container.ID+"/json", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIVerifyHeader(c *check.C) {
<ide> create := func(ct string) (*http.Response, io.ReadCloser, error) {
<ide> jsonData := bytes.NewBuffer(nil)
<ide> c.Assert(json.NewEncoder(jsonData).Encode(config), checker.IsNil)
<del> return sockRequestRaw("POST", "/containers/create", jsonData, ct)
<add> return request.SockRequestRaw("POST", "/containers/create", jsonData, ct, daemonHost())
<ide> }
<ide>
<ide> // Try with no content-type
<ide> func (s *DockerSuite) TestContainerAPIInvalidPortSyntax(c *check.C) {
<ide> }
<ide> }`
<ide>
<del> res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIRestartPolicyInvalidPolicyName(c *check.C)
<ide> }
<ide> }`
<ide>
<del> res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIRestartPolicyRetryMismatch(c *check.C) {
<ide> }
<ide> }`
<ide>
<del> res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIRestartPolicyNegativeRetryCount(c *check.C
<ide> }
<ide> }`
<ide>
<del> res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIRestartPolicyDefaultRetryCount(c *check.C)
<ide> }
<ide> }`
<ide>
<del> res, _, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
<add> res, _, err := request.SockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
<ide> }
<ide> func (s *DockerSuite) TestContainerAPIPostCreateNull(c *check.C) {
<ide> "NetworkDisabled":false,
<ide> "OnBuild":null}`
<ide>
<del> res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
<ide>
<ide> func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
<ide> "Memory": 524287
<ide> }`
<ide>
<del> res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
<add> res, body, err := request.SockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> b, err2 := testutil.ReadBody(body)
<ide> c.Assert(err2, checker.IsNil)
<ide> func (s *DockerSuite) TestContainerAPIRename(c *check.C) {
<ide>
<ide> containerID := strings.TrimSpace(out)
<ide> newName := "TestContainerAPIRenameNew"
<del> statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
<add> statusCode, _, err := request.SockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> // 204 No Content is expected, not 200
<ide> c.Assert(statusCode, checker.Equals, http.StatusNoContent)
<ide> func (s *DockerSuite) TestContainerAPIKill(c *check.C) {
<ide> name := "test-api-kill"
<ide> runSleepingContainer(c, "-i", "--name", name)
<ide>
<del> status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
<add> status, _, err := request.SockRequest("POST", "/containers/"+name+"/kill", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIRestart(c *check.C) {
<ide> name := "test-api-restart"
<ide> runSleepingContainer(c, "-di", "--name", name)
<ide>
<del> status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
<add> status, _, err := request.SockRequest("POST", "/containers/"+name+"/restart?t=1", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide> c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second), checker.IsNil)
<ide> func (s *DockerSuite) TestContainerAPIRestartNotimeoutParam(c *check.C) {
<ide> id := strings.TrimSpace(out)
<ide> c.Assert(waitRun(id), checker.IsNil)
<ide>
<del> status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
<add> status, _, err := request.SockRequest("POST", "/containers/"+name+"/restart", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide> c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second), checker.IsNil)
<ide> func (s *DockerSuite) TestContainerAPIStart(c *check.C) {
<ide> "OpenStdin": true,
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
<add> status, _, err := request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<del> status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
<add> status, _, err = request.SockRequest("POST", "/containers/"+name+"/start", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide>
<ide> // second call to start should give 304
<del> status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
<add> status, _, err = request.SockRequest("POST", "/containers/"+name+"/start", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> // TODO(tibor): figure out why this doesn't work on windows
<ide> func (s *DockerSuite) TestContainerAPIStop(c *check.C) {
<ide> name := "test-api-stop"
<ide> runSleepingContainer(c, "-i", "--name", name)
<ide>
<del> status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=30", nil)
<add> status, _, err := request.SockRequest("POST", "/containers/"+name+"/stop?t=30", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide> c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
<ide>
<ide> // second call to start should give 304
<del> status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=30", nil)
<add> status, _, err = request.SockRequest("POST", "/containers/"+name+"/stop?t=30", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNotModified)
<ide> }
<ide> func (s *DockerSuite) TestContainerAPIWait(c *check.C) {
<ide> }
<ide> dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2")
<ide>
<del> status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
<add> status, body, err := request.SockRequest("POST", "/containers/"+name+"/wait", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
<ide> func (s *DockerSuite) TestContainerAPICopyNotExistsAnyMore(c *check.C) {
<ide> Resource: "/test.txt",
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
<add> status, _, err := request.SockRequest("POST", "/containers/"+name+"/copy", postData, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNotFound)
<ide> }
<ide> func (s *DockerSuite) TestContainerAPICopyPre124(c *check.C) {
<ide> Resource: "/test.txt",
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
<add> status, body, err := request.SockRequest("POST", "/v1.23/containers/"+name+"/copy", postData, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestContainerAPICopyResourcePathEmptyPr124(c *check.C) {
<ide> Resource: "",
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
<add> status, body, err := request.SockRequest("POST", "/v1.23/containers/"+name+"/copy", postData, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide> c.Assert(string(body), checker.Matches, "Path cannot be empty\n")
<ide> func (s *DockerSuite) TestContainerAPICopyResourcePathNotFoundPre124(c *check.C)
<ide> Resource: "/notexist",
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
<add> status, body, err := request.SockRequest("POST", "/v1.23/containers/"+name+"/copy", postData, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide> c.Assert(string(body), checker.Matches, "Could not find the file /notexist in container "+name+"\n")
<ide> func (s *DockerSuite) TestContainerAPICopyContainerNotFoundPr124(c *check.C) {
<ide> Resource: "/something",
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", "/v1.23/containers/notexists/copy", postData)
<add> status, _, err := request.SockRequest("POST", "/v1.23/containers/notexists/copy", postData, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNotFound)
<ide> }
<ide> func (s *DockerSuite) TestContainerAPIDelete(c *check.C) {
<ide>
<ide> dockerCmd(c, "stop", id)
<ide>
<del> status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
<add> status, _, err := request.SockRequest("DELETE", "/containers/"+id, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestContainerAPIDeleteNotExist(c *check.C) {
<del> status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
<add> status, body, err := request.SockRequest("DELETE", "/containers/doesnotexist", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNotFound)
<ide> c.Assert(getErrorMessage(c, body), checker.Matches, "No such container: doesnotexist")
<ide> func (s *DockerSuite) TestContainerAPIDeleteForce(c *check.C) {
<ide> id := strings.TrimSpace(out)
<ide> c.Assert(waitRun(id), checker.IsNil)
<ide>
<del> status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
<add> status, _, err := request.SockRequest("DELETE", "/containers/"+id+"?force=1", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide> }
<ide> func (s *DockerSuite) TestContainerAPIDeleteRemoveLinks(c *check.C) {
<ide> links := inspectFieldJSON(c, id2, "HostConfig.Links")
<ide> c.Assert(links, checker.Equals, "[\"/tlink1:/tlink2/tlink1\"]", check.Commentf("expected to have links between containers"))
<ide>
<del> status, b, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
<add> status, b, err := request.SockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusNoContent, check.Commentf(string(b)))
<ide>
<ide> func (s *DockerSuite) TestContainerAPIDeleteConflict(c *check.C) {
<ide> id := strings.TrimSpace(out)
<ide> c.Assert(waitRun(id), checker.IsNil)
<ide>
<del> status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
<add> status, _, err := request.SockRequest("DELETE", "/containers/"+id, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusConflict)
<ide> }
<ide> func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) {
<ide> _, err = os.Stat(source)
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
<add> status, _, err := request.SockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide> _, err = os.Stat(source)
<ide> func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) {
<ide>
<ide> // Regression test for https://github.com/docker/docker/issues/6231
<ide> func (s *DockerSuite) TestContainerAPIChunkedEncoding(c *check.C) {
<del> conn, err := sockConn(time.Duration(10*time.Second), "")
<del> c.Assert(err, checker.IsNil)
<del> client := httputil.NewClientConn(conn, nil)
<del> defer client.Close()
<ide>
<ide> config := map[string]interface{}{
<ide> "Image": "busybox",
<ide> "Cmd": append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...),
<ide> "OpenStdin": true,
<ide> }
<del> b, err := json.Marshal(config)
<del> c.Assert(err, checker.IsNil)
<ide>
<del> req, err := http.NewRequest("POST", "/containers/create", bytes.NewBuffer(b))
<del> c.Assert(err, checker.IsNil)
<del> req.Header.Set("Content-Type", "application/json")
<del> // This is a cheat to make the http request do chunked encoding
<del> // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
<del> // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
<del> req.ContentLength = -1
<del>
<del> resp, err := client.Do(req)
<add> resp, _, err := request.Post(daemonHost(), "/containers/create", request.JSONBody(config), func(req *http.Request) error {
<add> // This is a cheat to make the http request do chunked encoding
<add> // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
<add> // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
<add> req.ContentLength = -1
<add> return nil
<add> })
<ide> c.Assert(err, checker.IsNil, check.Commentf("error creating container with chunked encoding"))
<del> resp.Body.Close()
<ide> c.Assert(resp.StatusCode, checker.Equals, http.StatusCreated)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestContainerAPIPostContainerStop(c *check.C) {
<ide> containerID := strings.TrimSpace(out)
<ide> c.Assert(waitRun(containerID), checker.IsNil)
<ide>
<del> statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
<add> statusCode, _, err := request.SockRequest("POST", "/containers/"+containerID+"/stop", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> // 204 No Content is expected, not 200
<ide> c.Assert(statusCode, checker.Equals, http.StatusNoContent)
<ide> func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *c
<ide> Entrypoint string
<ide> Cmd []string
<ide> }{"busybox", "echo", []string{"hello", "world"}}
<del> _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
<add> _, _, err := request.SockRequest("POST", "/containers/create?name=echotest", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> out, _ := dockerCmd(c, "start", "-a", "echotest")
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
<ide> func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *c
<ide> Entrypoint []string
<ide> Cmd []string
<ide> }{"busybox", []string{"echo"}, []string{"hello", "world"}}
<del> _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
<add> _, _, err = request.SockRequest("POST", "/containers/create?name=echotest2", config2, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> out, _ = dockerCmd(c, "start", "-a", "echotest2")
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
<ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
<ide> Entrypoint string
<ide> Cmd string
<ide> }{"busybox", "echo", "hello world"}
<del> _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
<add> _, _, err := request.SockRequest("POST", "/containers/create?name=echotest", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> out, _ := dockerCmd(c, "start", "-a", "echotest")
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
<ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
<ide> Image string
<ide> Cmd []string
<ide> }{"busybox", []string{"echo", "hello", "world"}}
<del> _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
<add> _, _, err = request.SockRequest("POST", "/containers/create?name=echotest2", config2, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> out, _ = dockerCmd(c, "start", "-a", "echotest2")
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
<ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *che
<ide> CapAdd string
<ide> CapDrop string
<ide> }{"busybox", "NET_ADMIN", "SYS_ADMIN"}
<del> status, _, err := sockRequest("POST", "/containers/create?name=capaddtest0", config)
<add> status, _, err := request.SockRequest("POST", "/containers/create?name=capaddtest0", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *che
<ide> CapAdd []string
<ide> CapDrop []string
<ide> }{"busybox", []string{"NET_ADMIN", "SYS_ADMIN"}, []string{"SETGID"}}
<del> status, _, err = sockRequest("POST", "/containers/create?name=capaddtest1", config2)
<add> status, _, err = request.SockRequest("POST", "/containers/create?name=capaddtest1", config2, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide> }
<ide> func (s *DockerSuite) TestContainerAPICreateNoHostConfig118(c *check.C) {
<ide> config := struct {
<ide> Image string
<ide> }{"busybox"}
<del> status, _, err := sockRequest("POST", "/v1.18/containers/create", config)
<add> status, _, err := request.SockRequest("POST", "/v1.18/containers/create", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide> }
<ide> func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(
<ide> query.Set("path", "/vol2/symlinkToAbsDir")
<ide> urlPath := fmt.Sprintf("/v1.20/containers/%s/archive?%s", cID, query.Encode())
<ide>
<del> statusCode, body, err := sockRequest("PUT", urlPath, nil)
<add> statusCode, body, err := request.SockRequest("PUT", urlPath, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> if !isCpCannotCopyReadOnly(fmt.Errorf(string(body))) {
<ide> func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(
<ide> }
<ide>
<ide> func (s *DockerSuite) TestContainerAPIGetContainersJSONEmpty(c *check.C) {
<del> status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/json?all=1", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> c.Assert(string(body), checker.Equals, "[]\n")
<ide> func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C)
<ide> CpusetCpus string
<ide> }{"busybox", "1-42,,"}
<ide> name := "wrong-cpuset-cpus"
<del> status, body, err := sockRequest("POST", "/containers/create?name="+name, c1)
<add> status, body, err := request.SockRequest("POST", "/containers/create?name="+name, c1, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide> expected := "Invalid value 1-42,, for cpuset cpus"
<ide> func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C)
<ide> CpusetMems string
<ide> }{"busybox", "42-3,1--"}
<ide> name = "wrong-cpuset-mems"
<del> status, body, err = sockRequest("POST", "/containers/create?name="+name, c2)
<add> status, body, err = request.SockRequest("POST", "/containers/create?name="+name, c2, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide> expected = "Invalid value 42-3,1-- for cpuset mems"
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
<ide> "HostConfig": map[string]interface{}{"ShmSize": -1},
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide> c.Assert(getErrorMessage(c, body), checker.Contains, "SHM size can not be less than 0")
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.
<ide> "Cmd": "mount",
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusCreated)
<ide>
<ide> var container containertypes.ContainerCreateCreatedBody
<ide> c.Assert(json.Unmarshal(body, &container), check.IsNil)
<ide>
<del> status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
<add> status, body, err = request.SockRequest("GET", "/containers/"+container.ID+"/json", nil, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) {
<ide> "Cmd": "mount",
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusCreated)
<ide>
<ide> var container containertypes.ContainerCreateCreatedBody
<ide> c.Assert(json.Unmarshal(body, &container), check.IsNil)
<ide>
<del> status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
<add> status, body, err = request.SockRequest("GET", "/containers/"+container.ID+"/json", nil, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) {
<ide> "HostConfig": map[string]interface{}{"ShmSize": 1073741824},
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusCreated)
<ide>
<ide> var container containertypes.ContainerCreateCreatedBody
<ide> c.Assert(json.Unmarshal(body, &container), check.IsNil)
<ide>
<del> status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
<add> status, body, err = request.SockRequest("GET", "/containers/"+container.ID+"/json", nil, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(
<ide> "Image": "busybox",
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create", config)
<add> status, body, err := request.SockRequest("POST", "/containers/create", config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusCreated)
<ide>
<ide> var container containertypes.ContainerCreateCreatedBody
<ide> c.Assert(json.Unmarshal(body, &container), check.IsNil)
<ide>
<del> status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
<add> status, body, err = request.SockRequest("GET", "/containers/"+container.ID+"/json", nil, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che
<ide> OomScoreAdj int
<ide> }{"busybox", 1001}
<ide> name := "oomscoreadj-over"
<del> status, b, err := sockRequest("POST", "/containers/create?name="+name, config)
<add> status, b, err := request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che
<ide> OomScoreAdj int
<ide> }{"busybox", -1001}
<ide> name = "oomscoreadj-low"
<del> status, b, err = sockRequest("POST", "/containers/create?name="+name, config)
<add> status, b, err = request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide> expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]"
<ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che
<ide>
<ide> // test case for #22210 where an empty container name caused panic.
<ide> func (s *DockerSuite) TestContainerAPIDeleteWithEmptyName(c *check.C) {
<del> status, out, err := sockRequest("DELETE", "/containers/", nil)
<add> status, out, err := request.SockRequest("DELETE", "/containers/", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusBadRequest)
<ide> c.Assert(string(out), checker.Contains, "No container name or ID supplied")
<ide> func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *check.C) {
<ide> "NetworkDisabled": true,
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
<add> status, _, err := request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<del> status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
<add> status, _, err = request.SockRequest("POST", "/containers/"+name+"/start", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide>
<ide> func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *check.C) {
<ide> }
<ide> bc := make(chan b, 1)
<ide> go func() {
<del> status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
<add> status, body, err := request.SockRequest("GET", "/containers/"+name+"/stats", nil, daemonHost())
<ide> bc <- b{status, body, err}
<ide> }()
<ide>
<ide> func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) {
<ide>
<ide> for i, x := range cases {
<ide> c.Logf("case %d", i)
<del> status, b, err := sockRequest("POST", "/containers/create", x.config)
<add> status, b, err := request.SockRequest("POST", "/containers/create", x.config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, x.status, check.Commentf("%s\n%v", string(b), cases[i].config))
<ide> if len(x.msg) > 0 {
<ide> func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *check.C) {
<ide> "Cmd": []string{"/bin/sh", "-c", "cat /foo/bar"},
<ide> "HostConfig": map[string]interface{}{"Mounts": []map[string]interface{}{{"Type": "bind", "Source": tmpDir, "Target": destPath}}},
<ide> }
<del> status, resp, err := sockRequest("POST", "/containers/create?name=test", data)
<add> status, resp, err := request.SockRequest("POST", "/containers/create?name=test", data, daemonHost())
<ide> c.Assert(err, checker.IsNil, check.Commentf(string(resp)))
<ide> c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(resp)))
<ide>
<ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) {
<ide> }
<ide> for i, x := range cases {
<ide> c.Logf("case %d - config: %v", i, x.cfg)
<del> status, data, err := sockRequest("POST", "/containers/create", wrapper{containertypes.Config{Image: testImg}, containertypes.HostConfig{Mounts: []mounttypes.Mount{x.cfg}}})
<add> status, data, err := request.SockRequest("POST", "/containers/create", wrapper{containertypes.Config{Image: testImg}, containertypes.HostConfig{Mounts: []mounttypes.Mount{x.cfg}}}, daemonHost())
<ide> c.Assert(err, checker.IsNil, check.Commentf(string(data)))
<ide> c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(data)))
<ide>
<ide> func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *check.C) {
<ide> fmt.Sprintf("mount | grep 'tmpfs on %s'", target)},
<ide> "HostConfig": map[string]interface{}{"Mounts": []map[string]interface{}{x.cfg}},
<ide> }
<del> status, resp, err := sockRequest("POST", "/containers/create?name="+cName, data)
<add> status, resp, err := request.SockRequest("POST", "/containers/create?name="+cName, data, daemonHost())
<ide> c.Assert(err, checker.IsNil, check.Commentf(string(resp)))
<ide> c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(resp)))
<ide> out, _ := dockerCmd(c, "start", "-a", cName)
<ide><path>integration-cli/docker_api_create_test.go
<ide> import (
<ide> "net/http"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestAPICreateWithNotExistImage(c *check.C) {
<ide> "Volumes": map[string]struct{}{"/tmp": {}},
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create?name="+name, config)
<add> status, body, err := request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusNotFound)
<ide> expected := "No such image: test456:v1"
<ide> func (s *DockerSuite) TestAPICreateWithNotExistImage(c *check.C) {
<ide> "Volumes": map[string]struct{}{"/tmp": {}},
<ide> }
<ide>
<del> status, body, err = sockRequest("POST", "/containers/create?name="+name, config2)
<add> status, body, err = request.SockRequest("POST", "/containers/create?name="+name, config2, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusNotFound)
<ide> expected = "No such image: test456:latest"
<ide> func (s *DockerSuite) TestAPICreateWithNotExistImage(c *check.C) {
<ide> "Image": "sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
<ide> }
<ide>
<del> status, body, err = sockRequest("POST", "/containers/create?name="+name, config3)
<add> status, body, err = request.SockRequest("POST", "/containers/create?name="+name, config3, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusNotFound)
<ide> expected = "No such image: sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa"
<ide> func (s *DockerSuite) TestAPICreateEmptyEnv(c *check.C) {
<ide> "Cmd": []string{"true"},
<ide> }
<ide>
<del> status, body, err := sockRequest("POST", "/containers/create?name="+name, config)
<add> status, body, err := request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide> expected := "invalid environment variable:"
<ide> func (s *DockerSuite) TestAPICreateEmptyEnv(c *check.C) {
<ide> "Env": []string{"=", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},
<ide> "Cmd": []string{"true"},
<ide> }
<del> status, body, err = sockRequest("POST", "/containers/create?name="+name, config)
<add> status, body, err = request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide> expected = "invalid environment variable: ="
<ide> func (s *DockerSuite) TestAPICreateEmptyEnv(c *check.C) {
<ide> "Env": []string{"=foo", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},
<ide> "Cmd": []string{"true"},
<ide> }
<del> status, body, err = sockRequest("POST", "/containers/create?name="+name, config)
<add> status, body, err = request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide> expected = "invalid environment variable: =foo"
<ide><path>integration-cli/docker_api_events_test.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/go-check/check"
<ide> )
<ide> func (s *DockerSuite) TestEventsAPIEmptyOutput(c *check.C) {
<ide> }
<ide> chResp := make(chan *apiResp)
<ide> go func() {
<del> resp, body, err := sockRequestRaw("GET", "/events", nil, "")
<add> resp, body, err := request.SockRequestRaw("GET", "/events", nil, "", daemonHost())
<ide> body.Close()
<ide> chResp <- &apiResp{resp, err}
<ide> }()
<ide> func (s *DockerSuite) TestEventsAPIBackwardsCompatible(c *check.C) {
<ide> q := url.Values{}
<ide> q.Set("since", ts)
<ide>
<del> _, body, err := sockRequestRaw("GET", "/events?"+q.Encode(), nil, "")
<add> _, body, err := request.SockRequestRaw("GET", "/events?"+q.Encode(), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> defer body.Close()
<ide>
<ide><path>integration-cli/docker_api_exec_resize_test.go
<ide> import (
<ide> "sync"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestExecResizeAPIHeightWidthNoInt(c *check.C) {
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<ide> endpoint := "/exec/" + cleanedContainerID + "/resize?h=foo&w=bar"
<del> status, _, err := sockRequest("POST", endpoint, nil)
<add> status, _, err := request.SockRequest("POST", endpoint, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide> }
<ide> func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *check.C) {
<ide> "Cmd": []string{"/bin/sh"},
<ide> }
<ide> uri := fmt.Sprintf("/containers/%s/exec", name)
<del> status, body, err := sockRequest("POST", uri, data)
<add> status, body, err := request.SockRequest("POST", uri, data, daemonHost())
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *check.C) {
<ide> }
<ide>
<ide> payload := bytes.NewBufferString(`{"Tty":true}`)
<del> conn, _, err := sockRequestHijack("POST", fmt.Sprintf("/exec/%s/start", execID), payload, "application/json")
<add> conn, _, err := request.SockRequestHijack("POST", fmt.Sprintf("/exec/%s/start", execID), payload, "application/json", daemonHost())
<ide> if err != nil {
<ide> return fmt.Errorf("Failed to start the exec: %q", err.Error())
<ide> }
<ide> defer conn.Close()
<ide>
<del> _, rc, err := sockRequestRaw("POST", fmt.Sprintf("/exec/%s/resize?h=24&w=80", execID), nil, "text/plain")
<add> _, rc, err := request.SockRequestRaw("POST", fmt.Sprintf("/exec/%s/resize?h=24&w=80", execID), nil, "text/plain", daemonHost())
<ide> // It's probably a panic of the daemon if io.ErrUnexpectedEOF is returned.
<ide> if err == io.ErrUnexpectedEOF {
<ide> return fmt.Errorf("The daemon might have crashed.")
<ide><path>integration-cli/docker_api_exec_test.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/testutil"
<ide> "github.com/go-check/check"
<ide> )
<ide> func (s *DockerSuite) TestExecAPICreateNoCmd(c *check.C) {
<ide> name := "exec_test"
<ide> dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
<ide>
<del> status, body, err := sockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": nil})
<add> status, body, err := request.SockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": nil}, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide>
<ide> func (s *DockerSuite) TestExecAPICreateNoValidContentType(c *check.C) {
<ide> c.Fatalf("Can not encode data to json %s", err)
<ide> }
<ide>
<del> res, body, err := sockRequestRaw("POST", fmt.Sprintf("/containers/%s/exec", name), jsonData, "text/plain")
<add> res, body, err := request.SockRequestRaw("POST", fmt.Sprintf("/containers/%s/exec", name), jsonData, "text/plain", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
<ide>
<ide> func (s *DockerSuite) TestExecAPICreateContainerPaused(c *check.C) {
<ide> dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
<ide>
<ide> dockerCmd(c, "pause", name)
<del> status, body, err := sockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": []string{"true"}})
<add> status, body, err := request.SockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": []string{"true"}}, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusConflict)
<ide>
<ide> func (s *DockerSuite) TestExecAPIStartEnsureHeaders(c *check.C) {
<ide> dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
<ide>
<ide> id := createExec(c, "test")
<del> resp, _, err := sockRequestRaw("POST", fmt.Sprintf("/exec/%s/start", id), strings.NewReader(`{"Detach": true}`), "application/json")
<add> resp, _, err := request.SockRequestRaw("POST", fmt.Sprintf("/exec/%s/start", id), strings.NewReader(`{"Detach": true}`), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(resp.Header.Get("Server"), checker.Not(checker.Equals), "")
<ide> }
<ide> func (s *DockerSuite) TestExecAPIStartBackwardsCompatible(c *check.C) {
<ide> runSleepingContainer(c, "-d", "--name", "test")
<ide> id := createExec(c, "test")
<ide>
<del> resp, body, err := sockRequestRaw("POST", fmt.Sprintf("/v1.20/exec/%s/start", id), strings.NewReader(`{"Detach": true}`), "text/plain")
<add> resp, body, err := request.SockRequestRaw("POST", fmt.Sprintf("/v1.20/exec/%s/start", id), strings.NewReader(`{"Detach": true}`), "text/plain", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> b, err := testutil.ReadBody(body)
<ide> func (s *DockerSuite) TestExecAPIStartWithDetach(c *check.C) {
<ide> "cmd": []string{"true"},
<ide> "AttachStdin": true,
<ide> }
<del> _, b, err := sockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), data)
<add> _, b, err := request.SockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), data, daemonHost())
<ide> c.Assert(err, checker.IsNil, check.Commentf(string(b)))
<ide>
<ide> createResp := struct {
<ide> ID string `json:"Id"`
<ide> }{}
<ide> c.Assert(json.Unmarshal(b, &createResp), checker.IsNil, check.Commentf(string(b)))
<ide>
<del> _, body, err := sockRequestRaw("POST", fmt.Sprintf("/exec/%s/start", createResp.ID), strings.NewReader(`{"Detach": true}`), "application/json")
<add> _, body, err := request.SockRequestRaw("POST", fmt.Sprintf("/exec/%s/start", createResp.ID), strings.NewReader(`{"Detach": true}`), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> b, err = testutil.ReadBody(body)
<ide> comment := check.Commentf("response body: %s", b)
<ide> c.Assert(err, checker.IsNil, comment)
<ide>
<del> resp, _, err := sockRequestRaw("GET", "/_ping", nil, "")
<add> resp, _, err := request.SockRequestRaw("GET", "/_ping", nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> if resp.StatusCode != http.StatusOK {
<ide> c.Fatal("daemon is down, it should alive")
<ide> }
<ide> }
<ide>
<ide> func createExec(c *check.C, name string) string {
<del> _, b, err := sockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": []string{"true"}})
<add> _, b, err := request.SockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": []string{"true"}}, daemonHost())
<ide> c.Assert(err, checker.IsNil, check.Commentf(string(b)))
<ide>
<ide> createResp := struct {
<ide> func createExec(c *check.C, name string) string {
<ide> }
<ide>
<ide> func startExec(c *check.C, id string, code int) {
<del> resp, body, err := sockRequestRaw("POST", fmt.Sprintf("/exec/%s/start", id), strings.NewReader(`{"Detach": true}`), "application/json")
<add> resp, body, err := request.SockRequestRaw("POST", fmt.Sprintf("/exec/%s/start", id), strings.NewReader(`{"Detach": true}`), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> b, err := testutil.ReadBody(body)
<ide> func startExec(c *check.C, id string, code int) {
<ide> }
<ide>
<ide> func inspectExec(c *check.C, id string, out interface{}) {
<del> resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/exec/%s/json", id), nil, "")
<add> resp, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/exec/%s/json", id), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> defer body.Close()
<ide> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide><path>integration-cli/docker_api_images_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestAPIImagesFilter(c *check.C) {
<ide> getImages := func(filter string) []image {
<ide> v := url.Values{}
<ide> v.Set("filter", filter)
<del> status, b, err := sockRequest("GET", "/images/json?"+v.Encode(), nil)
<add> status, b, err := request.SockRequest("GET", "/images/json?"+v.Encode(), nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestAPIImagesSaveAndLoad(c *check.C) {
<ide> c.Assert(err, checker.IsNil)
<ide> id := strings.TrimSpace(out)
<ide>
<del> res, body, err := sockRequestRaw("GET", "/images/"+id+"/get", nil, "")
<add> res, body, err := request.SockRequestRaw("GET", "/images/"+id+"/get", nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> defer body.Close()
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide>
<ide> dockerCmd(c, "rmi", id)
<ide>
<del> res, loadBody, err := sockRequestRaw("POST", "/images/load", body, "application/x-tar")
<add> res, loadBody, err := request.SockRequestRaw("POST", "/images/load", body, "application/x-tar", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> defer loadBody.Close()
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide> func (s *DockerSuite) TestAPIImagesDelete(c *check.C) {
<ide>
<ide> dockerCmd(c, "tag", name, "test:tag1")
<ide>
<del> status, _, err := sockRequest("DELETE", "/images/"+id, nil)
<add> status, _, err := request.SockRequest("DELETE", "/images/"+id, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusConflict)
<ide>
<del> status, _, err = sockRequest("DELETE", "/images/test:noexist", nil)
<add> status, _, err = request.SockRequest("DELETE", "/images/test:noexist", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNotFound) //Status Codes:404 – no such image
<ide>
<del> status, _, err = sockRequest("DELETE", "/images/test:tag1", nil)
<add> status, _, err = request.SockRequest("DELETE", "/images/test:tag1", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> }
<ide> func (s *DockerSuite) TestAPIImagesHistory(c *check.C) {
<ide>
<ide> id := strings.TrimSpace(out)
<ide>
<del> status, body, err := sockRequest("GET", "/images/"+id+"/history", nil)
<add> status, body, err := request.SockRequest("GET", "/images/"+id+"/history", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestAPIImagesHistory(c *check.C) {
<ide> func (s *DockerSuite) TestAPIImagesSearchJSONContentType(c *check.C) {
<ide> testRequires(c, Network)
<ide>
<del> res, b, err := sockRequestRaw("GET", "/images/search?term=test", nil, "application/json")
<add> res, b, err := request.SockRequestRaw("GET", "/images/search?term=test", nil, "application/json", daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> b.Close()
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide><path>integration-cli/docker_api_info_test.go
<ide> import (
<ide> "net/http"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestInfoAPI(c *check.C) {
<ide> endpoint := "/info"
<ide>
<del> status, body, err := sockRequest("GET", endpoint, nil)
<add> status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost())
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> func (s *DockerSuite) TestInfoAPIVersioned(c *check.C) {
<ide> testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
<ide> endpoint := "/v1.20/info"
<ide>
<del> status, body, err := sockRequest("GET", endpoint, nil)
<add> status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost())
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide><path>integration-cli/docker_api_inspect_test.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/versions/v1p20"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/go-check/check"
<ide> )
<ide> func (s *DockerSuite) TestInspectAPIImageResponse(c *check.C) {
<ide> dockerCmd(c, "tag", "busybox:latest", "busybox:mytag")
<ide>
<ide> endpoint := "/images/busybox/json"
<del> status, body, err := sockRequest("GET", endpoint, nil)
<add> status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost())
<ide>
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide><path>integration-cli/docker_api_inspect_unix_test.go
<ide> import (
<ide> "net/http"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestInspectAPICpusetInConfigPre120(c *check.C) {
<ide> name := "cpusetinconfig-pre120"
<ide> dockerCmd(c, "run", "--name", name, "--cpuset-cpus", "0", "busybox", "true")
<ide>
<del> status, body, err := sockRequest("GET", fmt.Sprintf("/v1.19/containers/%s/json", name), nil)
<add> status, body, err := request.SockRequest("GET", fmt.Sprintf("/v1.19/containers/%s/json", name), nil, daemonHost())
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide> c.Assert(err, check.IsNil)
<ide>
<ide><path>integration-cli/docker_api_logs_test.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) {
<ide> chLog := make(chan logOut)
<ide>
<ide> go func() {
<del> res, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1×tamps=1", id), nil, "")
<add> res, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1×tamps=1", id), nil, "", daemonHost())
<ide> if err != nil {
<ide> chLog <- logOut{"", nil, err}
<ide> return
<ide> func (s *DockerSuite) TestLogsAPINoStdoutNorStderr(c *check.C) {
<ide> name := "logs_test"
<ide> dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
<ide>
<del> status, body, err := sockRequest("GET", fmt.Sprintf("/containers/%s/logs", name), nil)
<add> status, body, err := request.SockRequest("GET", fmt.Sprintf("/containers/%s/logs", name), nil, daemonHost())
<ide> c.Assert(status, checker.Equals, http.StatusBadRequest)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> func (s *DockerSuite) TestLogsAPIFollowEmptyOutput(c *check.C) {
<ide> t0 := time.Now()
<ide> dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10")
<ide>
<del> _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name), bytes.NewBuffer(nil), "")
<add> _, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name), bytes.NewBuffer(nil), "", daemonHost())
<ide> t1 := time.Now()
<ide> c.Assert(err, checker.IsNil)
<ide> body.Close()
<ide> func (s *DockerSuite) TestLogsAPIFollowEmptyOutput(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestLogsAPIContainerNotFound(c *check.C) {
<ide> name := "nonExistentContainer"
<del> resp, _, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name), bytes.NewBuffer(nil), "")
<add> resp, _, err := request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name), bytes.NewBuffer(nil), "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(resp.StatusCode, checker.Equals, http.StatusNotFound)
<ide> }
<ide><path>integration-cli/docker_api_network_test.go
<ide> import (
<ide> "github.com/docker/docker/api/types/filters"
<ide> "github.com/docker/docker/api/types/network"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func createDeletePredefinedNetwork(c *check.C, name string) {
<ide> }
<ide>
<ide> func isNetworkAvailable(c *check.C, name string) bool {
<del> status, body, err := sockRequest("GET", "/networks", nil)
<del> c.Assert(status, checker.Equals, http.StatusOK)
<add> resp, body, err := request.Get(daemonHost(), "/networks")
<add> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> nJSON := []types.NetworkResource{}
<del> err = json.Unmarshal(body, &nJSON)
<add> err = json.NewDecoder(body).Decode(&nJSON)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> for _, n := range nJSON {
<ide> func getNetworkIDByName(c *check.C, name string) string {
<ide> c.Assert(err, checker.IsNil)
<ide> v.Set("filters", filterJSON)
<ide>
<del> status, body, err := sockRequest("GET", "/networks?"+v.Encode(), nil)
<del> c.Assert(status, checker.Equals, http.StatusOK)
<add> resp, body, err := request.Get(daemonHost(), "/networks?"+v.Encode())
<add> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> nJSON := []types.NetworkResource{}
<del> err = json.Unmarshal(body, &nJSON)
<add> err = json.NewDecoder(body).Decode(&nJSON)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(len(nJSON), checker.Equals, 1)
<ide>
<ide> return nJSON[0].ID
<ide> }
<ide>
<ide> func getNetworkResource(c *check.C, id string) *types.NetworkResource {
<del> _, obj, err := sockRequest("GET", "/networks/"+id, nil)
<add> _, obj, err := request.Get(daemonHost(), "/networks/"+id)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> nr := types.NetworkResource{}
<del> err = json.Unmarshal(obj, &nr)
<add> err = json.NewDecoder(obj).Decode(&nr)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> return &nr
<ide> }
<ide>
<ide> func createNetwork(c *check.C, config types.NetworkCreateRequest, shouldSucceed bool) string {
<del> status, resp, err := sockRequest("POST", "/networks/create", config)
<add> resp, body, err := request.Post(daemonHost(), "/networks/create", request.JSONBody(config))
<ide> if !shouldSucceed {
<del> c.Assert(status, checker.Not(checker.Equals), http.StatusCreated)
<add> c.Assert(resp.StatusCode, checker.Not(checker.Equals), http.StatusCreated)
<ide> return ""
<ide> }
<ide>
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(status, checker.Equals, http.StatusCreated)
<add> c.Assert(resp.StatusCode, checker.Equals, http.StatusCreated)
<ide>
<ide> var nr types.NetworkCreateResponse
<del> err = json.Unmarshal(resp, &nr)
<add> err = json.NewDecoder(body).Decode(&nr)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> return nr.ID
<ide> func connectNetwork(c *check.C, nid, cid string) {
<ide> Container: cid,
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", "/networks/"+nid+"/connect", config)
<del> c.Assert(status, checker.Equals, http.StatusOK)
<add> resp, _, err := request.Post(daemonHost(), "/networks/"+nid+"/connect", request.JSONBody(config))
<add> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide> c.Assert(err, checker.IsNil)
<ide> }
<ide>
<ide> func disconnectNetwork(c *check.C, nid, cid string) {
<ide> Container: cid,
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", "/networks/"+nid+"/disconnect", config)
<del> c.Assert(status, checker.Equals, http.StatusOK)
<add> resp, _, err := request.Post(daemonHost(), "/networks/"+nid+"/disconnect", request.JSONBody(config))
<add> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide> c.Assert(err, checker.IsNil)
<ide> }
<ide>
<ide> func deleteNetwork(c *check.C, id string, shouldSucceed bool) {
<del> status, _, err := sockRequest("DELETE", "/networks/"+id, nil)
<add> resp, _, err := request.Delete(daemonHost(), "/networks/"+id)
<ide> if !shouldSucceed {
<del> c.Assert(status, checker.Not(checker.Equals), http.StatusOK)
<add> c.Assert(resp.StatusCode, checker.Not(checker.Equals), http.StatusOK)
<ide> return
<ide> }
<del> c.Assert(status, checker.Equals, http.StatusNoContent)
<add> c.Assert(resp.StatusCode, checker.Equals, http.StatusNoContent)
<ide> c.Assert(err, checker.IsNil)
<ide> }
<ide><path>integration-cli/docker_api_resize_test.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestResizeAPIResponse(c *check.C) {
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<ide> endpoint := "/containers/" + cleanedContainerID + "/resize?h=40&w=40"
<del> status, _, err := sockRequest("POST", endpoint, nil)
<add> status, _, err := request.SockRequest("POST", endpoint, nil, daemonHost())
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide> c.Assert(err, check.IsNil)
<ide> }
<ide> func (s *DockerSuite) TestResizeAPIHeightWidthNoInt(c *check.C) {
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<ide> endpoint := "/containers/" + cleanedContainerID + "/resize?h=foo&w=bar"
<del> status, _, err := sockRequest("POST", endpoint, nil)
<add> status, _, err := request.SockRequest("POST", endpoint, nil, daemonHost())
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide> c.Assert(err, check.IsNil)
<ide> }
<ide> func (s *DockerSuite) TestResizeAPIResponseWhenContainerNotStarted(c *check.C) {
<ide> dockerCmd(c, "wait", cleanedContainerID)
<ide>
<ide> endpoint := "/containers/" + cleanedContainerID + "/resize?h=40&w=40"
<del> status, body, err := sockRequest("POST", endpoint, nil)
<add> status, body, err := request.SockRequest("POST", endpoint, nil, daemonHost())
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<ide> c.Assert(err, check.IsNil)
<ide>
<ide><path>integration-cli/docker_api_stats_test.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/versions"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestAPIStatsNoStreamGetCpu(c *check.C) {
<ide> id := strings.TrimSpace(out)
<ide> c.Assert(waitRun(id), checker.IsNil)
<ide>
<del> resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
<add> resp, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide> c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json")
<ide> func (s *DockerSuite) TestAPIStatsStoppedContainerInGoroutines(c *check.C) {
<ide> id := strings.TrimSpace(out)
<ide>
<ide> getGoRoutines := func() int {
<del> _, body, err := sockRequestRaw("GET", fmt.Sprintf("/info"), nil, "")
<add> _, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/info"), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> info := types.Info{}
<ide> err = json.NewDecoder(body).Decode(&info)
<ide> func (s *DockerSuite) TestAPIStatsStoppedContainerInGoroutines(c *check.C) {
<ide>
<ide> // When the HTTP connection is closed, the number of goroutines should not increase.
<ide> routines := getGoRoutines()
<del> _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats", id), nil, "")
<add> _, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats", id), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> body.Close()
<ide>
<ide> func (s *DockerSuite) TestAPIStatsNetworkStatsVersioning(c *check.C) {
<ide> func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats {
<ide> var st *types.StatsJSON
<ide>
<del> _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
<add> _, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> err = json.NewDecoder(body).Decode(&st)
<ide> func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats {
<ide> func getVersionedStats(c *check.C, id string, apiVersion string) map[string]interface{} {
<ide> stats := make(map[string]interface{})
<ide>
<del> _, body, err := sockRequestRaw("GET", fmt.Sprintf("/%s/containers/%s/stats?stream=false", apiVersion, id), nil, "")
<add> _, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/%s/containers/%s/stats?stream=false", apiVersion, id), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> defer body.Close()
<ide>
<ide> func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool {
<ide> func (s *DockerSuite) TestAPIStatsContainerNotFound(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide>
<del> status, _, err := sockRequest("GET", "/containers/nonexistent/stats", nil)
<add> status, _, err := request.SockRequest("GET", "/containers/nonexistent/stats", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNotFound)
<ide>
<del> status, _, err = sockRequest("GET", "/containers/nonexistent/stats?stream=0", nil)
<add> status, _, err = request.SockRequest("GET", "/containers/nonexistent/stats?stream=0", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNotFound)
<ide> }
<ide> func (s *DockerSuite) TestAPIStatsNoStreamConnectedContainers(c *check.C) {
<ide>
<ide> ch := make(chan error)
<ide> go func() {
<del> resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id2), nil, "")
<add> resp, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id2), nil, "", daemonHost())
<ide> defer body.Close()
<ide> if err != nil {
<ide> ch <- err
<ide><path>integration-cli/docker_api_stats_unix_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestAPIStatsContainerGetMemoryLimit(c *check.C) {
<ide> testRequires(c, DaemonIsLinux, memoryLimitSupport)
<ide>
<del> resp, body, err := sockRequestRaw("GET", "/info", nil, "application/json")
<add> resp, body, err := request.SockRequestRaw("GET", "/info", nil, "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide> var info types.Info
<ide> func (s *DockerSuite) TestAPIStatsContainerGetMemoryLimit(c *check.C) {
<ide> dockerCmd(c, "run", "-d", "--name", conName, "busybox", "top")
<ide> c.Assert(waitRun(conName), checker.IsNil)
<ide>
<del> resp, body, err = sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", conName), nil, "")
<add> resp, body, err = request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", conName), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide> c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json")
<ide><path>integration-cli/docker_api_test.go
<ide> package main
<ide>
<ide> import (
<ide> "fmt"
<add> "io/ioutil"
<ide> "net/http"
<ide> "net/http/httptest"
<ide> "runtime"
<ide> import (
<ide>
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/testutil"
<ide> icmd "github.com/docker/docker/pkg/testutil/cmd"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestAPIOptionsRoute(c *check.C) {
<del> status, _, err := sockRequest("OPTIONS", "/", nil)
<add> resp, _, err := request.Do(daemonHost(), "/", request.Method(http.MethodOptions))
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(status, checker.Equals, http.StatusOK)
<add> c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestAPIGetEnabledCORS(c *check.C) {
<del> res, body, err := sockRequestRaw("GET", "/version", nil, "")
<add> res, body, err := request.SockRequestRaw("GET", "/version", nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
<ide> body.Close()
<ide> func (s *DockerSuite) TestAPIClientVersionOldNotSupported(c *check.C) {
<ide> v[1] = strconv.Itoa(vMinInt)
<ide> version := strings.Join(v, ".")
<ide>
<del> status, body, err := sockRequest("GET", "/v"+version+"/version", nil)
<add> resp, body, err := request.Get(daemonHost(), "/v"+version+"/version")
<ide> c.Assert(err, checker.IsNil)
<del> c.Assert(status, checker.Equals, http.StatusBadRequest)
<add> defer body.Close()
<add> c.Assert(resp.StatusCode, checker.Equals, http.StatusBadRequest)
<ide> expected := fmt.Sprintf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", version, api.MinVersion)
<del> c.Assert(strings.TrimSpace(string(body)), checker.Contains, expected)
<add> content, err := ioutil.ReadAll(body)
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(strings.TrimSpace(string(content)), checker.Contains, expected)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestAPIDockerAPIVersion(c *check.C) {
<ide> func (s *DockerSuite) TestAPIDockerAPIVersion(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestAPIErrorJSON(c *check.C) {
<del> httpResp, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(`{}`), "application/json")
<add> httpResp, body, err := request.Post(daemonHost(), "/containers/create", request.JSONBody(struct{}{}))
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(httpResp.StatusCode, checker.Equals, http.StatusInternalServerError)
<ide> c.Assert(httpResp.Header.Get("Content-Type"), checker.Equals, "application/json")
<ide> func (s *DockerSuite) TestAPIErrorPlainText(c *check.C) {
<ide> // Windows requires API 1.25 or later. This test is validating a behaviour which was present
<ide> // in v1.23, but changed in 1.24, hence not applicable on Windows. See apiVersionSupportsJSONErrors
<ide> testRequires(c, DaemonIsLinux)
<del> httpResp, body, err := sockRequestRaw("POST", "/v1.23/containers/create", strings.NewReader(`{}`), "application/json")
<add> httpResp, body, err := request.Post(daemonHost(), "/v1.23/containers/create", request.JSONBody(struct{}{}))
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(httpResp.StatusCode, checker.Equals, http.StatusInternalServerError)
<ide> c.Assert(httpResp.Header.Get("Content-Type"), checker.Contains, "text/plain")
<ide> func (s *DockerSuite) TestAPIErrorPlainText(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestAPIErrorNotFoundJSON(c *check.C) {
<ide> // 404 is a different code path to normal errors, so test separately
<del> httpResp, body, err := sockRequestRaw("GET", "/notfound", nil, "application/json")
<add> httpResp, body, err := request.Get(daemonHost(), "/notfound", request.JSON)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(httpResp.StatusCode, checker.Equals, http.StatusNotFound)
<ide> c.Assert(httpResp.Header.Get("Content-Type"), checker.Equals, "application/json")
<ide> func (s *DockerSuite) TestAPIErrorNotFoundJSON(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestAPIErrorNotFoundPlainText(c *check.C) {
<del> httpResp, body, err := sockRequestRaw("GET", "/v1.23/notfound", nil, "application/json")
<add> httpResp, body, err := request.Get(daemonHost(), "/v1.23/notfound", request.JSON)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(httpResp.StatusCode, checker.Equals, http.StatusNotFound)
<ide> c.Assert(httpResp.Header.Get("Content-Type"), checker.Contains, "text/plain")
<ide><path>integration-cli/docker_api_update_unix_test.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestAPIUpdateContainer(c *check.C) {
<ide> "MemorySwap": 524288000,
<ide> }
<ide> dockerCmd(c, "run", "-d", "--name", name, "-m", "200M", "busybox", "top")
<del> _, _, err := sockRequest("POST", "/containers/"+name+"/update", hostConfig)
<add> _, _, err := request.SockRequest("POST", "/containers/"+name+"/update", hostConfig, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> c.Assert(inspectField(c, name, "HostConfig.Memory"), checker.Equals, "314572800")
<ide><path>integration-cli/docker_api_version_test.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestGetVersion(c *check.C) {
<del> status, body, err := sockRequest("GET", "/version", nil)
<add> status, body, err := request.SockRequest("GET", "/version", nil, daemonHost())
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide><path>integration-cli/docker_api_volumes_test.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> volumetypes "github.com/docker/docker/api/types/volume"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestVolumesAPIList(c *check.C) {
<ide> prefix, _ := getPrefixAndSlashFromDaemonPlatform()
<ide> dockerCmd(c, "run", "-v", prefix+"/foo", "busybox")
<ide>
<del> status, b, err := sockRequest("GET", "/volumes", nil)
<add> status, b, err := request.SockRequest("GET", "/volumes", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestVolumesAPICreate(c *check.C) {
<ide> config := volumetypes.VolumesCreateBody{
<ide> Name: "test",
<ide> }
<del> status, b, err := sockRequest("POST", "/volumes/create", config)
<add> status, b, err := request.SockRequest("POST", "/volumes/create", config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusCreated, check.Commentf(string(b)))
<ide>
<ide> func (s *DockerSuite) TestVolumesAPIRemove(c *check.C) {
<ide> prefix, _ := getPrefixAndSlashFromDaemonPlatform()
<ide> dockerCmd(c, "run", "-v", prefix+"/foo", "--name=test", "busybox")
<ide>
<del> status, b, err := sockRequest("GET", "/volumes", nil)
<add> status, b, err := request.SockRequest("GET", "/volumes", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide>
<ide> func (s *DockerSuite) TestVolumesAPIRemove(c *check.C) {
<ide> c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes))
<ide>
<ide> v := volumes.Volumes[0]
<del> status, _, err = sockRequest("DELETE", "/volumes/"+v.Name, nil)
<add> status, _, err = request.SockRequest("DELETE", "/volumes/"+v.Name, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusConflict, check.Commentf("Should not be able to remove a volume that is in use"))
<ide>
<ide> dockerCmd(c, "rm", "-f", "test")
<del> status, data, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
<add> status, data, err := request.SockRequest("DELETE", "/volumes/"+v.Name, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent, check.Commentf(string(data)))
<ide>
<ide> func (s *DockerSuite) TestVolumesAPIInspect(c *check.C) {
<ide> config := volumetypes.VolumesCreateBody{
<ide> Name: "test",
<ide> }
<del> status, b, err := sockRequest("POST", "/volumes/create", config)
<add> status, b, err := request.SockRequest("POST", "/volumes/create", config, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusCreated, check.Commentf(string(b)))
<ide>
<del> status, b, err = sockRequest("GET", "/volumes", nil)
<add> status, b, err = request.SockRequest("GET", "/volumes", nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK, check.Commentf(string(b)))
<ide>
<ide> func (s *DockerSuite) TestVolumesAPIInspect(c *check.C) {
<ide> c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes))
<ide>
<ide> var vol types.Volume
<del> status, b, err = sockRequest("GET", "/volumes/"+config.Name, nil)
<add> status, b, err = request.SockRequest("GET", "/volumes/"+config.Name, nil, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusOK, check.Commentf(string(b)))
<ide> c.Assert(json.Unmarshal(b, &vol), checker.IsNil)
<ide><path>integration-cli/docker_cli_events_test.go
<ide> import (
<ide> eventtypes "github.com/docker/docker/api/types/events"
<ide> eventstestutils "github.com/docker/docker/daemon/events/testutils"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/testutil"
<ide> icmd "github.com/docker/docker/pkg/testutil/cmd"
<ide> "github.com/go-check/check"
<ide> func (s *DockerSuite) TestEventsResize(c *check.C) {
<ide> c.Assert(waitRun(cID), checker.IsNil)
<ide>
<ide> endpoint := "/containers/" + cID + "/resize?h=80&w=24"
<del> status, _, err := sockRequest("POST", endpoint, nil)
<add> status, _, err := request.SockRequest("POST", endpoint, nil, daemonHost())
<ide> c.Assert(status, checker.Equals, http.StatusOK)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide><path>integration-cli/docker_cli_exec_test.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> icmd "github.com/docker/docker/pkg/testutil/cmd"
<ide> "github.com/go-check/check"
<ide> )
<ide> func (s *DockerSuite) TestExecInspectID(c *check.C) {
<ide> }
<ide>
<ide> // But we should still be able to query the execID
<del> sc, body, err := sockRequest("GET", "/exec/"+execID+"/json", nil)
<add> sc, body, err := request.SockRequest("GET", "/exec/"+execID+"/json", nil, daemonHost())
<ide> c.Assert(sc, checker.Equals, http.StatusOK, check.Commentf("received status != 200 OK: %d\n%s", sc, body))
<ide>
<ide> // Now delete the container and then an 'inspect' on the exec should
<ide> // result in a 404 (not 'container not running')
<ide> out, ec := dockerCmd(c, "rm", "-f", id)
<ide> c.Assert(ec, checker.Equals, 0, check.Commentf("error removing container: %s", out))
<del> sc, body, err = sockRequest("GET", "/exec/"+execID+"/json", nil)
<add> sc, body, err = request.SockRequest("GET", "/exec/"+execID+"/json", nil, daemonHost())
<ide> c.Assert(sc, checker.Equals, http.StatusNotFound, check.Commentf("received status != 404: %d\n%s", sc, body))
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_kill_test.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestKillStoppedContainerAPIPre120(c *check.C) {
<ide> runSleepingContainer(c, "--name", "docker-kill-test-api", "-d")
<ide> dockerCmd(c, "stop", "docker-kill-test-api")
<ide>
<del> status, _, err := sockRequest("POST", fmt.Sprintf("/v1.19/containers/%s/kill", "docker-kill-test-api"), nil)
<add> status, _, err := request.SockRequest("POST", fmt.Sprintf("/v1.19/containers/%s/kill", "docker-kill-test-api"), nil, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusNoContent)
<ide> }
<ide><path>integration-cli/docker_cli_update_unix_test.go
<ide> package main
<ide> import (
<ide> "encoding/json"
<ide> "fmt"
<del> "github.com/kr/pty"
<ide> "os/exec"
<ide> "strings"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> "github.com/go-check/check"
<add> "github.com/kr/pty"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestUpdateRunningContainer(c *check.C) {
<ide> func (s *DockerSuite) TestUpdateStats(c *check.C) {
<ide> c.Assert(waitRun(name), checker.IsNil)
<ide>
<ide> getMemLimit := func(id string) uint64 {
<del> resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "")
<add> resp, body, err := request.SockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json")
<ide>
<ide><path>integration-cli/docker_deprecated_api_v124_test.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/pkg/testutil"
<ide> "github.com/go-check/check"
<ide> )
<ide> func (s *DockerSuite) TestDeprecatedContainerAPIStartHostConfig(c *check.C) {
<ide> config := map[string]interface{}{
<ide> "Binds": []string{"/aa:/bb"},
<ide> }
<del> status, body, err := sockRequest("POST", "/containers/"+name+"/start", config)
<add> status, body, err := request.SockRequest("POST", "/containers/"+name+"/start", config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusBadRequest)
<ide> c.Assert(string(body), checker.Contains, "was deprecated since v1.10")
<ide> func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumeBinds(c *check.C) {
<ide> "Volumes": map[string]struct{}{path: {}},
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config)
<add> status, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> bindPath := testutil.RandomTmpDirPath("test", daemonPlatform)
<ide> config = map[string]interface{}{
<ide> "Binds": []string{bindPath + ":" + path},
<ide> }
<del> status, _, err = sockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config)
<add> status, _, err = request.SockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide>
<ide> func (s *DockerSuite) TestDeprecatedContainerAPIStartDupVolumeBinds(c *check.C)
<ide> "Volumes": map[string]struct{}{"/tmp": {}},
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config)
<add> status, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> func (s *DockerSuite) TestDeprecatedContainerAPIStartDupVolumeBinds(c *check.C)
<ide> config = map[string]interface{}{
<ide> "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
<ide> }
<del> status, body, err := sockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config)
<add> status, body, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusInternalServerError)
<ide> c.Assert(string(body), checker.Contains, "Duplicate mount point", check.Commentf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err))
<ide> func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumesFrom(c *check.C) {
<ide> "Volumes": map[string]struct{}{volPath: {}},
<ide> }
<ide>
<del> status, _, err := sockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config)
<add> status, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusCreated)
<ide>
<ide> config = map[string]interface{}{
<ide> "VolumesFrom": []string{volName},
<ide> }
<del> status, _, err = sockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config)
<add> status, _, err = request.SockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide>
<ide> func (s *DockerSuite) TestDeprecatedPostContainerBindNormalVolume(c *check.C) {
<ide> dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox")
<ide>
<ide> bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
<del> status, _, err := sockRequest("POST", formatV123StartAPIURL("/containers/two/start"), bindSpec)
<add> status, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/two/start"), bindSpec, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(status, checker.Equals, http.StatusNoContent)
<ide>
<ide> func (s *DockerSuite) TestDeprecatedStartWithTooLowMemoryLimit(c *check.C) {
<ide> "Memory": 524287
<ide> }`
<ide>
<del> res, body, err := sockRequestRaw("POST", formatV123StartAPIURL("/containers/"+containerID+"/start"), strings.NewReader(config), "application/json")
<add> res, body, err := request.SockRequestRaw("POST", formatV123StartAPIURL("/containers/"+containerID+"/start"), strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> b, err2 := testutil.ReadBody(body)
<ide> c.Assert(err2, checker.IsNil)
<ide> func (s *DockerSuite) TestDeprecatedPostContainersStartWithoutLinksInHostConfig(
<ide> hc := inspectFieldJSON(c, name, "HostConfig")
<ide> config := `{"HostConfig":` + hc + `}`
<ide>
<del> res, b, err := sockRequestRaw("POST", formatV123StartAPIURL("/containers/"+name+"/start"), strings.NewReader(config), "application/json")
<add> res, b, err := request.SockRequestRaw("POST", formatV123StartAPIURL("/containers/"+name+"/start"), strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
<ide> b.Close()
<ide> func (s *DockerSuite) TestDeprecatedPostContainersStartWithLinksInHostConfig(c *
<ide> hc := inspectFieldJSON(c, name, "HostConfig")
<ide> config := `{"HostConfig":` + hc + `}`
<ide>
<del> res, b, err := sockRequestRaw("POST", formatV123StartAPIURL("/containers/"+name+"/start"), strings.NewReader(config), "application/json")
<add> res, b, err := request.SockRequestRaw("POST", formatV123StartAPIURL("/containers/"+name+"/start"), strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
<ide> b.Close()
<ide> func (s *DockerSuite) TestDeprecatedPostContainersStartWithLinksInHostConfigIdLi
<ide> hc := inspectFieldJSON(c, name, "HostConfig")
<ide> config := `{"HostConfig":` + hc + `}`
<ide>
<del> res, b, err := sockRequestRaw("POST", formatV123StartAPIURL("/containers/"+name+"/start"), strings.NewReader(config), "application/json")
<add> res, b, err := request.SockRequestRaw("POST", formatV123StartAPIURL("/containers/"+name+"/start"), strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
<ide> b.Close()
<ide> func (s *DockerSuite) TestDeprecatedStartWithNilDNS(c *check.C) {
<ide>
<ide> config := `{"HostConfig": {"Dns": null}}`
<ide>
<del> res, b, err := sockRequestRaw("POST", formatV123StartAPIURL("/containers/"+containerID+"/start"), strings.NewReader(config), "application/json")
<add> res, b, err := request.SockRequestRaw("POST", formatV123StartAPIURL("/containers/"+containerID+"/start"), strings.NewReader(config), "application/json", daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
<ide> b.Close()
<ide><path>integration-cli/docker_deprecated_api_v124_unix_test.go
<ide> import (
<ide> "fmt"
<ide>
<ide> "github.com/docker/docker/integration-cli/checker"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerNetworkSuite) TestDeprecatedDockerNetworkStartAPIWithHostconfig(c
<ide> "NetworkMode": netName,
<ide> },
<ide> }
<del> _, _, err := sockRequest("POST", formatV123StartAPIURL("/containers/"+conName+"/start"), config)
<add> _, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/"+conName+"/start"), config, daemonHost())
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(waitRun(conName), checker.IsNil)
<ide> networks := inspectField(c, conName, "NetworkSettings.Networks")
<ide><path>integration-cli/docker_utils_test.go
<ide> package main
<ide>
<ide> import (
<del> "bufio"
<ide> "bytes"
<ide> "encoding/json"
<ide> "errors"
<ide> import (
<ide> "net"
<ide> "net/http"
<ide> "net/http/httptest"
<del> "net/http/httputil"
<ide> "net/url"
<ide> "os"
<ide> "os/exec"
<ide> import (
<ide> "github.com/docker/docker/integration-cli/checker"
<ide> "github.com/docker/docker/integration-cli/daemon"
<ide> "github.com/docker/docker/integration-cli/registry"
<add> "github.com/docker/docker/integration-cli/request"
<ide> "github.com/docker/docker/opts"
<del> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/stringutils"
<del> "github.com/docker/docker/pkg/testutil"
<ide> icmd "github.com/docker/docker/pkg/testutil/cmd"
<ide> "github.com/go-check/check"
<ide> )
<ide> func daemonHost() string {
<ide> return daemonURLStr
<ide> }
<ide>
<del>// FIXME(vdemeester) should probably completely move to daemon struct/methods
<del>func sockConn(timeout time.Duration, daemonStr string) (net.Conn, error) {
<del> if daemonStr == "" {
<del> daemonStr = daemonHost()
<del> }
<del> return daemon.SockConn(timeout, daemonStr)
<del>}
<del>
<del>func sockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
<del> jsonData := bytes.NewBuffer(nil)
<del> if err := json.NewEncoder(jsonData).Encode(data); err != nil {
<del> return -1, nil, err
<del> }
<del>
<del> res, body, err := sockRequestRaw(method, endpoint, jsonData, "application/json")
<del> if err != nil {
<del> return -1, nil, err
<del> }
<del> b, err := testutil.ReadBody(body)
<del> return res.StatusCode, b, err
<del>}
<del>
<del>func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
<del> return sockRequestRawToDaemon(method, endpoint, data, ct, "")
<del>}
<del>
<del>func sockRequestRawToDaemon(method, endpoint string, data io.Reader, ct, daemon string) (*http.Response, io.ReadCloser, error) {
<del> req, client, err := newRequestClient(method, endpoint, data, ct, daemon)
<del> if err != nil {
<del> return nil, nil, err
<del> }
<del>
<del> resp, err := client.Do(req)
<del> if err != nil {
<del> client.Close()
<del> return nil, nil, err
<del> }
<del> body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
<del> defer resp.Body.Close()
<del> return client.Close()
<del> })
<del>
<del> return resp, body, nil
<del>}
<del>
<del>func sockRequestHijack(method, endpoint string, data io.Reader, ct string) (net.Conn, *bufio.Reader, error) {
<del> req, client, err := newRequestClient(method, endpoint, data, ct, "")
<del> if err != nil {
<del> return nil, nil, err
<del> }
<del>
<del> client.Do(req)
<del> conn, br := client.Hijack()
<del> return conn, br, nil
<del>}
<del>
<del>func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string) (*http.Request, *httputil.ClientConn, error) {
<del> c, err := sockConn(time.Duration(10*time.Second), daemon)
<del> if err != nil {
<del> return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
<del> }
<del>
<del> client := httputil.NewClientConn(c, nil)
<del>
<del> req, err := http.NewRequest(method, endpoint, data)
<del> if err != nil {
<del> client.Close()
<del> return nil, nil, fmt.Errorf("could not create new request: %v", err)
<del> }
<del>
<del> if ct != "" {
<del> req.Header.Set("Content-Type", ct)
<del> }
<del> return req, client, nil
<del>}
<del>
<ide> // FIXME(vdemeester) move this away are remove ignoreNoSuchContainer bool
<ide> func deleteContainer(ignoreNoSuchContainer bool, container ...string) error {
<ide> result := icmd.RunCommand(dockerBinary, append([]string{"rm", "-fv"}, container...)...)
<ide> func deleteAllNetworks(c *check.C) {
<ide> // nat is a pre-defined network on Windows and cannot be removed
<ide> continue
<ide> }
<del> status, b, err := sockRequest("DELETE", "/networks/"+n.Name, nil)
<add> status, b, err := request.SockRequest("DELETE", "/networks/"+n.Name, nil, daemonHost())
<ide> if err != nil {
<ide> errs = append(errs, err.Error())
<ide> continue
<ide> func deleteAllNetworks(c *check.C) {
<ide>
<ide> func getAllNetworks() ([]types.NetworkResource, error) {
<ide> var networks []types.NetworkResource
<del> _, b, err := sockRequest("GET", "/networks", nil)
<add> _, b, err := request.SockRequest("GET", "/networks", nil, daemonHost())
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func deleteAllPlugins(c *check.C) {
<ide> var errs []string
<ide> for _, p := range plugins {
<ide> pluginName := p.Name
<del> status, b, err := sockRequest("DELETE", "/plugins/"+pluginName+"?force=1", nil)
<add> status, b, err := request.SockRequest("DELETE", "/plugins/"+pluginName+"?force=1", nil, daemonHost())
<ide> if err != nil {
<ide> errs = append(errs, err.Error())
<ide> continue
<ide> func deleteAllPlugins(c *check.C) {
<ide>
<ide> func getAllPlugins() (types.PluginsListResponse, error) {
<ide> var plugins types.PluginsListResponse
<del> _, b, err := sockRequest("GET", "/plugins", nil)
<add> _, b, err := request.SockRequest("GET", "/plugins", nil, daemonHost())
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func deleteAllVolumes(c *check.C) {
<ide> c.Assert(err, checker.IsNil)
<ide> var errs []string
<ide> for _, v := range volumes {
<del> status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
<add> status, b, err := request.SockRequest("DELETE", "/volumes/"+v.Name, nil, daemonHost())
<ide> if err != nil {
<ide> errs = append(errs, err.Error())
<ide> continue
<ide> func deleteAllVolumes(c *check.C) {
<ide>
<ide> func getAllVolumes() ([]*types.Volume, error) {
<ide> var volumes volumetypes.VolumesListOKBody
<del> _, b, err := sockRequest("GET", "/volumes", nil)
<add> _, b, err := request.SockRequest("GET", "/volumes", nil, daemonHost())
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func daemonTime(c *check.C) time.Time {
<ide> return time.Now()
<ide> }
<ide>
<del> status, body, err := sockRequest("GET", "/info", nil)
<add> status, body, err := request.SockRequest("GET", "/info", nil, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide>
<ide> func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg
<ide>
<ide> func getInspectBody(c *check.C, version, id string) []byte {
<ide> endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
<del> status, body, err := sockRequest("GET", endpoint, nil)
<add> status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost())
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide> return body
<ide> func getGoroutineNumber() (int, error) {
<ide> i := struct {
<ide> NGoroutines int
<ide> }{}
<del> status, b, err := sockRequest("GET", "/info", nil)
<add> status, b, err := request.SockRequest("GET", "/info", nil, daemonHost())
<ide> if err != nil {
<ide> return 0, err
<ide> }
<add><path>integration-cli/request/npipe.go
<del><path>integration-cli/daemon/npipe.go
<ide> // +build !windows
<ide>
<del>package daemon
<add>package request
<ide>
<ide> import (
<ide> "net"
<add><path>integration-cli/request/npipe_windows.go
<del><path>integration-cli/daemon/npipe_windows.go
<del>package daemon
<add>package request
<ide>
<ide> import (
<ide> "net"
<ide><path>integration-cli/request/request.go
<add>package request
<add>
<add>import (
<add> "bufio"
<add> "bytes"
<add> "crypto/tls"
<add> "encoding/json"
<add> "fmt"
<add> "io"
<add> "io/ioutil"
<add> "net"
<add> "net/http"
<add> "net/http/httputil"
<add> "net/url"
<add> "os"
<add> "path/filepath"
<add> "time"
<add>
<add> dclient "github.com/docker/docker/client"
<add> "github.com/docker/docker/pkg/ioutils"
<add> "github.com/docker/docker/pkg/testutil"
<add> "github.com/docker/go-connections/sockets"
<add> "github.com/docker/go-connections/tlsconfig"
<add> "github.com/pkg/errors"
<add>)
<add>
<add>// Method creates a modifier that sets the specified string as the request method
<add>func Method(method string) func(*http.Request) error {
<add> return func(req *http.Request) error {
<add> req.Method = method
<add> return nil
<add> }
<add>}
<add>
<add>// JSON sets the Content-Type request header to json
<add>func JSON(req *http.Request) error {
<add> req.Header.Set("Content-Type", "application/json")
<add> return nil
<add>}
<add>
<add>// JSONBody creates a modifier that encodes the specified data to a JSON string and set it as request body. It also sets
<add>// the Content-Type header of the request.
<add>func JSONBody(data interface{}) func(*http.Request) error {
<add> return func(req *http.Request) error {
<add> jsonData := bytes.NewBuffer(nil)
<add> if err := json.NewEncoder(jsonData).Encode(data); err != nil {
<add> return err
<add> }
<add> req.Body = ioutil.NopCloser(jsonData)
<add> req.Header.Set("Content-Type", "application/json")
<add> return nil
<add> }
<add>}
<add>
<add>// Post creates and execute a POST request on the specified host and endpoint, with the specified request modifiers
<add>func Post(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
<add> return Do(host, endpoint, append(modifiers, Method(http.MethodPost))...)
<add>}
<add>
<add>// Delete creates and execute a DELETE request on the specified host and endpoint, with the specified request modifiers
<add>func Delete(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
<add> return Do(host, endpoint, append(modifiers, Method(http.MethodDelete))...)
<add>}
<add>
<add>// Get creates and execute a GET request on the specified host and endpoint, with the specified request modifiers
<add>func Get(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
<add> return Do(host, endpoint, modifiers...)
<add>}
<add>
<add>// Do creates and execute a request on the specified host and endpoint, with the specified request modifiers
<add>func Do(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
<add> req, err := New(host, endpoint, modifiers...)
<add> if err != nil {
<add> return nil, nil, err
<add> }
<add> client, err := NewClient(host)
<add> if err != nil {
<add> return nil, nil, err
<add> }
<add> resp, err := client.Do(req)
<add> var body io.ReadCloser
<add> if resp != nil {
<add> body = ioutils.NewReadCloserWrapper(resp.Body, func() error {
<add> defer resp.Body.Close()
<add> return nil
<add> })
<add> }
<add> return resp, body, err
<add>}
<add>
<add>// New creates a new http Request to the specified host and endpoint, with the specified request modifiers
<add>func New(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Request, error) {
<add> _, addr, _, err := dclient.ParseHost(host)
<add> if err != nil {
<add> return nil, err
<add> }
<add> if err != nil {
<add> return nil, errors.Wrapf(err, "could not parse url %q", host)
<add> }
<add> req, err := http.NewRequest("GET", endpoint, nil)
<add> if err != nil {
<add> return nil, fmt.Errorf("could not create new request: %v", err)
<add> }
<add>
<add> req.URL.Scheme = "http"
<add> req.URL.Host = addr
<add>
<add> for _, config := range modifiers {
<add> if err := config(req); err != nil {
<add> return nil, err
<add> }
<add> }
<add> return req, nil
<add>}
<add>
<add>// NewClient creates an http client for the specific host
<add>func NewClient(host string) (*http.Client, error) {
<add> // FIXME(vdemeester) 10*time.Second timeout of SockRequest… ?
<add> proto, addr, _, err := dclient.ParseHost(host)
<add> if err != nil {
<add> return nil, err
<add> }
<add> transport := new(http.Transport)
<add> if proto == "tcp" && os.Getenv("DOCKER_TLS_VERIFY") != "" {
<add> // Setup the socket TLS configuration.
<add> tlsConfig, err := getTLSConfig()
<add> if err != nil {
<add> return nil, err
<add> }
<add> transport = &http.Transport{TLSClientConfig: tlsConfig}
<add> }
<add> err = sockets.ConfigureTransport(transport, proto, addr)
<add> return &http.Client{
<add> Transport: transport,
<add> }, err
<add>}
<add>
<add>// FIXME(vdemeester) httputil.ClientConn is deprecated, use http.Client instead (closer to actual client)
<add>// Deprecated: Use New instead of NewRequestClient
<add>// Deprecated: use request.Do (or Get, Delete, Post) instead
<add>func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Request, *httputil.ClientConn, error) {
<add> c, err := SockConn(time.Duration(10*time.Second), daemon)
<add> if err != nil {
<add> return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
<add> }
<add>
<add> client := httputil.NewClientConn(c, nil)
<add>
<add> req, err := http.NewRequest(method, endpoint, data)
<add> if err != nil {
<add> client.Close()
<add> return nil, nil, fmt.Errorf("could not create new request: %v", err)
<add> }
<add>
<add> for _, opt := range modifiers {
<add> opt(req)
<add> }
<add>
<add> if ct != "" {
<add> req.Header.Set("Content-Type", ct)
<add> }
<add> return req, client, nil
<add>}
<add>
<add>// SockRequest create a request against the specified host (with method, endpoint and other request modifier) and
<add>// returns the status code, and the content as an byte slice
<add>// Deprecated: use request.Do instead
<add>func SockRequest(method, endpoint string, data interface{}, daemon string, modifiers ...func(*http.Request)) (int, []byte, error) {
<add> jsonData := bytes.NewBuffer(nil)
<add> if err := json.NewEncoder(jsonData).Encode(data); err != nil {
<add> return -1, nil, err
<add> }
<add>
<add> res, body, err := SockRequestRaw(method, endpoint, jsonData, "application/json", daemon, modifiers...)
<add> if err != nil {
<add> return -1, nil, err
<add> }
<add> b, err := testutil.ReadBody(body)
<add> return res.StatusCode, b, err
<add>}
<add>
<add>// SockRequestRaw create a request against the specified host (with method, endpoint and other request modifier) and
<add>// returns the http response, the output as a io.ReadCloser
<add>// Deprecated: use request.Do (or Get, Delete, Post) instead
<add>func SockRequestRaw(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Response, io.ReadCloser, error) {
<add> req, client, err := newRequestClient(method, endpoint, data, ct, daemon, modifiers...)
<add> if err != nil {
<add> return nil, nil, err
<add> }
<add>
<add> resp, err := client.Do(req)
<add> body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
<add> defer resp.Body.Close()
<add> return client.Close()
<add> })
<add> if err != nil {
<add> client.Close()
<add> }
<add>
<add> return resp, body, err
<add>}
<add>
<add>// SockRequestHijack creates a connection to specified host (with method, contenttype, …) and returns a hijacked connection
<add>// and the output as a `bufio.Reader`
<add>func SockRequestHijack(method, endpoint string, data io.Reader, ct string, daemon string, modifiers ...func(*http.Request)) (net.Conn, *bufio.Reader, error) {
<add> req, client, err := newRequestClient(method, endpoint, data, ct, daemon, modifiers...)
<add> if err != nil {
<add> return nil, nil, err
<add> }
<add>
<add> client.Do(req)
<add> conn, br := client.Hijack()
<add> return conn, br, nil
<add>}
<add>
<add>// SockConn opens a connection on the specified socket
<add>func SockConn(timeout time.Duration, daemon string) (net.Conn, error) {
<add> daemonURL, err := url.Parse(daemon)
<add> if err != nil {
<add> return nil, errors.Wrapf(err, "could not parse url %q", daemon)
<add> }
<add>
<add> var c net.Conn
<add> switch daemonURL.Scheme {
<add> case "npipe":
<add> return npipeDial(daemonURL.Path, timeout)
<add> case "unix":
<add> return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
<add> case "tcp":
<add> if os.Getenv("DOCKER_TLS_VERIFY") != "" {
<add> // Setup the socket TLS configuration.
<add> tlsConfig, err := getTLSConfig()
<add> if err != nil {
<add> return nil, err
<add> }
<add> dialer := &net.Dialer{Timeout: timeout}
<add> return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
<add> }
<add> return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
<add> default:
<add> return c, errors.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
<add> }
<add>}
<add>
<add>func getTLSConfig() (*tls.Config, error) {
<add> dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
<add>
<add> if dockerCertPath == "" {
<add> return nil, errors.New("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
<add> }
<add>
<add> option := &tlsconfig.Options{
<add> CAFile: filepath.Join(dockerCertPath, "ca.pem"),
<add> CertFile: filepath.Join(dockerCertPath, "cert.pem"),
<add> KeyFile: filepath.Join(dockerCertPath, "key.pem"),
<add> }
<add> tlsConfig, err := tlsconfig.Client(*option)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> return tlsConfig, nil
<add>} | 32 |
Python | Python | fix default getattr | 9e5b549b4d47678bdc74bc8f650e82cf25bfc245 | <ide><path>tests/test_modeling_common.py
<ide> def test_determinism(self):
<ide>
<ide> def test_attention_outputs(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<del> seq_len = self.model_tester.seq_length
<add> seq_len = getattr(self.model_tester, "seq_length", None)
<ide> decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len)
<ide> encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
<ide> decoder_key_length = getattr(self.model_tester, "key_length", decoder_seq_length) | 1 |
Javascript | Javascript | make sourcemap updates in two .replace() passes | 37f1da6b91a86ef3f54f4cf16dd87f5afd33c835 | <ide><path>build/release/cdn.js
<ide> function makeReleaseCopies( Release ) {
<ide>
<ide> // Map files need to reference the new uncompressed name;
<ide> // assume that all files reside in the same directory.
<del> // "file":"jquery.min.js","sources":["jquery.js"]
<add> // "file":"jquery.min.js" ... "sources":["jquery.js"]
<ide> text = fs.readFileSync( builtFile, "utf8" )
<del> .replace( /"file":"([^"]+)","sources":\["([^"]+)"\]/,
<del> "\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js" ) +
<del> "\",\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" );
<add> .replace( /"file":"([^"]+)"/,
<add> "\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js\"" ) )
<add> .replace( /"sources":\["([^"]+)"\]/,
<add> "\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" );
<ide> fs.writeFileSync( releaseFile, text );
<ide> } else if ( builtFile !== releaseFile ) {
<ide> shell.cp( "-f", builtFile, releaseFile ); | 1 |
Python | Python | choose framework for onnx export | 37a9fc49f210470804b2d59247a896aa3340f6b7 | <ide><path>src/transformers/onnx/__main__.py
<ide> def main():
<ide> parser.add_argument(
<ide> "--atol", type=float, default=None, help="Absolute difference tolerence when validating the model."
<ide> )
<add> parser.add_argument(
<add> "--framework", type=str, choices=["pt", "tf"], default="pt", help="The framework to use for the ONNX export."
<add> )
<ide> parser.add_argument("output", type=Path, help="Path indicating where to store generated ONNX model.")
<ide>
<ide> # Retrieve CLI arguments
<ide> def main():
<ide> raise ValueError(f"Unsupported model type: {config.model_type}")
<ide>
<ide> # Allocate the model
<del> model = FeaturesManager.get_model_from_feature(args.feature, args.model)
<add> model = FeaturesManager.get_model_from_feature(args.feature, args.model, framework=args.framework)
<ide> model_kind, model_onnx_config = FeaturesManager.check_supported_model_or_raise(model, feature=args.feature)
<ide> onnx_config = model_onnx_config(model.config)
<ide>
<ide><path>src/transformers/onnx/features.py
<ide> AutoModelForSequenceClassification,
<ide> AutoModelForTokenClassification,
<ide> )
<del>elif is_tf_available():
<add>if is_tf_available():
<ide> from transformers.models.auto import (
<ide> TFAutoModel,
<ide> TFAutoModelForCausalLM,
<ide> TFAutoModelForSequenceClassification,
<ide> TFAutoModelForTokenClassification,
<ide> )
<del>else:
<add>if not is_torch_available() and not is_tf_available():
<ide> logger.warning(
<ide> "The ONNX export features are only supported for PyTorch or TensorFlow. You will not be able to export models without one of these libraries installed."
<ide> )
<ide> def supported_features_mapping(
<ide>
<ide>
<ide> class FeaturesManager:
<add> _TASKS_TO_AUTOMODELS = {}
<add> _TASKS_TO_TF_AUTOMODELS = {}
<ide> if is_torch_available():
<ide> _TASKS_TO_AUTOMODELS = {
<ide> "default": AutoModel,
<ide> class FeaturesManager:
<ide> "question-answering": AutoModelForQuestionAnswering,
<ide> "image-classification": AutoModelForImageClassification,
<ide> }
<del> elif is_tf_available():
<del> _TASKS_TO_AUTOMODELS = {
<add> if is_tf_available():
<add> _TASKS_TO_TF_AUTOMODELS = {
<ide> "default": TFAutoModel,
<ide> "masked-lm": TFAutoModelForMaskedLM,
<ide> "causal-lm": TFAutoModelForCausalLM,
<ide> class FeaturesManager:
<ide> "multiple-choice": TFAutoModelForMultipleChoice,
<ide> "question-answering": TFAutoModelForQuestionAnswering,
<ide> }
<del> else:
<del> _TASKS_TO_AUTOMODELS = {}
<ide>
<ide> # Set of model topologies we support associated to the features supported by each topology and the factory
<ide> _SUPPORTED_MODEL_TYPE = {
<ide> def get_supported_features_for_model_type(
<ide> model_type: str, model_name: Optional[str] = None
<ide> ) -> Dict[str, Callable[[PretrainedConfig], OnnxConfig]]:
<ide> """
<del> Try to retrieve the feature -> OnnxConfig constructor map from the model type.
<add> Tries to retrieve the feature -> OnnxConfig constructor map from the model type.
<ide>
<ide> Args:
<del> model_type: The model type to retrieve the supported features for.
<del> model_name: The name attribute of the model object, only used for the exception message.
<add> model_type (`str`):
<add> The model type to retrieve the supported features for.
<add> model_name (`str`, *optional*):
<add> The name attribute of the model object, only used for the exception message.
<ide>
<ide> Returns:
<ide> The dictionary mapping each feature to a corresponding OnnxConfig constructor.
<ide> def feature_to_task(feature: str) -> str:
<ide> return feature.replace("-with-past", "")
<ide>
<ide> @staticmethod
<del> def get_model_class_for_feature(feature: str) -> Type:
<add> def _validate_framework_choice(framework: str):
<add> """
<add> Validates if the framework requested for the export is both correct and available, otherwise throws an
<add> exception.
<add> """
<add> if framework not in ["pt", "tf"]:
<add> raise ValueError(
<add> f"Only two frameworks are supported for ONNX export: pt or tf, but {framework} was provided."
<add> )
<add> elif framework == "pt" and not is_torch_available():
<add> raise RuntimeError("Cannot export model to ONNX using PyTorch because no PyTorch package was found.")
<add> elif framework == "tf" and not is_tf_available():
<add> raise RuntimeError("Cannot export model to ONNX using TensorFlow because no TensorFlow package was found.")
<add>
<add> @staticmethod
<add> def get_model_class_for_feature(feature: str, framework: str = "pt") -> Type:
<ide> """
<del> Attempt to retrieve an AutoModel class from a feature name.
<add> Attempts to retrieve an AutoModel class from a feature name.
<ide>
<ide> Args:
<del> feature: The feature required.
<add> feature (`str`):
<add> The feature required.
<add> framework (`str`, *optional*, defaults to `"pt"`):
<add> The framework to use for the export.
<ide>
<ide> Returns:
<ide> The AutoModel class corresponding to the feature.
<ide> """
<ide> task = FeaturesManager.feature_to_task(feature)
<del> if task not in FeaturesManager._TASKS_TO_AUTOMODELS:
<add> FeaturesManager._validate_framework_choice(framework)
<add> if framework == "pt":
<add> task_to_automodel = FeaturesManager._TASKS_TO_AUTOMODELS
<add> else:
<add> task_to_automodel = FeaturesManager._TASKS_TO_TF_AUTOMODELS
<add> if task not in task_to_automodel:
<ide> raise KeyError(
<ide> f"Unknown task: {feature}. "
<ide> f"Possible values are {list(FeaturesManager._TASKS_TO_AUTOMODELS.values())}"
<ide> )
<del> return FeaturesManager._TASKS_TO_AUTOMODELS[task]
<add> return task_to_automodel[task]
<ide>
<del> def get_model_from_feature(feature: str, model: str) -> Union[PreTrainedModel, TFPreTrainedModel]:
<add> def get_model_from_feature(
<add> feature: str, model: str, framework: str = "pt"
<add> ) -> Union[PreTrainedModel, TFPreTrainedModel]:
<ide> """
<del> Attempt to retrieve a model from a model's name and the feature to be enabled.
<add> Attempts to retrieve a model from a model's name and the feature to be enabled.
<ide>
<ide> Args:
<del> feature: The feature required.
<del> model: The name of the model to export.
<add> feature (`str`):
<add> The feature required.
<add> model (`str`):
<add> The name of the model to export.
<add> framework (`str`, *optional*, defaults to `"pt"`):
<add> The framework to use for the export.
<ide>
<ide> Returns:
<ide> The instance of the model.
<ide>
<ide> """
<del> # If PyTorch and TensorFlow are installed in the same environment, we
<del> # load an AutoModel class by default
<del> model_class = FeaturesManager.get_model_class_for_feature(feature)
<add> model_class = FeaturesManager.get_model_class_for_feature(feature, framework)
<ide> try:
<ide> model = model_class.from_pretrained(model)
<del> # Load TensorFlow weights in an AutoModel instance if PyTorch and
<del> # TensorFlow are installed in the same environment
<ide> except OSError:
<del> model = model_class.from_pretrained(model, from_tf=True)
<add> if framework == "pt":
<add> model = model_class.from_pretrained(model, from_tf=True)
<add> else:
<add> model = model_class.from_pretrained(model, from_pt=True)
<ide> return model
<ide>
<ide> @staticmethod | 2 |
Python | Python | move version check to a function | f175abc3457b6c8aec01a8b5c53adc8de5a4111d | <ide><path>official/utils/logs/mlperf_helper.py
<ide> def unparse_line(parsed_line): # type: (ParsedLine) -> str
<ide> def get_mlperf_log():
<ide> """Shielded import of mlperf_log module."""
<ide> try:
<del> import pkg_resources
<ide> import mlperf_compliance
<ide>
<del> version = pkg_resources.get_distribution("mlperf_compliance")
<del> version = tuple(int(i) for i in version.version.split("."))
<del> if version < _MIN_VERSION:
<del> tf.logging.warning(
<del> "mlperf_compliance is version {}, must be at least version {}".format(
<del> ".".join([str(i) for i in version]),
<del> ".".join([str(i) for i in _MIN_VERSION])))
<del> raise ImportError
<del>
<del> mlperf_log = mlperf_compliance.mlperf_log
<add> def test_mlperf_log_pip_version():
<add> """Check that mlperf_compliance is up to date."""
<add> import pkg_resources
<add> version = pkg_resources.get_distribution("mlperf_compliance")
<add> version = tuple(int(i) for i in version.version.split("."))
<add> if version < _MIN_VERSION:
<add> tf.logging.warning(
<add> "mlperf_compliance is version {}, must be >= {}".format(
<add> ".".join([str(i) for i in version]),
<add> ".".join([str(i) for i in _MIN_VERSION])))
<add> raise ImportError
<add> return mlperf_compliance.mlperf_log
<add>
<add> mlperf_log = test_mlperf_log_pip_version()
<ide>
<ide> except ImportError:
<ide> mlperf_log = None | 1 |
Text | Text | add tips for succesful changes | 59e1d579e09b56cd909655fdefb405f0eb02b086 | <ide><path>CONTRIBUTING.md
<ide> committing your changes. Most editors have plug-ins that do this automatically.
<ide> Pull request descriptions should be as clear as possible and include a reference
<ide> to all the issues that they address.
<ide>
<add>### Successful Changes
<add>
<add>Before contributing large or high impact changes, make the effort to coordinate
<add>with the maintainers of the project before submitting a pull request. This
<add>prevents you from doing extra work that may or may not be merged.
<add>
<add>Large PRs that are just submitted without any prior communication are unlikely
<add>to be successful.
<add>
<add>While pull requests are the methodology for submitting changes to code, changes
<add>are much more likely to be accepted if they are accompanied by additional
<add>engineering work. While we don't define this explicitly, most of these goals
<add>are accomplished through communication of the design goals and subsequent
<add>solutions. Often times, it helps to first state the problem before presenting
<add>solutions.
<add>
<add>Typically, the best methods of accomplishing this are to submit an issue,
<add>stating the problem. This issue can include a problem statement and a
<add>checklist with requirements. If solutions are proposed, alternatives should be
<add>listed and eliminated. Even if the criteria for elimination of a solution is
<add>frivolous, say so.
<add>
<add>Larger changes typically work best with design documents. These are focused on
<add>providing context to the design at the time the feature was conceived and can
<add>inform future documentation contributions.
<add>
<add>### Commit Messages
<add>
<ide> Commit messages must start with a capitalized and short summary (max. 50 chars)
<ide> written in the imperative, followed by an optional, more detailed explanatory
<ide> text which is separated from the summary by an empty line.
<ide>
<add>Commit messages should follow best practices, including explaining the context
<add>of the problem and how it was solved, including in caveats or follow up changes
<add>required. They should tell the story of the change and provide readers
<add>understanding of what led to it.
<add>
<add>If you're lost about what this even means, please see [How to Write a Git
<add>Commit Message](http://chris.beams.io/posts/git-commit/) for a start.
<add>
<add>In practice, the best approach to maintaining a nice commit message is to
<add>leverage a `git add -p` and `git commit --amend` to formulate a solid
<add>changeset. This allows one to piece together a change, as information becomes
<add>available.
<add>
<add>If you squash a series of commits, don't just submit that. Re-write the commit
<add>message, as if the series of commits was a single stroke of brilliance.
<add>
<add>That said, there is no requirement to have a single commit for a PR, as long as
<add>each commit tells the story. For example, if there is a feature that requires a
<add>package, it might make sense to have the package in a separate commit then have
<add>a subsequent commit that uses it.
<add>
<add>Remember, you're telling part of the story with the commit message. Don't make
<add>your chapter weird.
<add>
<add>### Review
<add>
<ide> Code review comments may be added to your pull request. Discuss, then make the
<ide> suggested modifications and push additional commits to your feature branch. Post
<ide> a comment after pushing. New commits show up in the pull request automatically, | 1 |
Javascript | Javascript | unify some of the getter/no-getter logic | 58580a70282b78d24b78c7fc39d86cd90565c41e | <ide><path>packages/ember-metal/lib/platform.js
<ide> if (!platform.create) {
<ide> platform.create.isSimulated = true;
<ide> }
<ide>
<add>Object.defineProperty = null;
<ide> /** @private */
<ide> var defineProperty = Object.defineProperty;
<ide> var canRedefineProperties, canDefinePropertyOnDOM;
<ide> if (!platform.defineProperty) {
<ide> platform.hasPropertyAccessors = false;
<ide>
<ide> platform.defineProperty = function(obj, keyName, desc) {
<del> Ember.assert("property descriptor cannot have `get` or `set` on this platform", !desc.get && !desc.set);
<del> obj[keyName] = desc.value;
<add> if (!desc.get) { obj[keyName] = desc.value; }
<ide> };
<ide>
<ide> platform.defineProperty.isSimulated = true;
<ide><path>packages/ember-metal/lib/properties.js
<ide> var GUID_KEY = Ember.GUID_KEY;
<ide> var META_KEY = Ember.META_KEY;
<ide> var meta = Ember.meta;
<ide> var o_create = Ember.platform.create;
<del>var o_defineProperty = Ember.platform.defineProperty;
<add>var objectDefineProperty = Ember.platform.defineProperty;
<ide> var SIMPLE_PROPERTY, WATCHED_PROPERTY;
<ide>
<ide> // ..........................................................
<ide> var SIMPLE_PROPERTY, WATCHED_PROPERTY;
<ide> var Descriptor = Ember.Descriptor = function() {};
<ide>
<ide> var setup = Descriptor.setup = function(obj, keyName, value) {
<del> o_defineProperty(obj, keyName, {
<add> objectDefineProperty(obj, keyName, {
<ide> writable: true,
<ide> configurable: true,
<ide> enumerable: true,
<ide> DescriptorPrototype.val = function(obj, keyName) {
<ide> // SIMPLE AND WATCHED PROPERTIES
<ide> //
<ide>
<del>// if accessors are disabled for the app then this will act as a guard when
<del>// testing on browsers that do support accessors. It will throw an exception
<del>// if you do foo.bar instead of Ember.get(foo, 'bar')
<del>
<ide> // The exception to this is that any objects managed by Ember but not a descendant
<ide> // of Ember.Object will not throw an exception, instead failing silently. This
<ide> // prevent errors with other libraries that may attempt to access special
<ide> // properties on standard objects like Array. Usually this happens when copying
<ide> // an object by looping over all properties.
<del>
<del>if (!USE_ACCESSORS) {
<del> Ember.Descriptor.MUST_USE_GETTER = function() {
<del> if (this instanceof Ember.Object) {
<del> Ember.assert('Must use Ember.get() to access this property', false);
<del> }
<del> };
<del>
<del> Ember.Descriptor.MUST_USE_SETTER = function() {
<del> if (this instanceof Ember.Object) {
<del> if (this.isDestroyed) {
<del> Ember.assert('You cannot set observed properties on destroyed objects', false);
<del> } else {
<del> Ember.assert('Must use Ember.set() to access this property', false);
<del> }
<add>//
<add>// QUESTION: What is this scenario exactly?
<add>var mandatorySetter = Ember.Descriptor.MUST_USE_SETTER = function() {
<add> if (this instanceof Ember.Object) {
<add> if (this.isDestroyed) {
<add> Ember.assert('You cannot set observed properties on destroyed objects', false);
<add> } else {
<add> Ember.assert('Must use Ember.set() to access this property', false);
<ide> }
<del> };
<del>}
<add> }
<add>};
<ide>
<ide> var WATCHED_DESC = {
<ide> configurable: true,
<ide> enumerable: true,
<del> set: Ember.Descriptor.MUST_USE_SETTER
<add> set: mandatorySetter
<ide> };
<ide>
<ide> /** @private */
<ide> function rawGet(obj, keyName, values) {
<ide> var ret = values[keyName];
<del> if (ret !== undefined) { return ret; }
<del> if (obj.unknownProperty) { return obj.unknownProperty(keyName); }
<add> if (ret === undefined && obj.unknownProperty) {
<add> ret = obj.unknownProperty(keyName);
<add> }
<add> return ret;
<ide> }
<ide>
<ide> function get(obj, keyName) {
<ide> function watchedGet(obj, keyName) {
<ide> return rawGet(obj, keyName, meta(obj, false).values || emptyObject);
<ide> }
<ide>
<add>var hasGetters = Ember.platform.hasPropertyAccessors, rawSet;
<add>
<add>rawSet = function(obj, keyName, value, values) {
<add> values[keyName] = value;
<add>};
<add>
<add>// if there are no getters, keep the raw property up to date
<add>if (!Ember.platform.hasPropertyAccessors) {
<add> rawSet = function(obj, keyName, value, values) {
<add> obj[keyName] = value;
<add> values[keyName] = value;
<add> };
<add>}
<add>
<ide> /** @private */
<ide> function watchedSet(obj, keyName, value) {
<del> var m = meta(obj), changed = value !== m.values[keyName];
<add> var m = meta(obj),
<add> values = m.values,
<add> changed = value !== values[keyName];
<ide>
<ide> if (changed) {
<ide> Ember.propertyWillChange(obj, keyName);
<del> m.values[keyName] = value;
<add> rawSet(obj, keyName, value, m.values);
<ide> Ember.propertyDidChange(obj, keyName);
<ide> }
<ide>
<ide> return value;
<ide> }
<ide>
<del>var WATCHED_GETTERS = {};
<ide> /** @private */
<del>function mkWatchedGetter(keyName) {
<del> var ret = WATCHED_GETTERS[keyName];
<del> if (!ret) {
<del> ret = WATCHED_GETTERS[keyName] = function() {
<del> return watchedGet(this, keyName);
<del> };
<del> }
<del> return ret;
<add>function makeWatchedGetter(keyName) {
<add> return function() {
<add> return watchedGet(this, keyName);
<add> };
<ide> }
<ide>
<del>var WATCHED_SETTERS = {};
<ide> /** @private */
<del>function mkWatchedSetter(keyName) {
<del> var ret = WATCHED_SETTERS[keyName];
<del> if (!ret) {
<del> ret = WATCHED_SETTERS[keyName] = function(value) {
<del> return watchedSet(this, keyName, value);
<del> };
<del> }
<del> return ret;
<add>function makeWatchedSetter(keyName) {
<add> return function(value) {
<add> return watchedSet(this, keyName, value);
<add> };
<ide> }
<ide>
<ide> /**
<ide> function mkWatchedSetter(keyName) {
<ide> Private version of simple property that invokes property change callbacks.
<ide> */
<ide> WATCHED_PROPERTY = new Ember.Descriptor();
<add>WATCHED_PROPERTY.get = watchedGet ;
<add>WATCHED_PROPERTY.set = watchedSet ;
<ide>
<del>if (Ember.platform.hasPropertyAccessors) {
<del> WATCHED_PROPERTY.get = watchedGet ;
<del> WATCHED_PROPERTY.set = watchedSet ;
<del>
<del> if (USE_ACCESSORS) {
<del> WATCHED_PROPERTY.setup = function(obj, keyName, value) {
<del> WATCHED_DESC.get = mkWatchedGetter(keyName);
<del> WATCHED_DESC.set = mkWatchedSetter(keyName);
<del> o_defineProperty(obj, keyName, WATCHED_DESC);
<del> WATCHED_DESC.get = WATCHED_DESC.set = null;
<del> if (value !== undefined) meta(obj).values[keyName] = value;
<del> };
<del>
<del> } else {
<del> WATCHED_PROPERTY.setup = function(obj, keyName, value) {
<del> WATCHED_DESC.get = mkWatchedGetter(keyName);
<del> o_defineProperty(obj, keyName, WATCHED_DESC);
<del> WATCHED_DESC.get = null;
<del> if (value !== undefined) meta(obj).values[keyName] = value;
<del> };
<del> }
<del>
<del> WATCHED_PROPERTY.teardown = function(obj, keyName) {
<del> var ret = meta(obj).values[keyName];
<del> delete meta(obj).values[keyName];
<del> return ret;
<del> };
<del>
<del>// NOTE: if platform does not have property accessors then we just have to
<del>// set values and hope for the best. You just won't get any warnings...
<del>} else {
<del>
<del> WATCHED_PROPERTY.set = function(obj, keyName, value) {
<del> var m = meta(obj), watching;
<add>WATCHED_PROPERTY.setup = function(obj, keyName, value) {
<add> objectDefineProperty(obj, keyName, {
<add> configurable: true,
<add> enumerable: true,
<add> set: mandatorySetter,
<add> get: makeWatchedGetter(keyName)
<add> });
<ide>
<del> watching = m.watching[keyName]>0 && value!==obj[keyName];
<del> if (watching) Ember.propertyWillChange(obj, keyName);
<del> obj[keyName] = value;
<del> if (watching) Ember.propertyDidChange(obj, keyName);
<del> return value;
<del> };
<add> meta(obj).values[keyName] = value;
<add>};
<ide>
<del>}
<add>WATCHED_PROPERTY.teardown = function(obj, keyName) {
<add> var ret = meta(obj).values[keyName];
<add> delete meta(obj).values[keyName];
<add> return ret;
<add>};
<ide>
<ide> /**
<ide> The default descriptor for simple properties. Pass as the third argument
<ide> SIMPLE_PROPERTY = Ember.SIMPLE_PROPERTY;
<ide> SIMPLE_PROPERTY.unwatched = WATCHED_PROPERTY.unwatched = SIMPLE_PROPERTY;
<ide> SIMPLE_PROPERTY.watched = WATCHED_PROPERTY.watched = WATCHED_PROPERTY;
<ide>
<del>
<ide> // ..........................................................
<ide> // DEFINING PROPERTIES API
<ide> //
<ide> function hasDesc(descs, keyName) {
<ide> }).property('firstName', 'lastName').cacheable());
<ide> */
<ide> Ember.defineProperty = function(obj, keyName, desc, val) {
<del> var m = meta(obj, false), descs = m.descs, watching = m.watching[keyName]>0, override = true;
<add> var m = meta(obj, false),
<add> descs = m.descs,
<add> watching = m.watching[keyName]>0,
<add> override = true;
<ide>
<ide> if (val === undefined) {
<add> // if a value wasn't provided, the value is the old value
<add> // (which can be obtained by calling teardown on a property
<add> // with a descriptor).
<ide> override = false;
<ide> val = hasDesc(descs, keyName) ? descs[keyName].teardown(obj, keyName) : obj[keyName];
<ide> } else if (hasDesc(descs, keyName)) {
<add> // otherwise, tear down the descriptor, but use the provided
<add> // value as the new value instead of the descriptor's current
<add> // value.
<ide> descs[keyName].teardown(obj, keyName);
<ide> }
<ide>
<del> if (!desc) desc = SIMPLE_PROPERTY;
<add> if (!desc) {
<add> desc = SIMPLE_PROPERTY;
<add> }
<ide>
<ide> if (desc instanceof Ember.Descriptor) {
<ide> m = meta(obj, true);
<ide> Ember.defineProperty = function(obj, keyName, desc, val) {
<ide> // compatibility with ES5
<ide> } else {
<ide> if (descs[keyName]) meta(obj).descs[keyName] = null;
<del> o_defineProperty(obj, keyName, desc);
<add> objectDefineProperty(obj, keyName, desc);
<ide> }
<ide>
<ide> // if key is being watched, override chains that
<ide><path>packages/ember-metal/tests/performance_test.js
<ide> test("computed properties are not executed if they are the last segment of an ob
<ide>
<ide> Ember.addObserver(foo, 'bar.baz.bam', function() {});
<ide>
<del> Ember.propertyDidChange(foo.bar.baz, 'bam');
<add> Ember.propertyDidChange(Ember.getPath(foo, 'bar.baz'), 'bam');
<ide>
<ide> equal(count, 0, "should not have recomputed property");
<ide> });
<ide><path>packages/ember-metal/tests/platform/defineProperty_test.js
<ide> test('defining a non enumerable property', function() {
<ide> }
<ide> });
<ide>
<del>test('defining a getter/setter', function() {
<del> var obj = {}, getCnt = 0, setCnt = 0, v = 'FOO';
<add>// If accessors don't exist, behavior that relies on getters
<add>// and setters don't do anything
<add>if (Ember.platform.hasPropertyAccessors) {
<add> test('defining a getter/setter', function() {
<add> var obj = {}, getCnt = 0, setCnt = 0, v = 'FOO';
<ide>
<del> var desc = {
<del> enumerable: true,
<del> get: function() { getCnt++; return v; },
<del> set: function(val) { setCnt++; v = val; }
<del> };
<add> var desc = {
<add> enumerable: true,
<add> get: function() { getCnt++; return v; },
<add> set: function(val) { setCnt++; v = val; }
<add> };
<ide>
<del> if (Ember.platform.hasPropertyAccessors) {
<del> Ember.platform.defineProperty(obj, 'foo', desc);
<del> equal(obj.foo, 'FOO', 'should return getter');
<del> equal(getCnt, 1, 'should have invoked getter');
<add> if (Ember.platform.hasPropertyAccessors) {
<add> Ember.platform.defineProperty(obj, 'foo', desc);
<add> equal(obj.foo, 'FOO', 'should return getter');
<add> equal(getCnt, 1, 'should have invoked getter');
<ide>
<del> obj.foo = 'BAR';
<del> equal(obj.foo, 'BAR', 'setter should have worked');
<del> equal(setCnt, 1, 'should have invoked setter');
<add> obj.foo = 'BAR';
<add> equal(obj.foo, 'BAR', 'setter should have worked');
<add> equal(setCnt, 1, 'should have invoked setter');
<ide>
<del> } else {
<del> raises(function() {
<del> Ember.platform.defineProperty(obj, 'foo', desc);
<del> }, Error, 'should throw exception if getters/setters not supported');
<del> }
<add> }
<ide>
<del>});
<add> });
<ide>
<del>test('defining getter/setter along with writable', function() {
<del> var obj ={};
<del> raises(function() {
<del> Ember.platform.defineProperty(obj, 'foo', {
<del> enumerable: true,
<del> get: function() {},
<del> set: function() {},
<del> writable: true
<del> });
<del> }, Error, 'defining writable and get/set should throw exception');
<del>});
<add> test('defining getter/setter along with writable', function() {
<add> var obj ={};
<add> raises(function() {
<add> Ember.platform.defineProperty(obj, 'foo', {
<add> enumerable: true,
<add> get: function() {},
<add> set: function() {},
<add> writable: true
<add> });
<add> }, Error, 'defining writable and get/set should throw exception');
<add> });
<ide>
<del>test('defining getter/setter along with value', function() {
<del> var obj ={};
<del> raises(function() {
<del> Ember.platform.defineProperty(obj, 'foo', {
<del> enumerable: true,
<del> get: function() {},
<del> set: function() {},
<del> value: 'FOO'
<del> });
<del> }, Error, 'defining value and get/set should throw exception');
<del>});
<add> test('defining getter/setter along with value', function() {
<add> var obj ={};
<add> raises(function() {
<add> Ember.platform.defineProperty(obj, 'foo', {
<add> enumerable: true,
<add> get: function() {},
<add> set: function() {},
<add> value: 'FOO'
<add> });
<add> }, Error, 'defining value and get/set should throw exception');
<add> });
<add>} | 4 |
Javascript | Javascript | remove console log from planegeometry | dd74de1edfd027eb413cf01b8b5422567489a688 | <ide><path>src/extras/geometries/PlaneGeometry.js
<ide>
<ide> THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
<ide>
<del> console.log( 'THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.' );
<del>
<ide> THREE.Geometry.call( this );
<ide>
<ide> this.type = 'PlaneGeometry'; | 1 |
Ruby | Ruby | use `-s` flag in `uname` call | b0668f4e312c4890972768915233a56fc395e691 | <ide><path>Library/Homebrew/os.rb
<ide> def self.kernel_version
<ide> # @api public
<ide> sig { returns(String) }
<ide> def self.uname
<del> @uname ||= Utils.safe_popen_read("uname").chomp
<add> @uname ||= Utils.safe_popen_read("uname", "-s").chomp
<ide> end
<ide>
<ide> ::OS_VERSION = ENV["HOMEBREW_OS_VERSION"] | 1 |
Java | Java | introduce failing @disabled test for gh-23856 | f8b875d2d8a6ad4462a8b28cbeae4e40e400c087 | <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
<ide> import javax.annotation.ParametersAreNonnullByDefault;
<ide>
<ide> import org.junit.jupiter.api.BeforeEach;
<add>import org.junit.jupiter.api.Disabled;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.core.Ordered;
<ide> void findAnnotationWithRepeatablesElements() {
<ide> TestRepeatableContainer.class)).isNotNull();
<ide> }
<ide>
<add> @Test // gh-23856
<add> void findAnnotationFindsRepeatableContainerOnComposedAnnotationMetaAnnotatedWithRepeatableAnnotations() {
<add> MyRepeatableContainer annotation = AnnotationUtils.findAnnotation(MyRepeatableMeta1And2.class, MyRepeatableContainer.class);
<add>
<add> assertThat(annotation).isNotNull();
<add> assertThat(annotation.value()).extracting(MyRepeatable::value).containsExactly("meta1", "meta2");
<add> }
<add>
<add> @Test // gh-23856
<add> @Disabled("disabled until gh-23856 is resolved")
<add> void findAnnotationFindsRepeatableContainerOnComposedAnnotationMetaAnnotatedWithRepeatableAnnotationsOnMethod() throws NoSuchMethodException {
<add> Method method = getClass().getDeclaredMethod("methodWithComposedAnnotationMetaAnnotatedWithRepeatableAnnotations");
<add> MyRepeatableContainer annotation = AnnotationUtils.findAnnotation(method, MyRepeatableContainer.class);
<add>
<add> assertThat(annotation).isNotNull();
<add> assertThat(annotation.value()).extracting(MyRepeatable::value).containsExactly("meta1", "meta2");
<add> }
<add>
<add>
<ide> @SafeVarargs
<ide> static <T> T[] asArray(T... arr) {
<ide> return arr;
<ide> public void foo(String t) {
<ide> @interface MyRepeatableMeta2 {
<ide> }
<ide>
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Inherited
<add> @MyRepeatable("meta1")
<add> @MyRepeatable("meta2")
<add> @interface MyRepeatableMeta1And2 {
<add> }
<add>
<add> @MyRepeatableMeta1And2
<add> void methodWithComposedAnnotationMetaAnnotatedWithRepeatableAnnotations() {
<add> }
<add>
<ide> interface InterfaceWithRepeated {
<ide>
<ide> @MyRepeatable("A") | 1 |
Go | Go | copy parents cpus and mems for cpuset | 3de15bda7e1d3ab193094e6e07a5b2e42ea828bd | <ide><path>pkg/cgroups/fs/apply_raw.go
<ide> func GetStats(c *cgroups.Cgroup, subsystem string, pid int) (map[string]float64,
<ide> return sys.Stats(d)
<ide> }
<ide>
<del>func (raw *data) path(subsystem string) (string, error) {
<add>func (raw *data) parent(subsystem string) (string, error) {
<ide> initPath, err := cgroups.GetInitCgroupDir(subsystem)
<ide> if err != nil {
<ide> return "", err
<ide> }
<del> return filepath.Join(raw.root, subsystem, initPath, raw.cgroup), nil
<add> return filepath.Join(raw.root, subsystem, initPath), nil
<add>}
<add>
<add>func (raw *data) path(subsystem string) (string, error) {
<add> parent, err := raw.parent(subsystem)
<add> if err != nil {
<add> return "", err
<add> }
<add> return filepath.Join(parent, raw.cgroup), nil
<ide> }
<ide>
<ide> func (raw *data) join(subsystem string) (string, error) {
<ide><path>pkg/cgroups/fs/cpuset.go
<ide> package fs
<ide>
<ide> import (
<add> "bytes"
<add> "io/ioutil"
<ide> "os"
<add> "path/filepath"
<add> "strconv"
<ide> )
<ide>
<ide> type cpusetGroup struct {
<ide> type cpusetGroup struct {
<ide> func (s *cpusetGroup) Set(d *data) error {
<ide> // we don't want to join this cgroup unless it is specified
<ide> if d.c.CpusetCpus != "" {
<del> dir, err := d.join("cpuset")
<del> if err != nil && d.c.CpusetCpus != "" {
<add> dir, err := d.path("cpuset")
<add> if err != nil {
<add> return err
<add> }
<add> if err := s.ensureParent(dir); err != nil {
<ide> return err
<ide> }
<del> defer func() {
<del> if err != nil {
<del> os.RemoveAll(dir)
<del> }
<del> }()
<ide>
<add> // because we are not using d.join we need to place the pid into the procs file
<add> // unlike the other subsystems
<add> if err := writeFile(dir, "cgroup.procs", strconv.Itoa(d.pid)); err != nil {
<add> return err
<add> }
<ide> if err := writeFile(dir, "cpuset.cpus", d.c.CpusetCpus); err != nil {
<ide> return err
<ide> }
<ide> func (s *cpusetGroup) Remove(d *data) error {
<ide> func (s *cpusetGroup) Stats(d *data) (map[string]float64, error) {
<ide> return nil, ErrNotSupportStat
<ide> }
<add>
<add>func (s *cpusetGroup) getSubsystemSettings(parent string) (cpus []byte, mems []byte, err error) {
<add> if cpus, err = ioutil.ReadFile(filepath.Join(parent, "cpuset.cpus")); err != nil {
<add> return
<add> }
<add> if mems, err = ioutil.ReadFile(filepath.Join(parent, "cpuset.mems")); err != nil {
<add> return
<add> }
<add> return cpus, mems, nil
<add>}
<add>
<add>// ensureParent ensures that the parent directory of current is created
<add>// with the proper cpus and mems files copied from it's parent if the values
<add>// are a file with a new line char
<add>func (s *cpusetGroup) ensureParent(current string) error {
<add> parent := filepath.Dir(current)
<add>
<add> if _, err := os.Stat(parent); err != nil {
<add> if !os.IsNotExist(err) {
<add> return err
<add> }
<add>
<add> if err := s.ensureParent(parent); err != nil {
<add> return err
<add> }
<add> }
<add>
<add> if err := os.MkdirAll(current, 0755); err != nil && !os.IsExist(err) {
<add> return err
<add> }
<add> return s.copyIfNeeded(current, parent)
<add>}
<add>
<add>// copyIfNeeded copies the cpuset.cpus and cpuset.mems from the parent
<add>// directory to the current directory if the file's contents are 0
<add>func (s *cpusetGroup) copyIfNeeded(current, parent string) error {
<add> var (
<add> err error
<add> currentCpus, currentMems []byte
<add> parentCpus, parentMems []byte
<add> )
<add>
<add> if currentCpus, currentMems, err = s.getSubsystemSettings(current); err != nil {
<add> return err
<add> }
<add> if parentCpus, parentMems, err = s.getSubsystemSettings(parent); err != nil {
<add> return err
<add> }
<add>
<add> if s.isEmpty(currentCpus) {
<add> if err := writeFile(current, "cpuset.cpus", string(parentCpus)); err != nil {
<add> return err
<add> }
<add> }
<add> if s.isEmpty(currentMems) {
<add> if err := writeFile(current, "cpuset.mems", string(parentMems)); err != nil {
<add> return err
<add> }
<add> }
<add> return nil
<add>}
<add>
<add>func (s *cpusetGroup) isEmpty(b []byte) bool {
<add> return len(bytes.Trim(b, "\n")) == 0
<add>} | 2 |
Text | Text | fix double word 'be' [ci skip] | 1c44d968679674efa61073b42737e1f1efea7f97 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> config.active_record.auto_explain_threshold_in_seconds = 0.5
<ide>
<ide> ### config/environments/test.rb
<ide>
<del>The `mass_assignment_sanitizer` configuration setting should also be be added to `config/environments/test.rb`:
<add>The `mass_assignment_sanitizer` configuration setting should also be added to `config/environments/test.rb`:
<ide>
<ide> ```ruby
<ide> # Raise exception on mass assignment protection for Active Record models | 1 |
PHP | PHP | add forgetuser() method to guardhelpers | 73685ff12821f7491c506bc78e91b0c917dfa75a | <ide><path>src/Illuminate/Auth/GuardHelpers.php
<ide> public function setUser(AuthenticatableContract $user)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Forget the user.
<add> *
<add> * @return void
<add> */
<add> public function forgetUser()
<add> {
<add> $this->user = null;
<add> }
<add>
<ide> /**
<ide> * Get the user provider used by the guard.
<ide> *
<ide><path>src/Illuminate/Support/Facades/Auth.php
<ide> * @method static \Illuminate\Auth\SessionGuard setRequest(\Symfony\Component\HttpFoundation\Request $request)
<ide> * @method static \Illuminate\Support\Timebox getTimebox()
<ide> * @method static \Illuminate\Contracts\Auth\Authenticatable authenticate()
<add> * @method static void forgetUser()
<ide> * @method static \Illuminate\Contracts\Auth\UserProvider getProvider()
<ide> * @method static void setProvider(\Illuminate\Contracts\Auth\UserProvider $provider)
<ide> * @method static void macro(string $name, object|callable $macro)
<ide><path>tests/Auth/AuthGuardTest.php
<ide> public function testLoginOnceFailure()
<ide> $this->assertFalse($guard->once(['foo']));
<ide> }
<ide>
<add> public function testForgetUserSetsUserToNull()
<add> {
<add> $user = m::mock(Authenticatable::class);
<add> $guard = $this->getGuard()->setUser($user);
<add> $guard->forgetUser();
<add> $this->assertNull($guard->getUser());
<add> }
<add>
<ide> protected function getGuard()
<ide> {
<ide> [$session, $provider, $request, $cookie, $timebox] = $this->getMocks(); | 3 |
Ruby | Ruby | address new cop offence in railties | 23392eff9f8065475739e58232a5db97604f8056 | <ide><path>railties/test/generators/actions_test.rb
<ide> def test_environment_with_block_should_include_block_contents_in_environment_ini
<ide> run_generator
<ide>
<ide> action :environment do
<del> _ = "# This wont be added"# assignment to silence parse-time warning "unused literal ignored"
<add> _ = "# This wont be added" # assignment to silence parse-time warning "unused literal ignored"
<ide> "# This will be added"
<ide> end
<ide> | 1 |
Python | Python | fix redacting secrets in context exceptions. | 6df3ee7997e335eb7d353d4ec0f5c2dd3a0e0d26 | <ide><path>airflow/utils/log/secrets_masker.py
<ide> def _record_attrs_to_ignore(self) -> Iterable[str]:
<ide> )
<ide> return frozenset(record.__dict__).difference({'msg', 'args'})
<ide>
<add> def _redact_exception_with_context(self, exception):
<add> exception.args = (self.redact(v) for v in exception.args)
<add> if exception.__context__:
<add> self._redact_exception_with_context(exception.__context__)
<add> if exception.__cause__ and exception.__cause__ is not exception.__context__:
<add> self._redact_exception_with_context(exception.__cause__)
<add>
<ide> def filter(self, record) -> bool:
<ide> if self.ALREADY_FILTERED_FLAG in record.__dict__:
<ide> # Filters are attached to multiple handlers and logs, keep a
<ide> def filter(self, record) -> bool:
<ide> record.__dict__[k] = self.redact(v)
<ide> if record.exc_info and record.exc_info[1] is not None:
<ide> exc = record.exc_info[1]
<del> # I'm not sure if this is a good idea!
<del> exc.args = (self.redact(v) for v in exc.args)
<add> self._redact_exception_with_context(exc)
<ide> record.__dict__[self.ALREADY_FILTERED_FLAG] = True
<ide>
<ide> return True
<ide><path>tests/utils/log/test_secrets_masker.py
<ide> from airflow.utils.log.secrets_masker import SecretsMasker, should_hide_value_for_key
<ide> from tests.test_utils.config import conf_vars
<ide>
<add>p = "password"
<add>
<ide>
<ide> @pytest.fixture
<ide> def logger(caplog):
<ide> def test_exc_tb(self, logger, caplog):
<ide> """
<ide> )
<ide>
<add> def test_masking_in_implicit_context_exceptions(self, logger, caplog):
<add> """
<add> Show that redacting password works in context exceptions.
<add> """
<add> try:
<add> try:
<add> try:
<add> raise RuntimeError(f"Cannot connect to user:{p}")
<add> except RuntimeError as ex1:
<add> raise RuntimeError(f'Exception: {ex1}')
<add> except RuntimeError as ex2:
<add> raise RuntimeError(f'Exception: {ex2}')
<add> except RuntimeError:
<add> logger.exception("Err")
<add>
<add> line = lineno() - 8
<add>
<add> assert caplog.text == textwrap.dedent(
<add> f"""\
<add> ERROR Err
<add> Traceback (most recent call last):
<add> File ".../test_secrets_masker.py", line {line}, in test_masking_in_implicit_context_exceptions
<add> raise RuntimeError(f"Cannot connect to user:{{p}}")
<add> RuntimeError: Cannot connect to user:***
<add>
<add> During handling of the above exception, another exception occurred:
<add>
<add> Traceback (most recent call last):
<add> File ".../test_secrets_masker.py", line {line+2}, in test_masking_in_implicit_context_exceptions
<add> raise RuntimeError(f'Exception: {{ex1}}')
<add> RuntimeError: Exception: Cannot connect to user:***
<add>
<add> During handling of the above exception, another exception occurred:
<add>
<add> Traceback (most recent call last):
<add> File ".../test_secrets_masker.py", line {line+4}, in test_masking_in_implicit_context_exceptions
<add> raise RuntimeError(f'Exception: {{ex2}}')
<add> RuntimeError: Exception: Exception: Cannot connect to user:***
<add> """
<add> )
<add>
<add> def test_masking_in_explicit_context_exceptions(self, logger, caplog):
<add> """
<add> Show that redacting password works in context exceptions.
<add> """
<add> exception = None
<add> try:
<add> raise RuntimeError(f"Cannot connect to user:{p}")
<add> except RuntimeError as ex:
<add> exception = ex
<add> try:
<add> raise RuntimeError(f'Exception: {exception}') from exception
<add> except RuntimeError:
<add> logger.exception("Err")
<add>
<add> line = lineno() - 8
<add>
<add> assert caplog.text == textwrap.dedent(
<add> f"""\
<add> ERROR Err
<add> Traceback (most recent call last):
<add> File ".../test_secrets_masker.py", line {line}, in test_masking_in_explicit_context_exceptions
<add> raise RuntimeError(f"Cannot connect to user:{{p}}")
<add> RuntimeError: Cannot connect to user:***
<add>
<add> The above exception was the direct cause of the following exception:
<add>
<add> Traceback (most recent call last):
<add> File ".../test_secrets_masker.py", line {line+4}, in test_masking_in_explicit_context_exceptions
<add> raise RuntimeError(f'Exception: {{exception}}') from exception
<add> RuntimeError: Exception: Cannot connect to user:***
<add> """
<add> )
<add>
<ide> @pytest.mark.parametrize(
<ide> ("name", "value", "expected_mask"),
<ide> [ | 2 |
Javascript | Javascript | put deprecation warning for classset | 835316bc1351dcf4d849a27c44a1a7c1b6f7bda4 | <ide><path>src/core/__tests__/ReactCompositeComponent-test.js
<ide> var ReactPropTypes;
<ide> var ReactServerRendering;
<ide> var ReactTestUtils;
<ide>
<del>var cx;
<ide> var reactComponentExpect;
<ide> var mocks;
<ide>
<ide> describe('ReactCompositeComponent', function() {
<ide>
<ide> beforeEach(function() {
<del> cx = require('cx');
<ide> mocks = require('mocks');
<ide>
<ide> reactComponentExpect = require('reactComponentExpect');
<ide> describe('ReactCompositeComponent', function() {
<ide> return this.refs.anch;
<ide> },
<ide> render: function() {
<del> var className = cx({'anchorClass': this.props.anchorClassOn});
<add> var className = this.props.anchorClassOn ? 'anchorClass' : '';
<ide> return this.props.renderAnchor ?
<ide> <a ref="anch" className={className}></a> :
<ide> <b></b>;
<ide><path>src/vendor/stubs/cx.js
<ide> * @param [string ...] Variable list of classNames in the string case.
<ide> * @return string Renderable space-separated CSS className.
<ide> */
<add>
<add>'use strict';
<add>var warning = require('warning');
<add>
<add>var warned = false;
<add>
<ide> function cx(classNames) {
<add> if (__DEV__) {
<add> warning(
<add> warned,
<add> 'React.addons.classSet will be deprecated in a future version. See ' +
<add> 'http://fb.me/react-addons-classset'
<add> );
<add> warned = true;
<add> }
<add>
<ide> if (typeof classNames == 'object') {
<ide> return Object.keys(classNames).filter(function(className) {
<ide> return classNames[className]; | 2 |
Python | Python | replace assignment with augmented assignment | d5c185aec14506c3f53fbae58c499083a7d5d2db | <ide><path>glances/outputs/glances_curses.py
<ide> def display_plugin(self, plugin_stats,
<ide> # New line
<ide> if m['msg'].startswith('\n'):
<ide> # Go to the next line
<del> y = y + 1
<add> y += 1
<ide> # Return to the first column
<ide> x = display_x
<ide> continue
<ide> def display_plugin(self, plugin_stats,
<ide> # Python 3: strings are strings and bytes are bytes, all is
<ide> # good
<ide> offset = len(m['msg'])
<del> x = x + offset
<add> x += offset
<ide> if x > x_max:
<ide> x_max = x
<ide>
<ide><path>glances/plugins/glances_batpercent.py
<ide> def update(self):
<ide> """Update the stats."""
<ide> if self.initok:
<ide> self.bat.update()
<del> self.bat_list = [{'label': _("Battery"), 'value': self.getcapacitypercent(), 'unit': '%'}]
<add> self.bat_list = [{'label': _("Battery"), 'value': self.battery_percent, 'unit': '%'}]
<ide> else:
<ide> self.bat_list = []
<ide>
<ide> def get(self):
<ide> """Get the stats."""
<ide> return self.bat_list
<ide>
<del> def getcapacitypercent(self):
<add> @property
<add> def battery_percent(self):
<ide> """Get batteries capacity percent."""
<ide> if not self.initok or not self.bat.stat:
<ide> return []
<ide> def getcapacitypercent(self):
<ide> bsum = 0
<ide> for b in self.bat.stat:
<ide> try:
<del> bsum = bsum + int(b.capacity)
<add> bsum += int(b.capacity)
<ide> except ValueError:
<ide> return []
<ide> | 2 |
Javascript | Javascript | kill subprocess only after last ack | 94be2b17938d5ecdf1d40317d0bdee46906bfe4b | <ide><path>test/parallel/test-child-process-send-returns-boolean.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>
<add>// subprocess.send() will return false if the channel has closed or when the
<add>// backlog of unsent messages exceeds a threshold that makes it unwise to send
<add>// more. Otherwise, the method returns true.
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide> const { fork, spawn } = require('child_process');
<ide> const fixtures = require('../common/fixtures');
<ide>
<del>const emptyFile = fixtures.path('empty.js');
<add>// Just a script that stays alive (does not listen to `process.on('message')`).
<add>const subScript = fixtures.path('child-process-persistent.js');
<add>
<add>{
<add> // Test `send` return value on `fork` that opens and IPC by deafult.
<add> const n = fork(subScript);
<add> // `subprocess.send` should always return `true` for the first send.
<add> const rv = n.send({ h: 'w' }, (err) => { if (err) assert.fail(err); });
<add> assert.strictEqual(rv, true);
<add> n.kill();
<add>}
<ide>
<del>const n = fork(emptyFile);
<add>{
<add> // Test `send` return value on `spawn` and saturate backlog with handles.
<add> // Call `spawn` with options that open an IPC channel.
<add> const spawnOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] };
<add> const s = spawn(process.execPath, [subScript], spawnOptions);
<ide>
<del>const rv = n.send({ hello: 'world' });
<del>assert.strictEqual(rv, true);
<add> const server = net.createServer(common.mustNotCall()).listen(0, () => {
<add> const handle = server._handle;
<ide>
<del>const spawnOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] };
<del>const s = spawn(process.execPath, [emptyFile], spawnOptions);
<del>let handle = null;
<del>s.on('exit', function() {
<del> handle.close();
<del>});
<add> // Sending a handle and not giving the tickQueue time to acknoladge should
<add> // create the internal backlog, but leave it empty.
<add> const rv1 = s.send('one', handle, (err) => { if (err) assert.fail(err); });
<add> assert.strictEqual(rv1, true);
<add> // Since the first `send` included a handle (should be unackoladged),
<add> // we can safly queue up only one more message.
<add> const rv2 = s.send('two', (err) => { if (err) assert.fail(err); });
<add> assert.strictEqual(rv2, true);
<add> // The backlog should now be indicate to backoff.
<add> const rv3 = s.send('three', (err) => { if (err) assert.fail(err); });
<add> assert.strictEqual(rv3, false);
<add> const rv4 = s.send('four', (err) => {
<add> if (err) assert.fail(err);
<add> // `send` queue should have been drained.
<add> const rv5 = s.send('5', handle, (err) => { if (err) assert.fail(err); });
<add> assert.strictEqual(rv5, true);
<ide>
<del>net.createServer(common.mustNotCall()).listen(0, function() {
<del> handle = this._handle;
<del> assert.strictEqual(s.send('one', handle), true);
<del> assert.strictEqual(s.send('two', handle), true);
<del> assert.strictEqual(s.send('three'), false);
<del> assert.strictEqual(s.send('four'), false);
<del>});
<add> // End test and cleanup.
<add> s.kill();
<add> handle.close();
<add> server.close();
<add> });
<add> assert.strictEqual(rv4, false);
<add> });
<add>} | 1 |
Python | Python | add ctc_decode to numpy backend | b7fad0752779177e0968f93832d8a5b302236a7d | <ide><path>tests/keras/backend/backend_test.py
<ide> def test_ctc_decode_greedy(self):
<ide> for t in range(max_time_steps)]
<ide>
<ide> # change tensorflow order to keras backend order
<del> inputs = K.variable(np.asarray(inputs).transpose((1, 0, 2)))
<del> # batch_size length vector of sequence_lengths
<del> input_length = K.variable(np.array([seq_len_0, seq_len_1], dtype=np.int32))
<del>
<del> # batch_size length vector of negative log probabilities
<del> log_prob_truth = np.array([
<del> np.sum(-np.log([1.0, 0.6, 0.6, 0.9])),
<del> np.sum(-np.log([0.9, 0.9, 0.9, 0.9, 0.9]))
<del> ], np.float32)[:, np.newaxis]
<add> inputs = np.asarray(inputs).transpose((1, 0, 2))
<ide>
<del> # keras output, unlike tensorflow, is a dense (not sparse) tensor
<del> decode_truth = np.array([[0, 1, -1], [1, 1, 0]])
<add> # batch_size length vector of sequence_lengths
<add> input_length = np.array([seq_len_0, seq_len_1], dtype=np.int32)
<ide>
<add> decode_pred_np, log_prob_pred_np = KNP.ctc_decode(inputs,
<add> input_length, greedy=True)
<add> inputs = K.variable(inputs)
<add> input_length = K.variable(input_length)
<ide> decode_pred_tf, log_prob_pred_tf = K.ctc_decode(inputs,
<del> input_length,
<del> greedy=True)
<add> input_length, greedy=True)
<ide>
<ide> assert len(decode_pred_tf) == 1
<ide>
<ide> decode_pred = K.eval(decode_pred_tf[0])
<ide> log_prob_pred = K.eval(log_prob_pred_tf)
<ide>
<del> assert np.alltrue(decode_truth == decode_pred)
<del> assert np.allclose(log_prob_truth, log_prob_pred)
<add> assert np.alltrue(decode_pred_np == decode_pred)
<add> assert np.allclose(log_prob_pred_np, log_prob_pred)
<ide>
<ide> @pytest.mark.skipif(K.backend() != 'tensorflow',
<ide> reason='Beam search is only implemented with '
<ide><path>tests/keras/backend/reference_operations.py
<ide> def resize_volumes(x, depth_factor, height_factor, width_factor, data_format):
<ide> def one_hot(indices, num_classes):
<ide> return to_categorical(indices, num_classes)
<ide>
<add>
<add>def ctc_decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1):
<add> num_samples = y_pred.shape[0]
<add> num_classes = y_pred.shape[-1]
<add> log_prob = np.zeros((num_samples, 1))
<add> decoded_dense = -np.ones_like(y_pred[..., 0])
<add> decoded_length = np.zeros((num_samples,), dtype=np.int)
<add> if greedy:
<add> for i in range(num_samples):
<add> prob = y_pred[i]
<add> length = input_length[i]
<add> decoded = np.argmax(prob[:length], axis=-1)
<add> log_prob[i] = -np.sum(np.log(prob[np.arange(length), decoded]))
<add> decoded = _remove_repeats(decoded)
<add> decoded = _remove_blanks(decoded, num_classes)
<add> decoded_length[i] = len(decoded)
<add> decoded_dense[i, :len(decoded)] = decoded
<add> return decoded_dense[:, :np.max(decoded_length)], log_prob
<add> else:
<add> raise "not supported yet"
<add>
<add>
<add>def _remove_repeats(inds):
<add> is_not_repeat = np.insert(np.diff(inds).astype(np.bool), 0, True)
<add> return inds[is_not_repeat]
<add>
<add>
<add>def _remove_blanks(inds, num_classes):
<add> return inds[inds < (num_classes - 1)]
<add>
<add>
<ide> square = np.square
<ide> abs = np.abs
<ide> exp = np.exp | 2 |
Ruby | Ruby | remove unnessary option setting from test runner | 9fa07095a35be2d8cb5adcc992b988e73a6d9719 | <ide><path>railties/lib/rails/test_unit/minitest_plugin.rb
<ide> def self.plugin_rails_options(opts, options)
<ide>
<ide> options[:color] = true
<ide> options[:output_inline] = true
<del> options[:patterns] = opts.order!
<add> options[:patterns] = defined?(@rake_patterns) ? @rake_patterns : opts.order!
<ide> end
<ide>
<ide> # Running several Rake tasks in a single command would trip up the runner,
<ide> def self.plugin_rails_init(options)
<ide>
<ide> ENV["RAILS_ENV"] = options[:environment] || "test"
<ide>
<del> unless run_with_autorun
<del> patterns = defined?(@rake_patterns) ? @rake_patterns : options[:patterns]
<del> ::Rails::TestRequirer.require_files(patterns)
<del> end
<add> ::Rails::TestRequirer.require_files(options[:patterns]) unless run_with_autorun
<ide>
<ide> unless options[:full_backtrace] || ENV["BACKTRACE"]
<ide> # Plugin can run without Rails loaded, check before filtering.
<ide><path>railties/test/application/test_runner_test.rb
<ide> def test_pass_TEST_env_on_rake_test
<ide> assert_match '1 runs, 1 assertions', output
<ide> end
<ide>
<add> def test_pass_rake_options
<add> create_test_file :models, 'account'
<add> output = Dir.chdir(app_path) { `bin/rake --rakefile Rakefile --trace=stdout test` }
<add>
<add> assert_match '1 runs, 1 assertions', output
<add> assert_match 'Execute test', output
<add> end
<add>
<ide> def test_rails_db_create_all_restores_db_connection
<ide> create_test_file :models, 'account'
<ide> output = Dir.chdir(app_path) { `bin/rails db:create:all db:migrate && echo ".tables" | rails dbconsole` } | 2 |
Javascript | Javascript | fix a little typo | e58b076eab0b6e31a1ee8bd70ed5b154f141f548 | <ide><path>fonts.js
<ide> var Font = (function Font() {
<ide> }
<ide> }
<ide>
<del> if (properties.firstChar < 0x20)
<add> if (properties.firstChar < 0x20) {
<ide> var code = 0;
<ide> for (var j = 0; j < glyphs.length; j++) {
<ide> var glyph = glyphs[j];
<ide> glyphs[j].unicode += 0x1F;
<ide> properties.glyphs[glyph.glyph] = encoding[++code] = glyph.unicode;
<add> }
<ide> }
<add>
<ide> return cmap.data = createCMapTable(glyphs, deltas);
<ide> } else if (format == 6) {
<ide> // Format 6 is a 2-bytes dense mapping, which means the font data | 1 |
Python | Python | fix handling of errors around git [ci skip] | a5633b205f287775ea92b617b052662f4f4a1081 | <ide><path>spacy/cli/_util.py
<ide> def ensure_pathy(path):
<ide>
<ide>
<ide> def git_sparse_checkout(repo: str, subpath: str, dest: Path, *, branch: str = "master"):
<add> git_version = get_git_version()
<ide> if dest.exists():
<ide> msg.fail("Destination of checkout must not exist", exits=1)
<ide> if not dest.parent.exists():
<ide> def git_sparse_checkout(repo: str, subpath: str, dest: Path, *, branch: str = "m
<ide> # *that* we can do by path.
<ide> # We're using Git and sparse checkout to only clone the files we need
<ide> with make_tempdir() as tmp_dir:
<del> git_version = get_git_version()
<ide> supports_sparse = git_version >= (2, 22)
<ide> # This is the "clone, but don't download anything" part.
<ide> cmd = f"git clone {repo} {tmp_dir} --no-checkout --depth 1 " f"-b {branch} "
<ide> if supports_sparse:
<ide> cmd += f"--filter=blob:none" # <-- The key bit
<ide> else:
<del> msg.warn(
<add> err_old = (
<ide> f"You're running an old version of Git (v{git_version[0]}.{git_version[1]}) "
<del> f"that doesn't fully support sparse checkout yet. This means that "
<del> f"more files than necessary may be downloaded temporarily. To "
<del> f"only download the files needed, upgrade to Git v2.22 or above."
<add> f"that doesn't fully support sparse checkout yet."
<add> )
<add> err_unk = "You're running an unknown version of Git, so sparse checkout has been disabled."
<add> msg.warn(
<add> f"{err_unk if git_version == (0, 0) else err_old} "
<add> f"This means that more files than necessary may be downloaded "
<add> f"temporarily. To only download the files needed, make sure "
<add> f"you're using Git v2.22 or above."
<ide> )
<del> _attempt_run_command(cmd)
<add> try_run_command(cmd)
<ide> # Now we need to find the missing filenames for the subpath we want.
<ide> # Looking for this 'rev-list' command in the git --help? Hah.
<ide> cmd = f"git -C {tmp_dir} rev-list --objects --all {'--missing=print ' if supports_sparse else ''} -- {subpath}"
<del> ret = _attempt_run_command(cmd)
<add> ret = try_run_command(cmd)
<ide> git_repo = _from_http_to_git(repo)
<ide> # Now pass those missings into another bit of git internals
<ide> missings = " ".join([x[1:] for x in ret.stdout.split() if x.startswith("?")])
<ide> def git_sparse_checkout(repo: str, subpath: str, dest: Path, *, branch: str = "m
<ide> msg.fail(err, exits=1)
<ide> if supports_sparse:
<ide> cmd = f"git -C {tmp_dir} fetch-pack {git_repo} {missings}"
<del> _attempt_run_command(cmd)
<add> try_run_command(cmd)
<ide> # And finally, we can checkout our subpath
<ide> cmd = f"git -C {tmp_dir} checkout {branch} {subpath}"
<del> _attempt_run_command(cmd)
<add> try_run_command(cmd)
<ide> # We need Path(name) to make sure we also support subdirectories
<ide> shutil.move(str(tmp_dir / Path(subpath)), str(dest))
<ide>
<ide>
<del>def get_git_version() -> Tuple[int, int]:
<del> ret = _attempt_run_command(["git", "--version"])
<del> # TODO: this seems kinda brittle?
<del> version = ret.stdout[11:].strip().split(".")
<add>def get_git_version(
<add> error: str = "Could not run 'git'. Make sure it's installed and the executable is available.",
<add>) -> Tuple[int, int]:
<add> """Get the version of git and raise an error if calling 'git --version' fails.
<add>
<add> error (str): The error message to show.
<add> RETURNS (Tuple[int, int]): The version as a (major, minor) tuple. Returns
<add> (0, 0) if the version couldn't be determined.
<add> """
<add> ret = try_run_command(["git", "--version"], error=error)
<add> stdout = ret.stdout.strip()
<add> if not stdout or not stdout.startswith("git version"):
<add> return (0, 0)
<add> version = stdout[11:].strip().split(".")
<ide> return (int(version[0]), int(version[1]))
<ide>
<ide>
<del>def _attempt_run_command(cmd: Union[str, List[str]]):
<add>def try_run_command(
<add> cmd: Union[str, List[str]], error: str = "Could not run command"
<add>) -> subprocess.CompletedProcess:
<add> """Try running a command and raise an error if it fails.
<add>
<add> cmd (Union[str, List[str]]): The command to run.
<add> error (str): The error message.
<add> RETURNS (CompletedProcess): The completed process if the command ran.
<add> """
<ide> try:
<ide> return run_command(cmd, capture=True)
<ide> except subprocess.CalledProcessError as e:
<del> err = f"Could not run command"
<del> msg.fail(err)
<add> msg.fail(error)
<ide> print(cmd)
<ide> sys.exit(1)
<ide>
<ide><path>spacy/cli/project/assets.py
<ide>
<ide> from ...util import ensure_path, working_dir
<ide> from .._util import project_cli, Arg, PROJECT_FILE, load_project_config, get_checksum
<del>from .._util import download_file, git_sparse_checkout
<add>from .._util import download_file, git_sparse_checkout, get_git_version
<ide>
<ide>
<ide> @project_cli.command("assets")
<ide> def project_assets(project_dir: Path) -> None:
<ide> dest = (project_dir / asset["dest"]).resolve()
<ide> checksum = asset.get("checksum")
<ide> if "git" in asset:
<add> git_err = (
<add> f"Cloning spaCy project templates requires Git and the 'git' command. "
<add> f"Make sure it's installed and that the executable is available."
<add> )
<add> get_git_version(error=git_err)
<ide> if dest.exists():
<ide> # If there's already a file, check for checksum
<ide> if checksum and checksum == get_checksum(dest):
<ide><path>spacy/cli/project/clone.py
<ide> from ... import about
<ide> from ...util import ensure_path
<ide> from .._util import project_cli, Arg, Opt, COMMAND, PROJECT_FILE
<del>from .._util import git_sparse_checkout
<add>from .._util import git_sparse_checkout, get_git_version
<ide>
<ide>
<ide> @project_cli.command("clone")
<ide> def check_clone(name: str, dest: Path, repo: str) -> None:
<ide> dest (Path): Local destination of cloned directory.
<ide> repo (str): URL of the repo to clone from.
<ide> """
<del> try:
<del> subprocess.run(["git", "--version"], stdout=subprocess.DEVNULL)
<del> except Exception:
<del> msg.fail(
<del> f"Cloning spaCy project templates requires Git and the 'git' command. ",
<del> f"To clone a project without Git, copy the files from the '{name}' "
<del> f"directory in the {repo} to {dest} manually and then run:",
<del> f"{COMMAND} project init {dest}",
<del> exits=1,
<del> )
<add> git_err = (
<add> f"Cloning spaCy project templates requires Git and the 'git' command. ",
<add> f"To clone a project without Git, copy the files from the '{name}' "
<add> f"directory in the {repo} to {dest} manually.",
<add> )
<add> get_git_version(error=git_err)
<ide> if not dest:
<ide> msg.fail(f"Not a valid directory to clone project: {dest}", exits=1)
<ide> if dest.exists(): | 3 |
PHP | PHP | improve docs for unaryexpression | 3546466c673e33b2906b729e4c91fa83c1d44ef3 | <ide><path>src/Database/Expression/UnaryExpression.php
<ide> use Cake\Database\ExpressionInterface;
<ide> use Cake\Database\ValueBinder;
<ide>
<add>/**
<add> * An expression object that represents an expression with only a single operand.
<add> */
<ide> class UnaryExpression extends QueryExpression {
<ide>
<ide> /** | 1 |
Python | Python | fix nan in optimizer_on_cpu | cba85a67b9c2897593321012f3c6a575545e49e2 | <ide><path>examples/run_squad.py
<ide> def set_optimizer_params_grad(named_params_optimizer, named_params_model, test_n
<ide> if name_opti != name_model:
<ide> logger.error("name_opti != name_model: {} {}".format(name_opti, name_model))
<ide> raise ValueError
<del> if test_nan and torch.isnan(param_model.grad).sum() > 0:
<del> is_nan = True
<del> if param_opti.grad is None:
<del> param_opti.grad = torch.nn.Parameter(param_opti.data.new().resize_(*param_opti.data.size()))
<del> param_opti.grad.data.copy_(param_model.grad.data)
<add> if param_model.grad is not None:
<add> if test_nan and torch.isnan(param_model.grad).sum() > 0:
<add> is_nan = True
<add> if param_opti.grad is None:
<add> param_opti.grad = torch.nn.Parameter(param_opti.data.new().resize_(*param_opti.data.size()))
<add> param_opti.grad.data.copy_(param_model.grad.data)
<ide> return is_nan
<ide>
<ide> def main(): | 1 |
PHP | PHP | remove confusing identation | e082ed250f5471a99cf9b990e8f76cfdfa1a217a | <ide><path>src/Illuminate/Database/Grammar.php
<ide> protected function wrapAliasedValue($value, $prefixAlias = false)
<ide> $segments[1] = $this->tablePrefix.$segments[1];
<ide> }
<ide>
<del> return $this->wrap(
<del> $segments[0]).' as '.$this->wrapValue($segments[1]
<del> );
<add> return $this->wrap($segments[0]).' as '.$this->wrapValue($segments[1]);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | remove outdated info | cec45957ac597eda04dbe8b5b1bc0dbf8e5ddff2 | <ide><path>docs/KnownIssues.md
<ide> There are properties that work on one platform only, either because they can inh
<ide> There are known cases where the APIs could be made more consistent across iOS and Android:
<ide>
<ide> - `<AndroidViewPager>` and `<ScrollView pagingEnabled={true}>` on iOS do a similar thing. We might want to unify them to `<ViewPager>`.
<del>- `alert()` needs Android support (once the Dialogs module is open sourced)
<ide> - It might be possible to bring `LinkingIOS` and `IntentAndroid` closer together.
<ide> - `ActivityIndicator` could render a native spinning indicator on both platforms (currently this is done using `ActivityIndicatorIOS` on iOS and `ProgressBarAndroid` on Android).
<ide> - `ProgressBar` could render a horizontal progress bar on both platforms (on iOS this is `ProgressViewIOS`, on Android it's `ProgressBarAndroid`). | 1 |
Text | Text | add stitches example to css-in-js docs | e5960dc6d6d512950393e3d457aedc4e0d5f7918 | <ide><path>docs/basic-features/built-in-css-support.md
<ide> module.exports = {
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-cxs">Cxs</a></li>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-aphrodite">Aphrodite</a></li>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-fela">Fela</a></li>
<add> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-stitches">Stitches</a></li>
<ide> </ul>
<ide> </details>
<ide> | 1 |
Javascript | Javascript | add todo note about ember.location documentation | 1bff946579a832526349ac3f70ce032c6eb95d2c | <ide><path>packages/ember-application/lib/system/location.js
<ide> var get = Ember.get, set = Ember.set;
<ide> onUpdateURL(callback): triggers the callback when the URL changes
<ide>
<ide> Calling setURL will not trigger onUpdateURL callbacks.
<add>
<add> TODO: This, as well as the Ember.Location documentation below, should
<add> perhaps be moved so that it's visible in the JsDoc output.
<ide> */
<ide>
<ide> /** | 1 |
Javascript | Javascript | remove unnecessary judgment | 311f196219770da1fddd2447690b98aa6e8d7d78 | <ide><path>lib/WebpackOptionsApply.js
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> default:
<ide> throw new Error("Unsupported target '" + options.target + "'.");
<ide> }
<del> }
<del> // @ts-ignore This is always true, which is good this way
<del> else if (options.target !== false) {
<del> options.target(compiler);
<ide> } else {
<del> throw new Error("Unsupported target '" + options.target + "'.");
<add> options.target(compiler);
<ide> }
<ide>
<ide> if (options.output.library || options.output.libraryTarget !== "var") { | 1 |
Text | Text | use list for common disable reasons | 09132be32a163d83895081b0ddd02a314b4b54b6 | <ide><path>docs/Deprecating-Disabling-and-Removing-Formulae.md
<ide> If a user attempts to install a disabled formula, they will be shown an error me
<ide>
<ide> A formula should be disabled to indicate to users that the formula cannot be used and will be removed in the future. Disabled formulae may no longer build from source or have working bottles.
<ide>
<del>The most common reasons for disabling are when the formula cannot be built from source (meaning no bottles can be built), the formula has been deprecated for a long time, the upstream repository has been removed, or the project has no license.
<add>The most common reasons for disabling a formula are:
<add>
<add>- it cannot be built from source (meaning no bottles can be built)
<add>- it has been deprecated for a long time
<add>- the upstream repository has been removed
<add>- the project has no license
<ide>
<ide> **Note: disabled formulae in homebrew/core will be automatically removed one year after their disable date**
<ide> | 1 |
Ruby | Ruby | remove private verify readonly attr method | 7a8aee08b610f6edbfe5be076dc14e5cdcf1355e | <ide><path>activerecord/lib/active_record/persistence.rb
<ide> def update_columns(attributes)
<ide> raise ActiveRecordError, "can not update on a new record object" unless persisted?
<ide>
<ide> attributes.each_key do |key|
<del> raise ActiveRecordError, "#{key.to_s} is marked as readonly" if self.class.readonly_attributes.include?(key.to_s)
<add> raise ActiveRecordError, "#{key} is marked as readonly" if self.class.readonly_attributes.include?(key.to_s)
<ide> end
<ide>
<ide> attributes.each do |k,v|
<ide> def create
<ide> @new_record = false
<ide> id
<ide> end
<del>
<del> def verify_readonly_attribute(name)
<del> raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
<del> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | implement a default computed property setter | 37107a04e46852086077f428d99f91e7d59926fb | <ide><path>packages/ember-metal/lib/computed.js
<ide> ComputedPropertyPrototype.set = function(obj, keyName, value) {
<ide> // argument.
<ide> if (func.length === 3) {
<ide> ret = func.call(obj, keyName, value, cachedValue);
<del> } else {
<add> } else if (func.length === 2) {
<ide> ret = func.call(obj, keyName, value);
<add> } else {
<add> Ember.defineProperty(obj, keyName, null, value);
<add> return;
<ide> }
<ide>
<ide> if (hadCachedValue && cachedValue === ret) { return; }
<ide><path>packages/ember-metal/tests/computed_test.js
<ide> module('Ember.computed - cacheable', {
<ide> setup: function() {
<ide> obj = {};
<ide> count = 0;
<del> Ember.defineProperty(obj, 'foo', Ember.computed(function() {
<add> Ember.defineProperty(obj, 'foo', Ember.computed(function(key, value) {
<ide> count++;
<ide> return 'bar '+count;
<ide> }));
<ide> module('Ember.computed - dependentkey', {
<ide> setup: function() {
<ide> obj = { bar: 'baz' };
<ide> count = 0;
<del> Ember.defineProperty(obj, 'foo', Ember.computed(function() {
<add> Ember.defineProperty(obj, 'foo', Ember.computed(function(key, value) {
<ide> count++;
<ide> return 'bar '+count;
<ide> }).property('bar'));
<ide> testBoth('should invalidate multiple nested dependent keys', function(get, set)
<ide>
<ide> testBoth('circular keys should not blow up', function(get, set) {
<ide>
<del> Ember.defineProperty(obj, 'bar', Ember.computed(function() {
<add> Ember.defineProperty(obj, 'bar', Ember.computed(function(key, value) {
<ide> count++;
<ide> return 'bar '+count;
<ide> }).property('foo'));
<ide>
<del> Ember.defineProperty(obj, 'foo', Ember.computed(function() {
<add> Ember.defineProperty(obj, 'foo', Ember.computed(function(key, value) {
<ide> count++;
<ide> return 'foo '+count;
<ide> }).property('bar'));
<ide> testBoth('setting a cached computed property that modifies the value you give it
<ide> equal(plusOneDidChange, 2);
<ide> });
<ide>
<add>module('Ember.computed - default setter');
<add>
<add>testBoth("when setting a value on a computed property that doesn't handle sets", function(get, set) {
<add> var obj = {};
<add>
<add> Ember.defineProperty(obj, 'foo', Ember.computed(function() {
<add> return 'foo';
<add> }));
<add>
<add> Ember.set(obj, 'foo', 'bar');
<add>
<add> equal(Ember.get(obj, 'foo'), 'bar', 'The set value is properly returned');
<add> ok(!Ember.meta(obj).descs.foo, 'The computed property was removed');
<add>});
<add>
<ide> module('CP macros');
<ide>
<ide> testBoth('Ember.computed.not', function(get, set) { | 2 |
Go | Go | copy volumesrw values when using --volumes-from | 5ae8c7a98592f83a31f3f45fc22728e45e95626c | <ide><path>container.go
<ide> func (container *Container) Start(hostConfig *HostConfig) error {
<ide> return nil
<ide> }
<ide> container.Volumes[volPath] = id
<add> if isRW, exists := c.VolumesRW[volPath]; exists {
<add> container.VolumesRW[volPath] = isRW
<add> }
<ide> }
<ide> }
<ide>
<ide><path>container_test.go
<ide> func TestBindMounts(t *testing.T) {
<ide>
<ide> }
<ide> }
<add>
<add>// Test that VolumesRW values are copied to the new container. Regression test for #1201
<add>func TestVolumesFromReadonlyMount(t *testing.T) {
<add> runtime := mkRuntime(t)
<add> defer nuke(runtime)
<add> container, err := NewBuilder(runtime).Create(
<add> &Config{
<add> Image: GetTestImage(runtime).ID,
<add> Cmd: []string{"/bin/echo", "-n", "foobar"},
<add> Volumes: map[string]struct{}{"/test": {}},
<add> },
<add> )
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer runtime.Destroy(container)
<add> _, err = container.Output()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if !container.VolumesRW["/test"] {
<add> t.Fail()
<add> }
<add>
<add> container2, err := NewBuilder(runtime).Create(
<add> &Config{
<add> Image: GetTestImage(runtime).ID,
<add> Cmd: []string{"/bin/echo", "-n", "foobar"},
<add> VolumesFrom: container.ID,
<add> },
<add> )
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer runtime.Destroy(container2)
<add>
<add> _, err = container2.Output()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if container.Volumes["/test"] != container2.Volumes["/test"] {
<add> t.Fail()
<add> }
<add>
<add> actual, exists := container2.VolumesRW["/test"]
<add> if !exists {
<add> t.Fail()
<add> }
<add>
<add> if container.VolumesRW["/test"] != actual {
<add> t.Fail()
<add> }
<add>} | 2 |
Ruby | Ruby | fix path in cleanup_before | 232eccc4285712697d66f72bd39fa196b5ba1f98 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def cleanup_before
<ide> git "reset", "--hard"
<ide> git "checkout", "-f", "master"
<ide> git "clean", "-ffdx" unless ENV["HOMEBREW_RUBY"] == "1.8.7"
<del> pr_locks = "#{HOMEBREW_REPOSITORY}/.git/refs/remotes/*/pr/*/*.lock"
<add> pr_locks = "#{@repository}/.git/refs/remotes/*/pr/*/*.lock"
<ide> Dir.glob(pr_locks) { |lock| FileUtils.rm_rf lock }
<ide> end
<ide> | 1 |
Java | Java | fix typos in native animated error messages | 0d073013a52dbfd835ded496f89d924b8a80c32a | <ide><path>ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java
<ide> public void startListeningToAnimatedNodeValue(int tag, AnimatedNodeValueListener
<ide> AnimatedNode node = mAnimatedNodes.get(tag);
<ide> if (node == null || !(node instanceof ValueAnimatedNode)) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Animated node with tag " + tag + " does not exists or is not a 'value' node");
<add> "Animated node with tag " + tag + " does not exist, or is not a 'value' node");
<ide> }
<ide> ((ValueAnimatedNode) node).setValueListener(listener);
<ide> }
<ide> public void stopListeningToAnimatedNodeValue(int tag) {
<ide> AnimatedNode node = mAnimatedNodes.get(tag);
<ide> if (node == null || !(node instanceof ValueAnimatedNode)) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Animated node with tag " + tag + " does not exists or is not a 'value' node");
<add> "Animated node with tag " + tag + " does not exist, or is not a 'value' node");
<ide> }
<ide> ((ValueAnimatedNode) node).setValueListener(null);
<ide> }
<ide> public void setAnimatedNodeValue(int tag, double value) {
<ide> AnimatedNode node = mAnimatedNodes.get(tag);
<ide> if (node == null || !(node instanceof ValueAnimatedNode)) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Animated node with tag " + tag + " does not exists or is not a 'value' node");
<add> "Animated node with tag " + tag + " does not exist, or is not a 'value' node");
<ide> }
<ide> stopAnimationsForNode(node);
<ide> ((ValueAnimatedNode) node).mValue = value;
<ide> public void setAnimatedNodeOffset(int tag, double offset) {
<ide> AnimatedNode node = mAnimatedNodes.get(tag);
<ide> if (node == null || !(node instanceof ValueAnimatedNode)) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Animated node with tag " + tag + " does not exists or is not a 'value' node");
<add> "Animated node with tag " + tag + " does not exist, or is not a 'value' node");
<ide> }
<ide> ((ValueAnimatedNode) node).mOffset = offset;
<ide> mUpdatedNodes.put(tag, node);
<ide> public void flattenAnimatedNodeOffset(int tag) {
<ide> AnimatedNode node = mAnimatedNodes.get(tag);
<ide> if (node == null || !(node instanceof ValueAnimatedNode)) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Animated node with tag " + tag + " does not exists or is not a 'value' node");
<add> "Animated node with tag " + tag + " does not exist, or is not a 'value' node");
<ide> }
<ide> ((ValueAnimatedNode) node).flattenOffset();
<ide> }
<ide> public void extractAnimatedNodeOffset(int tag) {
<ide> AnimatedNode node = mAnimatedNodes.get(tag);
<ide> if (node == null || !(node instanceof ValueAnimatedNode)) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Animated node with tag " + tag + " does not exists or is not a 'value' node");
<add> "Animated node with tag " + tag + " does not exist, or is not a 'value' node");
<ide> }
<ide> ((ValueAnimatedNode) node).extractOffset();
<ide> }
<ide> public void startAnimatingNode(
<ide> AnimatedNode node = mAnimatedNodes.get(animatedNodeTag);
<ide> if (node == null) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Animated node with tag " + animatedNodeTag + " does not exists");
<add> "Animated node with tag " + animatedNodeTag + " does not exist");
<ide> }
<ide> if (!(node instanceof ValueAnimatedNode)) {
<ide> throw new JSApplicationIllegalArgumentException( | 1 |
Ruby | Ruby | update openssl in whitelist | 45908d8ff269d20bc12ce2ad6df17bf594e44126 | <ide><path>Library/Homebrew/rubocops/uses_from_macos.rb
<ide> class UsesFromMacos < FormulaCop
<ide> m4
<ide> ncurses
<ide> openldap
<del> openssl
<add> openssl@1.1
<ide> perl
<ide> php
<ide> ruby | 1 |
Go | Go | fix datarace in apistatsnetworkstatsversioning | 825e3a66a419038600024be7dfc5ca24426444f0 | <ide><path>integration-cli/docker_api_stats_test.go
<ide> func (s *DockerSuite) TestApiStatsNetworkStatsVersioning(c *check.C) {
<ide> c.Assert(waitRun(id), checker.IsNil)
<ide> wg := sync.WaitGroup{}
<ide>
<del> for i := 17; i <= 21; i++ {
<add> // Windows API versions prior to 1.21 doesn't support stats.
<add> startAt := 17
<add> if daemonPlatform == "windows" {
<add> startAt = 21
<add> }
<add>
<add> for i := startAt; i <= 21; i++ {
<ide> wg.Add(1)
<del> go func() {
<add> go func(i int) {
<ide> defer wg.Done()
<ide> apiVersion := fmt.Sprintf("v1.%d", i)
<ide> statsJSONBlob := getVersionedStats(c, id, apiVersion)
<ide> func (s *DockerSuite) TestApiStatsNetworkStatsVersioning(c *check.C) {
<ide> c.Assert(jsonBlobHasGTE121NetworkStats(statsJSONBlob), checker.Equals, true,
<ide> check.Commentf("Stats JSON blob from API %s %#v does not look like a >=v1.21 API stats structure", apiVersion, statsJSONBlob))
<ide> }
<del> }()
<add> }(i)
<ide> }
<ide> wg.Wait()
<ide> } | 1 |
Python | Python | remove limitation to pull latest images. | 3a7e89dbddf5fc60dbcb9582acf5e3a79d702c7c | <ide><path>dev/breeze/src/airflow_breeze/commands/ci_image_commands.py
<ide> def pull(
<ide> extra_pytest_args: Tuple,
<ide> ):
<ide> """Pull and optionally verify CI images - possibly in parallel for all Python versions."""
<del> if image_tag == "latest":
<del> get_console().print("[red]You cannot pull latest images because they are not published any more!\n")
<del> get_console().print(
<del> "[yellow]You need to specify commit tag to pull and image. If you wish to get"
<del> " the latest image, you need to run `breeze ci-image build` command\n"
<del> )
<del> sys.exit(1)
<ide> perform_environment_checks(verbose=verbose)
<ide> if run_in_parallel:
<ide> python_version_list = get_python_version_list(python_versions)
<ide><path>dev/breeze/src/airflow_breeze/commands/production_image_commands.py
<ide> def pull_prod_image(
<ide> extra_pytest_args: Tuple,
<ide> ):
<ide> """Pull and optionally verify Production images - possibly in parallel for all Python versions."""
<del> if image_tag == "latest":
<del> get_console().print("[red]You cannot pull latest images because they are not published any more!\n")
<del> get_console().print(
<del> "[yellow]You need to specify commit tag to pull and image. If you wish to get"
<del> " the latest image, you need to run `breeze ci-image build` command\n"
<del> )
<del> sys.exit(1)
<ide> perform_environment_checks(verbose=verbose)
<ide> if run_in_parallel:
<ide> python_version_list = get_python_version_list(python_versions) | 2 |
PHP | PHP | camelize type of test being generated | 75daff8df9b7fea565adcd6b15083751f98849d5 | <ide><path>lib/Cake/Console/Command/Task/TestTask.php
<ide> public function generateConstructor($type, $fullClassName) {
<ide> */
<ide> public function testCaseFileName($type, $className) {
<ide> $path = $this->getPath() . 'Case' . DS;
<add> $type = Inflector::camelize($type);
<ide> if (isset($this->classTypes[$type])) {
<ide> $path .= $this->classTypes[$type] . DS;
<ide> } | 1 |
Python | Python | add missing migration file for | 6ea6e37ac999025c8ee71fbc52764c1fd877c736 | <ide><path>rest_framework/authtoken/migrations/0002_auto_20160226_1747.py
<add># -*- coding: utf-8 -*-
<add>from __future__ import unicode_literals
<add>
<add>from django.db import migrations, models
<add>from django.conf import settings
<add>
<add>
<add>class Migration(migrations.Migration):
<add>
<add> dependencies = [
<add> ('authtoken', '0001_initial'),
<add> ]
<add>
<add> operations = [
<add> migrations.AlterModelOptions(
<add> name='token',
<add> options={'verbose_name_plural': 'Tokens', 'verbose_name': 'Token'},
<add> ),
<add> migrations.AlterField(
<add> model_name='token',
<add> name='created',
<add> field=models.DateTimeField(verbose_name='Created', auto_now_add=True),
<add> ),
<add> migrations.AlterField(
<add> model_name='token',
<add> name='key',
<add> field=models.CharField(verbose_name='Key', max_length=40, primary_key=True, serialize=False),
<add> ),
<add> migrations.AlterField(
<add> model_name='token',
<add> name='user',
<add> field=models.OneToOneField(to=settings.AUTH_USER_MODEL, verbose_name='User', related_name='auth_token'),
<add> ),
<add> ] | 1 |
PHP | PHP | add missing import. | 33b1deadf128751477a4f1bc1398cc91b9f84ed0 | <ide><path>src/Illuminate/Routing/RouteParameterBinder.php
<ide>
<ide> namespace Illuminate\Routing;
<ide>
<add>use Illuminate\Support\Arr;
<add>
<ide> class RouteParameterBinder
<ide> {
<ide> /** | 1 |
Text | Text | add v1.3.6 changes | 02c9dc6e16704edbf9bf5207d09765d69027d7e3 | <ide><path>CHANGELOG.md
<add><a name="1.3.6"></a>
<add># 1.3.6 robofunky-danceblaster (2014-12-08)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$browser:** prevent infinite digests when clearing the hash of a url
<add> ([10ac5948](https://github.com/angular/angular.js/commit/10ac5948097e2c8eaead238603d29ee580dc8273),
<add> [#9629](https://github.com/angular/angular.js/issues/9629), [#9635](https://github.com/angular/angular.js/issues/9635), [#10228](https://github.com/angular/angular.js/issues/10228), [#10308](https://github.com/angular/angular.js/issues/10308))
<add>- **$location:**
<add> - allow hash fragments with hashPrefix in hash-bang location urls
<add> ([2dc34a96](https://github.com/angular/angular.js/commit/2dc34a969956eea680be4c8d9f800556d110996a),
<add> [#9629](https://github.com/angular/angular.js/issues/9629), [#9635](https://github.com/angular/angular.js/issues/9635), [#10228](https://github.com/angular/angular.js/issues/10228), [#10308](https://github.com/angular/angular.js/issues/10308))
<add> - strip off empty hash segments when comparing
<add> ([e93710fe](https://github.com/angular/angular.js/commit/e93710fe0e4fb05ceee59a04f290692a5bec5d20),
<add> [#9635](https://github.com/angular/angular.js/issues/9635))
<add>- **$parse:** Follow JavaScript context for unbound functions
<add> ([429938da](https://github.com/angular/angular.js/commit/429938da1f45b8a649b8c77762fb0ae59b6d0cea))
<add>- **filterFilter:**
<add> - don't match primitive sub-expressions against any prop
<add> ([a75537d4](https://github.com/angular/angular.js/commit/a75537d461c92e3455e372ff5005bf0cad2d2e95))
<add> - ignore function properties and account for inherited properties
<add> ([5ced914c](https://github.com/angular/angular.js/commit/5ced914cc8625008e6249d5ac5942d5822287cc0),
<add> [#9984](https://github.com/angular/angular.js/issues/9984))
<add> - correctly handle deep expression objects
<add> ([f7cf8460](https://github.com/angular/angular.js/commit/f7cf846045b1e2fb39c62e304c61b44d5c805e31),
<add> [#7323](https://github.com/angular/angular.js/issues/7323), [#9698](https://github.com/angular/angular.js/issues/9698), [#9757](https://github.com/angular/angular.js/issues/9757))
<add>- **http:** preserve config object when resolving from cache
<add> ([facfec98](https://github.com/angular/angular.js/commit/facfec98412c0bb8678d578bade05ffef06a9e84),
<add> [#9004](https://github.com/angular/angular.js/issues/9004), [#9030](https://github.com/angular/angular.js/issues/9030))
<add>- **inputs:** ignoring input events in IE caused by placeholder changes or focus/blur on inputs with placeholders
<add> ([55d9db56](https://github.com/angular/angular.js/commit/55d9db56a6f7d29b16f8393612648080c6d535d6),
<add> [#9265](https://github.com/angular/angular.js/issues/9265))
<add>- **linky:** make urls starting with www. links, like markdown
<add> ([915a891a](https://github.com/angular/angular.js/commit/915a891ad4cdcaa5e47e976db8f4d402d230be77),
<add> [#10290](https://github.com/angular/angular.js/issues/10290))
<add>- **ngAnimate:** do not use jQuery class API
<add> ([40a537c2](https://github.com/angular/angular.js/commit/40a537c25f70ad556a41bb2d00ea3e257410e9af),
<add> [#10024](https://github.com/angular/angular.js/issues/10024), [#10329](https://github.com/angular/angular.js/issues/10329))
<add>- **ngMock:** allow numeric timeouts in $httpBackend mock
<add> ([acb066e8](https://github.com/angular/angular.js/commit/acb066e84a10483e1025eed295352b66747dbb8a),
<add> [#4891](https://github.com/angular/angular.js/issues/4891))
<add>- **ngModelController:** always use the most recent viewValue for validation
<add> ([2d6a0a1d](https://github.com/angular/angular.js/commit/2d6a0a1dc1e7125cab2e30244e35e97e11802843),
<add> [#10126](https://github.com/angular/angular.js/issues/10126), [#10299](https://github.com/angular/angular.js/issues/10299))
<add>- **ngSanitize:** exclude smart quotes at the end of the link
<add> ([7c6be43e](https://github.com/angular/angular.js/commit/7c6be43e83590798cffef63d076fb79d5296fba2),
<add> [#7307](https://github.com/angular/angular.js/issues/7307))
<add>- **ngmodel:** fixing many keys incorrectly marking inputs as dirty
<add> ([d21dff21](https://github.com/angular/angular.js/commit/d21dff21ed8beb015ad911f11d57cceb56fc439f))
<add>- **numberFilter:** numbers rounding to zero shouldn't be negative
<add> ([96c61fe7](https://github.com/angular/angular.js/commit/96c61fe756d7d3db011818bf0925e3d86ffff8ce),
<add> [#10278](https://github.com/angular/angular.js/issues/10278))
<add>- **orderBy:**
<add> - make object-to-primtiive behaviour work for objects with null prototype
<add> ([3aa57528](https://github.com/angular/angular.js/commit/3aa5752894419b4638d5c934879258fa6a1c0d07))
<add> - maintain order in array of objects when predicate is not provided
<add> ([8bfeddb5](https://github.com/angular/angular.js/commit/8bfeddb5d671017f4a21b8b46334ac816710b143),
<add> [#9566](https://github.com/angular/angular.js/issues/9566), [#9747](https://github.com/angular/angular.js/issues/9747), [#10311](https://github.com/angular/angular.js/issues/10311))
<add>- **parse:** fix operators associativity
<add> ([ed1243ff](https://github.com/angular/angular.js/commit/ed1243ffc7c2cb4bd5b4dece597597db8eb08e34))
<add>
<add>
<add>## Features
<add>
<add>- **$$jqLite:** export jqLite as a private service
<add> ([f2e7f875](https://github.com/angular/angular.js/commit/f2e7f875e2ad4b271c4e72ebd3860f905132eed9))
<add>- **$injector:** print caller name in "unknown provider" errors (when available)
<add> ([013b522c](https://github.com/angular/angular.js/commit/013b522c9e690665aecb0e0f656e4557a673ec09),
<add> [#8135](https://github.com/angular/angular.js/issues/8135), [#9721](https://github.com/angular/angular.js/issues/9721))
<add>- **jsonFilter:** add optional arg to define custom indentation
<add> ([1191edba](https://github.com/angular/angular.js/commit/1191edba4eaa15f675fa4ed047949a150843971b),
<add> [#9771](https://github.com/angular/angular.js/issues/9771))
<add>- **ngAria:** bind keypress on ng-click w/ option
<add> ([5481e2cf](https://github.com/angular/angular.js/commit/5481e2cfcd4d136a1c7f45cd4ce0fa1a8a15074d),
<add> [#10288](https://github.com/angular/angular.js/issues/10288))
<add>
<add>
<add>## Breaking Changes
<add>
<add>- **$location:** due to [2dc34a96](https://github.com/angular/angular.js/commit/2dc34a969956eea680be4c8d9f800556d110996a),
<add>
<add>
<add>We no longer throw an `ihshprfx` error if the URL after the base path
<add>contains only a hash fragment. Previously, if the base URL was `http://abc.com/base/`
<add>and the hashPrefix is `!` then trying to parse `http://abc.com/base/#some-fragment`
<add>would have thrown an error. Now we simply assume it is a normal fragment and
<add>that the path is empty, resulting `$location.absUrl() === "http://abc.com/base/#!/#some-fragment"`.
<add>
<add>This should not break any applications, but you can no longer rely on receiving the
<add>`ihshprfx` error for paths that have the syntax above. It is actually more similar
<add>to what currently happens for invalid extra paths anyway: If the base URL
<add>and hashPrfix are set up as above, then `http://abc.com/base/other/path` does not
<add>throw an error but just ignores the extra path: `http://abc.com/base`.
<add>
<add>Closes #9629
<add>Closes #9635
<add>Closes #10228
<add>Closes #10308
<add>
<add>
<ide> <a name="1.3.5"></a>
<ide> # 1.3.5 cybernetic-mercantilism (2014-12-01)
<ide> | 1 |
Ruby | Ruby | restore build_bottle defaults | eaea27c960de3bf76fc9976bfad037c0a559018d | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def initialize(formula)
<ide> @ignore_deps = false
<ide> @only_deps = false
<ide> @build_from_source = ARGV.build_from_source? || ARGV.build_all_from_source?
<del> @build_bottle = ARGV.build_bottle?
<add> @build_bottle = false
<ide> @force_bottle = ARGV.force_bottle?
<ide> @interactive = false
<ide> @git = false
<ide> def install_dependency(dep, inherited_options)
<ide> fi.options |= inherited_options
<ide> fi.options &= df.options
<ide> fi.build_from_source = ARGV.build_formula_from_source?(df)
<del> fi.build_bottle = false
<ide> fi.force_bottle = false
<ide> fi.verbose = verbose?
<ide> fi.quieter = quieter? | 1 |
Python | Python | add evaluate to test dependencies | af1e6b4d87cb3ec008a91319b8599560337bf254 | <ide><path>setup.py
<ide> "datasets",
<ide> "deepspeed>=0.6.5",
<ide> "dill<0.3.5",
<add> "evaluate",
<ide> "fairscale>0.3",
<ide> "faiss-cpu",
<ide> "fastapi",
<ide> def run(self):
<ide> "psutil",
<ide> "datasets",
<ide> "dill",
<add> "evaluate",
<ide> "pytest-timeout",
<ide> "black",
<ide> "sacrebleu",
<ide><path>src/transformers/dependency_versions_table.py
<ide> "datasets": "datasets",
<ide> "deepspeed": "deepspeed>=0.6.5",
<ide> "dill": "dill<0.3.5",
<add> "evaluate": "evaluate",
<ide> "fairscale": "fairscale>0.3",
<ide> "faiss-cpu": "faiss-cpu",
<ide> "fastapi": "fastapi", | 2 |
Javascript | Javascript | add xhr docs | c863514660fed43058c93b288cdf68d476a9cabc | <ide><path>src/angular-mocks.js
<ide> * Built-in mocks:
<ide> *
<ide> * * {@link angular.mock.service.$browser $browser } - A mock implementation of the browser.
<del> * * {@link angular.mock.service.$exceptionHandler $exceptionHandler } - A mock implementation of the
<del> * angular service exception handler.
<add> * * {@link angular.mock.service.$exceptionHandler $exceptionHandler } - A mock implementation of
<add> * the angular service exception handler.
<ide> * * {@link angular.mock.service.$log $log } - A mock implementation of the angular service log.
<ide> */
<ide> angular.mock = {};
<ide> angular.mock = {};
<ide> * @workInProgress
<ide> * @ngdoc service
<ide> * @name angular.mock.service.$browser
<add> *
<add> * @description
<add> * This service is a mock implementation of {@link angular.service.$browser}. It provides fake
<add> * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
<add> * cookies.
<add> *
<add> * This implementation is automatically available and replaces regular `$browser` service in tests
<add> * when `angular-mocks.js` is loaded.
<add> *
<add> * The api of this service is the same as the real {@link angular.service.$browser $browser}, except
<add> * that there are several helper methods available which can be used in tests.
<add> *
<add> * The following apis can be used in tests:
<add> *
<add> * - {@link angular.mock.service.$browser.xhr $browser.xhr} — enables testing of code that uses
<add> * the {@link angular.service.$xhr $xhr service} to make XmlHttpRequests.
<add> * - $browser.defer — enables testing of code that uses
<add> * {@link angular.service.$defer $defer service} for executing functions via the `setTimeout` api.
<ide> */
<ide> function MockBrowser() {
<ide> var self = this,
<ide> function MockBrowser() {
<ide> };
<ide>
<ide>
<add> /**
<add> * @ngdoc function
<add> * @name angular.mock.service.$browser.xhr
<add> *
<add> * @description
<add> * Generic method for training browser to expect a request in a test and respond to it.
<add> *
<add> * See also convenience methods for browser training:
<add> *
<add> * - {@link angular.mock.service.$browser.xhr.expectGET $browser.xhr.expectGET}
<add> * - {@link angular.mock.service.$browser.xhr.expectPOST $browser.xhr.expectPOST}
<add> * - {@link angular.mock.service.$browser.xhr.expectPUT $browser.xhr.expectPUT}
<add> * - {@link angular.mock.service.$browser.xhr.expectDELETE $browser.xhr.expectDELETE}
<add> * - {@link angular.mock.service.$browser.xhr.expectJSON $browser.xhr.expectJSON}
<add> *
<add> * To flush pending requests in tests use
<add> * {@link angular.mock.service.$browser.xhr.flush $browser.xhr.flush}.
<add> *
<add> * @param {string} method Expected HTTP method.
<add> * @param {string} url Url path for which a request is expected.
<add> * @param {(object|string)=} data Expected body of the (POST) HTTP request.
<add> * @param {function(number, *)} callback Callback to call when response is flushed.
<add> * @param {object} headers Key-value pairs of expected headers.
<add> * @returns {object} Response configuration object. You can call its `respond()` method to
<add> * configure what should the browser mock return when the response is
<add> * {@link angular.mock.service.$browser.xhr.flush flushed}.
<add> */
<ide> self.xhr = function(method, url, data, callback, headers) {
<ide> headers = headers || {};
<ide> if (data && angular.isObject(data)) data = angular.toJson(data);
<ide> function MockBrowser() {
<ide> }
<ide> };
<ide> };
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.mock.service.$browser.xhr.expectGET
<add> *
<add> * @description
<add> * Trains browser to expect a `GET` request and respond to it.
<add> *
<add> * @param {string} url Url path for which a request is expected.
<add> * @returns {object} Response configuration object. You can call its `respond()` method to
<add> * configure what should the browser mock return when the response is
<add> * {@link angular.mock.service.$browser.xhr.flush flushed}.
<add> */
<ide> self.xhr.expectGET = angular.bind(self, self.xhr.expect, 'GET');
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.mock.service.$browser.xhr.expectPOST
<add> *
<add> * @description
<add> * Trains browser to expect a `POST` request and respond to it.
<add> *
<add> * @param {string} url Url path for which a request is expected.
<add> * @returns {object} Response configuration object. You can call its `respond()` method to
<add> * configure what should the browser mock return when the response is
<add> * {@link angular.mock.service.$browser.xhr.flush flushed}.
<add> */
<ide> self.xhr.expectPOST = angular.bind(self, self.xhr.expect, 'POST');
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.mock.service.$browser.xhr.expectDELETE
<add> *
<add> * @description
<add> * Trains browser to expect a `DELETE` request and respond to it.
<add> *
<add> * @param {string} url Url path for which a request is expected.
<add> * @returns {object} Response configuration object. You can call its `respond()` method to
<add> * configure what should the browser mock return when the response is
<add> * {@link angular.mock.service.$browser.xhr.flush flushed}.
<add> */
<ide> self.xhr.expectDELETE = angular.bind(self, self.xhr.expect, 'DELETE');
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.mock.service.$browser.xhr.expectPUT
<add> *
<add> * @description
<add> * Trains browser to expect a `PUT` request and respond to it.
<add> *
<add> * @param {string} url Url path for which a request is expected.
<add> * @returns {object} Response configuration object. You can call its `respond()` method to
<add> * configure what should the browser mock return when the response is
<add> * {@link angular.mock.service.$browser.xhr.flush flushed}.
<add> */
<ide> self.xhr.expectPUT = angular.bind(self, self.xhr.expect, 'PUT');
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.mock.service.$browser.xhr.expectJSON
<add> *
<add> * @description
<add> * Trains browser to expect a `JSON` request and respond to it.
<add> *
<add> * @param {string} url Url path for which a request is expected.
<add> * @returns {object} Response configuration object. You can call its `respond()` method to
<add> * configure what should the browser mock return when the response is
<add> * {@link angular.mock.service.$browser.xhr.flush flushed}.
<add> */
<ide> self.xhr.expectJSON = angular.bind(self, self.xhr.expect, 'JSON');
<add>
<add> /**
<add> * @ngdoc function
<add> * @name angular.mock.service.$browser.xhr.flush
<add> *
<add> * @description
<add> * Flushes all pending requests and executes xhr callbacks with the trained response as the
<add> * argument.
<add> */
<ide> self.xhr.flush = function() {
<ide> if (requests.length == 0) {
<ide> throw new Error("No xhr requests to be flushed!"); | 1 |
Python | Python | fix dimensionality bug | 3e52915fa7106a739aa6f9feda9937961ce25068 | <ide><path>transformers/modeling_roberta.py
<ide> def __init__(self, config):
<ide>
<ide> def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
<ide> if position_ids is None:
<del>
<ide> if input_ids is not None:
<ide> # Create the position ids from the input token ids. Any padded tokens remain padded.
<ide> position_ids = self.create_position_ids_from_input_ids(input_ids).to(input_ids.device)
<ide> def create_position_ids_from_inputs_embeds(self, inputs_embeds):
<ide>
<ide> position_ids = torch.arange(self.padding_idx+1, sequence_length+self.padding_idx+1, dtype=torch.long,
<ide> device=inputs_embeds.device)
<del> return position_ids.unsqueeze(0)
<add> return position_ids.unsqueeze(0).expand(input_shape)
<ide>
<ide>
<ide> ROBERTA_START_DOCSTRING = r""" The RoBERTa model was proposed in
<ide><path>transformers/tests/modeling_roberta_test.py
<ide> def test_create_position_ids_respects_padding_index(self):
<ide> ]])
<ide>
<ide> position_ids = model.create_position_ids_from_input_ids(input_ids)
<add> self.assertEqual(
<add> position_ids.shape,
<add> expected_positions.shape
<add> )
<ide> self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
<ide>
<ide> def test_create_position_ids_from_inputs_embeds(self):
<ide> def test_create_position_ids_from_inputs_embeds(self):
<ide> first available non-padding position index is RobertaEmbeddings.padding_idx + 1
<ide> """
<ide> config = self.model_tester.prepare_config_and_inputs()[0]
<del> model = RobertaEmbeddings(config=config)
<del>
<del> input_ids = torch.Tensor(1, 4, 30)
<del> expected_positions = torch.as_tensor([[
<del> 0 + model.padding_idx + 1,
<del> 1 + model.padding_idx + 1,
<del> 2 + model.padding_idx + 1,
<del> 3 + model.padding_idx + 1,
<del> ]])
<del> position_ids = model.create_position_ids_from_inputs_embeds(input_ids)
<del> self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
<add> embeddings = RobertaEmbeddings(config=config)
<add>
<add> inputs_embeds = torch.Tensor(2, 4, 30)
<add> expected_single_positions = [
<add> 0 + embeddings.padding_idx + 1,
<add> 1 + embeddings.padding_idx + 1,
<add> 2 + embeddings.padding_idx + 1,
<add> 3 + embeddings.padding_idx + 1,
<add> ]
<add> expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions])
<add> position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds)
<add> self.assertEqual(
<add> position_ids.shape,
<add> expected_positions.shape
<add> )
<add> self.assertTrue(
<add> torch.all(torch.eq(position_ids, expected_positions))
<add> )
<ide>
<ide>
<ide> class RobertaModelIntegrationTest(unittest.TestCase): | 2 |
Ruby | Ruby | remove scriptfileformula test | bc650a4f0d3689cab306a66f2a874aea1cdc7c24 | <ide><path>Library/Homebrew/test/test_formula_installer.rb
<ide> def test_a_basic_install
<ide> assert_equal 3, bin.children.length
<ide> end
<ide> end
<del>
<del> def test_script_install
<del> mktmpdir do |dir|
<del> name = "test_script_formula"
<del> path = Pathname.new(dir)+"#{name}.rb"
<del>
<del> path.write <<-EOS.undent
<del> class #{Formulary.class_s(name)} < ScriptFileFormula
<del> url "file://#{File.expand_path(__FILE__)}"
<del> version "1"
<del> end
<del> EOS
<del>
<del> f = Formulary.factory(path.to_s)
<del>
<del> temporary_install(f) { assert_equal 1, f.bin.children.length }
<del> end
<del> end
<ide> end | 1 |
PHP | PHP | use the authenticate middleware from core | 945052508f6c7a00909fd91e5bb9be14d0cbac53 | <ide><path>app/Http/Kernel.php
<ide> class Kernel extends HttpKernel
<ide> * @var array
<ide> */
<ide> protected $routeMiddleware = [
<del> 'auth' => \App\Http\Middleware\Authenticate::class,
<add> 'auth' => \Illuminate\Http\Middleware\Authenticate::class,
<ide> 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
<ide> 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
<ide> 'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
<ide><path>app/Http/Middleware/Authenticate.php
<del><?php
<del>
<del>namespace App\Http\Middleware;
<del>
<del>use Closure;
<del>use Illuminate\Support\Facades\Auth;
<del>use Illuminate\Auth\AuthenticationException;
<del>
<del>class Authenticate
<del>{
<del> /**
<del> * Handle an incoming request.
<del> *
<del> * @param \Illuminate\Http\Request $request
<del> * @param \Closure $next
<del> * @param string ...$guards
<del> * @return mixed
<del> *
<del> * @throws \Illuminate\Auth\AuthenticationException
<del> */
<del> public function handle($request, Closure $next, ...$guards)
<del> {
<del> $this->authenticate($guards);
<del>
<del> return $next($request);
<del> }
<del>
<del> /**
<del> * Determine if the user is logged in to any of the given guards.
<del> *
<del> * @param array $guards
<del> * @return void
<del> *
<del> * @throws \Illuminate\Auth\AuthenticationException
<del> */
<del> protected function authenticate(array $guards)
<del> {
<del> if (count($guards) <= 1) {
<del> Auth::guard(array_first($guards))->authenticate();
<del>
<del> return Auth::shouldUse($guard);
<del> }
<del>
<del> foreach ($guards as $guard) {
<del> if (Auth::guard($guard)->check()) {
<del> return Auth::shouldUse($guard);
<del> }
<del> }
<del>
<del> throw new AuthenticationException;
<del> }
<del>} | 2 |
Text | Text | remove unopened closing brace | 714bb17aea08dc043b1b3e7e7c87b7afa78c5a26 | <ide><path>guides/source/getting_started.md
<ide> it look as follows:
<ide> ```html+erb
<ide> <h1>Editing post</h1>
<ide>
<del><%= form_for :post, url: post_path(@post.id) },
<del>method: :patch do |f| %>
<add><%= form_for :post, url: post_path(@post.id), method: :patch do |f| %>
<ide> <% if @post.errors.any? %>
<ide> <div id="errorExplanation">
<ide> <h2><%= pluralize(@post.errors.count, "error") %> prohibited | 1 |
Python | Python | fix plugins path | 6bef4843be1c2e3c33441d5395524ceb192dd950 | <ide><path>glances/core/glances_globals.py
<ide> print('psutil 2.0 or higher is needed. Glances cannot start.')
<ide> sys.exit(1)
<ide>
<del># Path definitions
<del>work_path = os.path.realpath(os.path.dirname(__file__))
<del>appname_path = os.path.split(sys.argv[0])[0]
<del>sys_prefix = os.path.realpath(os.path.dirname(appname_path))
<del>
<ide> # PY3?
<ide> is_py3 = sys.version_info >= (3, 3)
<ide>
<ide> is_mac = sys.platform.startswith('darwin')
<ide> is_windows = sys.platform.startswith('win')
<ide>
<add># Path definitions
<add>work_path = os.path.realpath(os.path.dirname(__file__))
<add>appname_path = os.path.split(sys.argv[0])[0]
<add>sys_prefix = os.path.realpath(os.path.dirname(appname_path))
<add>
<add># Set the plugins path
<add>plugins_path = os.path.realpath(os.path.join(work_path, '..', 'plugins'))
<add>sys_path = sys.path[:]
<add>sys.path.insert(0, plugins_path)
<add>
<ide> # i18n
<ide> gettext_domain = __appname__
<ide> i18n_path = os.path.realpath(os.path.join(work_path, '..', '..', 'i18n'))
<ide><path>glances/core/glances_stats.py
<ide> import os
<ide> import sys
<ide>
<add>from glances.core.glances_globals import plugins_path, sys_path
<add>
<ide>
<ide> class GlancesStats(object):
<ide> """
<ide> def load_plugins(self, args=None):
<ide> """
<ide> Load all plugins in the "plugins" folder
<ide> """
<del>
<del> # Set the plugins' path
<del> plug_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../plugins")
<del> sys.path.insert(0, plug_dir)
<del>
<ide> header = "glances_"
<del> for plug in os.listdir(plug_dir):
<del> if (plug.startswith(header) and
<del> plug.endswith(".py") and
<del> plug != (header + "plugin.py")):
<add> for item in os.listdir(plugins_path):
<add> if (item.startswith(header) and
<add> item.endswith(".py") and
<add> item != (header + "plugin.py")):
<ide> # Import the plugin
<del> m = __import__(os.path.basename(plug)[:-3])
<add> plugin = __import__(os.path.basename(item)[:-3])
<ide> # Add the plugin to the dictionary
<ide> # The key is the plugin name
<ide> # for example, the file glances_xxx.py
<ide> # generate self._plugins_list["xxx"] = ...
<del> plugname = os.path.basename(plug)[len(header):-3].lower()
<del> self._plugins[plugname] = m.Plugin(args=args)
<add> plugin_name = os.path.basename(item)[len(header):-3].lower()
<add> self._plugins[plugin_name] = plugin.Plugin(args=args)
<add> # Restoring system path
<add> sys.path = sys_path
<ide>
<ide> def getAllPlugins(self):
<ide> """
<ide> def __init__(self):
<ide>
<ide> def set_plugins(self, input_plugins):
<ide> """
<del> Set the plugin list accoring to the Glances' server
<add> Set the plugin list according to the Glances server
<ide> """
<del>
<del> # Set the plugins' path
<del> plug_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../plugins")
<del> sys.path.insert(0, plug_dir)
<del>
<ide> header = "glances_"
<del> for plug in input_plugins:
<add> for item in input_plugins:
<ide> # Import the plugin
<del> m = __import__(header + plug)
<del> # Add the plugin to the dictionnary
<add> plugin = __import__(header + item)
<add> # Add the plugin to the dictionary
<ide> # The key is the plugin name
<ide> # for example, the file glances_xxx.py
<ide> # generate self._plugins_list["xxx"] = ...
<del> # print "DEBUG: Init %s plugin" % plug
<del> self._plugins[plug] = m.Plugin()
<add> # print "DEBUG: Init %s plugin" % item
<add> self._plugins[item] = plugin.Plugin()
<add> # Restoring system path
<add> sys.path = sys_path
<ide>
<ide>
<ide> class GlancesStatsClientSNMP(GlancesStats): | 2 |
Ruby | Ruby | add view tests for mysql | bb0d70788a2cddb6598228806150b55d87e2e81d | <ide><path>activerecord/test/cases/adapters/postgresql/view_test.rb
<del>require "cases/helper"
<del>require "cases/view_test"
<del>
<del>class UpdateableViewTest < ActiveRecord::PostgreSQLTestCase
<del> fixtures :books
<del>
<del> class PrintedBook < ActiveRecord::Base
<del> self.primary_key = "id"
<del> end
<del>
<del> setup do
<del> @connection = ActiveRecord::Base.connection
<del> @connection.execute <<-SQL
<del> CREATE VIEW printed_books
<del> AS SELECT id, name, status, format FROM books WHERE format = 'paperback'
<del> SQL
<del> end
<del>
<del> teardown do
<del> @connection.execute "DROP VIEW printed_books" if @connection.table_exists? "printed_books"
<del> end
<del>
<del> def test_update_record
<del> book = PrintedBook.first
<del> book.name = "AWDwR"
<del> book.save!
<del> book.reload
<del> assert_equal "AWDwR", book.name
<del> end
<del>
<del> def test_insert_record
<del> PrintedBook.create! name: "Rails in Action", status: 0, format: "paperback"
<del>
<del> new_book = PrintedBook.last
<del> assert_equal "Rails in Action", new_book.name
<del> end
<del>
<del> def test_update_record_to_fail_view_conditions
<del> book = PrintedBook.first
<del> book.format = "ebook"
<del> book.save!
<del>
<del> assert_raises ActiveRecord::RecordNotFound do
<del> book.reload
<del> end
<del> end
<del>end
<del>
<del>if ActiveRecord::Base.connection.respond_to?(:supports_materialized_views?) &&
<del> ActiveRecord::Base.connection.supports_materialized_views?
<del>class MaterializedViewTest < ActiveRecord::PostgreSQLTestCase
<del> include ViewBehavior
<del>
<del> private
<del> def create_view(name, query)
<del> @connection.execute "CREATE MATERIALIZED VIEW #{name} AS #{query}"
<del> end
<del>
<del> def drop_view(name)
<del> @connection.execute "DROP MATERIALIZED VIEW #{name}" if @connection.table_exists? name
<del>
<del> end
<del>end
<del>end
<ide><path>activerecord/test/cases/view_test.rb
<ide> def test_does_not_have_a_primary_key
<ide> assert_nil Paperback.primary_key
<ide> end
<ide> end
<add>
<add># sqlite dose not support CREATE, INSERT, and DELETE for VIEW
<add>if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
<add>class UpdateableViewTest < ActiveRecord::TestCase
<add> self.use_transactional_tests = false
<add> fixtures :books
<add>
<add> class PrintedBook < ActiveRecord::Base
<add> self.primary_key = "id"
<add> end
<add>
<add> setup do
<add> @connection = ActiveRecord::Base.connection
<add> @connection.execute <<-SQL
<add> CREATE VIEW printed_books
<add> AS SELECT id, name, status, format FROM books WHERE format = 'paperback'
<add> SQL
<add> end
<add>
<add> teardown do
<add> @connection.execute "DROP VIEW printed_books" if @connection.table_exists? "printed_books"
<add> end
<add>
<add> def test_update_record
<add> book = PrintedBook.first
<add> book.name = "AWDwR"
<add> book.save!
<add> book.reload
<add> assert_equal "AWDwR", book.name
<add> end
<add>
<add> def test_insert_record
<add> PrintedBook.create! name: "Rails in Action", status: 0, format: "paperback"
<add>
<add> new_book = PrintedBook.last
<add> assert_equal "Rails in Action", new_book.name
<add> end
<add>
<add> def test_update_record_to_fail_view_conditions
<add> book = PrintedBook.first
<add> book.format = "ebook"
<add> book.save!
<add>
<add> assert_raises ActiveRecord::RecordNotFound do
<add> book.reload
<add> end
<add> end
<add>end
<add>end # end fo `if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)`
<add>end # end fo `if ActiveRecord::Base.connection.supports_views?`
<add>
<add>if ActiveRecord::Base.connection.respond_to?(:supports_materialized_views?) &&
<add> ActiveRecord::Base.connection.supports_materialized_views?
<add>class MaterializedViewTest < ActiveRecord::PostgreSQLTestCase
<add> include ViewBehavior
<add>
<add> private
<add> def create_view(name, query)
<add> @connection.execute "CREATE MATERIALIZED VIEW #{name} AS #{query}"
<add> end
<add>
<add> def drop_view(name)
<add> @connection.execute "DROP MATERIALIZED VIEW #{name}" if @connection.table_exists? name
<add>
<add> end
<add>end
<ide> end | 2 |
Python | Python | add documentation about url_for's default scheme | b49074eb6b19d8f5fdb3301a6e50f11845dd530d | <ide><path>flask/helpers.py
<ide> def external_url_handler(error, endpoint, values):
<ide> address can be changed via `SERVER_NAME` configuration variable which
<ide> defaults to `localhost`.
<ide> :param _scheme: a string specifying the desired URL scheme. The `_external`
<del> parameter must be set to `True` or a `ValueError` is raised.
<add> parameter must be set to `True` or a `ValueError` is raised. The default
<add> behavior uses the same scheme as the current request, or
<add> ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no
<add> request context is available.
<ide> :param _anchor: if provided this is added as anchor to the URL.
<ide> :param _method: if provided this explicitly specifies an HTTP method.
<ide> """ | 1 |
PHP | PHP | use contract for event dispatcher | 4036d0becae1e5fedbcb86eda44bb756dff44d8a | <ide><path>src/Illuminate/Events/Dispatcher.php
<ide>
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
<add>use Illuminate\Contracts\Container\Container as ContainerContract;
<ide>
<ide> class Dispatcher implements DispatcherContract {
<ide>
<ide> /**
<ide> * The IoC container instance.
<ide> *
<del> * @var \Illuminate\Container\Container
<add> * @var \Illuminate\Contracts\Container\Container
<ide> */
<ide> protected $container;
<ide>
<ide> class Dispatcher implements DispatcherContract {
<ide> /**
<ide> * Create a new event dispatcher instance.
<ide> *
<del> * @param \Illuminate\Container\Container $container
<add> * @param \Illuminate\Contracts\Container\Container $container
<ide> * @return void
<ide> */
<del> public function __construct(Container $container = null)
<add> public function __construct(ContainerContract $container = null)
<ide> {
<ide> $this->container = $container ?: new Container;
<ide> } | 1 |
Javascript | Javascript | use correct batch size for batchedhash | d806cf5294a010f5c3280a38ab7500c681ca7c11 | <ide><path>lib/util/hash/BatchedHash.js
<ide> "use strict";
<ide>
<ide> const Hash = require("../Hash");
<del>
<del>const MAX_STRING_LENGTH = 21845;
<add>const MAX_SHORT_STRING = require("./wasm-hash").MAX_SHORT_STRING;
<ide>
<ide> class BatchedHash extends Hash {
<ide> constructor(hash) {
<ide> class BatchedHash extends Hash {
<ide> if (
<ide> typeof data === "string" &&
<ide> inputEncoding === this.encoding &&
<del> this.string.length + data.length < MAX_STRING_LENGTH
<add> this.string.length + data.length < MAX_SHORT_STRING
<ide> ) {
<ide> this.string += data;
<ide> return this;
<ide> class BatchedHash extends Hash {
<ide> this.string = undefined;
<ide> }
<ide> if (typeof data === "string") {
<del> if (data.length < MAX_STRING_LENGTH) {
<add> if (data.length < MAX_SHORT_STRING) {
<ide> this.string = data;
<ide> this.encoding = inputEncoding;
<ide> } else {
<ide><path>lib/util/hash/wasm-hash.js
<ide> const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
<ide> };
<ide>
<ide> module.exports = create;
<add>module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING; | 2 |
Javascript | Javascript | make observer static | 448c29120b2e0a11e8b8d26a2645cf55bb8a83c7 | <ide><path>packages/ember-metal/lib/mixin.js
<ide> export function aliasMethod(methodName) {
<ide> @param {Function} func
<ide> @return func
<ide> @public
<add> @static
<ide> */
<ide> export function observer(...args) {
<ide> let _paths, func;
<ide> export function observer(...args) {
<ide>
<ide> ```javascript
<ide> import EmberObject from '@ember/object';
<del>
<add>
<ide> EmberObject.extend({
<ide> valueObserver: Ember.immediateObserver('value', function() {
<ide> // Executes whenever the "value" property changes | 1 |
Text | Text | add 1.2.31 and 1.4.13 release info | 8d394de91fd96f87afdbb277520b111232ec4bdb | <ide><path>CHANGELOG.md
<add><a name="1.4.13"></a>
<add># 1.4.13 croaking-elderweed (2016-10-10)
<add>
<add>## Bug Fixes
<add>- **input:** ensure that hidden input values are correct after history back
<add> ([693d1334](https://github.com/angular/angular.js/commit/693d1334566f78987f5a361a100db4f889f35abd)
<add>
<add>
<add><a name="1.2.31"></a>
<add># 1.2.31 barking-moustache (2016-10-10)
<add>
<add>## Bug Fixes
<add>- **input:** ensure that hidden input values are correct after history back
<add> ([7ec663fc](https://github.com/angular/angular.js/commit/7ec663fc708aa7a9a9ce62d2306f24d7a733a86d)
<add>
<add>
<add><a name="1.4.12"></a>
<add># 1.4.12
<add>
<add>*Invalid release*
<add>
<add>
<ide> <a name="1.5.8"></a>
<ide> # 1.5.8 arbitrary-fallbacks (2016-07-22)
<ide> | 1 |
PHP | PHP | fix cookie issues | bb9db21af137344feffa192fcabe4e439c8b0f60 | <ide><path>src/Illuminate/Cookie/Middleware/EncryptCookies.php
<ide> protected function decrypt(Request $request)
<ide> $value = $this->decryptCookie($key, $cookie);
<ide>
<ide> $request->cookies->set(
<del> $key, strpos($value, sha1($key).'|') !== 0 ? null : substr($value, 41)
<add> $key, strpos($value, sha1($key.'v2').'|') !== 0 ? null : substr($value, 41)
<ide> );
<ide> } catch (DecryptException $e) {
<ide> $request->cookies->set($key, null);
<ide> protected function encrypt(Response $response)
<ide> $response->headers->setCookie($this->duplicate(
<ide> $cookie,
<ide> $this->encrypter->encrypt(
<del> sha1($cookie->getName()).'|'.$cookie->getValue(),
<add> sha1($cookie->getName().'v2').'|'.$cookie->getValue(),
<ide> static::serialized($cookie->getName())
<ide> )
<ide> ));
<ide><path>src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php
<ide> protected function getTokenFromRequest($request)
<ide> $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
<ide>
<ide> if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
<del> $token = $this->encrypter->decrypt($header, static::serialized());
<add> $token = substr($this->encrypter->decrypt($header, static::serialized()), 41);
<ide> }
<ide>
<ide> return $token;
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php
<ide> protected function prepareCookiesForRequest()
<ide> return array_merge($this->defaultCookies, $this->unencryptedCookies);
<ide> }
<ide>
<del> return collect($this->defaultCookies)->map(function ($value) {
<del> return encrypt($value, false);
<add> return collect($this->defaultCookies)->map(function ($value, $key) {
<add> return encrypt(sha1($key.'v2').'|'.$value, false);
<ide> })->merge($this->unencryptedCookies)->all();
<ide> }
<ide> | 3 |
Javascript | Javascript | avoid extra var in coreobject during prod builds | b6068455ba1296bb50d1ba5631cb02f9ad84e617 | <ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> function makeCtor() {
<ide> initProperties = [arguments[0]];
<ide> }
<ide>
<del> let beforeInitCalled = true;
<add> let beforeInitCalled; // only used in debug builds to enable the proxy trap
<add>
<add> // using DEBUG here to avoid the extraneous variable when not needed
<add> if (DEBUG) {
<add> beforeInitCalled = true;
<add> }
<ide>
<ide> if (DEBUG && MANDATORY_GETTER && EMBER_METAL_ES5_GETTERS && HAS_NATIVE_PROXY && typeof self.unknownProperty === 'function') {
<ide> let messageFor = (obj, property) => {
<ide> function makeCtor() {
<ide> if (ENV._ENABLE_BINDING_SUPPORT) {
<ide> Mixin.finishPartial(self, m);
<ide> }
<del> beforeInitCalled = false;
<add>
<add> // using DEBUG here to avoid the extraneous variable when not needed
<add> if (DEBUG) {
<add> beforeInitCalled = false;
<add> }
<ide> self.init(...arguments);
<ide>
<ide> self[POST_INIT](); | 1 |
Javascript | Javascript | add aspath on the server | 03324880a8fce13e99cd3a7a9fe1fc5fde7fa2c8 | <ide><path>server/render.js
<ide> async function doRender (req, res, pathname, query, {
<ide> const app = createElement(App, {
<ide> Component: enhancer(Component),
<ide> props,
<del> router: new Router(pathname, query)
<add> router: new Router(pathname, query, asPath)
<ide> })
<ide>
<ide> const render = staticMarkup ? renderToStaticMarkup : renderToString
<ide><path>test/integration/basic/pages/nav/with-hoc.js
<ide> const Link = withRouter(({router, children, href}) => {
<ide>
<ide> return (
<ide> <div>
<del> <span>Current path: {router.pathname}</span>
<add> <span id='pathname'>Current path: {router.pathname}</span>
<add> <span id='asPath'>Current asPath: {router.asPath}</span>
<ide> <a href='#' onClick={handleClick}>{children}</a>
<ide> </div>
<ide> )
<ide><path>test/integration/basic/test/client-navigation.js
<ide> export default (context, render) => {
<ide> it('should navigate as expected', async () => {
<ide> const browser = await webdriver(context.appPort, '/nav/with-hoc')
<ide>
<del> const spanText = await browser.elementByCss('span').text()
<del> expect(spanText).toBe('Current path: /nav/with-hoc')
<add> const pathname = await browser.elementByCss('#pathname').text()
<add> expect(pathname).toBe('Current path: /nav/with-hoc')
<add>
<add> const asPath = await browser.elementByCss('#asPath').text()
<add> expect(asPath).toBe('Current asPath: /nav/with-hoc')
<ide>
<ide> const text = await browser
<ide> .elementByCss('.nav-with-hoc a').click()
<ide><path>test/integration/basic/test/rendering.js
<del>/* global describe, test, expect */
<add>/* global describe, test, it, expect */
<ide>
<ide> import cheerio from 'cheerio'
<ide>
<ide> export default function ({ app }, suiteName, render) {
<ide> expect($('h1').text()).toBe('404')
<ide> expect($('h2').text()).toBe('This page could not be found.')
<ide> })
<add>
<add> describe('with the HOC based router', () => {
<add> it('should navigate as expected', async () => {
<add> const $ = await get$('/nav/with-hoc')
<add>
<add> expect($('#pathname').text()).toBe('Current path: /nav/with-hoc')
<add> })
<add>
<add> it('should include asPath', async () => {
<add> const $ = await get$('/nav/with-hoc')
<add>
<add> expect($('#asPath').text()).toBe('Current asPath: /nav/with-hoc')
<add> })
<add> })
<ide> })
<ide> }
<ide><path>test/lib/next-test-utils.js
<ide> export const nextBuild = build
<ide> export const nextExport = _export
<ide> export const pkg = _pkg
<ide>
<del>export function renderViaAPI (app, pathname, query = {}) {
<del> const url = `${pathname}?${qs.stringify(query)}`
<add>export function renderViaAPI (app, pathname, query) {
<add> const url = `${pathname}${query ? `?${qs.stringify(query)}` : ''}`
<ide> return app.renderToHTML({ url }, {}, pathname, query)
<ide> }
<ide>
<del>export function renderViaHTTP (appPort, pathname, query = {}) {
<del> const url = `http://localhost:${appPort}${pathname}?${qs.stringify(query)}`
<add>export function renderViaHTTP (appPort, pathname, query) {
<add> const url = `http://localhost:${appPort}${pathname}${query ? `?${qs.stringify(query)}` : ''}`
<ide> return fetch(url).then((res) => res.text())
<ide> }
<ide> | 5 |
Text | Text | add lucid to list of users | c7848545b32937681275371dc1ae82c5305f36a9 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> * [Kogan.com](https://github.com/kogan) [[@geeknam](https://github.com/geeknam)]
<ide> * [LendUp](https://www.lendup.com/) [[@lendup](https://github.com/lendup)]
<ide> * [LingoChamp](http://www.liulishuo.com/) [[@haitaoyao](https://github.com/haitaoyao)]
<add>* [Lucid](http://luc.id) [[@jbrownlucid](https://github.com/jbrownlucid) & [@kkourtchikov](https://github.com/kkourtchikov)]
<ide> * [Lyft](https://www.lyft.com/)[[@SaurabhBajaj](https://github.com/SaurabhBajaj)]
<ide> * [Sense360](https://github.com/Sense360) [[@kamilmroczek](https://github.com/KamilMroczek)]
<ide> * [Sidecar](https://hello.getsidecar.com/) [[@getsidecar](https://github.com/getsidecar)] | 1 |
Javascript | Javascript | reduce unnecessary sync rimraf retries | d7b8ae72d97557571c577a865c37e7a5b196a332 | <ide><path>lib/internal/fs/rimraf.js
<ide> function _rmdirSync(path, options, originalErr) {
<ide> rimrafSync(join(path, child), options);
<ide> });
<ide>
<del> for (let i = 1; i <= options.maxRetries + 1; i++) {
<add> const tries = options.maxRetries + 1;
<add>
<add> for (let i = 1; i <= tries; i++) {
<ide> try {
<ide> return rmdirSync(path, options);
<del> } catch {
<del> if (options.retryDelay > 0)
<add> } catch (err) {
<add> // Only sleep if this is not the last try, and the delay is greater
<add> // than zero, and an error was encountered that warrants a retry.
<add> if (retryErrorCodes.has(err.code) &&
<add> i < tries &&
<add> options.retryDelay > 0) {
<ide> sleep(i * options.retryDelay);
<add> }
<ide> }
<ide> }
<ide> } | 1 |
Python | Python | fix typo in gpt2doubleheadsmodel docs | 1321356bdf54a6c11048851bff98c2a0181f2084 | <ide><path>src/transformers/models/gpt2/modeling_gpt2.py
<ide> def forward(
<ide> 1[``.
<ide> labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide> Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
<del> ``labels = input_ids`` Indices are selected in ``[-1, 0, ..., config.vocab_size]`` All labels set to
<del> ``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ..., config.vocab_size]``
<add> ``labels = input_ids`` Indices are selected in ``[-100, 0, ..., config.vocab_size - 1]`` All labels set to
<add> ``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ..., config.vocab_size - 1]``
<ide> mc_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size)`, `optional`):
<ide> Labels for computing the multiple choice classification loss. Indices should be in ``[0, ...,
<ide> num_choices]`` where `num_choices` is the size of the second dimension of the input tensors. (see | 1 |
Text | Text | fix a broken link | b83985bc6b964992015bc1750ec9b9bab46f3fd8 | <ide><path>guides/source/asset_pipeline.md
<ide> Customizing the Pipeline
<ide> ### CSS Compression
<ide>
<ide> There is currently one option for compressing CSS, YUI. The [YUI CSS
<del>compressor]((http://yui.github.io/yuicompressor/css.html) provides
<add>compressor](http://yui.github.io/yuicompressor/css.html) provides
<ide> minification.
<ide>
<ide> The following line enables YUI compression, and requires the `yui-compressor` | 1 |
Text | Text | add linkedin obtaining api keys instructions | db09dc57bee531575f357fd8167672f70ea4179d | <ide><path>README.md
<ide> app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRe
<ide>
<ide> <hr>
<ide>
<add><img src="http://cdn3.tnwcdn.com/wp-content/blogs.dir/1/files/2013/11/linkedin_logo_11.jpg" width="200">
<add>- Sign in at [LinkedIn Developer Network](http://developer.linkedin.com/)
<add>- From the account name dropdown menu select **API Keys**
<add> - It might ask you to sign in once again
<add>- Click on **+ Add New Application**
<add>- Fill in all the required fields
<add>- For **Default Scope** make sure *at least* the following is checked:
<add> - **r_basicprofile**
<add> - **r_emailaddress**
<add>- For **OAuth 1.0 Accept Redirect URL**: http://localhost:3000/
<add>- Click on **Add Application** button
<add>- Copy and paste *OAuth User Token* and *OAuth User Secret* keys into `config/secrets.js`
<add> - *API Key* is your **clientID**
<add> - *Secret Key* is your **clientSecret**
<add>
<add><hr>
<add>
<ide> <img src="https://s3.amazonaws.com/venmo/venmo_logo_blue.png" width="200">
<ide> - Visit the **Account** section of your Venmo profile after logging in
<ide> - Click on the **Developers** tab | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.