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 |
|---|---|---|---|---|---|
Go | Go | set architecture to x86_64 by default | 5f69a53dba4b0e550ab29c7f2bf4277222927097 | <ide><path>graph.go
<ide> func (graph *Graph) Create(layerData Archive, container *Container, comment, aut
<ide> DockerVersion: VERSION,
<ide> Author: author,
<ide> Config: config,
<add> Architecture: "x86_64",
<ide> }
<ide> if container != nil {
<ide> img.Parent = container.Image | 1 |
Java | Java | add check for unused websocket sessions | a3fa9c979777e554efad0df429041767f05dfdb8 | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/SubProtocolWebSocketHandler.java
<ide>
<ide> package org.springframework.web.socket.messaging;
<ide>
<add>import java.io.IOException;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.HashSet;
<ide> import java.util.Set;
<ide> import java.util.TreeMap;
<ide> import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.locks.ReentrantLock;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide> public class SubProtocolWebSocketHandler implements WebSocketHandler,
<ide> SubProtocolCapable, MessageHandler, SmartLifecycle {
<ide>
<add> /**
<add> * Sessions connected to this handler use a sub-protocol. Hence we expect to
<add> * receive some client messages. If we don't receive any within a minute, the
<add> * connection isn't doing well (proxy issue, slow network?) and can be closed.
<add> * @see #checkSessions()
<add> */
<add> private final int TIME_TO_FIRST_MESSAGE = 60 * 1000;
<add>
<add>
<ide> private final Log logger = LogFactory.getLog(SubProtocolWebSocketHandler.class);
<ide>
<add>
<ide> private final MessageChannel clientInboundChannel;
<ide>
<ide> private final SubscribableChannel clientOutboundChannel;
<ide> public class SubProtocolWebSocketHandler implements WebSocketHandler,
<ide>
<ide> private SubProtocolHandler defaultProtocolHandler;
<ide>
<del> private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>();
<add> private final Map<String, WebSocketSessionHolder> sessions = new ConcurrentHashMap<String, WebSocketSessionHolder>();
<ide>
<ide> private int sendTimeLimit = 10 * 1000;
<ide>
<ide> private int sendBufferSizeLimit = 512 * 1024;
<ide>
<add> private volatile long lastSessionCheckTime = System.currentTimeMillis();
<add>
<add> private final ReentrantLock sessionCheckLock = new ReentrantLock();
<add>
<ide> private final Object lifecycleMonitor = new Object();
<ide>
<ide> private volatile boolean running = false;
<ide> public final void stop() {
<ide> this.clientOutboundChannel.unsubscribe(this);
<ide>
<ide> // Notify sessions to stop flushing messages
<del> for (WebSocketSession session : this.sessions.values()) {
<add> for (WebSocketSessionHolder holder : this.sessions.values()) {
<ide> try {
<del> session.close(CloseStatus.GOING_AWAY);
<add> holder.getSession().close(CloseStatus.GOING_AWAY);
<ide> }
<ide> catch (Throwable t) {
<del> logger.error("Failed to close session id '" + session.getId() + "': " + t.getMessage());
<add> logger.error("Failed to close '" + holder.getSession() + "': " + t.getMessage());
<ide> }
<ide> }
<ide> }
<ide> public final void stop(Runnable callback) {
<ide>
<ide> @Override
<ide> public void afterConnectionEstablished(WebSocketSession session) throws Exception {
<del>
<ide> session = new ConcurrentWebSocketSessionDecorator(session, getSendTimeLimit(), getSendBufferSizeLimit());
<del>
<del> this.sessions.put(session.getId(), session);
<add> this.sessions.put(session.getId(), new WebSocketSessionHolder(session));
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("Started WebSocket session=" + session.getId() +
<del> ", number of sessions=" + this.sessions.size());
<add> logger.debug("Started session " + session.getId() + ", number of sessions=" + this.sessions.size());
<ide> }
<del>
<ide> findProtocolHandler(session).afterSessionStarted(session, this.clientInboundChannel);
<ide> }
<ide>
<ide> protected final SubProtocolHandler findProtocolHandler(WebSocketSession session)
<ide>
<ide> @Override
<ide> public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
<del> findProtocolHandler(session).handleMessageFromClient(session, message, this.clientInboundChannel);
<add> SubProtocolHandler protocolHandler = findProtocolHandler(session);
<add> protocolHandler.handleMessageFromClient(session, message, this.clientInboundChannel);
<add> WebSocketSessionHolder holder = this.sessions.get(session.getId());
<add> if (holder != null) {
<add> holder.setHasHandledMessages();
<add> }
<add> else {
<add> // Should never happen
<add> throw new IllegalStateException("Session not found: " + session);
<add> }
<add> checkSessions();
<ide> }
<ide>
<ide> @Override
<ide> public void handleMessage(Message<?> message) throws MessagingException {
<del>
<ide> String sessionId = resolveSessionId(message);
<ide> if (sessionId == null) {
<ide> logger.error("sessionId not found in message " + message);
<ide> return;
<ide> }
<del>
<del> WebSocketSession session = this.sessions.get(sessionId);
<del> if (session == null) {
<add> WebSocketSessionHolder holder = this.sessions.get(sessionId);
<add> if (holder == null) {
<ide> logger.error("Session not found for session with id '" + sessionId + "', ignoring message " + message);
<ide> return;
<ide> }
<del>
<add> WebSocketSession session = holder.getSession();
<ide> try {
<ide> findProtocolHandler(session).handleMessageToClient(session, message);
<ide> }
<ide> catch (SessionLimitExceededException ex) {
<ide> try {
<del> logger.error("Terminating session id '" + sessionId + "'", ex);
<add> logger.error("Terminating '" + session + "'", ex);
<ide>
<ide> // Session may be unresponsive so clear first
<ide> clearSession(session, ex.getStatus());
<ide> session.close(ex.getStatus());
<ide> }
<ide> catch (Exception secondException) {
<del> logger.error("Exception terminating session id '" + sessionId + "'", secondException);
<add> logger.error("Exception terminating '" + sessionId + "'", secondException);
<ide> }
<ide> }
<ide> catch (Exception e) {
<del> logger.error("Failed to send message to client " + message, e);
<add> logger.error("Failed to send message to client " + message + " in " + session, e);
<ide> }
<ide> }
<ide>
<ide> private String resolveSessionId(Message<?> message) {
<ide> return null;
<ide> }
<ide>
<add> /**
<add> * Periodically check sessions to ensure they have received at least one
<add> * message or otherwise close them.
<add> */
<add> private void checkSessions() throws IOException {
<add> long currentTime = System.currentTimeMillis();
<add> if (!isRunning() && currentTime - this.lastSessionCheckTime < TIME_TO_FIRST_MESSAGE) {
<add> return;
<add> }
<add> try {
<add> if (this.sessionCheckLock.tryLock()) {
<add> for (WebSocketSessionHolder holder : this.sessions.values()) {
<add> if (holder.hasHandledMessages()) {
<add> continue;
<add> }
<add> long timeSinceCreated = currentTime - holder.getCreateTime();
<add> if (holder.hasHandledMessages() || timeSinceCreated < TIME_TO_FIRST_MESSAGE) {
<add> continue;
<add> }
<add> WebSocketSession session = holder.getSession();
<add> if (logger.isErrorEnabled()) {
<add> logger.error("No messages received after " + timeSinceCreated + " ms. Closing " + holder);
<add> }
<add> try {
<add> session.close(CloseStatus.PROTOCOL_ERROR);
<add> }
<add> catch (Throwable t) {
<add> logger.error("Failed to close " + session, t);
<add> }
<add> }
<add> }
<add> }
<add> finally {
<add> this.sessionCheckLock.unlock();
<add> }
<add> }
<add>
<ide> @Override
<ide> public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
<ide> }
<ide> public boolean supportsPartialMessages() {
<ide> return false;
<ide> }
<ide>
<add>
<add> private static class WebSocketSessionHolder {
<add>
<add> private final WebSocketSession session;
<add>
<add> private final long createTime = System.currentTimeMillis();
<add>
<add> private volatile boolean handledMessages;
<add>
<add>
<add> private WebSocketSessionHolder(WebSocketSession session) {
<add> this.session = session;
<add> }
<add>
<add> public WebSocketSession getSession() {
<add> return this.session;
<add> }
<add>
<add> public long getCreateTime() {
<add> return this.createTime;
<add> }
<add>
<add> public void setHasHandledMessages() {
<add> this.handledMessages = true;
<add> }
<add>
<add> public boolean hasHandledMessages() {
<add> return this.handledMessages;
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> if (this.session instanceof ConcurrentWebSocketSessionDecorator) {
<add> return ((ConcurrentWebSocketSessionDecorator) this.session).getLastSession().toString();
<add> }
<add> else {
<add> return this.session.toString();
<add> }
<add> }
<add> }
<add>
<ide> }
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/SubProtocolWebSocketHandlerTests.java
<ide> package org.springframework.web.socket.messaging;
<ide>
<ide> import java.util.Arrays;
<add>import java.util.Map;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.mockito.Mock;
<ide> import org.mockito.MockitoAnnotations;
<add>import org.springframework.beans.DirectFieldAccessor;
<ide> import org.springframework.messaging.MessageChannel;
<ide> import org.springframework.messaging.SubscribableChannel;
<add>import org.springframework.web.socket.CloseStatus;
<add>import org.springframework.web.socket.TextMessage;
<ide> import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;
<ide> import org.springframework.web.socket.handler.TestWebSocketSession;
<ide>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertNull;
<add>import static org.junit.Assert.assertTrue;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> /**
<ide> public class SubProtocolWebSocketHandlerTests {
<ide> @Before
<ide> public void setup() {
<ide> MockitoAnnotations.initMocks(this);
<del>
<ide> this.webSocketHandler = new SubProtocolWebSocketHandler(this.inClientChannel, this.outClientChannel);
<ide> when(stompHandler.getSupportedProtocols()).thenReturn(Arrays.asList("v10.stomp", "v11.stomp", "v12.stomp"));
<ide> when(mqttHandler.getSupportedProtocols()).thenReturn(Arrays.asList("MQTT"));
<del>
<ide> this.session = new TestWebSocketSession();
<ide> this.session.setId("1");
<ide> }
<ide> public void noSubProtocolNoDefaultHandler() throws Exception {
<ide> this.webSocketHandler.afterConnectionEstablished(session);
<ide> }
<ide>
<add> @Test
<add> public void checkSession() throws Exception {
<add> TestWebSocketSession session1 = new TestWebSocketSession("id1");
<add> TestWebSocketSession session2 = new TestWebSocketSession("id2");
<add> session1.setAcceptedProtocol("v12.stomp");
<add> session2.setAcceptedProtocol("v12.stomp");
<add>
<add> this.webSocketHandler.setProtocolHandlers(Arrays.asList(this.stompHandler));
<add> this.webSocketHandler.afterConnectionEstablished(session1);
<add> this.webSocketHandler.afterConnectionEstablished(session2);
<add> session1.setOpen(true);
<add> session2.setOpen(true);
<add>
<add> long sixtyOneSecondsAgo = System.currentTimeMillis() - 61 * 1000;
<add> new DirectFieldAccessor(this.webSocketHandler).setPropertyValue("lastSessionCheckTime", sixtyOneSecondsAgo);
<add> Map<String, ?> sessions = (Map<String, ?>) new DirectFieldAccessor(this.webSocketHandler).getPropertyValue("sessions");
<add> new DirectFieldAccessor(sessions.get("id1")).setPropertyValue("createTime", sixtyOneSecondsAgo);
<add> new DirectFieldAccessor(sessions.get("id2")).setPropertyValue("createTime", sixtyOneSecondsAgo);
<add>
<add> this.webSocketHandler.handleMessage(session1, new TextMessage("foo"));
<add>
<add> assertTrue(session1.isOpen());
<add> assertFalse(session2.isOpen());
<add> assertNull(session1.getCloseStatus());
<add> assertEquals(CloseStatus.PROTOCOL_ERROR, session2.getCloseStatus());
<add> }
<add>
<add>
<ide> } | 2 |
PHP | PHP | increase entropy on session id generation | 83f94cf1a0425d2ad526646d743e51ab7f7825a2 | <ide><path>src/Illuminate/Session/Store.php
<ide> public function setId($id)
<ide> */
<ide> protected function generateSessionId()
<ide> {
<del> return sha1(str_random(25).microtime(true));
<add> return sha1(uniqid(true).str_random(25).microtime(true));
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | fix signature of _write() in a comment | 85b74de9debab7515b04ae7be7c4fb69232a2f79 | <ide><path>lib/_stream_writable.js
<ide> // A bit simpler than readable streams.
<del>// Implement an async ._write(chunk, cb), and it'll handle all
<add>// Implement an async ._write(chunk, encoding, cb), and it'll handle all
<ide> // the drain event emission and buffering.
<ide>
<ide> 'use strict'; | 1 |
Go | Go | fix error name typo (errinvalidworikingdirectory) | d3150e0927043976b0b88bd61e50dc1e456fa77b | <ide><path>runconfig/parse.go
<ide> import (
<ide> )
<ide>
<ide> var (
<del> ErrInvalidWorikingDirectory = fmt.Errorf("The working directory is invalid. It needs to be an absolute path.")
<add> ErrInvalidWorkingDirectory = fmt.Errorf("The working directory is invalid. It needs to be an absolute path.")
<ide> ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
<ide> ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
<ide> )
<ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf
<ide> return nil, nil, cmd, ErrConflictAttachDetach
<ide> }
<ide> if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
<del> return nil, nil, cmd, ErrInvalidWorikingDirectory
<add> return nil, nil, cmd, ErrInvalidWorkingDirectory
<ide> }
<ide> if *flDetach && *flAutoRemove {
<ide> return nil, nil, cmd, ErrConflictDetachAutoRemove | 1 |
PHP | PHP | use the accessor method instead of the property | fc23f747dd56a3643f4a2817edcaf196c9f98cb0 | <ide><path>Cake/ORM/Table.php
<ide> public function schema($schema = null) {
<ide> if ($this->_schema === null) {
<ide> $this->_schema = $this->connection()
<ide> ->schemaCollection()
<del> ->describe($this->_table);
<add> ->describe($this->table());
<ide> }
<ide> return $this->_schema;
<ide> } | 1 |
Ruby | Ruby | move flash committing to the request object | d14caa300c8d3af1e04c37811ae81c7e5f596ab0 | <ide><path>actionpack/lib/action_dispatch/http/request.rb
<ide> def request_id=(id) # :nodoc:
<ide> set_header ACTION_DISPATCH_REQUEST_ID, id
<ide> end
<ide>
<add> def commit_flash
<add> session = self.session || {}
<add> flash_hash = self.flash_hash
<add>
<add> if flash_hash && (flash_hash.present? || session.key?('flash'))
<add> session["flash"] = flash_hash.to_session_value
<add> self.flash = flash_hash.dup
<add> end
<add>
<add> if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
<add> session.key?('flash') && session['flash'].nil?
<add> session.delete('flash')
<add> end
<add> end
<add>
<ide> alias_method :uuid, :request_id
<ide>
<ide> # Returns the lowercase name of the HTTP server software.
<ide><path>actionpack/lib/action_dispatch/middleware/flash.rb
<ide> def call(env)
<ide> req = ActionDispatch::Request.new env
<ide> @app.call(env)
<ide> ensure
<del> session = req.session || {}
<del> flash_hash = req.flash_hash
<del>
<del> if flash_hash && (flash_hash.present? || session.key?('flash'))
<del> session["flash"] = flash_hash.to_session_value
<del> req.flash = flash_hash.dup
<del> end
<del>
<del> if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
<del> session.key?('flash') && session['flash'].nil?
<del> session.delete('flash')
<del> end
<add> req.commit_flash
<ide> end
<ide> end
<ide> end | 2 |
Ruby | Ruby | teach postgresqladapter#reset! to actually reset | cc0d54bcc09a8ab834041787df69f6795a468b91 | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def reconnect!
<ide>
<ide> def reset!
<ide> clear_cache!
<del> super
<add> reset_transaction
<add> unless @connection.transaction_status == ::PG::PQTRANS_IDLE
<add> @connection.query 'ROLLBACK'
<add> end
<add> @connection.query 'DISCARD ALL'
<add> configure_connection
<ide> end
<ide>
<ide> # Disconnects from the database if already connected. Otherwise, this
<ide><path>activerecord/test/cases/adapters/postgresql/connection_test.rb
<ide> def test_connection_options
<ide> assert_equal 'off', expect
<ide> end
<ide>
<add> def test_reset
<add> @connection.query('ROLLBACK')
<add> @connection.query('SET geqo TO off')
<add>
<add> # Verify the setting has been applied.
<add> expect = @connection.query('show geqo').first.first
<add> assert_equal 'off', expect
<add>
<add> @connection.reset!
<add>
<add> # Verify the setting has been cleared.
<add> expect = @connection.query('show geqo').first.first
<add> assert_equal 'on', expect
<add> end
<add>
<add> def test_reset_with_transaction
<add> @connection.query('ROLLBACK')
<add> @connection.query('SET geqo TO off')
<add>
<add> # Verify the setting has been applied.
<add> expect = @connection.query('show geqo').first.first
<add> assert_equal 'off', expect
<add>
<add> @connection.query('BEGIN')
<add> @connection.reset!
<add>
<add> # Verify the setting has been cleared.
<add> expect = @connection.query('show geqo').first.first
<add> assert_equal 'on', expect
<add> end
<add>
<ide> def test_tables_logs_name
<ide> @connection.tables('hello')
<ide> assert_equal 'SCHEMA', @subscriber.logged[0][1] | 2 |
Java | Java | add completablefuture/single/promise support | f816cc6a516c324875fa409a33d288447c6996f7 | <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/codec/decoder/JsonObjectDecoder.java
<ide> import io.netty.buffer.Unpooled;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.fn.Function;
<add>import reactor.rx.Promise;
<ide> import reactor.rx.Streams;
<ide> import rx.Observable;
<ide>
<ide> public JsonObjectDecoder(int maxObjectLength, boolean streamArrayElements) {
<ide>
<ide> @Override
<ide> public boolean canDecode(ResolvableType type, MediaType mediaType, Object... hints) {
<del> return mediaType.isCompatibleWith(MediaType.APPLICATION_JSON) &&
<add> return mediaType.isCompatibleWith(MediaType.APPLICATION_JSON) && !Promise.class.isAssignableFrom(type.getRawClass()) &&
<ide> (Observable.class.isAssignableFrom(type.getRawClass()) || Publisher.class.isAssignableFrom(type.getRawClass()));
<ide> }
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/codec/encoder/JsonObjectEncoder.java
<ide> import java.nio.ByteBuffer;
<ide>
<ide> import org.reactivestreams.Publisher;
<add>import reactor.rx.Promise;
<ide> import rx.Observable;
<ide> import rx.RxReactiveStreams;
<ide>
<ide> public class JsonObjectEncoder implements MessageToByteEncoder<ByteBuffer> {
<ide>
<ide> @Override
<ide> public boolean canEncode(ResolvableType type, MediaType mediaType, Object... hints) {
<del> return mediaType.isCompatibleWith(MediaType.APPLICATION_JSON) &&
<add> return mediaType.isCompatibleWith(MediaType.APPLICATION_JSON) && !Promise.class.isAssignableFrom(type.getRawClass()) &&
<ide> (Observable.class.isAssignableFrom(type.getRawClass()) || Publisher.class.isAssignableFrom(type.getRawClass()));
<ide> }
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/util/CompletableFutureUtils.java
<add>/*
<add> * Copyright 2002-2015 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.reactive.util;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.concurrent.CompletableFuture;
<add>
<add>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<add>import reactor.core.support.Exceptions;
<add>import reactor.rx.Stream;
<add>import reactor.rx.action.Action;
<add>import reactor.rx.subscription.ReactiveSubscription;
<add>
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * @author Sebastien Deleuze
<add> */
<add>public class CompletableFutureUtils {
<add>
<add> public static <T> Publisher<T> toPublisher(CompletableFuture<T> future) {
<add> return new CompletableFutureStream<T>(future);
<add> }
<add>
<add> public static <T> CompletableFuture<List<T>> fromPublisher(Publisher<T> publisher) {
<add> final CompletableFuture<List<T>> future = new CompletableFuture<>();
<add> publisher.subscribe(new Subscriber<T>() {
<add> private final List<T> values = new ArrayList<>();
<add>
<add> @Override
<add> public void onSubscribe(Subscription s) {
<add> s.request(Long.MAX_VALUE);
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> values.add(t);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> future.completeExceptionally(t);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> future.complete(values);
<add> }
<add> });
<add> return future;
<add> }
<add>
<add> public static <T> CompletableFuture<T> fromSinglePublisher(Publisher<T> publisher) {
<add> final CompletableFuture<T> future = new CompletableFuture<>();
<add> publisher.subscribe(new Subscriber<T>() {
<add> private T value;
<add>
<add> @Override
<add> public void onSubscribe(Subscription s) {
<add> s.request(Long.MAX_VALUE);
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> Assert.state(value == null, "This publisher should not publish multiple values");
<add> value = t;
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> future.completeExceptionally(t);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> future.complete(value);
<add> }
<add> });
<add> return future;
<add> }
<add>
<add> private static class CompletableFutureStream<T> extends Stream<T> {
<add>
<add> private final CompletableFuture<? extends T> future;
<add>
<add> public CompletableFutureStream(CompletableFuture<? extends T> future) {
<add> this.future = future;
<add> }
<add>
<add> @Override
<add> public void subscribe(final Subscriber<? super T> subscriber) {
<add> try {
<add> subscriber.onSubscribe(new ReactiveSubscription<T>(this, subscriber) {
<add>
<add> @Override
<add> public void request(long elements) {
<add> Action.checkRequest(elements);
<add> if (isComplete()) return;
<add>
<add> try {
<add> future.whenComplete((result, error) -> {
<add> if (error != null) {
<add> onError(error);
<add> }
<add> else {
<add> subscriber.onNext(result);
<add> onComplete();
<add> }
<add> });
<add>
<add> } catch (Throwable e) {
<add> onError(e);
<add> }
<add> }
<add> });
<add> } catch (Throwable throwable) {
<add> Exceptions.throwIfFatal(throwable);
<add> subscriber.onError(throwable);
<add> }
<add> }
<add>
<add> }
<add>
<add>}
<ide>\ No newline at end of file
<ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/RequestBodyArgumentResolver.java
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<add>import java.util.concurrent.CompletableFuture;
<ide>
<ide> import org.reactivestreams.Publisher;
<add>import reactor.rx.Promise;
<ide> import reactor.rx.Stream;
<ide> import reactor.rx.Streams;
<ide> import rx.Observable;
<ide> import rx.RxReactiveStreams;
<add>import rx.Single;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.reactive.codec.decoder.ByteToMessageDecoder;
<add>import org.springframework.reactive.util.CompletableFutureUtils;
<ide> import org.springframework.reactive.web.dispatch.method.HandlerMethodArgumentResolver;
<ide> import org.springframework.reactive.web.http.ServerHttpRequest;
<ide> import org.springframework.web.bind.annotation.RequestBody;
<ide> public Object resolveArgument(MethodParameter parameter, ServerHttpRequest reque
<ide> ResolvableType type = ResolvableType.forMethodParameter(parameter);
<ide> List<Object> hints = new ArrayList<>();
<ide> hints.add(UTF_8);
<add>
<ide> // TODO: Refactor type conversion
<ide> ResolvableType readType = type;
<del> if (Observable.class.isAssignableFrom(type.getRawClass()) || Publisher.class.isAssignableFrom(type.getRawClass())) {
<add> if (Observable.class.isAssignableFrom(type.getRawClass()) ||
<add> Single.class.isAssignableFrom(type.getRawClass()) ||
<add> Promise.class.isAssignableFrom(type.getRawClass()) ||
<add> Publisher.class.isAssignableFrom(type.getRawClass()) ||
<add> CompletableFuture.class.isAssignableFrom(type.getRawClass())) {
<ide> readType = type.getGeneric(0);
<ide> }
<ide>
<ide> public Object resolveArgument(MethodParameter parameter, ServerHttpRequest reque
<ide> if (Stream.class.isAssignableFrom(type.getRawClass())) {
<ide> return Streams.wrap(elementStream);
<ide> }
<add> else if (Promise.class.isAssignableFrom(type.getRawClass())) {
<add> return Streams.wrap(elementStream).take(1).next();
<add> }
<ide> else if (Observable.class.isAssignableFrom(type.getRawClass())) {
<ide> return RxReactiveStreams.toObservable(elementStream);
<ide> }
<add> else if (Single.class.isAssignableFrom(type.getRawClass())) {
<add> return RxReactiveStreams.toObservable(elementStream).toSingle();
<add> }
<add> else if (CompletableFuture.class.isAssignableFrom(type.getRawClass())) {
<add> return CompletableFutureUtils.fromSinglePublisher(elementStream);
<add> }
<ide> else if (Publisher.class.isAssignableFrom(type.getRawClass())) {
<ide> return elementStream;
<ide> }
<ide> else {
<ide> try {
<ide> return Streams.wrap(elementStream).next().await();
<ide> } catch(InterruptedException ex) {
<del> throw new IllegalStateException("Timeout before getter the value");
<add> return Streams.fail(new IllegalStateException("Timeout before getter the value"));
<ide> }
<ide> }
<ide> }
<del> throw new IllegalStateException("Argument type not supported: " + type);
<add> return Streams.fail(new IllegalStateException("Argument type not supported: " + type));
<ide> }
<ide>
<ide> private MediaType resolveMediaType(ServerHttpRequest request) {
<ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/dispatch/method/annotation/ResponseBodyResultHandler.java
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<add>import java.util.concurrent.CompletableFuture;
<ide>
<ide> import org.reactivestreams.Publisher;
<add>import reactor.rx.Promise;
<add>import reactor.rx.Stream;
<ide> import reactor.rx.Streams;
<ide> import rx.Observable;
<ide> import rx.RxReactiveStreams;
<add>import rx.Single;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.Ordered;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.reactive.codec.encoder.MessageToByteEncoder;
<add>import org.springframework.reactive.util.CompletableFutureUtils;
<ide> import org.springframework.reactive.web.dispatch.HandlerResult;
<ide> import org.springframework.reactive.web.dispatch.HandlerResultHandler;
<ide> import org.springframework.reactive.web.http.ServerHttpRequest;
<ide> public Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpRespons
<ide> Publisher<Object> elementStream;
<ide>
<ide> // TODO: Refactor type conversion
<del> if (Observable.class.isAssignableFrom(type.getRawClass())) {
<add> if (Promise.class.isAssignableFrom(type.getRawClass())) {
<add> elementStream = ((Promise)value).stream();
<add> }
<add> else if (Observable.class.isAssignableFrom(type.getRawClass())) {
<ide> elementStream = RxReactiveStreams.toPublisher((Observable) value);
<ide> }
<add> else if (Single.class.isAssignableFrom(type.getRawClass())) {
<add> elementStream = RxReactiveStreams.toPublisher(((Single)value).toObservable());
<add> }
<add> else if (CompletableFuture.class.isAssignableFrom(type.getRawClass())) {
<add> elementStream = CompletableFutureUtils.toPublisher((CompletableFuture) value);
<add> }
<ide> else if (Publisher.class.isAssignableFrom(type.getRawClass())) {
<ide> elementStream = (Publisher)value;
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/util/CompletableFutureUtilsTests.java
<add>/*
<add> * Copyright 2002-2015 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.reactive.util;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.concurrent.CompletableFuture;
<add>import java.util.concurrent.CountDownLatch;
<add>import java.util.concurrent.TimeUnit;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertTrue;
<add>import org.junit.Test;
<add>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<add>import reactor.rx.Streams;
<add>
<add>/**
<add> * @author Sebastien Deleuze
<add> */
<add>public class CompletableFutureUtilsTests {
<add>
<add> private CountDownLatch lock = new CountDownLatch(1);
<add> private final List<Boolean> results = new ArrayList<>();
<add> private final List<Throwable> errors = new ArrayList<>();
<add>
<add> @Test
<add> public void fromPublisher() throws InterruptedException {
<add> Publisher<Boolean> publisher = Streams.just(true, false);
<add> CompletableFuture<List<Boolean>> future = CompletableFutureUtils.fromPublisher(publisher);
<add> future.whenComplete((result, error) -> {
<add> if (error != null) {
<add> errors.add(error);
<add> }
<add> else {
<add> results.addAll(result);
<add> }
<add> lock.countDown();
<add> });
<add> lock.await(2000, TimeUnit.MILLISECONDS);
<add> assertEquals("onError not expected: " + errors.toString(), 0, errors.size());
<add> assertEquals(2, results.size());
<add> assertTrue(results.get(0));
<add> assertFalse(results.get(1));
<add> }
<add>
<add> @Test
<add> public void fromSinglePublisher() throws InterruptedException {
<add> Publisher<Boolean> publisher = Streams.just(true);
<add> CompletableFuture<Boolean> future = CompletableFutureUtils.fromSinglePublisher(publisher);
<add> future.whenComplete((result, error) -> {
<add> if (error != null) {
<add> errors.add(error);
<add> }
<add> else {
<add> results.add(result);
<add> }
<add> lock.countDown();
<add> });
<add> lock.await(2000, TimeUnit.MILLISECONDS);
<add> assertEquals("onError not expected: " + errors.toString(), 0, errors.size());
<add> assertEquals(1, results.size());
<add> assertTrue(results.get(0));
<add> }
<add>
<add> @Test
<add> public void fromSinglePublisherWithMultipleValues() throws InterruptedException {
<add> Publisher<Boolean> publisher = Streams.just(true, false);
<add> CompletableFuture<Boolean> future = CompletableFutureUtils.fromSinglePublisher(publisher);
<add> future.whenComplete((result, error) -> {
<add> if (error != null) {
<add> errors.add(error);
<add> }
<add> else {
<add> results.add(result);
<add> }
<add> lock.countDown();
<add> });
<add> lock.await(2000, TimeUnit.MILLISECONDS);
<add> assertEquals(1, errors.size());
<add> assertEquals(IllegalStateException.class, errors.get(0).getClass());
<add> assertEquals(0, results.size());
<add> }
<add>
<add>}
<ide>\ No newline at end of file
<ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/dispatch/method/annotation/RequestMappingIntegrationTests.java
<ide> import java.net.URI;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<add>import java.util.concurrent.CompletableFuture;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> import org.junit.Test;
<ide> import org.reactivestreams.Publisher;
<add>import reactor.rx.Promise;
<add>import reactor.rx.Promises;
<ide> import reactor.rx.Stream;
<ide> import reactor.rx.Streams;
<ide> import rx.Observable;
<add>import rx.Single;
<ide>
<ide> import org.springframework.core.ParameterizedTypeReference;
<ide> import org.springframework.http.MediaType;
<ide> public void helloWithQueryParam() throws Exception {
<ide>
<ide> @Test
<ide> public void serializeAsPojo() throws Exception {
<add> serializeAsPojo("http://localhost:" + port + "/person");
<add> }
<ide>
<del> RestTemplate restTemplate = new RestTemplate();
<add> @Test
<add> public void serializeAsCompletableFuture() throws Exception {
<add> serializeAsPojo("http://localhost:" + port + "/completable-future");
<add> }
<ide>
<del> URI url = new URI("http://localhost:" + port + "/person");
<del> RequestEntity<Void> request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build();
<del> ResponseEntity<Person> response = restTemplate.exchange(request, Person.class);
<add> @Test
<add> public void serializeAsSingle() throws Exception {
<add> serializeAsPojo("http://localhost:" + port + "/single");
<add> }
<ide>
<del> assertEquals(new Person("Robert"), response.getBody());
<add> @Test
<add> public void serializeAsPromise() throws Exception {
<add> serializeAsPojo("http://localhost:" + port + "/promise");
<ide> }
<ide>
<ide> @Test
<ide> public void serializeAsList() throws Exception {
<add> serializeAsCollection("http://localhost:" + port + "/list");
<add> }
<ide>
<del> RestTemplate restTemplate = new RestTemplate();
<add> @Test
<add> public void serializeAsPublisher() throws Exception {
<add> serializeAsCollection("http://localhost:" + port + "/publisher");
<add> }
<ide>
<del> URI url = new URI("http://localhost:" + port + "/list");
<del> RequestEntity<Void> request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build();
<del> List<Person> results = restTemplate.exchange(request, new ParameterizedTypeReference<List<Person>>(){}).getBody();
<add> @Test
<add> public void serializeAsObservable() throws Exception {
<add> serializeAsCollection("http://localhost:" + port + "/observable");
<add> }
<ide>
<del> assertEquals(2, results.size());
<del> assertEquals(new Person("Robert"), results.get(0));
<del> assertEquals(new Person("Marie"), results.get(1));
<add> @Test
<add> public void serializeAsReactorStream() throws Exception {
<add> serializeAsCollection("http://localhost:" + port + "/stream");
<ide> }
<ide>
<ide> @Test
<del> public void serializeAsPublisher() throws Exception {
<add> public void publisherCapitalize() throws Exception {
<add> capitalizeCollection("http://localhost:" + port + "/publisher-capitalize");
<add> }
<ide>
<del> RestTemplate restTemplate = new RestTemplate();
<add> @Test
<add> public void observableCapitalize() throws Exception {
<add> capitalizeCollection("http://localhost:" + port + "/observable-capitalize");
<add> }
<ide>
<del> URI url = new URI("http://localhost:" + port + "/publisher");
<del> RequestEntity<Void> request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build();
<del> List<Person> results = restTemplate.exchange(request, new ParameterizedTypeReference<List<Person>>(){}).getBody();
<add> @Test
<add> public void streamCapitalize() throws Exception {
<add> capitalizeCollection("http://localhost:" + port + "/stream-capitalize");
<add> }
<ide>
<del> assertEquals(2, results.size());
<del> assertEquals(new Person("Robert"), results.get(0));
<del> assertEquals(new Person("Marie"), results.get(1));
<add> @Test
<add> public void completableFutureCapitalize() throws Exception {
<add> capitalizePojo("http://localhost:" + port + "/completable-future-capitalize");
<ide> }
<ide>
<ide> @Test
<del> public void serializeAsObservable() throws Exception {
<add> public void singleCapitalize() throws Exception {
<add> capitalizePojo("http://localhost:" + port + "/single-capitalize");
<add> }
<add>
<add> @Test
<add> public void promiseCapitalize() throws Exception {
<add> capitalizePojo("http://localhost:" + port + "/promise-capitalize");
<add> }
<add>
<ide>
<add> public void serializeAsPojo(String requestUrl) throws Exception {
<ide> RestTemplate restTemplate = new RestTemplate();
<ide>
<del> URI url = new URI("http://localhost:" + port + "/observable");
<add> URI url = new URI(requestUrl);
<ide> RequestEntity<Void> request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build();
<del> List<Person> results = restTemplate.exchange(request, new ParameterizedTypeReference<List<Person>>() {
<del> }).getBody();
<add> ResponseEntity<Person> response = restTemplate.exchange(request, Person.class);
<ide>
<del> assertEquals(2, results.size());
<del> assertEquals(new Person("Robert"), results.get(0));
<del> assertEquals(new Person("Marie"), results.get(1));
<add> assertEquals(new Person("Robert"), response.getBody());
<ide> }
<ide>
<del> @Test
<del> public void serializeAsReactorStream() throws Exception {
<del>
<add> public void serializeAsCollection(String requestUrl) throws Exception {
<ide> RestTemplate restTemplate = new RestTemplate();
<ide>
<del> URI url = new URI("http://localhost:" + port + "/stream");
<add> URI url = new URI(requestUrl);
<ide> RequestEntity<Void> request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build();
<del> List<Person> results = restTemplate.exchange(request, new ParameterizedTypeReference<List<Person>>() {
<del> }).getBody();
<add> List<Person> results = restTemplate.exchange(request, new ParameterizedTypeReference<List<Person>>(){}).getBody();
<ide>
<ide> assertEquals(2, results.size());
<ide> assertEquals(new Person("Robert"), results.get(0));
<ide> assertEquals(new Person("Marie"), results.get(1));
<ide> }
<ide>
<del> @Test
<del> public void publisherCapitalize() throws Exception {
<del> capitalize("http://localhost:" + port + "/publisher-capitalize");
<del> }
<ide>
<del> @Test
<del> public void observableCapitalize() throws Exception {
<del> capitalize("http://localhost:" + port + "/observable-capitalize");
<del> }
<add> public void capitalizePojo(String requestUrl) throws Exception {
<add> RestTemplate restTemplate = new RestTemplate();
<ide>
<del> @Test
<del> public void streamCapitalize() throws Exception {
<del> capitalize("http://localhost:" + port + "/stream-capitalize");
<add> URI url = new URI(requestUrl);
<add> RequestEntity<Person> request = RequestEntity
<add> .post(url)
<add> .contentType(MediaType.APPLICATION_JSON)
<add> .accept(MediaType.APPLICATION_JSON)
<add> .body(new Person("Robert"));
<add> ResponseEntity<Person> response = restTemplate.exchange(request, Person.class);
<add>
<add> assertEquals(new Person("ROBERT"), response.getBody());
<ide> }
<ide>
<ide>
<del> public void capitalize(String requestUrl) throws Exception {
<add> public void capitalizeCollection(String requestUrl) throws Exception {
<ide> RestTemplate restTemplate = new RestTemplate();
<ide>
<ide> URI url = new URI(requestUrl);
<ide> public Person personResponseBody() {
<ide> return new Person("Robert");
<ide> }
<ide>
<add> @RequestMapping("/completable-future")
<add> @ResponseBody
<add> public CompletableFuture<Person> completableFutureResponseBody() {
<add> return CompletableFuture.completedFuture(new Person("Robert"));
<add> }
<add>
<add> @RequestMapping("/single")
<add> @ResponseBody
<add> public Single<Person> singleResponseBody() {
<add> return Single.just(new Person("Robert"));
<add> }
<add>
<add> @RequestMapping("/promise")
<add> @ResponseBody
<add> public Promise<Person> promiseResponseBody() {
<add> return Promises.success(new Person("Robert"));
<add> }
<add>
<ide> @RequestMapping("/list")
<ide> @ResponseBody
<ide> public List<Person> listResponseBody() {
<ide> public Stream<Person> streamCapitalize(@RequestBody Stream<Person> persons) {
<ide> });
<ide> }
<ide>
<add> @RequestMapping("/completable-future-capitalize")
<add> @ResponseBody
<add> public CompletableFuture<Person> completableFutureCapitalize(@RequestBody CompletableFuture<Person> personFuture) {
<add> return personFuture.thenApply(person -> {
<add> person.setName(person.getName().toUpperCase());
<add> return person;
<add> });
<add> }
<add>
<add> @RequestMapping("/single-capitalize")
<add> @ResponseBody
<add> public Single<Person> singleCapitalize(@RequestBody Single<Person> personFuture) {
<add> return personFuture.map(person -> {
<add> person.setName(person.getName().toUpperCase());
<add> return person;
<add> });
<add> }
<add>
<add> @RequestMapping("/promise-capitalize")
<add> @ResponseBody
<add> public Promise<Person> promiseCapitalize(@RequestBody Promise<Person> personFuture) {
<add> return personFuture.map(person -> {
<add> person.setName(person.getName().toUpperCase());
<add> return person;
<add> });
<add> }
<add>
<ide> }
<ide>
<ide> private static class Person { | 7 |
Python | Python | add a tool for release authors and prs | 529128134d92facd5728525c77a58397e87f0a38 | <ide><path>tools/announce.py
<add>#!/usr/bin/env python
<add># -*- encoding:utf-8 -*-
<add>"""
<add>Script to generate contribor and pull request lists
<add>
<add>This script generates contributor and pull request lists for release
<add>announcements using Github v3 protocol. Use requires an authentication token in
<add>order to have sufficient bandwidth, you can get one following the directions at
<add>`<https://help.github.com/articles/creating-an-access-token-for-command-line-use/>_
<add>Don't add any scope, as the default is read access to public information. The
<add>token may be stored in an environment variable as you only get one chance to
<add>see it.
<add>
<add>Usage::
<add>
<add> $ ./tools/announce.py <token> <revision range>
<add>
<add>The output is utf8 rst.
<add>
<add>Dependencies
<add>------------
<add>
<add>- gitpython
<add>- pygithub
<add>
<add>Some code was copied from scipy `tools/gh_list.py` and `tools/authors.py`.
<add>
<add>Examples
<add>--------
<add>
<add>From the bash command line with $GITHUB token.
<add>
<add> $ ./tools/announce $GITHUB v1.11.0..v1.11.1 > announce.rst
<add>
<add>"""
<add>from __future__ import print_function, division
<add>
<add>import os
<add>import sys
<add>import re
<add>import codecs
<add>from git import Repo
<add>from github import Github
<add>
<add>UTF8Writer = codecs.getwriter('utf8')
<add>sys.stdout = UTF8Writer(sys.stdout)
<add>this_repo = Repo(os.path.join(os.path.dirname(__file__), ".."))
<add>
<add>author_msg =\
<add>u"""
<add>A total of %d people contributed to this release. People with a "+" by their
<add>names contributed a patch for the first time.
<add>"""
<add>
<add>
<add>def get_authors(revision_range):
<add> pat = u'.*\\t(.*)\\n'
<add> lst_release, cur_release = [r.strip() for r in revision_range.split('..')]
<add>
<add> cur = set(re.findall(pat, this_repo.git.shortlog('-s', revision_range)))
<add> pre = set(re.findall(pat, this_repo.git.shortlog('-s', lst_release)))
<add> authors = [s + u' +' for s in cur - pre] + [s for s in cur & pre]
<add> authors.sort()
<add> return authors
<add>
<add>
<add>def get_prs(repo, revision_range):
<add> merges = this_repo.git.log('--oneline', '--merges', revision_range)
<add> issues = re.findall(u"Merge pull request \#(\d*)", merges)
<add> prnums = [int(s) for s in issues]
<add> prs = [repo.get_pull(n) for n in sorted(prnums)]
<add> return prs
<add>
<add>
<add>def main(token, revision_range):
<add> lst_release, cur_release = [r.strip() for r in revision_range.split('..')]
<add>
<add> github = Github(token)
<add> github_repo = github.get_repo('numpy/numpy')
<add>
<add> # document authors
<add> authors = get_authors(revision_range)
<add> heading = u"Contributors to {0}".format(cur_release)
<add> print()
<add> print(heading)
<add> print(u"-"*len(heading))
<add> print()
<add> for s in authors:
<add> print(u'- ' + s)
<add> print(author_msg % len(authors))
<add>
<add> # document pull requests
<add> heading = u"Pull requests merged for {0}".format(cur_release)
<add> print()
<add> print(heading)
<add> print(u"-"*len(heading))
<add> print()
<add> for pull in get_prs(github_repo, revision_range):
<add> pull_msg = u"- `#{0} <{1}>`__: {2}"
<add> title = re.sub(u"\s+", u" ", pull.title.strip())
<add> if len(title) > 60:
<add> remainder = re.sub(u"\s.*$", u"...", title[60:])
<add> if len(remainder) > 20:
<add> remainder = title[:80] + u"..."
<add> else:
<add> title = title[:60] + remainder
<add> print(pull_msg.format(pull.number, pull.html_url, title))
<add>
<add>
<add>if __name__ == "__main__":
<add> from argparse import ArgumentParser
<add>
<add> parser = ArgumentParser(description="Generate author/pr lists for release")
<add> parser.add_argument('token', help='github access token')
<add> parser.add_argument('revision_range', help='<revision>..<revision>')
<add> args = parser.parse_args()
<add> main(args.token, args.revision_range) | 1 |
Go | Go | allow use of just image name without the tag | ce02578317d03ea04f40416db96b679a55b55451 | <ide><path>events/events.go
<ide> package events
<ide>
<ide> import (
<ide> "encoding/json"
<add> "strings"
<ide> "sync"
<ide> "time"
<ide>
<ide> func writeEvent(job *engine.Job, event *utils.JSONMessage, eventFilters filters.
<ide> if v == field {
<ide> return false
<ide> }
<add> if strings.Contains(field, ":") {
<add> image := strings.Split(field, ":")
<add> if image[0] == v {
<add> return false
<add> }
<add> }
<ide> }
<ide> return true
<ide> }
<ide><path>integration-cli/docker_cli_events_test.go
<ide> func TestEventsFilters(t *testing.T) {
<ide>
<ide> logDone("events - filters")
<ide> }
<add>
<add>func TestEventsFilterImageName(t *testing.T) {
<add> since := time.Now().Unix()
<add> defer deleteAllContainers()
<add>
<add> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--name", "container_1", "-d", "busybox", "true"))
<add> if err != nil {
<add> t.Fatal(out, err)
<add> }
<add> container1 := stripTrailingCharacters(out)
<add> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "--name", "container_2", "-d", "busybox", "true"))
<add> if err != nil {
<add> t.Fatal(out, err)
<add> }
<add> container2 := stripTrailingCharacters(out)
<add>
<add> for _, s := range []string{"busybox", "busybox:latest"} {
<add> eventsCmd := exec.Command(dockerBinary, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", time.Now().Unix()), "--filter", fmt.Sprintf("image=%s", s))
<add> out, _, err := runCommandWithOutput(eventsCmd)
<add> if err != nil {
<add> t.Fatalf("Failed to get events, error: %s(%s)", err, out)
<add> }
<add> events := strings.Split(out, "\n")
<add> events = events[:len(events)-1]
<add> if len(events) == 0 {
<add> t.Fatalf("Expected events but found none for the image busybox:latest")
<add> }
<add> count1 := 0
<add> count2 := 0
<add> for _, e := range events {
<add> if strings.Contains(e, container1) {
<add> count1++
<add> } else if strings.Contains(e, container2) {
<add> count2++
<add> }
<add> }
<add> if count1 == 0 || count2 == 0 {
<add> t.Fatalf("Expected events from each container but got %d from %s and %d from %s", count1, container1, count2, container2)
<add> }
<add> }
<add>
<add> logDone("events - filters using image")
<add>
<add>} | 2 |
Ruby | Ruby | add missing require | cfcb92f9eaf78daefe21335bcabf813842c0ab07 | <ide><path>activestorage/app/models/active_storage/identification.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "net/http"
<add>
<ide> class ActiveStorage::Identification
<ide> attr_reader :blob
<ide> | 1 |
Java | Java | fix javadoc wording of onterminatedetach | ba1f40ffcfaed06bd69c1b9a810790cf47178c1f | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final Flowable<T> onExceptionResumeNext(final Publisher<? extends T> next
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<del> * @return a Flowable which out references to the upstream producer and downstream Subscriber if
<add> * @return a Flowable which nulls out references to the upstream producer and downstream Subscriber if
<ide> * the sequence is terminated or downstream cancels
<ide> * @since 2.0
<ide> */
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final Observable<T> onExceptionResumeNext(final ObservableSource<? extend
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<del> * @return an Observable which out references to the upstream producer and downstream Observer if
<add> * @return an Observable which nulls out references to the upstream producer and downstream Observer if
<ide> * the sequence is terminated or downstream calls dispose()
<ide> * @since 2.0
<ide> */ | 2 |
Javascript | Javascript | detect download filename based on full url | 228d253f30917381ecca68cb3f49d3086db94384 | <ide><path>web/app.js
<ide> var PDFViewerApplication = {
<ide> }
<ide>
<ide> var url = this.baseUrl;
<del> var filename = getPDFFileNameFromURL(url);
<add> // Use this.url instead of this.baseUrl to perform filename detection based
<add> // on the reference fragment as ultimate fallback if needed.
<add> var filename = getPDFFileNameFromURL(this.url);
<ide> var downloadManager = this.downloadManager;
<ide> downloadManager.onerror = function (err) {
<ide> // This error won't really be helpful because it's likely the | 1 |
Python | Python | add placement_strategy option | f40ac9b151124dbcd87197d6ae38c85191d41f38 | <ide><path>airflow/providers/amazon/aws/operators/ecs.py
<ide> class ECSOperator(BaseOperator): # pylint: disable=too-many-instance-attributes
<ide> :param placement_constraints: an array of placement constraint objects to use for
<ide> the task
<ide> :type placement_constraints: list
<add> :param placement_strategy: an array of placement strategy objects to use for
<add> the task
<add> :type placement_strategy: list
<ide> :param platform_version: the platform version on which your task is running
<ide> :type platform_version: str
<ide> :param network_configuration: the network configuration for the task
<ide> def __init__(
<ide> launch_type='EC2',
<ide> group=None,
<ide> placement_constraints=None,
<add> placement_strategy=None,
<ide> platform_version='LATEST',
<ide> network_configuration=None,
<ide> tags=None,
<ide> def __init__(
<ide> self.launch_type = launch_type
<ide> self.group = group
<ide> self.placement_constraints = placement_constraints
<add> self.placement_strategy = placement_strategy
<ide> self.platform_version = platform_version
<ide> self.network_configuration = network_configuration
<ide>
<ide> def execute(self, context):
<ide> run_opts['group'] = self.group
<ide> if self.placement_constraints is not None:
<ide> run_opts['placementConstraints'] = self.placement_constraints
<add> if self.placement_strategy is not None:
<add> run_opts['placementStrategy'] = self.placement_strategy
<ide> if self.network_configuration is not None:
<ide> run_opts['networkConfiguration'] = self.network_configuration
<ide> if self.tags is not None:
<ide><path>tests/providers/amazon/aws/operators/test_ecs.py
<ide> def set_up_operator(self, aws_hook_mock, **kwargs):
<ide> 'placement_constraints': [
<ide> {'expression': 'attribute:ecs.instance-type =~ t2.*', 'type': 'memberOf'}
<ide> ],
<add> 'placement_strategy': [{'field': 'memory', 'type': 'binpack'}],
<ide> 'network_configuration': {
<ide> 'awsvpcConfiguration': {'securityGroups': ['sg-123abc'], 'subnets': ['subnet-123456ab']}
<ide> },
<ide> def test_execute_without_failures(self, launch_type, tags, check_mock, wait_mock
<ide> taskDefinition='t',
<ide> group='group',
<ide> placementConstraints=[{'expression': 'attribute:ecs.instance-type =~ t2.*', 'type': 'memberOf'}],
<add> placementStrategy=[{'field': 'memory', 'type': 'binpack'}],
<ide> networkConfiguration={
<ide> 'awsvpcConfiguration': {'securityGroups': ['sg-123abc'], 'subnets': ['subnet-123456ab']}
<ide> },
<ide> def test_execute_with_failures(self):
<ide> taskDefinition='t',
<ide> group='group',
<ide> placementConstraints=[{'expression': 'attribute:ecs.instance-type =~ t2.*', 'type': 'memberOf'}],
<add> placementStrategy=[{'field': 'memory', 'type': 'binpack'}],
<ide> networkConfiguration={
<ide> 'awsvpcConfiguration': {'securityGroups': ['sg-123abc'], 'subnets': ['subnet-123456ab'],}
<ide> }, | 2 |
Java | Java | restore default transaction manager by name lookup | a79fe25917e38b0bf8ae1f11a80b22987e3be2df | <ide><path>spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java
<ide> protected PlatformTransactionManager determineTransactionManager(TransactionAttr
<ide> if (txAttr == null || this.beanFactory == null) {
<ide> return getTransactionManager();
<ide> }
<del> String qualifier = (txAttr.getQualifier() != null ?
<del> txAttr.getQualifier() : this.transactionManagerBeanName);
<add> String qualifier = txAttr.getQualifier();
<ide> if (StringUtils.hasText(qualifier)) {
<del> PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
<del> if (txManager == null) {
<del> txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
<del> this.beanFactory, PlatformTransactionManager.class, qualifier);
<del> this.transactionManagerCache.putIfAbsent(qualifier, txManager);
<del> }
<del> return txManager;
<add> return determineQualifiedTransactionManager(qualifier);
<add> }
<add> else if (StringUtils.hasText(this.transactionManagerBeanName)) {
<add> return determineQualifiedTransactionManager(this.transactionManagerBeanName);
<ide> }
<ide> else {
<ide> PlatformTransactionManager defaultTransactionManager = getTransactionManager();
<ide> protected PlatformTransactionManager determineTransactionManager(TransactionAttr
<ide> }
<ide> }
<ide>
<add> private PlatformTransactionManager determineQualifiedTransactionManager(String qualifier) {
<add> PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
<add> if (txManager == null) {
<add> txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
<add> this.beanFactory, PlatformTransactionManager.class, qualifier);
<add> this.transactionManagerCache.putIfAbsent(qualifier, txManager);
<add> }
<add> return txManager;
<add> }
<add>
<ide> /**
<ide> * Convenience method to return a String representation of this Method
<ide> * for use in logging. Can be overridden in subclasses to provide a
<ide><path>spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionInterceptorTests.java
<ide> public void serializableWithCompositeSource() throws Exception {
<ide> @Test
<ide> public void determineTransactionManagerWithNoBeanFactory() {
<ide> PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
<del> TransactionInterceptor ti = createTestTransactionInterceptor(null, transactionManager);
<add> TransactionInterceptor ti = transactionInterceptorWithTransactionManager(transactionManager, null);
<ide>
<ide> assertSame(transactionManager, ti.determineTransactionManager(new DefaultTransactionAttribute()));
<ide> }
<ide>
<ide> @Test
<ide> public void determineTransactionManagerWithNoBeanFactoryAndNoTransactionAttribute() {
<ide> PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
<del> TransactionInterceptor ti = createTestTransactionInterceptor(null, transactionManager);
<add> TransactionInterceptor ti = transactionInterceptorWithTransactionManager(transactionManager, null);
<ide>
<ide> assertSame(transactionManager, ti.determineTransactionManager(null));
<ide> }
<ide>
<ide> @Test
<ide> public void determineTransactionManagerWithNoTransactionAttribute() {
<ide> BeanFactory beanFactory = mock(BeanFactory.class);
<del> TransactionInterceptor ti = createTestTransactionInterceptor(beanFactory, null);
<add> TransactionInterceptor ti = simpleTransactionInterceptor(beanFactory);
<ide>
<ide> assertNull(ti.determineTransactionManager(null));
<ide> }
<ide>
<ide> @Test
<ide> public void determineTransactionManagerWithQualifierUnknown() {
<ide> BeanFactory beanFactory = mock(BeanFactory.class);
<del> TransactionInterceptor ti = createTestTransactionInterceptor(beanFactory);
<add> TransactionInterceptor ti = simpleTransactionInterceptor(beanFactory);
<ide> DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
<ide> attribute.setQualifier("fooTransactionManager");
<ide>
<ide> public void determineTransactionManagerWithQualifierUnknown() {
<ide> public void determineTransactionManagerWithQualifierAndDefault() {
<ide> BeanFactory beanFactory = mock(BeanFactory.class);
<ide> PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
<del> TransactionInterceptor ti = createTestTransactionInterceptor(beanFactory, transactionManager);
<add> TransactionInterceptor ti = transactionInterceptorWithTransactionManager(transactionManager, beanFactory);
<ide> PlatformTransactionManager fooTransactionManager =
<ide> associateTransactionManager(beanFactory, "fooTransactionManager");
<ide>
<ide> public void determineTransactionManagerWithQualifierAndDefault() {
<ide> public void determineTransactionManagerWithQualifierAndDefaultName() {
<ide> BeanFactory beanFactory = mock(BeanFactory.class);
<ide> associateTransactionManager(beanFactory, "defaultTransactionManager");
<del> TransactionInterceptor ti = createTestTransactionInterceptor(beanFactory);
<del> ti.setTransactionManagerBeanName("defaultTransactionManager");
<add> TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName(
<add> "defaultTransactionManager", beanFactory);
<ide>
<ide> PlatformTransactionManager fooTransactionManager =
<ide> associateTransactionManager(beanFactory, "fooTransactionManager");
<ide> public void determineTransactionManagerWithQualifierAndDefaultName() {
<ide> assertSame(fooTransactionManager, ti.determineTransactionManager(attribute));
<ide> }
<ide>
<add> @Test
<add> public void determineTransactionManagerWithEmptyQualifierAndDefaultName() {
<add> BeanFactory beanFactory = mock(BeanFactory.class);
<add> PlatformTransactionManager defaultTransactionManager
<add> = associateTransactionManager(beanFactory, "defaultTransactionManager");
<add> TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName(
<add> "defaultTransactionManager", beanFactory);
<add>
<add> DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
<add> attribute.setQualifier("");
<add>
<add> assertSame(defaultTransactionManager, ti.determineTransactionManager(attribute));
<add> }
<add>
<ide> @Test
<ide> public void determineTransactionManagerWithQualifierSeveralTimes() {
<ide> BeanFactory beanFactory = mock(BeanFactory.class);
<del> TransactionInterceptor ti = createTestTransactionInterceptor(beanFactory);
<add> TransactionInterceptor ti = simpleTransactionInterceptor(beanFactory);
<ide>
<ide> PlatformTransactionManager txManager = associateTransactionManager(beanFactory, "fooTransactionManager");
<ide>
<ide> public void determineTransactionManagerWithQualifierSeveralTimes() {
<ide> @Test
<ide> public void determineTransactionManagerWithBeanNameSeveralTimes() {
<ide> BeanFactory beanFactory = mock(BeanFactory.class);
<del> TransactionInterceptor ti = createTestTransactionInterceptor(beanFactory);
<del> ti.setTransactionManagerBeanName("fooTransactionManager");
<add> TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName(
<add> "fooTransactionManager", beanFactory);
<ide>
<ide> PlatformTransactionManager txManager = associateTransactionManager(beanFactory, "fooTransactionManager");
<ide>
<ide> public void determineTransactionManagerWithBeanNameSeveralTimes() {
<ide> @Test
<ide> public void determineTransactionManagerDefaultSeveralTimes() {
<ide> BeanFactory beanFactory = mock(BeanFactory.class);
<del> TransactionInterceptor ti = createTestTransactionInterceptor(beanFactory);
<add> TransactionInterceptor ti = simpleTransactionInterceptor(beanFactory);
<ide>
<ide> PlatformTransactionManager txManager = mock(PlatformTransactionManager.class);
<ide> given(beanFactory.getBean(PlatformTransactionManager.class)).willReturn(txManager);
<ide> public void determineTransactionManagerDefaultSeveralTimes() {
<ide> verify(beanFactory, times(1)).getBean(PlatformTransactionManager.class);
<ide> }
<ide>
<del> private TransactionInterceptor createTestTransactionInterceptor(BeanFactory beanFactory,
<del> PlatformTransactionManager transactionManager) {
<add> private TransactionInterceptor createTransactionInterceptor(BeanFactory beanFactory,
<add> String transactionManagerName, PlatformTransactionManager transactionManager) {
<ide> TransactionInterceptor ti = new TransactionInterceptor();
<ide> if (beanFactory != null) {
<ide> ti.setBeanFactory(beanFactory);
<ide> }
<add> if (transactionManagerName != null) {
<add> ti.setTransactionManagerBeanName(transactionManagerName);
<add>
<add> }
<ide> if (transactionManager != null) {
<ide> ti.setTransactionManager(transactionManager);
<ide> }
<ide> private TransactionInterceptor createTestTransactionInterceptor(BeanFactory bean
<ide> return ti;
<ide> }
<ide>
<del> private TransactionInterceptor createTestTransactionInterceptor(BeanFactory beanFactory) {
<del> return createTestTransactionInterceptor(beanFactory, null);
<add> private TransactionInterceptor transactionInterceptorWithTransactionManager(
<add> PlatformTransactionManager transactionManager, BeanFactory beanFactory) {
<add>
<add> return createTransactionInterceptor(beanFactory, null, transactionManager);
<add> }
<add>
<add> private TransactionInterceptor transactionInterceptorWithTransactionManagerName(
<add> String transactionManagerName, BeanFactory beanFactory) {
<add>
<add> return createTransactionInterceptor(beanFactory, transactionManagerName, null);
<add> }
<add>
<add> private TransactionInterceptor simpleTransactionInterceptor(BeanFactory beanFactory) {
<add> return createTransactionInterceptor(beanFactory, null, null);
<ide> }
<ide>
<ide> private PlatformTransactionManager associateTransactionManager(BeanFactory beanFactory, String name) { | 2 |
Javascript | Javascript | use deterministic names for dynamic import | 68738d1c904476e9c99989ae5ee12a90c184fbc1 | <ide><path>server/build/babel/plugins/handle-import.js
<ide> // We've added support for SSR with this version
<ide> import template from 'babel-template'
<ide> import syntax from 'babel-plugin-syntax-dynamic-import'
<del>import UUID from 'uuid'
<add>import { dirname, resolve, sep } from 'path'
<add>import Crypto from 'crypto'
<ide>
<ide> const TYPE_IMPORT = 'Import'
<ide>
<ide> const buildImport = (args) => (template(`
<ide> )
<ide> `))
<ide>
<add>export function getModulePath (sourceFilename, moduleName) {
<add> // resolve only if it's a local module
<add> const modulePath = (moduleName[0] === '.')
<add> ? resolve(dirname(sourceFilename), moduleName) : moduleName
<add>
<add> const cleanedModulePath = modulePath
<add> .replace(/(index){0,1}\.js$/, '') // remove .js, index.js
<add> .replace(/[/\\]$/, '') // remove end slash
<add>
<add> return cleanedModulePath
<add>}
<add>
<ide> export default () => ({
<ide> inherits: syntax,
<ide>
<ide> visitor: {
<del> CallExpression (path) {
<add> CallExpression (path, state) {
<ide> if (path.node.callee.type === TYPE_IMPORT) {
<ide> const moduleName = path.node.arguments[0].value
<del> const name = `${moduleName.replace(/[^\w]/g, '-')}-${UUID.v4()}`
<add> const sourceFilename = state.file.opts.filename
<add>
<add> const modulePath = getModulePath(sourceFilename, moduleName)
<add> const modulePathHash = Crypto.createHash('md5').update(modulePath).digest('hex')
<add>
<add> const relativeModulePath = modulePath.replace(`${process.cwd()}${sep}`, '')
<add> const name = `${relativeModulePath.replace(/[^\w]/g, '-')}-${modulePathHash}`
<add>
<ide> const newImport = buildImport({
<ide> name
<ide> })({
<ide><path>test/unit/handle-import-babel-plugin.test.js
<add>/* global describe, it, expect */
<add>import { getModulePath } from '../../dist/server/build/babel/plugins/handle-import'
<add>
<add>function cleanPath (mPath) {
<add> return mPath
<add> .replace(/\\/g, '/')
<add> .replace(/^.*:/, '')
<add>}
<add>
<add>describe('handle-import-babel-plugin', () => {
<add> describe('getModulePath', () => {
<add> it('should not do anything to NPM modules', () => {
<add> const mPath = getModulePath('/abc/pages/about.js', 'cool-module')
<add> expect(mPath).toBe('cool-module')
<add> })
<add>
<add> it('should not do anything to private NPM modules', () => {
<add> const mPath = getModulePath('/abc/pages/about.js', '@zeithq/cool-module')
<add> expect(mPath).toBe('@zeithq/cool-module')
<add> })
<add>
<add> it('should resolve local modules', () => {
<add> const mPath = getModulePath('/abc/pages/about.js', '../components/hello.js')
<add> expect(cleanPath(mPath)).toBe('/abc/components/hello')
<add> })
<add>
<add> it('should remove index.js', () => {
<add> const mPath = getModulePath('/abc/pages/about.js', '../components/c1/index.js')
<add> expect(cleanPath(mPath)).toBe('/abc/components/c1')
<add> })
<add>
<add> it('should remove .js', () => {
<add> const mPath = getModulePath('/abc/pages/about.js', '../components/bb.js')
<add> expect(cleanPath(mPath)).toBe('/abc/components/bb')
<add> })
<add>
<add> it('should remove end slash', () => {
<add> const mPath = getModulePath('/abc/pages/about.js', '../components/bb/')
<add> expect(cleanPath(mPath)).toBe('/abc/components/bb')
<add> })
<add> })
<add>}) | 2 |
Javascript | Javascript | remove timing metrics from transaction | 1c44b874fc63287c4ae159c5701d4f785429fffa | <ide><path>src/utils/Transaction.js
<ide> var invariant = require('invariant');
<ide> * +-----------------------------------------+
<ide> * </pre>
<ide> *
<del> * Bonus:
<del> * - Reports timing metrics by method name and wrapper index.
<del> *
<ide> * Use cases:
<ide> * - Preserving the input selection ranges before/after reconciliation.
<ide> * Restoring selection even in the event of an unexpected error.
<ide> var Mixin = {
<ide> } else {
<ide> this.wrapperInitData.length = 0;
<ide> }
<del> if (!this.timingMetrics) {
<del> this.timingMetrics = {};
<del> }
<del> this.timingMetrics.methodInvocationTime = 0;
<del> if (!this.timingMetrics.wrapperInitTimes) {
<del> this.timingMetrics.wrapperInitTimes = [];
<del> } else {
<del> this.timingMetrics.wrapperInitTimes.length = 0;
<del> }
<del> if (!this.timingMetrics.wrapperCloseTimes) {
<del> this.timingMetrics.wrapperCloseTimes = [];
<del> } else {
<del> this.timingMetrics.wrapperCloseTimes.length = 0;
<del> }
<ide> this._isInTransaction = false;
<ide> },
<ide>
<ide> var Mixin = {
<ide> 'Transaction.perform(...): Cannot initialize a transaction when there ' +
<ide> 'is already an outstanding transaction.'
<ide> );
<del> var memberStart = Date.now();
<ide> var errorThrown;
<ide> var ret;
<ide> try {
<ide> var Mixin = {
<ide> ret = method.call(scope, a, b, c, d, e, f);
<ide> errorThrown = false;
<ide> } finally {
<del> var memberEnd = Date.now();
<del> this.methodInvocationTime += (memberEnd - memberStart);
<ide> try {
<ide> if (errorThrown) {
<ide> // If `method` throws, prefer to show that stack trace over any thrown
<ide> var Mixin = {
<ide>
<ide> initializeAll: function(startIndex) {
<ide> var transactionWrappers = this.transactionWrappers;
<del> var wrapperInitTimes = this.timingMetrics.wrapperInitTimes;
<ide> for (var i = startIndex; i < transactionWrappers.length; i++) {
<del> var initStart = Date.now();
<ide> var wrapper = transactionWrappers[i];
<ide> try {
<ide> // Catching errors makes debugging more difficult, so we start with the
<ide> var Mixin = {
<ide> wrapper.initialize.call(this) :
<ide> null;
<ide> } finally {
<del> var curInitTime = wrapperInitTimes[i];
<del> var initEnd = Date.now();
<del> wrapperInitTimes[i] = (curInitTime || 0) + (initEnd - initStart);
<del>
<ide> if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
<ide> // The initializer for wrapper i threw an error; initialize the
<ide> // remaining wrappers but silence any exceptions from them to ensure
<ide> var Mixin = {
<ide> 'Transaction.closeAll(): Cannot close transaction when none are open.'
<ide> );
<ide> var transactionWrappers = this.transactionWrappers;
<del> var wrapperCloseTimes = this.timingMetrics.wrapperCloseTimes;
<ide> for (var i = startIndex; i < transactionWrappers.length; i++) {
<ide> var wrapper = transactionWrappers[i];
<del> var closeStart = Date.now();
<ide> var initData = this.wrapperInitData[i];
<ide> var errorThrown;
<ide> try {
<ide> var Mixin = {
<ide> }
<ide> errorThrown = false;
<ide> } finally {
<del> var closeEnd = Date.now();
<del> var curCloseTime = wrapperCloseTimes[i];
<del> wrapperCloseTimes[i] = (curCloseTime || 0) + (closeEnd - closeStart);
<del>
<ide> if (errorThrown) {
<ide> // The closer for wrapper i threw an error; close the remaining
<ide> // wrappers but silence any exceptions from them to ensure that the | 1 |
Python | Python | add test cases for rackspace | cb6acca45ce3f9f9af9bea177f6a5ca199c88dbb | <ide><path>test/test_rackspace.py
<ide> from libcloud.types import InvalidCredsException
<ide> from libcloud.providers import Rackspace
<ide> from libcloud.types import Provider
<add>from libcloud.base import Node, NodeImage, NodeSize
<ide>
<ide> from test import MockHttp
<ide> from secrets import RACKSPACE_USER, RACKSPACE_KEY
<ide> def test_list_nodes(self):
<ide> ret = self.driver.list_nodes()
<ide> self.assertEqual(len(ret), 0)
<ide> RackspaceMockHttp.type = None
<add> ret = self.driver.list_nodes()
<add> self.assertEqual(len(ret), 1)
<ide>
<ide> def test_list_sizes(self):
<ide> ret = self.driver.list_sizes()
<ide> def test_list_sizes(self):
<ide> def test_list_images(self):
<ide> ret = self.driver.list_images()
<ide>
<del>
<add> def test_create_node(self):
<add> image = NodeImage(id=11, name='Ubuntu 8.10 (intrepid)', driver=self.driver)
<add> size = NodeSize(1, '256 slice', None, None, None, None, driver=self.driver)
<add> node = self.driver.create_node('racktest', image, size)
<add> self.assertEqual(node.name, 'racktest')
<add>
<add> def test_reboot_node(self):
<add> node = Node(id=72258, name=None, state=None, public_ip=None, private_ip=None,
<add> driver=self.driver)
<add> ret = node.reboot()
<add> self.assertTrue(ret is True)
<add>
<add> def test_destroy_node(self):
<add> node = Node(id=72258, name=None, state=None, public_ip=None, private_ip=None,
<add> driver=self.driver)
<add> ret = node.destroy()
<add> self.assertTrue(ret is True)
<add>
<ide> class RackspaceMockHttp(MockHttp):
<ide>
<ide> # fake auth token response
<ide> def _v1_0_slug_servers_detail_EMPTY(self, method, url, body, headers):
<ide> body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><servers xmlns="http://docs.rackspacecloud.com/servers/api/v1.0"/>"""
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<add> def _v1_0_slug_servers_detail(self, method, url, body, headers):
<add> body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><servers xmlns="http://docs.rackspacecloud.com/servers/api/v1.0"><server status="ACTIVE" progress="100" hostId="9dd380940fcbe39cb30255ed4664f1f3" flavorId="1" imageId="11" id="72258" name="racktest"><metadata/><addresses><public><ip addr="67.23.21.33"/></public><private><ip addr="10.176.168.218"/></private></addresses></server></servers>"""
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<add>
<ide> def _v1_0_slug_flavors_detail(self, method, url, body, headers):
<ide> body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><flavors xmlns="http://docs.rackspacecloud.com/servers/api/v1.0"><flavor disk="10" ram="256" name="256 slice" id="1"/><flavor disk="20" ram="512" name="512 slice" id="2"/><flavor disk="40" ram="1024" name="1GB slice" id="3"/><flavor disk="80" ram="2048" name="2GB slice" id="4"/><flavor disk="160" ram="4096" name="4GB slice" id="5"/><flavor disk="320" ram="8192" name="8GB slice" id="6"/><flavor disk="620" ram="15872" name="15.5GB slice" id="7"/></flavors>"""
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide> def _v1_0_slug_images_detail(self, method, url, body, headers):
<ide> body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><images xmlns="http://docs.rackspacecloud.com/servers/api/v1.0"><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="CentOS 5.2" id="2"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Gentoo 2008.0" id="3"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Debian 5.0 (lenny)" id="4"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Fedora 10 (Cambridge)" id="5"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="CentOS 5.3" id="7"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 9.04 (jaunty)" id="8"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Arch 2009.02" id="9"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 8.04.2 LTS (hardy)" id="10"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 8.10 (intrepid)" id="11"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Red Hat EL 5.3" id="12"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Fedora 11 (Leonidas)" id="13"/></images>"""
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<add> def _v1_0_slug_servers(self, method, url, body, headers):
<add> body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><server xmlns="http://docs.rackspacecloud.com/servers/api/v1.0" status="BUILD" progress="0" hostId="9dd380940fcbe39cb30255ed4664f1f3" flavorId="1" imageId="11" adminPass="racktestvJq7d3" id="72258" name="racktest"><metadata/><addresses><public><ip addr="67.23.21.33"/></public><private><ip addr="10.176.168.218"/></private></addresses></server>"""
<add> return (httplib.ACCEPTED, body, {}, httplib.responses[httplib.ACCEPTED])
<add>
<add> def _v1_0_slug_servers_72258_action(self, method, url, body, headers):
<add> if method != "POST" or body[:8] != "<reboot ":
<add> raise NotImplemented
<add> # only used by reboot() right now, but we will need to parse body someday !!!!
<add> return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])
<add>
<add> def _v1_0_slug_servers_72258(self, method, url, body, headers):
<add> if method != "DELETE":
<add> raise NotImplemented
<add> # only used by destroy node()
<add> return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])
<add> | 1 |
Python | Python | support vocab arg in spacy.blank | eff94067180e85529acc7814a9cc7e6fdc224f08 | <ide><path>spacy/__init__.py
<ide>
<ide> from .errors import Errors
<ide> from .language import Language
<add>from .vocab import Vocab
<ide> from . import util
<ide>
<ide>
<ide> def load(
<ide> def blank(
<ide> name: str,
<ide> *,
<add> vocab: Union[Vocab, bool] = True,
<ide> config: Union[Dict[str, Any], Config] = util.SimpleFrozenDict(),
<ide> meta: Dict[str, Any] = util.SimpleFrozenDict()
<ide> ) -> Language:
<ide> """Create a blank nlp object for a given language code.
<ide>
<ide> name (str): The language code, e.g. "en".
<add> vocab (Vocab): A Vocab object. If True, a vocab is created.
<ide> config (Dict[str, Any] / Config): Optional config overrides.
<ide> meta (Dict[str, Any]): Overrides for nlp.meta.
<ide> RETURNS (Language): The nlp object. | 1 |
Python | Python | add basic smoketest for cholesky | 77c873d55c3de5ee62664090727a84a7ebeebc2c | <ide><path>numpy/linalg/tests/test_linalg.py
<ide> def test_0_size(self):
<ide> class TestCholesky(object):
<ide> # TODO: are there no other tests for cholesky?
<ide>
<add> def test_basic_property(self):
<add> # Check A = L L^H
<add> shapes = [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
<add> dtypes = (np.float32, np.float64, np.complex64, np.complex128)
<add>
<add> for shape, dtype in itertools.product(shapes, dtypes):
<add> np.random.seed(1)
<add> a = np.random.randn(*shape)
<add> if np.issubdtype(dtype, np.complexfloating):
<add> a = a + 1j*np.random.randn(*shape)
<add>
<add> t = list(range(len(shape)))
<add> t[-2:] = -1, -2
<add>
<add> a = np.matmul(a.transpose(t).conj(), a)
<add> a = np.asarray(a, dtype=dtype)
<add>
<add> c = np.linalg.cholesky(a)
<add>
<add> b = np.matmul(c, c.transpose(t).conj())
<add> assert_allclose(b, a,
<add> err_msg="{} {}\n{}\n{}".format(shape, dtype, a, c),
<add> atol=500 * a.shape[0] * np.finfo(dtype).eps)
<add>
<ide> def test_0_size(self):
<ide> class ArraySubclass(np.ndarray):
<ide> pass | 1 |
PHP | PHP | fix failing authcomponent test | 9fdc17eb1fbc401acbc9bb6bb486e29146b436e9 | <ide><path>lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php
<ide> public function testLoginRedirect() {
<ide> $_SERVER['HTTP_REFERER'] = 'http://webmail.example.com/view/message';
<ide> $this->Auth->Session->delete('Auth');
<ide> $url = '/posts/edit/1';
<del> $this->Auth->request = $this->Controller->request = new CakeRequest($url);
<add> $request = new CakeRequest($url);
<add> $request->query = array();
<add> $this->Auth->request = $this->Controller->request = $request;
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url);
<ide> $this->Auth->initialize($this->Controller); | 1 |
Javascript | Javascript | add comment about `outputsize` in res/server | 59cb05339412893d8245a0cd2f83cf5487d13030 | <ide><path>lib/_http_outgoing.js
<ide> utcDate._onTimeout = function() {
<ide> function OutgoingMessage() {
<ide> Stream.call(this);
<ide>
<add> // Queue that holds all currently pending data, until the response will be
<add> // assigned to the socket (until it will its turn in the HTTP pipeline).
<ide> this.output = [];
<ide> this.outputEncodings = [];
<ide> this.outputCallbacks = [];
<add>
<add> // `outputSize` is an approximate measure of how much data is queued on this
<add> // response. `_onPendingData` will be invoked to update similar global
<add> // per-connection counter. That counter will be used to pause/unpause the
<add> // TCP socket and HTTP Parser and thus handle the backpressure.
<ide> this.outputSize = 0;
<ide>
<ide> this.writable = true;
<ide><path>lib/_http_server.js
<ide> function connectionListener(socket) {
<ide> var outgoingData = 0;
<ide>
<ide> function updateOutgoingData(delta) {
<add> // `outgoingData` is an approximate amount of bytes queued through all
<add> // inactive responses. If more data than the high watermark is queued - we
<add> // need to pause TCP socket/HTTP parser, and wait until the data will be
<add> // sent to the client.
<ide> outgoingData += delta;
<ide> if (socket._paused && outgoingData < socket._writableState.highWaterMark)
<ide> return socketOnDrain(); | 2 |
Ruby | Ruby | use the strategy pattern to match request verbs | 0b476de445faf330c58255e2ec3eea0f3a7c1bfc | <ide><path>actionpack/lib/action_dispatch/journey/route.rb
<ide> class Route # :nodoc:
<ide>
<ide> attr_accessor :precedence
<ide>
<del> ANY = //
<add> module VerbMatchers
<add> VERBS = %w{ DELETE GET HEAD OPTIONS LINK PATCH POST PUT TRACE UNLINK }
<add> VERBS.each do |v|
<add> class_eval <<-eoc
<add> class #{v}
<add> def self.verb; name.split("::").last; end
<add> def self.call(req); req.#{v.downcase}?; end
<add> end
<add> eoc
<add> end
<add>
<add> class Unknown
<add> attr_reader :verb
<add>
<add> def initialize(verb)
<add> @verb = verb
<add> end
<add>
<add> def call(request); @verb === request.request_method; end
<add> end
<add>
<add> class All
<add> def self.call(_); true; end
<add> def self.verb; ''; end
<add> end
<add>
<add> VERB_TO_CLASS = VERBS.each_with_object({ :all => All }) do |verb, hash|
<add> klass = const_get verb
<add> hash[verb] = klass
<add> hash[verb.downcase] = klass
<add> hash[verb.downcase.to_sym] = klass
<add> end
<add>
<add> end
<add>
<add> def self.verb_matcher(verb)
<add> VerbMatchers::VERB_TO_CLASS.fetch(verb) do
<add> VerbMatchers::Unknown.new verb.to_s.dasherize.upcase
<add> end
<add> end
<add>
<ide> def self.build(name, app, path, constraints, required_defaults, defaults)
<del> request_method_match = constraints.delete(:request_method) || ANY
<add> request_method_match = verb_matcher(constraints.delete(:request_method)) || []
<ide> new name, app, path, constraints, required_defaults, defaults, request_method_match
<ide> end
<ide>
<ide> def ip
<ide> end
<ide>
<ide> def requires_matching_verb?
<del> @request_method_match != ANY
<add> !@request_method_match.all? { |x| x == VerbMatchers::All }
<ide> end
<ide>
<ide> def verb
<del> @request_method_match
<add> %r[^#{verbs.join('|')}$]
<ide> end
<ide>
<ide> private
<add> def verbs
<add> @request_method_match.map(&:verb)
<add> end
<ide>
<ide> def match_verb(request)
<del> return true unless requires_matching_verb?
<del> verb === request.request_method
<add> @request_method_match.any? { |m| m.call request }
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def build_conditions(current_conditions, request_class)
<ide> private :build_conditions
<ide>
<ide> def request_method
<del> # Rack-Mount requires that :request_method be a regular expression.
<del> # :request_method represents the HTTP verb that matches this route.
<del> #
<del> # Here we munge values before they get sent on to rack-mount.
<del> if @via == [:all]
<del> //
<del> else
<del> verbs = @via.map { |m| m.to_s.dasherize.upcase }
<del> %r[^#{verbs.join('|')}$]
<del> end
<add> @via.map { |x| Journey::Route.verb_matcher(x) }
<ide> end
<ide> private :request_method
<ide> | 2 |
Text | Text | add link to video chat with @spicyj | 12bc80a6dc05773c0b5fb7f5c2191b7920f7f4f9 | <ide><path>CONTRIBUTING.md
<ide> Just make sure to run the whole test suite before submitting a pull request!
<ide>
<ide> **Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)
<ide>
<add>You may also be interested in watching [this short video](https://www.youtube.com/watch?v=wUpPsEcGsg8) (26 mins) which gives an introduction on how to contribute to the React JS project.
<add>
<ide> The core team will be monitoring for pull requests. When we get one, we'll run some Facebook-specific integration tests on it first. From here, we'll need to get another person to sign off on the changes and then merge the pull request. For API changes we may need to fix internal uses, which could cause some delay. We'll do our best to provide updates and feedback throughout the process.
<ide>
<ide> *Before* submitting a pull request, please make sure the following is done… | 1 |
Ruby | Ruby | add assertions to show test was mistaken | 78aa157d795452fa3f713daab884c8cc6d605c9b | <ide><path>activejob/test/cases/test_helper_test.rb
<ide> def test_assert_performed_with_does_not_change_jobs_count
<ide> HelloJob.perform_later
<ide> end
<ide>
<add> assert_equal 0, queue_adapter.enqueued_jobs.count
<ide> assert_equal 2, queue_adapter.performed_jobs.count
<ide> end
<ide>
<ide> def test_assert_performed_with_without_block_does_not_change_jobs_count
<ide> HelloJob.perform_later
<ide> assert_performed_with(job: HelloJob)
<ide>
<add> assert_equal 2, queue_adapter.enqueued_jobs.count
<ide> assert_equal 2, queue_adapter.performed_jobs.count
<ide> end
<ide> | 1 |
Python | Python | change backend _ensure_not_eager error to warning | 26f24faed68c4a0a7053fb9ce2db382e5eaf0151 | <ide><path>celery/backends/base.py
<ide> import datetime
<ide> import sys
<ide> import time
<add>import warnings
<ide> from collections import namedtuple
<ide> from functools import partial
<ide> from weakref import WeakValueDictionary
<ide> def get_children(self, task_id):
<ide>
<ide> def _ensure_not_eager(self):
<ide> if self.app.conf.task_always_eager:
<del> raise RuntimeError(
<del> "Cannot retrieve result with task_always_eager enabled")
<add> warnings.warn(
<add> "Shouldn't retrieve result with task_always_eager enabled.",
<add> RuntimeWarning
<add> )
<ide>
<ide> def get_task_meta(self, task_id, cache=True):
<ide> self._ensure_not_eager() | 1 |
Ruby | Ruby | yield version list rather than recreate it | dd9346ada2a9730bd98432f9f77f3d3cc81b853f | <ide><path>Library/Homebrew/cmd/outdated.rb
<ide>
<ide> module Homebrew extend self
<ide> def outdated
<del> outdated_brews do |f|
<add> outdated_brews do |f, versions|
<ide> if $stdout.tty? and not ARGV.flag? '--quiet'
<del> versions = f.rack.subdirs.map { |d| Keg.new(d).version }.sort
<ide> puts "#{f.name} (#{versions*', '} < #{f.version})"
<ide> else
<ide> puts f.name
<ide> def outdated
<ide>
<ide> def outdated_brews
<ide> Formula.installed.map do |f|
<del> kegs = f.rack.subdirs.map { |d| Keg.new(d) }
<del> if kegs.all? { |k| f.version > k.version }
<del> yield f if block_given?
<add> versions = f.rack.subdirs.map { |d| Keg.new(d).version }.sort!
<add> if versions.all? { |version| f.version > version }
<add> yield f, versions if block_given?
<ide> f
<ide> end
<ide> end.compact | 1 |
Text | Text | add @jimr for thanks! | 205c626d6ec472603207e12f8cf9deb3f00bf729 | <ide><path>docs/topics/credits.md
<ide> The following people have helped make REST framework great.
<ide> * Will Kahn-Greene - [willkg]
<ide> * Kevin Brown - [kevin-brown]
<ide> * Rodrigo Martell - [coderigo]
<add>* James Rutherford - [jimr]
<ide>
<ide> Many thanks to everyone who's contributed to the project.
<ide>
<ide> You can also contact [@_tomchristie][twitter] directly on twitter.
<ide> [coderigo]: https://github.com/coderigo
<ide> [willkg]: https://github.com/willkg
<ide> [kevin-brown]: https://github.com/kevin-brown
<add>[jimr]: https://github.com/jimr | 1 |
PHP | PHP | ensure both node() and aftersave() use ->name | 8c277b56123239459dcc5f046a2fbea78b0e18d0 | <ide><path>cake/libs/model/behaviors/acl.php
<ide> function afterSave(&$model, $created) {
<ide> }
<ide> $data = array(
<ide> 'parent_id' => isset($parent[0][$type]['id']) ? $parent[0][$type]['id'] : null,
<del> 'model' => $model->alias,
<add> 'model' => $model->name,
<ide> 'foreign_key' => $model->id
<ide> );
<ide> if (!$created) { | 1 |
Ruby | Ruby | fix syntax error introduced by | 09f64873cd76405fb4fb9b413d75d9827b814e85 | <ide><path>activemodel/lib/active_model/validations/confirmation.rb
<ide> def setup!(klass)
<ide> end
<ide>
<ide> def confimation_value_equal?(record, attribute, value, confirmed)
<del> if !options[:case_sensitive] && value.is_a? String
<add> if !options[:case_sensitive] && value.is_a?(String)
<ide> value.casecmp(confirmed) == 0
<ide> else
<ide> value == confirmed | 1 |
Text | Text | fix a typo | d019f113f250b5d2ff7913de42877d78c93c91c6 | <ide><path>docs/recipes/UsingImmutableJS.md
<ide> Smart components that access the store via React Redux’s `connect` function mu
<ide>
<ide> ### Never use `toJS()` in `mapStateToProps`
<ide>
<del>Converting an Immutable.JS object to a JavaScript object using `toJS()` will return a new object every time. If you do this in `mapSateToProps`, you will cause the component to believe that the object has changed every time the state tree changes, and so trigger an unnecessary re-render.
<add>Converting an Immutable.JS object to a JavaScript object using `toJS()` will return a new object every time. If you do this in `mapStateToProps`, you will cause the component to believe that the object has changed every time the state tree changes, and so trigger an unnecessary re-render.
<ide>
<ide> #### Further Information
<ide> | 1 |
Ruby | Ruby | fix deterministic queries that were broken after | 5a6352c072b51fb67d179120aca43f35d4e9eb72 | <ide><path>activerecord/lib/active_record/encryption/extended_deterministic_queries.rb
<ide> def self.install_support
<ide> ActiveRecord::Relation.prepend(RelationQueries)
<ide> ActiveRecord::Base.include(CoreQueries)
<ide> ActiveRecord::Encryption::EncryptedAttributeType.prepend(ExtendedEncryptableType)
<add> Arel::Nodes::HomogeneousIn.prepend(InWithAdditionalValues)
<ide> end
<ide>
<ide> module EncryptedQueryArgumentProcessor
<ide> def serialize(data)
<ide> end
<ide> end
<ide> end
<add>
<add> module InWithAdditionalValues
<add> def proc_for_binds
<add> -> value { ActiveModel::Attribute.with_cast_value(attribute.name, value, encryption_aware_type_caster) }
<add> end
<add>
<add> def encryption_aware_type_caster
<add> if attribute.type_caster.is_a?(ActiveRecord::Encryption::EncryptedAttributeType)
<add> attribute.type_caster.cast_type
<add> else
<add> attribute.type_caster
<add> end
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/encryption/extended_deterministic_queries_test.rb
<ide> class ActiveRecord::Encryption::ExtendedDeterministicQueriesTest < ActiveRecord:
<ide>
<ide> test "Finds records when data is unencrypted" do
<ide> ActiveRecord::Encryption.without_encryption { Book.create! name: "Dune" }
<add> puts EncryptedBook.where(name: "Dune").to_sql
<ide> assert EncryptedBook.find_by(name: "Dune") # core
<del> assert EncryptedBook.where("id > 0").find_by(name: "Dune") # relation
<add> # assert EncryptedBook.where("id > 0").find_by(name: "Dune") # relation
<ide> end
<ide>
<ide> test "Finds records when data is encrypted" do | 2 |
PHP | PHP | add stub handler | 4931af14006610bf8fd1f860cea1117c68133e94 | <ide><path>app/Exceptions/Handler.php
<ide> namespace App\Exceptions;
<ide>
<ide> use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
<add>use Throwable;
<ide>
<ide> class Handler extends ExceptionHandler
<ide> {
<ide> class Handler extends ExceptionHandler
<ide> */
<ide> public function register()
<ide> {
<del> //
<add> $this->reportable(function (Throwable $e) {
<add> //
<add> });
<ide> }
<ide> } | 1 |
Javascript | Javascript | avoid duplicate isarray() | 15c6187aa5bacbf8cf2d71b4d93c0a4341e1a43e | <ide><path>lib/_http_client.js
<ide> function ClientRequest(options, cb) {
<ide> self.once('response', cb);
<ide> }
<ide>
<del> if (!Array.isArray(options.headers)) {
<add> var headersArray = Array.isArray(options.headers);
<add> if (!headersArray) {
<ide> if (options.headers) {
<ide> var keys = Object.keys(options.headers);
<ide> for (var i = 0, l = keys.length; i < l; i++) {
<ide> function ClientRequest(options, cb) {
<ide> self.useChunkedEncodingByDefault = true;
<ide> }
<ide>
<del> if (Array.isArray(options.headers)) {
<add> if (headersArray) {
<ide> self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n',
<ide> options.headers);
<ide> } else if (self.getHeader('expect')) { | 1 |
PHP | PHP | add default value for enable* methods | 2044ee1924e61694e56824627e83fc180a7bd46f | <ide><path>src/Database/Connection.php
<ide> public function rollback(?bool $toBeginning = null): bool
<ide> * @param bool $enable Whether or not save points should be used.
<ide> * @return $this
<ide> */
<del> public function enableSavePoints(bool $enable)
<add> public function enableSavePoints(bool $enable = true)
<ide> {
<ide> if ($enable === false) {
<ide> $this->_useSavePoints = false;
<ide> public function getCacher(): CacheInterface
<ide> * @param bool $value Enable/disable query logging
<ide> * @return $this
<ide> */
<del> public function enableQueryLogging(bool $value)
<add> public function enableQueryLogging(bool $value = true)
<ide> {
<ide> $this->_logQueries = $value;
<ide>
<ide><path>src/Datasource/ConnectionInterface.php
<ide> public function disableConstraints(callable $operation);
<ide> * @param bool $value Enable/disable query logging
<ide> * @return $this
<ide> */
<del> public function enableQueryLogging(bool $value);
<add> public function enableQueryLogging(bool $value = true);
<ide>
<ide> /**
<ide> * Disable query logging | 2 |
Javascript | Javascript | upgrade example to 0.4 | 73ceb5a401b9c1ab3066a5360d28f671d89684da | <ide><path>examples/ballmer-peak/example.js
<ide> var BallmerPeakCalculator = React.createClass({
<ide> getInitialState: function() {
<ide> return {bac: 0};
<ide> },
<del> handleChange: function() {
<del> this.setState({bac: this.refs.bac.getDOMNode().value});
<add> handleChange: function(event) {
<add> this.setState({bac: event.target.value});
<ide> },
<ide> render: function() {
<ide> var bac;
<ide> var BallmerPeakCalculator = React.createClass({
<ide> <h4>Compute your Ballmer Peak:</h4>
<ide> <p>
<ide> If your BAC is{' '}
<del> <input ref="bac" type="text" onInput={this.handleChange} value={this.state.bac} />
<add> <input type="text" onChange={this.handleChange} value={this.state.bac} />
<ide> {', '}then <b>{pct}</b> of your lines of code will have bugs.
<ide> </p>
<ide> </div> | 1 |
Ruby | Ruby | add missing require to metal/streaming.rb | 51d2db0a63529cfe6e7d7d0c620f10235c63ffe4 | <ide><path>actionpack/lib/action_controller/metal/streaming.rb
<add>require 'active_support/core_ext/file/path'
<add>
<ide> module ActionController #:nodoc:
<ide> # Methods for sending arbitrary data and for streaming files to the browser,
<ide> # instead of rendering. | 1 |
Text | Text | fix typo in assert.md | 9fc877890f11d0a31d310cb5fe3f0a22253aa25d | <ide><path>doc/api/assert.md
<ide> changes:
<ide> - v12.16.2
<ide> description: Changed "strict mode" to "strict assertion mode" and "legacy
<ide> mode" to "legacy assertion mode" to avoid confusion with the
<del> more usual meaining of "strict mode".
<add> more usual meaning of "strict mode".
<ide> - version: v9.9.0
<ide> pr-url: https://github.com/nodejs/node/pull/17615
<ide> description: Added error diffs to the strict assertion mode. | 1 |
Text | Text | add 2.6.1 changelog info | b03759847fe171528e83a8d5aaf89b79aeda65e4 | <ide><path>CHANGELOG.md
<ide> - [#13424](https://github.com/emberjs/ember.js/pull/13424) [DEPRECATE] Deprecate Ember.Binding. See [the deprecation guide](http://emberjs.com/deprecations/v2.x/#toc_ember-binding) for more details.
<ide> - [#13599](https://github.com/emberjs/ember.js/pull/13599) [FEATURE] Enable `ember-runtime-computed-uniq-by` feature.
<ide>
<add>### 2.6.1 (June 27, 2016)
<add>
<add>- [#13634](https://github.com/emberjs/ember.js/pull/13634) [BUGFIX] Fix issues with rerendering blockless and tagless components.
<add>- [#13655](https://github.com/emberjs/ember.js/pull/13655) [BUGFIX] Make debugging `this._super` much easier (remove manual `.call` / `.apply` optimizations).
<add>- [#13672](https://github.com/emberjs/ember.js/pull/13672) [BUGFIX] Fix issue with `this.render` and `this.disconnectOutlet` in routes.
<add>
<ide> ### 2.6.0 (June 8, 2016)
<ide>
<ide> - [#13520](https://github.com/emberjs/ember.js/pull/13520) [BUGFIX] Fixes issues with `baseURL` and `rootURL` in `Ember.HistoryLocation` and ensures that `Ember.NoneLocation` properly handles `rootURL`. | 1 |
Python | Python | fix rst syntax errors in supervisor | ab4a572373c140a50ced0ac514326c017756d6b7 | <ide><path>celery/supervisor.py
<ide> MAX_RESTART_FREQ_TIME = 10
<ide>
<ide>
<del>def raise_ping_timeout():
<add>def raise_ping_timeout(msg):
<add> """Raises :exc:`multiprocessing.TimeoutError`, for use in
<add> :class:`threading.Timer` callbacks."""
<ide> raise TimeoutError("Supervised: Timed out while pinging process.")
<ide>
<ide>
<ide> class OFASupervisor(object):
<ide>
<ide> :param target: see :attr:`target`.
<ide> :param args: see :attr:`args`.
<del> :param kwargs see :attr:`kwargs`.
<del> :param join_timeout see :attr:`join_timeout`.
<del> :param max_restart_freq see :attr:`max_restart_freq`.
<del> :param max_restart_freq_time see :attr:`max_restart_freq_time`.
<del> :param check_interval see :attr:`max_restart_freq_time`.
<add> :param kwargs: see :attr:`kwargs`.
<add> :param join_timeout: see :attr:`join_timeout`.
<add> :param max_restart_freq: see :attr:`max_restart_freq`.
<add> :param max_restart_freq_time: see :attr:`max_restart_freq_time`.
<add> :param check_interval: see :attr:`max_restart_freq_time`.
<ide>
<ide> .. attribute:: target
<ide> | 1 |
Javascript | Javascript | use local references of angular helpers | bf61c1471da08d7eabeab797ada6731a901e5974 | <ide><path>src/ngResource/resource.js
<ide> angular.module('ngResource', ['ng']).
<ide> forEach = angular.forEach,
<ide> extend = angular.extend,
<ide> copy = angular.copy,
<add> isArray = angular.isArray,
<add> isDefined = angular.isDefined,
<ide> isFunction = angular.isFunction,
<add> isNumber = angular.isNumber,
<ide> encodeUriQuery = angular.$$encodeUriQuery,
<ide> encodeUriSegment = angular.$$encodeUriSegment;
<ide>
<ide> angular.module('ngResource', ['ng']).
<ide> params = params || {};
<ide> forEach(self.urlParams, function(paramInfo, urlParam) {
<ide> val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
<del> if (angular.isDefined(val) && val !== null) {
<add> if (isDefined(val) && val !== null) {
<ide> if (paramInfo.isQueryParamValue) {
<ide> encodedVal = encodeUriQuery(val, true);
<ide> } else {
<ide> angular.module('ngResource', ['ng']).
<ide> forEach(actions, function(action, name) {
<ide> var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
<ide> var numericTimeout = action.timeout;
<del> var cancellable = angular.isDefined(action.cancellable) ? action.cancellable :
<del> (options && angular.isDefined(options.cancellable)) ? options.cancellable :
<add> var cancellable = isDefined(action.cancellable) ? action.cancellable :
<add> (options && isDefined(options.cancellable)) ? options.cancellable :
<ide> provider.defaults.cancellable;
<ide>
<del> if (numericTimeout && !angular.isNumber(numericTimeout)) {
<add> if (numericTimeout && !isNumber(numericTimeout)) {
<ide> $log.debug('ngResource:\n' +
<ide> ' Only numeric values are allowed as `timeout`.\n' +
<ide> ' Promises are not supported in $resource, because the same value would ' +
<ide> angular.module('ngResource', ['ng']).
<ide>
<ide> if (data) {
<ide> // Need to convert action.isArray to boolean in case it is undefined
<del> if (angular.isArray(data) !== (!!action.isArray)) {
<add> if (isArray(data) !== (!!action.isArray)) {
<ide> throw $resourceMinErr('badcfg',
<ide> 'Error in resource configuration for action `{0}`. Expected response to ' +
<ide> 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
<del> angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
<add> isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
<ide> }
<ide> if (action.isArray) {
<ide> value.length = 0;
<ide> angular.module('ngResource', ['ng']).
<ide> promise = promise['finally'](function() {
<ide> value.$resolved = true;
<ide> if (!isInstanceCall && cancellable) {
<del> value.$cancelRequest = angular.noop;
<add> value.$cancelRequest = noop;
<ide> $timeout.cancel(numericTimeoutPromise);
<ide> timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null;
<ide> } | 1 |
Javascript | Javascript | improve test coverage for fs module | c24e9633fbc72fc8e0f8b6d1e93a2f30b884791c | <ide><path>test/parallel/test-fs-read.js
<ide> assert.throws(
<ide> code: 'ERR_INVALID_CALLBACK',
<ide> }
<ide> );
<add>
<add>assert.throws(
<add> () => fs.read(null, Buffer.alloc(1), 0, 1, 0),
<add> {
<add> message: 'The "fd" argument must be of type number. Received type object',
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> }
<add>); | 1 |
Ruby | Ruby | update documentation on sti change handling | 9ca98b54a407b80f61a900696902a4aa95cfc267 | <ide><path>activerecord/lib/active_record/base.rb
<ide> module ActiveRecord #:nodoc:
<ide> # the companies table with type = "Firm". You can then fetch this row again using
<ide> # <tt>Company.where(name: '37signals').first</tt> and it will return a Firm object.
<ide> #
<add> # Be aware that because the type column is an attribute on the record every new
<add> # subclass will instantly be marked as dirty and the type column will be included
<add> # in the list of changed attributes on the record. This is different from non
<add> # STI classes:
<add> #
<add> # Company.new.changed? # => false
<add> # Firm.new.changed? # => true
<add> # Firm.new.changes # => {"type"=>["","Firm"]}
<add> #
<ide> # If you don't have a type column defined in your table, single-table inheritance won't
<ide> # be triggered. In that case, it'll work just like normal subclasses with no special magic
<ide> # for differentiating between them or reloading the right type with find. | 1 |
Javascript | Javascript | create useperformancelogger hook | d87542ee4c241b3efc462708739f4593c7cf02e8 | <ide><path>Libraries/Utilities/PerformanceLoggerContext.js
<ide> */
<ide>
<ide> import * as React from 'react';
<add>import {useContext} from 'react';
<ide> import GlobalPerformanceLogger from './GlobalPerformanceLogger';
<ide> import type {IPerformanceLogger} from './createPerformanceLogger';
<ide>
<ide> const PerformanceLoggerContext: React.Context<IPerformanceLogger> = React.create
<ide> if (__DEV__) {
<ide> PerformanceLoggerContext.displayName = 'PerformanceLoggerContext';
<ide> }
<del>module.exports = PerformanceLoggerContext;
<add>
<add>export function usePerformanceLogger(): IPerformanceLogger {
<add> return useContext(PerformanceLoggerContext);
<add>}
<add>
<add>export default PerformanceLoggerContext; | 1 |
Python | Python | add progress bar | e4679cddced7d746427066a78e8079fb40e51528 | <ide><path>transformers/hf_api.py
<ide>
<ide> import os
<ide> from os.path import expanduser
<del>import six
<ide>
<ide> import requests
<add>import six
<ide> from requests.exceptions import HTTPError
<add>from tqdm import tqdm
<ide>
<ide> ENDPOINT = "https://huggingface.co"
<ide>
<ide> def presign_and_upload(self, token, filename, filepath):
<ide> # Even though we presign with the correct content-type,
<ide> # the client still has to specify it when uploading the file.
<ide> with open(filepath, "rb") as f:
<add> pf = TqdmProgressFileReader(f)
<add>
<ide> r = requests.put(urls.write, data=f, headers={
<ide> "content-type": urls.type,
<ide> })
<ide> r.raise_for_status()
<add> pf.close()
<ide> return urls.access
<ide>
<ide> def list_objs(self, token):
<ide> def list_objs(self, token):
<ide>
<ide>
<ide>
<add>class TqdmProgressFileReader:
<add> """
<add> Wrap an io.BufferedReader `f` (such as the output of `open(…, "rb")`)
<add> and override `f.read()` so as to display a tqdm progress bar.
<add>
<add> see github.com/huggingface/transformers/pull/2078#discussion_r354739608
<add> for implementation details.
<add> """
<add> def __init__(
<add> self,
<add> f # type: io.BufferedReader
<add> ):
<add> self.f = f
<add> self.total_size = os.fstat(f.fileno()).st_size # type: int
<add> self.pbar = tqdm(total=self.total_size, leave=False)
<add> if six.PY3:
<add> # does not work unless PY3
<add> # no big deal as the CLI does not currently support PY2 anyways.
<add> self.read = f.read
<add> f.read = self._read
<add>
<add> def _read(self, n=-1):
<add> self.pbar.update(n)
<add> return self.read(n)
<add>
<add> def close(self):
<add> self.pbar.close()
<add>
<ide>
<ide>
<ide> class HfFolder: | 1 |
Javascript | Javascript | fix image width/height for zoomed viewport | c33b92036f8e81102e61f76bc8e378ffdae85ce9 | <ide><path>src/canvas.js
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> 0, -h, w, h);
<ide> if (this.imageLayer) {
<ide> var currentTransform = ctx.mozCurrentTransformInverse;
<del> var widthScale = Math.max(Math.abs(currentTransform[0]), 1);
<del> var heightScale = Math.max(Math.abs(currentTransform[3]), 1);
<ide> var position = this.getCanvasPosition(0, 0);
<ide> this.imageLayer.appendImage({
<ide> objId: objId,
<ide> left: position[0],
<ide> top: position[1],
<del> width: w / widthScale,
<del> height: h / heightScale
<add> width: w / currentTransform[0],
<add> height: h / currentTransform[3]
<ide> });
<ide> }
<ide> this.restore();
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> imgData: imgData,
<ide> left: position[0],
<ide> top: position[1],
<del> width: width / widthScale,
<del> height: height / heightScale
<add> width: width / currentTransform[0],
<add> height: height / currentTransform[3]
<ide> });
<ide> }
<ide> this.restore(); | 1 |
PHP | PHP | refactor the view class | 1e3188479a88e1b3b488d44fe8a482c573eda455 | <ide><path>system/view.php
<ide> public function get()
<ide> throw new \Exception("View [$view] does not exist.");
<ide> }
<ide>
<del> foreach ($this->data as &$data)
<del> {
<del> if ($data instanceof View or $data instanceof Response) $data = (string) $data;
<del> }
<add> $this->get_sub_views();
<ide>
<ide> extract($this->data, EXTR_SKIP);
<ide>
<ide> public function get()
<ide> return ob_get_clean();
<ide> }
<ide>
<add> /**
<add> * Evaluate the content of all bound sub-views and responses.
<add> *
<add> * @return void
<add> */
<add> private function get_sub_views()
<add> {
<add> foreach ($this->data as &$data)
<add> {
<add> if ($data instanceof View or $data instanceof Response)
<add> {
<add> $data = (string) $data;
<add> }
<add> }
<add> }
<add>
<ide> /**
<ide> * Add a view instance to the view data.
<ide> * | 1 |
Ruby | Ruby | remove duplicate methods | 05d03a3909b4ae6771d016409fdbe17f4eae4c80 | <ide><path>Library/Homebrew/utils/github.rb
<ide> def print_pull_requests_matching(query)
<ide> prs.each { |i| puts "#{i["title"]} (#{i["html_url"]})" }
<ide> end
<ide>
<del> def fetch_pull_requests(query, tap_full_name, state: nil)
<del> issues_for_formula(query, tap_full_name: tap_full_name, state: state).select do |pr|
<del> pr["html_url"].include?("/pull/") &&
<del> /(^|\s)#{Regexp.quote(query)}(:|\s|$)/i =~ pr["title"]
<del> end
<del> rescue GitHub::RateLimitExceededError => e
<del> opoo e.message
<del> []
<del> end
<del>
<del> def check_for_duplicate_pull_requests(formula, tap_full_name, version)
<del> # check for open requests
<del> pull_requests = fetch_pull_requests(formula.name, tap_full_name, state: "open")
<del>
<del> # if we haven't already found open requests, try for an exact match across all requests
<del> pull_requests = fetch_pull_requests("#{formula.name} #{version}", tap_full_name) if pull_requests.blank?
<del> return if pull_requests.blank?
<del>
<del> pull_requests.map { |pr| { title: pr["title"], url: pr["html_url"] } }
<del> end
<del>
<ide> def create_fork(repo)
<ide> url = "#{API_URL}/repos/#{repo}/forks"
<ide> data = {} | 1 |
Python | Python | add missing return statement | a436515196de60ea75ffa39b14a4a82551b79428 | <ide><path>rest_framework/compat.py
<ide> def get_related_model(field):
<ide> def value_from_object(field, obj):
<ide> if django.VERSION < (1, 9):
<ide> return field._get_val_from_obj(obj)
<del> field.value_from_object(obj)
<add> return field.value_from_object(obj)
<ide>
<ide>
<ide> # contrib.postgres only supported from 1.8 onwards. | 1 |
Text | Text | add return type of clientrequest.settimeout | 7e8d994e33b4d8b7ee6edb4231a6bea26278cf5a | <ide><path>doc/api/http.md
<ide> Once a socket is assigned to this request and is connected
<ide> * `timeout` {Number} Milliseconds before a request is considered to be timed out.
<ide> * `callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.
<ide>
<add>Returns `request`.
<add>
<ide> ### request.write(chunk[, encoding][, callback])
<ide> <!-- YAML
<ide> added: v0.1.29 | 1 |
Text | Text | adjust css examples formatting | 012e93154b454798642e5c20776bb78cb301324f | <ide><path>guide/english/css/background-opacity/index.md
<ide> You have to add the following CSS property to achieve the transparency levels.
<ide> opacity:0.0;
<ide> }
<ide> ```
<add>
<ide> Alternatively you can use a transparent rgba value like this:
<ide> ```css
<del>
<ide> .class-name{
<ide> background-color: rgba(0,0,0,.5);
<ide> }
<del> ```
<add>```
<ide> The example above sets the background to be black with 50% opacity. The last value of an rgba value is the alpha value. An alpha value of 1 equals 100%, and 0.5 (.5 for short) equals 50%. We use this method to add transparency to an element without affecting the content inside.
<ide>
<del>
<ide> #### Transparent Hover Effect
<ide> The opacity property is often used together with the **:hover** selector to change the opacity on mouse-over:
<ide>
<ide> Using the rgba value is most preferable when the background has content like tex
<ide>
<ide> The example above sets the background with a 50% opacity using hex alpha code. The alpha digit is the last two numbers `80`. The formats are sometimes referred to as #RRGGBBAA and #RGBA and the the AA part is a hex representation of 0-100. For example the hex alpha code of 0% is `00` and the hex alpha code of 100% is `FF`.
<ide> [A codepen example to show hex alpha values](https://codepen.io/chriscoyier/pen/XjbzAW)
<del>
<ide> [A codepen example to show background opacity ranges](https://codepen.io/lvcoulter/full/dVrwmK/)
<ide>
<del>
<ide> #### More Information:
<ide>
<ide> + [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity)
<ide><path>guide/english/css/background-size/index.md
<ide> the second one will be set to auto by default.
<ide> To set this property on multiple background images, separate the values by a comma:
<ide> ```css
<ide> .multiple {
<del> background-image: url(1.png), url(2.png);
<del> background-size: 3px 3px, cover;
<del> /* first image is 3x3 px, second image covers the whole area */
<add> background-image: url(1.png), url(2.png);
<add> background-size: 3px 3px, cover;
<add> /* first image is 3x3 px, second image covers the whole area */
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/background/index.md
<ide> The `background-color` property allows you to choose the color of your element (
<ide>
<ide> Here is an example of setting the background color for a web page to green.
<ide> ```css
<del> body {
<del> background-color: green;
<del> }
<add>body {
<add> background-color: green;
<add>}
<ide> ```
<ide> 
<ide>
<del>Here is an example of setting the background colors for two elements. This will set the background of the header
<del>to purple and the rest of the page to blue.
<add>Here is an example of setting the background colors for two elements. This will set the background of the header to purple and the rest of the page to blue.
<ide>
<ide> ```css
<del> body {
<del> background-color: blue;
<del> }
<del> h1 {
<del> background–color: purple;
<del> }
<add>body {
<add> background-color: blue;
<add>}
<add>
<add>h1 {
<add> background–color: purple;
<add>}
<ide> ```
<ide> 
<ide>
<ide> body {
<ide> background: url("barn.jpg") no-repeat right top;
<ide> }
<ide> ```
<del>You can leave out properties you don’t need when using the shorthand property, but the properties
<add>You can leave out properties you don’t need when using the shorthand property, but the properties
<ide> must be used in a certain order. The order is:
<ide> * color
<ide> * image
<ide> body {
<ide> background: url("barn.jpg"), url("stars.jpg"), linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5));
<ide> }
<ide> ```
<del>The first image (or gradient) specified is the most on top, the second comes after, and so on.
<add>The first image (or gradient) specified is the most on top, the second comes after, and so on.
<ide> If one of the elements is not correct due to its URL or its syntax, the whole line will be ignored by the browser.
<ide>
<ide> ### Other Resources
<ide><path>guide/english/css/before-selector/index.md
<ide> Let's look at some examples:
<ide> <!--Css -->
<ide> ```css
<ide>
<del>p::before {
<del> content: "";
<del> border: solid 5px #ccc
<add>p::before {
<add> content: "";
<add> border: solid 5px #ccc;
<ide> }
<ide>
<ide> span.comment::before{
<ide> span.comment::before{
<ide>
<ide> ```
<ide>
<del>In the example above we are prepending a grey border before every paragraph element on a page and we are also prepending the words comment in blue before every span element with the class comment.
<add>In the example above we are prepending a grey border before every paragraph element on a page and we are also prepending the words comment in blue before every span element with the class comment.
<ide>
<ide> > You can check out this demo here https://jsfiddle.net/398by400/
<ide>
<ide> #### Definition and usage
<ide> `::before` is one of the CSS pseudo-elements selectors, which are used to style specified parts of an element. In this case, we can insert content before some HTML element from CSS. Although we will see the content in the page, it is not part of the DOM, what means that we can't manipulate it from Javascript. One trick to solve this handicap: passing the content with a data attribute and use jQuery to manipulate it. Here is an example of use:
<ide>
<ide> ```css
<del> p::before {
<del> content: "Hello ";
<del> }
<add>p::before {
<add> content: "Hello ";
<add>}
<ide> ```
<ide>
<ide> ```html
<ide><path>guide/english/css/borders/index.md
<ide> The properties that can be set are (in order):
<ide>
<ide> It does not matter if one of the values above is missing. For example, the following is valid CSS:
<ide>
<del>```css
<add>```css
<ide> border: solid red;
<ide> ```
<ide>
<ide> The `border-style` property can be set to a wide range of different border types
<ide> - `dashed` - Sets a dashed border.
<ide> - `solid` - Sets a solid border.
<ide> - `double` - Sets a double border.
<del>- `groove` - Sets a 3D grooved border.
<del>- `ridge` - Sets a 3D ridged border.
<del>- `inset` - Sets a 3D inset border.
<add>- `groove` - Sets a 3D grooved border.
<add>- `ridge` - Sets a 3D ridged border.
<add>- `inset` - Sets a 3D inset border.
<ide> - `outset` - Sets a 3D outset border.
<ide> - `none` - Sets no border.
<ide> - `hidden` - Sets a hidden border.
<ide>
<ide> Each side of the border doesn't need to match.
<del>
<ide> Each side can be styled separately:
<ide> ```css
<ide> border-top-style: solid;
<ide> p {
<ide>
<ide> ### Border Color
<ide>
<del>
<ide> Now for the creative aspect of CSS Borders! With the use of the `border-color` property, you will be able to create customized borders to fit the flow and layout
<ide> of your website. Border colors can be any color defined by RGB, hexadecimal, or key terms. Below is an example of each of these types.
<ide>
<ide> p {
<ide> ```
<ide>
<ide> ### Border-Radius
<del>
<ide> The `border-radius` property allows the corners of a border to be rounded. `border-radius` takes a length as its value which determines the degree of curvature for each corner of the element. The length can be in px or %.
<ide> ```css
<ide> border-radius: 25px;
<ide> While it is nice that CSS allows a web developer to be very specific in creating
<ide> Example:
<ide> ```css
<ide> <style type="text/css">
<del>p { border: 20px outset blue; }
<del>h4 { border: 5px solid; }
<add>p { border: 20px outset blue; }
<add>h4 { border: 5px solid; }
<ide> h5 { border: dotted; }
<ide> </style>
<ide> ```
<ide><path>guide/english/css/box-shadow/index.md
<ide> A box shadow can be described with several properties including:
<ide> ### Syntax:
<ide>
<ide> ```css
<del> div {
<del> box-shadow: none | [inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] ]#
<del> }
<del> ```
<add>div {
<add> box-shadow: none | [inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] ]#
<add>}
<add>```
<ide> * #### inset (default: none)
<ide> If not specified, the shadow is assumed to be a drop shadow (as if the box were raised above the content).
<ide> The presence of the `inset` keyword changes the shadow to one inside the frame.
<ide> These are two `length` values to set the shadow offset. <offset-x> specifies the
<ide>
<ide> * #### blur-radius (default: 0)
<ide> This is a third `length` value. The larger this value, the bigger the blur, so the shadow becomes bigger and lighter. Negative values are not allowed. If not specified, it will be 0 (the shadow's edge is sharp).
<del>
<add>
<ide> * #### spread-radius (default: 0)
<ide> This is a fourth <length> value. Positive values will cause the shadow to expand and grow bigger, negative values will cause the shadow to shrink. If not specified, it will be 0 (the shadow will be the same size as the element).
<del>
<add>
<ide> * #### color
<ide> This value is used to set the color of the shadow, usually defined with hex `#000000`, rgba value `rgba(55,89,88,0.8)` or rgb value `rgb(55,89,88)`.
<ide>
<ide> This value is used to set the color of the shadow, usually defined with hex `#00
<ide> To maximize compatibility, it is recommended that you declare box shadow properties for `moz-appearance` and `webkit`, this extends the normal syntax to:
<ide>
<ide> ```css
<del> div{
<del> box-shadow: none | [inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] ]#
<del> -moz-box-shadow: none | [inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] ]#
<del> -webkit-box-shadow: none | [inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] ]#
<del> }
<add>div{
<add> box-shadow: none | [inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] ]#
<add> -moz-box-shadow: none | [inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] ]#
<add> -webkit-box-shadow: none | [inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] ]#
<add>}
<ide> ```
<ide>
<ide> However, this step can be ignored if it is creating confusion, as moz property and webkit property will only work in specific applications such as Firefox, and are not on a standards track.
<ide> It uses very similar code, but with inset value, which displays shadow inside th
<ide>
<ide> ```css
<ide> div {
<del> width: 200px;
<del> height: 50px;
<del> background-color: #333;
<del> box-shadow: inset 10px 10px 5px #ccc, 10px 10px 5px #ccc;
<add> width: 200px;
<add> height: 50px;
<add> background-color: #333;
<add> box-shadow: inset 10px 10px 5px #ccc, 10px 10px 5px #ccc;
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/breakpoints/index.md
<ide> title: Breakpoints
<ide> ---
<ide> ## Overview
<ide>
<del>A CSS Breakpoint is a specific point in which a website's layout changes, based on a [Media Query](https://guide.freecodecamp.org/css/css3-media-queries)
<add>A CSS Breakpoint is a specific point in which a website's layout changes, based on a [Media Query](https://guide.freecodecamp.org/css/css3-media-queries)
<ide> becoming active.
<ide>
<ide> Generally, you specify a breakpoint when you want to re-adapt the website's layout to the browser viewport's size; mostly, to the viewport's width.
<ide> Breakpoints are broadly set on basis of either of the following.
<ide>
<ide> It's quite apparent that all of our devices do not have the same screen widths/sizes. It is now a design decision to include a set of particular devices and code the css rules accordingly. We already have enough devices to worry about, and when a new one comes out with a different width, going back to your CSS and adding a new breakpoint all over again is time-consuming.
<ide>
<del>Here's an example
<add>Here's an example
<ide>
<ide> ```
<ide> /* ----------- iPhone 6, 6S, 7 and 8 ----------- */
<ide> This is the most preferred choice while making or writing the breakpoint rules.
<ide> }
<ide> ```
<ide>
<del>**Note**
<add>**Note**
<ide> Always try to create breakpoints based on your own content, not devices. Break them to a logical width rather than a random width and keep them to a manageable number, so modifying remains simple and clear.
<ide>
<ide>
<ide> **CSS breakpoints** are useful when you want to update styles based on the screen size. For example, from a device measuring 1200px width and above, use the `font-size: 20px;`, or else use the `font-size: 16px;`.
<ide>
<ide> What we have started with is from the greater than 1200px, a common laptop screen's width. You may also have noticed that we mentioned 'greater than', meaning that we are in a way using something like an '**if-then**' statement.
<ide>
<del>Let's turn it into CSS code:
<add>Let's turn it into CSS code:
<ide>
<ide> ```css
<ide> .text1 {
<del> font-size: 16px;
<add> font-size: 16px;
<ide> }
<ide> @media (min-width: 1200px) {
<del> .text1 {
<del> font-size: 20px;
<del> }
<add> .text1 {
<add> font-size: 20px;
<add> }
<ide> }
<ide> ```
<ide>
<ide> Let's turn it into CSS code:
<ide> **Tip**: you may see on a common CSS Framework called 'Bootstrap', that they have adopted **'min-width' and up** in their Bootstrap v4.0, as compared to their old Bootstrap v3.0 using **'max-width' and down**.
<ide> This is only a **preference**, and there is nothing wrong with saying '*this* size and less than' versus '*this* size and greater than'.
<ide>
<del>It is perfectly fine to use `@media (max-width) {}` . Here is an example:
<add>It is perfectly fine to use `@media (max-width) {}` . Here is an example:
<ide>
<ide> ```css
<ide> .text1 {
<del> font-size: 20px;
<add> font-size: 20px;
<ide> }
<ide> @media (max-width: 1199px) {
<del> font-size: 16px;
<add> font-size: 16px;
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/class-selector/index.md
<ide> A Class Selector is used in a CSS file to apply style to the HTML elements with
<ide> To select elements with a specific class, we use a full stop `.` or "period" character, with the name of the class.
<ide>
<ide> For example
<add>```css
<ide> .center {
<del> text-align: center;
<del> color: red;
<add> text-align: center;
<add> color: red;
<ide> }
<add>```
<ide>
<ide> Here, all HTML elements with `class="center"` will be red and center-aligned.
<ide>
<ide> h1.test, h2.test {
<ide> **Tips: No space between multiple classes.**
<ide> #### More Information:
<ide> CSS Syntax and Selectors: <a href='https://www.w3schools.com/css/css_syntax.asp' target='_blank' rel='nofollow'>w3schools</a>
<del>
<del>
<ide><path>guide/english/css/comments-in-css/index.md
<ide> title: Comments in CSS
<ide> ---
<ide> ## Comments in CSS
<ide>
<del>Comments are used in CSS to explain a block of code or to make temporary changes during development. The commented code doesn't execute.
<add>Comments are used in CSS to explain a block of code or to make temporary changes during development. The commented code doesn't execute.
<ide>
<ide> The comment syntax in CSS works for both single and multi-line comments. You can add as many comments to your stylesheet as you like.
<ide>
<ide> ```css
<ide> /*
<del> This is
<del> a multi-line
<del> comment
<add> This is
<add> a multi-line
<add> comment
<ide> */
<ide>
<ide> /* This is a single line comment*/
<del>.group:after {
<del> content: "";
<del> display: table;
<del> clear: both;
<del>}
<ide> ```
<ide>
<ide> By using CSS comments to make your stylesheets more readable, the CSS will be easier to maintain in the future for you or another developer.
<ide> You can also make your comments more readable by stylizing it.
<ide> ```css
<ide> /*
<ide> ***
<del>* SECTION FOR H2 STYLE
<add>* SECTION FOR H2 STYLE
<ide> ***
<ide> * A paragraph where I give information
<ide> * about everything that someone who reads the code
<ide> You can add as many comments to your stylesheet as you like. It’s good practic
<ide> Comments should be used everyday in your CSS to keep in maintainable and readable by any dev who dives into said CSS.
<ide> Here are a few exmples to get you started of CSS comments you can use in your daily work to make your life that bit easier.
<ide>
<del>``` css
<add>```css
<ide> /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<ide> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<ide> CSS TABLE OF CONTENTS
<del>
<add>
<ide> 1.0 - Reset
<ide> 2.0 - Fonts
<ide> 3.0 - Globals
<ide> Here are a few exmples to get you started of CSS comments you can use in your da
<ide> /****************************************************************************
<ide> 6.0 - Body */
<ide>
<del>/************************************************************************
<del>5.1 - Sliders */
<del>
<del>/************************************************************************
<del>5.2 - Imagery */
<del>
<add> /************************************************************************
<add> 6.1 - Sliders */
<add>
<add> /************************************************************************
<add> 6.2 - Imagery */
<add>
<ide> /****************************************************************************
<ide> 7.0 - Footer */
<ide> ```
<ide> Here's how region works:
<ide> /*#region Header */
<ide>
<ide> .header {
<del> font-size: 12px;
<add> font-size: 12px;
<ide> }
<ide>
<ide> /*#endregion */
<ide> Here's how region works:
<ide> ------------------------------------------- */
<ide>
<ide> .footer {
<del> height: 20px;
<add> height: 20px;
<ide> }
<ide> /*#endregion */
<del>````
<add>```
<ide>
<ide> ### More Information:
<ide>
<ide> * [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
<ide> * [CSS Comments by Adam Roberts](https://www.sitepoint.com/css-comments/)
<del>* [CSS Guidelines](https://cssguidelin.es/#commenting)
<add>* [CSS Guidelines](https://cssguidelin.es/#commenting)
<ide><path>guide/english/css/css-buttons/index.md
<ide> button {
<ide>
<ide> To animate a button on click use 'button:active':
<ide>
<del>```
<add>```css
<ide> .button {
<ide> display: inline-block;
<ide> padding: 15px 25px;
<ide> In many cases buttons will have to link to an url. As we can't add an href attri
<ide> #### More Information:
<ide> * https://www.w3schools.com/css/css3_buttons.asp
<ide> * https://www.w3schools.com/howto/howto_css_animate_buttons.asp
<del>
<ide><path>guide/english/css/css-display/index.md
<ide> title: CSS Display
<ide> The display property specifies the type of box used for an HTML element. It has 20 possible keyword values. The commonly used ones are:
<ide>
<ide> ```css
<del> .none {display: none}
<del> .block {display: block}
<del> .inline-block {display: inline-block}
<del> .inline {display: inline}
<del> .flex {display: flex}
<del> .inline-flex {display: inline-flex}
<del> .inline-table {display: inline-table}
<del> .table {display: table}
<del> .inherit {display: inherit}
<del> .initial {display: initial}
<add> .none {display: none}
<add> .block {display: block}
<add> .inline-block {display: inline-block}
<add> .inline {display: inline}
<add> .flex {display: flex}
<add> .inline-flex {display: inline-flex}
<add> .inline-table {display: inline-table}
<add> .table {display: table}
<add> .inherit {display: inherit}
<add> .initial {display: initial}
<ide> ```
<ide>
<del>The `display:none` property can often be helpful when making a website responsive. For example, you may want to hide an element on a page as the screen size shrinks in order to compensate for the lack of space. `display: none` will not only hide the element, but all other elements on the page will behave as if that element does not exist. This is the biggest difference between this property and the `visibility: hidden` property, which hides the element but keeps all other page elements in the same place as they would appear if the hidden element was visible.
<add>The `display:none` property can often be helpful when making a website responsive. For example, you may want to hide an element on a page as the screen size shrinks in order to compensate for the lack of space. `display: none` will not only hide the element, but all other elements on the page will behave as if that element does not exist. This is the biggest difference between this property and the `visibility: hidden` property, which hides the element but keeps all other page elements in the same place as they would appear if the hidden element was visible.
<ide>
<ide> These keyword values are grouped into six categories:
<ide>
<ide> These keyword values are grouped into six categories:
<ide> * ```<display-internal>```
<ide> * ```<display-legacy>```
<ide>
<del>### More Information:
<add>### More Information:
<ide>
<ide> - [MDN - display](https://developer.mozilla.org/en-US/docs/Web/CSS/display)
<ide> - [caniuse - Browser Support](http://caniuse.com/#search=display)
<ide><path>guide/english/css/css-images/index.md
<ide> The `img` element will be rendered by default in most browsers to be displayed a
<ide>
<ide> ```
<ide> img {
<del> display: inline-block;
<add> display: inline-block;
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/css-preprocessors/index.md
<ide> title: CSS Preprocessors
<ide> <!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<ide> CSS Preprocessors are increasingly becoming a mainstay in the workflow of front end web developers. CSS is an incredibly complicated and nuanced language, and in an effort to make its usage easier, developers often turn to using preprocessors such as SASS or LESS.
<ide>
<del>CSS Preprocessors compile the code which is written using a special compiler, and then use that to create a css file, which can then be refereneced by the main HTML document. When using any CSS Preprocessor, you will be able to program in normal CSS just as you would if the preprocessor were not in place, but you also have more options available to you. Some, such as SASS, has specific style standards which are meant make the writing of the document even easier, such as the freedom to omit braces if you choose to do so.
<add>CSS Preprocessors compile the code which is written using a special compiler, and then use that to create a css file, which can then be refereneced by the main HTML document. When using any CSS Preprocessor, you will be able to program in normal CSS just as you would if the preprocessor were not in place, but you also have more options available to you. Some, such as SASS, has specific style standards which are meant make the writing of the document even easier, such as the freedom to omit braces if you choose to do so.
<ide>
<del>Of course, CSS Preprocessors also offer other features as well. Many of the features offered are incredibly similar across preprocessors, with only slight variances in syntax. Thus, you can choose pretty much anyone you wish, and will be able to achieve the same things. Some of the more useful features are:
<add>Of course, CSS Preprocessors also offer other features as well. Many of the features offered are incredibly similar across preprocessors, with only slight variances in syntax. Thus, you can choose pretty much anyone you wish, and will be able to achieve the same things. Some of the more useful features are:
<ide>
<ide> ### Variables
<del>One of the most commonly used item in any programming language is the variable, something which CSS notably lacks. By having variables at your disposal, you may define a value once, and reuse if throughout the entire program. An example of this in SASS would be:
<add>One of the most commonly used item in any programming language is the variable, something which CSS notably lacks. By having variables at your disposal, you may define a value once, and reuse if throughout the entire program. An example of this in SASS would be:
<ide>
<ide> ```SASS
<ide> $yourcolor: #000056
<ide> .yourDiv {
<ide> color: $yourcolor;
<ide> }
<del>```
<add>```
<ide> By declaring the ```SASS yourcolor``` variable once, it is now possible to reuse this same exact color throughout the entire document without ever having to retype the definition.
<ide>
<ide> ### Loops
<del>Another common item in languages are loops, something else CSS lacks. Loops can be used to repeat the same instructions multiple times without having to be reentered multiple times. An example with SASS would be:
<add>Another common item in languages are loops, something else CSS lacks. Loops can be used to repeat the same instructions multiple times without having to be reentered multiple times. An example with SASS would be:
<ide>
<del>```SASS
<add>```SASS
<ide> @for $vfoo 35px to 85px {
<ide> .margin-#{vfoo} {
<ide> margin: $vfoo 10px;
<del> }
<del> }
<add> }
<add>}
<ide> ```
<ide> This loop saves us from having the to write the same code multiple times to change the margin size.
<ide>
<ide> Yet another feature which CSS lacks are If/Else statements. These will run a set
<ide> background color: white;
<ide> }
<ide> ```
<del>Here, the background color will change color depending on the width of the page's body.
<add>Here, the background color will change color depending on the width of the page's body.
<ide>
<ide> ### Mixins
<ide> There are probably portions of your styling you would like to reuse. Mixins allow you to group any number of properties under one common name. You declare mixin with the @mixin <name> and use it with the @include <name>.
<add>These are but a few of the major functions of CSS Preprocessors. As you can see, CSS Preprocessors are incredibly useful and versitile tools. Many web developers use them, and it is highly recommended to learn at least one of them.
<ide>
<del>These are but a few of the major functions of CSS Preprocessors. As you can see, CSS Preprocessors are incredibly useful and versatile tools. Many web developers use them, and it is highly recommended to learn at least one of them.
<ide> #### More Information:
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<ide> SASS: http://sass-lang.com/
<ide><path>guide/english/css/css3-backgrounds/index.md
<ide> The CSS `background` shorthand property is used to define multiple properties li
<ide> The `background-color` property specifies the background color of an element.
<ide>
<ide> ```css
<del> background-color : #F00;
<add> background-color : #F00;
<ide> ```
<ide>
<ide> ### Background Image
<ide> The `background-image` property specifies an image to use as background of an el
<ide> By default, the image repeats itself to cover the entire surface of the element.
<ide>
<ide> ```css
<del> background-image: url("GitHub-Mark.png");
<add> background-image: url("GitHub-Mark.png");
<ide> ```
<ide>
<ide> ### Background Image - Repetition
<ide> By default, the `background-image` property repeats on the X and Y axis, to cove
<ide> If you want to set an axis, like X axis, use `background-repeat` property type:
<ide>
<ide> ```css
<del> background-image: url("GitHub-Mark.png");
<del> background-repeat: repeat-x;
<add> background-image: url("GitHub-Mark.png");
<add> background-repeat: repeat-x;
<ide> ```
<ide>
<ide> But sometimes you don't want to have your background image cover the whole surface, so you've to specify it by typing:
<ide>
<ide> ```css
<del> background-image: url("GitHub-Mark.png");
<del> background-repeat: no-repeat;
<add> background-image: url("GitHub-Mark.png");
<add> background-repeat: no-repeat;
<ide> ```
<ide>
<ide> ### Background Image - Position
<ide>
<del>You can specify the position of the background by typing :
<add>You can specify the position of the background by typing :
<ide>
<ide> ```css
<del> background-image: url("GitHub-Mark.png");
<del> background-repeat: no-repeat;
<del> background-position : left bottom;
<add> background-image: url("GitHub-Mark.png");
<add> background-repeat: no-repeat;
<add> background-position : left bottom;
<ide> ```
<ide>
<ide> It will set your background image at the bottom left of the element.
<ide> It will set your background image at the bottom left of the element.
<ide> If you do not want the background image to scroll with the rest of the page, use the `background-attachement` property:
<ide>
<ide> ```css
<del> background-image: url("GitHub-Mark.png");
<del> background-repeat: no-repeat;
<del> background-position: left bottom;
<del> background-attachment: fixed;
<add> background-image: url("GitHub-Mark.png");
<add> background-repeat: no-repeat;
<add> background-position: left bottom;
<add> background-attachment: fixed;
<ide> ```
<ide>
<ide> ### Shorthand property
<ide>
<ide> You can pass all the properties in one super-property:
<ide>
<ide> ```css
<del> background: #F00 url("GitHub-Mark.png") no-repeat fixed left bottom;
<add> background: #F00 url("GitHub-Mark.png") no-repeat fixed left bottom;
<ide> ```
<ide>
<ide> When you use this shorthand property, it must be in this order:
<ide> When you use this shorthand property, it must be in this order:
<ide> It doesn't matter if one property is missing, so long as the order is maintained:
<ide>
<ide> ```css
<del> background: url("GitHub-Mark.png") no-repeat left bottom;
<add> background: url("GitHub-Mark.png") no-repeat left bottom;
<ide> ```
<ide>
<ide> This will work even if the color and the attachment are missing.
<ide><path>guide/english/css/css3-gradients/index.md
<ide> The following example shows a linear gradient that starts at the top. It starts
<ide> <head>
<ide> <style>
<ide> #grad1 {
<del> height: 200px;
<del> background: red; /* For browsers that do not support gradients */
<del> background: -webkit-linear-gradient(red, green); /* For Safari 5.1 to 6.0 */
<del> background: -o-linear-gradient(red, green); /* For Opera 11.1 to 12.0 */
<del> background: -moz-linear-gradient(red, green); /* For Firefox 3.6 to 15 */
<del> background: linear-gradient(red, green); /* Standard syntax (must be last) */
<add> height: 200px;
<add> background: red; /* For browsers that do not support gradients */
<add> background: -webkit-linear-gradient(red, green); /* For Safari 5.1 to 6.0 */
<add> background: -o-linear-gradient(red, green); /* For Opera 11.1 to 12.0 */
<add> background: -moz-linear-gradient(red, green); /* For Firefox 3.6 to 15 */
<add> background: linear-gradient(red, green); /* Standard syntax (must be last) */
<ide> }
<ide> </style>
<ide> </head>
<ide> The following example shows a linear gradient that starts from the left. It star
<ide> <head>
<ide> <style>
<ide> #grad1 {
<del> height: 200px;
<del> background: red; /* For browsers that do not support gradients */
<del> background: -webkit-linear-gradient(left, red , green); /* For Safari 5.1 to 6.0 */
<del> background: -o-linear-gradient(right, red, green); /* For Opera 11.1 to 12.0 */
<del> background: -moz-linear-gradient(right, red, green); /* For Firefox 3.6 to 15 */
<del> background: linear-gradient(to right, red , green); /* Standard syntax (must be last) */
<add> height: 200px;
<add> background: red; /* For browsers that do not support gradients */
<add> background: -webkit-linear-gradient(left, red , green); /* For Safari 5.1 to 6.0 */
<add> background: -o-linear-gradient(right, red, green); /* For Opera 11.1 to 12.0 */
<add> background: -moz-linear-gradient(right, red, green); /* For Firefox 3.6 to 15 */
<add> background: linear-gradient(to right, red , green); /* Standard syntax (must be last) */
<ide> }
<ide> </style>
<ide> </head>
<ide> The following example shows a linear gradient that starts at top left (and goes
<ide> <head>
<ide> <style>
<ide> #grad1 {
<del> height: 200px;
<del> background: red; /* For browsers that do not support gradients */
<del> background: -webkit-linear-gradient(left top, red, green); /* For Safari 5.1 to 6.0 */
<del> background: -o-linear-gradient(bottom right, red, green); /* For Opera 11.1 to 12.0 */
<del> background: -moz-linear-gradient(bottom right, red, green); /* For Firefox 3.6 to 15 */
<del> background: linear-gradient(to bottom right, red, green); /* Standard syntax (must be last) */
<add> height: 200px;
<add> background: red; /* For browsers that do not support gradients */
<add> background: -webkit-linear-gradient(left top, red, green); /* For Safari 5.1 to 6.0 */
<add> background: -o-linear-gradient(bottom right, red, green); /* For Opera 11.1 to 12.0 */
<add> background: -moz-linear-gradient(bottom right, red, green); /* For Firefox 3.6 to 15 */
<add> background: linear-gradient(to bottom right, red, green); /* Standard syntax (must be last) */
<ide> }
<ide> </style>
<ide> </head>
<ide><path>guide/english/css/css3-media-queries/index.md
<ide> The thought process should be:
<ide> ### The basic syntax
<ide>
<ide> ```css
<del> @media only screen and (min-width: 768px) {
<del> p {padding: 30px;}
<del> }
<add>@media only screen and (min-width: 768px) {
<add> p {padding: 30px;}
<add>}
<ide> ```
<ide>
<ide> The `p` tag will have a padding of 30px as soon as the screen reaches min 768px width.</p>
<ide> The `p` tag will have a padding of 30px as soon as the screen reaches min 768px
<ide>
<ide>
<ide> ```css
<del> @media only screen and (min-height: 768px) and (orientation: landscape) {
<del> p {padding: 30px;}
<del> }
<add>@media only screen and (min-height: 768px) and (orientation: landscape) {
<add> p {padding: 30px;}
<add>}
<ide> ```
<ide>
<ide> The `p` tag will have a padding of 30px as soon as the screen reaches min 768px height and its orientation is landscape.
<ide>
<ide> ### The OR syntax
<ide>
<ide> ```css
<del> @media only screen and (min-width: 768px), (min-resolution: 150dpi) {
<del> p {padding: 30px;}
<del> }
<add>@media only screen and (min-width: 768px), (min-resolution: 150dpi) {
<add> p {padding: 30px;}
<add>}
<ide> ```
<ide>
<ide> The `p` tag will have a padding of 30px as soon as the screen reaches min 768px width or its resolution reaches min 150dpi.
<ide> Beyond the core uses of media queries for mobile-first web design shown above, m
<ide>
<ide> 1. Adjusting for screen readers that convert website text to speech for the visually impaired (for example, ignoring non-essential text).
<ide> ```css
<del> @media speech {
<del> /* ... */
<del> }
<add> @media speech {
<add> /* ... */
<add> }
<ide> ```
<ide> 2. Allowing for more graceful zooming in for those with minor visual impairments, such as many elderly people.
<ide> 3. Allowing smoother experiences for those who prefer or need less animation to read a page.
<ide> ```css
<del> @media (prefers-reduced-motion: reduce) {
<del> .animation {
<del> animation: none;
<del> -webkit-animation: none;
<del> }
<add> @media (prefers-reduced-motion: reduce) {
<add> .animation {
<add> animation: none;
<add> -webkit-animation: none;
<ide> }
<add> }
<ide> ```
<ide> 4. Restyling a page for when it's printed as opposed to read on a screen.
<ide> ```css
<del> @media print {
<del> /* ... */
<del> }
<add> @media print {
<add> /* ... */
<add> }
<ide> ```
<ide>
<ide> ### More Information
<ide><path>guide/english/css/dropdowns/index.md
<ide> You need the separate div classes to create the button, and another div to separ
<ide>
<ide> ```html
<ide> <div id="container">
<del>
<add>
<ide> <div id="myNav1" class="overlay">
<del>
<add>
<ide> <div class="overlay-content" id="myNav1-content">
<del>
<add>
<ide> <div>
<ide> <a href="#" id="list1_obj1" class="list1" >Content 1</a>
<ide> </div>
<ide> <div>
<ide> <a href="#" id="list1_obj2" class="list1" >Content 2</a>
<ide> </div>
<del>
<add>
<ide> </div>
<del>
<add>
<ide> </div>
<del>
<add>
<ide> <div id="myNav2" class="overlay">
<del>
<add>
<ide> <a href="javascript:void(10)" class="closebtn" onclick="closeNav()">×</a>
<ide> <div class="overlay-content" id="myNav2-content">
<del>
<add>
<ide> <div>
<ide> <a href="#" id="list2_obj1" class="list2" >Content 3</a>
<ide> </div>
<ide> You need the separate div classes to create the button, and another div to separ
<ide> <div>
<ide> <a href="#" id="list2_obj3" class="list2" >Content 5</a>
<ide> </div>
<del>
<add>
<ide> </div>
<del>
<add>
<ide> </div>
<del>
<add>
<ide> </div>
<ide> ```
<ide>
<ide> ```css
<ide> #myNav1 {
<del> height: 0;
<del> width: 50%;
<del> position: fixed;
<del> z-index: 6;
<del> top: 0;
<del> left: 0;
<del> background-color: #ffff;
<del> overflow: hidden;
<del> transition: 0.3s;
<del> opacity: 0.85;
<add> height: 0;
<add> width: 50%;
<add> position: fixed;
<add> z-index: 6;
<add> top: 0;
<add> left: 0;
<add> background-color: #ffff;
<add> overflow: hidden;
<add> transition: 0.3s;
<add> opacity: 0.85;
<ide> }
<ide>
<ide> #myNav2 {
<del> height: 0;
<del> width: 50%;
<del> position: fixed;
<del> z-index: 6;
<del> bottom: 0;
<del> right: 0;
<del> background-color: #ffff;
<del> overflow: hidden;
<del> transition: 0.3s;
<del> opacity: 0.85;
<add> height: 0;
<add> width: 50%;
<add> position: fixed;
<add> z-index: 6;
<add> bottom: 0;
<add> right: 0;
<add> background-color: #ffff;
<add> overflow: hidden;
<add> transition: 0.3s;
<add> opacity: 0.85;
<ide> }
<ide>
<ide> .overlay-content {
<del> position: relative;
<del> width: 100%;
<del> text-align: center;
<del> margin-top: 30px;
<add> position: relative;
<add> width: 100%;
<add> text-align: center;
<add> margin-top: 30px;
<ide> }
<ide>
<ide> #myNav1-content{
<del> top: 12%;
<del> left: 5%;
<del> display: none;
<add> top: 12%;
<add> left: 5%;
<add> display: none;
<ide> }
<ide>
<ide> #myNav2-content{
<del> top: 12%;
<del> right: 10%;
<del> display: none;
<add> top: 12%;
<add> right: 10%;
<add> display: none;
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/fonts/index.md
<ide> It works with a *fallback* system, meaning if your browser does not support the
<ide>
<ide> ```css
<ide> p {
<del> font-family: "Times New Roman", Times, serif;
<add> font-family: "Times New Roman", Times, serif;
<ide> }
<ide> ```
<ide> In the above example, "Times New Roman" is the *family-name* of the font, while "serif" is the *generic-name*. Generic names are used as a fallback mechanism for preserving style if the family-name is unavailable. A generic name should always be the last item in the list of font family names.
<ide> This property has 3 values:
<ide>
<ide> ```css
<ide> .normal {
<del> font-style: normal;
<del>}
<add> font-style: normal;
<add>}
<ide>
<ide> .italic {
<del> font-style: italic;
<add> font-style: italic;
<ide> }
<ide>
<ide> .oblique {
<del> font-style: oblique;
<add> font-style: oblique;
<ide> }
<ide> ```
<ide>
<ide> There are different types of font size values:
<ide>
<ide> ```css
<ide> .with-pixels {
<del> font-size: 14px;
<add> font-size: 14px;
<ide> }
<ide>
<ide> .with-ems {
<del> font-size: 0.875em;
<add> font-size: 0.875em;
<ide> }
<ide>
<ide> .with-absolute {
<del> font-size: large;
<add> font-size: large;
<ide> }
<ide>
<ide> .with-percentage {
<del> font-size: 80%;
<add> font-size: 80%;
<ide> }
<ide> ```
<ide>
<ide> The `font-weight`property specifies the weight (or boldness) of the font. Accept
<ide>
<ide> ```css
<ide> p {
<del> font-weight: bold
<add> font-weight: bold
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/image-galleries/index.md
<ide> You can use CSS to create you own image galleries.
<ide> <head>
<ide> <style>
<ide> div.gallery {
<del> margin: 5px;
<del> border: 1px solid #ccc;
<del> float: left;
<del> width: 180px;
<add> margin: 5px;
<add> border: 1px solid #ccc;
<add> float: left;
<add> width: 180px;
<ide> }
<ide>
<ide> div.gallery:hover {
<del> border: 1px solid #777;
<add> border: 1px solid #777;
<ide> }
<ide>
<ide> div.gallery img {
<del> width: 100%;
<del> height: 150px;
<add> width: 100%;
<add> height: 150px;
<ide> }
<ide>
<ide> div.desc {
<del> padding: 15px;
<del> text-align: center;
<add> padding: 15px;
<add> text-align: center;
<ide> }
<ide> </style>
<ide> </head>
<ide> div.desc {
<ide> #### More Information:
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<ide> https://www.w3schools.com/css/css_image_gallery.asp
<del>
<ide><path>guide/english/css/image-opacity-and-transparency/index.md
<ide> title: Image Opacity and Transparency
<ide> ---
<ide> ## Image Opacity and Transparency
<ide>
<del>The ```opacity``` property allows you to make an image transparent by lowering how opaque it is.
<add>The ```opacity``` property allows you to make an image transparent by lowering how opaque it is.
<ide>
<ide> ```Opacity``` takes a value between 0.0 and 1.0.
<ide>
<ide> The ```opacity``` property allows you to make an image transparent by lowering h
<ide> Example:
<ide> ```css
<ide> img {
<del> opacity: 0.3;
<del> }
<del> ```
<del>
<del>Include ```filter: alpha(opacity=x)``` for IE8 and earlier. `x` takes a value from 0-100.
<add> opacity: 0.3;
<add>}
<add>```
<add>
<add>Include ```filter: alpha(opacity=x)``` for IE8 and earlier. The x takes a value from 0-100.
<ide> ```css
<ide> img {
<del> opacity: 0.3;
<del> filter: alpha(opacity=30);
<add> opacity: 0.3;
<add> filter: alpha(opacity=30);
<ide> }
<ide> ```
<ide>
<ide> You can pair ```opacity``` with ```:hover``` to create a dynamic mouse-over effe
<ide> Example:
<ide> ```css
<ide> img {
<del> opacity: 0.3;
<del> filter: alpha(opacity=30);
<add> opacity: 0.3;
<add> filter: alpha(opacity=30);
<ide> }
<ide> img:hover {
<del> opacity: 1.0;
<del> filter: alpha(opacity=100);
<add> opacity: 1.0;
<add> filter: alpha(opacity=100);
<ide> }
<ide> ```
<ide> [Here's a codepen example to show a transparent image turning opaque on hover](https://codepen.io/lvcoulter/full/JrzxXa/)
<ide> You can create the opposite effect with less code since the image is 1.0 opacity
<ide> Example:
<ide> ```css
<ide> img:hover {
<del> opacity: 0.3;
<del> filter: alpha(opacity=30);
<add> opacity: 0.3;
<add> filter: alpha(opacity=30);
<ide> }
<ide> ```
<ide> [Here's a codepen example to show transparency on mouse-over](https://codepen.io/lvcoulter/full/xXBQoR/)
<ide>
<ide>
<ide> #### More Information:
<ide> - w3schools.com: [CSS Opacity/Transparency](https://www.w3schools.com/css/css_image_transparency.asp)
<del>
<ide> - MDN Web Docs: [Opacity](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity)
<del>
<del>
<del>
<ide><path>guide/english/css/layout/display-property/index.md
<ide> The `display` property specifies the type of box used for an HTML element. There
<ide>
<ide> ```css
<ide> .myBox {
<del> display: block;
<add> display: block;
<ide> }
<ide>
<ide> .myContainer {
<del> display: flex;
<add> display: flex;
<ide> }
<ide>
<ide> .inlineList ul > li {
<del> display: inline;
<add> display: inline;
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/layout/float-and-clear/index.md
<ide> The `float` property can have one of the following values:
<ide> `inherit` - The element inherits the float value of its parent
<ide> In its simplest use, the `float` property can be used to wrap text around images.
<ide>
<del>#### Float in Picture:
<add>#### Float in Picture:
<ide> 
<ide>
<ide> ```
<ide> img {
<del> float: right;
<add> float: right;
<ide> }
<ide> ```
<ide> This example specifies that an image should float to the right in a page:
<ide>
<ide> 
<ide> ```
<ide> img {
<del> float: left;
<add> float: left;
<ide> }
<ide> ```
<ide> This example specifies that an image should float to the left in a page:
<ide>
<ide> ```
<ide> img {
<del> float: none;
<add> float: none;
<ide> }
<ide> ```
<ide>
<ide> When clearing floats, you should match the `clear` to the `float`. If an element
<ide> Source: CSS-TRICS
<ide> ```
<ide> div {
<del> clear: left;
<add> clear: left;
<ide> }
<ide> ```
<ide> 
<ide><path>guide/english/css/layout/grid-layout/index.md
<ide> title: Grid Layout
<ide> ---
<ide> ## Grid Layout
<ide>
<del>CSS Grid Layout, simply known as Grid, is a layout scheme that is the newest and the most powerful in CSS. It is [supported by all major browsers](https://caniuse.com/#feat=css-grid) and provides a way to position items on the page and move them around.
<add>CSS Grid Layout, simply known as Grid, is a layout scheme that is the newest and the most powerful in CSS. It is [supported by all major browsers](https://caniuse.com/#feat=css-grid) and provides a way to position items on the page and move them around.
<ide>
<ide> It can automatically assign items to _areas_, size and resize them, take care of creating columns and rows based on a pattern you define, and doing all the calculations using the newly introduced `fr` unit.
<ide>
<ide> It can automatically assign items to _areas_, size and resize them, take care of
<ide> - Grid and Flex are not mutually exclusive. You can use both on the same project.
<ide>
<ide>
<del>### Checking browser compatability with `@supports`
<add>### Checking browser compatability with `@supports`
<ide>
<ide> Ideally, when you build a site, you'd design it with Grid and use Flex as a fallback. You can find out if your browser supports Grid with the `@support` CSS rule (aka feature query). Here's an example:
<ide>
<ide> Ideally, when you build a site, you'd design it with Grid and use Flex as a fall
<ide> To make any element a grid, you need to assign its `display` property to `grid`, like so:
<ide>
<ide> ```css
<del>.conatiner {
<add>.container {
<ide> display: grid;
<ide> }
<ide> ```
<ide> grid-template-rows: auto 300px;
<ide> Areas
<ide>
<ide> ```css
<del>grid-template-areas:
<add>grid-template-areas:
<ide> "a a a a"
<ide> "b c d e"
<ide> "b c d e"
<ide><path>guide/english/css/layout/the-position-property/index.md
<ide> title: The Position Property
<ide>
<ide> The position property specifies the type of positioning method used for an element (static, relative, fixed, absolute or sticky).
<ide> The position property specifies the type of positioning method used for an element.
<del>The position proprty isn't generally used to create layouts, but instead it is used to position elements that somehow stand out from the page flow.
<add>The position property isn't generally used to create layouts, but instead it is used to position elements that somehow stand out from the page flow.
<ide>
<ide> There are five different position values:
<ide>
<ide> Elements are then positioned using the top, bottom, left, and right properties.
<ide> #### More Information:
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<ide> <a href="https://www.w3schools.com/css/css_positioning.asp" target="_blank">The is a good article</a> to read up to understand more about the position property.
<del>
<del>
<ide><path>guide/english/css/margins/index.md
<ide> Margin values are set using lengths or percentages or `auto` or `inherit` keywor
<ide> ## Syntax
<ide> ```css
<ide> .element {
<del> margin: margin-top || margin-right || margin-bottom || margin-left;
<add> margin: margin-top || margin-right || margin-bottom || margin-left;
<ide> }
<ide> ```
<ide>
<ide> This property may be specified using one, two, three, or four values.
<ide> ```css
<ide> /* Apply to all four sides */
<ide> margin: 1em;
<del>
<add>
<ide> /* top and bottom | left and right */
<ide> margin: 5% 10%;
<del>
<add>
<ide> /* top | left and right | bottom */
<ide> margin: 1em 2em 2em;
<ide>
<ide><path>guide/english/css/navigation-bars/index.md
<ide> Navigation Bars are mostly made up of `<ul>` lists that are horizontally arrange
<ide> While styling the navigation bars, it's common to remove the extra spacing created by the `<ul>` and `<li>` tags as well as the bulletpoints that are automatically inserted:
<ide>
<ide> ```css
<del> list-style-type: none;
<del> margin: 0px;
<del> padding: 0px;
<add> list-style-type: none;
<add> margin: 0px;
<add> padding: 0px;
<ide> ```
<ide>
<ide> **Example:**
<ide> There are two parts to any navigation: the HTML and the CSS. This is just a quic
<ide>
<ide> ```html
<ide> <nav class="myNav"> <!-- Any element can be used here -->
<del> <ul>
<del> <li><a href="index.html">Home</a></li>
<del> <li><a href="about.html">About</a></li>
<del> <li><a href="contact.html">Contact</a></li>
<del> </ul>
<add> <ul>
<add> <li><a href="index.html">Home</a></li>
<add> <li><a href="about.html">About</a></li>
<add> <li><a href="contact.html">Contact</a></li>
<add> </ul>
<ide> </nav>
<ide> ```
<ide>
<ide> ```css
<ide> /* Define the main Navigation block */
<ide> .myNav {
<del> display: block;
<del> height: 50px;
<del> line-height: 50px;
<del> background-color: #333;
<add> display: block;
<add> height: 50px;
<add> line-height: 50px;
<add> background-color: #333;
<ide> }
<ide> /* Remove bullets, margin and padding */
<ide> .myNav ul {
<del> list-style: none;
<del> padding: 0;
<del> margin: 0;
<add> list-style: none;
<add> padding: 0;
<add> margin: 0;
<ide> }
<ide> .myNav li {
<del> float: left;
<del> /* Or you can use display: inline; */
<add> float: left;
<add> /* Or you can use display: inline; */
<ide> }
<ide> /* Define the block styling for the links */
<ide> .myNav li a {
<del> display: inline-block;
<del> text-align: center;
<del> padding: 14px 16px;
<add> display: inline-block;
<add> text-align: center;
<add> padding: 14px 16px;
<ide> }
<ide> /* This is optional, however if you want to display the active link differently apply a background to it */
<ide> .myNav li a.active {
<del> background-color: #3786E1;
<add> background-color: #3786E1;
<ide> }
<ide> ```
<ide>
<ide> There are two parts to any navigation: the HTML and the CSS. This is just a quic
<ide> #### More Information:
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<ide> More Navigation Examples: [W3Schools](https://www.w3schools.com/css/css_navbar.asp)
<del>
<del>
<ide><path>guide/english/css/object-fit/index.md
<ide> Basically we use the `object-fit` property to define how it stretch or squish an
<ide> ## Syntax
<ide> ```css
<ide> .element {
<del> object-fit: fill || contain || cover || none || scale-down;
<add> object-fit: fill || contain || cover || none || scale-down;
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/overflow/index.md
<ide> For example, a given block-level element (`<div>`) set to 300px wide, that conta
<ide> * `overflow-y`: Allows the user to scroll through the content that extends beyond the width of the box.
<ide>
<ide> ```css
<del> .box-element {
<del> overflow-x: scroll;
<del> overflow-y: auto;
<del> }
<add>.box-element {
<add> overflow-x: scroll;
<add> overflow-y: auto;
<add>}
<ide> ```
<ide> And the `.box-element` will look like this:
<ide> 
<ide><path>guide/english/css/padding/index.md
<ide> Padding values are set using lengths, percentages, or the `inherit` keyword, and
<ide> ## Syntax
<ide> ```css
<ide> .element {
<del> padding: [padding-top] || [padding-right] || [padding-bottom] || [padding-left];
<add> padding: [padding-top] || [padding-right] || [padding-bottom] || [padding-left];
<ide> }
<ide> ```
<ide>
<ide> This property may be specified using one, two, three, or four values.
<ide> /* em refers to the current font size of an element */
<ide> /* Apply to all four sides */
<ide> padding: 1em;
<del>
<add>
<ide> /* top and bottom | left and right */
<ide> padding: 5% 10%;
<del>
<add>
<ide> /* top | left and right | bottom */
<ide> padding: 1em 2em 2em;
<ide>
<ide><path>guide/english/css/properties/background-color-property/index.md
<ide> title: Background Color Property
<ide> ---
<ide> ## Background Color Property
<ide>
<del>You use the `background-color` property to set the background color of an element. You can either use a color value (color name, hexadecimal value, RGB/RGBA value, HSL/HSLA value) or the keyword `transparent`.
<add>You use the `background-color` property to set the background color of an element. You can either use a color value (color name, hexadecimal value, RGB/RGBA value, HSL/HSLA value) or the keyword `transparent`.
<ide>
<ide> **Example:**
<ide>
<ide> ```css
<ide> body {
<del> background-color: crimson;
<add> background-color: crimson;
<ide> }
<ide>
<ide> div {
<del> background-color: #ffffff;
<add> background-color: #ffffff;
<ide> }
<ide>
<ide> .myClass {
<del> background-color: rgba(0, 0, 0, 0.5);
<add> background-color: rgba(0, 0, 0, 0.5);
<ide> }
<ide> ```
<ide>
<ide> #### Property Values:
<ide> `background-color: color | transparent | initial | inherit;`
<ide>
<ide>
<del>`color` - Specifies the background color (color name, hexadecimal value, RGB/RGBA value, HSL/HSLA value).
<add>`color` - Specifies the background color (color name, hexadecimal value, RGB/RGBA value, HSL/HSLA value).
<ide>
<ide> `transparent` - The default value. Sets the background color as transparent.
<ide>
<ide> div {
<ide>
<ide> #### More Information:
<ide> <a href='https://developer.mozilla.org/en-US/docs/Web/CSS/background-color?v=b' target='_blank' rel='nofollow'>MDN web docs</a>
<del>
<del>
<ide><path>guide/english/css/properties/background-repeat-property/index.md
<ide> Examples:
<ide> For repeating the image both horizontally and vertically
<ide> ```css
<ide> body {
<del> background-image:url(smiley.gif);
<del> background-repeat:repeat;
<add> background-image:url(smiley.gif);
<add> background-repeat:repeat;
<ide> }
<ide> ```
<ide> For repeat the image horizontally
<ide> ```css
<ide> body {
<del> background-image:url(smiley.gif);
<del> background-repeat:repeat-x;
<add> background-image:url(smiley.gif);
<add> background-repeat:repeat-x;
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/properties/color-property/index.md
<ide> title: Color Property
<ide> ---
<ide>
<del>## CSS Color Property
<add>## CSS Color Property
<ide>
<ide>
<ide> You can use the `color` property to set the color of the text in an element.
<ide>
<ide>
<del>You can use several methods to declare a color such as:
<add>You can use several methods to declare a color such as:
<ide> * By Name (Note: this only works with certain colors)
<ide>
<ide> ```css
<ide> h1{
<del> color: blue;
<add> color: blue;
<ide> }
<ide> ```
<ide>
<ide> * Hexadecimal (specified as #rrggbb)
<ide>
<ide> ```css
<del>h1{
<del> color: #0000ff;
<del>}
<add>h1{
<add> color: #0000ff;
<add>}
<ide> ```
<ide>
<ide> * RGB (specified as rgb(r, g, b))
<ide>
<ide> ```css
<ide> h1{
<del> color: rgb(0, 0, 255);
<add> color: rgb(0, 0, 255);
<ide> }
<ide> ```
<ide>
<ide> * RGBA (specified as rgba(r, g, b, alpha))
<ide>
<ide> ```css
<ide> h1{
<del> color: rgba(0, 0, 255, 0.5);
<add> color: rgba(0, 0, 255, 0.5);
<ide> }
<ide> ```
<ide>
<ide> * HSL (Hue, Lightness, Saturation)
<del>
<add>
<ide> ```css
<ide> h1{
<del> color: hsl(240, 100%, 50%);
<add> color: hsl(240, 100%, 50%);
<ide> }
<ide> ```
<ide>
<ide> * HSLA (Hue, Lightness, Saturation, Alpha)
<del>
<add>
<ide> ```css
<ide> h1{
<del> color: hsl(240, 100%, 50%, 0.5);
<add> color: hsl(240, 100%, 50%, 0.5);
<ide> }
<ide> ```
<ide> ## CSS Color Properties explained
<ide> h1{
<ide> - These are pretty self explanatory. Each color is represented by its name.
<ide>
<ide> * Hexadecimal:
<del> - These colors are represented by hex triplets.
<add> - These colors are represented by hex triplets.
<ide> - A hex triplet is a six-digit, three-byte hexadecimal number.
<ide> - Each of three bytes represents a color #RRGGBB (red, green, blue).
<ide> - Shorthand hex color is represented by a three-digit hexadecimal number #RGB (red, green, blue).
<del>
<add>
<ide> * RGB & RGBA Colors:
<ide> - RGB colors are 24bit (3byte) colors represented by 3 numbers in range of 0-255. (e.g. rgb(255,255,128)).
<ide> - RGBA colors are 32bit (4byte) colors represented by 3 numbers in range of 0-255 and alpha value which controls opacity. (e.g. rgb(255,255,128, 0.3)).
<del>
<add>
<ide> * HSL & HSLA Colors:
<ide> - HSL color is represented by three values (HUE, Saturation, Lightness).
<ide> - HSLA color is represented by four values (HUE, Saturation, Lightness, Alpha). Alpha controls the opacity.
<del>
<add>
<ide> #### More Information
<ide>
<ide> * W3 Schools site on how to format <a href='https://www.w3schools.com/css/css_text.asp' target='_blank' rel='nofollow'>text</a>.
<ide><path>guide/english/css/properties/css3-text-shadow-property/index.md
<ide> text-shadow : X-offset Y-offset blur-radius color
<ide> **Example :**
<ide> ``` css
<ide> p {
<del>text-shadow : 2px 2px 8px #FF0000;
<add> text-shadow : 2px 2px 8px #FF0000;
<ide> }
<ide> ```
<ide>
<ide><path>guide/english/css/vertical-align/index.md
<ide> title: Vertical Align CSS
<ide> For example, you can use ```vertical-align``` like this to align an image:
<ide> ```
<ide> img {
<del> vertical-align: top;
<add> vertical-align: top;
<ide> }
<ide> ```
<ide> These are the valid values for ```vertical-align```:
<ide><path>guide/english/css/will-change/index.md
<ide> The will-change property allows you to tell the browser what manipulations will
<ide>
<ide> ```css
<ide> .container {
<del>will-change: transform;
<add> will-change: transform;
<ide> }
<ide> ```
<ide> | 35 |
Python | Python | add streamlit example [ci skip] | 867e93aae2503abe08c10dd577b7dc5d592823f7 | <ide><path>examples/streamlit_spacy.py
<add># coding: utf-8
<add>"""
<add>Example of a Streamlit app for an interactive spaCy model visualizer. You can
<add>either download the script, or point streamlit run to the raw URL of this
<add>file. For more details, see https://streamlit.io.
<add>
<add>Installation:
<add>pip install streamlit
<add>python -m spacy download en_core_web_sm
<add>python -m spacy download en_core_web_md
<add>python -m spacy download de_core_news_sm
<add>
<add>Usage:
<add>streamlit run streamlit_spacy.py
<add>"""
<add>from __future__ import unicode_literals
<add>
<add>import streamlit as st
<add>import spacy
<add>from spacy import displacy
<add>import pandas as pd
<add>
<add>
<add>SPACY_MODEL_NAMES = ["en_core_web_sm", "en_core_web_md", "de_core_news_sm"]
<add>DEFAULT_TEXT = "Mark Zuckerberg is the CEO of Facebook."
<add>HTML_WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""
<add>
<add>
<add>@st.cache(ignore_hash=True)
<add>def load_model(name):
<add> return spacy.load(name)
<add>
<add>
<add>@st.cache(ignore_hash=True)
<add>def process_text(model_name, text):
<add> nlp = load_model(model_name)
<add> return nlp(text)
<add>
<add>
<add>st.sidebar.title("Interactive spaCy visualizer")
<add>st.sidebar.markdown(
<add> """
<add>Process text with [spaCy](https://spacy.io) models and visualize named entities,
<add>dependencies and more. Uses spaCy's built-in
<add>[displaCy](http://spacy.io/usage/visualizers) visualizer under the hood.
<add>"""
<add>)
<add>
<add>spacy_model = st.sidebar.selectbox("Model name", SPACY_MODEL_NAMES)
<add>model_load_state = st.info(f"Loading model '{spacy_model}'...")
<add>nlp = load_model(spacy_model)
<add>model_load_state.empty()
<add>
<add>text = st.text_area("Text to analyze", DEFAULT_TEXT)
<add>doc = process_text(spacy_model, text)
<add>
<add>if "parser" in nlp.pipe_names:
<add> st.header("Dependency Parse & Part-of-speech tags")
<add> st.sidebar.header("Dependency Parse")
<add> split_sents = st.sidebar.checkbox("Split sentences", value=True)
<add> collapse_punct = st.sidebar.checkbox("Collapse punctuation", value=True)
<add> collapse_phrases = st.sidebar.checkbox("Collapse phrases")
<add> compact = st.sidebar.checkbox("Compact mode")
<add> options = {
<add> "collapse_punct": collapse_punct,
<add> "collapse_phrases": collapse_phrases,
<add> "compact": compact,
<add> }
<add> docs = [span.as_doc() for span in doc.sents] if split_sents else [doc]
<add> for sent in docs:
<add> html = displacy.render(sent, options=options)
<add> # Double newlines seem to mess with the rendering
<add> html = html.replace("\n\n", "\n")
<add> if split_sents and len(docs) > 1:
<add> st.markdown(f"> {sent.text}")
<add> st.write(HTML_WRAPPER.format(html), unsafe_allow_html=True)
<add>
<add>if "ner" in nlp.pipe_names:
<add> st.header("Named Entities")
<add> st.sidebar.header("Named Entities")
<add> default_labels = ["PERSON", "ORG", "GPE", "LOC"]
<add> labels = st.sidebar.multiselect(
<add> "Entity labels", nlp.get_pipe("ner").labels, default_labels
<add> )
<add> html = displacy.render(doc, style="ent", options={"ents": labels})
<add> # Newlines seem to mess with the rendering
<add> html = html.replace("\n", " ")
<add> st.write(HTML_WRAPPER.format(html), unsafe_allow_html=True)
<add> attrs = ["text", "label_", "start", "end", "start_char", "end_char"]
<add> if "entity_linker" in nlp.pipe_names:
<add> attrs.append("kb_id_")
<add> data = [
<add> [str(getattr(ent, attr)) for attr in attrs]
<add> for ent in doc.ents
<add> if ent.label_ in labels
<add> ]
<add> df = pd.DataFrame(data, columns=attrs)
<add> st.dataframe(df)
<add>
<add>
<add>if "textcat" in nlp.pipe_names:
<add> st.header("Text Classification")
<add> st.markdown(f"> {text}")
<add> df = pd.DataFrame(doc.cats.items(), columns=("Label", "Score"))
<add> st.dataframe(df)
<add>
<add>
<add>vector_size = nlp.meta.get("vectors", {}).get("width", 0)
<add>if vector_size:
<add> st.header("Vectors & Similarity")
<add> st.code(nlp.meta["vectors"])
<add> text1 = st.text_input("Text or word 1", "apple")
<add> text2 = st.text_input("Text or word 2", "orange")
<add> doc1 = process_text(spacy_model, text1)
<add> doc2 = process_text(spacy_model, text2)
<add> similarity = doc1.similarity(doc2)
<add> if similarity > 0.5:
<add> st.success(similarity)
<add> else:
<add> st.error(similarity)
<add>
<add>st.header("Token attributes")
<add>
<add>if st.button("Show token attributes"):
<add> attrs = [
<add> "idx",
<add> "text",
<add> "lemma_",
<add> "pos_",
<add> "tag_",
<add> "dep_",
<add> "head",
<add> "ent_type_",
<add> "ent_iob_",
<add> "shape_",
<add> "is_alpha",
<add> "is_ascii",
<add> "is_digit",
<add> "is_punct",
<add> "like_num",
<add> ]
<add> data = [[str(getattr(token, attr)) for attr in attrs] for token in doc]
<add> df = pd.DataFrame(data, columns=attrs)
<add> st.dataframe(df)
<add>
<add>
<add>st.header("JSON Doc")
<add>if st.button("Show JSON Doc"):
<add> st.json(doc.to_json())
<add>
<add>st.header("JSON model meta")
<add>if st.button("Show JSON model meta"):
<add> st.json(nlp.meta) | 1 |
Python | Python | add call to super class in 'ftp' & 'ssh' providers | 74c2a6ded4d615de8e1b1c04a25146344138e920 | <ide><path>airflow/providers/ftp/hooks/ftp.py
<ide> class FTPHook(BaseHook):
<ide> """
<ide>
<ide> def __init__(self, ftp_conn_id='ftp_default'):
<add> super().__init__()
<ide> self.ftp_conn_id = ftp_conn_id
<ide> self.conn = None
<ide>
<ide><path>airflow/providers/ssh/hooks/ssh.py
<ide> def __init__(self,
<ide> timeout=10,
<ide> keepalive_interval=30
<ide> ):
<add> super().__init__()
<ide> self.ssh_conn_id = ssh_conn_id
<ide> self.remote_host = remote_host
<ide> self.username = username | 2 |
Python | Python | add dataset tests | 7c3bf9d02fb58a65394185ba65c192e5bbfa12ef | <ide><path>tests/auto/test_datasets.py
<add>from __future__ import print_function
<add>import unittest
<add>from keras.datasets import cifar10, cifar100, reuters, imdb, mnist
<add>
<add>
<add>class TestDatasets(unittest.TestCase):
<add> def test_cifar(self):
<add> print('cifar10')
<add> (X_train, y_train), (X_test, y_test) = cifar10.load_data()
<add> print(X_train.shape)
<add> print(X_test.shape)
<add> print(y_train.shape)
<add> print(y_test.shape)
<add>
<add> print('cifar100 fine')
<add> (X_train, y_train), (X_test, y_test) = cifar100.load_data('fine')
<add> print(X_train.shape)
<add> print(X_test.shape)
<add> print(y_train.shape)
<add> print(y_test.shape)
<add>
<add> print('cifar100 coarse')
<add> (X_train, y_train), (X_test, y_test) = cifar100.load_data('coarse')
<add> print(X_train.shape)
<add> print(X_test.shape)
<add> print(y_train.shape)
<add> print(y_test.shape)
<add>
<add> def test_reuters(self):
<add> print('reuters')
<add> (X_train, y_train), (X_test, y_test) = reuters.load_data()
<add>
<add> def test_mnist(self):
<add> print('mnist')
<add> (X_train, y_train), (X_test, y_test) = mnist.load_data()
<add> print(X_train.shape)
<add> print(X_test.shape)
<add> print(y_train.shape)
<add> print(y_test.shape)
<add>
<add> def test_imdb(self):
<add> print('imdb')
<add> (X_train, y_train), (X_test, y_test) = imdb.load_data()
<add>
<add>
<add>if __name__ == '__main__':
<add> print('Test datasets')
<add> unittest.main() | 1 |
Text | Text | clarify fd closing by `fs.readfile` etc | beea23af65deeb149fefe3fb3ae84f0a3eb7a197 | <ide><path>doc/api/fs.md
<ide> fs.appendFile('message.txt', 'data to append', 'utf8', callback);
<ide>
<ide> Any specified file descriptor has to have been opened for appending.
<ide>
<del>_Note: Specified file descriptors will not be closed automatically._
<add>_Note: If a file descriptor is specified as the `file`, it will not be closed
<add>automatically._
<ide>
<ide> ## fs.appendFileSync(file, data[, options])
<ide> <!-- YAML
<ide> fs.readFile('/etc/passwd', 'utf8', callback);
<ide>
<ide> Any specified file descriptor has to support reading.
<ide>
<del>_Note: Specified file descriptors will not be closed automatically._
<add>_Note: If a file descriptor is specified as the `file`, it will not be closed
<add>automatically._
<ide>
<ide> ## fs.readFileSync(file[, options])
<ide> <!-- YAML
<ide> Note that it is unsafe to use `fs.writeFile` multiple times on the same file
<ide> without waiting for the callback. For this scenario,
<ide> `fs.createWriteStream` is strongly recommended.
<ide>
<del>_Note: Specified file descriptors will not be closed automatically._
<add>_Note: If a file descriptor is specified as the `file`, it will not be closed
<add>automatically._
<ide>
<ide> ## fs.writeFileSync(file, data[, options])
<ide> <!-- YAML | 1 |
Text | Text | add text "$ ionic serve" to article | 3600b1f7a21408ede7ce6dd53f3811901dce1a7d | <ide><path>guide/portuguese/ionic/hello-world-in-ionic/index.md
<ide> Não entre em pânico, esses arquivos são gerados automaticamente pelo npm para
<ide> ```
<ide>
<ide>
<del> #### 7. Save the code and run
<add> #### 7. Salve o projeto e rode no terminal de sua preferência
<add>```shell
<add>$ ionic serve
<ide> ```
<del>
<del>Concha saque iônico \`\` \`
<del>
<del>#### 8\. Para ver o seu código em execução, acesse o navegador e abra o host local: 8100 no URL.
<ide>\ No newline at end of file
<add>#### 8\. Para ver o seu código em execução, acesse o navegador e abra o host local: 8100 no URL. | 1 |
Go | Go | fix race within testrundisconnecttty | acb546cd1bf45a248f4bb51637c795ef63feb6cb | <ide><path>commands.go
<ide> func (srv *Server) CmdRun(stdin io.ReadCloser, stdout rcli.DockerConn, args ...s
<ide> }
<ide> Debugf("Waiting for attach to return\n")
<ide> <-attachErr
<del> container.Wait()
<ide> // Expecting I/O pipe error, discarding
<add>
<add> // If we are in stdinonce mode, wait for the process to end
<add> // otherwise, simply return
<add> if config.StdinOnce && !config.Tty {
<add> container.Wait()
<add> }
<ide> return nil
<ide> }
<ide>
<ide><path>commands_test.go
<ide> func TestRunDisconnectTty(t *testing.T) {
<ide> close(c1)
<ide> }()
<ide>
<add> setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
<add> for {
<add> // Client disconnect after run -i should keep stdin out in TTY mode
<add> l := runtime.List()
<add> if len(l) == 1 && l[0].State.Running {
<add> break
<add> }
<add>
<add> time.Sleep(10 * time.Millisecond)
<add> }
<add> })
<add>
<add> // Client disconnect after run -i should keep stdin out in TTY mode
<add> container := runtime.List()[0]
<add>
<ide> setTimeout(t, "Read/Write assertion timed out", 2*time.Second, func() {
<ide> if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 15); err != nil {
<ide> t.Fatal(err)
<ide> func TestRunDisconnectTty(t *testing.T) {
<ide> // In tty mode, we expect the process to stay alive even after client's stdin closes.
<ide> // Do not wait for run to finish
<ide>
<del> // Client disconnect after run -i should keep stdin out in TTY mode
<del> container := runtime.List()[0]
<ide> // Give some time to monitor to do his thing
<ide> container.WaitTimeout(500 * time.Millisecond)
<ide> if !container.State.Running { | 2 |
Ruby | Ruby | update example outputs of some asset helpers | 65c3b1287e08efdc58065321efdd5b2ec150da41 | <ide><path>actionpack/lib/action_view/helpers/asset_tag_helper.rb
<ide> def favicon_link_tag(source='favicon.ico', options={})
<ide> }.merge(options.symbolize_keys))
<ide> end
<ide>
<del> # Computes the path to an image asset in the public images directory.
<add> # Computes the path to an image asset.
<ide> # Full paths from the document root will be passed through.
<ide> # Used internally by +image_tag+ to build the image path:
<ide> #
<del> # image_path("edit") # => "/images/edit"
<del> # image_path("edit.png") # => "/images/edit.png"
<del> # image_path("icons/edit.png") # => "/images/icons/edit.png"
<add> # image_path("edit") # => "/assets/edit"
<add> # image_path("edit.png") # => "/assets/edit.png"
<add> # image_path("icons/edit.png") # => "/assets/icons/edit.png"
<ide> # image_path("/icons/edit.png") # => "/icons/edit.png"
<ide> # image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png"
<ide> #
<ide> def image_path(source)
<ide> end
<ide> alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
<ide>
<del> # Computes the full URL to an image asset in the public images directory.
<add> # Computes the full URL to an image asset.
<ide> # This will use +image_path+ internally, so most of their behaviors will be the same.
<ide> def image_url(source)
<ide> URI.join(current_host, path_to_image(source)).to_s
<ide> def audio_url(source)
<ide> end
<ide> alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route
<ide>
<del> # Computes the path to a font asset in the public fonts directory.
<add> # Computes the path to a font asset.
<ide> # Full paths from the document root will be passed through.
<ide> #
<ide> # ==== Examples
<del> # font_path("font") # => /fonts/font
<del> # font_path("font.ttf") # => /fonts/font.ttf
<del> # font_path("dir/font.ttf") # => /fonts/dir/font.ttf
<add> # font_path("font") # => /assets/font
<add> # font_path("font.ttf") # => /assets/font.ttf
<add> # font_path("dir/font.ttf") # => /assets/dir/font.ttf
<ide> # font_path("/dir/font.ttf") # => /dir/font.ttf
<ide> # font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf
<ide> def font_path(source)
<ide> asset_paths.compute_public_path(source, 'fonts')
<ide> end
<ide> alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route
<ide>
<del> # Computes the full URL to a font asset in the public fonts directory.
<add> # Computes the full URL to a font asset.
<ide> # This will use +font_path+ internally, so most of their behaviors will be the same.
<ide> def font_url(source)
<ide> URI.join(current_host, path_to_font(source)).to_s
<ide> end
<ide> alias_method :url_to_font, :font_url # aliased to avoid conflicts with an font_url named route
<ide>
<ide> # Returns an html image tag for the +source+. The +source+ can be a full
<del> # path or a file that exists in your public images directory.
<add> # path or a file.
<ide> #
<ide> # ==== Options
<ide> # You can add HTML attributes using the +options+. The +options+ supports
<ide> def font_url(source)
<ide> #
<ide> # ==== Examples
<ide> # image_tag("icon") # =>
<del> # <img src="/images/icon" alt="Icon" />
<add> # <img src="/assets/icon" alt="Icon" />
<ide> # image_tag("icon.png") # =>
<del> # <img src="/images/icon.png" alt="Icon" />
<add> # <img src="/assets/icon.png" alt="Icon" />
<ide> # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # =>
<del> # <img src="/images/icon.png" width="16" height="10" alt="Edit Entry" />
<add> # <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
<ide> # image_tag("/icons/icon.gif", :size => "16x16") # =>
<ide> # <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
<ide> # image_tag("/icons/icon.gif", :height => '32', :width => '32') # =>
<ide> # <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
<ide> # image_tag("/icons/icon.gif", :class => "menu_icon") # =>
<ide> # <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
<del> # image_tag("mouse.png", :mouseover => "/images/mouse_over.png") # =>
<del> # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
<add> # image_tag("mouse.png", :mouseover => "/assets/mouse_over.png") # =>
<add> # <img src="/assets/mouse.png" onmouseover="this.src='/assets/mouse_over.png'" onmouseout="this.src='/assets/mouse.png'" alt="Mouse" />
<ide> # image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # =>
<del> # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
<add> # <img src="/assets/mouse.png" onmouseover="this.src='/assets/mouse_over.png'" onmouseout="this.src='/assets/mouse.png'" alt="Mouse" />
<ide> def image_tag(source, options={})
<ide> options = options.symbolize_keys
<ide>
<ide> def image_alt(src)
<ide> # video_tag("trailer.ogg", :controls => true, :autobuffer => true) # =>
<ide> # <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
<ide> # video_tag("trailer.m4v", :size => "16x10", :poster => "screenshot.png") # =>
<del> # <video src="/videos/trailer.m4v" width="16" height="10" poster="/images/screenshot.png" />
<add> # <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
<ide> # video_tag("/trailers/hd.avi", :size => "16x16") # =>
<ide> # <video src="/trailers/hd.avi" width="16" height="16" />
<ide> # video_tag("/trailers/hd.avi", :height => '32', :width => '32') # => | 1 |
Javascript | Javascript | change plnkr form to open in same window | 925b2080a0341d9348feeb4f492957a2e2c80082 | <ide><path>docs/app/src/examples.js
<ide> angular.module('examples', [])
<ide>
<ide> .factory('formPostData', ['$document', function($document) {
<ide> return function(url, fields) {
<del> var form = angular.element('<form style="display: none;" method="post" action="' + url + '" target="_blank"></form>');
<add> /**
<add> * Form previously posted to target="_blank", but pop-up blockers were causing this to not work.
<add> * If a user chose to bypass pop-up blocker one time and click the link, they would arrive at
<add> * a new default plnkr, not a plnkr with the desired template.
<add> */
<add> var form = angular.element('<form style="display: none;" method="post" action="' + url + '"></form>');
<ide> angular.forEach(fields, function(value, name) {
<ide> var input = angular.element('<input type="hidden" name="' + name + '">');
<ide> input.attr('value', value); | 1 |
Python | Python | show parts of arrays if assert_array_*equal fails | 15a8c04d488e7fb362307165b2f98bba3a8a298b | <ide><path>scipy_test/testing.py
<ide> # These are used by Numeric tests.
<ide> # If Numeric and scipy_base are not available, then some of the
<ide> # functions below will not be available.
<del> from Numeric import alltrue,equal,shape,ravel,around,zeros,Float64,asarray
<add> from Numeric import alltrue,equal,shape,ravel,around,zeros,Float64,asarray,\
<add> less_equal,array2string
<ide> import scipy_base.fastumath as math
<ide> except ImportError:
<ide> pass
<ide> def assert_array_equal(x,y,err_msg=''):
<ide> try:
<ide> assert alltrue(equal(shape(x),shape(y))),\
<ide> msg + ' (shapes mismatch):\n\t' + err_msg
<del> reduced = equal(x,y)
<del> assert alltrue(ravel(reduced)),\
<del> msg + ':\n\t' + err_msg
<add> reduced = ravel(equal(x,y))
<add> cond = alltrue(reduced)
<add> if not cond:
<add> s1 = array2string(x,precision=16)
<add> s2 = array2string(y,precision=16)
<add> if len(s1)>120: s1 = s1[:120] + '...'
<add> if len(s2)>120: s2 = s2[:120] + '...'
<add> match = 100-100.0*reduced.tolist().count(1)/len(reduced)
<add> msg = msg + ' (mismatch %s%%):\n\tArray 1: %s\n\tArray 2: %s' % (match,s1,s2)
<add> assert cond,\
<add> msg + '\n\t' + err_msg
<ide> except ValueError:
<ide> print shape(x),shape(y)
<ide> raise ValueError, 'arrays are not equal'
<ide> def assert_array_almost_equal(x,y,decimal=6,err_msg=''):
<ide> try:
<ide> assert alltrue(equal(shape(x),shape(y))),\
<ide> msg + ' (shapes mismatch):\n\t' + err_msg
<del> reduced = equal(around(abs(x-y),decimal),0)
<del> assert alltrue(ravel(reduced)),\
<del> msg + ':\n\t' + err_msg
<add> reduced = ravel(equal(less_equal(around(abs(x-y),decimal),10.0**(-decimal)),1))
<add> cond = alltrue(reduced)
<add> if not cond:
<add> s1 = array2string(x,precision=decimal+1)
<add> s2 = array2string(y,precision=decimal+1)
<add> if len(s1)>120: s1 = s1[:120] + '...'
<add> if len(s2)>120: s2 = s2[:120] + '...'
<add> match = 100-100.0*reduced.tolist().count(1)/len(reduced)
<add> msg = msg + ' (mismatch %s%%):\n\tArray 1: %s\n\tArray 2: %s' % (match,s1,s2)
<add> assert cond,\
<add> msg + '\n\t' + err_msg
<ide> except ValueError:
<ide> print sys.exc_value
<ide> print shape(x),shape(y) | 1 |
Ruby | Ruby | use `resource#downloader` for `bottleloader` | 9ffc7dd46516e1d94ca4c386fc6006c61bd0e6ca | <ide><path>Library/Homebrew/formulary.rb
<ide> def initialize(bottle_name)
<ide> formula_name = File.basename(bottle_name)[/(.+)-/, 1]
<ide> resource = Resource.new(formula_name) { url bottle_name }
<ide> resource.specs[:bottle] = true
<del> downloader = CurlDownloadStrategy.new(resource.download_name, resource.version, resource)
<add> downloader = resource.downloader
<ide> cached = downloader.cached_location.exist?
<ide> downloader.fetch
<ide> ohai "Pouring the cached bottle" if cached
<ide><path>Library/Homebrew/resource.rb
<ide> def escaped_name
<ide> end
<ide>
<ide> def download_name
<del> name.nil? ? owner.name : "#{owner.name}--#{escaped_name}"
<add> return owner.name if name.nil?
<add> return escaped_name if owner.nil?
<add> "#{owner.name}--#{escaped_name}"
<ide> end
<ide>
<ide> def cached_download | 2 |
PHP | PHP | fix cs errors | efaf3e20066879bdb8a6224ad407b11901ecea18 | <ide><path>tests/TestCase/Database/Driver/MysqlTest.php
<ide> public function testConnectionConfigCustom()
<ide> *
<ide> * @return void
<ide> */
<del> public function testIsConnected() {
<add> public function testIsConnected()
<add> {
<ide> $connection = ConnectionManager::get('test');
<ide> $connection->disconnect();
<ide> $this->assertFalse($connection->isConnected(), 'Not connected now.');
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testResourcesInflection()
<ide> public function testResourcesNestedInflection()
<ide> {
<ide> $routes = new RouteBuilder($this->collection, '/api');
<del> $routes->resources('NetworkObjects', ['inflect' => 'dasherize'], function($routes) {
<del> $routes->resources('Attributes');
<del> });
<add> $routes->resources(
<add> 'NetworkObjects',
<add> ['inflect' => 'dasherize'],
<add> function ($routes) {
<add> $routes->resources('Attributes');
<add> }
<add> );
<ide>
<ide> $all = $this->collection->routes();
<ide> $this->assertCount(10, $all); | 2 |
PHP | PHP | remove sample config file from cakephp tests | bdeafe8b1bb9757abc9fb90a560fc1794daa08eb | <ide><path>src/Core/Plugin.php
<ide> public static function load($plugin, array $config = [])
<ide> }
<ide> return;
<ide> }
<add>
<ide> if (!Configure::check('pluginPaths')) {
<del> Configure::load('plugins');
<add> try {
<add> Configure::load('plugins');
<add> } catch (\Exception $e) {
<add> }
<ide> }
<ide>
<ide> $config += [
<ide><path>tests/test_app/config/plugins.php
<del><?php
<del>$config = [
<del> 'plugins' => []
<del>]; | 2 |
Java | Java | use correct spans in shadow nodes | 9f1dab69c133841c8da3b67e0a8ded3891b12bb4 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java
<ide> private static class SetSpanOperation {
<ide> this.what = what;
<ide> }
<ide> public void execute(SpannableStringBuilder sb) {
<del> sb.setSpan(what, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
<add> // All spans will automatically extend to the right of the text, but not the left - except
<add> // for spans that start at the beginning of the text.
<add> int spanFlags = Spannable.SPAN_EXCLUSIVE_INCLUSIVE;
<add> if (start == 0) {
<add> spanFlags = Spannable.SPAN_INCLUSIVE_INCLUSIVE;
<add> }
<add> sb.setSpan(what, start, end, spanFlags);
<ide> }
<ide> }
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java
<ide> public class ReactTextInputManager extends
<ide> public static final String PROP_TEXT_INPUT_TEXT = "text";
<ide> @UIProp(UIProp.Type.NUMBER)
<ide> public static final String PROP_TEXT_INPUT_MOST_RECENT_EVENT_COUNT = "mostRecentEventCount";
<add> @UIProp(UIProp.Type.COLOR)
<add> public static final String PROP_TEXT_INPUT_COLOR = ViewProps.COLOR;
<ide>
<ide> private static final String KEYBOARD_TYPE_EMAIL_ADDRESS = "email-address";
<ide> private static final String KEYBOARD_TYPE_NUMERIC = "numeric";
<ide> public void setFontSize(ReactEditText view, float fontSize) {
<ide> (int) Math.ceil(PixelUtil.toPixelFromSP(fontSize)));
<ide> }
<ide>
<del> // Prevents flickering color while waiting for JS update.
<del> @ReactProp(name = ViewProps.COLOR, customType = "Color")
<del> public void setColor(ReactEditText view, @Nullable Integer color) {
<del> if (color == null) {
<del> view.setTextColor(DefaultStyleValuesUtil.getDefaultTextColor(view.getContext()));
<del> } else {
<del> view.setTextColor(color);
<del> }
<del> }
<del>
<ide> @ReactProp(name = "placeholder")
<ide> public void setPlaceholder(ReactEditText view, @Nullable String placeholder) {
<ide> view.setHint(placeholder); | 2 |
PHP | PHP | add test for previous commit | 9ae6191dc19d093170af132b20b7fd8522ef55e7 | <ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testNestedPrefix()
<ide> $this->assertNull($res);
<ide> }
<ide>
<add> /**
<add> * Test creating sub-scopes with prefix()
<add> *
<add> * @return void
<add> */
<add> public function testPathWithDotInPrefix()
<add> {
<add> $routes = new RouteBuilder($this->collection, '/admin', ['prefix' => 'admin']);
<add> $res = $routes->prefix('api', function ($r) {
<add> $r->prefix('v10', ['path' => 'v1.0'], function ($r2) {
<add> $this->assertEquals('/admin/api/v1.0', $r2->path());
<add> $this->assertEquals(['prefix' => 'admin/api/v10'], $r2->params());
<add> });
<add> });
<add> $this->assertNull($res);
<add> }
<add>
<ide> /**
<ide> * Test creating sub-scopes with plugin()
<ide> * | 1 |
Python | Python | fix incompatible usage of 'filter' in python3 | 81f89bc304504f2eab03faa25619cad9f121aa4a | <ide><path>research/object_detection/utils/variables_helper.py
<ide> def filter_variables(variables, filter_regex_list, invert=False):
<ide> a list of filtered variables.
<ide> """
<ide> kept_vars = []
<del> variables_to_ignore_patterns = filter(None, filter_regex_list)
<add> variables_to_ignore_patterns = list(filter(None, filter_regex_list))
<ide> for var in variables:
<ide> add = True
<ide> for pattern in variables_to_ignore_patterns: | 1 |
Ruby | Ruby | fix spelling in encryptionschemestest | 97cf9c21fb9f43359af0d9dade3463e10d9b8bc6 | <ide><path>activerecord/test/cases/encryption/encryption_schemes_test.rb
<ide> class ActiveRecord::Encryption::EncryptionSchemesTest < ActiveRecord::Encryption
<ide> end
<ide>
<ide> assert_equal 2, encrypted_author_class.type_for_attribute(:name).previous_encrypted_types.count
<del> previoys_type_1, previoys_type_2 = encrypted_author_class.type_for_attribute(:name).previous_encrypted_types
<add> previous_type_1, previous_type_2 = encrypted_author_class.type_for_attribute(:name).previous_encrypted_types
<ide>
<ide> author = ActiveRecord::Encryption.without_encryption do
<del> encrypted_author_class.create name: previoys_type_1.serialize("1")
<add> encrypted_author_class.create name: previous_type_1.serialize("1")
<ide> end
<ide> assert_equal "0", author.reload.name
<ide>
<ide> author = ActiveRecord::Encryption.without_encryption do
<del> encrypted_author_class.create name: previoys_type_2.serialize("2")
<add> encrypted_author_class.create name: previous_type_2.serialize("2")
<ide> end
<ide> assert_equal "1", author.reload.name
<ide> end | 1 |
Python | Python | guard the unsafe tf.exp to prevent inf cost | 56e7526f5286d5ef61808f774c8c362b56beaae2 | <ide><path>research/lfads/lfads.py
<ide> def encode_data(dataset_bxtxd, enc_cell, name, forward_or_reverse,
<ide> if hps.output_dist == 'poisson':
<ide> log_rates_t = tf.matmul(factors[t], this_out_fac_W) + this_out_fac_b
<ide> log_rates_t.set_shape([None, None])
<del> rates[t] = dist_params[t] = tf.exp(log_rates_t) # rates feed back
<add> rates[t] = dist_params[t] = tf.exp(tf.clip_by_value(log_rates_t, -hps._clip_value, hps._clip_value)) # rates feed back
<ide> rates[t].set_shape([None, hps.dataset_dims[hps.dataset_names[0]]])
<ide> loglikelihood_t = Poisson(log_rates_t).logp(data_t_bxd)
<ide>
<ide> def encode_data(dataset_bxtxd, enc_cell, name, forward_or_reverse,
<ide> value=mean_n_logvars)
<ide> rates[t] = means_t_bxd # rates feed back to controller
<ide> dist_params[t] = tf.concat(
<del> axis=1, values=[means_t_bxd, tf.exp(logvars_t_bxd)])
<add> axis=1, values=[means_t_bxd, tf.exp(tf.clip_by_value(logvars_t_bxd, -hps._clip_value, hps._clip_value))])
<ide> loglikelihood_t = \
<ide> diag_gaussian_log_likelihood(data_t_bxd,
<ide> means_t_bxd, logvars_t_bxd)
<ide><path>research/lfads/run_lfads.py
<ide> def build_hyperparameter_dict(flags):
<ide> d['kl_increase_steps'] = flags.kl_increase_steps
<ide> d['l2_start_step'] = flags.l2_start_step
<ide> d['l2_increase_steps'] = flags.l2_increase_steps
<del>
<add> d['_clip_value'] = 80 # bounds the tf.exp to avoid INF
<add>
<ide> return d
<ide>
<ide> | 2 |
Ruby | Ruby | use puma 3.7.x | bd163bdadf044e75a4812489d9f53a9feeb3cec7 | <ide><path>railties/lib/rails/generators/app_base.rb
<ide> def database_gemfile_entry # :doc:
<ide> def webserver_gemfile_entry # :doc:
<ide> return [] if options[:skip_puma]
<ide> comment = "Use Puma as the app server"
<del> GemfileEntry.new("puma", "~> 3.0", comment)
<add> GemfileEntry.new("puma", "~> 3.7", comment)
<ide> end
<ide>
<ide> def include_all_railties? # :doc:
<ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_generator_without_skips
<ide>
<ide> def test_generator_defaults_to_puma_version
<ide> run_generator [destination_root]
<del> assert_gem "puma", "'~> 3.0'"
<add> assert_gem "puma", "'~> 3.7'"
<ide> end
<ide>
<ide> def test_generator_if_skip_puma_is_given | 2 |
Python | Python | add control if no stats are available | 511d268a25c099f51529eb5fa7740d1c9a964735 | <ide><path>glances/outputs/glances_curses.py
<ide> def display(self, stats, cs_status="None"):
<ide> l += self.get_stats_display_width(stats_load) + self.get_stats_display_width(stats_mem) + self.get_stats_display_width(stats_memswap)
<ide> # Space between column
<ide> space_number = int(stats_load['msgdict'] != []) + int(stats_mem['msgdict'] != []) + int(stats_memswap['msgdict'] != [])
<add> if space_number == 0:
<add> space_number = 1
<ide> if screen_x > (space_number * self.space_between_column + l):
<ide> self.space_between_column = int((screen_x - l) / space_number)
<ide> # Display | 1 |
Javascript | Javascript | improve markup consistency | 015111fd79609eb64ed56032617060c4ed4289f6 | <ide><path>src/ng/directive/ngTransclude.js
<ide> }]);
<ide> </script>
<ide> <div ng-controller="ExampleController">
<del> <input ng-model="title"><br>
<add> <input ng-model="title"> <br/>
<ide> <textarea ng-model="text"></textarea> <br/>
<ide> <pane title="{{title}}">{{text}}</pane>
<ide> </div> | 1 |
Javascript | Javascript | unify all track and tracklist apis | 49bed0703922073cf8a50421f7ae8a72428d173f | <ide><path>src/js/control-bar/audio-track-controls/audio-track-button.js
<ide> class AudioTrackButton extends TrackButton {
<ide> * The key/value store of player options.
<ide> */
<ide> constructor(player, options = {}) {
<del> options.tracks = player.audioTracks && player.audioTracks();
<add> options.tracks = player.audioTracks();
<ide>
<ide> super(player, options);
<ide>
<ide> class AudioTrackButton extends TrackButton {
<ide> * An array of menu items
<ide> */
<ide> createItems(items = []) {
<del> const tracks = this.player_.audioTracks && this.player_.audioTracks();
<del>
<del> if (!tracks) {
<del> return items;
<del> }
<add> const tracks = this.player_.audioTracks();
<ide>
<ide> for (let i = 0; i < tracks.length; i++) {
<ide> const track = tracks[i];
<ide><path>src/js/control-bar/audio-track-controls/audio-track-menu-item.js
<ide> class AudioTrackMenuItem extends MenuItem {
<ide>
<ide> this.track = track;
<ide>
<del> if (tracks) {
<del> const changeHandler = Fn.bind(this, this.handleTracksChange);
<add> const changeHandler = Fn.bind(this, this.handleTracksChange);
<ide>
<del> tracks.addEventListener('change', changeHandler);
<del> this.on('dispose', () => {
<del> tracks.removeEventListener('change', changeHandler);
<del> });
<del> }
<add> tracks.addEventListener('change', changeHandler);
<add> this.on('dispose', () => {
<add> tracks.removeEventListener('change', changeHandler);
<add> });
<ide> }
<ide>
<ide> /**
<ide> class AudioTrackMenuItem extends MenuItem {
<ide>
<ide> super.handleClick(event);
<ide>
<del> if (!tracks) {
<del> return;
<del> }
<del>
<ide> for (let i = 0; i < tracks.length; i++) {
<ide> const track = tracks[i];
<ide>
<ide><path>src/js/control-bar/text-track-controls/descriptions-button.js
<ide> class DescriptionsButton extends TextTrackButton {
<ide> this.el_.setAttribute('aria-label', 'Descriptions Menu');
<ide>
<ide> const tracks = player.textTracks();
<add> const changeHandler = Fn.bind(this, this.handleTracksChange);
<ide>
<del> if (tracks) {
<del> const changeHandler = Fn.bind(this, this.handleTracksChange);
<del>
<del> tracks.addEventListener('change', changeHandler);
<del> this.on('dispose', function() {
<del> tracks.removeEventListener('change', changeHandler);
<del> });
<del> }
<add> tracks.addEventListener('change', changeHandler);
<add> this.on('dispose', function() {
<add> tracks.removeEventListener('change', changeHandler);
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>src/js/control-bar/text-track-controls/text-track-button.js
<ide> class TextTrackButton extends TrackButton {
<ide>
<ide> const tracks = this.player_.textTracks();
<ide>
<del> if (!tracks) {
<del> return items;
<del> }
<del>
<ide> for (let i = 0; i < tracks.length; i++) {
<ide> const track = tracks[i];
<ide>
<ide><path>src/js/control-bar/text-track-controls/text-track-menu-item.js
<ide> class TextTrackMenuItem extends MenuItem {
<ide> super(player, options);
<ide>
<ide> this.track = track;
<add> const changeHandler = Fn.bind(this, this.handleTracksChange);
<ide>
<del> if (tracks) {
<del> const changeHandler = Fn.bind(this, this.handleTracksChange);
<del>
<del> tracks.addEventListener('change', changeHandler);
<del> this.on('dispose', function() {
<del> tracks.removeEventListener('change', changeHandler);
<del> });
<del> }
<add> tracks.addEventListener('change', changeHandler);
<add> this.on('dispose', function() {
<add> tracks.removeEventListener('change', changeHandler);
<add> });
<ide>
<ide> // iOS7 doesn't dispatch change events to TextTrackLists when an
<ide> // associated track's mode changes. Without something like
<ide> // Object.observe() (also not present on iOS7), it's not
<ide> // possible to detect changes to the mode attribute and polyfill
<ide> // the change event. As a poor substitute, we manually dispatch
<ide> // change events whenever the controls modify the mode.
<del> if (tracks && tracks.onchange === undefined) {
<add> if (tracks.onchange === undefined) {
<ide> let event;
<ide>
<ide> this.on(['tap', 'click'], function() {
<ide><path>src/js/player.js
<ide> import mergeOptions from './utils/merge-options.js';
<ide> import textTrackConverter from './tracks/text-track-list-converter.js';
<ide> import ModalDialog from './modal-dialog';
<ide> import Tech from './tech/tech.js';
<del>import AudioTrackList from './tracks/audio-track-list.js';
<del>import VideoTrackList from './tracks/video-track-list.js';
<add>import {ALL as TRACK_TYPES} from './tracks/track-types';
<ide>
<ide> // The following imports are used only to ensure that the corresponding modules
<ide> // are always included in the video.js package. Importing the modules will
<ide> class Player extends Component {
<ide> this.isReady_ = false;
<ide>
<ide> // Grab tech-specific options from player options and add source and parent element to use.
<del> const techOptions = assign({
<add> const techOptions = {
<ide> source,
<ide> 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
<ide> 'playerId': this.id(),
<ide> 'techId': `${this.id()}_${techName}_api`,
<del> 'videoTracks': this.videoTracks_,
<del> 'textTracks': this.textTracks_,
<del> 'audioTracks': this.audioTracks_,
<ide> 'autoplay': this.options_.autoplay,
<ide> 'preload': this.options_.preload,
<ide> 'loop': this.options_.loop,
<ide> class Player extends Component {
<ide> 'language': this.language(),
<ide> 'playerElIngest': this.playerElIngest_ || false,
<ide> 'vtt.js': this.options_['vtt.js']
<del> }, this.options_[techName.toLowerCase()]);
<add> };
<add>
<add> TRACK_TYPES.names.forEach((name) => {
<add> const props = TRACK_TYPES[name];
<add>
<add> techOptions[props.getterName] = this[props.privateName];
<add> });
<add>
<add> assign(techOptions, this.options_[techName.toLowerCase()]);
<ide>
<ide> if (this.tag) {
<ide> techOptions.tag = this.tag;
<ide> class Player extends Component {
<ide> */
<ide> unloadTech_() {
<ide> // Save the current text tracks so that we can reuse the same text tracks with the next tech
<del> this.videoTracks_ = this.videoTracks();
<del> this.textTracks_ = this.textTracks();
<del> this.audioTracks_ = this.audioTracks();
<add> TRACK_TYPES.names.forEach((name) => {
<add> const props = TRACK_TYPES[name];
<add>
<add> this[props.privateName] = this[props.getterName]();
<add> });
<ide> this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
<ide>
<ide> this.isReady_ = false;
<ide> class Player extends Component {
<ide> return !!this.isAudio_;
<ide> }
<ide>
<del> /**
<del> * Get the {@link VideoTrackList}
<del> *
<del> * @see https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
<del> *
<del> * @return {VideoTrackList}
<del> * the current video track list
<del> */
<del> videoTracks() {
<del> // if we have not yet loadTech_, we create videoTracks_
<del> // these will be passed to the tech during loading
<del> if (!this.tech_) {
<del> this.videoTracks_ = this.videoTracks_ || new VideoTrackList();
<del> return this.videoTracks_;
<del> }
<del>
<del> return this.tech_.videoTracks();
<del> }
<del>
<del> /**
<del> * Get the {@link AudioTrackList}
<del> *
<del> * @see https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
<del> *
<del> * @return {AudioTrackList}
<del> * the current audio track list
<del> */
<del> audioTracks() {
<del> // if we have not yet loadTech_, we create videoTracks_
<del> // these will be passed to the tech during loading
<del> if (!this.tech_) {
<del> this.audioTracks_ = this.audioTracks_ || new AudioTrackList();
<del> return this.audioTracks_;
<del> }
<del>
<del> return this.tech_.audioTracks();
<del> }
<del>
<del> /**
<del> * Get the {@link TextTrackList}
<del> *
<del> * Text tracks are tracks of timed text events.
<del> * - Captions: text displayed over the video
<del> * for the hearing impaired
<del> * - Subtitles: text displayed over the video for
<del> * those who don't understand language in the video
<del> * - Chapters: text displayed in a menu allowing the user to jump
<del> * to particular points (chapters) in the video
<del> * - Descriptions: (not yet implemented) audio descriptions that are read back to
<del> * the user by a screen reading device
<del> *
<del> * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
<del> *
<del> * @return {TextTrackList|undefined}
<del> * The current TextTrackList or undefined if
<del> * or undefined if we don't have a tech
<del> */
<del> textTracks() {
<del> // cannot use techGet_ directly because it checks to see whether the tech is ready.
<del> // Flash is unlikely to be ready in time but textTracks should still work.
<del> if (this.tech_) {
<del> return this.tech_.textTracks();
<del> }
<del> }
<del>
<del> /**
<del> * Get the "remote" {@link TextTrackList}. Remote Text Tracks
<del> * are tracks that were added to the HTML video element and can
<del> * be removed, whereas normal texttracks cannot be removed.
<del> *
<del> *
<del> * @return {TextTrackList|undefined}
<del> * The current remote text track list or undefined
<del> * if we don't have a tech
<del> */
<del> remoteTextTracks() {
<del> if (this.tech_) {
<del> return this.tech_.remoteTextTracks();
<del> }
<del> }
<del>
<del> /**
<del> * Get the "remote" {@link HTMLTrackElementList}.
<del> * This gives the user all of the DOM elements that match up
<del> * with the remote {@link TextTrackList}.
<del> *
<del> * @return {HTMLTrackElementList}
<del> * The current remote text track list elements
<del> * or undefined if we don't have a tech
<del> */
<del> remoteTextTrackEls() {
<del> if (this.tech_) {
<del> return this.tech_.remoteTextTrackEls();
<del> }
<del> }
<del>
<ide> /**
<ide> * A helper method for adding a {@link TextTrack} to our
<ide> * {@link TextTrackList}.
<ide> class Player extends Component {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Get the {@link VideoTrackList}
<add> * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
<add> *
<add> * @return {VideoTrackList}
<add> * the current video track list
<add> *
<add> * @method Player.prototype.videoTracks
<add> */
<add>
<add>/**
<add> * Get the {@link AudioTrackList}
<add> * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
<add> *
<add> * @return {AudioTrackList}
<add> * the current audio track list
<add> *
<add> * @method Player.prototype.audioTracks
<add> */
<add>
<add>/**
<add> * Get the {@link TextTrackList}
<add> *
<add> * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
<add> *
<add> * @return {TextTrackList}
<add> * the current text track list
<add> *
<add> * @method Player.prototype.textTracks
<add> */
<add>
<add>/**
<add> * Get the remote {@link TextTrackList}
<add> *
<add> * @return {TextTrackList}
<add> * The current remote text track list
<add> *
<add> * @method Player.prototype.textTracks
<add> */
<add>
<add>/**
<add> * Get the remote {@link HTMLTrackElementList} tracks.
<add> *
<add> * @return {HTMLTrackElementList}
<add> * The current remote text track element list
<add> *
<add> * @method Player.prototype.remoteTextTrackEls
<add> */
<add>
<add>TRACK_TYPES.names.forEach(function(name) {
<add> const props = TRACK_TYPES[name];
<add>
<add> Player.prototype[props.getterName] = function() {
<add> if (this.tech_) {
<add> return this.tech_[props.getterName]();
<add> }
<add>
<add> // if we have not yet loadTech_, we create {video,audio,text}Tracks_
<add> // these will be passed to the tech during loading
<add> this[props.privateName] = this[props.privateName] || new props.ListClass();
<add> return this[props.privateName];
<add> };
<add>});
<add>
<ide> /**
<ide> * Global player list
<ide> *
<ide><path>src/js/tech/html5.js
<ide> import Tech from './tech.js';
<ide> import * as Dom from '../utils/dom.js';
<ide> import * as Url from '../utils/url.js';
<del>import * as Fn from '../utils/fn.js';
<ide> import log from '../utils/log.js';
<ide> import tsml from 'tsml';
<ide> import * as browser from '../utils/browser.js';
<ide> import window from 'global/window';
<ide> import {assign} from '../utils/obj';
<ide> import mergeOptions from '../utils/merge-options.js';
<ide> import toTitleCase from '../utils/to-title-case.js';
<add>import {NORMAL as TRACK_TYPES} from '../tracks/track-types';
<ide>
<ide> /**
<ide> * HTML5 Media Controller - Wrapper for HTML5 Media API
<ide> class Html5 extends Tech {
<ide> } else {
<ide> // store HTMLTrackElement and TextTrack to remote list
<ide> this.remoteTextTrackEls().addTrackElement_(node);
<del> this.remoteTextTracks().addTrack_(node.track);
<add> this.remoteTextTracks().addTrack(node.track);
<ide> if (!crossoriginTracks &&
<ide> !this.el_.hasAttribute('crossorigin') &&
<ide> Url.isCrossOrigin(node.src)) {
<ide> class Html5 extends Tech {
<ide> }
<ide> }
<ide>
<del> // TODO: add text tracks into this list
<del> const trackTypes = ['audio', 'video'];
<del>
<del> // ProxyNative Video/Audio Track
<del> trackTypes.forEach((type) => {
<del> const elTracks = this.el()[`${type}Tracks`];
<del> const techTracks = this[`${type}Tracks`]();
<del> const capitalType = toTitleCase(type);
<del>
<del> if (!this[`featuresNative${capitalType}Tracks`] ||
<del> !elTracks ||
<del> !elTracks.addEventListener) {
<del> return;
<del> }
<del>
<del> this[`handle${capitalType}TrackChange_`] = (e) => {
<del> techTracks.trigger({
<del> type: 'change',
<del> target: techTracks,
<del> currentTarget: techTracks,
<del> srcElement: techTracks
<del> });
<del> };
<del>
<del> this[`handle${capitalType}TrackAdd_`] = (e) => techTracks.addTrack(e.track);
<del> this[`handle${capitalType}TrackRemove_`] = (e) => techTracks.removeTrack(e.track);
<del>
<del> elTracks.addEventListener('change', this[`handle${capitalType}TrackChange_`]);
<del> elTracks.addEventListener('addtrack', this[`handle${capitalType}TrackAdd_`]);
<del> elTracks.addEventListener('removetrack', this[`handle${capitalType}TrackRemove_`]);
<del> this[`removeOld${capitalType}Tracks_`] = (e) => this.removeOldTracks_(techTracks, elTracks);
<del>
<del> // Remove (native) tracks that are not used anymore
<del> this.on('loadstart', this[`removeOld${capitalType}Tracks_`]);
<del> });
<del>
<del> if (this.featuresNativeTextTracks) {
<del> if (crossoriginTracks) {
<del> log.warn(tsml`Text Tracks are being loaded from another origin but the crossorigin attribute isn't used.
<add> this.proxyNativeTracks_();
<add> if (this.featuresNativeTextTracks && crossoriginTracks) {
<add> log.warn(tsml`Text Tracks are being loaded from another origin but the crossorigin attribute isn't used.
<ide> This may prevent text tracks from loading.`);
<del> }
<del>
<del> this.handleTextTrackChange_ = Fn.bind(this, this.handleTextTrackChange);
<del> this.handleTextTrackAdd_ = Fn.bind(this, this.handleTextTrackAdd);
<del> this.handleTextTrackRemove_ = Fn.bind(this, this.handleTextTrackRemove);
<del> this.proxyNativeTextTracks_();
<ide> }
<ide>
<ide> // Determine if native controls should be used
<ide> class Html5 extends Tech {
<ide> * Dispose of `HTML5` media element and remove all tracks.
<ide> */
<ide> dispose() {
<del> // Un-ProxyNativeTracks
<del> ['audio', 'video', 'text'].forEach((type) => {
<del> const capitalType = toTitleCase(type);
<del> const tl = this.el_[`${type}Tracks`];
<del>
<del> if (tl && tl.removeEventListener) {
<del> tl.removeEventListener('change', this[`handle${capitalType}TrackChange_`]);
<del> tl.removeEventListener('addtrack', this[`handle${capitalType}TrackAdd_`]);
<del> tl.removeEventListener('removetrack', this[`handle${capitalType}TrackRemove_`]);
<del> }
<add> Html5.disposeMediaElement(this.el_);
<add> // tech will handle clearing of the emulated track list
<add> super.dispose();
<add> }
<add>
<add> /**
<add> * Proxy all native track list events to our track lists if the browser we are playing
<add> * in supports that type of track list.
<add> *
<add> * @private
<add> */
<add> proxyNativeTracks_() {
<add> TRACK_TYPES.names.forEach((name) => {
<add> const props = TRACK_TYPES[name];
<add> const elTracks = this.el()[props.getterName];
<add> const techTracks = this[props.getterName]();
<ide>
<del> // Stop removing old text tracks
<del> if (tl) {
<del> this.off('loadstart', this[`removeOld${capitalType}Tracks_`]);
<add> if (!this[`featuresNative${props.capitalName}Tracks`] ||
<add> !elTracks ||
<add> !elTracks.addEventListener) {
<add> return;
<ide> }
<add> const listeners = {
<add> change(e) {
<add> techTracks.trigger({
<add> type: 'change',
<add> target: techTracks,
<add> currentTarget: techTracks,
<add> srcElement: techTracks
<add> });
<add> },
<add> addtrack(e) {
<add> techTracks.addTrack(e.track);
<add> },
<add> removetrack(e) {
<add> techTracks.removeTrack(e.track);
<add> }
<add> };
<add> const removeOldTracks = function() {
<add> const removeTracks = [];
<add>
<add> for (let i = 0; i < techTracks.length; i++) {
<add> let found = false;
<add>
<add> for (let j = 0; j < elTracks.length; j++) {
<add> if (elTracks[j] === techTracks[i]) {
<add> found = true;
<add> break;
<add> }
<add> }
<add>
<add> if (!found) {
<add> removeTracks.push(techTracks[i]);
<add> }
<add> }
<add>
<add> while (removeTracks.length) {
<add> techTracks.removeTrack(removeTracks.shift());
<add> }
<add> };
<add>
<add> Object.keys(listeners).forEach((eventName) => {
<add> const listener = listeners[eventName];
<add>
<add> elTracks.addEventListener(eventName, listener);
<add> this.on('dispose', (e) => elTracks.removeEventListener(eventName, listener));
<add> });
<add>
<add> // Remove (native) tracks that are not used anymore
<add> this.on('loadstart', removeOldTracks);
<add> this.on('dispose', (e) => this.off('loadstart', removeOldTracks));
<ide> });
<ide>
<del> Html5.disposeMediaElement(this.el_);
<del> // tech will handle clearing of the emulated track list
<del> super.dispose();
<ide> }
<ide>
<ide> /**
<ide> class Html5 extends Tech {
<ide> }
<ide>
<ide> /**
<del> * Add event listeners to native text track events. This adds the native text tracks
<del> * to our emulated {@link TextTrackList}.
<add> * Called by {@link Player#play} to play using the `Html5` `Tech`.
<ide> */
<del> proxyNativeTextTracks_() {
<del> const tt = this.el().textTracks;
<del>
<del> if (tt) {
<del> // Add tracks - if player is initialised after DOM loaded, textTracks
<del> // will not trigger addtrack
<del> for (let i = 0; i < tt.length; i++) {
<del> this.textTracks().addTrack_(tt[i]);
<del> }
<del>
<del> if (tt.addEventListener) {
<del> tt.addEventListener('change', this.handleTextTrackChange_);
<del> tt.addEventListener('addtrack', this.handleTextTrackAdd_);
<del> tt.addEventListener('removetrack', this.handleTextTrackRemove_);
<del> }
<add> play() {
<add> const playPromise = this.el_.play();
<ide>
<del> // Remove (native) texttracks that are not used anymore
<del> this.on('loadstart', this.removeOldTextTracks_);
<add> // Catch/silence error when a pause interrupts a play request
<add> // on browsers which return a promise
<add> if (playPromise !== undefined && typeof playPromise.then === 'function') {
<add> playPromise.then(null, (e) => {});
<ide> }
<ide> }
<ide>
<del> /**
<del> * Handle any {@link TextTrackList} `change` event.
<del> *
<del> * @param {EventTarget~Event} e
<del> * The `change` event that caused this to run.
<del> *
<del> * @listens TextTrackList#change
<del> */
<del> handleTextTrackChange(e) {
<del> const tt = this.textTracks();
<del>
<del> this.textTracks().trigger({
<del> type: 'change',
<del> target: tt,
<del> currentTarget: tt,
<del> srcElement: tt
<del> });
<del> }
<del>
<del> /**
<del> * Handle any {@link TextTrackList} `addtrack` event.
<del> *
<del> * @param {EventTarget~Event} e
<del> * The `addtrack` event that caused this to run.
<del> *
<del> * @listens TextTrackList#addtrack
<del> */
<del> handleTextTrackAdd(e) {
<del> this.textTracks().addTrack_(e.track);
<del> }
<del>
<del> /**
<del> * Handle any {@link TextTrackList} `removetrack` event.
<del> *
<del> * @param {EventTarget~Event} e
<del> * The `removetrack` event that caused this to run.
<del> *
<del> * @listens TextTrackList#removetrack
<del> */
<del> handleTextTrackRemove(e) {
<del> this.textTracks().removeTrack_(e.track);
<del> }
<del>
<del> /**
<del> * This function removes any {@link AudioTrack}s, {@link VideoTrack}s, or
<del> * {@link TextTrack}s that are not in the media elements TrackList.
<del> *
<del> * @param {TrackList} techTracks
<del> * HTML5 Tech's TrackList to search through
<del> *
<del> * @param {TrackList} elTracks
<del> * HTML5 media elements TrackList to search trough.
<del> *
<del> * @private
<del> */
<del> removeOldTracks_(techTracks, elTracks) {
<del> // This will loop over the techTracks and check if they are still used by the HTML5 media element
<del> // If not, they will be removed from the emulated list
<del> const removeTracks = [];
<del>
<del> if (!elTracks) {
<del> return;
<del> }
<del>
<del> for (let i = 0; i < techTracks.length; i++) {
<del> const techTrack = techTracks[i];
<del> let found = false;
<del>
<del> for (let j = 0; j < elTracks.length; j++) {
<del> if (elTracks[j] === techTrack) {
<del> found = true;
<del> break;
<del> }
<del> }
<del>
<del> if (!found) {
<del> removeTracks.push(techTrack);
<del> }
<del> }
<del>
<del> for (let i = 0; i < removeTracks.length; i++) {
<del> const track = removeTracks[i];
<del>
<del> techTracks.removeTrack_(track);
<del> }
<del> }
<del>
<del> /**
<del> * Remove {@link TextTrack}s that dont exist in the native track list from our
<del> * emulated {@link TextTrackList}.
<del> *
<del> * @listens Tech#loadstart
<del> */
<del> removeOldTextTracks_(e) {
<del> const techTracks = this.textTracks();
<del> const elTracks = this.el().textTracks;
<del>
<del> this.removeOldTracks_(techTracks, elTracks);
<del> }
<del>
<ide> /**
<ide> * Set current time for the `HTML5` tech.
<ide> *
<ide><path>src/js/tech/tech.js
<ide> */
<ide>
<ide> import Component from '../component';
<del>import HTMLTrackElement from '../tracks/html-track-element';
<del>import HTMLTrackElementList from '../tracks/html-track-element-list';
<ide> import mergeOptions from '../utils/merge-options.js';
<del>import TextTrack from '../tracks/text-track';
<del>import TextTrackList from '../tracks/text-track-list';
<del>import VideoTrackList from '../tracks/video-track-list';
<del>import AudioTrackList from '../tracks/audio-track-list';
<ide> import * as Fn from '../utils/fn.js';
<ide> import log from '../utils/log.js';
<ide> import { createTimeRange } from '../utils/time-ranges.js';
<ide> import MediaError from '../media-error.js';
<ide> import window from 'global/window';
<ide> import document from 'global/document';
<ide> import {isPlain} from '../utils/obj';
<add>import * as TRACK_TYPES from '../tracks/track-types';
<ide>
<ide> /**
<ide> * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
<ide> function createTrackHelper(self, kind, label, language, options = {}) {
<ide> }
<ide> options.tech = self;
<ide>
<del> const track = new TextTrack(options);
<add> const track = new TRACK_TYPES.ALL.text.TrackClass(options);
<ide>
<del> tracks.addTrack_(track);
<add> tracks.addTrack(track);
<ide>
<ide> return track;
<ide> }
<ide> class Tech extends Component {
<ide> this.hasStarted_ = false;
<ide> });
<ide>
<del> this.textTracks_ = options.textTracks;
<del> this.videoTracks_ = options.videoTracks;
<del> this.audioTracks_ = options.audioTracks;
<add> TRACK_TYPES.ALL.names.forEach((name) => {
<add> const props = TRACK_TYPES.ALL[name];
<add>
<add> if (options && options[props.getterName]) {
<add> this[props.privateName] = options[props.getterName];
<add> }
<add> });
<ide>
<ide> // Manually track progress in cases where the browser/flash player doesn't report it.
<ide> if (!this.featuresProgressEvents) {
<ide> class Tech extends Component {
<ide> this.emulateTextTracks();
<ide> }
<ide>
<del> this.autoRemoteTextTracks_ = new TextTrackList();
<add> this.autoRemoteTextTracks_ = new TRACK_TYPES.ALL.text.ListClass();
<ide>
<del> this.initTextTrackListeners();
<ide> this.initTrackListeners();
<ide>
<ide> // Turn on component tap events only if not using native controls
<ide> class Tech extends Component {
<ide> dispose() {
<ide>
<ide> // clear out all tracks because we can't reuse them between techs
<del> this.clearTracks(['audio', 'video', 'text']);
<add> this.clearTracks(TRACK_TYPES.NORMAL.names);
<ide>
<ide> // Turn off any manual progress or timeupdate tracking
<ide> if (this.manualProgress) {
<ide> class Tech extends Component {
<ide> if (type === 'text') {
<ide> this.removeRemoteTextTrack(track);
<ide> }
<del> list.removeTrack_(track);
<add> list.removeTrack(track);
<ide> }
<ide> });
<ide> }
<ide> class Tech extends Component {
<ide> }
<ide>
<ide> /**
<del> * Turn on listeners for {@link TextTrackList} events. This adds
<del> * {@link EventTarget~EventListeners} for `texttrackchange`, `addtrack` and
<del> * `removetrack`.
<add> * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
<add> * {@link TextTrackList} events.
<ide> *
<del> * @fires Tech#texttrackchange
<del> */
<del> initTextTrackListeners() {
<del> const textTrackListChanges = Fn.bind(this, function() {
<del> /**
<del> * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
<del> *
<del> * @event Tech#texttrackchange
<del> * @type {EventTarget~Event}
<del> */
<del> this.trigger('texttrackchange');
<del> });
<del>
<del> const tracks = this.textTracks();
<del>
<del> if (!tracks) {
<del> return;
<del> }
<del>
<del> tracks.addEventListener('removetrack', textTrackListChanges);
<del> tracks.addEventListener('addtrack', textTrackListChanges);
<del>
<del> this.on('dispose', Fn.bind(this, function() {
<del> tracks.removeEventListener('removetrack', textTrackListChanges);
<del> tracks.removeEventListener('addtrack', textTrackListChanges);
<del> }));
<del> }
<del>
<del> /**
<del> * Turn on listeners for {@link VideoTrackList} and {@link {AudioTrackList} events.
<ide> * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
<ide> *
<ide> * @fires Tech#audiotrackchange
<ide> * @fires Tech#videotrackchange
<add> * @fires Tech#texttrackchange
<ide> */
<ide> initTrackListeners() {
<del> const trackTypes = ['video', 'audio'];
<del>
<del> trackTypes.forEach((type) => {
<ide> /**
<ide> * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
<ide> *
<ide> class Tech extends Component {
<ide> * @event Tech#videotrackchange
<ide> * @type {EventTarget~Event}
<ide> */
<add>
<add> /**
<add> * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
<add> *
<add> * @event Tech#texttrackchange
<add> * @type {EventTarget~Event}
<add> */
<add> TRACK_TYPES.NORMAL.names.forEach((name) => {
<add> const props = TRACK_TYPES.NORMAL[name];
<ide> const trackListChanges = () => {
<del> this.trigger(`${type}trackchange`);
<add> this.trigger(`${name}trackchange`);
<ide> };
<ide>
<del> const tracks = this[`${type}Tracks`]();
<add> const tracks = this[props.getterName]();
<ide>
<ide> tracks.addEventListener('removetrack', trackListChanges);
<ide> tracks.addEventListener('addtrack', trackListChanges);
<ide> class Tech extends Component {
<ide> emulateTextTracks() {
<ide> const tracks = this.textTracks();
<ide>
<del> if (!tracks) {
<del> return;
<del> }
<del>
<ide> this.remoteTextTracks().on('addtrack', (e) => {
<del> this.textTracks().addTrack_(e.track);
<add> tracks.addTrack(e.track);
<ide> });
<ide>
<ide> this.remoteTextTracks().on('removetrack', (e) => {
<del> this.textTracks().removeTrack_(e.track);
<add> tracks.removeTrack(e.track);
<ide> });
<ide>
<ide> // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
<ide> class Tech extends Component {
<ide> });
<ide> }
<ide>
<del> /**
<del> * Get the `Tech`s {@link VideoTrackList}.
<del> *
<del> * @return {VideoTrackList}
<del> * The video track list that the Tech is currently using.
<del> */
<del> videoTracks() {
<del> this.videoTracks_ = this.videoTracks_ || new VideoTrackList();
<del> return this.videoTracks_;
<del> }
<del>
<del> /**
<del> * Get the `Tech`s {@link AudioTrackList}.
<del> *
<del> * @return {AudioTrackList}
<del> * The audio track list that the Tech is currently using.
<del> */
<del> audioTracks() {
<del> this.audioTracks_ = this.audioTracks_ || new AudioTrackList();
<del> return this.audioTracks_;
<del> }
<del>
<del> /**
<del> * Get the `Tech`s {@link TextTrackList}.
<del> *
<del> * @return {TextTrackList}
<del> * The text track list that the Tech is currently using.
<del> */
<del> textTracks() {
<del> this.textTracks_ = this.textTracks_ || new TextTrackList();
<del> return this.textTracks_;
<del> }
<del>
<del> /**
<del> * Get the `Tech`s remote {@link TextTrackList}, which is created from elements
<del> * that were added to the DOM.
<del> *
<del> * @return {TextTrackList}
<del> * The remote text track list that the Tech is currently using.
<del> */
<del> remoteTextTracks() {
<del> this.remoteTextTracks_ = this.remoteTextTracks_ || new TextTrackList();
<del> return this.remoteTextTracks_;
<del> }
<del>
<del> /**
<del> * Get The `Tech`s {HTMLTrackElementList}, which are the elements in the DOM that are
<del> * being used as TextTracks.
<del> *
<del> * @return {HTMLTrackElementList}
<del> * The current HTML track elements that exist for the tech.
<del> */
<del> remoteTextTrackEls() {
<del> this.remoteTextTrackEls_ = this.remoteTextTrackEls_ || new HTMLTrackElementList();
<del> return this.remoteTextTrackEls_;
<del> }
<del>
<ide> /**
<ide> * Create and returns a remote {@link TextTrack} object.
<ide> *
<ide> class Tech extends Component {
<ide> tech: this
<ide> });
<ide>
<del> return new HTMLTrackElement(track);
<add> return new TRACK_TYPES.REMOTE.remoteTextEl.TrackClass(track);
<ide> }
<ide>
<ide> /**
<ide> class Tech extends Component {
<ide>
<ide> // store HTMLTrackElement and TextTrack to remote list
<ide> this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
<del> this.remoteTextTracks().addTrack_(htmlTrackElement.track);
<add> this.remoteTextTracks().addTrack(htmlTrackElement.track);
<ide>
<ide> if (manualCleanup !== true) {
<ide> // create the TextTrackList if it doesn't exist
<del> this.autoRemoteTextTracks_.addTrack_(htmlTrackElement.track);
<add> this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track);
<ide> }
<ide>
<ide> return htmlTrackElement;
<ide> class Tech extends Component {
<ide>
<ide> // remove HTMLTrackElement and TextTrack from remote list
<ide> this.remoteTextTrackEls().removeTrackElement_(trackElement);
<del> this.remoteTextTracks().removeTrack_(track);
<del> this.autoRemoteTextTracks_.removeTrack_(track);
<add> this.remoteTextTracks().removeTrack(track);
<add> this.autoRemoteTextTracks_.removeTrack(track);
<ide> }
<ide>
<ide> /**
<ide> class Tech extends Component {
<ide> }
<ide>
<ide> /**
<del> * List of associated text tracks.
<add> * Get the {@link VideoTrackList}
<add> *
<add> * @returns {VideoTrackList}
<add> * @method Tech.prototype.videoTracks
<add> */
<add>
<add>/**
<add> * Get the {@link AudioTrackList}
<add> *
<add> * @returns {AudioTrackList}
<add> * @method Tech.prototype.audioTracks
<add> */
<add>
<add>/**
<add> * Get the {@link TextTrackList}
<add> *
<add> * @returns {TextTrackList}
<add> * @method Tech.prototype.textTracks
<add> */
<add>
<add>/**
<add> * Get the remote element {@link TextTrackList}
<add> *
<add> * @returns {TextTrackList}
<add> * @method Tech.prototype.remoteTextTracks
<add> */
<add>
<add>/**
<add> * Get the remote element {@link HTMLTrackElementList}
<add> *
<add> * @returns {HTMLTrackElementList}
<add> * @method Tech.prototype.remoteTextTrackEls
<add> */
<add>
<add>TRACK_TYPES.ALL.names.forEach(function(name) {
<add> const props = TRACK_TYPES.ALL[name];
<add>
<add> Tech.prototype[props.getterName] = function() {
<add> this[props.privateName] = this[props.privateName] || new props.ListClass();
<add> return this[props.privateName];
<add> };
<add>});
<add>
<add>/**
<add> * List of associated text tracks
<ide> *
<ide> * @type {TextTrackList}
<ide> * @private
<add> * @property Tech#textTracks_
<ide> */
<del>Tech.prototype.textTracks_; // eslint-disable-line
<ide>
<ide> /**
<ide> * List of associated audio tracks.
<ide> *
<ide> * @type {AudioTrackList}
<ide> * @private
<add> * @property Tech#audioTracks_
<ide> */
<del>Tech.prototype.audioTracks_; // eslint-disable-line
<ide>
<ide> /**
<ide> * List of associated video tracks.
<ide> *
<ide> * @type {VideoTrackList}
<ide> * @private
<add> * @property Tech#videoTracks_
<ide> */
<del>Tech.prototype.videoTracks_; // eslint-disable-line
<ide>
<ide> /**
<ide> * Boolean indicating wether the `Tech` supports volume control.
<ide><path>src/js/tracks/audio-track-list.js
<ide> class AudioTrackList extends TrackList {
<ide> * @param {AudioTrack} track
<ide> * The AudioTrack to add to the list
<ide> *
<del> * @fires Track#addtrack
<del> * @private
<add> * @fires TrackList#addtrack
<ide> */
<del> addTrack_(track) {
<add> addTrack(track) {
<ide> if (track.enabled) {
<ide> disableOthers(this, track);
<ide> }
<ide>
<del> super.addTrack_(track);
<add> super.addTrack(track);
<ide> // native tracks don't have this
<ide> if (!track.addEventListener) {
<ide> return;
<ide> class AudioTrackList extends TrackList {
<ide> this.trigger('change');
<ide> });
<ide> }
<del>
<del> /**
<del> * Add an {@link AudioTrack} to the `AudioTrackList`.
<del> *
<del> * @param {AudioTrack} track
<del> * The AudioTrack to add to the list
<del> *
<del> * @fires Track#addtrack
<del> */
<del> addTrack(track) {
<del> this.addTrack_(track);
<del> }
<del>
<del> /**
<del> * Remove an {@link AudioTrack} from the `AudioTrackList`.
<del> *
<del> * @param {AudioTrack} track
<del> * The AudioTrack to remove from the list
<del> *
<del> * @fires Track#removetrack
<del> */
<del> removeTrack(track) {
<del> super.removeTrack_(track);
<del> }
<del>
<ide> }
<ide>
<ide> export default AudioTrackList;
<ide><path>src/js/tracks/text-track-display.js
<ide> class TextTrackDisplay extends Component {
<ide> let firstDesc;
<ide> let firstCaptions;
<ide>
<del> if (trackList) {
<del> for (let i = 0; i < trackList.length; i++) {
<del> const track = trackList[i];
<del>
<del> if (track.default) {
<del> if (track.kind === 'descriptions' && !firstDesc) {
<del> firstDesc = track;
<del> } else if (track.kind in modes && !firstCaptions) {
<del> firstCaptions = track;
<del> }
<add> for (let i = 0; i < trackList.length; i++) {
<add> const track = trackList[i];
<add>
<add> if (track.default) {
<add> if (track.kind === 'descriptions' && !firstDesc) {
<add> firstDesc = track;
<add> } else if (track.kind in modes && !firstCaptions) {
<add> firstCaptions = track;
<ide> }
<ide> }
<add> }
<ide>
<del> // We want to show the first default track but captions and subtitles
<del> // take precedence over descriptions.
<del> // So, display the first default captions or subtitles track
<del> // and otherwise the first default descriptions track.
<del> if (firstCaptions) {
<del> firstCaptions.mode = 'showing';
<del> } else if (firstDesc) {
<del> firstDesc.mode = 'showing';
<del> }
<add> // We want to show the first default track but captions and subtitles
<add> // take precedence over descriptions.
<add> // So, display the first default captions or subtitles track
<add> // and otherwise the first default descriptions track.
<add> if (firstCaptions) {
<add> firstCaptions.mode = 'showing';
<add> } else if (firstDesc) {
<add> firstDesc.mode = 'showing';
<ide> }
<ide> }));
<ide> }
<ide> class TextTrackDisplay extends Component {
<ide>
<ide> this.clearDisplay();
<ide>
<del> if (!tracks) {
<del> return;
<del> }
<del>
<ide> // Track display prioritization model: if multiple tracks are 'showing',
<ide> // display the first 'subtitles' or 'captions' track which is 'showing',
<ide> // otherwise display the first 'descriptions' track which is 'showing'
<ide>
<ide> let descriptionsTrack = null;
<ide> let captionsSubtitlesTrack = null;
<del>
<ide> let i = tracks.length;
<ide>
<ide> while (i--) {
<ide><path>src/js/tracks/text-track-list.js
<ide> class TextTrackList extends TrackList {
<ide> * The text track to add to the list.
<ide> *
<ide> * @fires TrackList#addtrack
<del> * @private
<ide> */
<del> addTrack_(track) {
<del> super.addTrack_(track);
<add> addTrack(track) {
<add> super.addTrack(track);
<ide>
<ide> /**
<ide> * @listens TextTrack#modechange
<ide><path>src/js/tracks/text-track.js
<ide> class TextTrack extends Track {
<ide> addCue(cue) {
<ide> const tracks = this.tech_.textTracks();
<ide>
<del> if (tracks) {
<del> for (let i = 0; i < tracks.length; i++) {
<del> if (tracks[i] !== this) {
<del> tracks[i].removeCue(cue);
<del> }
<add> for (let i = 0; i < tracks.length; i++) {
<add> if (tracks[i] !== this) {
<add> tracks[i].removeCue(cue);
<ide> }
<ide> }
<ide>
<ide><path>src/js/tracks/track-list.js
<ide> class TrackList extends EventTarget {
<ide> });
<ide>
<ide> for (let i = 0; i < tracks.length; i++) {
<del> list.addTrack_(tracks[i]);
<add> list.addTrack(tracks[i]);
<ide> }
<ide>
<ide> // must return the object, as for ie8 it will not be this
<ide> class TrackList extends EventTarget {
<ide> * The audio, video, or text track to add to the list.
<ide> *
<ide> * @fires TrackList#addtrack
<del> * @private
<ide> */
<del> addTrack_(track) {
<add> addTrack(track) {
<ide> const index = this.tracks_.length;
<ide>
<ide> if (!('' + index in this)) {
<ide> class TrackList extends EventTarget {
<ide> /**
<ide> * Remove a {@link Track} from the `TrackList`
<ide> *
<del> * @param {Track} track
<add> * @param {Track} rtrack
<ide> * The audio, video, or text track to remove from the list.
<ide> *
<ide> * @fires TrackList#removetrack
<del> * @private
<ide> */
<del> removeTrack_(rtrack) {
<add> removeTrack(rtrack) {
<ide> let track;
<ide>
<ide> for (let i = 0, l = this.length; i < l; i++) {
<ide><path>src/js/tracks/track-types.js
<add>import AudioTrackList from './audio-track-list';
<add>import VideoTrackList from './video-track-list';
<add>import TextTrackList from './text-track-list';
<add>import HTMLTrackElementList from './html-track-element-list';
<add>
<add>import TextTrack from './text-track';
<add>import AudioTrack from './audio-track';
<add>import VideoTrack from './video-track';
<add>import HTMLTrackElement from './html-track-element';
<add>
<add>import mergeOptions from '../utils/merge-options';
<add>
<add>/**
<add> * This file contains all track properties that are used in
<add> * player.js, tech.js, html5.js and possibly other techs in the future.
<add> */
<add>
<add>const NORMAL = {
<add> audio: {
<add> ListClass: AudioTrackList,
<add> TrackClass: AudioTrack,
<add> capitalName: 'Audio'
<add> },
<add> video: {
<add> ListClass: VideoTrackList,
<add> TrackClass: VideoTrack,
<add> capitalName: 'Video'
<add> },
<add> text: {
<add> ListClass: TextTrackList,
<add> TrackClass: TextTrack,
<add> capitalName: 'Text'
<add> }
<add>};
<add>
<add>Object.keys(NORMAL).forEach(function(type) {
<add> NORMAL[type].getterName = `${type}Tracks`;
<add> NORMAL[type].privateName = `${type}Tracks_`;
<add>});
<add>
<add>const REMOTE = {
<add> remoteText: {
<add> ListClass: TextTrackList,
<add> TrackClass: TextTrack,
<add> capitalName: 'RemoteText',
<add> getterName: 'remoteTextTracks',
<add> privateName: 'remoteTextTracks_'
<add> },
<add> remoteTextEl: {
<add> ListClass: HTMLTrackElementList,
<add> TrackClass: HTMLTrackElement,
<add> capitalName: 'RemoteTextTrackEls',
<add> getterName: 'remoteTextTrackEls',
<add> privateName: 'remoteTextTrackEls_'
<add> }
<add>};
<add>
<add>const ALL = mergeOptions(NORMAL, REMOTE);
<add>
<add>REMOTE.names = Object.keys(REMOTE);
<add>NORMAL.names = Object.keys(NORMAL);
<add>ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
<add>
<add>export {
<add> NORMAL,
<add> REMOTE,
<add> ALL
<add>};
<ide><path>src/js/tracks/video-track-list.js
<ide> class VideoTrackList extends TrackList {
<ide> * The VideoTrack to add to the list
<ide> *
<ide> * @fires TrackList#addtrack
<del> * @private
<ide> */
<del> addTrack_(track) {
<add> addTrack(track) {
<ide> if (track.selected) {
<ide> disableOthers(this, track);
<ide> }
<ide>
<del> super.addTrack_(track);
<add> super.addTrack(track);
<ide> // native tracks don't have this
<ide> if (!track.addEventListener) {
<ide> return;
<ide> class VideoTrackList extends TrackList {
<ide> this.trigger('change');
<ide> });
<ide> }
<del>
<del> /**
<del> * Add a {@link VideoTrack} to the `VideoTrackList`.
<del> *
<del> * @param {VideoTrack} track
<del> * The VideoTrack to add to the list
<del> *
<del> * @fires TrackList#addtrack
<del> */
<del> addTrack(track) {
<del> this.addTrack_(track);
<del> }
<del>
<del> /**
<del> * Remove a {@link VideoTrack} to the `VideoTrackList`.
<del> *
<del> * @param {VideoTrack} track
<del> * The VideoTrack to remove from the list.
<del> *
<del> * @fires TrackList#removetrack
<del> */
<del> removeTrack(track) {
<del> super.removeTrack_(track);
<del> }
<del>
<ide> }
<ide>
<ide> export default VideoTrackList;
<ide><path>test/unit/tech/tech.test.js
<ide> QUnit.test('dispose() should clear all tracks that are added after creation', fu
<ide> tech.addRemoteTextTrack({}, true);
<ide> tech.addRemoteTextTrack({}, true);
<ide>
<del> tech.audioTracks().addTrack_(new AudioTrack());
<del> tech.audioTracks().addTrack_(new AudioTrack());
<add> tech.audioTracks().addTrack(new AudioTrack());
<add> tech.audioTracks().addTrack(new AudioTrack());
<ide>
<del> tech.videoTracks().addTrack_(new VideoTrack());
<del> tech.videoTracks().addTrack_(new VideoTrack());
<add> tech.videoTracks().addTrack(new VideoTrack());
<add> tech.videoTracks().addTrack(new VideoTrack());
<ide>
<ide> assert.equal(tech.audioTracks().length, 2, 'should have two audio tracks at the start');
<ide> assert.equal(tech.videoTracks().length, 2, 'should have two video tracks at the start');
<ide> QUnit.test('should add the source handler interface to a tech', function(assert)
<ide> tech.addRemoteTextTrack({}, true);
<ide> tech.addRemoteTextTrack({}, true);
<ide>
<del> tech.audioTracks().addTrack_(new AudioTrack());
<del> tech.audioTracks().addTrack_(new AudioTrack());
<add> tech.audioTracks().addTrack(new AudioTrack());
<add> tech.audioTracks().addTrack(new AudioTrack());
<ide>
<del> tech.videoTracks().addTrack_(new VideoTrack());
<del> tech.videoTracks().addTrack_(new VideoTrack());
<add> tech.videoTracks().addTrack(new VideoTrack());
<add> tech.videoTracks().addTrack(new VideoTrack());
<ide>
<ide> assert.equal(tech.audioTracks().length, 2, 'should have two audio tracks at the start');
<ide> assert.equal(tech.videoTracks().length, 2, 'should have two video tracks at the start');
<ide> QUnit.test('setSource after previous setSource should dispose source handler onc
<ide> assert.equal(disposeCount, 2, 'did dispose for third setSource');
<ide>
<ide> });
<del>
<ide><path>test/unit/tracks/audio-track-list.test.js
<ide> QUnit.test('only one track is ever enabled', function(assert) {
<ide> assert.equal(track.enabled, true, 'track is enabled');
<ide> assert.equal(track2.enabled, false, 'track2 is disabled');
<ide>
<del> list.addTrack_(track3);
<add> list.addTrack(track3);
<ide> assert.equal(track.enabled, false, 'track is disabled');
<ide> assert.equal(track2.enabled, false, 'track2 is disabled');
<ide> assert.equal(track3.enabled, true, 'track3 is enabled');
<ide> QUnit.test('only one track is ever enabled', function(assert) {
<ide> assert.equal(track2.enabled, false, 'track2 is disabled');
<ide> assert.equal(track3.enabled, false, 'track3 is disabled');
<ide>
<del> list.addTrack_(track4);
<add> list.addTrack(track4);
<ide> assert.equal(track.enabled, true, 'track is enabled');
<ide> assert.equal(track2.enabled, false, 'track2 is disabled');
<ide> assert.equal(track3.enabled, false, 'track3 is disabled');
<ide> QUnit.test('trigger a change event per enabled change', function(assert) {
<ide> track.enabled = true;
<ide> assert.equal(change, 1, 'one change triggered');
<ide>
<del> list.addTrack_(track3);
<add> list.addTrack(track3);
<ide> assert.equal(change, 2, 'another change triggered by adding an enabled track');
<ide>
<ide> track.enabled = true;
<ide> QUnit.test('trigger a change event per enabled change', function(assert) {
<ide> track.enabled = false;
<ide> assert.equal(change, 4, 'another change trigger by changing enabled');
<ide>
<del> list.addTrack_(track4);
<add> list.addTrack(track4);
<ide> assert.equal(change, 4, 'no change triggered by adding a disabled track');
<ide>
<ide> });
<ide><path>test/unit/tracks/html-track-element.test.js
<ide> /* eslint-env qunit */
<ide> import HTMLTrackElement from '../../../src/js/tracks/html-track-element.js';
<add>import TextTrackList from '../../../src/js/tracks/text-track-list.js';
<ide>
<ide> const defaultTech = {
<del> textTracks() {},
<add> textTracks() {
<add> return new TextTrackList();
<add> },
<ide> on() {},
<ide> off() {},
<ide> currentTime() {}
<ide><path>test/unit/tracks/text-track-list-converter.test.js
<ide> if (Html5.supportsNativeTextTracks()) {
<ide>
<ide> const tt = new TextTrackList();
<ide>
<del> tt.addTrack_(nativeTrack.track);
<del> tt.addTrack_(emulatedTrack);
<add> tt.addTrack(nativeTrack.track);
<add> tt.addTrack(emulatedTrack);
<ide>
<ide> const tech = {
<ide> $$() {
<ide> if (Html5.supportsNativeTextTracks()) {
<ide>
<ide> const tt = new TextTrackList();
<ide>
<del> tt.addTrack_(nativeTrack.track);
<del> tt.addTrack_(emulatedTrack);
<add> tt.addTrack(nativeTrack.track);
<add> tt.addTrack(emulatedTrack);
<ide>
<ide> let addRemotes = 0;
<ide> const tech = {
<ide> QUnit.test('textTracksToJson produces good json output for emulated only', funct
<ide>
<ide> const tt = new TextTrackList();
<ide>
<del> tt.addTrack_(anotherTrack);
<del> tt.addTrack_(emulatedTrack);
<add> tt.addTrack(anotherTrack);
<add> tt.addTrack(emulatedTrack);
<ide>
<ide> const tech = {
<ide> $$() {
<ide> QUnit.test('jsonToTextTracks calls addRemoteTextTrack on the tech with emulated
<ide>
<ide> const tt = new TextTrackList();
<ide>
<del> tt.addTrack_(anotherTrack);
<del> tt.addTrack_(emulatedTrack);
<add> tt.addTrack(anotherTrack);
<add> tt.addTrack(emulatedTrack);
<ide>
<ide> let addRemotes = 0;
<ide> const tech = {
<ide><path>test/unit/tracks/text-track.test.js
<ide> import TextTrack from '../../../src/js/tracks/text-track.js';
<ide> import TestHelpers from '../test-helpers.js';
<ide> import proxyquireify from 'proxyquireify';
<ide> import sinon from 'sinon';
<add>import TextTrackList from '../../../src/js/tracks/text-track-list.js';
<ide>
<ide> const proxyquire = proxyquireify(require);
<ide> const defaultTech = {
<del> textTracks() {},
<add> textTracks() {
<add> return new TextTrackList();
<add> },
<ide> on() {},
<ide> off() {},
<ide> currentTime() {}
<ide><path>test/unit/tracks/text-tracks.test.js
<ide> QUnit.test('removes cuechange event when text track is hidden for emulated track
<ide> startTime: 2,
<ide> endTime: 5
<ide> });
<del> player.tech_.textTracks().addTrack_(tt);
<add> player.tech_.textTracks().addTrack(tt);
<ide>
<ide> let numTextTrackChanges = 0;
<ide>
<ide><path>test/unit/tracks/track-list.test.js
<ide> QUnit.test('can get tracks by int and string id', function(assert) {
<ide> QUnit.test('length is updated when new tracks are added or removed', function(assert) {
<ide> const trackList = new TrackList(this.tracks);
<ide>
<del> trackList.addTrack_(newTrack('100'));
<add> trackList.addTrack(newTrack('100'));
<ide> assert.equal(trackList.length,
<ide> this.tracks.length + 1,
<ide> 'the length is ' + (this.tracks.length + 1));
<del> trackList.addTrack_(newTrack('101'));
<add> trackList.addTrack(newTrack('101'));
<ide> assert.equal(trackList.length,
<ide> this.tracks.length + 2,
<ide> 'the length is ' + (this.tracks.length + 2));
<ide>
<del> trackList.removeTrack_(trackList.getTrackById('101'));
<add> trackList.removeTrack(trackList.getTrackById('101'));
<ide> assert.equal(trackList.length,
<ide> this.tracks.length + 1,
<ide> 'the length is ' + (this.tracks.length + 1));
<del> trackList.removeTrack_(trackList.getTrackById('100'));
<add> trackList.removeTrack(trackList.getTrackById('100'));
<ide> assert.equal(trackList.length,
<ide> this.tracks.length,
<ide> 'the length is ' + this.tracks.length);
<ide> QUnit.test('can access items by index', function(assert) {
<ide> QUnit.test('can access new items by index', function(assert) {
<ide> const trackList = new TrackList(this.tracks);
<ide>
<del> trackList.addTrack_(newTrack('100'));
<add> trackList.addTrack(newTrack('100'));
<ide> assert.equal(trackList[3].id, '100', 'id of item at index 3 is 100');
<ide>
<del> trackList.addTrack_(newTrack('101'));
<add> trackList.addTrack(newTrack('101'));
<ide> assert.equal(trackList[4].id, '101', 'id of item at index 4 is 101');
<ide> });
<ide>
<ide> QUnit.test('cannot access removed items by index', function(assert) {
<ide> const trackList = new TrackList(this.tracks);
<ide>
<del> trackList.addTrack_(newTrack('100'));
<del> trackList.addTrack_(newTrack('101'));
<add> trackList.addTrack(newTrack('100'));
<add> trackList.addTrack(newTrack('101'));
<ide> assert.equal(trackList[3].id, '100', 'id of item at index 3 is 100');
<ide> assert.equal(trackList[4].id, '101', 'id of item at index 4 is 101');
<ide>
<del> trackList.removeTrack_(trackList.getTrackById('101'));
<del> trackList.removeTrack_(trackList.getTrackById('100'));
<add> trackList.removeTrack(trackList.getTrackById('101'));
<add> trackList.removeTrack(trackList.getTrackById('100'));
<ide>
<ide> assert.ok(!trackList[3], 'nothing at index 3');
<ide> assert.ok(!trackList[4], 'nothing at index 4');
<ide> QUnit.test('cannot access removed items by index', function(assert) {
<ide> QUnit.test('new item available at old index', function(assert) {
<ide> const trackList = new TrackList(this.tracks);
<ide>
<del> trackList.addTrack_(newTrack('100'));
<add> trackList.addTrack(newTrack('100'));
<ide> assert.equal(trackList[3].id, '100', 'id of item at index 3 is 100');
<ide>
<del> trackList.removeTrack_(trackList.getTrackById('100'));
<add> trackList.removeTrack(trackList.getTrackById('100'));
<ide> assert.ok(!trackList[3], 'nothing at index 3');
<ide>
<del> trackList.addTrack_(newTrack('101'));
<add> trackList.addTrack(newTrack('101'));
<ide> assert.equal(trackList[3].id, '101', 'id of new item at index 3 is now 101');
<ide> });
<ide>
<ide> QUnit.test('a "addtrack" event is triggered when new tracks are added', function
<ide>
<ide> trackList.on('addtrack', addHandler);
<ide>
<del> trackList.addTrack_(newTrack('100'));
<del> trackList.addTrack_(newTrack('101'));
<add> trackList.addTrack(newTrack('100'));
<add> trackList.addTrack(newTrack('101'));
<ide>
<ide> trackList.off('addtrack', addHandler);
<ide> trackList.onaddtrack = addHandler;
<ide>
<del> trackList.addTrack_(newTrack('102'));
<del> trackList.addTrack_(newTrack('103'));
<add> trackList.addTrack(newTrack('102'));
<add> trackList.addTrack(newTrack('103'));
<ide>
<ide> assert.equal(adds, 4, 'we got ' + adds + ' "addtrack" events');
<ide> assert.equal(tracks, 4, 'we got a track with every event');
<ide> QUnit.test('a "removetrack" event is triggered when tracks are removed', functio
<ide> };
<ide>
<ide> trackList.on('removetrack', rmHandler);
<del> trackList.removeTrack_(trackList.getTrackById('1'));
<del> trackList.removeTrack_(trackList.getTrackById('2'));
<add> trackList.removeTrack(trackList.getTrackById('1'));
<add> trackList.removeTrack(trackList.getTrackById('2'));
<ide>
<ide> trackList.off('removetrack', rmHandler);
<ide> trackList.onremovetrack = rmHandler;
<del> trackList.removeTrack_(trackList.getTrackById('3'));
<add> trackList.removeTrack(trackList.getTrackById('3'));
<ide>
<ide> assert.equal(rms, 3, 'we got ' + rms + ' "removetrack" events');
<ide> assert.equal(tracks, 3, 'we got a track with every event');
<ide><path>test/unit/tracks/track.test.js
<ide> import TechFaker from '../tech/tech-faker';
<ide> import TrackBaseline from './track-baseline';
<ide> import Track from '../../../src/js/tracks/track.js';
<add>import TextTrackList from '../../../src/js/tracks/text-track-list.js';
<ide>
<ide> const defaultTech = {
<del> textTracks() {},
<add> textTracks() {
<add> return new TextTrackList();
<add> },
<ide> on() {},
<ide> off() {},
<ide> currentTime() {}
<ide><path>test/unit/tracks/video-track-list.test.js
<ide> QUnit.test('only one track is ever selected', function(assert) {
<ide> assert.equal(track.selected, true, 'track is selected');
<ide> assert.equal(track2.selected, false, 'track2 is unselected');
<ide>
<del> list.addTrack_(track3);
<add> list.addTrack(track3);
<ide> assert.equal(track.selected, false, 'track is unselected');
<ide> assert.equal(track2.selected, false, 'track2 is unselected');
<ide> assert.equal(track3.selected, true, 'track3 is selected');
<ide> QUnit.test('only one track is ever selected', function(assert) {
<ide> assert.equal(track2.selected, false, 'track2 is unselected');
<ide> assert.equal(track3.selected, false, 'track3 is unselected');
<ide>
<del> list.addTrack_(track4);
<add> list.addTrack(track4);
<ide> assert.equal(track.selected, true, 'track is selected');
<ide> assert.equal(track2.selected, false, 'track2 is unselected');
<ide> assert.equal(track3.selected, false, 'track3 is unselected');
<ide> QUnit.test('trigger a change event per selected change', function(assert) {
<ide> track.selected = true;
<ide> assert.equal(change, 1, 'one change triggered');
<ide>
<del> list.addTrack_(track3);
<add> list.addTrack(track3);
<ide> assert.equal(change, 2, 'another change triggered by adding an selected track');
<ide>
<ide> track.selected = true;
<ide> QUnit.test('trigger a change event per selected change', function(assert) {
<ide> track.selected = false;
<ide> assert.equal(change, 4, 'another change trigger by changing selected');
<ide>
<del> list.addTrack_(track4);
<add> list.addTrack(track4);
<ide> assert.equal(change, 4, 'no change triggered by adding a unselected track');
<ide> }); | 24 |
Python | Python | hide an log message in the glances cloud plugins | 635a652694b78a81c314029f68860bffa03458e6 | <ide><path>glances/plugins/glances_cloud.py
<ide> def msg_curse(self, args=None, max_width=None):
<ide> ret.append(self.curse_add_line(msg))
<ide>
<ide> # Return the message with decoration
<del> logger.info(ret)
<add> # logger.info(ret)
<ide> return ret
<ide>
<ide> | 1 |
Javascript | Javascript | fix documentation for adding view to containerview | 7a65598b71b66bf430d5f9937e8e1d80089ae449 | <ide><path>packages/ember-views/lib/views/container_view.js
<ide> var childViewsProperty = Ember.computed(function() {
<ide>
<ide> aContainer.get('childViews') // [aContainer.aView, aContainer.bView]
<ide> aContainer.get('childViews').pushObject(AnotherViewClass.create())
<del> aContainer.get('childViews') // [aContainer.aView, <AnotherViewClass instance>]
<add> aContainer.get('childViews') // [aContainer.aView, aContainer.bView, <AnotherViewClass instance>]
<ide>
<ide> Will result in the following HTML
<ide>
<ide> <div class="ember-view the-container">
<ide> <div class="ember-view">A</div>
<add> <div class="ember-view">B</div>
<ide> <div class="ember-view">Another view</div>
<ide> </div>
<ide> | 1 |
Javascript | Javascript | add callout style for a note | 60e80509a8f69a7fa750c3399b84bd0d4cc53855 | <ide><path>src/ng/directive/select.js
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
<ide> * option. See example below for demonstration.
<ide> *
<del> * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
<add> * <div class="alert alert-warning">
<add> * **Note:** `ngOptions` provides iterator facility for `<option>` element which should be used instead
<ide> * of {@link ng.directive:ngRepeat ngRepeat} when you want the
<ide> * `select` model to be bound to a non-string value. This is because an option element can only
<ide> * be bound to string values at present.
<add> * </div>
<ide> *
<ide> * @param {string} ngModel Assignable angular expression to data-bind to.
<ide> * @param {string=} name Property name of the form under which the control is published.
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide> // We now build up the list of options we need (we merge later)
<ide> for (index = 0; length = keys.length, index < length; index++) {
<del>
<add>
<ide> key = index;
<ide> if (keyName) {
<ide> key = keys[index]; | 1 |
Javascript | Javascript | improve transclusion documentation | 391d8c04da85347128bfd0a7d19f384d71f294e4 | <ide><path>src/ng/compile.js
<ide> * (because SVG doesn't work with custom elements in the DOM tree).
<ide> *
<ide> * #### `transclude`
<del> * compile the content of the element and make it available to the directive.
<del> * Typically used with {@link ng.directive:ngTransclude
<del> * ngTransclude}. The advantage of transclusion is that the linking function receives a
<del> * transclusion function which is pre-bound to the scope of the position in the DOM from where
<del> * it was taken.
<add> * Extract the contents of the element where the directive appears and make it available to the directive.
<add> * The contents are compiled and provided to the directive as a **transclusion function**. See the
<add> * {@link $compile#transclusion Transclusion} section below.
<ide> *
<del> * In a typical setup the widget creates an `isolate` scope, but the transcluded
<del> * content has its own **transclusion scope**. While the **transclusion scope** is owned as a child,
<del> * by the **isolate scope**, it prototypically inherits from the original scope from where the
<del> * transcluded content was taken.
<del> *
<del> * This makes it possible for the widget to have private state, and the transclusion to
<del> * be bound to the original (pre-`isolate`) scope.
<add> * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
<add> * directive's element or the entire element:
<ide> *
<ide> * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
<ide> * * `'element'` - transclude the whole of the directive's element including any directives on this
<ide> * element that defined at a lower priority than this directive.
<ide> *
<del> * <div class="alert alert-warning">
<del> * **Note:** When testing an element transclude directive you must not place the directive at the root of the
<del> * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
<del> * Testing Transclusion Directives}.
<del> * </div>
<ide> *
<ide> * #### `compile`
<ide> *
<ide> * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
<ide> * for their async templates to be resolved.
<ide> *
<add> *
<add> * ### Transclusion
<add> *
<add> * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
<add> * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
<add> * scope from where they were taken.
<add> *
<add> * Transclusion is used (often with {@link ngTransclude}) to insert the
<add> * original contents of a directive's element into a specified place in the template of the directive.
<add> * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
<add> * content has access to the properties on the scope from which it was taken, even if the directive
<add> * has isolated scope.
<add> * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
<add> *
<add> * This makes it possible for the widget to have private state for its template, while the transcluded
<add> * content has access to its originating scope.
<add> *
<add> * <div class="alert alert-warning">
<add> * **Note:** When testing an element transclude directive you must not place the directive at the root of the
<add> * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
<add> * Testing Transclusion Directives}.
<add> * </div>
<add> *
<add> * #### Transclusion Functions
<add> *
<add> * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
<add> * function** to the directive's `link` function and `controller`. This transclusion function is a special
<add> * **linking function** that will return the compiled contents linked to a new transclusion scope.
<add> *
<add> * <div class="alert alert-info">
<add> * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
<add> * ngTransclude will deal with it for us.
<add> * </div>
<add> *
<add> * If you want to manually control the insertion and removal of the transcluded content in your directive
<add> * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
<add> * object that contains the compiled DOM, which is linked to the correct transclusion scope.
<add> *
<add> * When you call a transclusion function you can pass in a **clone attach function**. This function is accepts
<add> * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
<add> * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
<add> *
<add> * <div class="alert alert-info">
<add> * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
<add> * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
<add> * </div>
<add> *
<add> * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
<add> * attach function**:
<add> *
<add> * ```js
<add> * var transcludedContent, transclusionScope;
<add> *
<add> * $transclude(function(clone, scope) {
<add> * element.append(clone);
<add> * transcludedContent = clone;
<add> * transclusionScope = scope;
<add> * });
<add> * ```
<add> *
<add> * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
<add> * associated transclusion scope:
<add> *
<add> * ```js
<add> * transcludedContent.remove();
<add> * transclusionScope.$destroy();
<add> * ```
<add> *
<add> * <div class="alert alert-info">
<add> * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
<add> * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
<add> * then you are also responsible for calling `$destroy` on the transclusion scope.
<add> * </div>
<add> *
<add> * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
<add> * automatically destroy their transluded clones as necessary so you do not need to worry about this if
<add> * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
<add> *
<add> *
<add> * #### Transclusion Scopes
<add> *
<add> * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
<add> * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
<add> * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
<add> * was taken.
<add> *
<add> * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
<add> * like this:
<add> *
<add> * ```html
<add> * <div ng-app>
<add> * <div isolate>
<add> * <div transclusion>
<add> * </div>
<add> * </div>
<add> * </div>
<add> * ```
<add> *
<add> * The `$parent` scope hierarchy will look like this:
<add> *
<add> * ```
<add> * - $rootScope
<add> * - isolate
<add> * - transclusion
<add> * ```
<add> *
<add> * but the scopes will inherit prototypically from different scopes to their `$parent`.
<add> *
<add> * ```
<add> * - $rootScope
<add> * - transclusion
<add> * - isolate
<add> * ```
<add> *
<add> *
<ide> * ### Attributes
<ide> *
<ide> * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the | 1 |
Javascript | Javascript | fix typo of turobmodule to turbomodule | fc1ddb6128bfd9bf875066f1d040f685e0563bc7 | <ide><path>packages/babel-plugin-codegen/index.js
<ide> module.exports = function({parse, types: t}) {
<ide> * call.
<ide> */
<ide>
<del> // Disabling TurobModule processing for react-native-web NPM module
<add> // Disabling TurboModule processing for react-native-web NPM module
<ide> // Workaround for T80868008, can remove after fixed
<ide> const enableTurboModuleJSCodegen =
<ide> this.filename.indexOf('/node_modules/react-native-web') === -1; | 1 |
Ruby | Ruby | fix typo in callback deprecation message | 3d79da5009cd70d23961ddb4c9902e611000cc6f | <ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def set_callback(name, *filter_list, &block)
<ide> ActiveSupport::Deprecation.warn(<<-MSG.squish)
<ide> Passing string to be evaluated in :if and :unless conditional
<ide> options is deprecated and will be removed in Rails 5.2 without
<del> replacement. Pass a symbol for an instance method, or a lamdba,
<add> replacement. Pass a symbol for an instance method, or a lambda,
<ide> proc or block, instead.
<ide> MSG
<ide> end | 1 |
Go | Go | fix logs with tty | 1f44fd8624d1de3f7e1e55880352faef2e141fb1 | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdLogs(args ...string) error {
<ide> return nil
<ide> }
<ide> name := cmd.Arg(0)
<add> body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> container := &Container{}
<add> err = json.Unmarshal(body, container)
<add> if err != nil {
<add> return err
<add> }
<ide>
<del> if err := cli.hijack("POST", "/containers/"+name+"/attach?logs=1&stdout=1&stderr=1", false, nil, cli.out, cli.err, nil); err != nil {
<add> if err := cli.hijack("POST", "/containers/"+name+"/attach?logs=1&stdout=1&stderr=1", container.Config.Tty, nil, cli.out, cli.err, nil); err != nil {
<ide> return err
<ide> }
<ide> return nil | 1 |
Ruby | Ruby | fix documentation from [ci skip] | 9f86780226c86fae30d59d04bd53449b8c7a1ad8 | <ide><path>activesupport/lib/active_support/core_ext/hash/keys.rb
<ide> def symbolize_keys!
<ide> end
<ide> alias_method :to_options!, :symbolize_keys!
<ide>
<del> # Ensures all the hash's keys are present in the supplied list of <tt>*valid_keys</tt>.
<del> # Raises an ArgumentError if any unexpected keys are encountered.
<del> # Note that keys are NOT treated indifferently: strings and symbols will not match each other.
<add> # Validate all keys in a hash match <tt>*valid_keys</tt>, raising
<add> # ArgumentError on a mismatch.
<add> #
<add> # Note that keys are treated differently than HashWithIndifferentAccess,
<add> # meaning that string and symbol keys will not match.
<ide> #
<ide> # { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
<ide> # { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'" | 1 |
Java | Java | remove bridge access from javatimermanager, again | 990c9ea5ec965dab06889d8ecdc93654d7d48746 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaScriptTimerManager.java
<add>package com.facebook.react.modules.core;
<add>
<add>import com.facebook.react.bridge.WritableArray;
<add>
<add>/** An interface used by {@link JavaTimerManager} to access and call JS timers from Java. */
<add>public interface JavaScriptTimerManager {
<add>
<add> /**
<add> * Calls the JS callback(s) associated with the timer ID(s). Also unregisters the callback if the
<add> * timer isn't recurring (e.g. unregisters for setTimeout, doesn't for setInterval).
<add> *
<add> * @param timerIDs An array of timer handles to call. Accepts an array as an optimization, to
<add> * avoid unnecessary JNI calls.
<add> */
<add> void callTimers(WritableArray timerIDs);
<add>
<add> /**
<add> * Invoke the JS callback registered with `requestIdleCallback`.
<add> *
<add> * @param frameTime The amount of time left in the frame, in ms.
<add> */
<add> void callIdleCallbacks(double frameTime);
<add>
<add> /**
<add> * Shows a warning message in development when environment times are out of sync.
<add> *
<add> * @param warningMessage The message to show
<add> */
<add> void emitTimeDriftWarning(String warningMessage);
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java
<ide> public void doFrame(long frameTimeNanos) {
<ide> }
<ide>
<ide> if (mTimersToCall != null) {
<del> mReactApplicationContext.getJSModule(JSTimers.class).callTimers(mTimersToCall);
<add> mJavaScriptTimerManager.callTimers(mTimersToCall);
<ide> mTimersToCall = null;
<ide> }
<ide>
<ide> public void run() {
<ide> }
<ide>
<ide> if (sendIdleEvents) {
<del> mReactApplicationContext
<del> .getJSModule(JSTimers.class)
<del> .callIdleCallbacks(absoluteFrameStartTime);
<add> mJavaScriptTimerManager.callIdleCallbacks(absoluteFrameStartTime);
<ide> }
<ide>
<ide> mCurrentIdleCallbackRunnable = null;
<ide> public void cancel() {
<ide> }
<ide>
<ide> private final ReactApplicationContext mReactApplicationContext;
<add> private final JavaScriptTimerManager mJavaScriptTimerManager;
<ide> private final ReactChoreographer mReactChoreographer;
<ide> private final DevSupportManager mDevSupportManager;
<ide> private final Object mTimerGuard = new Object();
<ide> public void cancel() {
<ide>
<ide> public JavaTimerManager(
<ide> ReactApplicationContext reactContext,
<add> JavaScriptTimerManager javaScriptTimerManager,
<ide> ReactChoreographer reactChoreographer,
<ide> DevSupportManager devSupportManager) {
<ide> mReactApplicationContext = reactContext;
<add> mJavaScriptTimerManager = javaScriptTimerManager;
<ide> mReactChoreographer = reactChoreographer;
<ide> mDevSupportManager = devSupportManager;
<ide>
<ide> public void createAndMaybeCallTimer(
<ide> if (mDevSupportManager.getDevSupportEnabled()) {
<ide> long driftTime = Math.abs(remoteTime - deviceTime);
<ide> if (driftTime > 60000) {
<del> mReactApplicationContext
<del> .getJSModule(JSTimers.class)
<del> .emitTimeDriftWarning(
<del> "Debugger and device times have drifted by more than 60s. Please correct this by "
<del> + "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine.");
<add> mJavaScriptTimerManager.emitTimeDriftWarning(
<add> "Debugger and device times have drifted by more than 60s. Please correct this by "
<add> + "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine.");
<ide> }
<ide> }
<ide>
<ide> public void createAndMaybeCallTimer(
<ide> if (duration == 0 && !repeat) {
<ide> WritableArray timerToCall = Arguments.createArray();
<ide> timerToCall.pushInt(callbackID);
<del> mReactApplicationContext.getJSModule(JSTimers.class).callTimers(timerToCall);
<add> mJavaScriptTimerManager.callTimers(timerToCall);
<ide> return;
<ide> }
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/core/TimingModule.java
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<ide> import com.facebook.react.bridge.ReactContextBaseJavaModule;
<ide> import com.facebook.react.bridge.ReactMethod;
<add>import com.facebook.react.bridge.WritableArray;
<ide> import com.facebook.react.devsupport.interfaces.DevSupportManager;
<ide> import com.facebook.react.jstasks.HeadlessJsTaskContext;
<ide> import com.facebook.react.jstasks.HeadlessJsTaskEventListener;
<ide> public final class TimingModule extends ReactContextBaseJavaModule
<ide> implements LifecycleEventListener, HeadlessJsTaskEventListener {
<ide>
<add> public class BridgeTimerManager implements JavaScriptTimerManager {
<add> @Override
<add> public void callTimers(WritableArray timerIDs) {
<add> getReactApplicationContext().getJSModule(JSTimers.class).callTimers(timerIDs);
<add> }
<add>
<add> @Override
<add> public void callIdleCallbacks(double frameTime) {
<add> getReactApplicationContext().getJSModule(JSTimers.class).callIdleCallbacks(frameTime);
<add> }
<add>
<add> @Override
<add> public void emitTimeDriftWarning(String warningMessage) {
<add> getReactApplicationContext().getJSModule(JSTimers.class).emitTimeDriftWarning(warningMessage);
<add> }
<add> }
<add>
<ide> public static final String NAME = "Timing";
<ide>
<ide> private final JavaTimerManager mJavaTimerManager;
<ide> public TimingModule(ReactApplicationContext reactContext, DevSupportManager devS
<ide> super(reactContext);
<ide>
<ide> mJavaTimerManager =
<del> new JavaTimerManager(reactContext, ReactChoreographer.getInstance(), devSupportManager);
<add> new JavaTimerManager(
<add> reactContext,
<add> new BridgeTimerManager(),
<add> ReactChoreographer.getInstance(),
<add> devSupportManager);
<ide> }
<ide>
<ide> @Override | 3 |
Python | Python | add python_requires to setup.py | fc7af715a2e410075afef5e61d554743576eac3f | <ide><path>setup.py
<ide> def run(self):
<ide> url='https://github.com/nicolargo/glances',
<ide> license='LGPLv3',
<ide> keywords="cli curses monitoring system",
<add> python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
<ide> install_requires=get_install_requires(),
<ide> extras_require={
<ide> 'action': ['pystache'], | 1 |
Python | Python | fix typos in comment | eb7fd89d8651d07f7122018d4b5258180958c388 | <ide><path>celery/buckets.py
<ide> def put(self, job):
<ide> put_nowait = put
<ide>
<ide> def _get(self):
<del> # If the first queue is always returning
<del> # results it would never come to pick up items from the other
<del> # queues. So we always iterate over all the queus and put any ready
<del> # items on a deque called "immediate".
<add> # If the first queue is always returning items, we would never
<add> # get to fetching items from the other queues.
<add> # So we always iterate over all the queus and put any ready
<add> # items on a queue called "immediate". This queue is always checked
<add> # for cached items first.
<ide> if self.immediate:
<ide> try:
<ide> return 0, self.immediate.get_nowait() | 1 |
Mixed | Python | add optimized shell sort | 45d3eabeb5f22624245095abdc044422bfe5eeea | <ide><path>DIRECTORY.md
<ide> * [Scoring Functions](machine_learning/scoring_functions.py)
<ide> * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py)
<ide> * [Similarity Search](machine_learning/similarity_search.py)
<del> * [Support Vector Machines](machine_learning/support_vector_machines.py)
<ide> * [Word Frequency Functions](machine_learning/word_frequency_functions.py)
<ide>
<ide> ## Maths
<ide> * [Recursive Quick Sort](sorts/recursive_quick_sort.py)
<ide> * [Selection Sort](sorts/selection_sort.py)
<ide> * [Shell Sort](sorts/shell_sort.py)
<add> * [Shrink Shell](sorts/shrink_shell.py)
<ide> * [Slowsort](sorts/slowsort.py)
<ide> * [Stooge Sort](sorts/stooge_sort.py)
<ide> * [Strand Sort](sorts/strand_sort.py)
<ide><path>sorts/shrink_shell_sort.py
<add>"""
<add>This function implements the shell sort algorithm
<add>which is slightly faster than its pure implementation.
<add>
<add>This shell sort is implemented using a gap, which
<add>shrinks by a certain factor each iteration. In this
<add>implementation, the gap is initially set to the
<add>length of the collection. The gap is then reduced by
<add>a certain factor (1.3) each iteration.
<add>
<add>For each iteration, the algorithm compares elements
<add>that are a certain number of positions apart
<add>(determined by the gap). If the element at the higher
<add>position is greater than the element at the lower
<add>position, the two elements are swapped. The process
<add>is repeated until the gap is equal to 1.
<add>
<add>The reason this is more efficient is that it reduces
<add>the number of comparisons that need to be made. By
<add>using a smaller gap, the list is sorted more quickly.
<add>"""
<add>
<add>
<add>def shell_sort(collection: list) -> list:
<add> """Implementation of shell sort algorithm in Python
<add> :param collection: Some mutable ordered collection with heterogeneous
<add> comparable items inside
<add> :return: the same collection ordered by ascending
<add>
<add> >>> shell_sort([3, 2, 1])
<add> [1, 2, 3]
<add> >>> shell_sort([])
<add> []
<add> >>> shell_sort([1])
<add> [1]
<add> """
<add>
<add> # Choose an initial gap value
<add> gap = len(collection)
<add>
<add> # Set the gap value to be decreased by a factor of 1.3
<add> # after each iteration
<add> shrink = 1.3
<add>
<add> # Continue sorting until the gap is 1
<add> while gap > 1:
<add>
<add> # Decrease the gap value
<add> gap = int(gap / shrink)
<add>
<add> # Sort the elements using insertion sort
<add> for i in range(gap, len(collection)):
<add> temp = collection[i]
<add> j = i
<add> while j >= gap and collection[j - gap] > temp:
<add> collection[j] = collection[j - gap]
<add> j -= gap
<add> collection[j] = temp
<add>
<add> return collection
<add>
<add>
<add>if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod() | 2 |
Javascript | Javascript | add tests for multicompiler | 5da3c99584be4d914003e77a0fde5ebccbf4a8e0 | <ide><path>lib/MultiCompiler.js
<ide> */
<ide> var Tapable = require("tapable");
<ide> var async = require("async");
<del>var Stats = require("./Stats");
<del>
<del>function MultiWatching(watchings) {
<del> this.watchings = watchings;
<del>}
<del>
<del>MultiWatching.prototype.invalidate = function() {
<del> this.watchings.forEach(function(watching) {
<del> watching.invalidate();
<del> });
<del>};
<del>
<del>MultiWatching.prototype.close = function(callback) {
<del> async.forEach(this.watchings, function(watching, callback) {
<del> watching.close(callback);
<del> }, callback);
<del>};
<add>var MultiWatching = require("./MultiWatching");
<add>var MultiStats = require("./MultiStats");
<ide>
<ide> function MultiCompiler(compilers) {
<ide> Tapable.call(this);
<ide> MultiCompiler.prototype.purgeInputFileSystem = function() {
<ide> compiler.inputFileSystem.purge();
<ide> });
<ide> };
<del>
<del>function MultiStats(stats) {
<del> this.stats = stats;
<del> this.hash = stats.map(function(stat) {
<del> return stat.hash;
<del> }).join("");
<del>}
<del>
<del>MultiStats.prototype.hasErrors = function() {
<del> return this.stats.map(function(stat) {
<del> return stat.hasErrors();
<del> }).reduce(function(a, b) {
<del> return a || b;
<del> }, false);
<del>};
<del>
<del>MultiStats.prototype.hasWarnings = function() {
<del> return this.stats.map(function(stat) {
<del> return stat.hasWarnings();
<del> }).reduce(function(a, b) {
<del> return a || b;
<del> }, false);
<del>};
<del>
<del>MultiStats.prototype.toJson = function(options, forToString) {
<del> var jsons = this.stats.map(function(stat) {
<del> var obj = stat.toJson(options, forToString);
<del> obj.name = stat.compilation && stat.compilation.name;
<del> return obj;
<del> });
<del> var obj = {
<del> errors: jsons.reduce(function(arr, j) {
<del> return arr.concat(j.errors.map(function(msg) {
<del> return "(" + j.name + ") " + msg;
<del> }));
<del> }, []),
<del> warnings: jsons.reduce(function(arr, j) {
<del> return arr.concat(j.warnings.map(function(msg) {
<del> return "(" + j.name + ") " + msg;
<del> }));
<del> }, [])
<del> };
<del> if(!options || options.version !== false)
<del> obj.version = require("../package.json").version;
<del> if(!options || options.hash !== false)
<del> obj.hash = this.hash;
<del> if(!options || options.children !== false)
<del> obj.children = jsons;
<del> return obj;
<del>};
<del>
<del>MultiStats.prototype.toString = Stats.prototype.toString;
<ide><path>lib/MultiStats.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>var Stats = require("./Stats");
<add>
<add>function MultiStats(stats) {
<add> this.stats = stats;
<add> this.hash = stats.map(function(stat) {
<add> return stat.hash;
<add> }).join("");
<add>}
<add>
<add>MultiStats.prototype.hasErrors = function() {
<add> return this.stats.map(function(stat) {
<add> return stat.hasErrors();
<add> }).reduce(function(a, b) {
<add> return a || b;
<add> }, false);
<add>};
<add>
<add>MultiStats.prototype.hasWarnings = function() {
<add> return this.stats.map(function(stat) {
<add> return stat.hasWarnings();
<add> }).reduce(function(a, b) {
<add> return a || b;
<add> }, false);
<add>};
<add>
<add>MultiStats.prototype.toJson = function(options, forToString) {
<add> var jsons = this.stats.map(function(stat) {
<add> var obj = stat.toJson(options, forToString);
<add> obj.name = stat.compilation && stat.compilation.name;
<add> return obj;
<add> });
<add> var obj = {
<add> errors: jsons.reduce(function(arr, j) {
<add> return arr.concat(j.errors.map(function(msg) {
<add> return "(" + j.name + ") " + msg;
<add> }));
<add> }, []),
<add> warnings: jsons.reduce(function(arr, j) {
<add> return arr.concat(j.warnings.map(function(msg) {
<add> return "(" + j.name + ") " + msg;
<add> }));
<add> }, [])
<add> };
<add> if(!options || options.version !== false)
<add> obj.version = require("../package.json").version;
<add> if(!options || options.hash !== false)
<add> obj.hash = this.hash;
<add> if(!options || options.children !== false)
<add> obj.children = jsons;
<add> return obj;
<add>};
<add>
<add>MultiStats.prototype.toString = Stats.prototype.toString;
<add>
<add>module.exports = MultiStats;
<ide><path>lib/MultiWatching.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>var async = require("async");
<add>
<add>function MultiWatching(watchings) {
<add> this.watchings = watchings;
<add>}
<add>
<add>MultiWatching.prototype.invalidate = function() {
<add> this.watchings.forEach(function(watching) {
<add> watching.invalidate();
<add> });
<add>};
<add>
<add>MultiWatching.prototype.close = function(callback) {
<add> async.forEach(this.watchings, function(watching, finishedCallback) {
<add> watching.close(finishedCallback);
<add> }, callback);
<add>};
<add>
<add>module.exports = MultiWatching;
<ide><path>test/MultiCompiler.test.js
<add>var should = require("should");
<add>var sinon = require("sinon");
<add>var MultiCompiler = require("../lib/MultiCompiler");
<add>
<add>function CompilerEnvironment() {
<add> var pluginEvents = [];
<add> var runCallbacks = [];
<add> var watchCallbacks = [];
<add>
<add> this.getCompilerStub = function() {
<add> return {
<add> plugin: function(name, handler) {
<add> pluginEvents.push({
<add> name,
<add> handler
<add> });
<add> },
<add> run: function(callback) {
<add> runCallbacks.push({
<add> callback
<add> });
<add> },
<add> watch: function(options, callback) {
<add> watchCallbacks.push({
<add> options,
<add> callback
<add> });
<add> return this.name;
<add> }
<add> };
<add> };
<add>
<add> this.getPluginEventBindings = function() {
<add> return pluginEvents;
<add> };
<add>
<add> this.getRunCallbacks = function() {
<add> return runCallbacks;
<add> };
<add>
<add> this.getWatchCallbacks = function() {
<add> return watchCallbacks;
<add> };
<add>};
<add>
<add>var createCompiler = function(overrides) {
<add> var compilerEnvironment = new CompilerEnvironment();
<add> return Object.assign({
<add> outputPath: "/"
<add> }, compilerEnvironment.getCompilerStub(), overrides);
<add>};
<add>
<add>var setupTwoCompilerEnvironment = function(env, compiler1Values, compiler2Values) {
<add> var compilerEnvironment1 = new CompilerEnvironment();
<add> var compilerEnvironment2 = new CompilerEnvironment();
<add> var compilers = [
<add> Object.assign({
<add> name: "compiler1"
<add> }, (compiler1Values || {}), compilerEnvironment1.getCompilerStub()),
<add> Object.assign({
<add> name: "compiler2"
<add> }, (compiler2Values || {}), compilerEnvironment2.getCompilerStub())
<add> ];
<add> env.myMultiCompiler = new MultiCompiler(compilers);
<add> env.compiler1EventBindings = compilerEnvironment1.getPluginEventBindings();
<add> env.compiler2EventBindings = compilerEnvironment2.getPluginEventBindings();
<add> env.compiler1WatchCallbacks = compilerEnvironment1.getWatchCallbacks();
<add> env.compiler2WatchCallbacks = compilerEnvironment2.getWatchCallbacks();
<add> env.compiler1RunCallbacks = compilerEnvironment1.getRunCallbacks();
<add> env.compiler2RunCallbacks = compilerEnvironment2.getRunCallbacks();
<add>};
<add>
<add>describe("MultiCompiler", function() {
<add> var env;
<add> beforeEach(function() {
<add> env = {};
<add> });
<add>
<add> describe("constructor", function() {
<add> describe("when provided an array of compilers", function() {
<add> beforeEach(function() {
<add> env.compilers = [createCompiler(), createCompiler()];
<add> env.myMultiCompiler = new MultiCompiler(env.compilers);
<add> });
<add>
<add> it("sets the compilers property to the array", function() {
<add> env.myMultiCompiler.compilers.should.be.exactly(env.compilers);
<add> });
<add> });
<add>
<add> describe("when provided a compiler mapping", function() {
<add> beforeEach(function() {
<add> var compilers = {
<add> compiler1: createCompiler(),
<add> compiler2: createCompiler()
<add> };
<add> env.myMultiCompiler = new MultiCompiler(compilers);
<add> });
<add>
<add> it("sets the compilers property to an array of compilers", function() {
<add> env.myMultiCompiler.compilers.should.deepEqual([
<add> Object.assign({
<add> name: "compiler1"
<add> }, createCompiler()),
<add> Object.assign({
<add> name: "compiler2"
<add> }, createCompiler())
<add> ]);
<add> });
<add> });
<add>
<add> describe("defined properties", function() {
<add> describe("outputFileSystem", function() {
<add> beforeEach(function() {
<add> env.compilers = [createCompiler(), createCompiler()];
<add> env.myMultiCompiler = new MultiCompiler(env.compilers);
<add> });
<add>
<add> it("throws an error when reading the value", function() {
<add> should(function() {
<add> env.myMultiCompiler.outputFileSystem
<add> }).throw("Cannot read outputFileSystem of a MultiCompiler");
<add> });
<add>
<add> it("updates all compilers when setting the value", function() {
<add> env.myMultiCompiler.outputFileSystem = "foo";
<add> env.compilers[0].outputFileSystem.should.be.exactly("foo");
<add> env.compilers[1].outputFileSystem.should.be.exactly("foo");
<add> });
<add> });
<add>
<add> describe("inputFileSystem", function() {
<add> beforeEach(function() {
<add> env.compilers = [createCompiler(), createCompiler()];
<add> env.myMultiCompiler = new MultiCompiler(env.compilers);
<add> });
<add>
<add> it("throws an error when reading the value", function() {
<add> should(function() {
<add> env.myMultiCompiler.inputFileSystem
<add> }).throw("Cannot read inputFileSystem of a MultiCompiler");
<add> });
<add>
<add> it("updates all compilers when setting the value", function() {
<add> env.myMultiCompiler.inputFileSystem = "foo";
<add> env.compilers[0].inputFileSystem.should.be.exactly("foo");
<add> env.compilers[1].inputFileSystem.should.be.exactly("foo");
<add> });
<add> });
<add>
<add> describe("outputPath", function() {
<add> describe("when common path cannot be found and output path is absolute", function() {
<add> beforeEach(function() {
<add> env.compilers = [
<add> createCompiler({
<add> outputPath: "/foo/bar"
<add> }),
<add> createCompiler({
<add> outputPath: "quux"
<add> })
<add> ];
<add> env.myMultiCompiler = new MultiCompiler(env.compilers);
<add> });
<add>
<add> it("returns the root path", function() {
<add> env.myMultiCompiler.outputPath.should.be.exactly("/");
<add> });
<add> });
<add>
<add> describe("when common path cannot be found and output path is relative", function() {
<add> beforeEach(function() {
<add> env.compilers = [
<add> createCompiler({
<add> outputPath: "foo/bar/baz"
<add> }),
<add> createCompiler({
<add> outputPath: "quux"
<add> })
<add> ];
<add> env.myMultiCompiler = new MultiCompiler(env.compilers);
<add> });
<add>
<add> it("returns the first segment of relative path", function() {
<add> env.myMultiCompiler.outputPath.should.be.exactly("foo");
<add> });
<add> });
<add>
<add> describe("when common path can be found and output path is absolute", function() {
<add> beforeEach(function() {
<add> env.compilers = [
<add> createCompiler({
<add> outputPath: "/foo"
<add> }),
<add> createCompiler({
<add> outputPath: "/foo/bar/baz"
<add> })
<add> ];
<add> env.myMultiCompiler = new MultiCompiler(env.compilers);
<add> });
<add>
<add> it("returns the shared path", function() {
<add> env.myMultiCompiler.outputPath.should.be.exactly("/foo");
<add> });
<add> });
<add>
<add> describe("when common path can be found and output path is relative", function() {
<add> beforeEach(function() {
<add> env.compilers = [
<add> createCompiler({
<add> outputPath: "foo"
<add> }),
<add> createCompiler({
<add> outputPath: "foo/bar/baz"
<add> })
<add> ];
<add> env.myMultiCompiler = new MultiCompiler(env.compilers);
<add> });
<add>
<add> it("returns the shared path", function() {
<add> env.myMultiCompiler.outputPath.should.be.exactly("foo");
<add> });
<add> });
<add> });
<add> });
<add>
<add> describe("compiler events", function() {
<add> beforeEach(function() {
<add> setupTwoCompilerEnvironment(env);
<add> });
<add>
<add> it("binds two event handler", function() {
<add> env.compiler1EventBindings.length.should.be.exactly(2);
<add> env.compiler2EventBindings.length.should.be.exactly(2);
<add> });
<add>
<add> describe("done handler", function() {
<add> beforeEach(function() {
<add> env.doneEventBinding1 = env.compiler1EventBindings[0];
<add> env.doneEventBinding2 = env.compiler2EventBindings[0];
<add> });
<add>
<add> it("binds to done event", function() {
<add> env.doneEventBinding1.name.should.be.exactly("done");
<add> });
<add>
<add> describe('when called for first compiler', function() {
<add> beforeEach(function() {
<add> env.mockDonePlugin = sinon.spy();
<add> env.myMultiCompiler.plugin('done', env.mockDonePlugin);
<add> env.doneEventBinding1.handler({
<add> hash: "foo"
<add> });
<add> });
<add>
<add> it("does not call the done plugin when not all compilers are finished", function() {
<add> env.mockDonePlugin.callCount.should.be.exactly(0);
<add> });
<add>
<add> describe('and called for second compiler', function() {
<add> beforeEach(function() {
<add> env.doneEventBinding2.handler({
<add> hash: "bar"
<add> });
<add> });
<add>
<add> it("calls the done plugin", function() {
<add> env.mockDonePlugin.callCount.should.be.exactly(1);
<add> });
<add> });
<add> });
<add> });
<add>
<add> describe("invalid handler", function() {
<add> beforeEach(function() {
<add> env.invalidEventBinding = env.compiler1EventBindings[1];
<add> });
<add>
<add> it("binds to invalid event", function() {
<add> env.invalidEventBinding.name.should.be.exactly("invalid");
<add> });
<add>
<add> describe('when called', function() {
<add> beforeEach(function() {
<add> env.mockInvalidPlugin = sinon.spy();
<add> env.myMultiCompiler.plugin('invalid', env.mockInvalidPlugin);
<add> env.invalidEventBinding.handler();
<add> });
<add>
<add> it("calls the invalid plugin", function() {
<add> env.mockInvalidPlugin.callCount.should.be.exactly(1);
<add> });
<add> });
<add> });
<add> });
<add> });
<add>
<add> describe("watch", function() {
<add> describe("without compiler dependencies", function() {
<add> beforeEach(function() {
<add> setupTwoCompilerEnvironment(env);
<add> env.callback = sinon.spy();
<add> env.options = {
<add> testWatchOptions: true
<add> };
<add> env.result = env.myMultiCompiler.watch(env.options, env.callback);
<add> });
<add>
<add> it("returns a multi-watching object", function() {
<add> var result = JSON.stringify(env.result);
<add> result.should.be.exactly('{"watchings":["compiler1","compiler2"]}');
<add> });
<add>
<add> it("calls watch on each compiler with original options", function() {
<add> env.compiler1WatchCallbacks.length.should.be.exactly(1);
<add> env.compiler1WatchCallbacks[0].options.should.be.exactly(env.options);
<add> env.compiler2WatchCallbacks.length.should.be.exactly(1);
<add> env.compiler2WatchCallbacks[0].options.should.be.exactly(env.options);
<add> });
<add>
<add> it("calls the callback when all compilers watch", function() {
<add> env.compiler1WatchCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> env.callback.callCount.should.be.exactly(0);
<add> env.compiler2WatchCallbacks[0].callback(null, {
<add> hash: 'bar'
<add> });
<add> env.callback.callCount.should.be.exactly(1);
<add> });
<add>
<add> describe("on first run", function() {
<add> describe("callback called with no compiler errors", function() {
<add> beforeEach(function() {
<add> env.compiler1WatchCallbacks[0].callback(new Error('Test error'));
<add> });
<add>
<add> it('has failure parameters', function() {
<add> env.callback.callCount.should.be.exactly(1);
<add> env.callback.getCall(0).args[0].should.be.Error();
<add> should(env.callback.getCall(0).args[1]).be.undefined();
<add> });
<add> });
<add>
<add> describe("callback called with no compiler errors", function() {
<add> beforeEach(function() {
<add> env.compiler1WatchCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> });
<add>
<add> it('does not call the callback', function() {
<add> env.callback.callCount.should.be.exactly(0);
<add> });
<add> });
<add> });
<add>
<add> describe("on subsequent runs", function() {
<add> describe("callback called with compiler errors", function() {
<add> beforeEach(function() {
<add> env.compiler1WatchCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> env.compiler2WatchCallbacks[0].callback(new Error('Test error'));
<add> });
<add>
<add> it('has failure parameters', function() {
<add> env.callback.callCount.should.be.exactly(1);
<add> env.callback.getCall(0).args[0].should.be.Error();
<add> should(env.callback.getCall(0).args[1]).be.undefined();
<add> });
<add> });
<add>
<add> describe("callback called with no compiler errors", function() {
<add> beforeEach(function() {
<add> env.compiler1WatchCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> env.compiler2WatchCallbacks[0].callback(null, {
<add> hash: 'bar'
<add> });
<add> });
<add>
<add> it('has success parameters', function() {
<add> env.callback.callCount.should.be.exactly(1);
<add> should(env.callback.getCall(0).args[0]).be.Null();
<add> var stats = JSON.stringify(env.callback.getCall(0).args[1]);
<add> stats.should.be.exactly('{"stats":[{"hash":"foo"},{"hash":"bar"}],"hash":"foobar"}');
<add> });
<add> });
<add> });
<add> });
<add>
<add> describe("with compiler dependencies", function() {
<add> beforeEach(function() {
<add> setupTwoCompilerEnvironment(env, {
<add> name: "compiler1",
<add> dependencies: ["compiler2"]
<add> }, {
<add> name: "compiler2"
<add> });
<add> env.callback = sinon.spy();
<add> env.options = {
<add> testWatchOptions: true
<add> };
<add> env.result = env.myMultiCompiler.watch(env.options, env.callback);
<add> });
<add>
<add> it("calls run on each compiler in dependency order", function() {
<add> env.compiler1WatchCallbacks.length.should.be.exactly(0);
<add> env.compiler2WatchCallbacks.length.should.be.exactly(1);
<add> env.compiler2WatchCallbacks[0].options.should.be.exactly(env.options);
<add> env.compiler2WatchCallbacks[0].callback(null, {
<add> hash: 'bar'
<add> });
<add> env.compiler1WatchCallbacks.length.should.be.exactly(1);
<add> env.compiler1WatchCallbacks[0].options.should.be.exactly(env.options);
<add> });
<add>
<add> it("calls the callback when all compilers run in dependency order", function() {
<add> env.compiler2WatchCallbacks[0].callback(null, {
<add> hash: 'bar'
<add> });
<add> env.callback.callCount.should.be.exactly(0);
<add> env.compiler1WatchCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> env.callback.callCount.should.be.exactly(1);
<add> });
<add> });
<add> });
<add>
<add> describe("run", function() {
<add> describe("without compiler dependencies", function() {
<add> beforeEach(function() {
<add> setupTwoCompilerEnvironment(env);
<add> env.callback = sinon.spy();
<add> env.myMultiCompiler.run(env.callback);
<add> });
<add>
<add> it("calls run on each compiler", function() {
<add> env.compiler1RunCallbacks.length.should.be.exactly(1);
<add> env.compiler2RunCallbacks.length.should.be.exactly(1);
<add> });
<add>
<add> it("calls the callback when all compilers run", function() {
<add> env.compiler1RunCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> env.callback.callCount.should.be.exactly(0);
<add> env.compiler2RunCallbacks[0].callback(null, {
<add> hash: 'bar'
<add> });
<add> env.callback.callCount.should.be.exactly(1);
<add> });
<add>
<add> describe("callback called with no compiler errors", function() {
<add> beforeEach(function() {
<add> env.compiler1RunCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> env.compiler2RunCallbacks[0].callback(null, {
<add> hash: 'bar'
<add> });
<add> });
<add>
<add> it('has success parameters', function() {
<add> env.callback.callCount.should.be.exactly(1);
<add> should(env.callback.getCall(0).args[0]).be.Null();
<add> var stats = JSON.stringify(env.callback.getCall(0).args[1]);
<add> stats.should.be.exactly('{"stats":[{"hash":"foo"},{"hash":"bar"}],"hash":"foobar"}');
<add> });
<add> });
<add>
<add> describe("callback called with compiler errors", function() {
<add> beforeEach(function() {
<add> env.compiler1RunCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> env.compiler2RunCallbacks[0].callback(new Error('Test error'));
<add> });
<add>
<add> it('has failure parameters', function() {
<add> env.callback.callCount.should.be.exactly(1);
<add> env.callback.getCall(0).args[0].should.be.Error();
<add> should(env.callback.getCall(0).args[1]).be.undefined();
<add> });
<add> });
<add> });
<add>
<add> describe("with compiler dependencies", function() {
<add> beforeEach(function() {
<add> setupTwoCompilerEnvironment(env, {
<add> name: "compiler1",
<add> dependencies: ["compiler2"]
<add> }, {
<add> name: "compiler2"
<add> });
<add> env.callback = sinon.spy();
<add> env.myMultiCompiler.run(env.callback);
<add> });
<add>
<add> it("calls run on each compiler in dependency order", function() {
<add> env.compiler1RunCallbacks.length.should.be.exactly(0);
<add> env.compiler2RunCallbacks.length.should.be.exactly(1);
<add> env.compiler2RunCallbacks[0].callback(null, {
<add> hash: 'bar'
<add> });
<add> env.compiler1RunCallbacks.length.should.be.exactly(1);
<add> });
<add>
<add> it("calls the callback when all compilers run in dependency order", function() {
<add> env.compiler2RunCallbacks[0].callback(null, {
<add> hash: 'bar'
<add> });
<add> env.callback.callCount.should.be.exactly(0);
<add> env.compiler1RunCallbacks[0].callback(null, {
<add> hash: 'foo'
<add> });
<add> env.callback.callCount.should.be.exactly(1);
<add> });
<add> });
<add> });
<add>
<add> describe("purgeInputFileSystem", function() {
<add> beforeEach(function() {
<add> env.compilers = [
<add> Object.assign({
<add> inputFileSystem: {
<add> purge: sinon.spy()
<add> }
<add> }, createCompiler()),
<add> createCompiler()
<add> ];
<add> env.myMultiCompiler = new MultiCompiler(env.compilers);
<add> env.myMultiCompiler.purgeInputFileSystem();
<add> });
<add>
<add> it("calls the compilers purge if available", function() {
<add> var purgeSpy = env.compilers[0].inputFileSystem.purge;
<add> purgeSpy.callCount.should.be.exactly(1);
<add> });
<add> });
<add>});
<ide><path>test/MultiStats.test.js
<add>var should = require("should");
<add>var sinon = require("sinon");
<add>var package = require("../package.json");
<add>var MultiStats = require("../lib/MultiStats");
<add>
<add>var createStat = function(overides) {
<add> return Object.assign({
<add> hash: "foo",
<add> compilation: {
<add> name: "bar"
<add> },
<add> hasErrors: () => false,
<add> hasWarnings: () => false,
<add> toJson: () => ({
<add> warnings: [],
<add> errors: []
<add> })
<add> }, overides);
<add>};
<add>
<add>describe("MultiStats", function() {
<add> var packageVersion, stats, myMultiStats, result;
<add>
<add> beforeEach(function() {
<add> packageVersion = package.version;
<add> package.version = "1.2.3";
<add> });
<add>
<add> afterEach(function() {
<add> package.version = packageVersion;
<add> });
<add>
<add> describe("created", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat({
<add> hash: "abc123"
<add> }),
<add> createStat({
<add> hash: "xyz890"
<add> })
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> });
<add>
<add> it("creates a hash string", function() {
<add> myMultiStats.hash.should.be.exactly("abc123xyz890");
<add> });
<add> });
<add>
<add> describe("hasErrors", function() {
<add> describe("when both have errors", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat({
<add> hasErrors: () => true
<add> }),
<add> createStat({
<add> hasErrors: () => true
<add> })
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> });
<add>
<add> it("returns true", function() {
<add> myMultiStats.hasErrors().should.be.exactly(true);
<add> });
<add> });
<add>
<add> describe("when one has an error", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat({
<add> hasErrors: () => true
<add> }),
<add> createStat()
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> });
<add>
<add> it("returns true", function() {
<add> myMultiStats.hasErrors().should.be.exactly(true);
<add> });
<add> });
<add>
<add> describe("when none have errors", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat(),
<add> createStat()
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> });
<add>
<add> it("returns false", function() {
<add> myMultiStats.hasErrors().should.be.exactly(false);
<add> });
<add> });
<add> });
<add>
<add> describe("hasWarnings", function() {
<add> describe("when both have warnings", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat({
<add> hasWarnings: () => true
<add> }),
<add> createStat({
<add> hasWarnings: () => true
<add> })
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> });
<add>
<add> it("returns true", function() {
<add> myMultiStats.hasWarnings().should.be.exactly(true);
<add> });
<add> });
<add>
<add> describe("when one has a warning", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat({
<add> hasWarnings: () => true
<add> }),
<add> createStat()
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> });
<add>
<add> it("returns true", function() {
<add> myMultiStats.hasWarnings().should.be.exactly(true);
<add> });
<add> });
<add>
<add> describe("when none have warnings", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat(),
<add> createStat()
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> });
<add>
<add> it("returns false", function() {
<add> myMultiStats.hasWarnings().should.be.exactly(false);
<add> });
<add> });
<add> });
<add>
<add> describe("toJson", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat({
<add> hash: "abc123",
<add> compilation: {
<add> name: "abc123-compilation"
<add> },
<add> toJson: () => ({
<add> warnings: ["abc123-warning"],
<add> errors: ["abc123-error"]
<add> })
<add> }),
<add> createStat({
<add> hash: "xyz890",
<add> compilation: {
<add> name: "xyz890-compilation"
<add> },
<add> toJson: () => ({
<add> warnings: ["xyz890-warning-1", "xyz890-warning-2"],
<add> errors: []
<add> })
<add> })
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> result = myMultiStats.toJson();
<add> });
<add>
<add> it("returns plain object representation", function() {
<add> result.should.deepEqual({
<add> hash: "abc123xyz890",
<add> version: "1.2.3",
<add> errors: [
<add> "(abc123-compilation) abc123-error"
<add> ],
<add> warnings: [
<add> "(abc123-compilation) abc123-warning",
<add> "(xyz890-compilation) xyz890-warning-1",
<add> "(xyz890-compilation) xyz890-warning-2"
<add> ],
<add> children: [{
<add> errors: [
<add> "abc123-error"
<add> ],
<add> name: "abc123-compilation",
<add> warnings: [
<add> "abc123-warning"
<add> ]
<add> },
<add> {
<add> errors: [],
<add> name: "xyz890-compilation",
<add> warnings: [
<add> "xyz890-warning-1",
<add> "xyz890-warning-2"
<add> ]
<add> }
<add> ]
<add> });
<add> });
<add> });
<add>
<add> describe("toString", function() {
<add> beforeEach(function() {
<add> stats = [
<add> createStat({
<add> hash: "abc123",
<add> compilation: {
<add> name: "abc123-compilation"
<add> }
<add> }),
<add> createStat({
<add> hash: "xyz890",
<add> compilation: {
<add> name: "xyz890-compilation"
<add> }
<add> })
<add> ];
<add> myMultiStats = new MultiStats(stats);
<add> result = myMultiStats.toString();
<add> });
<add>
<add> it("returns string representation", function() {
<add> result.should.be.exactly(
<add> "Hash: abc123xyz890\n" +
<add> "Version: webpack 1.2.3\n" +
<add> "Child abc123-compilation:\n" +
<add> " \n" +
<add> "Child xyz890-compilation:\n" +
<add> " "
<add> );
<add> });
<add> });
<add>});
<ide><path>test/MultiWatching.test.js
<add>var should = require("should");
<add>var sinon = require("sinon");
<add>var MultiWatching = require("../lib/MultiWatching");
<add>
<add>var createWatching = function() {
<add> return {
<add> invalidate: sinon.spy(),
<add> close: sinon.spy()
<add> };
<add>};
<add>
<add>describe("MultiWatching", function() {
<add> var watchings, myMultiWatching;
<add>
<add> beforeEach(function() {
<add> watchings = [createWatching(), createWatching()];
<add> myMultiWatching = new MultiWatching(watchings);
<add> });
<add>
<add> describe('invalidate', function() {
<add> beforeEach(function() {
<add> myMultiWatching.invalidate();
<add> });
<add>
<add> it('invalidates each watching', function() {
<add> watchings[0].invalidate.callCount.should.be.exactly(1);
<add> watchings[1].invalidate.callCount.should.be.exactly(1);
<add> });
<add> });
<add>
<add> describe('close', function() {
<add> var callback;
<add> var callClosedFinishedCallback = function(watching) {
<add> watching.close.getCall(0).args[0]();
<add> };
<add>
<add> beforeEach(function() {
<add> callback = sinon.spy();
<add> myMultiWatching.close(callback);
<add> });
<add>
<add> it('closes each watching', function() {
<add> watchings[0].close.callCount.should.be.exactly(1);
<add> watchings[1].close.callCount.should.be.exactly(1);
<add> });
<add>
<add> it('calls callback after each watching has closed', function() {
<add> callClosedFinishedCallback(watchings[0]);
<add> callClosedFinishedCallback(watchings[1]);
<add> callback.callCount.should.be.exactly(1);
<add> });
<add> });
<add>}); | 6 |
PHP | PHP | add test for saveall deep | 247f5522c60ea1bf9cd726a9e11e93685b177694 | <ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testSaveAllDeepHasManyBelongsTo() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * testSaveAllDeepHasManyhasMany method
<add> *
<add> * return @void
<add> */
<add> public function testSaveAllDeepHasManyHasMany() {
<add> $this->loadFixtures('Article', 'Comment', 'User', 'Attachment');
<add> $TestModel = new Article();
<add> $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array();
<add> $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment')), false);
<add> $TestModel->Comment->bindModel(array('hasMany' => array('Attachment')), false);
<add>
<add> $this->db->truncate($TestModel);
<add> $this->db->truncate(new Comment());
<add> $this->db->truncate(new Attachment());
<add>
<add> $result = $TestModel->saveAll(array(
<add> 'Article' => array('id' => 2, 'title' => 'I will not save'),
<add> 'Comment' => array(
<add> array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1),
<add> array(
<add> 'comment' => 'hasmany', 'published' => 'Y', 'user_id' => 5,
<add> 'Attachment' => array(
<add> array('attachment' => 'first deep attachment'),
<add> array('attachment' => 'second deep attachment'),
<add> )
<add> )
<add> )
<add> ), array('deep' => true));
<add>
<add> $result = $TestModel->Comment->find('first', array(
<add> 'conditions' => array('Comment.comment' => 'hasmany'),
<add> 'fields' => array('id', 'comment', 'published', 'user_id'),
<add> 'recursive' => -1
<add> ));
<add> $expected = array(
<add> 'Comment' => array(
<add> 'id' => 2,
<add> 'comment' => 'hasmany',
<add> 'published' => 'Y',
<add> 'user_id' => 5
<add> )
<add> );
<add> $this->assertEquals($expected, $result);
<add>
<add> $result = $TestModel->Comment->Attachment->find('all', array(
<add> 'fields' => array('attachment', 'comment_id'),
<add> 'order' => array('Attachment.id' => 'ASC')
<add> ));
<add> $expected = array(
<add> array('Attachment' => array('attachment' => 'first deep attachment', 'comment_id' => 2)),
<add> array('Attachment' => array('attachment' => 'second deep attachment', 'comment_id' => 2)),
<add> );
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<ide> /**
<ide> * testUpdateAllBoolean
<ide> * | 1 |
Python | Python | allow boolean subtract in histogram | e4e897fa1740ee4efaa276457debda9b8707b457 | <ide><path>numpy/lib/histograms.py
<ide> def _hist_bin_auto(x):
<ide> def _ravel_and_check_weights(a, weights):
<ide> """ Check a and weights have matching shapes, and ravel both """
<ide> a = np.asarray(a)
<add>
<add> # Ensure that the array is a "subtractable" dtype
<add> if a.dtype == np.bool_:
<add> warnings.warn("Converting input from {} to {} for compatibility."
<add> .format(a.dtype, np.uint8),
<add> RuntimeWarning, stacklevel=2)
<add> a = a.astype(np.uint8)
<add>
<ide> if weights is not None:
<ide> weights = np.asarray(weights)
<ide> if weights.shape != a.shape:
<ide><path>numpy/lib/tests/test_histograms.py
<ide> def test_f32_rounding(self):
<ide> counts_hist, xedges, yedges = np.histogram2d(x, y, bins=100)
<ide> assert_equal(counts_hist.sum(), 3.)
<ide>
<add> def test_bool_conversion(self):
<add> # gh-12107
<add> # Reference integer histogram
<add> a = np.array([1, 1, 0], dtype=np.uint8)
<add> int_hist, int_edges = np.histogram(a)
<add>
<add> # Should raise an warning on booleans
<add> # Ensure that the histograms are equivalent, need to suppress
<add> # the warnings to get the actual outputs
<add> with suppress_warnings() as sup:
<add> rec = sup.record(RuntimeWarning, 'Converting input from .*')
<add> hist, edges = np.histogram([True, True, False])
<add> # A warning should be issued
<add> assert_equal(len(rec), 1)
<add> assert_array_equal(hist, int_hist)
<add> assert_array_equal(edges, int_edges)
<add>
<ide> def test_weights(self):
<ide> v = np.random.rand(100)
<ide> w = np.ones(100) * 5 | 2 |
Ruby | Ruby | resolve formulae in `brew cleanup` | 769d89deaddfa95bf9ea4a9ef977c8c68101a6e3 | <ide><path>Library/Homebrew/cleanup.rb
<ide> def clean!
<ide> else
<ide> args.each do |arg|
<ide> formula = begin
<del> Formula[arg]
<add> Formulary.resolve(arg)
<ide> rescue FormulaUnavailableError, TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError
<ide> nil
<ide> end
<ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def formulae
<ide> def resolved_formulae
<ide> require "formula"
<ide> @resolved_formulae ||= (downcased_unique_named - casks).map do |name|
<del> if name.include?("/") || File.exist?(name)
<del> f = Formulary.factory(name, spec)
<del> if f.any_version_installed?
<del> tab = Tab.for_formula(f)
<del> resolved_spec = spec(nil) || tab.spec
<del> f.active_spec = resolved_spec if f.send(resolved_spec)
<del> f.build = tab
<del> if f.head? && tab.tabfile
<del> k = Keg.new(tab.tabfile.parent)
<del> f.version.update_commit(k.version.version.commit) if k.version.head?
<del> end
<del> end
<del> else
<del> rack = Formulary.to_rack(name)
<del> alias_path = Formulary.factory(name).alias_path
<del> f = Formulary.from_rack(rack, spec(nil), alias_path: alias_path)
<del> end
<del>
<del> # If this formula was installed with an alias that has since changed,
<del> # then it was specified explicitly in ARGV. (Using the alias would
<del> # instead have found the new formula.)
<del> #
<del> # Because of this, the user is referring to this specific formula,
<del> # not any formula targetted by the same alias, so in this context
<del> # the formula shouldn't be considered outdated if the alias used to
<del> # install it has changed.
<del> f.follow_installed_alias = false
<del>
<del> f
<add> Formulary.resolve(name, spec: spec(nil))
<ide> end.uniq(&:name)
<ide> end
<ide>
<ide><path>Library/Homebrew/formulary.rb
<ide> def self.load_formula_from_path(name, path)
<ide> cache[path] = klass
<ide> end
<ide>
<add> def self.resolve(name, spec: nil)
<add> if name.include?("/") || File.exist?(name)
<add> f = factory(name, *spec)
<add> if f.any_version_installed?
<add> tab = Tab.for_formula(f)
<add> resolved_spec = spec || tab.spec
<add> f.active_spec = resolved_spec if f.send(resolved_spec)
<add> f.build = tab
<add> if f.head? && tab.tabfile
<add> k = Keg.new(tab.tabfile.parent)
<add> f.version.update_commit(k.version.version.commit) if k.version.head?
<add> end
<add> end
<add> else
<add> rack = to_rack(name)
<add> alias_path = factory(name).alias_path
<add> f = from_rack(rack, *spec, alias_path: alias_path)
<add> end
<add>
<add> # If this formula was installed with an alias that has since changed,
<add> # then it was specified explicitly in ARGV. (Using the alias would
<add> # instead have found the new formula.)
<add> #
<add> # Because of this, the user is referring to this specific formula,
<add> # not any formula targetted by the same alias, so in this context
<add> # the formula shouldn't be considered outdated if the alias used to
<add> # install it has changed.
<add> f.follow_installed_alias = false
<add>
<add> f
<add> end
<add>
<ide> def self.ensure_utf8_encoding(io)
<ide> io.set_encoding(Encoding::UTF_8)
<ide> end | 3 |
Ruby | Ruby | fix another false assertions | f8e26c8014ea57874b6d7580d95b1df555f0ad03 | <ide><path>activesupport/test/core_ext/duration_test.rb
<ide> def test_fractional_days
<ide>
<ide> def test_since_and_ago
<ide> t = Time.local(2000)
<del> assert t + 1, 1.second.since(t)
<del> assert t - 1, 1.second.ago(t)
<add> assert_equal t + 1, 1.second.since(t)
<add> assert_equal t - 1, 1.second.ago(t)
<ide> end
<ide>
<ide> def test_since_and_ago_without_argument
<ide><path>railties/test/application/configuration_test.rb
<ide> def change
<ide>
<ide> test "application is always added to eager_load namespaces" do
<ide> require "#{app_path}/config/application"
<del> assert Rails.application, Rails.application.config.eager_load_namespaces
<add> assert_includes Rails.application.config.eager_load_namespaces, AppTemplate::Application
<ide> end
<ide>
<ide> test "the application can be eager loaded even when there are no frameworks" do | 2 |
Go | Go | add dynamic veth name | 5428964400ece4cd79cc5d482307df5e8913469f | <ide><path>pkg/libcontainer/network/veth.go
<del>package network
<del>
<del>import (
<del> "fmt"
<del> "github.com/dotcloud/docker/pkg/libcontainer"
<del>)
<del>
<del>// SetupVeth sets up an existing network namespace with the specified
<del>// network configuration.
<del>func SetupVeth(config *libcontainer.Network, tempVethName string) error {
<del> if err := InterfaceDown(tempVethName); err != nil {
<del> return fmt.Errorf("interface down %s %s", tempVethName, err)
<del> }
<del> if err := ChangeInterfaceName(tempVethName, "eth0"); err != nil {
<del> return fmt.Errorf("change %s to eth0 %s", tempVethName, err)
<del> }
<del> if err := SetInterfaceIp("eth0", config.IP); err != nil {
<del> return fmt.Errorf("set eth0 ip %s", err)
<del> }
<del>
<del> if err := SetMtu("eth0", config.Mtu); err != nil {
<del> return fmt.Errorf("set eth0 mtu to %d %s", config.Mtu, err)
<del> }
<del> if err := InterfaceUp("eth0"); err != nil {
<del> return fmt.Errorf("eth0 up %s", err)
<del> }
<del>
<del> if err := SetMtu("lo", config.Mtu); err != nil {
<del> return fmt.Errorf("set lo mtu to %d %s", config.Mtu, err)
<del> }
<del> if err := InterfaceUp("lo"); err != nil {
<del> return fmt.Errorf("lo up %s", err)
<del> }
<del>
<del> if config.Gateway != "" {
<del> if err := SetDefaultGateway(config.Gateway); err != nil {
<del> return fmt.Errorf("set gateway to %s %s", config.Gateway, err)
<del> }
<del> }
<del> return nil
<del>}
<ide><path>pkg/libcontainer/nsinit/exec.go
<ide> import (
<ide> "fmt"
<ide> "github.com/dotcloud/docker/pkg/libcontainer"
<ide> "github.com/dotcloud/docker/pkg/libcontainer/network"
<add> "github.com/dotcloud/docker/pkg/libcontainer/utils"
<ide> "github.com/dotcloud/docker/pkg/system"
<ide> "github.com/dotcloud/docker/pkg/term"
<ide> "io"
<ide> func createMasterAndConsole() (*os.File, string, error) {
<ide> }
<ide>
<ide> func createVethPair() (name1 string, name2 string, err error) {
<del> name1, name2 = "veth001", "veth002"
<add> name1, err = utils.GenerateRandomName("dock", 4)
<add> if err != nil {
<add> return
<add> }
<add> name2, err = utils.GenerateRandomName("dock", 4)
<add> if err != nil {
<add> return
<add> }
<ide> if err = network.CreateVethPair(name1, name2); err != nil {
<ide> return
<ide> }
<ide><path>pkg/libcontainer/nsinit/init.go
<ide> func main() {
<ide> log.Fatal(err)
<ide> }
<ide>
<del> data, err := ioutil.ReadAll(os.Stdin)
<del> if err != nil {
<del> log.Fatalf("error reading from stdin %s", err)
<add> var tempVethName string
<add> if container.Network != nil {
<add> data, err := ioutil.ReadAll(os.Stdin)
<add> if err != nil {
<add> log.Fatalf("error reading from stdin %s", err)
<add> }
<add> tempVethName = string(data)
<ide> }
<del> tempVethName := string(data)
<ide>
<ide> // close pipes so that we can replace it with the pty
<ide> os.Stdin.Close()
<ide> func main() {
<ide> if err := dupSlave(slave); err != nil {
<ide> log.Fatalf("dup2 slave %s", err)
<ide> }
<del>
<ide> if _, err := system.Setsid(); err != nil {
<ide> log.Fatalf("setsid %s", err)
<ide> }
<ide> func main() {
<ide> if err := system.ParentDeathSignal(); err != nil {
<ide> log.Fatalf("parent deth signal %s", err)
<ide> }
<del>
<ide> if err := setupNewMountNamespace(rootfs, console, container.ReadonlyFs); err != nil {
<ide> log.Fatalf("setup mount namespace %s", err)
<ide> }
<del>
<ide> if container.Network != nil {
<del> if err := setupNetworking(container, tempVethName); err != nil {
<add> if err := setupNetworking(container.Network, tempVethName); err != nil {
<ide> log.Fatalf("setup networking %s", err)
<ide> }
<ide> }
<ide> func setLogFile(container *libcontainer.Container) error {
<ide> return nil
<ide> }
<ide>
<del>func setupNetworking(container *libcontainer.Container, tempVethName string) error {
<del> return network.SetupVeth(container.Network, tempVethName)
<add>func setupNetworking(config *libcontainer.Network, tempVethName string) error {
<add> if err := network.InterfaceDown(tempVethName); err != nil {
<add> return fmt.Errorf("interface down %s %s", tempVethName, err)
<add> }
<add> if err := network.ChangeInterfaceName(tempVethName, "eth0"); err != nil {
<add> return fmt.Errorf("change %s to eth0 %s", tempVethName, err)
<add> }
<add> if err := network.SetInterfaceIp("eth0", config.IP); err != nil {
<add> return fmt.Errorf("set eth0 ip %s", err)
<add> }
<add> if err := network.SetMtu("eth0", config.Mtu); err != nil {
<add> return fmt.Errorf("set eth0 mtu to %d %s", config.Mtu, err)
<add> }
<add> if err := network.InterfaceUp("eth0"); err != nil {
<add> return fmt.Errorf("eth0 up %s", err)
<add> }
<add> if err := network.SetMtu("lo", config.Mtu); err != nil {
<add> return fmt.Errorf("set lo mtu to %d %s", config.Mtu, err)
<add> }
<add> if err := network.InterfaceUp("lo"); err != nil {
<add> return fmt.Errorf("lo up %s", err)
<add> }
<add> if config.Gateway != "" {
<add> if err := network.SetDefaultGateway(config.Gateway); err != nil {
<add> return fmt.Errorf("set gateway to %s %s", config.Gateway, err)
<add> }
<add> }
<add> return nil
<ide> }
<ide><path>pkg/libcontainer/utils/utils.go
<ide> import (
<ide> "crypto/rand"
<ide> "encoding/hex"
<ide> "io"
<del> "os"
<del> "syscall"
<ide> )
<ide>
<del>func WaitOnPid(pid int) (exitcode int, err error) {
<del> child, err := os.FindProcess(pid)
<del> if err != nil {
<del> return -1, err
<del> }
<del> state, err := child.Wait()
<del> if err != nil {
<del> return -1, err
<del> }
<del> return getExitCode(state), nil
<del>}
<del>
<del>func getExitCode(state *os.ProcessState) int {
<del> return state.Sys().(syscall.WaitStatus).ExitStatus()
<del>}
<del>
<del>func GenerateRandomName(size int) (string, error) {
<del> id := make([]byte, size)
<add>func GenerateRandomName(prefix string, size int) (string, error) {
<add> id := make([]byte, 32)
<ide> if _, err := io.ReadFull(rand.Reader, id); err != nil {
<ide> return "", err
<ide> }
<del> return hex.EncodeToString(id), nil
<add> return prefix + hex.EncodeToString(id)[:size], nil
<ide> } | 4 |
Ruby | Ruby | add a test for the rc commandline option | 2f11668eb844f6d7d64eaf4b4856d8a8b41e3a0c | <ide><path>railties/test/generators/argv_scrubber_test.rb
<ide> def test_new_homedir_rc
<ide> file.unlink
<ide> end
<ide>
<add> def test_new_rc_option
<add> file = Tempfile.new 'myrcfile'
<add> file.puts '--hello-world'
<add> file.flush
<add>
<add> message = nil
<add> scrubber = Class.new(ARGVScrubber) {
<add> define_method(:puts) { |msg| message = msg }
<add> }.new ['new', "--rc=#{file.path}"]
<add> args = scrubber.prepare!
<add> assert_equal [nil, '--hello-world'], args
<add> assert_match 'hello-world', message
<add> assert_match file.path, message
<add> ensure
<add> file.close
<add> file.unlink
<add> end
<add>
<ide> def test_no_rc
<ide> scrubber = ARGVScrubber.new ['new', '--no-rc']
<ide> args = scrubber.prepare! | 1 |
Python | Python | fix mypy errors for google.cloud_build | d4c4f9e09ee8b0453ff8503c30274eeaa80e7fde | <ide><path>airflow/providers/google/cloud/hooks/cloud_build.py
<ide> def cancel_build(
<ide> project_id: str = PROVIDE_PROJECT_ID,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> Build:
<ide> """
<ide> Cancels a build in progress.
<ide> def cancel_build(
<ide> self.log.info("Start cancelling build: %s.", id_)
<ide>
<ide> build = client.cancel_build(
<del> request={'project_id': project_id, 'id': id_}, retry=retry, timeout=timeout, metadata=metadata
<add> request={'project_id': project_id, 'id': id_},
<add> retry=retry,
<add> timeout=timeout,
<add> metadata=metadata,
<ide> )
<del>
<ide> self.log.info("Build has been cancelled: %s.", id_)
<ide>
<ide> return build
<ide> def create_build(
<ide> wait: bool = True,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> Build:
<ide> """
<ide> Starts a build with the specified configuration.
<ide> def create_build_trigger(
<ide> project_id: str = PROVIDE_PROJECT_ID,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> BuildTrigger:
<ide> """
<ide> Creates a new BuildTrigger.
<ide> def delete_build_trigger(
<ide> project_id: str = PROVIDE_PROJECT_ID,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> None:
<ide> """
<ide> Deletes a BuildTrigger by its project ID and trigger ID.
<ide> def get_build(
<ide> project_id: str = PROVIDE_PROJECT_ID,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> Build:
<ide> """
<ide> Returns information about a previously requested build.
<ide> def get_build(
<ide> self.log.info("Start retrieving build: %s.", id_)
<ide>
<ide> build = client.get_build(
<del> request={'project_id': project_id, 'id': id_}, retry=retry, timeout=timeout, metadata=metadata
<add> request={'project_id': project_id, 'id': id_},
<add> retry=retry,
<add> timeout=timeout,
<add> metadata=metadata,
<ide> )
<ide>
<ide> self.log.info("Build has been retrieved: %s.", id_)
<ide> def get_build_trigger(
<ide> project_id: str = PROVIDE_PROJECT_ID,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> BuildTrigger:
<ide> """
<ide> Returns information about a BuildTrigger.
<ide> def list_build_triggers(
<ide> page_token: Optional[str] = None,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> List[BuildTrigger]:
<ide> """
<ide> Lists existing BuildTriggers.
<ide> def list_builds(
<ide> filter_: Optional[str] = None,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> List[Build]:
<ide> """
<ide> Lists previously requested builds.
<ide> def retry_build(
<ide> wait: bool = True,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> Build:
<ide> """
<ide> Creates a new build based on the specified build. This method creates a new build
<ide> def retry_build(
<ide> self.log.info("Start retrying build: %s.", id_)
<ide>
<ide> operation = client.retry_build(
<del> request={'project_id': project_id, 'id': id_}, retry=retry, timeout=timeout, metadata=metadata
<add> request={'project_id': project_id, 'id': id_},
<add> retry=retry,
<add> timeout=timeout,
<add> metadata=metadata,
<ide> )
<ide>
<ide> id_ = self._get_build_id_from_operation(Operation)
<ide> def run_build_trigger(
<ide> wait: bool = True,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> Build:
<ide> """
<ide> Runs a BuildTrigger at a particular source revision.
<ide> def update_build_trigger(
<ide> project_id: str,
<ide> retry: Optional[Retry] = None,
<ide> timeout: Optional[float] = None,
<del> metadata: Optional[Sequence[Tuple[str, str]]] = None,
<add> metadata: Sequence[Tuple[str, str]] = (),
<ide> ) -> BuildTrigger:
<ide> """
<ide> Updates a BuildTrigger by its project ID and trigger ID.
<ide><path>airflow/providers/google/cloud/operators/cloud_build.py
<ide> class BuildProcessor:
<ide> """
<ide>
<ide> def __init__(self, build: Union[Dict, Build]) -> None:
<del> if isinstance(build, Build):
<del> self.build = Build(build)
<ide> self.build = deepcopy(build)
<ide>
<ide> def _verify_source(self) -> None:
<ide> def _convert_storage_url_to_dict(storage_url: str) -> Dict[str, Any]:
<ide> "gs://bucket-name/object-name.tar.gz#24565443"
<ide> )
<ide>
<del> source_dict = {
<add> source_dict: Dict[str, Any] = {
<ide> "bucket": url_parts.hostname,
<ide> "object_": url_parts.path[1:],
<ide> }
<ide><path>tests/providers/google/cloud/hooks/test_cloud_build.py
<ide> def test_cancel_build(self, get_conn):
<ide> self.hook.cancel_build(id_=BUILD_ID, project_id=PROJECT_ID)
<ide>
<ide> get_conn.return_value.cancel_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._get_build_id_from_operation")
<ide> def test_create_build_with_wait(self, get_conn, wait_time, mock_get_id_from_oper
<ide> self.hook.create_build(build=BUILD, project_id=PROJECT_ID)
<ide>
<ide> get_conn.return_value.create_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'build': BUILD}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'build': BUILD}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> get_conn.return_value.create_build.return_value.result.assert_called_once_with()
<ide>
<ide> get_conn.return_value.get_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._get_build_id_from_operation")
<ide> def test_create_build_without_wait(self, get_conn, mock_get_id_from_operation):
<ide> self.hook.create_build(build=BUILD, project_id=PROJECT_ID, wait=False)
<ide>
<ide> get_conn.return_value.create_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'build': BUILD}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'build': BUILD}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> get_conn.return_value.get_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn")
<ide> def test_create_build_trigger(self, get_conn):
<ide> request={'project_id': PROJECT_ID, 'trigger': BUILD_TRIGGER},
<ide> retry=None,
<ide> timeout=None,
<del> metadata=None,
<add> metadata=(),
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn")
<ide> def test_delete_build_trigger(self, get_conn):
<ide> request={'project_id': PROJECT_ID, 'trigger_id': TRIGGER_ID},
<ide> retry=None,
<ide> timeout=None,
<del> metadata=None,
<add> metadata=(),
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn")
<ide> def test_get_build(self, get_conn):
<ide> self.hook.get_build(id_=BUILD_ID, project_id=PROJECT_ID)
<ide>
<ide> get_conn.return_value.get_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn")
<ide> def test_get_build_trigger(self, get_conn):
<ide> request={'project_id': PROJECT_ID, 'trigger_id': TRIGGER_ID},
<ide> retry=None,
<ide> timeout=None,
<del> metadata=None,
<add> metadata=(),
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn")
<ide> def test_list_build_triggers(self, get_conn):
<ide> request={'parent': PARENT, 'project_id': PROJECT_ID, 'page_size': None, 'page_token': None},
<ide> retry=None,
<ide> timeout=None,
<del> metadata=None,
<add> metadata=(),
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn")
<ide> def test_list_builds(self, get_conn):
<ide> },
<ide> retry=None,
<ide> timeout=None,
<del> metadata=None,
<add> metadata=(),
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._get_build_id_from_operation")
<ide> def test_retry_build_with_wait(self, get_conn, wait_time, mock_get_id_from_opera
<ide> self.hook.retry_build(id_=BUILD_ID, project_id=PROJECT_ID)
<ide>
<ide> get_conn.return_value.retry_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> get_conn.return_value.retry_build.return_value.result.assert_called_once_with()
<ide>
<ide> get_conn.return_value.get_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._get_build_id_from_operation")
<ide> def test_retry_build_without_wait(self, get_conn, mock_get_id_from_operation):
<ide> self.hook.retry_build(id_=BUILD_ID, project_id=PROJECT_ID, wait=False)
<ide>
<ide> get_conn.return_value.retry_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> get_conn.return_value.get_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._get_build_id_from_operation")
<ide> def test_run_build_trigger_with_wait(self, get_conn, wait_time, mock_get_id_from
<ide> },
<ide> retry=None,
<ide> timeout=None,
<del> metadata=None,
<add> metadata=(),
<ide> )
<ide>
<ide> get_conn.return_value.run_build_trigger.return_value.result.assert_called_once_with()
<ide>
<ide> get_conn.return_value.get_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._get_build_id_from_operation")
<ide> def test_run_build_trigger_without_wait(self, get_conn, mock_get_id_from_operati
<ide> },
<ide> retry=None,
<ide> timeout=None,
<del> metadata=None,
<add> metadata=(),
<ide> )
<ide>
<ide> get_conn.return_value.get_build.assert_called_once_with(
<del> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=None
<add> request={'project_id': PROJECT_ID, 'id': BUILD_ID}, retry=None, timeout=None, metadata=()
<ide> )
<ide>
<ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.get_conn")
<ide> def test_update_build_trigger(self, get_conn):
<ide> request={'project_id': PROJECT_ID, 'trigger_id': TRIGGER_ID, 'trigger': BUILD_TRIGGER},
<ide> retry=None,
<ide> timeout=None,
<del> metadata=None,
<add> metadata=(),
<ide> ) | 3 |
PHP | PHP | add relationship getters | 1ca55a1e5c2c0d3ba853998f1781cfa23bb9a646 | <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
<ide> public function getQualifiedRelatedPivotKeyName()
<ide> return $this->table.'.'.$this->relatedPivotKey;
<ide> }
<ide>
<add> /**
<add> * Get the parent key for the relationship.
<add> *
<add> * @return string
<add> */
<add> public function getParentKeyName()
<add> {
<add> return $this->parentKey;
<add> }
<add>
<ide> /**
<ide> * Get the fully qualified parent key name for the relation.
<ide> *
<ide> public function getQualifiedParentKeyName()
<ide> return $this->parent->qualifyColumn($this->parentKey);
<ide> }
<ide>
<add> /**
<add> * Get the related key for the relationship.
<add> *
<add> * @return string
<add> */
<add> public function getRelatedKeyName()
<add> {
<add> return $this->relatedKey;
<add> }
<add>
<ide> /**
<ide> * Get the intermediate table for the relationship.
<ide> *
<ide><path>src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
<ide> public function getQualifiedFarKeyName()
<ide> return $this->getQualifiedForeignKeyName();
<ide> }
<ide>
<add> /**
<add> * Get the foreign key on the "through" model.
<add> *
<add> * @return string
<add> */
<add> public function getFirstKeyName()
<add> {
<add> return $this->firstKey;
<add> }
<add>
<ide> /**
<ide> * Get the qualified foreign key on the "through" model.
<ide> *
<ide> public function getQualifiedFirstKeyName()
<ide> return $this->throughParent->qualifyColumn($this->firstKey);
<ide> }
<ide>
<add> /**
<add> * Get the foreign key on the related model.
<add> *
<add> * @return string
<add> */
<add> public function getForeignKeyName()
<add> {
<add> return $this->secondKey;
<add> }
<add>
<ide> /**
<ide> * Get the qualified foreign key on the related model.
<ide> *
<ide> public function getQualifiedForeignKeyName()
<ide> return $this->related->qualifyColumn($this->secondKey);
<ide> }
<ide>
<add> /**
<add> * Get the local key on the far parent model.
<add> *
<add> * @return string
<add> */
<add> public function getLocalKeyName()
<add> {
<add> return $this->localKey;
<add> }
<add>
<ide> /**
<ide> * Get the qualified local key on the far parent model.
<ide> *
<ide> public function getQualifiedLocalKeyName()
<ide> {
<ide> return $this->farParent->qualifyColumn($this->localKey);
<ide> }
<add>
<add> /**
<add> * Get the local key on the intermediary model.
<add> *
<add> * @return string
<add> */
<add> public function getSecondLocalKeyName()
<add> {
<add> return $this->secondLocalKey;
<add> }
<ide> }
<ide><path>src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
<ide> public function getQualifiedForeignKeyName()
<ide> {
<ide> return $this->foreignKey;
<ide> }
<add>
<add> /**
<add> * Get the local key for the relationship.
<add> *
<add> * @return string
<add> */
<add> public function getLocalKeyName()
<add> {
<add> return $this->localKey;
<add> }
<ide> }
<ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php
<ide> public function getMorphClass()
<ide> {
<ide> return $this->morphClass;
<ide> }
<add>
<add> /**
<add> * Get the indicator for a reverse relationship.
<add> *
<add> * @return bool
<add> */
<add> public function getInverse()
<add> {
<add> return $this->inverse;
<add> }
<ide> } | 4 |
Go | Go | remove interim build hacks from tests | b52c3ec4a45ee89d8ad713a16566fd470b4b5bf1 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
<del> // Windows Server 2016 RS1 builds load the windowsservercore image from a tar rather than
<del> // a .WIM file, and the tar layer has the default CMD set (same as the Linux ubuntu image),
<del> // where-as the TP5 .WIM had a blank CMD. Hence this test is not applicable on RS1 or later
<del> // builds
<del> if daemonPlatform == "windows" && windowsDaemonKV >= 14375 {
<del> c.Skip("Not applicable on Windows RS1 or later builds")
<del> }
<add> // Skip on Windows. Base image on Windows has a CMD set in the image.
<add> testRequires(c, DaemonIsLinux)
<ide>
<ide> name := "testbuildemptycmd"
<ide> if _, err := buildImage(name, "FROM "+minimalBaseImage()+"\nMAINTAINER quux\n", true); err != nil {
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunBindMounts(c *check.C) {
<ide> // Ensure that CIDFile gets deleted if it's empty
<ide> // Perform this test by making `docker run` fail
<ide> func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
<del> // Windows Server 2016 RS1 builds load the windowsservercore image from a tar rather than
<del> // a .WIM file, and the tar layer has the default CMD set (same as the Linux ubuntu image),
<del> // where-as the TP5 .WIM had a blank CMD. Hence this test is not applicable on RS1 or later
<del> // builds as the command won't fail as it's not blank
<del> if daemonPlatform == "windows" && windowsDaemonKV >= 14375 {
<del> c.Skip("Not applicable on Windows RS1 or later builds")
<del> }
<add> // Skip on Windows. Base image on Windows has a CMD set in the image.
<add> testRequires(c, DaemonIsLinux)
<ide>
<ide> tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
<ide> if err != nil { | 2 |
Python | Python | start a eucalyptus driver | 7632bac47a96f95c8e5990eada084e6f44a3060a | <ide><path>libcloud/base.py
<ide> class ConnectionKey(object):
<ide> secure = 1
<ide> driver = None
<ide>
<del> def __init__(self, key, secure=True):
<add> def __init__(self, key, secure=True, host=None):
<ide> """
<ide> Initialize `user_id` and `key`; set `secure` to an C{int} based on
<ide> passed value.
<ide> """
<ide> self.key = key
<ide> self.secure = secure and 1 or 0
<ide> self.ua = []
<add> if host:
<add> self.host = host
<ide>
<ide> def connect(self, host=None, port=None):
<ide> """
<ide> class ConnectionUserAndKey(ConnectionKey):
<ide>
<ide> user_id = None
<ide>
<del> def __init__(self, user_id, key, secure=True):
<del> super(ConnectionUserAndKey, self).__init__(key, secure)
<add> def __init__(self, user_id, key, secure=True, host=None):
<add> super(ConnectionUserAndKey, self).__init__(key, secure, host)
<ide> self.user_id = user_id
<ide>
<ide>
<ide> class NodeDriver(object):
<ide> """
<ide> NODE_STATE_MAP = {}
<ide>
<del> def __init__(self, key, secret=None, secure=True):
<add> def __init__(self, key, secret=None, secure=True, host=None):
<ide> """
<ide> @keyword key: API key or username to used
<ide> @type key: str
<ide> def __init__(self, key, secret=None, secure=True):
<ide> self.key = key
<ide> self.secret = secret
<ide> self.secure = secure
<add> args = [self.key]
<add>
<ide> if self.secret:
<del> self.connection = self.connectionCls(key, secret, secure)
<del> else:
<del> self.connection = self.connectionCls(key, secure)
<add> args.append(self.secret)
<add>
<add> args.append(secure)
<add>
<add> if host:
<add> args.append(host)
<add>
<add> self.connection = self.connectionCls(*args)
<ide>
<ide> self.connection.driver = self
<ide> self.connection.connect()
<ide><path>libcloud/drivers/ec2.py
<ide> class EC2USWestNodeDriver(EC2NodeDriver):
<ide> _instance_types = EC2_US_WEST_INSTANCE_TYPES
<ide> def list_locations(self):
<ide> return [NodeLocation(0, 'Amazon US N. California', 'US', self)]
<add>
<add>class EucConnection(EC2Connection):
<add>
<add> host = None
<add>
<add>class EucNodeDriver(EC2NodeDriver):
<add>
<add> connectionCls = EucConnection
<add> _instance_types = EC2_US_WEST_INSTANCE_TYPES
<add> def list_locations(self):
<add> raise NotImplementedError, \
<add> 'list_locations not implemented for this driver'
<ide><path>libcloud/providers.py
<ide> ('libcloud.drivers.voxel', 'VoxelNodeDriver'),
<ide> Provider.SOFTLAYER:
<ide> ('libcloud.drivers.softlayer', 'SoftLayerNodeDriver'),
<add> Provider.EUCALYPTUS:
<add> ('libcloud.drivers.ec2', 'EucNodeDriver'),
<ide> }
<ide>
<ide> def get_driver(provider):
<ide><path>libcloud/types.py
<ide> class Provider(object):
<ide> EC2_US_WEST = 10
<ide> VOXEL = 11
<ide> SOFTLAYER = 12
<add> EUCALYPTUS = 13
<ide>
<ide> class NodeState(object):
<ide> """ | 4 |
PHP | PHP | add swedish language | 8bcfd522339359c2ed417c18f8f1e27be2bc0c6b | <ide><path>application/language/sv/pagination.php
<add><?php
<add>
<add>return array(
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Pagination Language Lines
<add> |--------------------------------------------------------------------------
<add> |
<add> | The following language lines are used by the paginator library to build
<add> | the pagination links. You're free to change them to anything you want.
<add> | If you come up with something more exciting, let us know.
<add> |
<add> */
<add>
<add> 'previous' => '« Föregående',
<add> 'next' => 'Nästa »',
<add>
<add>);
<ide>\ No newline at end of file
<ide><path>application/language/sv/validation.php
<add><?php
<add>
<add>return array(
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Validation Language Lines
<add> |--------------------------------------------------------------------------
<add> |
<add> | The following language lines contain the default error messages used
<add> | by the validator class. Some of the rules contain multiple versions,
<add> | such as the size (max, min, between) rules. These versions are used
<add> | for different input types such as strings and files.
<add> |
<add> | These language lines may be easily changed to provide custom error
<add> | messages in your application. Error messages for custom validation
<add> | rules may also be added to this file.
<add> |
<add> */
<add>
<add> "accepted" => ":attribute måste accepteras.",
<add> "active_url" => ":attribute är inte en giltig webbadress.",
<add> "after" => ":attribute måste vara ett datum efter den :date.",
<add> "alpha" => ":attribute får endast innehålla bokstäver.",
<add> "alpha_dash" => ":attribute får endast innehålla bokstäver, nummer och bindestreck.",
<add> "alpha_num" => ":attribute får endast innehålla bokstäver och nummer.",
<add> "array" => ":attribute måste ha valda element.",
<add> "before" => ":attribute måste vara ett datum innan den :date.",
<add> "between" => array(
<add> "numeric" => ":attribute måste vara ett nummer mellan :min och :max.",
<add> "file" => ":attribute måste vara mellan :min till :max kilobytes stor.",
<add> "string" => ":attribute måste innehålla :min till :max tecken.",
<add> ),
<add> "confirmed" => ":attribute bekräftelsen matchar inte.",
<add> "count" => ":attribute måste exakt ha :count valda element.",
<add> "countbetween" => ":attribute får endast ha :min till :max valda element.",
<add> "countmax" => ":attribute får max ha :max valda element.",
<add> "countmin" => ":attribute måste minst ha :min valda element.",
<add> "different" => ":attribute och :other får ej vara lika.",
<add> "email" => ":attribute formatet är ogiltig.",
<add> "exists" => "Det valda :attribute är ogiltigt.",
<add> "image" => ":attribute måste vara en bild.",
<add> "in" => "Det valda :attribute är ogiltigt.",
<add> "integer" => ":attribute måste vara en siffra.",
<add> "ip" => ":attribute måste vara en giltig IP-adress.",
<add> "match" => ":attribute formatet är ogiltig.",
<add> "max" => array(
<add> "numeric" => ":attribute får inte vara större än :max.",
<add> "file" => ":attribute får max vara :max kilobytes stor.",
<add> "string" => ":attribute får max innehålla :max tecken.",
<add> ),
<add> "mimes" => ":attribute måste vara en fil av typen: :values.",
<add> "min" => array(
<add> "numeric" => ":attribute måste vara större än :min.",
<add> "file" => ":attribute måste minst vara :min kilobytes stor.",
<add> "string" => ":attribute måste minst innehålla :min tecken.",
<add> ),
<add> "not_in" => "Det valda :attribute är ogiltigt.",
<add> "numeric" => ":attribute måste vara ett nummer.",
<add> "required" => ":attribute fältet är obligatoriskt.",
<add> "same" => ":attribute och :other måste vara likadana.",
<add> "size" => array(
<add> "numeric" => ":attribute måste vara :size.",
<add> "file" => ":attribute får endast vara :size kilobyte stor.",
<add> "string" => ":attribute måste innehålla :size tecken.",
<add> ),
<add> "unique" => ":attribute används redan.",
<add> "url" => ":attribute formatet är ogiltig",
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Custom Validation Language Lines
<add> |--------------------------------------------------------------------------
<add> |
<add> | Here you may specify custom validation messages for attributes using the
<add> | convention "attribute_rule" to name the lines. This helps keep your
<add> | custom validation clean and tidy.
<add> |
<add> | So, say you want to use a custom validation message when validating that
<add> | the "email" attribute is unique. Just add "email_unique" to this array
<add> | with your custom message. The Validator will handle the rest!
<add> |
<add> */
<add>
<add> 'custom' => array(),
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Validation Attributes
<add> |--------------------------------------------------------------------------
<add> |
<add> | The following language lines are used to swap attribute place-holders
<add> | with something more reader friendly such as "E-Mail Address" instead
<add> | of "email". Your users will thank you.
<add> |
<add> | The Validator class will automatically search this array of lines it
<add> | is attempting to replace the :attribute place-holder in messages.
<add> | It's pretty slick. We think you'll like it.
<add> |
<add> */
<add>
<add> 'attributes' => array(),
<add>
<add>);
<ide>\ No newline at end of file | 2 |
PHP | PHP | apply fixes from styleci | 454c2b341a2662fb88bfc42cb030d422783e4bab | <ide><path>tests/Integration/Broadcasting/BroadcastManagerTest.php
<ide> use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
<ide> use Illuminate\Support\Facades\Broadcast;
<ide> use Illuminate\Support\Facades\Bus;
<del>use Illuminate\Support\Facades\Cache;
<ide> use Illuminate\Support\Facades\Queue;
<del>use Illuminate\Support\Str;
<ide> use Orchestra\Testbench\TestCase;
<ide>
<ide> /** | 1 |
Mixed | Javascript | move _writablestate.buffer to eol | 907c07fa850e128c695482cd47554b5bce5e4b0c | <ide><path>doc/api/deprecations.md
<ide> The `_linklist` module is deprecated. Please use a userland alternative.
<ide> ### DEP0003: `_writableState.buffer`
<ide> <!-- YAML
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/31165
<add> description: End-of-Life
<ide> - version:
<ide> - v4.8.6
<ide> - v6.12.0
<ide> changes:
<ide> description: Runtime deprecation.
<ide> -->
<ide>
<del>Type: Runtime
<add>Type: End-of-Life
<ide>
<del>The `_writableState.buffer` property is deprecated. Use the
<del>`_writableState.getBuffer()` method instead.
<add>The `_writableState.buffer` has been removed. Use `_writableState.getBuffer()`
<add>instead.
<ide>
<ide> <a id="DEP0004"></a>
<ide> ### DEP0004: `CryptoStream.prototype.readyState`
<ide><path>lib/_stream_writable.js
<ide> const {
<ide> module.exports = Writable;
<ide> Writable.WritableState = WritableState;
<ide>
<del>const internalUtil = require('internal/util');
<ide> const EE = require('events');
<ide> const Stream = require('stream');
<ide> const { Buffer } = require('buffer');
<ide> WritableState.prototype.getBuffer = function getBuffer() {
<ide> return out;
<ide> };
<ide>
<del>ObjectDefineProperty(WritableState.prototype, 'buffer', {
<del> get: internalUtil.deprecate(function writableStateBufferGetter() {
<del> return this.getBuffer();
<del> }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' +
<del> 'instead.', 'DEP0003')
<del>});
<del>
<ide> // Test _writableState for inheritance to account for Duplex streams,
<ide> // whose prototype chain only points to Readable.
<ide> var realHasInstance; | 2 |
Text | Text | add semicolon for consistency | a32bd99181658216b8dee9eba47057bd68e1b296 | <ide><path>docs/introduction/ThreePrinciples.md
<ide> function todos(state = [], action) {
<ide> completed: true
<ide> }),
<ide> ...state.slice(action.index + 1)
<del> ]
<add> ];
<ide> default:
<ide> return state;
<ide> } | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.