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 |
|---|---|---|---|---|---|
Java | Java | abersnaze/rxjava into merge-940 | 8c1e037d9f6c8a0cc2b691db0adf282aa4733e3a | <ide><path>rxjava-contrib/rxjava-debug/src/main/java/rx/operators/DebugSubscriber.java
<ide> import rx.Observable.Operator;
<ide> import rx.Observer;
<ide> import rx.Subscriber;
<del>import rx.functions.Action1;
<del>import rx.functions.Action2;
<del>import rx.functions.Func1;
<ide> import rx.plugins.DebugNotification;
<add>import rx.plugins.DebugNotificationListener;
<ide>
<ide> public final class DebugSubscriber<T, C> extends Subscriber<T> {
<del> private final Func1<T, T> onNextHook;
<del> private final Func1<DebugNotification, C> start;
<del> private final Action1<C> complete;
<del> private final Action2<C, Throwable> error;
<add> private DebugNotificationListener<C> listener;
<ide> private final Observer<? super T> o;
<ide> private Operator<? extends T, ?> from = null;
<ide> private Operator<?, ? super T> to = null;
<ide>
<ide> public DebugSubscriber(
<del> Func1<T, T> onNextHook,
<del> Func1<DebugNotification, C> start,
<del> Action1<C> complete,
<del> Action2<C, Throwable> error,
<add> DebugNotificationListener<C> listener,
<ide> Subscriber<? super T> _o,
<ide> Operator<? extends T, ?> _out,
<ide> Operator<?, ? super T> _in) {
<ide> super(_o);
<del> this.start = start;
<del> this.complete = complete;
<del> this.error = error;
<add> this.listener = listener;
<ide> this.o = _o;
<del> this.onNextHook = onNextHook;
<ide> this.from = _out;
<ide> this.to = _in;
<del> this.add(new DebugSubscription<T, C>(this, start, complete, error));
<add> this.add(new DebugSubscription<T, C>(this, listener));
<ide> }
<ide>
<ide> @Override
<ide> public void onCompleted() {
<del> final DebugNotification<T, C> n = DebugNotification.createOnCompleted(o, from, to);
<del> C context = start.call(n);
<add> final DebugNotification<T> n = DebugNotification.createOnCompleted(o, from, to);
<add> C context = listener.start(n);
<ide> try {
<ide> o.onCompleted();
<del> complete.call(context);
<add> listener.complete(context);
<ide> } catch (Throwable e) {
<del> error.call(context, e);
<add> listener.error(context, e);
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void onError(Throwable e) {
<del> final DebugNotification<T, C> n = DebugNotification.createOnError(o, from, e, to);
<del> C context = start.call(n);
<add> final DebugNotification<T> n = DebugNotification.createOnError(o, from, e, to);
<add> C context = listener.start(n);
<ide> try {
<ide> o.onError(e);
<del> complete.call(context);
<add> listener.complete(context);
<ide> } catch (Throwable e2) {
<del> error.call(context, e2);
<add> listener.error(context, e2);
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void onNext(T t) {
<del> final DebugNotification<T, C> n = DebugNotification.createOnNext(o, from, t, to);
<del> C context = start.call(n);
<add> final DebugNotification<T> n = DebugNotification.createOnNext(o, from, t, to);
<add> t = (T) listener.onNext(n);
<add>
<add> C context = listener.start(n);
<ide> try {
<del> o.onNext(onNextHook.call(t));
<del> complete.call(context);
<add> o.onNext(t);
<add> listener.complete(context);
<ide> } catch (Throwable e) {
<del> error.call(context, e);
<add> listener.error(context, e);
<ide> }
<ide> }
<ide>
<ide><path>rxjava-contrib/rxjava-debug/src/main/java/rx/operators/DebugSubscription.java
<ide> package rx.operators;
<ide>
<ide> import rx.Subscription;
<del>import rx.functions.Action1;
<del>import rx.functions.Action2;
<del>import rx.functions.Func1;
<ide> import rx.plugins.DebugNotification;
<add>import rx.plugins.DebugNotificationListener;
<ide>
<ide> final class DebugSubscription<T, C> implements Subscription {
<ide> private final DebugSubscriber<T, C> debugObserver;
<del> private final Func1<DebugNotification, C> start;
<del> private final Action1<C> complete;
<del> private final Action2<C, Throwable> error;
<add> private DebugNotificationListener<C> listener;
<ide>
<del> DebugSubscription(DebugSubscriber<T, C> debugObserver, Func1<DebugNotification, C> start, Action1<C> complete, Action2<C, Throwable> error) {
<add> DebugSubscription(DebugSubscriber<T, C> debugObserver, DebugNotificationListener<C> listener) {
<ide> this.debugObserver = debugObserver;
<del> this.start = start;
<del> this.complete = complete;
<del> this.error = error;
<add> this.listener = listener;
<ide> }
<ide>
<ide> @Override
<ide> public void unsubscribe() {
<del> final DebugNotification<T, C> n = DebugNotification.<T, C> createUnsubscribe(debugObserver.getActual(), debugObserver.getFrom(), debugObserver.getTo());
<del> C context = start.call(n);
<add> final DebugNotification<T> n = DebugNotification.<T> createUnsubscribe(debugObserver.getActual(), debugObserver.getFrom(), debugObserver.getTo());
<add> C context = listener.start(n);
<ide> try {
<ide> debugObserver.unsubscribe();
<del> complete.call(context);
<add> listener.complete(context);
<ide> } catch (Throwable e) {
<del> error.call(context, e);
<add> listener.error(context, e);
<ide> }
<ide> }
<ide>
<ide><path>rxjava-contrib/rxjava-debug/src/main/java/rx/plugins/DebugHook.java
<ide> * @author gscampbell
<ide> */
<ide> public class DebugHook<C> extends RxJavaObservableExecutionHook {
<del> private final Func1 onNextHook;
<del> private final Func1<DebugNotification, C> start;
<del> private final Action1<C> complete;
<del> private final Action2<C, Throwable> error;
<add> private DebugNotificationListener<C> listener;
<ide>
<ide> /**
<ide> * Creates a new instance of the DebugHook RxJava plug-in that can be passed into
<ide> * @param events
<ide> * This action is invoked as each notification is generated
<ide> */
<del> public DebugHook(Func1 onNextDataHook, Func1<DebugNotification, C> start, Action1<C> complete, Action2<C, Throwable> error) {
<del> this.complete = complete;
<del> this.error = error;
<del> this.onNextHook = onNextDataHook == null ? Functions.identity() : onNextDataHook;
<del> this.start = (Func1<DebugNotification, C>) (start == null ? Actions.empty() : start);
<add> public DebugHook(DebugNotificationListener<C> listener) {
<add> if (listener == null)
<add> throw new IllegalArgumentException("The debug listener must not be null");
<add> this.listener = listener;
<ide> }
<ide>
<ide> @Override
<ide> public <T> OnSubscribe<T> onSubscribeStart(final Observable<? extends T> observableInstance, final OnSubscribe<T> f) {
<ide> return new OnSubscribe<T>() {
<ide> @Override
<ide> public void call(Subscriber<? super T> o) {
<del> C context = start.call(DebugNotification.createSubscribe(o, observableInstance, f));
<add> final DebugNotification<T> n = DebugNotification.createSubscribe(o, observableInstance, f);
<add> o = wrapOutbound(null, o);
<add>
<add> C context = listener.start(n);
<ide> try {
<del> f.call(wrapOutbound(null, o));
<del> complete.call(context);
<add> f.call(o);
<add> listener.complete(context);
<ide> }
<ide> catch(Throwable e) {
<del> error.call(context, e);
<add> listener.error(context, e);
<ide> }
<ide> }
<ide> };
<ide> }
<ide>
<ide> @Override
<del> public <T> Subscription onSubscribeReturn(Observable<? extends T> observableInstance, Subscription subscription) {
<add> public <T> Subscription onSubscribeReturn(Subscription subscription) {
<ide> return subscription;
<ide> }
<ide>
<ide> @Override
<ide> public <T> OnSubscribe<T> onCreate(final OnSubscribe<T> f) {
<del> return new OnCreateWrapper<T>(f);
<add> return new DebugOnSubscribe<T>(f);
<ide> }
<add>
<add> public final class DebugOnSubscribe<T> implements OnSubscribe<T> {
<add> private final OnSubscribe<T> f;
<add>
<add> private DebugOnSubscribe(OnSubscribe<T> f) {
<add> this.f = f;
<add> }
<add>
<add> @Override
<add> public void call(Subscriber<? super T> o) {
<add> f.call(wrapInbound(null, o));
<add> }
<add>
<add> public OnSubscribe<T> getActual() {
<add> return f;
<add> }
<add> }
<add>
<ide>
<ide> @Override
<ide> public <T, R> Operator<? extends R, ? super T> onLift(final Operator<? extends R, ? super T> bind) {
<ide> public Subscriber<? super T> call(final Subscriber<? super R> o) {
<ide> };
<ide> }
<ide>
<del> @Override
<del> public <T> Subscription onAdd(Subscriber<T> subscriber, Subscription s) {
<del> return s;
<del> }
<del>
<ide> @SuppressWarnings("unchecked")
<ide> private <R> Subscriber<? super R> wrapOutbound(Operator<? extends R, ?> bind, Subscriber<? super R> o) {
<ide> if (o instanceof DebugSubscriber) {
<ide> if (bind != null)
<ide> ((DebugSubscriber<R, C>) o).setFrom(bind);
<ide> return o;
<ide> }
<del> return new DebugSubscriber<R, C>(onNextHook, start, complete, error, o, bind, null);
<add> return new DebugSubscriber<R, C>(listener, o, bind, null);
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> private <T> Subscriber<? super T> wrapInbound(Operator<?, ? super T> bind, Subsc
<ide> ((DebugSubscriber<T, C>) o).setTo(bind);
<ide> return o;
<ide> }
<del> return new DebugSubscriber<T, C>(onNextHook, start, complete, error, o, null, bind);
<del> }
<del>
<del> public final class OnCreateWrapper<T> implements OnSubscribe<T> {
<del> private final OnSubscribe<T> f;
<del>
<del> private OnCreateWrapper(OnSubscribe<T> f) {
<del> this.f = f;
<del> }
<del>
<del> @Override
<del> public void call(Subscriber<? super T> o) {
<del> f.call(wrapInbound(null, o));
<del> }
<del>
<del> public OnSubscribe<T> getActual() {
<del> return f;
<del> }
<add> return new DebugSubscriber<T, C>(listener, o, null, bind);
<ide> }
<ide> }
<ide><path>rxjava-contrib/rxjava-debug/src/main/java/rx/plugins/DebugNotification.java
<ide> import rx.observers.SafeSubscriber;
<ide> import rx.operators.DebugSubscriber;
<ide>
<del>public class DebugNotification<T, C> {
<add>public class DebugNotification<T> {
<ide> public static enum Kind {
<ide> OnNext, OnError, OnCompleted, Subscribe, Unsubscribe
<ide> }
<ide> public static enum Kind {
<ide> private final T value;
<ide> private final Observer observer;
<ide>
<del> public static <T, C> DebugNotification<T, C> createSubscribe(Observer<? super T> o, Observable<? extends T> source, OnSubscribe<T> sourceFunc) {
<add> @SuppressWarnings("unchecked")
<add> public static <T, C> DebugNotification<T> createSubscribe(Observer<? super T> o, Observable<? extends T> source, OnSubscribe<T> sourceFunc) {
<ide> Operator<?, ? super T> to = null;
<ide> Operator<? extends T, ?> from = null;
<ide> if (o instanceof SafeSubscriber) {
<del> o = ((SafeSubscriber) o).getActual();
<add> o = ((SafeSubscriber<T>) o).getActual();
<ide> }
<ide> if (o instanceof DebugSubscriber) {
<del> to = ((DebugSubscriber<T, C>) o).getTo();
<del> from = ((DebugSubscriber<T, C>) o).getFrom();
<del> o = ((DebugSubscriber) o).getActual();
<add> final DebugSubscriber ds = (DebugSubscriber) o;
<add> to = ds.getTo();
<add> from = ds.getFrom();
<add> o = ds.getActual();
<ide> }
<del> if (sourceFunc instanceof DebugHook.OnCreateWrapper) {
<del> sourceFunc = ((DebugHook.OnCreateWrapper) sourceFunc).getActual();
<add> if (sourceFunc instanceof DebugHook.DebugOnSubscribe) {
<add> sourceFunc = ((DebugHook<C>.DebugOnSubscribe<T>) sourceFunc).getActual();
<ide> }
<del> return new DebugNotification<T, C>(o, from, Kind.Subscribe, null, null, to, source, sourceFunc);
<add> return new DebugNotification<T>(o, from, Kind.Subscribe, null, null, to, source, sourceFunc);
<ide> }
<ide>
<del> public static <T, C> DebugNotification<T, C> createOnNext(Observer<? super T> o, Operator<? extends T, ?> from, T t, Operator<?, ? super T> to) {
<del> return new DebugNotification<T, C>(o, from, Kind.OnNext, t, null, to, null, null);
<add> public static <T> DebugNotification<T> createOnNext(Observer<? super T> o, Operator<? extends T, ?> from, T t, Operator<?, ? super T> to) {
<add> return new DebugNotification<T>(o, from, Kind.OnNext, t, null, to, null, null);
<ide> }
<ide>
<del> public static <T, C> DebugNotification<T, C> createOnError(Observer<? super T> o, Operator<? extends T, ?> from, Throwable e, Operator<?, ? super T> to) {
<del> return new DebugNotification<T, C>(o, from, Kind.OnError, null, e, to, null, null);
<add> public static <T> DebugNotification<T> createOnError(Observer<? super T> o, Operator<? extends T, ?> from, Throwable e, Operator<?, ? super T> to) {
<add> return new DebugNotification<T>(o, from, Kind.OnError, null, e, to, null, null);
<ide> }
<ide>
<del> public static <T, C> DebugNotification<T, C> createOnCompleted(Observer<? super T> o, Operator<? extends T, ?> from, Operator<?, ? super T> to) {
<del> return new DebugNotification<T, C>(o, from, Kind.OnCompleted, null, null, to, null, null);
<add> public static <T> DebugNotification<T> createOnCompleted(Observer<? super T> o, Operator<? extends T, ?> from, Operator<?, ? super T> to) {
<add> return new DebugNotification<T>(o, from, Kind.OnCompleted, null, null, to, null, null);
<ide> }
<ide>
<del> public static <T, C> DebugNotification<T, C> createUnsubscribe(Observer<? super T> o, Operator<? extends T, ?> from, Operator<?, ? super T> to) {
<del> return new DebugNotification<T, C>(o, from, Kind.Unsubscribe, null, null, to, null, null);
<add> public static <T> DebugNotification<T> createUnsubscribe(Observer<? super T> o, Operator<? extends T, ?> from, Operator<?, ? super T> to) {
<add> return new DebugNotification<T>(o, from, Kind.Unsubscribe, null, null, to, null, null);
<ide> }
<ide>
<ide> private DebugNotification(Observer o, Operator<? extends T, ?> from, Kind kind, T value, Throwable throwable, Operator<?, ? super T> to, Observable<? extends T> source, OnSubscribe<T> sourceFunc) {
<ide> public Throwable getThrowable() {
<ide> public Kind getKind() {
<ide> return kind;
<ide> }
<del>
<add>
<ide> public Observable<? extends T> getSource() {
<ide> return source;
<ide> }
<del>
<add>
<ide> public OnSubscribe<T> getSourceFunc() {
<ide> return sourceFunc;
<ide> }
<ide> public OnSubscribe<T> getSourceFunc() {
<ide> */
<ide> public String toString() {
<ide> final StringBuilder s = new StringBuilder("{");
<del> s.append("\"observer\": \"").append(observer.getClass().getName()).append("@").append(Integer.toHexString(observer.hashCode())).append("\"");
<add> s.append("\"observer\": ");
<add> if (observer != null)
<add> s.append("\"").append(observer.getClass().getName()).append("@").append(Integer.toHexString(observer.hashCode())).append("\"");
<add> else
<add> s.append("null");
<ide> s.append(", \"type\": \"").append(kind).append("\"");
<ide> if (kind == Kind.OnNext)
<del> // not json safe
<del> s.append(", \"value\": \"").append(value).append("\"");
<add> s.append(", \"value\": ").append(quote(value)).append("");
<ide> if (kind == Kind.OnError)
<ide> s.append(", \"exception\": \"").append(throwable.getMessage().replace("\\", "\\\\").replace("\"", "\\\"")).append("\"");
<ide> if (source != null)
<ide> public String toString() {
<ide> s.append("}");
<ide> return s.toString();
<ide> }
<add>
<add> public static String quote(Object obj) {
<add> if (obj == null) {
<add> return "null";
<add> }
<add>
<add> String string;
<add> try {
<add> string = obj.toString();
<add> } catch (Throwable e) {
<add> return "\"\"";
<add> }
<add> if (string == null || string.length() == 0) {
<add> return "\"\"";
<add> }
<add>
<add> char c = 0;
<add> int i;
<add> int len = string.length();
<add> StringBuilder sb = new StringBuilder(len + 4);
<add> String t;
<add>
<add> sb.append('"');
<add> for (i = 0; i < len; i += 1) {
<add> c = string.charAt(i);
<add> switch (c) {
<add> case '\\':
<add> case '"':
<add> sb.append('\\');
<add> sb.append(c);
<add> break;
<add> case '/':
<add> sb.append('\\');
<add> sb.append(c);
<add> break;
<add> case '\b':
<add> sb.append("\\b");
<add> break;
<add> case '\t':
<add> sb.append("\\t");
<add> break;
<add> case '\n':
<add> sb.append("\\n");
<add> break;
<add> case '\f':
<add> sb.append("\\f");
<add> break;
<add> case '\r':
<add> sb.append("\\r");
<add> break;
<add> default:
<add> if (c < ' ') {
<add> t = "000" + Integer.toHexString(c);
<add> sb.append("\\u" + t.substring(t.length() - 4));
<add> } else {
<add> sb.append(c);
<add> }
<add> }
<add> }
<add> sb.append('"');
<add> return sb.toString();
<add> }
<ide> }
<ide><path>rxjava-contrib/rxjava-debug/src/main/java/rx/plugins/DebugNotificationListener.java
<add>package rx.plugins;
<add>
<add>import rx.Observable;
<add>import rx.Observable.Operator;
<add>import rx.Observer;
<add>
<add>/**
<add> * Subclasses of this are passed into the constructor of {@link DebugHook} to receive notification
<add> * about all activity in Rx.
<add> *
<add> * @author gscampbell
<add> *
<add> * @param <C>
<add> * Context type that is returned from start and passed to either complete or error.
<add> * @see DebugHook
<add> */
<add>@SuppressWarnings("unused")
<add>public abstract class DebugNotificationListener<C> {
<add> /**
<add> * Override this to change the default behavior of returning the encapsulated value. This will
<add> * only be invoked when the {@link DebugNotification#getKind()} is
<add> * {@link DebugNotification.Kind#OnNext} and the value (null or not) is just about to be sent to
<add> * next {@link Observer}. This can end up being called multiple times for
<add> * the same value as it passes from {@link Operator} to {@link Operator} in the
<add> * {@link Observable} chain.
<add> * <p>
<add> * This can be used to decorate or replace the values passed into any onNext function or just
<add> * perform extra logging, metrics and other such things and pass-thru the function.
<add> *
<add> * @param n
<add> * {@link DebugNotification} containing the data and context about what is happening.
<add> * @return
<add> */
<add> public <T> T onNext(DebugNotification<T> n) {
<add> return n.getValue();
<add> }
<add>
<add> /**
<add> * For each {@link DebugNotification.Kind} start is invoked before the actual method is invoked.
<add> * <p>
<add> * This can be used to perform extra logging, metrics and other such things.
<add> *
<add> * @param n
<add> * {@link DebugNotification} containing the data and context about what is happening.
<add> * @return
<add> * A contextual object that the listener can use in the {@link #complete(C)} or
<add> * {@link #error(C, Throwable)} after the actual operation has ended.
<add> */
<add> public <T> C start(DebugNotification<T> n) {
<add> return null;
<add> }
<add>
<add> /**
<add> * After the actual operations has completed from {@link #start(DebugNotification)} this is
<add> * invoked
<add> *
<add> * @param context
<add> */
<add> public void complete(C context) {
<add> }
<add>
<add> /**
<add> * After the actual operations has thrown an exception from {@link #start(DebugNotification)}
<add> * this is invoked
<add> *
<add> * @param context
<add> */
<add> public void error(C context, Throwable e) {
<add> }
<add>}
<ide><path>rxjava-contrib/rxjava-debug/src/test/java/rx/debug/DebugHookTest.java
<ide> package rx.debug;
<ide>
<add>import static org.junit.Assert.*;
<ide> import static org.mockito.Matchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.Arrays;
<add>import java.util.Map.Entry;
<add>import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import org.hamcrest.BaseMatcher;
<ide> import org.hamcrest.Description;
<ide> import org.junit.After;
<ide> import org.junit.Before;
<del>import org.junit.Ignore;
<ide> import org.junit.Test;
<del>import org.mockito.invocation.InvocationOnMock;
<del>import org.mockito.stubbing.Answer;
<add>import org.mockito.InOrder;
<ide>
<ide> import rx.Observable;
<del>import rx.Subscriber;
<del>import rx.functions.Action1;
<del>import rx.functions.Action2;
<ide> import rx.functions.Func1;
<add>import rx.observers.Subscribers;
<ide> import rx.plugins.DebugHook;
<ide> import rx.plugins.DebugNotification;
<ide> import rx.plugins.DebugNotification.Kind;
<add>import rx.plugins.DebugNotificationListener;
<ide> import rx.plugins.PlugReset;
<ide> import rx.plugins.RxJavaPlugins;
<ide>
<ide> public void reset() {
<ide> PlugReset.reset();
<ide> }
<ide>
<add> private static class TestDebugNotificationListener extends DebugNotificationListener<Object> {
<add> ConcurrentHashMap<Thread, AtomicInteger> allThreadDepths = new ConcurrentHashMap<Thread, AtomicInteger>(1);
<add> ThreadLocal<AtomicInteger> currentThreadDepth = new ThreadLocal<AtomicInteger>() {
<add> protected AtomicInteger initialValue() {
<add> AtomicInteger depth = new AtomicInteger();
<add> allThreadDepths.put(Thread.currentThread(), depth);
<add> return depth;
<add> };
<add> };
<add>
<add> @Override
<add> public <T> T onNext(DebugNotification<T> n) {
<add> if (n == null)
<add> return null; // because we are verifying on a spied object.
<add> System.err.println("next: " + n.getValue());
<add> return super.onNext(n);
<add> }
<add>
<add> @Override
<add> public <T> Object start(DebugNotification<T> n) {
<add> if (n == null)
<add> return null; // because we are verifying on a spied object.
<add> currentThreadDepth.get().incrementAndGet();
<add> Object context = new Object();
<add> System.err.println("start: " + Integer.toHexString(context.hashCode()) + " " + n);
<add> return context;
<add> }
<add>
<add> @Override
<add> public void complete(Object context) {
<add> if (context == null)
<add> return; // because we are verifying on a spied object.
<add> currentThreadDepth.get().decrementAndGet();
<add> System.err.println("complete: " + Integer.toHexString(context.hashCode()));
<add> }
<add>
<add> @Override
<add> public void error(Object context, Throwable e) {
<add> if (context == null)
<add> return; // because we are verifying on a spied object.
<add> currentThreadDepth.get().decrementAndGet();
<add> System.err.println("error: " + Integer.toHexString(context.hashCode()));
<add> }
<add>
<add> public void assertValidState() {
<add> for (Entry<Thread, AtomicInteger> threadDepth : allThreadDepths.entrySet()) {
<add> assertEquals(0, threadDepth.getValue().get());
<add> }
<add> }
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<ide> @Test
<del> @Ignore
<ide> public void testSimple() {
<del> Func1 start = mock(Func1.class);
<del> Action1 complete = mock(Action1.class);
<del> Action2 error = mock(Action2.class);
<del> final DebugHook hook = new DebugHook(null, start, complete, error);
<add> TestDebugNotificationListener listener = new TestDebugNotificationListener();
<add> listener = spy(listener);
<add> final DebugHook hook = new DebugHook(listener);
<ide> RxJavaPlugins.getInstance().registerObservableExecutionHook(hook);
<del> Observable.empty().subscribe();
<del> verify(start, times(1)).call(subscribe());
<del> verify(start, times(1)).call(onCompleted());
<ide>
<del> verify(complete, times(2)).call(any());
<add> Observable.from(1).subscribe(Subscribers.empty());
<add>
<add> final InOrder inOrder = inOrder(listener);
<add> inOrder.verify(listener).start(subscribe());
<add> inOrder.verify(listener).onNext(onNext(1));
<add> inOrder.verify(listener).start(onNext(1));
<add> inOrder.verify(listener).complete(any());
<add> inOrder.verify(listener).start(onCompleted());
<add> inOrder.verify(listener, times(2)).complete(any());
<add> inOrder.verifyNoMoreInteractions();
<ide>
<del> verify(error, never()).call(any(), any());
<add> listener.assertValidState();
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> @Test
<ide> public void testOneOp() {
<del> Func1<DebugNotification<Integer, Object>, Object> start = mock(Func1.class);
<del> doAnswer(new Answer() {
<del> public Object answer(InvocationOnMock invocation) throws Throwable {
<del> Object context = new Object();
<del> System.out.println("start: " + context.hashCode() + " " + invocation.getArguments()[0]);
<del> return context;
<del> }
<del> }).when(start).call(any(DebugNotification.class));
<del> Action1<Object> complete = mock(Action1.class);
<del> doAnswer(new Answer() {
<del> public Object answer(InvocationOnMock invocation) throws Throwable {
<del> System.out.println("complete: " + invocation.getArguments()[0].hashCode());
<del> return null;
<del> }
<del> }).when(complete).call(any());
<del> Action2<Object, Throwable> error = mock(Action2.class);
<del> doAnswer(new Answer() {
<del> public Object answer(InvocationOnMock invocation) throws Throwable {
<del> System.out.println("error: " + invocation.getArguments()[1].hashCode());
<del> return null;
<del> }
<del> }).when(error).call(any(), any(Throwable.class));
<del> final DebugHook hook = new DebugHook(null, start, complete, error);
<add> TestDebugNotificationListener listener = new TestDebugNotificationListener();
<add> listener = spy(listener);
<add>
<add> // create and register the hooks.
<add> final DebugHook<Object> hook = new DebugHook<Object>(listener);
<ide> RxJavaPlugins.getInstance().registerObservableExecutionHook(hook);
<del> Observable.from(Arrays.asList(1, 3)).flatMap(new Func1<Integer, Observable<Integer>>() {
<add>
<add> // do the operation
<add> Observable
<add> .from(Arrays.asList(1, 3))
<add> .flatMap(new Func1<Integer, Observable<Integer>>() {
<add> @Override
<add> public Observable<Integer> call(Integer it) {
<add> return Observable.from(Arrays.asList(it * 10, (it + 1) * 10));
<add> }
<add> })
<add> .take(3)
<add> .subscribe(Subscribers.<Integer> empty());
<add>
<add> InOrder calls = inOrder(listener);
<add>
<add> calls.verify(listener).start(subscribe());
<add> calls.verify(listener).start(onNext(1)); // from to map
<add> calls.verify(listener).start(onNext(Observable.class)); // map to merge
<add> calls.verify(listener).start(subscribe()); // merge inner
<add> calls.verify(listener).start(onNext(10)); // from to merge inner
<add> calls.verify(listener).start(onNext(10)); // merge inner to take
<add> calls.verify(listener).start(onNext(10)); // take to empty subscriber
<add> calls.verify(listener, times(3)).complete(any());
<add> calls.verify(listener).start(onNext(20)); // next from to merge inner
<add> calls.verify(listener).start(onNext(20)); // merge inner to take
<add> calls.verify(listener).start(onNext(20)); // take to output
<add> calls.verify(listener, times(3)).complete(any());
<add> calls.verify(listener).start(onCompleted()); // sub from completes
<add> // calls.verify(listener).start(unsubscribe()); // merge's composite subscription
<add> // unnecessarily calls unsubscribe during the removing the subscription from the array.
<add> //
<add> // i didn't include it because it could cause a test failure if the internals change.
<add> calls.verify(listener, times(5)).complete(any()); // pop the call stack up to onNext(1)
<add> calls.verify(listener).start(onNext(3)); // from to map
<add> calls.verify(listener).start(onNext(Observable.class)); // map to merge
<add> calls.verify(listener).start(subscribe());
<add> calls.verify(listener).start(onNext(30)); // next from to merge inner
<add> calls.verify(listener).start(onNext(30)); // merge inner to take
<add> calls.verify(listener).start(onNext(30)); // take to output
<add> calls.verify(listener).complete(any());
<add> calls.verify(listener).start(onCompleted()); // take to output
<add> calls.verify(listener).start(unsubscribe()); // take unsubscribes
<add> calls.verify(listener).complete(any());
<add> calls.verify(listener).start(unsubscribe()); // merge inner unsubscribes
<add> calls.verify(listener).complete(any());
<add> calls.verify(listener).start(unsubscribe()); // merge outer unsubscribes
<add> calls.verify(listener).complete(any());
<add> calls.verify(listener).start(unsubscribe()); // map unsubscribe
<add> calls.verify(listener, times(7)).complete(any());
<add> calls.verifyNoMoreInteractions();
<add>
<add> listener.assertValidState();
<add> }
<add>
<add> private static <T> DebugNotification<T> onNext(final T value) {
<add> return argThat(new BaseMatcher<DebugNotification<T>>() {
<ide> @Override
<del> public Observable<Integer> call(Integer it) {
<del> return Observable.from(Arrays.asList(it, it + 1));
<add> public boolean matches(Object item) {
<add> if (item instanceof DebugNotification) {
<add> @SuppressWarnings("unchecked")
<add> DebugNotification<T> dn = (DebugNotification<T>) item;
<add> return dn.getKind() == Kind.OnNext && dn.getValue().equals(value);
<add> }
<add> return false;
<ide> }
<del> }).take(3).subscribe(new Subscriber<Integer>() {
<add>
<ide> @Override
<del> public void onCompleted() {
<add> public void describeTo(Description description) {
<add> description.appendText("OnNext " + value);
<ide> }
<add> });
<add> }
<ide>
<add> private static <T> DebugNotification<T> onNext(final Class<T> type) {
<add> return argThat(new BaseMatcher<DebugNotification<T>>() {
<ide> @Override
<del> public void onError(Throwable e) {
<add> public boolean matches(Object item) {
<add> if (item instanceof DebugNotification) {
<add> @SuppressWarnings("unchecked")
<add> DebugNotification<T> dn = (DebugNotification<T>) item;
<add> return dn.getKind() == Kind.OnNext && type.isAssignableFrom(dn.getValue().getClass());
<add> }
<add> return false;
<ide> }
<ide>
<ide> @Override
<del> public void onNext(Integer t) {
<add> public void describeTo(Description description) {
<add> description.appendText("OnNext " + type);
<ide> }
<ide> });
<del> verify(start, atLeast(3)).call(subscribe());
<del> verify(start, times(4)).call(onNext(1));
<del> // one less because it originates from the inner observable sent to merge
<del> verify(start, times(3)).call(onNext(2));
<del> verify(start, times(4)).call(onNext(3));
<del> // because the take unsubscribes
<del> verify(start, never()).call(onNext(4));
<del>
<del> verify(complete, atLeast(14)).call(any());
<del>
<del> verify(error, never()).call(any(), any(Throwable.class));
<ide> }
<ide>
<del> private static <T, C> DebugNotification<T, C> onNext(final T value) {
<del> return argThat(new BaseMatcher<DebugNotification<T, C>>() {
<add> private static <T> DebugNotification subscribe() {
<add> return argThat(new BaseMatcher<DebugNotification<T>>() {
<ide> @Override
<ide> public boolean matches(Object item) {
<ide> if (item instanceof DebugNotification) {
<del> DebugNotification<T, C> dn = (DebugNotification<T, C>) item;
<del> return dn.getKind() == Kind.OnNext && dn.getValue().equals(value);
<add> DebugNotification dn = (DebugNotification) item;
<add> return dn.getKind() == DebugNotification.Kind.Subscribe;
<ide> }
<ide> return false;
<ide> }
<ide>
<ide> @Override
<ide> public void describeTo(Description description) {
<del> description.appendText("OnNext " + value);
<add> description.appendText("Subscribe");
<ide> }
<ide> });
<ide> }
<ide>
<del> private static DebugNotification subscribe() {
<del> return argThat(new BaseMatcher<DebugNotification>() {
<add> private static <T> DebugNotification unsubscribe() {
<add> return argThat(new BaseMatcher<DebugNotification<T>>() {
<ide> @Override
<ide> public boolean matches(Object item) {
<ide> if (item instanceof DebugNotification) {
<ide> DebugNotification dn = (DebugNotification) item;
<del> return dn.getKind() == DebugNotification.Kind.Subscribe;
<add> return dn.getKind() == DebugNotification.Kind.Unsubscribe;
<ide> }
<ide> return false;
<ide> }
<ide>
<ide> @Override
<ide> public void describeTo(Description description) {
<del> description.appendText("Subscribe");
<add> description.appendText("Unsubscribe");
<ide> }
<ide> });
<ide> }
<ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> import java.util.concurrent.TimeUnit;
<ide>
<ide> import rx.exceptions.Exceptions;
<del>import rx.exceptions.OnErrorThrowable;
<ide> import rx.exceptions.OnErrorNotImplementedException;
<add>import rx.exceptions.OnErrorThrowable;
<ide> import rx.functions.Action0;
<ide> import rx.functions.Action1;
<ide> import rx.functions.Action2;
<ide> import rx.observables.ConnectableObservable;
<ide> import rx.observables.GroupedObservable;
<ide> import rx.observers.SafeSubscriber;
<del>import rx.operators.*;
<add>import rx.operators.OnSubscribeFromIterable;
<add>import rx.operators.OnSubscribeRange;
<add>import rx.operators.OperationAll;
<add>import rx.operators.OperationAmb;
<add>import rx.operators.OperationAny;
<add>import rx.operators.OperationAsObservable;
<add>import rx.operators.OperationAverage;
<add>import rx.operators.OperationBuffer;
<add>import rx.operators.OperationCache;
<add>import rx.operators.OperationCombineLatest;
<add>import rx.operators.OperationConcat;
<add>import rx.operators.OperationDebounce;
<add>import rx.operators.OperationDefaultIfEmpty;
<add>import rx.operators.OperationDefer;
<add>import rx.operators.OperationDelay;
<add>import rx.operators.OperationDematerialize;
<add>import rx.operators.OperationDistinct;
<add>import rx.operators.OperationDistinctUntilChanged;
<add>import rx.operators.OperationElementAt;
<add>import rx.operators.OperationFinally;
<add>import rx.operators.OperationFlatMap;
<add>import rx.operators.OperationGroupByUntil;
<add>import rx.operators.OperationGroupJoin;
<add>import rx.operators.OperationInterval;
<add>import rx.operators.OperationJoin;
<add>import rx.operators.OperationJoinPatterns;
<add>import rx.operators.OperationMaterialize;
<add>import rx.operators.OperationMergeDelayError;
<add>import rx.operators.OperationMergeMaxConcurrent;
<add>import rx.operators.OperationMinMax;
<add>import rx.operators.OperationMulticast;
<add>import rx.operators.OperationOnErrorResumeNextViaObservable;
<add>import rx.operators.OperationOnErrorReturn;
<add>import rx.operators.OperationOnExceptionResumeNextViaObservable;
<add>import rx.operators.OperationParallelMerge;
<add>import rx.operators.OperationReplay;
<add>import rx.operators.OperationSample;
<add>import rx.operators.OperationSequenceEqual;
<add>import rx.operators.OperationSingle;
<add>import rx.operators.OperationSkip;
<add>import rx.operators.OperationSkipLast;
<add>import rx.operators.OperationSkipUntil;
<add>import rx.operators.OperationSkipWhile;
<add>import rx.operators.OperationSum;
<add>import rx.operators.OperationSwitch;
<add>import rx.operators.OperationSynchronize;
<add>import rx.operators.OperationTakeLast;
<add>import rx.operators.OperationTakeTimed;
<add>import rx.operators.OperationTakeUntil;
<add>import rx.operators.OperationTakeWhile;
<add>import rx.operators.OperationThrottleFirst;
<add>import rx.operators.OperationTimeInterval;
<add>import rx.operators.OperationTimer;
<add>import rx.operators.OperationToMap;
<add>import rx.operators.OperationToMultimap;
<add>import rx.operators.OperationToObservableFuture;
<add>import rx.operators.OperationUsing;
<add>import rx.operators.OperationWindow;
<add>import rx.operators.OperatorCast;
<add>import rx.operators.OperatorDoOnEach;
<add>import rx.operators.OperatorFilter;
<add>import rx.operators.OperatorGroupBy;
<add>import rx.operators.OperatorMap;
<add>import rx.operators.OperatorMerge;
<add>import rx.operators.OperatorObserveOn;
<add>import rx.operators.OperatorOnErrorFlatMap;
<add>import rx.operators.OperatorOnErrorResumeNextViaFunction;
<add>import rx.operators.OperatorParallel;
<add>import rx.operators.OperatorRepeat;
<add>import rx.operators.OperatorRetry;
<add>import rx.operators.OperatorScan;
<add>import rx.operators.OperatorSkip;
<add>import rx.operators.OperatorSubscribeOn;
<add>import rx.operators.OperatorTake;
<add>import rx.operators.OperatorTimeout;
<add>import rx.operators.OperatorTimeoutWithSelector;
<add>import rx.operators.OperatorTimestamp;
<add>import rx.operators.OperatorToObservableList;
<add>import rx.operators.OperatorToObservableSortedList;
<add>import rx.operators.OperatorUnsubscribeOn;
<add>import rx.operators.OperatorZip;
<add>import rx.operators.OperatorZipIterable;
<ide> import rx.plugins.RxJavaObservableExecutionHook;
<ide> import rx.plugins.RxJavaPlugins;
<ide> import rx.schedulers.Schedulers;
<ide> */
<ide> public class Observable<T> {
<ide>
<del> final OnSubscribe<T> f;
<add> final OnSubscribe<T> onSubscribe;
<ide>
<ide> /**
<ide> * Observable with Function to execute when subscribed to.
<ide> * {@link OnSubscribe} to be executed when {@link #subscribe(Subscriber)} is called
<ide> */
<ide> protected Observable(OnSubscribe<T> f) {
<del> this.f = hook.onCreate(f);
<add> this.onSubscribe = f;
<ide> }
<ide>
<del> private final static RxJavaObservableExecutionHook hook = RxJavaPlugins.getInstance().getObservableExecutionHook();
<add> private final RxJavaObservableExecutionHook hook = RxJavaPlugins.getInstance().getObservableExecutionHook();
<ide>
<ide> /**
<ide> * Returns an Observable that will execute the specified function when a {@link Subscriber} subscribes to
<ide> public <R> Observable<R> lift(final Operator<? extends R, ? super T> lift) {
<ide> @Override
<ide> public void call(Subscriber<? super R> o) {
<ide> try {
<del> f.call(hook.onLift(lift).call(o));
<add> onSubscribe.call(hook.onLift(lift).call(o));
<ide> } catch (Throwable e) {
<ide> // localized capture of errors rather than it skipping all operators
<ide> // and ending up in the try/catch of the subscribe method which then
<ide> public void onNext(T t) {
<ide> */
<ide> public final Subscription subscribe(Subscriber<? super T> observer) {
<ide> // allow the hook to intercept and/or decorate
<del> OnSubscribe<T> onSubscribeFunction = hook.onSubscribeStart(this, f);
<add> OnSubscribe<T> onSubscribeFunction = hook.onSubscribeStart(this, onSubscribe);
<ide> // validate and proceed
<ide> if (observer == null) {
<ide> throw new IllegalArgumentException("observer can not be null");
<ide> public final Subscription subscribe(Subscriber<? super T> observer) {
<ide> observer = new SafeSubscriber<T>(observer);
<ide> onSubscribeFunction.call(observer);
<ide> }
<del> final Subscription returnSubscription = hook.onSubscribeReturn(this, observer);
<add> final Subscription returnSubscription = hook.onSubscribeReturn(observer);
<ide> // we return it inside a Subscription so it can't be cast back to Subscriber
<ide> return Subscriptions.create(new Action0() {
<ide>
<ide> public void call() {
<ide> Exceptions.throwIfFatal(e);
<ide> // if an unhandled error occurs executing the onSubscribe we will propagate it
<ide> try {
<del> observer.onError(hook.onSubscribeError(this, e));
<add> observer.onError(hook.onSubscribeError(e));
<ide> } catch (OnErrorNotImplementedException e2) {
<ide> // special handling when onError is not implemented ... we just rethrow
<ide> throw e2;
<ide> } catch (Throwable e2) {
<ide> // if this happens it means the onError itself failed (perhaps an invalid function implementation)
<ide> // so we are unable to propagate the error correctly and will just throw
<ide> RuntimeException r = new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2);
<del> hook.onSubscribeError(this, r);
<add> // TODO could the hook be the cause of the error in the on error handling.
<add> hook.onSubscribeError(r);
<add> // TODO why aren't we throwing the hook's return value.
<ide> throw r;
<ide> }
<ide> return Subscriptions.empty();
<ide><path>rxjava-core/src/main/java/rx/functions/Actions.java
<ide> private Actions() {
<ide> throw new IllegalStateException("No instances!");
<ide> }
<ide>
<del> public static final EmptyAction empty() {
<del> return EMPTY_ACTION;
<add> @SuppressWarnings("unchecked")
<add> public static final <T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> EmptyAction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> empty() {
<add> return (EmptyAction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>) EMPTY_ACTION;
<ide> }
<ide>
<ide> private static final EmptyAction EMPTY_ACTION = new EmptyAction();
<ide>
<del> private static final class EmptyAction implements Action0, Action1, Action2, Action3, Action4, Action5, Action6, Action7, Action8, Action9, ActionN {
<add> private static final class EmptyAction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> implements
<add> Action0,
<add> Action1<T0>,
<add> Action2<T0, T1>,
<add> Action3<T0, T1, T2>,
<add> Action4<T0, T1, T2, T3>,
<add> Action5<T0, T1, T2, T3, T4>,
<add> Action6<T0, T1, T2, T3, T4, T5>,
<add> Action7<T0, T1, T2, T3, T4, T5, T6>,
<add> Action8<T0, T1, T2, T3, T4, T5, T6, T7>,
<add> Action9<T0, T1, T2, T3, T4, T5, T6, T7, T8>,
<add> ActionN {
<ide> @Override
<ide> public void call() {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1) {
<add> public void call(T0 t1) {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1, Object t2) {
<add> public void call(T0 t1, T1 t2) {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1, Object t2, Object t3) {
<add> public void call(T0 t1, T1 t2, T2 t3) {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1, Object t2, Object t3, Object t4) {
<add> public void call(T0 t1, T1 t2, T2 t3, T3 t4) {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1, Object t2, Object t3, Object t4, Object t5) {
<add> public void call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5) {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1, Object t2, Object t3, Object t4, Object t5, Object t6) {
<add> public void call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5, T5 t6) {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1, Object t2, Object t3, Object t4, Object t5, Object t6, Object t7) {
<add> public void call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5, T5 t6, T6 t7) {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1, Object t2, Object t3, Object t4, Object t5, Object t6, Object t7, Object t8) {
<add> public void call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5, T5 t6, T6 t7, T7 t8) {
<ide> }
<ide>
<ide> @Override
<del> public void call(Object t1, Object t2, Object t3, Object t4, Object t5, Object t6, Object t7, Object t8, Object t9) {
<add> public void call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5, T5 t6, T6 t7, T7 t8, T8 t9) {
<ide> }
<ide>
<ide> @Override
<ide><path>rxjava-core/src/main/java/rx/functions/Functions.java
<ide> public Boolean call(Object o) {
<ide> return false;
<ide> }
<ide> }
<add>
<add> @SuppressWarnings("unchecked")
<add> public static <T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, R> NullFunction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, R> returnNull() {
<add> return (NullFunction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, R>) NULL_FUNCTION;
<add> }
<add>
<add> private static final NullFunction NULL_FUNCTION = new NullFunction();
<add>
<add> private static final class NullFunction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, R> implements
<add> Func0<R>,
<add> Func1<T0, R>,
<add> Func2<T0, T1, R>,
<add> Func3<T0, T1, T2, R>,
<add> Func4<T0, T1, T2, T3, R>,
<add> Func5<T0, T1, T2, T3, T4, R>,
<add> Func6<T0, T1, T2, T3, T4, T5, R>,
<add> Func7<T0, T1, T2, T3, T4, T5, T6, R>,
<add> Func8<T0, T1, T2, T3, T4, T5, T6, T7, R>,
<add> Func9<T0, T1, T2, T3, T4, T5, T6, T7, T8, R>,
<add> FuncN<R> {
<add> @Override
<add> public R call() {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1, T1 t2) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1, T1 t2, T2 t3) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1, T1 t2, T2 t3, T3 t4) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5, T5 t6) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5, T5 t6, T6 t7) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5, T5 t6, T6 t7, T7 t8) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(T0 t1, T1 t2, T2 t3, T3 t4, T4 t5, T5 t6, T6 t7, T7 t8, T8 t9) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public R call(Object... args) {
<add> return null;
<add> }
<add> }
<ide> }
<ide><path>rxjava-core/src/main/java/rx/operators/OnSubscribeFromIterable.java
<ide> public void call(Subscriber<? super T> o) {
<ide> }
<ide> o.onNext(i);
<ide> }
<add> if (o.isUnsubscribed()) {
<add> return;
<add> }
<ide> o.onCompleted();
<ide> }
<ide>
<ide><path>rxjava-core/src/main/java/rx/plugins/RxJavaObservableExecutionHook.java
<ide>
<ide> import rx.Observable;
<ide> import rx.Observable.OnSubscribe;
<del>import rx.Observable.OnSubscribeFunc;
<ide> import rx.Observable.Operator;
<ide> import rx.Subscriber;
<ide> import rx.Subscription;
<ide> import rx.functions.Func1;
<ide>
<ide> /**
<del> * Abstract ExecutionHook with invocations at different lifecycle points of {@link Observable} execution with a default no-op implementation.
<add> * Abstract ExecutionHook with invocations at different lifecycle points of {@link Observable}
<add> * execution with a default no-op implementation.
<ide> * <p>
<ide> * See {@link RxJavaPlugins} or the RxJava GitHub Wiki for information on configuring plugins: <a
<del> * href="https://github.com/Netflix/RxJava/wiki/Plugins">https://github.com/Netflix/RxJava/wiki/Plugins</a>.
<add> * href ="https://github.com/Netflix/RxJava/wiki/Plugins">https://github.com/Netflix/RxJava/wiki/
<add> * Plugins </a>.
<ide> * <p>
<ide> * <b>Note on thread-safety and performance</b>
<ide> * <p>
<del> * A single implementation of this class will be used globally so methods on this class will be invoked concurrently from multiple threads so all functionality must be thread-safe.
<add> * A single implementation of this class will be used globally so methods on this class will be
<add> * invoked concurrently from multiple threads so all functionality must be thread-safe.
<ide> * <p>
<del> * Methods are also invoked synchronously and will add to execution time of the observable so all behavior should be fast. If anything time-consuming is to be done it should be spawned asynchronously
<del> * onto separate worker threads.
<add> * Methods are also invoked synchronously and will add to execution time of the observable so all
<add> * behavior should be fast. If anything time-consuming is to be done it should be spawned
<add> * asynchronously onto separate worker threads.
<ide> *
<del> * */
<add> */
<ide> public abstract class RxJavaObservableExecutionHook {
<add> /**
<add> * Invoked during the construction by {@link Observable#create(OnSubscribe)}
<add> * <p>
<add> * This can be used to decorate or replace the <code>onSubscribe</code> function or just perform
<add> * extra logging, metrics and other such things and pass-thru the function.
<add> *
<add> * @param onSubscribe
<add> * original {@link OnSubscribe}<{@code T}> to be executed
<add> * @return {@link OnSubscribe}<{@code T}> function that can be modified, decorated, replaced or
<add> * just returned as a pass-thru.
<add> */
<add> public <T> OnSubscribe<T> onCreate(OnSubscribe<T> f) {
<add> return f;
<add> }
<add>
<ide> /**
<ide> * Invoked before {@link Observable#subscribe(rx.Subscriber)} is about to be executed.
<ide> * <p>
<del> * This can be used to decorate or replace the <code>onSubscribe</code> function or just perform extra logging, metrics and other such things and pass-thru the function.
<add> * This can be used to decorate or replace the <code>onSubscribe</code> function or just perform
<add> * extra logging, metrics and other such things and pass-thru the function.
<ide> *
<del> * @param observableInstance
<del> * The executing {@link Observable} instance.
<ide> * @param onSubscribe
<del> * original {@link Func1}<{@link Subscriber}{@code <T>}, {@link Subscription}> to be executed
<del> * @return {@link Func1}<{@link Subscriber}{@code <T>}, {@link Subscription}> function that can be modified, decorated, replaced or just returned as a pass-thru.
<add> * original {@link OnSubscribe}<{@code T}> to be executed
<add> * @return {@link OnSubscribe}<{@code T}> function that can be modified, decorated, replaced or
<add> * just returned as a pass-thru.
<ide> */
<del> public <T> OnSubscribe<T> onSubscribeStart(Observable<? extends T> observableInstance, final OnSubscribe<T> onSubscribe) {
<add> public <T> OnSubscribe<T> onSubscribeStart(Observable<? extends T> observableInsance, final OnSubscribe<T> onSubscribe) {
<ide> // pass-thru by default
<ide> return onSubscribe;
<ide> }
<ide>
<ide> /**
<del> * Invoked after successful execution of {@link Observable#subscribe(rx.Subscriber)} with returned {@link Subscription}.
<add> * Invoked after successful execution of {@link Observable#subscribe(rx.Subscriber)} with
<add> * returned {@link Subscription}.
<ide> * <p>
<del> * This can be used to decorate or replace the {@link Subscription} instance or just perform extra logging, metrics and other such things and pass-thru the subscription.
<add> * This can be used to decorate or replace the {@link Subscription} instance or just perform
<add> * extra logging, metrics and other such things and pass-thru the subscription.
<ide> *
<del> * @param observableInstance
<del> * The executing {@link Observable} instance.
<ide> * @param subscription
<ide> * original {@link Subscription}
<del> * @return {@link Subscription} subscription that can be modified, decorated, replaced or just returned as a pass-thru.
<add> * @return {@link Subscription} subscription that can be modified, decorated, replaced or just
<add> * returned as a pass-thru.
<ide> */
<del> public <T> Subscription onSubscribeReturn(Observable<? extends T> observableInstance, Subscription subscription) {
<add> public <T> Subscription onSubscribeReturn(Subscription subscription) {
<ide> // pass-thru by default
<ide> return subscription;
<ide> }
<ide>
<ide> /**
<del> * Invoked after failed execution of {@link Observable#subscribe(Subscriber)} with thrown Throwable.
<add> * Invoked after failed execution of {@link Observable#subscribe(Subscriber)} with thrown
<add> * Throwable.
<ide> * <p>
<del> * This is NOT errors emitted via {@link Subscriber#onError(Throwable)} but exceptions thrown when attempting
<del> * to subscribe to a {@link Func1}<{@link Subscriber}{@code <T>}, {@link Subscription}>.
<add> * This is NOT errors emitted via {@link Subscriber#onError(Throwable)} but exceptions thrown
<add> * when attempting to subscribe to a {@link Func1}<{@link Subscriber}{@code <T>},
<add> * {@link Subscription}>.
<ide> *
<del> * @param observableInstance
<del> * The executing {@link Observable} instance.
<ide> * @param e
<ide> * Throwable thrown by {@link Observable#subscribe(Subscriber)}
<ide> * @return Throwable that can be decorated, replaced or just returned as a pass-thru.
<ide> */
<del> public <T> Throwable onSubscribeError(Observable<? extends T> observableInstance, Throwable e) {
<add> public <T> Throwable onSubscribeError(Throwable e) {
<ide> // pass-thru by default
<ide> return e;
<ide> }
<ide>
<del> public <T> OnSubscribe<T> onCreate(OnSubscribe<T> f) {
<del> return f;
<del> }
<del>
<del> public <T, R> Operator<? extends R, ? super T> onLift(final Operator<? extends R, ? super T> bind) {
<del> return bind;
<del> }
<del>
<del> public <T> Subscription onAdd(Subscriber<T> subscriber, Subscription s) {
<del> return s;
<add> /**
<add> * Invoked just as the operator functions is called to bind two operations together into a new
<add> * {@link Observable} and the return value is used as the lifted function
<add> * <p>
<add> * This can be used to decorate or replace the {@link Operator} instance or just perform extra
<add> * logging, metrics and other such things and pass-thru the onSubscribe.
<add> *
<add> * @param lift
<add> * original {@link Operator}{@code<R, T>} ' * @return {@link Operator}{@code <R, T>}
<add> * function that can be modified, decorated, replaced or
<add> * just returned as a pass-thru.
<add> */
<add> public <T, R> Operator<? extends R, ? super T> onLift(final Operator<? extends R, ? super T> lift) {
<add> return lift;
<ide> }
<ide> } | 11 |
Text | Text | add facebook group to readme.md | 48ac4cdfbaef15b9ca5cad6f571c4ad5e76fca1d | <ide><path>README.md
<ide> This code is running live at [freeCodeCamp.org](https://www.freecodecamp.org).
<ide>
<ide> Our community also has:
<ide>
<del>- A super active [forum](https://www.freecodecamp.org/forum)
<del>- Thousands of [local study groups](https://study-group-directory.freecodecamp.org/) around the world, where you can code together in person
<del>- Medium's [largest technical publication](https://medium.freecodecamp.org)
<del>- A popular [YouTube channel](https://youtube.com/freecodecamp)
<add>- A [forum](https://www.freecodecamp.org/forum) where you can usually get programming help or project feedback within hours.
<add>- A [YouTube channel](https://youtube.com/freecodecamp) with free courses on Python, SQL, Android, and a wide variety of other technologies.
<add>- [Local study groups](https://study-group-directory.freecodecamp.org/) around the world, where you can code together in person
<ide> - A comprehensive [guide to thousands of programming topics](https://guide.freecodecamp.org/)
<add>- Medium's [largest technical publication](https://medium.freecodecamp.org)
<add>- A [Facebook group](https://www.facebook.com/groups/freeCodeCampEarth/permalink/428140994253892/) with over 100,000 members worldwide
<ide>
<ide> ### [Join our community here](https://www.freecodecamp.org/signin).
<ide> | 1 |
Java | Java | add more maybe operators 9/09-1 | db8b73317d662336ffabbb8285b1395ca977b890 | <ide><path>src/main/java/io/reactivex/Maybe.java
<ide> public static <T, R> Maybe<R> zipArray(Function<? super Object[], ? extends R> z
<ide> // Instance methods
<ide> // ------------------------------------------------------------------
<ide>
<add> /**
<add> * Mirrors the MaybeSource (current or provided) that first signals an event.
<add> * <p>
<add> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param other
<add> * a MaybeSource competing to react first
<add> * @return a Maybe that emits the same sequence as whichever of the source MaybeSources first
<add> * signalled
<add> * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a>
<add> */
<add> @SuppressWarnings("unchecked")
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Maybe<T> ambWith(MaybeSource<? extends T> other) {
<add> ObjectHelper.requireNonNull(other, "other is null");
<add> return ambArray(this, other);
<add> }
<add>
<ide> /**
<ide> * Waits in a blocking fashion until the current Maybe signals a success value (which is returned),
<ide> * null if completed or an exception (which is propagated).
<ide> public static <T, R> Maybe<R> zipArray(Function<? super Object[], ? extends R> z
<ide> * </dl>
<ide> * @return the success value
<ide> */
<del> public T blockingGet() {
<add> public final T blockingGet() {
<ide> BlockingObserver<T> observer = new BlockingObserver<T>();
<ide> subscribe(observer);
<ide> return observer.blockingGet();
<ide> public T blockingGet() {
<ide> * @param defaultValue the default item to return if this Maybe is empty
<ide> * @return the success value
<ide> */
<del> public T blockingGet(T defaultValue) {
<add> public final T blockingGet(T defaultValue) {
<ide> ObjectHelper.requireNonNull(defaultValue, "defaultValue is null");
<ide> BlockingObserver<T> observer = new BlockingObserver<T>();
<ide> subscribe(observer);
<ide> return observer.blockingGet(defaultValue);
<ide> }
<ide>
<add> /**
<add> * Returns a Maybe that subscribes to this Maybe lazily, caches its event
<add> * and replays it, to all the downstream subscribers.
<add> * <p>
<add> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cache.png" alt="">
<add> * <p>
<add> * The operator subscribes only when the first downstream subscriber subscribes and maintains
<add> * a single subscription towards this Maybe.
<add> * <p>
<add> * <em>Note:</em> You sacrifice the ability to unsubscribe from the origin when you use the {@code cache}.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code cache} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @return a Flowable that, when first subscribed to, caches all of its items and notifications for the
<add> * benefit of subsequent subscribers
<add> * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a>
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Maybe<T> cache() {
<add> return new MaybeCache<T>(this);
<add> }
<add>
<ide> /**
<ide> * Casts the success value of the current Maybe into the target type or signals a
<ide> * ClassCastException if not compatible.
<ide> public final <R> Maybe<R> concatMap(Function<? super T, ? extends MaybeSource<?
<ide> return RxJavaPlugins.onAssembly(new MaybeFlatten<T, R>(this, mapper));
<ide> }
<ide>
<add>
<add> /**
<add> * Returns a Flowable that emits the items emitted from the current MaybeSource, then the next, one after
<add> * the other, without interleaving them.
<add> * <p>
<add> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.png" alt="">
<add> * <dl>
<add> * <dt><b>Backpressure:</b></dt>
<add> * <dd>The operator honors backpressure from downstream.</dd>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param other
<add> * a MaybeSource to be concatenated after the current
<add> * @return a Flowable that emits items emitted by the two source MaybeSources, one after the other,
<add> * without interleaving them
<add> * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a>
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Flowable<T> concatWith(MaybeSource<? extends T> other) {
<add> ObjectHelper.requireNonNull(other, "other is null");
<add> return concat(this, other);
<add> }
<add>
<add> /**
<add> * Returns a Single that emits a Boolean that indicates whether the source Publisher emitted a
<add> * specified item.
<add> * <p>
<add> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/contains.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code contains} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param item
<add> * the item to search for in the emissions from the source Maybe, not null
<add> * @return a Single that emits {@code true} if the specified item is emitted by the source Maybe,
<add> * or {@code false} if the source Maybe completes without emitting that item
<add> * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a>
<add> */
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Single<Boolean> contains(final Object item) {
<add> ObjectHelper.requireNonNull(item, "item is null");
<add> return RxJavaPlugins.onAssembly(new MaybeContains<T>(this, item));
<add> }
<add>
<add> /**
<add> * Returns a Maybe that counts the total number of items emitted (0 or 1) by the source Maybe and emits
<add> * this count as a 64-bit Long.
<add> * <p>
<add> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/longCount.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code countLong} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @return a Single that emits a single item: the number of items emitted by the source Publisher as a
<add> * 64-bit Long item
<add> * @see <a href="http://reactivex.io/documentation/operators/count.html">ReactiveX operators documentation: Count</a>
<add> * @see #count()
<add> */
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Single<Long> count() {
<add> return RxJavaPlugins.onAssembly(new MaybeCount<T>(this));
<add> }
<add>
<add> /**
<add> * Returns a Maybe that emits the item emitted by the source Maybe or a specified default item
<add> * if the source Maybe is empty.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/defaultIfEmpty.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code defaultIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param defaultItem
<add> * the item to emit if the source Maybe emits no items
<add> * @return a Maybe that emits either the specified default item if the source Maybe emits no
<add> * items, or the items emitted by the source Maybe
<add> * @see <a href="http://reactivex.io/documentation/operators/defaultifempty.html">ReactiveX operators documentation: DefaultIfEmpty</a>
<add> */
<add> @BackpressureSupport(BackpressureKind.FULL)
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Maybe<T> defaultIfEmpty(T defaultItem) {
<add> ObjectHelper.requireNonNull(defaultItem, "item is null");
<add> return switchIfEmpty(just(defaultItem));
<add> }
<add>
<add>
<add> /**
<add> * Returns a Maybe that signals the events emitted by the source Maybe shifted forward in time by a
<add> * specified delay.
<add> * <p>
<add> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>This version of {@code delay} operates by default on the {@code computation} {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param delay
<add> * the delay to shift the source by
<add> * @param unit
<add> * the {@link TimeUnit} in which {@code period} is defined
<add> * @return the new Maybe instance
<add> * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
<add> */
<add> @SchedulerSupport(SchedulerSupport.COMPUTATION)
<add> public final Maybe<T> delay(long delay, TimeUnit unit) {
<add> return delay(delay, unit, Schedulers.computation());
<add> }
<add>
<add> /**
<add> * Returns a Maybe that signals the events emitted by the source Maybe shifted forward in time by a
<add> * specified delay running on the specified Scheduler.
<add> * <p>
<add> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.s.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>you specify which {@link Scheduler} this operator will use</dd>
<add> * </dl>
<add> *
<add> * @param delay
<add> * the delay to shift the source by
<add> * @param unit
<add> * the time unit of {@code delay}
<add> * @param scheduler
<add> * the {@link Scheduler} to use for delaying
<add> * @return the new Maybe instance
<add> * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
<add> */
<add> @SchedulerSupport(SchedulerSupport.CUSTOM)
<add> public final Maybe<T> delay(long delay, TimeUnit unit, Scheduler scheduler) {
<add> ObjectHelper.requireNonNull(unit, "unit is null");
<add> ObjectHelper.requireNonNull(scheduler, "scheduler is null");
<add> return RxJavaPlugins.onAssembly(new MaybeDelay<T>(this, Math.max(0L, delay), unit, scheduler));
<add> }
<add>
<ide> /**
<ide> * Registers an {@link Action} to be called when this Maybe invokes either
<ide> * {@link MaybeObserver#onComplete onSuccess},
<ide> public final <E extends MaybeObserver<? super T>> E subscribeWith(E observer) {
<ide> return observer;
<ide> }
<ide>
<add> /**
<add> * Returns a Maybe that emits the items emitted by the source Maybe or the items of an alternate
<add> * MaybeSource if the current Maybe is empty.
<add> * <p/>
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param other
<add> * the alternate MaybeSource to subscribe to if the main does not emit any items
<add> * @return a Maybe that emits the items emitted by the source Maybe or the items of an
<add> * alternate MaybeSource if the source Maybe is empty.
<add> */
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Maybe<T> switchIfEmpty(MaybeSource<? extends T> other) {
<add> ObjectHelper.requireNonNull(other, "other is null");
<add> return RxJavaPlugins.onAssembly(new MaybeSwitchIfEmpty<T>(this, other));
<add> }
<add>
<add>
<add> /**
<add> * Waits until this and the other MaybeSource signal a success value then applies the given BiFunction
<add> * to those values and emits the BiFunction's resulting value to downstream.
<add> *
<add> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
<add> *
<add> * <p>If either this or the other MaybeSource is empty or signals an error, the resulting Maybe will
<add> * terminate immediately and dispose the other source.
<add> *
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code zipWith} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param <U>
<add> * the type of items emitted by the {@code other} Publisher
<add> * @param <R>
<add> * the type of items emitted by the resulting Publisher
<add> * @param other
<add> * the other Publisher
<add> * @param zipper
<add> * a function that combines the pairs of items from the two Publishers to generate the items to
<add> * be emitted by the resulting Publisher
<add> * @return the new Maybe instance
<add> * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
<add> */
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final <U, R> Maybe<R> zipWith(MaybeSource<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) {
<add> ObjectHelper.requireNonNull(other, "other is null");
<add> return zip(this, other, zipper);
<add> }
<ide>
<ide> // ------------------------------------------------------------------
<ide> // Test helper
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDetach.java
<ide>
<ide> import org.reactivestreams.*;
<ide>
<del>import io.reactivex.internal.subscribers.flowable.EmptyComponent;
<ide> import io.reactivex.internal.subscriptions.SubscriptionHelper;
<add>import io.reactivex.internal.util.EmptyComponent;
<ide>
<ide> public final class FlowableDetach<T> extends AbstractFlowableWithUpstream<T, T> {
<ide>
<ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeCache.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import java.util.concurrent.atomic.*;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposable;
<add>
<add>/**
<add> * Consumes the source once and replays its signal to any current or future MaybeObservers.
<add> *
<add> * @param <T> the value type
<add> */
<add>public final class MaybeCache<T> extends Maybe<T> implements MaybeObserver<T> {
<add>
<add> @SuppressWarnings("rawtypes")
<add> static final CacheDisposable[] EMPTY = new CacheDisposable[0];
<add>
<add> @SuppressWarnings("rawtypes")
<add> static final CacheDisposable[] TERMINATED = new CacheDisposable[0];
<add>
<add> final AtomicReference<MaybeSource<T>> source;
<add>
<add> final AtomicReference<CacheDisposable<T>[]> observers;
<add>
<add> T value;
<add>
<add> Throwable error;
<add>
<add> @SuppressWarnings("unchecked")
<add> public MaybeCache(MaybeSource<T> source) {
<add> this.source = new AtomicReference<MaybeSource<T>>(source);
<add> this.observers = new AtomicReference<CacheDisposable<T>[]>(EMPTY);
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super T> observer) {
<add> CacheDisposable<T> parent = new CacheDisposable<T>(observer, this);
<add> observer.onSubscribe(parent);
<add>
<add> if (add(parent)) {
<add> if (parent.isDisposed()) {
<add> remove(parent);
<add> return;
<add> }
<add> } else {
<add> if (!parent.isDisposed()) {
<add> Throwable ex = error;
<add> if (ex != null) {
<add> observer.onError(ex);
<add> } else {
<add> T v = value;
<add> if (v != null) {
<add> observer.onSuccess(v);
<add> } else {
<add> observer.onComplete();
<add> }
<add> }
<add> }
<add> return;
<add> }
<add>
<add> MaybeSource<T> src = source.getAndSet(null);
<add> if (src != null) {
<add> src.subscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> // deliberately ignored
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Override
<add> public void onSuccess(T value) {
<add> this.value = value;
<add> for (CacheDisposable<T> inner : observers.getAndSet(TERMINATED)) {
<add> if (!inner.isDisposed()) {
<add> inner.actual.onSuccess(value);
<add> }
<add> }
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Override
<add> public void onError(Throwable e) {
<add> this.error = e;
<add> for (CacheDisposable<T> inner : observers.getAndSet(TERMINATED)) {
<add> if (!inner.isDisposed()) {
<add> inner.actual.onError(e);
<add> }
<add> }
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Override
<add> public void onComplete() {
<add> for (CacheDisposable<T> inner : observers.getAndSet(TERMINATED)) {
<add> if (!inner.isDisposed()) {
<add> inner.actual.onComplete();
<add> }
<add> }
<add> }
<add>
<add> boolean add(CacheDisposable<T> inner) {
<add> for (;;) {
<add> CacheDisposable<T>[] a = observers.get();
<add> if (a == TERMINATED) {
<add> return false;
<add> }
<add> int n = a.length;
<add>
<add> @SuppressWarnings("unchecked")
<add> CacheDisposable<T>[] b = new CacheDisposable[n + 1];
<add> System.arraycopy(a, 0, b, 0, n);
<add> b[n] = inner;
<add> if (observers.compareAndSet(a, b)) {
<add> return true;
<add> }
<add> }
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> void remove(CacheDisposable<T> inner) {
<add> for (;;) {
<add> CacheDisposable<T>[] a = observers.get();
<add> int n = a.length;
<add> if (n == 0) {
<add> return;
<add> }
<add>
<add> int j = -1;
<add>
<add> for (int i = 0; i < n; i++) {
<add> if (a[i] == inner) {
<add> j = i;
<add> break;
<add> }
<add> }
<add>
<add> if (j < 0) {
<add> return;
<add> }
<add>
<add> CacheDisposable<T>[] b;
<add> if (n == 1) {
<add> b = EMPTY;
<add> } else {
<add> b = new CacheDisposable[n - 1];
<add> System.arraycopy(a, 0, b, 0, j);
<add> System.arraycopy(a, j + 1, b, j, n - j - 1);
<add> }
<add> if (observers.compareAndSet(a, b)) {
<add> return;
<add> }
<add> }
<add> }
<add>
<add> static final class CacheDisposable<T>
<add> extends AtomicReference<MaybeCache<T>>
<add> implements Disposable {
<add> /** */
<add> private static final long serialVersionUID = -5791853038359966195L;
<add>
<add> final MaybeObserver<? super T> actual;
<add>
<add> public CacheDisposable(MaybeObserver<? super T> actual, MaybeCache<T> parent) {
<add> super(parent);
<add> this.actual = actual;
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> MaybeCache<T> mc = getAndSet(null);
<add> if (mc != null) {
<add> mc.remove(this);
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return get() == null;
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeContains.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<add>import io.reactivex.internal.fuseable.HasUpstreamMaybeSource;
<add>
<add>/**
<add> * Signals true if the source signals a value that is object-equals with the provided
<add> * value, false otherwise or for empty sources.
<add> *
<add> * @param <T> the value type
<add> */
<add>public final class MaybeContains<T> extends Single<Boolean> implements HasUpstreamMaybeSource<T> {
<add>
<add> final MaybeSource<T> source;
<add>
<add> final Object value;
<add>
<add> public MaybeContains(MaybeSource<T> source, Object value) {
<add> this.source = source;
<add> this.value = value;
<add> }
<add>
<add> @Override
<add> public MaybeSource<T> source() {
<add> return source;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(SingleObserver<? super Boolean> observer) {
<add> source.subscribe(new ContainsMaybeObserver(observer, value));
<add> }
<add>
<add> static final class ContainsMaybeObserver implements MaybeObserver<Object>, Disposable {
<add>
<add> final SingleObserver<? super Boolean> actual;
<add>
<add> final Object value;
<add>
<add> Disposable d;
<add>
<add> public ContainsMaybeObserver(SingleObserver<? super Boolean> actual, Object value) {
<add> this.actual = actual;
<add> this.value = value;
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> d.dispose();
<add> d = DisposableHelper.DISPOSED;
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return d.isDisposed();
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> if (DisposableHelper.validate(this.d, d)) {
<add> this.d = d;
<add> actual.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(Object value) {
<add> d = DisposableHelper.DISPOSED;
<add> actual.onSuccess(ObjectHelper.equals(value, this.value));
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> d = DisposableHelper.DISPOSED;
<add> actual.onError(e);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> d = DisposableHelper.DISPOSED;
<add> actual.onSuccess(false);
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeCount.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.fuseable.HasUpstreamMaybeSource;
<add>
<add>/**
<add> * Singals 1L if the source signalled an item or 0L if the source is empty.
<add> *
<add> * @param <T> the source value type
<add> */
<add>public final class MaybeCount<T> extends Single<Long> implements HasUpstreamMaybeSource<T> {
<add>
<add> final MaybeSource<T> source;
<add>
<add> public MaybeCount(MaybeSource<T> source) {
<add> this.source = source;
<add> }
<add>
<add> @Override
<add> public MaybeSource<T> source() {
<add> return source;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(SingleObserver<? super Long> observer) {
<add> source.subscribe(new CountMaybeObserver(observer));
<add> }
<add>
<add> static final class CountMaybeObserver implements MaybeObserver<Object>, Disposable {
<add> final SingleObserver<? super Long> actual;
<add>
<add> Disposable d;
<add>
<add> public CountMaybeObserver(SingleObserver<? super Long> actual) {
<add> this.actual = actual;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> if (DisposableHelper.validate(this.d, d)) {
<add> this.d = d;
<add>
<add> actual.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(Object value) {
<add> d = DisposableHelper.DISPOSED;
<add> actual.onSuccess(1L);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> d = DisposableHelper.DISPOSED;
<add> actual.onError(e);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> d = DisposableHelper.DISPOSED;
<add> actual.onSuccess(0L);
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return d.isDisposed();
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> d.dispose();
<add> d = DisposableHelper.DISPOSED;
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeDelay.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>
<add>/**
<add> * Delays all signal types by the given amount and re-emits them on the given scheduler.
<add> *
<add> * @param <T> the value type
<add> */
<add>public final class MaybeDelay<T> extends AbstractMaybeWithUpstream<T, T> {
<add>
<add> final long delay;
<add>
<add> final TimeUnit unit;
<add>
<add> final Scheduler scheduler;
<add>
<add> public MaybeDelay(MaybeSource<T> source, long delay, TimeUnit unit, Scheduler scheduler) {
<add> super(source);
<add> this.delay = delay;
<add> this.unit = unit;
<add> this.scheduler = scheduler;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super T> observer) {
<add> source.subscribe(new DelayMaybeObserver<T>(observer, delay, unit, scheduler));
<add> }
<add>
<add> static final class DelayMaybeObserver<T>
<add> extends AtomicReference<Disposable>
<add> implements MaybeObserver<T>, Disposable, Runnable {
<add> /** */
<add> private static final long serialVersionUID = 5566860102500855068L;
<add>
<add> final MaybeObserver<? super T> actual;
<add>
<add> final long delay;
<add>
<add> final TimeUnit unit;
<add>
<add> final Scheduler scheduler;
<add>
<add> T value;
<add>
<add> Throwable error;
<add>
<add> public DelayMaybeObserver(MaybeObserver<? super T> actual, long delay, TimeUnit unit, Scheduler scheduler) {
<add> this.actual = actual;
<add> this.delay = delay;
<add> this.unit = unit;
<add> this.scheduler = scheduler;
<add> }
<add>
<add> @Override
<add> public void run() {
<add> Throwable ex = error;
<add> if (ex != null) {
<add> actual.onError(ex);
<add> } else {
<add> T v = value;
<add> if (v != null) {
<add> actual.onSuccess(v);
<add> } else {
<add> actual.onComplete();
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> DisposableHelper.dispose(this);
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return DisposableHelper.isDisposed(get());
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> if (DisposableHelper.setOnce(this, d)) {
<add> actual.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(T value) {
<add> this.value = value;
<add> schedule();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> this.error = e;
<add> schedule();
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> schedule();
<add> }
<add>
<add> void schedule() {
<add> DisposableHelper.replace(this, scheduler.scheduleDirect(this, delay, unit));
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmpty.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>
<add>/**
<add> * Subscribes to the other source if the main source is empty.
<add> *
<add> * @param <T> the value type
<add> */
<add>public final class MaybeSwitchIfEmpty<T> extends AbstractMaybeWithUpstream<T, T> {
<add>
<add> final MaybeSource<? extends T> other;
<add>
<add> public MaybeSwitchIfEmpty(MaybeSource<T> source, MaybeSource<? extends T> other) {
<add> super(source);
<add> this.other = other;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super T> observer) {
<add> source.subscribe(new SwitchIfEmptyMaybeObserver<T>(observer, other));
<add> }
<add>
<add> static final class SwitchIfEmptyMaybeObserver<T>
<add> extends AtomicReference<Disposable>
<add> implements MaybeObserver<T>, Disposable {
<add> /** */
<add> private static final long serialVersionUID = -2223459372976438024L;
<add>
<add> final MaybeObserver<? super T> actual;
<add>
<add> final MaybeSource<? extends T> other;
<add>
<add> public SwitchIfEmptyMaybeObserver(MaybeObserver<? super T> actual, MaybeSource<? extends T> other) {
<add> this.actual = actual;
<add> this.other = other;
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> DisposableHelper.dispose(this);
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return DisposableHelper.isDisposed(get());
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> if (DisposableHelper.setOnce(this, d)) {
<add> actual.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(T value) {
<add> actual.onSuccess(value);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> actual.onError(e);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> Disposable d = get();
<add> if (d != DisposableHelper.DISPOSED) {
<add> if (compareAndSet(d, null)) {
<add> other.subscribe(new OtherMaybeObserver<T>(actual, this));
<add> }
<add> }
<add> }
<add>
<add> static final class OtherMaybeObserver<T> implements MaybeObserver<T> {
<add>
<add> final MaybeObserver<? super T> actual;
<add>
<add> final AtomicReference<Disposable> parent;
<add> public OtherMaybeObserver(MaybeObserver<? super T> actual, AtomicReference<Disposable> parent) {
<add> this.actual = actual;
<add> this.parent = parent;
<add> }
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.setOnce(parent, d);
<add> }
<add> @Override
<add> public void onSuccess(T value) {
<add> actual.onSuccess(value);
<add> }
<add> @Override
<add> public void onError(Throwable e) {
<add> actual.onError(e);
<add> }
<add> @Override
<add> public void onComplete() {
<add> actual.onComplete();
<add> }
<add> }
<add>
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDetach.java
<ide> import io.reactivex.*;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.internal.disposables.DisposableHelper;
<del>import io.reactivex.internal.subscribers.flowable.EmptyComponent;
<add>import io.reactivex.internal.util.EmptyComponent;
<ide>
<ide> /**
<ide> * Breaks the links between the upstream and the downstream (the Disposable and
<add><path>src/main/java/io/reactivex/internal/util/EmptyComponent.java
<del><path>src/main/java/io/reactivex/internal/subscribers/flowable/EmptyComponent.java
<ide> * the License for the specific language governing permissions and limitations under the License.
<ide> */
<ide>
<del>package io.reactivex.internal.subscribers.flowable;
<add>package io.reactivex.internal.util;
<ide>
<ide> import org.reactivestreams.*;
<ide>
<del>import io.reactivex.Observer;
<add>import io.reactivex.*;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<ide> /**
<ide> * Singleton implementing many interfaces as empty.
<ide> */
<del>public enum EmptyComponent implements Subscriber<Object>, Observer<Object>, Subscription, Disposable {
<add>public enum EmptyComponent implements Subscriber<Object>, Observer<Object>, MaybeObserver<Object>,
<add>SingleObserver<Object>, CompletableObserver, Subscription, Disposable {
<ide> INSTANCE;
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> public void onError(Throwable t) {
<ide> public void onComplete() {
<ide> // deliberately no-op
<ide> }
<add>
<add> @Override
<add> public void onSuccess(Object value) {
<add> // deliberately no-op
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/PublicFinalMethods.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex;
<add>
<add>import static org.junit.Assert.fail;
<add>
<add>import java.lang.reflect.*;
<add>
<add>import org.junit.Test;
<add>
<add>/**
<add> * Verifies that instance methods of the base reactive classes are all declared final.
<add> */
<add>public class PublicFinalMethods {
<add>
<add> static void scan(Class<?> clazz) {
<add> for (Method m : clazz.getMethods()) {
<add> if (m.getDeclaringClass() == clazz) {
<add> if ((m.getModifiers() & Modifier.STATIC) == 0) {
<add> if ((m.getModifiers() & (Modifier.PUBLIC | Modifier.FINAL)) == Modifier.PUBLIC) {
<add> fail("Not final: " + m);
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void flowable() {
<add> scan(Flowable.class);
<add> }
<add>
<add> @Test
<add> public void observable() {
<add> scan(Observable.class);
<add> }
<add>
<add> @Test
<add> public void single() {
<add> scan(Single.class);
<add> }
<add>
<add> @Test
<add> public void completable() {
<add> scan(Completable.class);
<add> }
<add>
<add> @Test
<add> public void maybe() {
<add> scan(Maybe.class);
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/TestHelper.java
<ide>
<ide> import io.reactivex.disposables.*;
<ide> import io.reactivex.exceptions.CompositeException;
<del>import io.reactivex.functions.Consumer;
<add>import io.reactivex.functions.*;
<ide> import io.reactivex.internal.fuseable.SimpleQueue;
<ide> import io.reactivex.internal.subscriptions.BooleanSubscription;
<del>import io.reactivex.internal.util.ExceptionHelper;
<add>import io.reactivex.internal.util.*;
<ide> import io.reactivex.observers.TestObserver;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.subscribers.TestSubscriber;
<ide> public static void doubleOnSubscribe(MaybeObserver<?> subscriber) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Checks if the upstream's Disposable sent through the onSubscribe reports
<add> * isDisposed properly before and after calling dispose.
<add> * @param source the source to test
<add> */
<add> public static void checkDisposed(Maybe<?> source) {
<add> final Boolean[] b = { null, null };
<add> final CountDownLatch cdl = new CountDownLatch(1);
<add> source.subscribe(new MaybeObserver<Object>() {
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> try {
<add> b[0] = d.isDisposed();
<add>
<add> d.dispose();
<add>
<add> b[1] = d.isDisposed();
<add> } finally {
<add> cdl.countDown();
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(Object value) {
<add> // ignored
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> // ignored
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> // ignored
<add> }
<add> });
<add>
<add> try {
<add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
<add> } catch (InterruptedException ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> }
<add>
<add> assertEquals("Reports disposed upfront?", false, b[0]);
<add> assertEquals("Didn't report disposed after?", true, b[1]);
<add> }
<add>
<add> /**
<add> * Checks if the upstream's Disposable sent through the onSubscribe reports
<add> * isDisposed properly before and after calling dispose.
<add> * @param source the source to test
<add> */
<add> public static void checkDisposed(Single<?> source) {
<add> final Boolean[] b = { null, null };
<add> final CountDownLatch cdl = new CountDownLatch(1);
<add> source.subscribe(new SingleObserver<Object>() {
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> try {
<add> b[0] = d.isDisposed();
<add>
<add> d.dispose();
<add>
<add> b[1] = d.isDisposed();
<add> } finally {
<add> cdl.countDown();
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(Object value) {
<add> // ignored
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> // ignored
<add> }
<add> });
<add>
<add> try {
<add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
<add> } catch (InterruptedException ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> }
<add>
<add> assertEquals("Reports disposed upfront?", false, b[0]);
<add> assertEquals("Didn't report disposed after?", true, b[1]);
<add> }
<add>
<add> /**
<add> * Checks if the upstream's Disposable sent through the onSubscribe reports
<add> * isDisposed properly before and after calling dispose.
<add> * @param source the source to test
<add> */
<add> public static void checkDisposed(Completable source) {
<add> final Boolean[] b = { null, null };
<add> final CountDownLatch cdl = new CountDownLatch(1);
<add> source.subscribe(new CompletableObserver() {
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> try {
<add> b[0] = d.isDisposed();
<add>
<add> d.dispose();
<add>
<add> b[1] = d.isDisposed();
<add> } finally {
<add> cdl.countDown();
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> // ignored
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> // ignored
<add> }
<add> });
<add>
<add> try {
<add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
<add> } catch (InterruptedException ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> }
<add>
<add> assertEquals("Reports disposed upfront?", false, b[0]);
<add> assertEquals("Didn't report disposed after?", true, b[1]);
<add> }
<add>
<add> enum NoOpConsumer implements Subscriber<Object>, Observer<Object>, MaybeObserver<Object>, SingleObserver<Object>, CompletableObserver {
<add> INSTANCE;
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> // deliberately no-op
<add> }
<add>
<add> @Override
<add> public void onSuccess(Object value) {
<add> // deliberately no-op
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> // deliberately no-op
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> // deliberately no-op
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Subscription s) {
<add> // deliberately no-op
<add> }
<add>
<add> @Override
<add> public void onNext(Object t) {
<add> // deliberately no-op
<add> }
<add> }
<add>
<add> /**
<add> * Check if the given transformed reactive type reports multiple onSubscribe calls to
<add> * RxJavaPlugins.
<add> * @param <T> the input value type
<add> * @param <R> the output value type
<add> * @param transform the transform to drive an operator
<add> */
<add> public static <T, R> void checkDoubleOnSubscribeMaybe(Function<Maybe<T>, ? extends MaybeSource<R>> transform) {
<add> List<Throwable> errors = trackPluginErrors();
<add> try {
<add> final Boolean[] b = { null, null };
<add> final CountDownLatch cdl = new CountDownLatch(1);
<add>
<add> Maybe<T> source = new Maybe<T>() {
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super T> observer) {
<add> try {
<add> Disposable d1 = Disposables.empty();
<add>
<add> observer.onSubscribe(d1);
<add>
<add> Disposable d2 = Disposables.empty();
<add>
<add> observer.onSubscribe(d2);
<add>
<add> b[0] = d1.isDisposed();
<add> b[1] = d2.isDisposed();
<add> } finally {
<add> cdl.countDown();
<add> }
<add> }
<add> };
<add>
<add> MaybeSource<R> out = transform.apply(source);
<add>
<add> out.subscribe(NoOpConsumer.INSTANCE);
<add>
<add> try {
<add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
<add> } catch (InterruptedException ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> }
<add>
<add> assertEquals("First disposed?", false, b[0]);
<add> assertEquals("Second not disposed?", true, b[1]);
<add>
<add> assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
<add> } catch (Throwable ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add>
<add> /**
<add> * Check if the given transformed reactive type reports multiple onSubscribe calls to
<add> * RxJavaPlugins.
<add> * @param <T> the input value type
<add> * @param <R> the output value type
<add> * @param transform the transform to drive an operator
<add> */
<add> public static <T, R> void checkDoubleOnSubscribeMaybeToSingle(Function<Maybe<T>, ? extends SingleSource<R>> transform) {
<add> List<Throwable> errors = trackPluginErrors();
<add> try {
<add> final Boolean[] b = { null, null };
<add> final CountDownLatch cdl = new CountDownLatch(1);
<add>
<add> Maybe<T> source = new Maybe<T>() {
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super T> observer) {
<add> try {
<add> Disposable d1 = Disposables.empty();
<add>
<add> observer.onSubscribe(d1);
<add>
<add> Disposable d2 = Disposables.empty();
<add>
<add> observer.onSubscribe(d2);
<add>
<add> b[0] = d1.isDisposed();
<add> b[1] = d2.isDisposed();
<add> } finally {
<add> cdl.countDown();
<add> }
<add> }
<add> };
<add>
<add> SingleSource<R> out = transform.apply(source);
<add>
<add> out.subscribe(NoOpConsumer.INSTANCE);
<add>
<add> try {
<add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
<add> } catch (InterruptedException ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> }
<add>
<add> assertEquals("First disposed?", false, b[0]);
<add> assertEquals("Second not disposed?", true, b[1]);
<add>
<add> assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
<add> } catch (Throwable ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add> /**
<add> * Check if the given transformed reactive type reports multiple onSubscribe calls to
<add> * RxJavaPlugins.
<add> * @param <T> the input value type
<add> * @param <R> the output value type
<add> * @param transform the transform to drive an operator
<add> */
<add> public static <T, R> void checkDoubleOnSubscribeSingle(Function<Single<T>, ? extends SingleSource<R>> transform) {
<add> List<Throwable> errors = trackPluginErrors();
<add> try {
<add> final Boolean[] b = { null, null };
<add> final CountDownLatch cdl = new CountDownLatch(1);
<add>
<add> Single<T> source = new Single<T>() {
<add> @Override
<add> protected void subscribeActual(SingleObserver<? super T> observer) {
<add> try {
<add> Disposable d1 = Disposables.empty();
<add>
<add> observer.onSubscribe(d1);
<add>
<add> Disposable d2 = Disposables.empty();
<add>
<add> observer.onSubscribe(d2);
<add>
<add> b[0] = d1.isDisposed();
<add> b[1] = d2.isDisposed();
<add> } finally {
<add> cdl.countDown();
<add> }
<add> }
<add> };
<add>
<add> SingleSource<R> out = transform.apply(source);
<add>
<add> out.subscribe(NoOpConsumer.INSTANCE);
<add>
<add> try {
<add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
<add> } catch (InterruptedException ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> }
<add>
<add> assertEquals("First disposed?", false, b[0]);
<add> assertEquals("Second not disposed?", true, b[1]);
<add>
<add> assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
<add> } catch (Throwable ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> /**
<add> * Check if the given transformed reactive type reports multiple onSubscribe calls to
<add> * RxJavaPlugins.
<add> * @param transform the transform to drive an operator
<add> */
<add> public static void checkDoubleOnSubscribeCompletable(Function<Completable, ? extends CompletableSource> transform) {
<add> List<Throwable> errors = trackPluginErrors();
<add> try {
<add> final Boolean[] b = { null, null };
<add> final CountDownLatch cdl = new CountDownLatch(1);
<add>
<add> Completable source = new Completable() {
<add> @Override
<add> protected void subscribeActual(CompletableObserver observer) {
<add> try {
<add> Disposable d1 = Disposables.empty();
<add>
<add> observer.onSubscribe(d1);
<add>
<add> Disposable d2 = Disposables.empty();
<add>
<add> observer.onSubscribe(d2);
<add>
<add> b[0] = d1.isDisposed();
<add> b[1] = d2.isDisposed();
<add> } finally {
<add> cdl.countDown();
<add> }
<add> }
<add> };
<add>
<add> CompletableSource out = transform.apply(source);
<add>
<add> out.subscribe(NoOpConsumer.INSTANCE);
<add>
<add> try {
<add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS));
<add> } catch (InterruptedException ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> }
<add>
<add> assertEquals("First disposed?", false, b[0]);
<add> assertEquals("Second not disposed?", true, b[1]);
<add>
<add> assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
<add> } catch (Throwable ex) {
<add> throw ExceptionHelper.wrapOrThrow(ex);
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeCacheTest.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.processors.PublishProcessor;
<add>import io.reactivex.schedulers.Schedulers;
<add>import io.reactivex.subscribers.TestSubscriber;
<add>
<add>public class MaybeCacheTest {
<add>
<add> @Test
<add> public void offlineSuccess() {
<add> Maybe<Integer> source = Maybe.just(1).cache();
<add> assertEquals(1, source.blockingGet().intValue());
<add>
<add> source.test()
<add> .assertResult(1);
<add> }
<add>
<add> @Test
<add> public void offlineError() {
<add> Maybe<Integer> source = Maybe.<Integer>error(new TestException()).cache();
<add>
<add> try {
<add> source.blockingGet();
<add> fail("Should have thrown");
<add> } catch (TestException ex) {
<add> // expected
<add> }
<add>
<add> source.test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add>
<add> @Test
<add> public void offlineComplete() {
<add> Maybe<Integer> source = Maybe.<Integer>empty().cache();
<add>
<add> assertNull(source.blockingGet());
<add>
<add> source.test()
<add> .assertResult();
<add> }
<add>
<add> @Test
<add> public void onlineSuccess() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> assertFalse(pp.hasSubscribers());
<add>
<add> assertNotNull(((MaybeCache<Integer>)source).source.get());
<add>
<add> TestSubscriber<Integer> ts = source.test();
<add>
<add> assertNull(((MaybeCache<Integer>)source).source.get());
<add>
<add> assertTrue(pp.hasSubscribers());
<add>
<add> source.test(true).assertEmpty();
<add>
<add> ts.assertEmpty();
<add>
<add> pp.onNext(1);
<add> pp.onComplete();
<add>
<add> ts.assertResult(1);
<add>
<add> source.test().assertResult(1);
<add>
<add> source.test(true).assertEmpty();
<add> }
<add>
<add> @Test
<add> public void onlineError() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> assertFalse(pp.hasSubscribers());
<add>
<add> assertNotNull(((MaybeCache<Integer>)source).source.get());
<add>
<add> TestSubscriber<Integer> ts = source.test();
<add>
<add> assertNull(((MaybeCache<Integer>)source).source.get());
<add>
<add> assertTrue(pp.hasSubscribers());
<add>
<add> source.test(true).assertEmpty();
<add>
<add> ts.assertEmpty();
<add>
<add> pp.onError(new TestException());
<add>
<add> ts.assertFailure(TestException.class);
<add>
<add> source.test().assertFailure(TestException.class);
<add>
<add> source.test(true).assertEmpty();
<add> }
<add>
<add> @Test
<add> public void onlineComplete() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> assertFalse(pp.hasSubscribers());
<add>
<add> assertNotNull(((MaybeCache<Integer>)source).source.get());
<add>
<add> TestSubscriber<Integer> ts = source.test();
<add>
<add> assertNull(((MaybeCache<Integer>)source).source.get());
<add>
<add> assertTrue(pp.hasSubscribers());
<add>
<add> source.test(true).assertEmpty();
<add>
<add> ts.assertEmpty();
<add>
<add> pp.onComplete();
<add>
<add> ts.assertResult();
<add>
<add> source.test().assertResult();
<add>
<add> source.test(true).assertEmpty();
<add> }
<add>
<add> @Test
<add> public void crossCancelOnSuccess() {
<add>
<add> final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add>
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> source.subscribe(new Consumer<Integer>() {
<add> @Override
<add> public void accept(Integer v) throws Exception {
<add> ts.cancel();
<add> }
<add> });
<add>
<add> source.toFlowable().subscribe(ts);
<add>
<add> pp.onNext(1);
<add> pp.onComplete();
<add>
<add> ts.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void crossCancelOnError() {
<add>
<add> final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add>
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> source.subscribe(Functions.emptyConsumer(), new Consumer<Object>() {
<add> @Override
<add> public void accept(Object v) throws Exception {
<add> ts.cancel();
<add> }
<add> });
<add>
<add> source.toFlowable().subscribe(ts);
<add>
<add> pp.onError(new TestException());
<add>
<add> ts.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void crossCancelOnComplete() {
<add>
<add> final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add>
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> source.subscribe(Functions.emptyConsumer(), Functions.emptyConsumer(), new Action() {
<add> @Override
<add> public void run() throws Exception {
<add> ts.cancel();
<add> }
<add> });
<add>
<add> source.toFlowable().subscribe(ts);
<add>
<add> pp.onComplete();
<add>
<add> ts.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void addAddRace() {
<add> for (int i = 0; i < 500; i++) {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> final Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> Runnable r = new Runnable() {
<add> @Override
<add> public void run() {
<add> source.test();
<add> }
<add> };
<add>
<add> TestHelper.race(r, r, Schedulers.single());
<add> }
<add> }
<add>
<add> @Test
<add> public void removeRemoveRace() {
<add> for (int i = 0; i < 500; i++) {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> final Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> final TestSubscriber<Integer> ts1 = source.test();
<add> final TestSubscriber<Integer> ts2 = source.test();
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ts1.cancel();
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ts2.cancel();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2, Schedulers.single());
<add> }
<add> }
<add>
<add> @Test
<add> public void doubleDispose() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> final Maybe<Integer> source = pp.toMaybe().cache();
<add>
<add> final Disposable[] dout = { null };
<add>
<add> source.subscribe(new MaybeObserver<Integer>() {
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> dout[0] = d;
<add> }
<add>
<add> @Override
<add> public void onSuccess(Integer value) {
<add>
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add>
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add>
<add> }
<add>
<add> });
<add>
<add> dout[0].dispose();
<add> dout[0].dispose();
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeContainsTest.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.fuseable.HasUpstreamMaybeSource;
<add>import io.reactivex.processors.PublishProcessor;
<add>import io.reactivex.subscribers.TestSubscriber;
<add>
<add>public class MaybeContainsTest {
<add>
<add> @Test
<add> public void doesContain() {
<add> Maybe.just(1).contains(1).test().assertResult(true);
<add> }
<add>
<add> @Test
<add> public void doesntContain() {
<add> Maybe.just(1).contains(2).test().assertResult(false);
<add> }
<add>
<add> @Test
<add> public void empty() {
<add> Maybe.empty().contains(2).test().assertResult(false);
<add> }
<add>
<add> @Test
<add> public void error() {
<add> Maybe.error(new TestException()).contains(2).test().assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> TestSubscriber<Boolean> ts = pp.toMaybe().contains(1).test();
<add>
<add> assertTrue(pp.hasSubscribers());
<add>
<add> ts.cancel();
<add>
<add> assertFalse(pp.hasSubscribers());
<add> }
<add>
<add>
<add> @Test
<add> public void isDisposed() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> TestHelper.checkDisposed(pp.toMaybe().contains(1));
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeMaybeToSingle(new Function<Maybe<Object>, SingleSource<Boolean>>() {
<add> @Override
<add> public SingleSource<Boolean> apply(Maybe<Object> f) throws Exception {
<add> return f.contains(1);
<add> }
<add> });
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Test
<add> public void hasSource() {
<add> assertSame(Maybe.empty(), ((HasUpstreamMaybeSource<Object>)(Maybe.empty().contains(0))).source());
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeCountTest.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.fuseable.HasUpstreamMaybeSource;
<add>import io.reactivex.processors.PublishProcessor;
<add>import io.reactivex.subscribers.TestSubscriber;
<add>
<add>public class MaybeCountTest {
<add>
<add> @Test
<add> public void one() {
<add> Maybe.just(1).count().test().assertResult(1L);
<add> }
<add>
<add> @Test
<add> public void empty() {
<add> Maybe.empty().count().test().assertResult(0L);
<add> }
<add>
<add> @Test
<add> public void error() {
<add> Maybe.error(new TestException()).count().test().assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> TestSubscriber<Long> ts = pp.toMaybe().count().test();
<add>
<add> assertTrue(pp.hasSubscribers());
<add>
<add> ts.cancel();
<add>
<add> assertFalse(pp.hasSubscribers());
<add> }
<add>
<add> @Test
<add> public void isDisposed() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> TestHelper.checkDisposed(pp.toMaybe().count());
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeMaybeToSingle(new Function<Maybe<Object>, SingleSource<Long>>() {
<add> @Override
<add> public SingleSource<Long> apply(Maybe<Object> f) throws Exception {
<add> return f.count();
<add> }
<add> });
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Test
<add> public void hasSource() {
<add> assertSame(Maybe.empty(), ((HasUpstreamMaybeSource<Object>)(Maybe.empty().count())).source());
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayTest.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.util.concurrent.TimeUnit;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.processors.PublishProcessor;
<add>import io.reactivex.schedulers.TestScheduler;
<add>import io.reactivex.subscribers.TestSubscriber;
<add>
<add>public class MaybeDelayTest {
<add>
<add> @Test
<add> public void success() {
<add> Maybe.just(1).delay(100, TimeUnit.MILLISECONDS)
<add> .test()
<add> .awaitDone(5, TimeUnit.SECONDS)
<add> .assertResult(1);
<add> }
<add>
<add> @Test
<add> public void error() {
<add> Maybe.error(new TestException()).delay(100, TimeUnit.MILLISECONDS)
<add> .test()
<add> .awaitDone(5, TimeUnit.SECONDS)
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void complete() {
<add> Maybe.empty().delay(100, TimeUnit.MILLISECONDS)
<add> .test()
<add> .awaitDone(5, TimeUnit.SECONDS)
<add> .assertResult();
<add> }
<add>
<add> @Test(expected = NullPointerException.class)
<add> public void nullUnit() {
<add> Maybe.just(1).delay(1, null);
<add> }
<add>
<add> @Test(expected = NullPointerException.class)
<add> public void nullScheduler() {
<add> Maybe.just(1).delay(1, TimeUnit.MILLISECONDS, null);
<add> }
<add>
<add> @Test
<add> public void disposeDuringDelay() {
<add> TestScheduler scheduler = new TestScheduler();
<add>
<add> TestSubscriber<Integer> ts = Maybe.just(1).delay(100, TimeUnit.MILLISECONDS, scheduler)
<add> .test();
<add>
<add> ts.cancel();
<add>
<add> scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
<add>
<add> ts.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> TestSubscriber<Integer> ts = pp.toMaybe().delay(100, TimeUnit.MILLISECONDS).test();
<add>
<add> assertTrue(pp.hasSubscribers());
<add>
<add> ts.cancel();
<add>
<add> assertFalse(pp.hasSubscribers());
<add> }
<add>
<add> @Test
<add> public void isDisposed() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> TestHelper.checkDisposed(pp.toMaybe().delay(100, TimeUnit.MILLISECONDS));
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Object>, Maybe<Object>>() {
<add> @Override
<add> public Maybe<Object> apply(Maybe<Object> f) throws Exception {
<add> return f.delay(100, TimeUnit.MILLISECONDS);
<add> }
<add> });
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptyTest.java
<add>/**
<add> * Copyright 2016 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.processors.PublishProcessor;
<add>import io.reactivex.schedulers.Schedulers;
<add>import io.reactivex.subscribers.TestSubscriber;
<add>
<add>public class MaybeSwitchIfEmptyTest {
<add>
<add> @Test
<add> public void nonEmpty() {
<add> Maybe.just(1).switchIfEmpty(Maybe.just(2)).test().assertResult(1);
<add> }
<add>
<add> @Test
<add> public void empty() {
<add> Maybe.<Integer>empty().switchIfEmpty(Maybe.just(2)).test().assertResult(2);
<add> }
<add>
<add> @Test
<add> public void defaultIfEmptyNonEmpty() {
<add> Maybe.just(1).defaultIfEmpty(2).test().assertResult(1);
<add> }
<add>
<add> @Test
<add> public void defaultIfEmptyEmpty() {
<add> Maybe.<Integer>empty().defaultIfEmpty(2).test().assertResult(2);
<add> }
<add>
<add> @Test
<add> public void error() {
<add> Maybe.<Integer>error(new TestException()).switchIfEmpty(Maybe.just(2))
<add> .test().assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void errorOther() {
<add> Maybe.empty().switchIfEmpty(Maybe.<Integer>error(new TestException()))
<add> .test().assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void emptyOtherToo() {
<add> Maybe.empty().switchIfEmpty(Maybe.empty())
<add> .test().assertResult();
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> TestSubscriber<Integer> ts = pp.toMaybe().switchIfEmpty(Maybe.just(2)).test();
<add>
<add> assertTrue(pp.hasSubscribers());
<add>
<add> ts.cancel();
<add>
<add> assertFalse(pp.hasSubscribers());
<add> }
<add>
<add>
<add> @Test
<add> public void isDisposed() {
<add> PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> TestHelper.checkDisposed(pp.toMaybe().switchIfEmpty(Maybe.just(2)));
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Integer>, Maybe<Integer>>() {
<add> @Override
<add> public Maybe<Integer> apply(Maybe<Integer> f) throws Exception {
<add> return f.switchIfEmpty(Maybe.just(2));
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void emptyCancelRace() {
<add> for (int i = 0; i < 500; i++) {
<add> final PublishProcessor<Integer> pp = PublishProcessor.create();
<add>
<add> final TestSubscriber<Integer> ts = pp.toMaybe().switchIfEmpty(Maybe.just(2)).test();
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> pp.onComplete();
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ts.cancel();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2, Schedulers.single());
<add> }
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/subscribers/flowable/EmptyComponentTest.java
<ide> import io.reactivex.TestHelper;
<ide> import io.reactivex.disposables.*;
<ide> import io.reactivex.exceptions.TestException;
<del>import io.reactivex.internal.subscribers.flowable.EmptyComponent;
<ide> import io.reactivex.internal.subscriptions.BooleanSubscription;
<add>import io.reactivex.internal.util.EmptyComponent;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<ide> public class EmptyComponentTest {
<ide><path>src/test/java/io/reactivex/maybe/MaybeTest.java
<ide> public void zip2() {
<ide> .assertResult("12");
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<add> @Test
<add> public void zipWith() {
<add> Maybe.just(1).zipWith(Maybe.just(2), ArgsToString.INSTANCE)
<add> .test()
<add> .assertResult("12");
<add> }
<add>
<ide> @SuppressWarnings("unchecked")
<ide> @Test
<ide> public void zip3() {
<ide> public void zip9() {
<ide> .test()
<ide> .assertResult("123456789");
<ide> }
<add>
<add>
<add> @Test
<add> public void ambWith1SignalsSuccess() {
<add> PublishProcessor<Integer> pp1 = PublishProcessor.create();
<add> PublishProcessor<Integer> pp2 = PublishProcessor.create();
<add>
<add> TestSubscriber<Integer> ts = pp1.toMaybe().ambWith(pp2.toMaybe())
<add> .test();
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(pp1.hasSubscribers());
<add> assertTrue(pp2.hasSubscribers());
<add>
<add> pp1.onNext(1);
<add> pp1.onComplete();
<add>
<add> assertFalse(pp1.hasSubscribers());
<add> assertFalse(pp2.hasSubscribers());
<add>
<add> ts.assertResult(1);
<add> }
<add>
<add> @Test
<add> public void ambWith2SignalsSuccess() {
<add> PublishProcessor<Integer> pp1 = PublishProcessor.create();
<add> PublishProcessor<Integer> pp2 = PublishProcessor.create();
<add>
<add> TestSubscriber<Integer> ts = pp1.toMaybe().ambWith(pp2.toMaybe())
<add> .test();
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(pp1.hasSubscribers());
<add> assertTrue(pp2.hasSubscribers());
<add>
<add> pp2.onNext(2);
<add> pp2.onComplete();
<add>
<add> assertFalse(pp1.hasSubscribers());
<add> assertFalse(pp2.hasSubscribers());
<add>
<add> ts.assertResult(2);
<add> }
<add>
<ide> } | 18 |
Python | Python | use rpc backend for integration tests | 0a8568ddff20e317ca8039d1ab88f4b453940a5e | <ide><path>t/integration/conftest.py
<ide> def celery_config():
<ide> return {
<ide> 'broker_url': 'pyamqp://',
<del> 'result_backend': 'redis://',
<add> 'result_backend': 'rpc',
<ide> }
<ide>
<ide> | 1 |
Javascript | Javascript | remove max_safe_integer check on length | e6e6b07e512dd4e71b0458cb02901ce6d5398e29 | <ide><path>lib/buffer.js
<ide> function fromArrayBuffer(obj, byteOffset, length) {
<ide> if (length !== length) {
<ide> length = 0;
<ide> } else if (length > 0) {
<del> length = (length < Number.MAX_SAFE_INTEGER ?
<del> length : Number.MAX_SAFE_INTEGER);
<ide> if (length > maxLength)
<ide> throw new RangeError("'length' is out of bounds");
<ide> } else { | 1 |
Javascript | Javascript | evaluate nginit before nginclude | 0e50810c53428f4c1f5bfdba9599df54cb7a6c6e | <ide><path>src/ng/directive/ngInit.js
<ide> * to initialize values on a scope.
<ide> * </div>
<ide> *
<add> * @priority 450
<add> *
<ide> * @element ANY
<ide> * @param {expression} ngInit {@link guide/expression Expression} to eval.
<ide> *
<ide> </doc:example>
<ide> */
<ide> var ngInitDirective = ngDirective({
<add> priority: 450,
<ide> compile: function() {
<ide> return {
<ide> pre: function(scope, element, attrs) {
<ide><path>test/ng/directive/ngInitSpec.js
<ide> describe('ngInit', function() {
<ide> element = $compile('<div ng-init="a=123"></div>')($rootScope);
<ide> expect($rootScope.a).toEqual(123);
<ide> }));
<add>
<add>
<add> it("should be evaluated before ngInclude", inject(function($rootScope, $templateCache, $compile) {
<add> $templateCache.put('template1.tpl', '<span>1</span>');
<add> $templateCache.put('template2.tpl', '<span>2</span>');
<add> $rootScope.template = 'template1.tpl';
<add> element = $compile('<div><div ng-include="template" ' +
<add> 'ng-init="template=\'template2.tpl\'"></div></div>')($rootScope);
<add> $rootScope.$digest();
<add> expect($rootScope.template).toEqual('template2.tpl');
<add> expect(element.find('span').text()).toEqual('2');
<add> }));
<add>
<add>
<add> it("should be evaluated after ngController", function() {
<add> module(function($controllerProvider) {
<add> $controllerProvider.register('TestCtrl', function($scope) {});
<add> });
<add> inject(function($rootScope, $compile) {
<add> element = $compile('<div><div ng-controller="TestCtrl" ' +
<add> 'ng-init="test=123"></div></div>')($rootScope);
<add> $rootScope.$digest();
<add> expect($rootScope.test).toBeUndefined();
<add> expect(element.children('div').scope().test).toEqual(123);
<add> });
<add> });
<ide> }); | 2 |
Javascript | Javascript | move $injector into the providercache | e3e8813e3c586093c79cffe2b17418c0c1797d4a | <ide><path>src/auto/injector.js
<ide> function createInjector(modulesToLoad) {
<ide> decorator: decorator
<ide> }
<ide> },
<del> providerInjector = createInternalInjector(providerCache, function() {
<del> throw Error("Unknown provider: " + path.join(' <- '));
<del> }),
<add> providerInjector = (providerCache.$injector =
<add> createInternalInjector(providerCache, function() {
<add> throw Error("Unknown provider: " + path.join(' <- '));
<add> })),
<ide> instanceCache = {},
<ide> instanceInjector = (instanceCache.$injector =
<ide> createInternalInjector(instanceCache, function(servicename) {
<ide> function createInjector(modulesToLoad) {
<ide> try {
<ide> for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
<ide> var invokeArgs = invokeQueue[i],
<del> provider = invokeArgs[0] == '$injector'
<del> ? providerInjector
<del> : providerInjector.get(invokeArgs[0]);
<add> provider = providerInjector.get(invokeArgs[0]);
<ide>
<ide> provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
<ide> }
<ide><path>test/auto/injectorSpec.js
<ide> describe('injector', function() {
<ide> var providers;
<ide> var injector;
<add> var providerInjector;
<ide>
<del> beforeEach(module(function($provide) {
<add> beforeEach(module(function($provide, $injector) {
<ide> providers = function(name, factory, annotations) {
<ide> $provide.factory(name, extend(factory, annotations||{}));
<ide> };
<add> providerInjector = $injector;
<ide> }));
<ide> beforeEach(inject(function($injector){
<ide> injector = $injector;
<ide> describe('injector', function() {
<ide> });
<ide>
<ide>
<add> it('should create a new $injector for the run phase', inject(function($injector) {
<add> expect($injector).not.toBe(providerInjector);
<add> }));
<add>
<add>
<ide> describe('invoke', function() {
<ide> var args;
<ide>
<ide> describe('injector', function() {
<ide>
<ide>
<ide> it('should decorate the missing service error with module name', function() {
<del> angular.module('TestModule', [], function($injector) {});
<add> angular.module('TestModule', [], function(xyzzy) {});
<ide> expect(function() {
<ide> createInjector(['TestModule']);
<del> }).toThrow('Unknown provider: $injector from TestModule');
<add> }).toThrow('Unknown provider: xyzzy from TestModule');
<ide> });
<ide>
<ide>
<ide> it('should decorate the missing service error with module function', function() {
<del> function myModule($injector){}
<add> function myModule(xyzzy){}
<ide> expect(function() {
<ide> createInjector([myModule]);
<del> }).toThrow('Unknown provider: $injector from ' + myModule);
<add> }).toThrow('Unknown provider: xyzzy from ' + myModule);
<ide> });
<ide>
<ide>
<ide> it('should decorate the missing service error with module array function', function() {
<del> function myModule($injector){}
<add> function myModule(xyzzy){}
<ide> expect(function() {
<del> createInjector([['$injector', myModule]]);
<del> }).toThrow('Unknown provider: $injector from ' + myModule);
<add> createInjector([['xyzzy', myModule]]);
<add> }).toThrow('Unknown provider: xyzzy from ' + myModule);
<ide> });
<ide>
<ide> | 2 |
Javascript | Javascript | add tests for challenge>builduserupdate | 953e1b2e113245186451e53c58afe2828f0afe47 | <ide><path>api-server/server/boot/challenge.js
<ide> const jsProjects = [
<ide> 'aa2e6f85cab2ab736c9a9b24'
<ide> ];
<ide>
<del>function buildUserUpdate(user, challengeId, _completedChallenge, timezone) {
<add>export function buildUserUpdate(
<add> user,
<add> challengeId,
<add> _completedChallenge,
<add> timezone
<add>) {
<ide> const { files } = _completedChallenge;
<ide> let completedChallenge = {};
<del>
<ide> if (jsProjects.includes(challengeId)) {
<ide> completedChallenge = {
<ide> ..._completedChallenge,
<ide><path>api-server/server/boot_tests/challenge.test.js
<ide> /* global describe xdescribe it expect */
<del>import { isEqual } from 'lodash';
<add>import { isEqual, first, find } from 'lodash';
<ide> import sinon from 'sinon';
<ide> import { mockReq, mockRes } from 'sinon-express-mock';
<ide>
<ide> import {
<add> buildUserUpdate,
<ide> buildChallengeUrl,
<ide> createChallengeUrlResolver,
<ide> createRedirectToCurrentChallenge,
<ide> getFirstChallenge,
<ide> isValidChallengeCompletion
<ide> } from '../boot/challenge';
<ide>
<del>const firstChallengeUrl = '/learn/the/first/challenge';
<del>const requestedChallengeUrl = '/learn/my/actual/challenge';
<del>const mockChallenge = {
<del> id: '123abc',
<del> block: 'actual',
<del> superBlock: 'my',
<del> dashedName: 'challenge'
<del>};
<del>const mockFirstChallenge = {
<del> id: '456def',
<del> block: 'first',
<del> superBlock: 'the',
<del> dashedName: 'challenge'
<del>};
<del>const mockUser = {
<del> username: 'camperbot',
<del> currentChallengeId: '123abc'
<del>};
<del>const mockApp = {
<del> models: {
<del> Challenge: {
<del> find() {
<del> return firstChallengeUrl;
<del> },
<del> findById(id, cb) {
<del> return id === mockChallenge.id
<del> ? cb(null, mockChallenge)
<del> : cb(new Error('challenge not found'));
<del> }
<del> }
<del> }
<del>};
<del>const mockGetFirstChallenge = () => firstChallengeUrl;
<del>const firstChallengeQuery = {
<del> // first challenge of the first block of the first superBlock
<del> where: { challengeOrder: 0, superOrder: 1, order: 0 }
<del>};
<add>import {
<add> firstChallengeUrl,
<add> requestedChallengeUrl,
<add> mockChallenge,
<add> mockFirstChallenge,
<add> mockUser,
<add> mockApp,
<add> mockGetFirstChallenge,
<add> firstChallengeQuery,
<add> mockCompletedChallenge,
<add> mockCompletedChallenges
<add>} from './fixtures';
<ide>
<ide> describe('boot/challenge', () => {
<ide> xdescribe('backendChallengeCompleted');
<ide>
<del> xdescribe('buildUserUpdate');
<add> describe('buildUserUpdate', () => {
<add> it('returns an Object with a nested "completedChallenges" property', () => {
<add> const result = buildUserUpdate(
<add> mockUser,
<add> '123abc',
<add> mockCompletedChallenge,
<add> 'UTC'
<add> );
<add> expect(result).toHaveProperty('updateData.$set.completedChallenges');
<add> });
<add>
<add> it('preserves file contents if the completed challenge is a JS Project', () => {
<add> const jsChallengeId = 'aa2e6f85cab2ab736c9a9b24';
<add> const completedChallenge = {
<add> ...mockCompletedChallenge,
<add> completedDate: Date.now(),
<add> id: jsChallengeId
<add> };
<add> const result = buildUserUpdate(
<add> mockUser,
<add> jsChallengeId,
<add> completedChallenge,
<add> 'UTC'
<add> );
<add> const firstCompletedChallenge = first(
<add> result.updateData.$set.completedChallenges
<add> );
<add>
<add> expect(firstCompletedChallenge).toEqual(completedChallenge);
<add> });
<add>
<add> it('preserves the original completed date of a challenge', () => {
<add> const completedChallengeId = 'aaa48de84e1ecc7c742e1124';
<add> const completedChallenge = {
<add> ...mockCompletedChallenge,
<add> completedDate: Date.now(),
<add> id: completedChallengeId
<add> };
<add> const originalCompletion = find(
<add> mockCompletedChallenges,
<add> x => x.id === completedChallengeId
<add> ).completedDate;
<add> const result = buildUserUpdate(
<add> mockUser,
<add> completedChallengeId,
<add> completedChallenge,
<add> 'UTC'
<add> );
<add>
<add> const firstCompletedChallenge = first(
<add> result.updateData.$set.completedChallenges
<add> );
<add>
<add> expect(firstCompletedChallenge.completedDate).toEqual(originalCompletion);
<add> });
<add>
<add> it('does not attempt to update progressTimestamps for a previously completed challenge', () => {
<add> const completedChallengeId = 'aaa48de84e1ecc7c742e1124';
<add> const completedChallenge = {
<add> ...mockCompletedChallenge,
<add> completedDate: Date.now(),
<add> id: completedChallengeId
<add> };
<add> const { updateData } = buildUserUpdate(
<add> mockUser,
<add> completedChallengeId,
<add> completedChallenge,
<add> 'UTC'
<add> );
<add>
<add> const hasProgressTimestamps =
<add> '$push' in updateData && 'progressTimestamps' in updateData.$push;
<add> expect(hasProgressTimestamps).toBe(false);
<add> });
<add>
<add> it('provides a progressTimestamps update for new challenge completion', () => {
<add> expect.assertions(2);
<add> const { updateData } = buildUserUpdate(
<add> mockUser,
<add> '123abc',
<add> mockCompletedChallenge,
<add> 'UTC'
<add> );
<add> expect(updateData).toHaveProperty('$push');
<add> expect(updateData.$push).toHaveProperty('progressTimestamps');
<add> });
<add>
<add> it('removes repeat completions from the completedChallenges array', () => {
<add> const completedChallengeId = 'aaa48de84e1ecc7c742e1124';
<add> const completedChallenge = {
<add> ...mockCompletedChallenge,
<add> completedDate: Date.now(),
<add> id: completedChallengeId
<add> };
<add> const {
<add> updateData: {
<add> $set: { completedChallenges }
<add> }
<add> } = buildUserUpdate(
<add> mockUser,
<add> completedChallengeId,
<add> completedChallenge,
<add> 'UTC'
<add> );
<add>
<add> expect(completedChallenges.length).toEqual(
<add> mockCompletedChallenges.length
<add> );
<add> });
<add>
<add> it('adds newly completed challenges to the completedChallenges array', () => {
<add> const {
<add> updateData: {
<add> $set: { completedChallenges }
<add> }
<add> } = buildUserUpdate(mockUser, '123abc', mockCompletedChallenge, 'UTC');
<add>
<add> expect(completedChallenges.length).toEqual(
<add> mockCompletedChallenges.length + 1
<add> );
<add> });
<add> });
<ide>
<ide> describe('buildChallengeUrl', () => {
<ide> it('resolves the correct Url for the provided challenge', () => {
<ide> describe('boot/challenge', () => {
<ide>
<ide> expect(result).toEqual(firstChallengeUrl);
<ide> });
<add>
<ide> it('returns the learn base if no challenges found', async () => {
<ide> const result = await getFirstChallenge(createMockChallengeModel(false));
<ide>
<ide> describe('boot/challenge', () => {
<ide> });
<ide> });
<ide>
<del> xdescribe('modernChallengeCompleted', () => {});
<add> xdescribe('modernChallengeCompleted');
<ide>
<ide> xdescribe('projectCompleted');
<ide>
<ide><path>api-server/server/boot_tests/fixtures.js
<add>export const firstChallengeUrl = '/learn/the/first/challenge';
<add>export const requestedChallengeUrl = '/learn/my/actual/challenge';
<add>export const mockChallenge = {
<add> id: '123abc',
<add> block: 'actual',
<add> superBlock: 'my',
<add> dashedName: 'challenge'
<add>};
<add>export const mockFirstChallenge = {
<add> id: '456def',
<add> block: 'first',
<add> superBlock: 'the',
<add> dashedName: 'challenge'
<add>};
<add>export const mockCompletedChallenge = {
<add> id: '890xyz',
<add> challengeType: 0,
<add> files: [
<add> {
<add> contents: 'file contents',
<add> key: 'indexfile',
<add> name: 'index',
<add> path: 'index.file',
<add> ext: 'file'
<add> }
<add> ],
<add> completedDate: Date.now()
<add>};
<add>export const mockCompletedChallenges = [
<add> {
<add> id: 'bd7123c8c441eddfaeb5bdef',
<add> completedDate: 1538052380328.0
<add> },
<add> {
<add> id: '587d7dbd367417b2b2512bb4',
<add> completedDate: 1547472893032.0,
<add> files: []
<add> },
<add> {
<add> id: 'aaa48de84e1ecc7c742e1124',
<add> completedDate: 1541678430790.0,
<add> files: [
<add> {
<add> contents:
<add> "function palindrome(str) {\n const clean = str.replace(/[\\W_]/g, '').toLowerCase()\n const revStr = clean.split('').reverse().join('');\n return clean === revStr;\n}\n\n\n\npalindrome(\"eye\");\n",
<add> ext: 'js',
<add> path: 'index.js',
<add> name: 'index',
<add> key: 'indexjs'
<add> }
<add> ]
<add> },
<add> {
<add> id: '5a24c314108439a4d4036164',
<add> completedDate: 1543845124143.0,
<add> files: []
<add> }
<add>];
<add>export const mockUser = {
<add> username: 'camperbot',
<add> currentChallengeId: '123abc',
<add> timezone: 'UTC',
<add> completedChallenges: mockCompletedChallenges
<add>};
<add>export const mockApp = {
<add> models: {
<add> Challenge: {
<add> find() {
<add> return firstChallengeUrl;
<add> },
<add> findById(id, cb) {
<add> return id === mockChallenge.id
<add> ? cb(null, mockChallenge)
<add> : cb(new Error('challenge not found'));
<add> }
<add> }
<add> }
<add>};
<add>export const mockGetFirstChallenge = () => firstChallengeUrl;
<add>export const firstChallengeQuery = {
<add> // first challenge of the first block of the first superBlock
<add> where: { challengeOrder: 0, superOrder: 1, order: 0 }
<add>}; | 3 |
Python | Python | close taskconsumer on reset_connection | 98137ba36d1f922b4967c5d15b71c7288d6565c6 | <ide><path>celery/worker.py
<ide> def __init__(self, concurrency=None, logfile=None, loglevel=None,
<ide> self.reset_connection()
<ide>
<ide> def reset_connection(self):
<add> if hasattr(self, "task_consumer"):
<add> self.task_consumer.close()
<ide> self.task_consumer = TaskConsumer(connection=DjangoAMQPConnection())
<ide>
<ide> def connection_diagnostics(self): | 1 |
Ruby | Ruby | add documentation for add_flash_types [ci skip] | b163754bc55c3d23e62071d39451c2fbe4579e99 | <ide><path>actionpack/lib/action_controller/metal/flash.rb
<ide> module Flash
<ide> end
<ide>
<ide> module ClassMethods
<add> # Creates new flash types. You can pass as many types as you want to create
<add> # flash types other than the default <tt>alert</tt> and <tt>notice</tt> in
<add> # your controllers and views. For instance:
<add> #
<add> # # in application_controller.rb
<add> # class ApplicationController < ActionController::Base
<add> # add_flash_types :warning
<add> # end
<add> #
<add> # # in your controller
<add> # redirect_to user_path(@user), warning: "Incomplete profile"
<add> #
<add> # # in your view
<add> # <%= warning %>
<add> #
<add> # This method will automatically define a new method for each of the given
<add> # names, and it will be available in your views.
<ide> def add_flash_types(*types)
<ide> types.each do |type|
<ide> next if _flash_types.include?(type) | 1 |
Ruby | Ruby | add a test | 2a9a10f5e3d4d8fc607606e700d1fd2dfec4eda2 | <ide><path>activemodel/test/cases/serialization_test.rb
<ide> def test_method_serializable_hash_should_work_with_except_and_methods
<ide> assert_equal expected , @user.serializable_hash(:except => [:name, :email], :methods => [:foo])
<ide> end
<ide>
<add> def test_should_not_call_methods_that_dont_respond
<add> expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com"}
<add> assert_equal expected , @user.serializable_hash(:methods => [:bar])
<add> end
<add>
<ide> end | 1 |
Ruby | Ruby | remove unused method | 45285f56f4993e3910df59e7e68b465a287ef089 | <ide><path>activerecord/lib/active_record/reflection.rb
<ide> def ==(other_aggregation)
<ide> active_record == other_aggregation.active_record
<ide> end
<ide>
<del> def sanitized_conditions #:nodoc:
<del> @sanitized_conditions ||= klass.send(:sanitize_sql, options[:conditions]) if options[:conditions]
<del> end
<del>
<ide> private
<ide> def derive_class_name
<ide> name.to_s.camelize | 1 |
Text | Text | remove references to rails versions | ed78770b1a13788a5d3fcae484f34654de580bd5 | <ide><path>guides/source/action_controller_overview.md
<ide> NOTE: Certain exceptions are only rescuable from the `ApplicationController` cla
<ide> Force HTTPS protocol
<ide> --------------------
<ide>
<del>Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use the `force_ssl` method in your controller to enforce that:
<add>Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. You can use the `force_ssl` method in your controller to enforce that:
<ide>
<ide> ```ruby
<ide> class DinnerController
<ide><path>guides/source/action_mailer_basics.md
<ide> When you call the `mail` method now, Action Mailer will detect the two templates
<ide>
<ide> #### Wire It Up So That the System Sends the Email When a User Signs Up
<ide>
<del>There are several ways to do this, some people create Rails Observers to fire off emails, others do it inside of the User Model. However, in Rails 3, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created.
<add>There are several ways to do this, some people create Rails Observers to fire off emails, others do it inside of the User Model. However, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created.
<ide>
<ide> Setting this up is painfully simple.
<ide>
<ide> This provides a much simpler implementation that does not require the registerin
<ide>
<ide> The method `welcome_email` returns a `Mail::Message` object which can then just be told `deliver` to send itself out.
<ide>
<del>NOTE: In previous versions of Rails, you would call `deliver_welcome_email` or `create_welcome_email`. This has been deprecated in Rails 3.0 in favour of just calling the method name itself.
<del>
<ide> WARNING: Sending out an email should only take a fraction of a second. If you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job.
<ide>
<ide> ### Auto encoding header values
<ide><path>guides/source/action_view_overview.md
<ide> Creates a field set for grouping HTML form elements.
<ide>
<ide> Creates a file upload field.
<ide>
<del>Prior to Rails 3.1, if you are using file uploads, then you will need to set the multipart option for the form tag. Rails 3.1+ does this automatically.
<del>
<ide> ```html+erb
<del><%= form_tag {action: "post"}, {multipart: true} do %>
<add><%= form_tag {action: "post"} do %>
<ide> <label for="file">File to Upload</label> <%= file_field_tag "file" %>
<ide> <%= submit_tag %>
<ide> <% end %>
<ide><path>guides/source/active_record_querying.md
<ide> You can specify an exclamation point (`!`) on the end of the dynamic finders to
<ide>
<ide> If you want to find both by name and locked, you can chain these finders together by simply typing "`and`" between the fields. For example, `Client.find_by_first_name_and_locked("Ryan", true)`.
<ide>
<del>WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say `Client.find_by_name_and_locked("Ryan")`, the behavior is to pass `nil` as the missing argument. This is **unintentional** and this behavior has been changed in Rails 3.2 to throw an `ArgumentError`.
<del>
<ide> Find or Build a New Object
<ide> --------------------------
<ide>
<ide><path>guides/source/active_support_core_extensions.md
<ide> C.subclasses # => [B, D]
<ide>
<ide> The order in which these classes are returned is unspecified.
<ide>
<del>WARNING: This method is redefined in some Rails core classes but should be all compatible in Rails 3.1.
<del>
<ide> NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
<ide>
<ide> #### `descendants`
<ide> Inserting data into HTML templates needs extra care. For example, you can't just
<ide>
<ide> #### Safe Strings
<ide>
<del>Active Support has the concept of <i>(html) safe</i> strings since Rails 3. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
<add>Active Support has the concept of <i>(html) safe</i> strings. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
<ide>
<ide> Strings are considered to be <i>unsafe</i> by default:
<ide>
<ide> Safe arguments are directly appended:
<ide> "".html_safe + "<".html_safe # => "<"
<ide> ```
<ide>
<del>These methods should not be used in ordinary views. In Rails 3 unsafe values are automatically escaped:
<add>These methods should not be used in ordinary views. Unsafe values are automatically escaped:
<ide>
<ide> ```erb
<del><%= @review.title %> <%# fine in Rails 3, escaped if needed %>
<add><%= @review.title %> <%# fine, escaped if needed %>
<ide> ```
<ide>
<ide> To insert something verbatim use the `raw` helper rather than calling `html_safe`:
<ide><path>guides/source/asset_pipeline.md
<ide> The Asset Pipeline
<ide> ==================
<ide>
<del>This guide covers the asset pipeline introduced in Rails 3.1.
<add>This guide covers the asset pipeline.
<ide>
<ide> After reading this guide, you will know:
<ide>
<ide> What is the Asset Pipeline?
<ide>
<ide> The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB.
<ide>
<del>Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 is integrated with Sprockets through Action Pack which depends on the `sprockets` gem, by default.
<del>
<ide> Making the asset pipeline a core feature of Rails means that all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "fast by default" strategy as outlined by DHH in his keynote at RailsConf 2011.
<ide>
<del>In Rails 3.1, the asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition:
<add>The asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition:
<ide>
<ide> ```ruby
<ide> config.assets.enabled = false
<ide> For example, a new Rails application includes a default `app/assets/javascripts/
<ide>
<ide> In JavaScript files, the directives begin with `//=`. In this case, the file is using the `require` and the `require_tree` directives. The `require` directive is used to tell Sprockets the files that you wish to require. Here, you are requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere in the search path for Sprockets. You need not supply the extensions explicitly. Sprockets assumes you are requiring a `.js` file when done from within a `.js` file.
<ide>
<del>NOTE. In Rails 3.1 the `jquery-rails` gem provides the `jquery.js` and `jquery_ujs.js` files via the asset pipeline. You won't see them in the application tree.
<del>
<ide> The `require_tree` directive tells Sprockets to recursively include _all_ JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file. You can also use the `require_directory` directive which includes all JavaScript files only in the directory specified, without recursion.
<ide>
<ide> Directives are processed top to bottom, but the order in which files are included by `require_tree` is unspecified. You should not rely on any particular order among those. If you need to ensure some particular JavaScript ends up above some other in the concatenated file, require the prerequisite file first in the manifest. Note that the family of `require` directives prevents files from being included twice in the output.
<ide> This can be changed to something else:
<ide> config.assets.prefix = "/some_other_path"
<ide> ```
<ide>
<del>This is a handy option if you are updating an existing project (pre Rails 3.1) that already uses this path or you wish to use this path for a new resource.
<add>This is a handy option if you are updating an older project that didn't use the asset pipeline and that already uses this path or you wish to use this path for a new resource.
<ide>
<ide> ### X-Sendfile Headers
<ide>
<ide><path>guides/source/configuring.md
<ide> These configuration methods are to be called on a `Rails::Railtie` object, such
<ide>
<ide> ### Configuring Assets
<ide>
<del>Rails 3.1 and up, by default, is set up to use the `sprockets` gem to manage assets within an application. This gem concatenates and compresses assets in order to make serving them much less painful.
<del>
<ide> * `config.assets.enabled` a flag that controls whether the asset pipeline is enabled. It is explicitly initialized in `config/application.rb`.
<ide>
<ide> * `config.assets.compress` a flag that enables the compression of compiled assets. It is explicitly set to true in `config/production.rb`.
<ide> Rails 3.1 and up, by default, is set up to use the `sprockets` gem to manage ass
<ide>
<ide> ### Configuring Generators
<ide>
<del>Rails 3 allows you to alter what generators are used with the `config.generators` method. This method takes a block:
<add>Rails allows you to alter what generators are used with the `config.generators` method. This method takes a block:
<ide>
<ide> ```ruby
<ide> config.generators do |g|
<ide><path>guides/source/engines.md
<ide> Finally, engines would not have been possible without the work of James Adam, Pi
<ide> Generating an engine
<ide> --------------------
<ide>
<del>To generate an engine with Rails 3.2, you will need to run the plugin generator and pass it options as appropriate to the need. For the "blorgh" example, you will need to create a "mountable" engine, running this command in a terminal:
<add>To generate an engine, you will need to run the plugin generator and pass it options as appropriate to the need. For the "blorgh" example, you will need to create a "mountable" engine, running this command in a terminal:
<ide>
<ide> ```bash
<ide> $ rails plugin new blorgh --mountable
<ide><path>guides/source/form_helpers.md
<ide> The following two forms both upload a file.
<ide> <% end %>
<ide> ```
<ide>
<del>NOTE: Since Rails 3.1, forms rendered using `form_for` have their encoding set to `multipart/form-data` automatically once a `file_field` is used inside the block. Previous versions required you to set this explicitly.
<del>
<ide> Rails provides the usual pair of helpers: the barebones `file_field_tag` and the model oriented `file_field`. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in `params[:picture]` and in the second case in `params[:person][:picture]`.
<ide>
<ide> ### What Gets Uploaded
<ide><path>guides/source/generators.md
<ide> After reading this guide, you will know:
<ide>
<ide> --------------------------------------------------------------------------------
<ide>
<del>NOTE: This guide is about generators in Rails 3, previous versions are not covered.
<del>
<ide> First Contact
<ide> -------------
<ide>
<ide><path>guides/source/layouts_and_rendering.md
<ide> def update
<ide> end
<ide> ```
<ide>
<del>To be explicit, you can use `render` with the `:action` option (though this is no longer necessary in Rails 3.0):
<del>
<del>```ruby
<del>def update
<del> @book = Book.find(params[:id])
<del> if @book.update_attributes(params[:book])
<del> redirect_to(@book)
<del> else
<del> render action: "edit"
<del> end
<del>end
<del>```
<del>
<del>WARNING: Using `render` with `:action` is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does _not_ run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling `render`.
<del>
<ide> #### Rendering an Action's Template from Another Controller
<ide>
<ide> What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with `render`, which accepts the full path (relative to `app/views`) of the template to render. For example, if you're running code in an `AdminProductsController` that lives in `app/controllers/admin`, you can render the results of an action to a template in `app/views/products` this way:
<ide> There are three tag options available for the `auto_discovery_link_tag`:
<ide>
<ide> The `javascript_include_tag` helper returns an HTML `script` tag for each source provided.
<ide>
<del>If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the Sprockets gem, which was introduced in Rails 3.1.
<add>If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the asset pipeline.
<ide>
<ide> A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization)
<ide>
<ide> You can even use dynamic paths such as `cache/#{current_site}/main/display`.
<ide>
<ide> The `image_tag` helper builds an HTML `<img />` tag to the specified file. By default, files are loaded from `public/images`.
<ide>
<del>WARNING: Note that you must specify the extension of the image. Previous versions of Rails would allow you to just use the image name and would append `.png` if no extension was given but Rails 3.0 does not.
<add>WARNING: Note that you must specify the extension of the image.
<ide>
<ide> ```erb
<ide> <%= image_tag "header.png" %>
<ide> Every partial also has a local variable with the same name as the partial (minus
<ide>
<ide> Within the `customer` partial, the `customer` variable will refer to `@new_customer` from the parent view.
<ide>
<del>WARNING: In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior was deprecated in 2.3 and has been removed in Rails 3.0.
<del>
<ide> If you have an instance of a model to render into a partial, you can use a shorthand syntax:
<ide>
<ide> ```erb
<ide> Partials are very useful in rendering collections. When you pass a collection to
<ide>
<ide> When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product`, and within the `_product` partial, you can refer to `product` to get the instance that is being rendered.
<ide>
<del>In Rails 3.0, there is also a shorthand for this. Assuming `@products` is a collection of `product` instances, you can simply write this in the `index.html.erb` to produce the same result:
<add>There is also a shorthand for this. Assuming `@products` is a collection of `product` instances, you can simply write this in the `index.html.erb` to produce the same result:
<ide>
<ide> ```html+erb
<ide> <h1>Products</h1>
<ide><path>guides/source/plugins.md
<ide> goodness.
<ide> Setup
<ide> -----
<ide>
<del>_"vendored plugins"_ were available in previous versions of Rails, but they are deprecated in
<del>Rails 3.2, and will not be available in the future.
<del>
<ide> Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared across
<ide> different rails applications using RubyGems and Bundler if desired.
<ide>
<ide> ### Generate a gemified plugin.
<ide>
<ide>
<del>Rails 3.1 ships with a `rails plugin new` command which creates a
<add>Rails ships with a `rails plugin new` command which creates a
<ide> skeleton for developing any kind of Rails extension with the ability
<ide> to run integration tests using a dummy Rails application. See usage
<ide> and options by asking for help:
<ide><path>guides/source/routing.md
<ide> get '*a/foo/*b', to: 'test#index'
<ide>
<ide> would match `zoo/woo/foo/bar/baz` with `params[:a]` equals `'zoo/woo'`, and `params[:b]` equals `'bar/baz'`.
<ide>
<del>NOTE: Starting from Rails 3.1, wildcard segments will always match the optional format segment by default. For example if you have this route:
<del>
<del>```ruby
<del>get '*pages', to: 'pages#show'
<del>```
<del>
<ide> NOTE: By requesting `'/foo/bar.json'`, your `params[:pages]` will be equals to `'foo/bar'` with the request format of JSON. If you want the old 3.0.x behavior back, you could supply `format: false` like this:
<ide>
<ide> ```ruby | 13 |
Ruby | Ruby | remove dead code | dcabc6c04301a44d875447e4f88534ca04a538d6 | <ide><path>actionpack/lib/action_view/helpers/url_helper.rb
<ide> def convert_options_to_data_attributes(options, html_options)
<ide> html_options['data-remote'] = 'true'
<ide> end
<ide>
<del> confirm = html_options.delete("confirm")
<del> method, href = html_options.delete("method"), html_options['href']
<ide>
<add> confirm = html_options.delete('confirm')
<add> method = html_options.delete('method')
<ide> add_confirm_to_attributes!(html_options, confirm) if confirm
<ide> add_method_to_attributes!(html_options, method) if method
<ide> | 1 |
Go | Go | remove engine.job from create action | 98996a432e079d1434182ea1cf84e70c927da4c2 | <ide><path>api/server/server.go
<ide> func postContainersCreate(eng *engine.Engine, version version.Version, w http.Re
<ide> return err
<ide> }
<ide> var (
<del> job = eng.Job("create", r.Form.Get("name"))
<del> outWarnings []string
<del> stdoutBuffer = bytes.NewBuffer(nil)
<del> warnings = bytes.NewBuffer(nil)
<add> warnings []string
<add> name = r.Form.Get("name")
<add> env = new(engine.Env)
<ide> )
<ide>
<del> if err := job.DecodeEnv(r.Body); err != nil {
<add> if err := env.Decode(r.Body); err != nil {
<ide> return err
<ide> }
<del> // Read container ID from the first line of stdout
<del> job.Stdout.Add(stdoutBuffer)
<del> // Read warnings from stderr
<del> job.Stderr.Add(warnings)
<del> if err := job.Run(); err != nil {
<add>
<add> containerId, warnings, err := getDaemon(eng).ContainerCreate(name, env)
<add> if err != nil {
<ide> return err
<ide> }
<del> // Parse warnings from stderr
<del> scanner := bufio.NewScanner(warnings)
<del> for scanner.Scan() {
<del> outWarnings = append(outWarnings, scanner.Text())
<del> }
<add>
<ide> return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
<del> ID: engine.Tail(stdoutBuffer, 1),
<del> Warnings: outWarnings,
<add> ID: containerId,
<add> Warnings: warnings,
<ide> })
<ide> }
<ide>
<ide><path>daemon/create.go
<ide> import (
<ide> "github.com/docker/libcontainer/label"
<ide> )
<ide>
<del>func (daemon *Daemon) ContainerCreate(job *engine.Job) error {
<del> var name string
<del> if len(job.Args) == 1 {
<del> name = job.Args[0]
<del> } else if len(job.Args) > 1 {
<del> return fmt.Errorf("Usage: %s", job.Name)
<del> }
<add>func (daemon *Daemon) ContainerCreate(name string, env *engine.Env) (string, []string, error) {
<add> var warnings []string
<ide>
<del> config := runconfig.ContainerConfigFromJob(job)
<del> hostConfig := runconfig.ContainerHostConfigFromJob(job.env)
<add> config := runconfig.ContainerConfigFromJob(env)
<add> hostConfig := runconfig.ContainerHostConfigFromJob(env)
<ide>
<ide> if len(hostConfig.LxcConf) > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
<del> return fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
<add> return "", warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
<ide> }
<ide> if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
<del> return fmt.Errorf("Minimum memory limit allowed is 4MB")
<add> return "", warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
<ide> }
<ide> if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
<del> job.Errorf("Your kernel does not support memory limit capabilities. Limitation discarded.\n")
<add> warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.\n")
<ide> hostConfig.Memory = 0
<ide> }
<ide> if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit {
<del> job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n")
<add> warnings = append(warnings, "Your kernel does not support swap limit capabilities. Limitation discarded.\n")
<ide> hostConfig.MemorySwap = -1
<ide> }
<ide> if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
<del> return fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.\n")
<add> return "", warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.\n")
<ide> }
<ide> if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
<del> return fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.\n")
<add> return "", warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.\n")
<ide> }
<ide>
<ide> container, buildWarnings, err := daemon.Create(config, hostConfig, name)
<ide> func (daemon *Daemon) ContainerCreate(job *engine.Job) error {
<ide> if tag == "" {
<ide> tag = graph.DEFAULTTAG
<ide> }
<del> return fmt.Errorf("No such image: %s (tag: %s)", config.Image, tag)
<add> return "", warnings, fmt.Errorf("No such image: %s (tag: %s)", config.Image, tag)
<ide> }
<del> return err
<add> return "", warnings, err
<ide> }
<ide> if !container.Config.NetworkDisabled && daemon.SystemConfig().IPv4ForwardingDisabled {
<del> job.Errorf("IPv4 forwarding is disabled.\n")
<add> warnings = append(warnings, "IPv4 forwarding is disabled.\n")
<ide> }
<del> container.LogEvent("create")
<del>
<del> job.Printf("%s\n", container.ID)
<ide>
<del> for _, warning := range buildWarnings {
<del> job.Errorf("%s\n", warning)
<del> }
<add> container.LogEvent("create")
<add> warnings = append(warnings, buildWarnings...)
<ide>
<del> return nil
<add> return container.ID, warnings, nil
<ide> }
<ide>
<ide> // Create creates a new container from the given configuration with a given name.
<ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> for name, method := range map[string]engine.Handler{
<ide> "container_inspect": daemon.ContainerInspect,
<del> "create": daemon.ContainerCreate,
<add> "container_stats": daemon.ContainerStats,
<add> "export": daemon.ContainerExport,
<ide> "info": daemon.CmdInfo,
<ide> "restart": daemon.ContainerRestart,
<ide> "stop": daemon.ContainerStop,
<ide><path>runconfig/config.go
<ide> type Config struct {
<ide> Labels map[string]string
<ide> }
<ide>
<del>func ContainerConfigFromJob(job *engine.Job) *Config {
<add>func ContainerConfigFromJob(env *engine.Env) *Config {
<ide> config := &Config{
<del> Hostname: job.Getenv("Hostname"),
<del> Domainname: job.Getenv("Domainname"),
<del> User: job.Getenv("User"),
<del> Memory: job.GetenvInt64("Memory"),
<del> MemorySwap: job.GetenvInt64("MemorySwap"),
<del> CpuShares: job.GetenvInt64("CpuShares"),
<del> Cpuset: job.Getenv("Cpuset"),
<del> AttachStdin: job.GetenvBool("AttachStdin"),
<del> AttachStdout: job.GetenvBool("AttachStdout"),
<del> AttachStderr: job.GetenvBool("AttachStderr"),
<del> Tty: job.GetenvBool("Tty"),
<del> OpenStdin: job.GetenvBool("OpenStdin"),
<del> StdinOnce: job.GetenvBool("StdinOnce"),
<del> Image: job.Getenv("Image"),
<del> WorkingDir: job.Getenv("WorkingDir"),
<del> NetworkDisabled: job.GetenvBool("NetworkDisabled"),
<del> MacAddress: job.Getenv("MacAddress"),
<add> Hostname: env.Get("Hostname"),
<add> Domainname: env.Get("Domainname"),
<add> User: env.Get("User"),
<add> Memory: env.GetInt64("Memory"),
<add> MemorySwap: env.GetInt64("MemorySwap"),
<add> CpuShares: env.GetInt64("CpuShares"),
<add> Cpuset: env.Get("Cpuset"),
<add> AttachStdin: env.GetBool("AttachStdin"),
<add> AttachStdout: env.GetBool("AttachStdout"),
<add> AttachStderr: env.GetBool("AttachStderr"),
<add> Tty: env.GetBool("Tty"),
<add> OpenStdin: env.GetBool("OpenStdin"),
<add> StdinOnce: env.GetBool("StdinOnce"),
<add> Image: env.Get("Image"),
<add> WorkingDir: env.Get("WorkingDir"),
<add> NetworkDisabled: env.GetBool("NetworkDisabled"),
<add> MacAddress: env.Get("MacAddress"),
<ide> }
<del> job.GetenvJson("ExposedPorts", &config.ExposedPorts)
<del> job.GetenvJson("Volumes", &config.Volumes)
<del> if PortSpecs := job.GetenvList("PortSpecs"); PortSpecs != nil {
<add> env.GetJson("ExposedPorts", &config.ExposedPorts)
<add> env.GetJson("Volumes", &config.Volumes)
<add> if PortSpecs := env.GetList("PortSpecs"); PortSpecs != nil {
<ide> config.PortSpecs = PortSpecs
<ide> }
<del> if Env := job.GetenvList("Env"); Env != nil {
<add> if Env := env.GetList("Env"); Env != nil {
<ide> config.Env = Env
<ide> }
<del> if Cmd := job.GetenvList("Cmd"); Cmd != nil {
<add> if Cmd := env.GetList("Cmd"); Cmd != nil {
<ide> config.Cmd = Cmd
<ide> }
<ide>
<del> job.GetenvJson("Labels", &config.Labels)
<add> env.GetJson("Labels", &config.Labels)
<ide>
<del> if Entrypoint := job.GetenvList("Entrypoint"); Entrypoint != nil {
<add> if Entrypoint := env.GetList("Entrypoint"); Entrypoint != nil {
<ide> config.Entrypoint = Entrypoint
<ide> }
<ide> return config | 4 |
Javascript | Javascript | remove dublicate classname from head | 267cff3b81a90307dbb522552043aa6adfdff8bc | <ide><path>lib/head.js
<ide> class Head extends React.Component {
<ide> }
<ide> }
<ide>
<del>export function defaultHead () {
<del> return [<meta charSet='utf-8' className='next-head' />]
<add>const NEXT_HEAD_IDENTIFIER = 'next-head'
<add>
<add>export function defaultHead (className = NEXT_HEAD_IDENTIFIER) {
<add> return [<meta charSet='utf-8' className={className} />]
<ide> }
<ide>
<ide> function reduceComponents (components) {
<ide> return components
<del> .map((c) => c.props.children)
<del> .map((children) => React.Children.toArray(children))
<add> .map((component) => React.Children.toArray(component.props.children))
<ide> .reduce((a, b) => a.concat(b), [])
<ide> .reduce((a, b) => {
<ide> if (React.Fragment && b.type === React.Fragment) {
<ide> function reduceComponents (components) {
<ide> return a.concat(b)
<ide> }, [])
<ide> .reverse()
<del> .concat(...defaultHead())
<del> .filter((c) => !!c)
<add> .concat(defaultHead())
<add> .filter(Boolean)
<ide> .filter(unique())
<ide> .reverse()
<ide> .map((c) => {
<del> const className = (c.props && c.props.className ? c.props.className + ' ' : '') + 'next-head'
<add> const className = (c.props && c.props.className ? c.props.className + ' ' : '') + NEXT_HEAD_IDENTIFIER
<ide> return React.cloneElement(c, { className })
<ide> })
<ide> } | 1 |
Ruby | Ruby | add as_cmake_arch_flags helper | b0d45b29bd91a76d1fc41a2aedd0cfe5238fd6da | <ide><path>Library/Homebrew/mach.rb
<ide> def as_arch_flags
<ide> self.collect{ |a| "-arch #{a}" }.join(' ')
<ide> end
<ide>
<add> def as_cmake_arch_flags
<add> self.join(';')
<add> end
<add>
<ide> protected
<ide>
<ide> def intersects_all?(*set) | 1 |
Text | Text | remove uneccesary colon | 473097144cbfa183bdc3c4e7d2b742affd2fc7f2 | <ide><path>docs/docs/08.1-more-about-refs.md
<ide> permalink: more-about-refs.html
<ide> prev: working-with-the-browser.html
<ide> next: tooling-integration.html
<ide> ---
<del>After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from `render()`. In most cases, this should be unnecessary because the reactive data flow always ensures that the most recent props are sent to each child that is output from `render()`. However, there are a few cases where it still might be necessary or beneficial, so React provides an escape hatch known as `refs`. These `refs` (references) are especially useful when you need to: find the DOM markup rendered by a component (for instance, to position it absolutely), use React components in a larger non-React application, or transition your existing codebase to React.
<add>After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from `render()`. In most cases, this should be unnecessary because the reactive data flow always ensures that the most recent props are sent to each child that is output from `render()`. However, there are a few cases where it still might be necessary or beneficial, so React provides an escape hatch known as `refs`. These `refs` (references) are especially useful when you need to find the DOM markup rendered by a component (for instance, to position it absolutely), use React components in a larger non-React application, or transition your existing codebase to React.
<ide>
<ide> Let's look at how to get a ref, and then dive into a complete example.
<ide> | 1 |
Java | Java | improve coverage, fix operator logic 03/12 | 90bca55c39fcc515013f2737e2f6fb6cbd2e660b | <ide><path>src/main/java/io/reactivex/exceptions/CompositeException.java
<ide> public int size() {
<ide> * @param e the {@link Throwable} {@code e}.
<ide> * @return The root cause of {@code e}. If {@code e.getCause()} returns {@code null} or {@code e}, just return {@code e} itself.
<ide> */
<del> private Throwable getRootCause(Throwable e) {
<add> /*private */Throwable getRootCause(Throwable e) {
<ide> Throwable root = e.getCause();
<ide> if (root == null || cause == root) {
<ide> return e;
<ide><path>src/main/java/io/reactivex/internal/functions/ObjectHelper.java
<ide> public static int compare(int v1, int v2) {
<ide> }
<ide>
<ide> /**
<del> * Compares two integer values similar to Long.compare.
<add> * Compares two long values similar to Long.compare.
<ide> * @param v1 the first value
<ide> * @param v2 the second value
<ide> * @return the comparison result
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java
<ide> void next() {
<ide>
<ide> BufferBoundarySubscriber<T, U, B> bs = new BufferBoundarySubscriber<T, U, B>(this);
<ide>
<del> Disposable o = other.get();
<del>
<del> if (!other.compareAndSet(o, bs)) {
<del> return;
<del> }
<del>
<del> U b;
<del> synchronized (this) {
<del> b = buffer;
<del> if (b == null) {
<del> return;
<add> if (DisposableHelper.replace(other, bs)) {
<add> U b;
<add> synchronized (this) {
<add> b = buffer;
<add> if (b == null) {
<add> return;
<add> }
<add> buffer = next;
<ide> }
<del> buffer = next;
<del> }
<ide>
<del> boundary.subscribe(bs);
<add> boundary.subscribe(bs);
<ide>
<del> fastPathEmitMax(b, false, this);
<add> fastPathEmitMax(b, false, this);
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java
<ide> public void request(long n) {
<ide>
<ide> @Override
<ide> public void cancel() {
<add> cancelled = true;
<ide> s.cancel();
<del>
<ide> DisposableHelper.dispose(timer);
<ide> }
<ide>
<ide> public void run() {
<ide>
<ide> synchronized (this) {
<ide> current = buffer;
<del> if (current != null) {
<del> buffer = next;
<add> if (current == null) {
<add> return;
<ide> }
<del> }
<del>
<del> if (current == null) {
<del> DisposableHelper.dispose(timer);
<del> return;
<add> buffer = next;
<ide> }
<ide>
<ide> fastPathEmitMax(current, false, this);
<ide> public void request(long n) {
<ide>
<ide> @Override
<ide> public void cancel() {
<del> clear();
<add> cancelled = true;
<ide> s.cancel();
<ide> w.dispose();
<add> clear();
<ide> }
<ide>
<ide> void clear() {
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounceTimed.java
<ide> protected void subscribeActual(Subscriber<? super T> s) {
<ide>
<ide> Subscription s;
<ide>
<del> final SequentialDisposable timer = new SequentialDisposable();
<add> Disposable timer;
<ide>
<ide> volatile long index;
<ide>
<ide> public void onNext(T t) {
<ide> long idx = index + 1;
<ide> index = idx;
<ide>
<del> Disposable d = timer.get();
<add> Disposable d = timer;
<ide> if (d != null) {
<ide> d.dispose();
<ide> }
<ide>
<ide> DebounceEmitter<T> de = new DebounceEmitter<T>(t, idx, this);
<del> if (timer.replace(de)) {
<del> d = worker.schedule(de, timeout, unit);
<del>
<del> de.setResource(d);
<del> }
<add> timer = de;
<add> d = worker.schedule(de, timeout, unit);
<add> de.setResource(d);
<ide> }
<ide>
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> return;
<ide> }
<ide> done = true;
<add> Disposable d = timer;
<add> if (d != null) {
<add> d.dispose();
<add> }
<ide> actual.onError(t);
<ide> worker.dispose();
<ide> }
<ide> public void onComplete() {
<ide> }
<ide> done = true;
<ide>
<del> Disposable d = timer.get();
<del> if (!DisposableHelper.isDisposed(d)) {
<del> @SuppressWarnings("unchecked")
<del> DebounceEmitter<T> de = (DebounceEmitter<T>)d;
<del> if (de != null) {
<del> de.emit();
<del> }
<del> DisposableHelper.dispose(timer);
<del> actual.onComplete();
<del> worker.dispose();
<add> Disposable d = timer;
<add> if (d != null) {
<add> d.dispose();
<add> }
<add> @SuppressWarnings("unchecked")
<add> DebounceEmitter<T> de = (DebounceEmitter<T>)d;
<add> if (de != null) {
<add> de.emit();
<ide> }
<add>
<add> actual.onComplete();
<add> worker.dispose();
<ide> }
<ide>
<ide> @Override
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableBuffer.java
<ide> public void onError(Throwable t) {
<ide> @Override
<ide> public void onComplete() {
<ide> U b = buffer;
<del> buffer = null;
<del> if (b != null && !b.isEmpty()) {
<del> actual.onNext(b);
<add> if (b != null) {
<add> buffer = null;
<add> if (!b.isEmpty()) {
<add> actual.onNext(b);
<add> }
<add> actual.onComplete();
<ide> }
<del> actual.onComplete();
<ide> }
<ide> }
<ide>
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableBufferBoundarySupplier.java
<ide> void next() {
<ide>
<ide> BufferBoundaryObserver<T, U, B> bs = new BufferBoundaryObserver<T, U, B>(this);
<ide>
<del> Disposable o = other.get();
<del>
<del> if (!other.compareAndSet(o, bs)) {
<del> return;
<del> }
<del>
<del> U b;
<del> synchronized (this) {
<del> b = buffer;
<del> if (b == null) {
<del> return;
<add> if (DisposableHelper.replace(other, bs)) {
<add> U b;
<add> synchronized (this) {
<add> b = buffer;
<add> if (b == null) {
<add> return;
<add> }
<add> buffer = next;
<ide> }
<del> buffer = next;
<del> }
<ide>
<del> boundary.subscribe(bs);
<add> boundary.subscribe(bs);
<ide>
<del> fastPathEmit(b, false, this);
<add> fastPathEmit(b, false, this);
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDebounceTimed.java
<ide> public void subscribeActual(Observer<? super T> t) {
<ide>
<ide> Disposable s;
<ide>
<del> final AtomicReference<Disposable> timer = new AtomicReference<Disposable>();
<add> Disposable timer;
<ide>
<ide> volatile long index;
<ide>
<ide> public void onNext(T t) {
<ide> long idx = index + 1;
<ide> index = idx;
<ide>
<del> Disposable d = timer.get();
<add> Disposable d = timer;
<ide> if (d != null) {
<ide> d.dispose();
<ide> }
<ide>
<ide> DebounceEmitter<T> de = new DebounceEmitter<T>(t, idx, this);
<del> if (timer.compareAndSet(d, de)) {
<del> d = worker.schedule(de, timeout, unit);
<del>
<del> de.setResource(d);
<del> }
<del>
<add> timer = de;
<add> d = worker.schedule(de, timeout, unit);
<add> de.setResource(d);
<ide> }
<ide>
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> RxJavaPlugins.onError(t);
<ide> return;
<ide> }
<add> Disposable d = timer;
<add> if (d != null) {
<add> d.dispose();
<add> }
<ide> done = true;
<ide> actual.onError(t);
<ide> worker.dispose();
<ide> public void onComplete() {
<ide> }
<ide> done = true;
<ide>
<del> Disposable d = timer.get();
<del> if (d != DisposableHelper.DISPOSED) {
<del> @SuppressWarnings("unchecked")
<del> DebounceEmitter<T> de = (DebounceEmitter<T>)d;
<del> if (de != null) {
<del> de.run();
<del> }
<del> actual.onComplete();
<del> worker.dispose();
<add> Disposable d = timer;
<add> if (d != null) {
<add> d.dispose();
<ide> }
<add> @SuppressWarnings("unchecked")
<add> DebounceEmitter<T> de = (DebounceEmitter<T>)d;
<add> if (de != null) {
<add> de.run();
<add> }
<add> actual.onComplete();
<add> worker.dispose();
<ide> }
<ide>
<ide> @Override
<ide><path>src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java
<ide> public void onSubscribe(Disposable d) {
<ide> public void onSuccess(T value) {
<ide> other.dispose();
<ide>
<del> Disposable a = get();
<add> Disposable a = getAndSet(DisposableHelper.DISPOSED);
<ide> if (a != DisposableHelper.DISPOSED) {
<del> a = getAndSet(DisposableHelper.DISPOSED);
<del> if (a != DisposableHelper.DISPOSED) {
<del> actual.onSuccess(value);
<del> }
<add> actual.onSuccess(value);
<ide> }
<ide> }
<ide>
<ide><path>src/main/java/io/reactivex/internal/util/MergerBiFunction.java
<ide> public List<T> apply(List<T> a, List<T> b) throws Exception {
<ide> while (at.hasNext()) {
<ide> both.add(at.next());
<ide> }
<del> } else
<del> if (s2 != null) {
<add> } else {
<ide> both.add(s2);
<ide> while (bt.hasNext()) {
<ide> both.add(bt.next());
<ide><path>src/test/java/io/reactivex/exceptions/CompositeExceptionTest.java
<ide> public void badException() {
<ide> assertSame(e, new CompositeException(e).getCause().getCause());
<ide> assertSame(e, new CompositeException(new RuntimeException(e)).getCause().getCause().getCause());
<ide> }
<add>
<add> @Test
<add> public void rootCauseEval() {
<add> final TestException ex0 = new TestException();
<add> Throwable throwable = new Throwable() {
<add>
<add> private static final long serialVersionUID = 3597694032723032281L;
<add>
<add> @Override
<add> public synchronized Throwable getCause() {
<add> return ex0;
<add> }
<add> };
<add> CompositeException ex = new CompositeException(throwable);
<add> assertSame(ex, ex.getRootCause(ex));
<add> }
<ide> }
<ide>
<ide> final class BadException extends Throwable {
<ide><path>src/test/java/io/reactivex/internal/functions/ObjectHelperTest.java
<ide> public void compare() {
<ide> assertEquals(0, ObjectHelper.compare(0, 0));
<ide> assertEquals(1, ObjectHelper.compare(2, 0));
<ide> }
<add>
<add> @Test
<add> public void compareLong() {
<add> assertEquals(-1, ObjectHelper.compare(0L, 2L));
<add> assertEquals(0, ObjectHelper.compare(0L, 0L));
<add> assertEquals(1, ObjectHelper.compare(2L, 0L));
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableBufferTest.java
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.exceptions.*;
<ide> import io.reactivex.functions.*;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<ide> import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.internal.operators.flowable.FlowableBufferBoundarySupplier.BufferBoundarySupplierSubscriber;
<add>import io.reactivex.internal.operators.flowable.FlowableBufferTimed.*;
<ide> import io.reactivex.internal.subscriptions.BooleanSubscription;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.processors.*;
<ide> protected void subscribeActual(Subscriber<? super Integer> s) {
<ide> RxJavaPlugins.reset();
<ide> }
<ide> }
<add>
<add> @Test
<add> public void bufferBoundarySupplierDisposed() {
<add> TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>();
<add> BufferBoundarySupplierSubscriber<Integer, List<Integer>, Integer> sub =
<add> new BufferBoundarySupplierSubscriber<Integer, List<Integer>, Integer>(
<add> ts, Functions.justCallable((List<Integer>)new ArrayList<Integer>()),
<add> Functions.justCallable(Flowable.<Integer>never())
<add> );
<add>
<add> BooleanSubscription bs = new BooleanSubscription();
<add>
<add> sub.onSubscribe(bs);
<add>
<add> assertFalse(sub.isDisposed());
<add>
<add> sub.dispose();
<add>
<add> assertTrue(sub.isDisposed());
<add>
<add> sub.next();
<add>
<add> assertSame(DisposableHelper.DISPOSED, sub.other.get());
<add>
<add> sub.cancel();
<add> sub.cancel();
<add>
<add> assertTrue(bs.isCancelled());
<add> }
<add>
<add> @Test
<add> public void bufferBoundarySupplierBufferAlreadyCleared() {
<add> TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>();
<add> BufferBoundarySupplierSubscriber<Integer, List<Integer>, Integer> sub =
<add> new BufferBoundarySupplierSubscriber<Integer, List<Integer>, Integer>(
<add> ts, Functions.justCallable((List<Integer>)new ArrayList<Integer>()),
<add> Functions.justCallable(Flowable.<Integer>never())
<add> );
<add>
<add> BooleanSubscription bs = new BooleanSubscription();
<add>
<add> sub.onSubscribe(bs);
<add>
<add> sub.buffer = null;
<add>
<add> sub.next();
<add>
<add> sub.onNext(1);
<add>
<add> sub.onComplete();
<add> }
<add>
<add> @Test
<add> public void timedDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() {
<add> @Override
<add> public Publisher<List<Object>> apply(Flowable<Object> f)
<add> throws Exception {
<add> return f.buffer(1, TimeUnit.SECONDS);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void timedCancelledUpfront() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> TestSubscriber<List<Object>> ts = Flowable.never()
<add> .buffer(1, TimeUnit.MILLISECONDS, sch)
<add> .test(1L, true);
<add>
<add> sch.advanceTimeBy(1, TimeUnit.MILLISECONDS);
<add>
<add> ts.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void timedInternalState() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>();
<add>
<add> BufferExactUnboundedSubscriber<Integer, List<Integer>> sub = new BufferExactUnboundedSubscriber<Integer, List<Integer>>(
<add> ts, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), 1, TimeUnit.SECONDS, sch);
<add>
<add> sub.onSubscribe(new BooleanSubscription());
<add>
<add> assertFalse(sub.isDisposed());
<add>
<add> sub.onError(new TestException());
<add> sub.onNext(1);
<add> sub.onComplete();
<add>
<add> sub.run();
<add>
<add> sub.dispose();
<add>
<add> assertTrue(sub.isDisposed());
<add>
<add> sub.buffer = new ArrayList<Integer>();
<add> sub.enter();
<add> sub.onComplete();
<add> }
<add>
<add> @Test
<add> public void timedSkipDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() {
<add> @Override
<add> public Publisher<List<Object>> apply(Flowable<Object> f)
<add> throws Exception {
<add> return f.buffer(2, 1, TimeUnit.SECONDS);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void timedSizedDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() {
<add> @Override
<add> public Publisher<List<Object>> apply(Flowable<Object> f)
<add> throws Exception {
<add> return f.buffer(2, TimeUnit.SECONDS, 10);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void timedSkipInternalState() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>();
<add>
<add> BufferSkipBoundedSubscriber<Integer, List<Integer>> sub = new BufferSkipBoundedSubscriber<Integer, List<Integer>>(
<add> ts, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), 1, 1, TimeUnit.SECONDS, sch.createWorker());
<add>
<add> sub.onSubscribe(new BooleanSubscription());
<add>
<add> sub.enter();
<add> sub.onComplete();
<add>
<add> sub.cancel();
<add>
<add> sub.run();
<add> }
<add>
<add> @Test
<add> public void timedSkipCancelWhenSecondBuffer() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> final TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>();
<add>
<add> BufferSkipBoundedSubscriber<Integer, List<Integer>> sub = new BufferSkipBoundedSubscriber<Integer, List<Integer>>(
<add> ts, new Callable<List<Integer>>() {
<add> int calls;
<add> @Override
<add> public List<Integer> call() throws Exception {
<add> if (++calls == 2) {
<add> ts.cancel();
<add> }
<add> return new ArrayList<Integer>();
<add> }
<add> }, 1, 1, TimeUnit.SECONDS, sch.createWorker());
<add>
<add> sub.onSubscribe(new BooleanSubscription());
<add>
<add> sub.run();
<add>
<add> assertTrue(ts.isCancelled());
<add> }
<add>
<add> @Test
<add> public void timedSizeBufferAlreadyCleared() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> TestSubscriber<List<Integer>> ts = new TestSubscriber<List<Integer>>();
<add>
<add> BufferExactBoundedSubscriber<Integer, List<Integer>> sub =
<add> new BufferExactBoundedSubscriber<Integer, List<Integer>>(
<add> ts, Functions.justCallable((List<Integer>)new ArrayList<Integer>()),
<add> 1, TimeUnit.SECONDS, 1, false, sch.createWorker())
<add> ;
<add>
<add> BooleanSubscription bs = new BooleanSubscription();
<add>
<add> sub.onSubscribe(bs);
<add>
<add> sub.producerIndex++;
<add>
<add> sub.run();
<add>
<add> assertFalse(sub.isDisposed());
<add>
<add> sub.enter();
<add> sub.onComplete();
<add>
<add> assertTrue(sub.isDisposed());
<add>
<add> sub.run();
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java
<ide> import io.reactivex.exceptions.*;
<ide> import io.reactivex.functions.Function;
<ide> import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.internal.operators.flowable.FlowableDebounceTimed.*;
<ide> import io.reactivex.internal.subscriptions.BooleanSubscription;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.processors.*;
<ide> protected void subscribeActual(Subscriber<? super Integer> subscriber) {
<ide> public void badRequestReported() {
<ide> TestHelper.assertBadRequestReported(Flowable.never().debounce(Functions.justFunction(Flowable.never())));
<ide> }
<add>
<add> @Test
<add> public void timedDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Object>>() {
<add> @Override
<add> public Publisher<Object> apply(Flowable<Object> f)
<add> throws Exception {
<add> return f.debounce(1, TimeUnit.SECONDS);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void timedDisposedIgnoredBySource() {
<add> final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add>
<add> new Flowable<Integer>() {
<add> @Override
<add> protected void subscribeActual(
<add> org.reactivestreams.Subscriber<? super Integer> s) {
<add> s.onSubscribe(new BooleanSubscription());
<add> ts.cancel();
<add> s.onNext(1);
<add> s.onComplete();
<add> }
<add> }
<add> .debounce(1, TimeUnit.SECONDS)
<add> .subscribe(ts);
<add> }
<add>
<add> @Test
<add> public void timedBadRequest() {
<add> TestHelper.assertBadRequestReported(Flowable.never().debounce(1, TimeUnit.SECONDS));
<add> }
<add>
<add> @Test
<add> public void timedLateEmit() {
<add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add> DebounceTimedSubscriber<Integer> sub = new DebounceTimedSubscriber<Integer>(
<add> ts, 1, TimeUnit.SECONDS, new TestScheduler().createWorker());
<add>
<add> sub.onSubscribe(new BooleanSubscription());
<add>
<add> DebounceEmitter<Integer> de = new DebounceEmitter<Integer>(1, 50, sub);
<add> de.emit();
<add> de.emit();
<add>
<add> ts.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void timedError() {
<add> Flowable.error(new TestException())
<add> .debounce(1, TimeUnit.SECONDS)
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableUsingTest.java
<ide> import io.reactivex.exceptions.*;
<ide> import io.reactivex.functions.*;
<ide> import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.internal.subscriptions.BooleanSubscription;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.subscribers.TestSubscriber;
<ide>
<ide> public void sourceSupplierReturnsNull() {
<ide> .assertFailureAndMessage(NullPointerException.class, "The sourceSupplier returned a null Publisher")
<ide> ;
<ide> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() {
<add> @Override
<add> public Flowable<Object> apply(Flowable<Object> o)
<add> throws Exception {
<add> return Flowable.using(Functions.justCallable(1), Functions.justFunction(o), Functions.emptyConsumer());
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void eagerDisposedOnComplete() {
<add> final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add>
<add> Flowable.using(Functions.justCallable(1), Functions.justFunction(new Flowable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Subscriber<? super Integer> observer) {
<add> observer.onSubscribe(new BooleanSubscription());
<add> ts.cancel();
<add> observer.onComplete();
<add> }
<add> }), Functions.emptyConsumer(), true)
<add> .subscribe(ts);
<add> }
<add>
<add> @Test
<add> public void eagerDisposedOnError() {
<add> final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
<add>
<add> Flowable.using(Functions.justCallable(1), Functions.justFunction(new Flowable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Subscriber<? super Integer> observer) {
<add> observer.onSubscribe(new BooleanSubscription());
<add> ts.cancel();
<add> observer.onError(new TestException());
<add> }
<add> }), Functions.emptyConsumer(), true)
<add> .subscribe(ts);
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFlatMapBiSelectorTest.java
<ide> import io.reactivex.*;
<ide> import io.reactivex.exceptions.TestException;
<ide> import io.reactivex.functions.*;
<add>import io.reactivex.observers.TestObserver;
<ide> import io.reactivex.processors.PublishProcessor;
<ide>
<ide> public class MaybeFlatMapBiSelectorTest {
<ide> public Object apply(Integer a, Integer b) throws Exception {
<ide> .test()
<ide> .assertFailure(NullPointerException.class);
<ide> }
<add>
<add> @Test
<add> public void mapperCancels() {
<add> final TestObserver<Integer> to = new TestObserver<Integer>();
<add>
<add> Maybe.just(1)
<add> .flatMap(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v) throws Exception {
<add> to.cancel();
<add> return Maybe.just(2);
<add> }
<add> }, new BiFunction<Integer, Integer, Integer>() {
<add> @Override
<add> public Integer apply(Integer a, Integer b) throws Exception {
<add> throw new IllegalStateException();
<add> }
<add> })
<add> .subscribeWith(to)
<add> .assertEmpty();
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java
<ide> import io.reactivex.disposables.*;
<ide> import io.reactivex.exceptions.*;
<ide> import io.reactivex.functions.*;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<ide> import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.internal.operators.observable.ObservableBuffer.BufferExactObserver;
<add>import io.reactivex.internal.operators.observable.ObservableBufferBoundarySupplier.BufferBoundarySupplierObserver;
<add>import io.reactivex.internal.operators.observable.ObservableBufferTimed.*;
<ide> import io.reactivex.observers.*;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.schedulers.*;
<ide> protected void subscribeActual(Observer<? super Integer> s) {
<ide> RxJavaPlugins.reset();
<ide> }
<ide> }
<add>
<add> @Test
<add> public void bufferBoundarySupplierDisposed() {
<add> TestObserver<List<Integer>> to = new TestObserver<List<Integer>>();
<add> BufferBoundarySupplierObserver<Integer, List<Integer>, Integer> sub =
<add> new BufferBoundarySupplierObserver<Integer, List<Integer>, Integer>(
<add> to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()),
<add> Functions.justCallable(Observable.<Integer>never())
<add> );
<add>
<add> Disposable bs = Disposables.empty();
<add>
<add> sub.onSubscribe(bs);
<add>
<add> assertFalse(sub.isDisposed());
<add>
<add> sub.dispose();
<add>
<add> assertTrue(sub.isDisposed());
<add>
<add> sub.next();
<add>
<add> assertSame(DisposableHelper.DISPOSED, sub.other.get());
<add>
<add> sub.dispose();
<add> sub.dispose();
<add>
<add> assertTrue(bs.isDisposed());
<add> }
<add>
<add> @Test
<add> public void bufferBoundarySupplierBufferAlreadyCleared() {
<add> TestObserver<List<Integer>> to = new TestObserver<List<Integer>>();
<add> BufferBoundarySupplierObserver<Integer, List<Integer>, Integer> sub =
<add> new BufferBoundarySupplierObserver<Integer, List<Integer>, Integer>(
<add> to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()),
<add> Functions.justCallable(Observable.<Integer>never())
<add> );
<add>
<add> Disposable bs = Disposables.empty();
<add>
<add> sub.onSubscribe(bs);
<add>
<add> sub.buffer = null;
<add>
<add> sub.next();
<add>
<add> sub.onNext(1);
<add>
<add> sub.onComplete();
<add> }
<add>
<add> @Test
<add> public void timedDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<List<Object>>>() {
<add> @Override
<add> public Observable<List<Object>> apply(Observable<Object> f)
<add> throws Exception {
<add> return f.buffer(1, TimeUnit.SECONDS);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void timedCancelledUpfront() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> TestObserver<List<Object>> to = Observable.never()
<add> .buffer(1, TimeUnit.MILLISECONDS, sch)
<add> .test(true);
<add>
<add> sch.advanceTimeBy(1, TimeUnit.MILLISECONDS);
<add>
<add> to.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void timedInternalState() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> TestObserver<List<Integer>> to = new TestObserver<List<Integer>>();
<add>
<add> BufferExactUnboundedObserver<Integer, List<Integer>> sub = new BufferExactUnboundedObserver<Integer, List<Integer>>(
<add> to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), 1, TimeUnit.SECONDS, sch);
<add>
<add> sub.onSubscribe(Disposables.empty());
<add>
<add> assertFalse(sub.isDisposed());
<add>
<add> sub.onError(new TestException());
<add> sub.onNext(1);
<add> sub.onComplete();
<add>
<add> sub.run();
<add>
<add> sub.dispose();
<add>
<add> assertTrue(sub.isDisposed());
<add>
<add> sub.buffer = new ArrayList<Integer>();
<add> sub.enter();
<add> sub.onComplete();
<add> }
<add>
<add> @Test
<add> public void timedSkipDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<List<Object>>>() {
<add> @Override
<add> public Observable<List<Object>> apply(Observable<Object> f)
<add> throws Exception {
<add> return f.buffer(2, 1, TimeUnit.SECONDS);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void timedSizedDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<List<Object>>>() {
<add> @Override
<add> public Observable<List<Object>> apply(Observable<Object> f)
<add> throws Exception {
<add> return f.buffer(2, TimeUnit.SECONDS, 10);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void timedSkipInternalState() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> TestObserver<List<Integer>> to = new TestObserver<List<Integer>>();
<add>
<add> BufferSkipBoundedObserver<Integer, List<Integer>> sub = new BufferSkipBoundedObserver<Integer, List<Integer>>(
<add> to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), 1, 1, TimeUnit.SECONDS, sch.createWorker());
<add>
<add> sub.onSubscribe(Disposables.empty());
<add>
<add> sub.enter();
<add> sub.onComplete();
<add>
<add> sub.dispose();
<add>
<add> sub.run();
<add> }
<add>
<add> @Test
<add> public void timedSkipCancelWhenSecondBuffer() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> final TestObserver<List<Integer>> to = new TestObserver<List<Integer>>();
<add>
<add> BufferSkipBoundedObserver<Integer, List<Integer>> sub = new BufferSkipBoundedObserver<Integer, List<Integer>>(
<add> to, new Callable<List<Integer>>() {
<add> int calls;
<add> @Override
<add> public List<Integer> call() throws Exception {
<add> if (++calls == 2) {
<add> to.cancel();
<add> }
<add> return new ArrayList<Integer>();
<add> }
<add> }, 1, 1, TimeUnit.SECONDS, sch.createWorker());
<add>
<add> sub.onSubscribe(Disposables.empty());
<add>
<add> sub.run();
<add>
<add> assertTrue(to.isCancelled());
<add> }
<add>
<add> @Test
<add> public void timedSizeBufferAlreadyCleared() {
<add> TestScheduler sch = new TestScheduler();
<add>
<add> TestObserver<List<Integer>> to = new TestObserver<List<Integer>>();
<add>
<add> BufferExactBoundedObserver<Integer, List<Integer>> sub =
<add> new BufferExactBoundedObserver<Integer, List<Integer>>(
<add> to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()),
<add> 1, TimeUnit.SECONDS, 1, false, sch.createWorker())
<add> ;
<add>
<add> Disposable bs = Disposables.empty();
<add>
<add> sub.onSubscribe(bs);
<add>
<add> sub.producerIndex++;
<add>
<add> sub.run();
<add>
<add> assertFalse(sub.isDisposed());
<add>
<add> sub.enter();
<add> sub.onComplete();
<add>
<add> sub.dispose();
<add>
<add> assertTrue(sub.isDisposed());
<add>
<add> sub.run();
<add>
<add> sub.onNext(1);
<add> }
<add>
<add> @Test
<add> public void bufferExactDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<List<Object>>>() {
<add> @Override
<add> public ObservableSource<List<Object>> apply(Observable<Object> o)
<add> throws Exception {
<add> return o.buffer(1);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void bufferExactState() {
<add> TestObserver<List<Integer>> to = new TestObserver<List<Integer>>();
<add>
<add> BufferExactObserver<Integer, List<Integer>> sub = new BufferExactObserver<Integer, List<Integer>>(
<add> to, 1, Functions.justCallable((List<Integer>)new ArrayList<Integer>())
<add> );
<add>
<add> sub.onComplete();
<add> sub.onNext(1);
<add> sub.onComplete();
<add> }
<add>
<add> @Test
<add> public void bufferSkipDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<List<Object>>>() {
<add> @Override
<add> public ObservableSource<List<Object>> apply(Observable<Object> o)
<add> throws Exception {
<add> return o.buffer(1, 2);
<add> }
<add> });
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java
<ide>
<ide> import org.junit.*;
<ide> import org.mockito.InOrder;
<add>import org.reactivestreams.Publisher;
<ide>
<ide> import io.reactivex.*;
<ide> import io.reactivex.disposables.*;
<ide> import io.reactivex.exceptions.TestException;
<ide> import io.reactivex.functions.Function;
<ide> import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.internal.operators.observable.ObservableDebounceTimed.*;
<ide> import io.reactivex.observers.TestObserver;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.schedulers.TestScheduler;
<ide> protected void subscribeActual(Observer<? super Integer> observer) {
<ide> to
<ide> .assertResult(2);
<ide> }
<add>
<add> @Test
<add> public void timedDoubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Object>>() {
<add> @Override
<add> public Publisher<Object> apply(Flowable<Object> f)
<add> throws Exception {
<add> return f.debounce(1, TimeUnit.SECONDS);
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void timedDisposedIgnoredBySource() {
<add> final TestObserver<Integer> to = new TestObserver<Integer>();
<add>
<add> new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(
<add> Observer<? super Integer> s) {
<add> s.onSubscribe(Disposables.empty());
<add> to.cancel();
<add> s.onNext(1);
<add> s.onComplete();
<add> }
<add> }
<add> .debounce(1, TimeUnit.SECONDS)
<add> .subscribe(to);
<add> }
<add>
<add> @Test
<add> public void timedLateEmit() {
<add> TestObserver<Integer> to = new TestObserver<Integer>();
<add> DebounceTimedObserver<Integer> sub = new DebounceTimedObserver<Integer>(
<add> to, 1, TimeUnit.SECONDS, new TestScheduler().createWorker());
<add>
<add> sub.onSubscribe(Disposables.empty());
<add>
<add> DebounceEmitter<Integer> de = new DebounceEmitter<Integer>(1, 50, sub);
<add> de.run();
<add> de.run();
<add>
<add> to.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void timedError() {
<add> Observable.error(new TestException())
<add> .debounce(1, TimeUnit.SECONDS)
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableUsingTest.java
<ide> public void sourceSupplierReturnsNull() {
<ide> .assertFailureAndMessage(NullPointerException.class, "The sourceSupplier returned a null ObservableSource")
<ide> ;
<ide> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<Object>>() {
<add> @Override
<add> public ObservableSource<Object> apply(Observable<Object> o)
<add> throws Exception {
<add> return Observable.using(Functions.justCallable(1), Functions.justFunction(o), Functions.emptyConsumer());
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void eagerDisposedOnComplete() {
<add> final TestObserver<Integer> to = new TestObserver<Integer>();
<add>
<add> Observable.using(Functions.justCallable(1), Functions.justFunction(new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> observer) {
<add> observer.onSubscribe(Disposables.empty());
<add> to.cancel();
<add> observer.onComplete();
<add> }
<add> }), Functions.emptyConsumer(), true)
<add> .subscribe(to);
<add> }
<add>
<add> @Test
<add> public void eagerDisposedOnError() {
<add> final TestObserver<Integer> to = new TestObserver<Integer>();
<add>
<add> Observable.using(Functions.justCallable(1), Functions.justFunction(new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> observer) {
<add> observer.onSubscribe(Disposables.empty());
<add> to.cancel();
<add> observer.onError(new TestException());
<add> }
<add> }), Functions.emptyConsumer(), true)
<add> .subscribe(to);
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/single/SingleFlatMapTest.java
<ide> public SingleSource<Integer> apply(Integer v) throws Exception {
<ide> .test()
<ide> .assertFailure(TestException.class);
<ide> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeSingle(new Function<Single<Object>, SingleSource<Object>>() {
<add> @Override
<add> public SingleSource<Object> apply(Single<Object> s)
<add> throws Exception {
<add> return s.flatMap(new Function<Object, SingleSource<? extends Object>>() {
<add> @Override
<add> public SingleSource<? extends Object> apply(Object v)
<add> throws Exception {
<add> return Single.just(v);
<add> }
<add> });
<add> }
<add> });
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/operators/single/SingleTakeUntilTest.java
<ide> import java.util.concurrent.CancellationException;
<ide>
<ide> import org.junit.Test;
<add>import org.reactivestreams.Subscriber;
<ide>
<ide> import io.reactivex.*;
<ide> import io.reactivex.exceptions.TestException;
<add>import io.reactivex.internal.subscriptions.BooleanSubscription;
<ide> import io.reactivex.observers.TestObserver;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.processors.PublishProcessor;
<ide> public void otherSignalsAndCompletes() {
<ide> RxJavaPlugins.reset();
<ide> }
<ide> }
<add>
<add> @Test
<add> public void flowableCancelDelayed() {
<add> Single.never()
<add> .takeUntil(new Flowable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Subscriber<? super Integer> s) {
<add> s.onSubscribe(new BooleanSubscription());
<add> s.onNext(1);
<add> s.onNext(2);
<add> }
<add> })
<add> .test()
<add> .assertFailure(CancellationException.class);
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/internal/util/MergerBiFunctionTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. 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 distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.util;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>
<add>import java.util.*;
<add>
<add>import org.junit.Test;
<add>
<add>public class MergerBiFunctionTest {
<add>
<add> @Test
<add> public void firstEmpty() throws Exception {
<add> MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() {
<add> @Override
<add> public int compare(Integer o1, Integer o2) {
<add> return o1.compareTo(o2);
<add> }
<add> });
<add> List<Integer> list = merger.apply(Collections.<Integer>emptyList(), Arrays.asList(3, 5));
<add>
<add> assertEquals(Arrays.asList(3, 5), list);
<add> }
<add>
<add> @Test
<add> public void bothEmpty() throws Exception {
<add> MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() {
<add> @Override
<add> public int compare(Integer o1, Integer o2) {
<add> return o1.compareTo(o2);
<add> }
<add> });
<add> List<Integer> list = merger.apply(Collections.<Integer>emptyList(), Collections.<Integer>emptyList());
<add>
<add> assertEquals(Collections.<Integer>emptyList(), list);
<add> }
<add>
<add> @Test
<add> public void secondEmpty() throws Exception {
<add> MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() {
<add> @Override
<add> public int compare(Integer o1, Integer o2) {
<add> return o1.compareTo(o2);
<add> }
<add> });
<add> List<Integer> list = merger.apply(Arrays.asList(2, 4), Collections.<Integer>emptyList());
<add>
<add> assertEquals(Arrays.asList(2, 4), list);
<add> }
<add>
<add> @Test
<add> public void sameSize() throws Exception {
<add> MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() {
<add> @Override
<add> public int compare(Integer o1, Integer o2) {
<add> return o1.compareTo(o2);
<add> }
<add> });
<add> List<Integer> list = merger.apply(Arrays.asList(2, 4), Arrays.asList(3, 5));
<add>
<add> assertEquals(Arrays.asList(2, 3, 4, 5), list);
<add> }
<add>
<add> @Test
<add> public void sameSizeReverse() throws Exception {
<add> MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() {
<add> @Override
<add> public int compare(Integer o1, Integer o2) {
<add> return o1.compareTo(o2);
<add> }
<add> });
<add> List<Integer> list = merger.apply(Arrays.asList(3, 5), Arrays.asList(2, 4));
<add>
<add> assertEquals(Arrays.asList(2, 3, 4, 5), list);
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/processors/ReplayProcessorTest.java
<ide> public void noHeadRetentionTime() {
<ide>
<ide> assertSame(o, buf.head);
<ide> }
<add>
<add> @Test
<add> public void invalidRequest() {
<add> TestHelper.assertBadRequestReported(ReplayProcessor.create());
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/subscribers/TestSubscriberTest.java
<ide> public void assertValuesOnlyThrowsWhenErrored() {
<ide> // expected
<ide> }
<ide> }
<add>
<add> @Test(timeout = 1000)
<add> public void awaitCount0() {
<add> TestSubscriber<Integer> ts = TestSubscriber.create();
<add> ts.awaitCount(0, TestWaitStrategy.SLEEP_1MS, 0);
<add> }
<ide> } | 24 |
Javascript | Javascript | add support for tabindex in ember controls | b4f4edd67b076fcd91bc1763693611577244b92a | <ide><path>packages/ember-handlebars/lib/controls/button.js
<ide> Ember.Button = Ember.View.extend(Ember.TargetActionSupport, {
<ide>
<ide> propagateEvents: false,
<ide>
<del> attributeBindings: ['type', 'disabled', 'href'],
<add> attributeBindings: ['type', 'disabled', 'href', 'tabindex'],
<ide>
<ide> /** @private
<ide> Overrides TargetActionSupport's targetObject computed
<ide><path>packages/ember-handlebars/lib/controls/checkbox.js
<ide> Ember.Checkbox = Ember.View.extend({
<ide>
<ide> tagName: 'input',
<ide>
<del> attributeBindings: ['type', 'checked', 'disabled'],
<add> attributeBindings: ['type', 'checked', 'disabled', 'tabindex'],
<ide>
<ide> type: "checkbox",
<ide> checked: false,
<ide><path>packages/ember-handlebars/lib/controls/select.js
<ide> Ember.Select = Ember.View.extend(
<ide> tagName: 'select',
<ide> classNames: ['ember-select'],
<ide> defaultTemplate: Ember.Handlebars.compile('{{#if view.prompt}}<option value>{{view.prompt}}</option>{{/if}}{{#each view.content}}{{view Ember.SelectOption contentBinding="this"}}{{/each}}'),
<del> attributeBindings: ['multiple'],
<add> attributeBindings: ['multiple', 'tabindex'],
<ide>
<ide> /**
<ide> The `multiple` attribute of the select element. Indicates whether multiple
<ide><path>packages/ember-handlebars/lib/controls/text_support.js
<ide> Ember.TextSupport = Ember.Mixin.create(
<ide>
<ide> value: "",
<ide>
<del> attributeBindings: ['placeholder', 'disabled', 'maxlength'],
<add> attributeBindings: ['placeholder', 'disabled', 'maxlength', 'tabindex'],
<ide> placeholder: null,
<ide> disabled: false,
<ide> maxlength: null,
<ide><path>packages/ember-handlebars/tests/controls/button_test.js
<ide> test("should become disabled if the disabled attribute is changed", function() {
<ide> ok(button.$().is(":not(:disabled)"));
<ide> });
<ide>
<add>test("should support the tabindex property", function() {
<add> button.set('tabindex', 6);
<add> append();
<add>
<add> equal(button.$().prop('tabindex'), '6', 'the initial button tabindex is set in the DOM');
<add>
<add> button.set('tabindex', 3);
<add> equal(button.$().prop('tabindex'), '3', 'the button tabindex changes when it is changed in the view');
<add>});
<add>
<add>
<ide> test("should trigger an action when clicked", function() {
<ide> var wasClicked = false;
<ide>
<ide><path>packages/ember-handlebars/tests/controls/checkbox_test.js
<ide> test("should become disabled if the disabled attribute is changed", function() {
<ide> ok(checkboxView.$().is(":not(:disabled)"));
<ide> });
<ide>
<add>test("should support the tabindex property", function() {
<add> checkboxView = Ember.Checkbox.create({});
<add>
<add> checkboxView.set('tabindex', 6);
<add> append();
<add>
<add> equal(checkboxView.$().prop('tabindex'), '6', 'the initial checkbox tabindex is set in the DOM');
<add>
<add> checkboxView.set('tabindex', 3);
<add> equal(checkboxView.$().prop('tabindex'), '3', 'the checkbox tabindex changes when it is changed in the view');
<add>});
<add>
<add>
<ide> test("checked property mirrors input value", function() {
<ide> checkboxView = Ember.Checkbox.create({});
<ide> Ember.run(function() { checkboxView.append(); });
<ide><path>packages/ember-handlebars/tests/controls/select_test.js
<ide> test("can have options", function() {
<ide> equal(select.$().text(), "123", "Options should have content");
<ide> });
<ide>
<add>
<add>test("select tabindex is updated when setting tabindex property of view", function() {
<add> select.set('tabindex', '4');
<add> append();
<add>
<add> equal(select.$().attr('tabindex'), "4", "renders select with the tabindex");
<add>
<add> select.set('tabindex', '1');
<add>
<add> equal(select.$().attr('tabindex'), "1", "updates select after tabindex changes");
<add>});
<add>
<ide> test("can specify the property path for an option's label and value", function() {
<ide> select.set('content', Ember.A([
<ide> { id: 1, firstName: 'Yehuda' },
<ide><path>packages/ember-handlebars/tests/controls/text_area_test.js
<ide> test("input cols is updated when setting cols property of view", function() {
<ide> equal(textArea.$().attr('cols'), "40", "updates text area after cols changes");
<ide> });
<ide>
<add>test("input tabindex is updated when setting tabindex property of view", function() {
<add> Ember.run(function() {
<add> set(textArea, 'tabindex', '4');
<add> textArea.append();
<add> });
<add>
<add> equal(textArea.$().attr('tabindex'), "4", "renders text area with the tabindex");
<add>
<add> Ember.run(function() { set(textArea, 'tabindex', '1'); });
<add>
<add> equal(textArea.$().attr('tabindex'), "1", "updates text area after tabindex changes");
<add>});
<add>
<ide> test("value binding works properly for inputs that haven't been created", function() {
<ide>
<ide> Ember.run(function() {
<ide><path>packages/ember-handlebars/tests/controls/text_field_test.js
<ide> test("input size is updated when setting size property of view", function() {
<ide> equal(textField.$().attr('size'), "40", "updates text field after size changes");
<ide> });
<ide>
<add>test("input tabindex is updated when setting tabindex property of view", function() {
<add> Ember.run(function() {
<add> set(textField, 'tabindex', '5');
<add> textField.append();
<add> });
<add>
<add> equal(textField.$().attr('tabindex'), "5", "renders text field with the tabindex");
<add>
<add> Ember.run(function() { set(textField, 'tabindex', '3'); });
<add>
<add> equal(textField.$().attr('tabindex'), "3", "updates text field after tabindex changes");
<add>});
<add>
<ide> test("input type is configurable when creating view", function() {
<ide> Ember.run(function() {
<ide> set(textField, 'type', 'password'); | 9 |
Python | Python | fix broken format string | ef1f7661c77a9e606189a52a5fb1a219e22400c8 | <ide><path>tools/icu/shrink-icu-src.py
<ide> shutil.rmtree(options.icusmall)
<ide>
<ide> if not os.path.isdir(options.icusrc):
<del> print 'Missing source ICU dir --icusrc=%' % (options.icusrc)
<add> print 'Missing source ICU dir --icusrc=%s' % (options.icusrc)
<ide> sys.exit(1)
<ide>
<ide> | 1 |
PHP | PHP | reword exception message and assert it in test | 984d070a777519a7622e45994901cd58fcd6c43f | <ide><path>src/Collection/CollectionTrait.php
<ide> public function last()
<ide> public function takeLast($howMany)
<ide> {
<ide> if ($howMany < 1) {
<del> throw new \InvalidArgumentException("takeLast requires a number greater than 0");
<add> throw new \InvalidArgumentException("The takeLast method requires a number greater than 0.");
<ide> }
<ide>
<ide> $iterator = $this->optimizeUnwrap();
<ide><path>tests/TestCase/Collection/CollectionTest.php
<ide> public function testLastNtWithNegative($data)
<ide> {
<ide> $collection = new Collection($data);
<ide> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The takeLast method requires a number greater than 0.');
<ide> $collection->takeLast(-1)->toArray();
<ide> }
<ide> | 2 |
Go | Go | fix compilation issue | 93f57705110e196dca1cf2b2ce7d261ee97b9e4e | <ide><path>runconfig/opts/parse.go
<ide> func Parse(cmd *flag.FlagSet, args []string) (*container.Config, *container.Host
<ide> entrypoint = strslice.StrSlice{*flEntrypoint}
<ide> }
<ide> // Validate if the given hostname is RFC 1123 (https://tools.ietf.org/html/rfc1123) compliant.
<add> hostname := *flHostname
<ide> if hostname != "" {
<ide> matched, _ := regexp.MatchString("^(([[:alnum:]]|[[:alnum:]][[:alnum:]\\-]*[[:alnum:]])\\.)*([[:alnum:]]|[[:alnum:]][[:alnum:]\\-]*[[:alnum:]])$", hostname)
<ide> if !matched { | 1 |
Go | Go | add test case check connect.endpointconfig not nil | fd74940304c86e43d8e8d44d0d8315086d5596c4 | <ide><path>client/network_connect_test.go
<ide> func TestNetworkConnect(t *testing.T) {
<ide> return nil, fmt.Errorf("expected 'container_id', got %s", connect.Container)
<ide> }
<ide>
<add> if connect.EndpointConfig == nil {
<add> return nil, fmt.Errorf("expected connect.EndpointConfig to be not nil, got %v", connect.EndpointConfig)
<add> }
<add>
<ide> if connect.EndpointConfig.NetworkID != "NetworkID" {
<ide> return nil, fmt.Errorf("expected 'NetworkID', got %s", connect.EndpointConfig.NetworkID)
<ide> } | 1 |
Mixed | Ruby | add update_sql option to #upsert_all | 8f3c12f8803b56943956e8a1539eca5df9f5a6a6 | <ide><path>activerecord/CHANGELOG.md
<add>* Add `update_sql` option to `#upsert_all` to make it possible to use raw SQL to update columns on conflict:
<add>
<add> ```ruby
<add> Book.upsert_all(
<add> [{ id: 1, status: 1 }, { id: 2, status: 1 }],
<add> update_sql: "status = GREATEST(books.status, EXCLUDED.status)"
<add> )
<add> ```
<add>
<add> *Vladimir Dementyev*
<add>
<ide> * Allow passing raw SQL as `returning` statement to `#upsert_all`:
<ide>
<ide> ```ruby
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def build_insert_sql(insert) # :nodoc:
<ide> sql << " ON DUPLICATE KEY UPDATE #{no_op_column}=#{no_op_column}"
<ide> elsif insert.update_duplicates?
<ide> sql << " ON DUPLICATE KEY UPDATE "
<del> sql << insert.touch_model_timestamps_unless { |column| "#{column}<=>VALUES(#{column})" }
<del> sql << insert.updatable_columns.map { |column| "#{column}=VALUES(#{column})" }.join(",")
<add> if insert.raw_update_sql?
<add> sql << insert.raw_update_sql
<add> else
<add> sql << insert.touch_model_timestamps_unless { |column| "#{column}<=>VALUES(#{column})" }
<add> sql << insert.updatable_columns.map { |column| "#{column}=VALUES(#{column})" }.join(",")
<add> end
<ide> end
<ide>
<ide> sql
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def build_insert_sql(insert) # :nodoc:
<ide> sql << " ON CONFLICT #{insert.conflict_target} DO NOTHING"
<ide> elsif insert.update_duplicates?
<ide> sql << " ON CONFLICT #{insert.conflict_target} DO UPDATE SET "
<del> sql << insert.touch_model_timestamps_unless { |column| "#{insert.model.quoted_table_name}.#{column} IS NOT DISTINCT FROM excluded.#{column}" }
<del> sql << insert.updatable_columns.map { |column| "#{column}=excluded.#{column}" }.join(",")
<add> if insert.raw_update_sql?
<add> sql << insert.raw_update_sql
<add> else
<add> sql << insert.touch_model_timestamps_unless { |column| "#{insert.model.quoted_table_name}.#{column} IS NOT DISTINCT FROM excluded.#{column}" }
<add> sql << insert.updatable_columns.map { |column| "#{column}=excluded.#{column}" }.join(",")
<add> end
<ide> end
<ide>
<ide> sql << " RETURNING #{insert.returning}" if insert.returning
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def build_insert_sql(insert) # :nodoc:
<ide> sql << " ON CONFLICT #{insert.conflict_target} DO NOTHING"
<ide> elsif insert.update_duplicates?
<ide> sql << " ON CONFLICT #{insert.conflict_target} DO UPDATE SET "
<del> sql << insert.touch_model_timestamps_unless { |column| "#{column} IS excluded.#{column}" }
<del> sql << insert.updatable_columns.map { |column| "#{column}=excluded.#{column}" }.join(",")
<add> if insert.raw_update_sql?
<add> sql << insert.raw_update_sql
<add> else
<add> sql << insert.touch_model_timestamps_unless { |column| "#{column} IS excluded.#{column}" }
<add> sql << insert.updatable_columns.map { |column| "#{column}=excluded.#{column}" }.join(",")
<add> end
<ide> end
<ide>
<ide> sql
<ide><path>activerecord/lib/active_record/insert_all.rb
<ide> module ActiveRecord
<ide> class InsertAll # :nodoc:
<ide> attr_reader :model, :connection, :inserts, :keys
<del> attr_reader :on_duplicate, :returning, :unique_by
<add> attr_reader :on_duplicate, :returning, :unique_by, :update_sql
<ide>
<del> def initialize(model, inserts, on_duplicate:, returning: nil, unique_by: nil)
<add> def initialize(model, inserts, on_duplicate:, returning: nil, unique_by: nil, update_sql: nil)
<ide> raise ArgumentError, "Empty list of attributes passed" if inserts.blank?
<ide>
<ide> @model, @connection, @inserts, @keys = model, model.connection, inserts, inserts.first.keys.map(&:to_s)
<del> @on_duplicate, @returning, @unique_by = on_duplicate, returning, unique_by
<add> @on_duplicate, @returning, @unique_by, @update_sql = on_duplicate, returning, unique_by, update_sql
<ide>
<ide> if model.scope_attributes?
<ide> @scope_attributes = model.scope_attributes
<ide> def touch_model_timestamps_unless(&block)
<ide> end.compact.join
<ide> end
<ide>
<add> def raw_update_sql
<add> insert_all.update_sql
<add> end
<add>
<add> alias raw_update_sql? raw_update_sql
<add>
<ide> private
<ide> attr_reader :connection, :insert_all
<ide>
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def insert_all!(attributes, returning: nil)
<ide> # go through Active Record's type casting and serialization.
<ide> #
<ide> # See <tt>ActiveRecord::Persistence#upsert_all</tt> for documentation.
<del> def upsert(attributes, returning: nil, unique_by: nil)
<del> upsert_all([ attributes ], returning: returning, unique_by: unique_by)
<add> def upsert(attributes, returning: nil, unique_by: nil, update_sql: nil)
<add> upsert_all([ attributes ], returning: returning, unique_by: unique_by, update_sql: update_sql)
<ide> end
<ide>
<ide> # Updates or inserts (upserts) multiple records into the database in a
<ide> def upsert(attributes, returning: nil, unique_by: nil)
<ide> # <tt>:unique_by</tt> is recommended to be paired with
<ide> # Active Record's schema_cache.
<ide> #
<add> # [:update_sql]
<add> # Specify a custom SQL for updating rows on conflict.
<add> #
<add> # NOTE: in this case you must provide all the columns you want to update by yourself.
<add> #
<ide> # ==== Examples
<ide> #
<ide> # # Inserts multiple records, performing an upsert when records have duplicate ISBNs.
<ide> def upsert(attributes, returning: nil, unique_by: nil)
<ide> # ], unique_by: :isbn)
<ide> #
<ide> # Book.find_by(isbn: "1").title # => "Eloquent Ruby"
<del> def upsert_all(attributes, returning: nil, unique_by: nil)
<del> InsertAll.new(self, attributes, on_duplicate: :update, returning: returning, unique_by: unique_by).execute
<add> def upsert_all(attributes, returning: nil, unique_by: nil, update_sql: nil)
<add> InsertAll.new(self, attributes, on_duplicate: :update, returning: returning, unique_by: unique_by, update_sql: update_sql).execute
<ide> end
<ide>
<ide> # Given an attributes hash, +instantiate+ returns a new instance of
<ide><path>activerecord/test/cases/insert_all_test.rb
<ide> def test_upsert_all_has_many_through
<ide> assert_raise(ArgumentError) { book.subscribers.upsert_all([ { nick: "Jimmy" } ]) }
<ide> end
<ide>
<add> def test_upsert_all_updates_using_provided_sql
<add> skip unless supports_insert_on_duplicate_update?
<add>
<add> operator = sqlite? ? "MAX" : "GREATEST"
<add>
<add> Book.upsert_all(
<add> [{ id: 1, status: 1 }, { id: 2, status: 1 }],
<add> update_sql: "status = #{operator}(books.status, 1)"
<add> )
<add> assert_equal "published", Book.find(1).status
<add> assert_equal "written", Book.find(2).status
<add> end
<add>
<ide> private
<ide> def capture_log_output
<ide> output = StringIO.new
<ide> def capture_log_output
<ide> ActiveRecord::Base.logger = old_logger
<ide> end
<ide> end
<add>
<add> def sqlite?
<add> ActiveRecord::Base.connection.adapter_name.match?(/sqlite/i)
<add> end
<ide> end | 7 |
Text | Text | introduce runhaskell option | 69a6531bb9f7a89fbed80c3b3c899358a1a8ab9f | <ide><path>guide/english/haskell/index.md
<ide> stack ghc hello.hs
<ide> ./hello
<ide> ```
<ide>
<add>Alternatively, you can use `runhaskell` to skip the compiling step.
<add>
<add>```shell
<add>stack runhaskell hello.hs
<add>```
<add>
<ide> ## Documentation
<ide> Hackage provides documentation for Haskell
<ide> | 1 |
Text | Text | add new wordings to the api description | 2b985a2027e99a3cff277fa21a42903316e9c248 | <ide><path>doc/api/process.md
<ide> exception value itself as its first argument.
<ide> If such a function is set, the [`'uncaughtException'`][] event will
<ide> not be emitted. If `--abort-on-uncaught-exception` was passed from the
<ide> command line or set through [`v8.setFlagsFromString()`][], the process will
<del>not abort.
<add>not abort. Actions configured to take place on exceptions such as report
<add>generations will be affected too
<ide>
<ide> To unset the capture function,
<ide> `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this | 1 |
PHP | PHP | add encrypt() and decrypt() methods | 215d43eb066369681b0a7637392a287bd36abf5d | <ide><path>lib/Cake/Test/Case/Utility/SecurityTest.php
<ide> public function testRijndaelInvalidKey() {
<ide> Security::rijndael($txt, $key, 'encrypt');
<ide> }
<ide>
<add>/**
<add> * Test encrypt/decrypt.
<add> *
<add> * @return void
<add> */
<add> public function testEncryptDecrypt() {
<add> $txt = 'The quick brown fox';
<add> $key = 'This key is longer than 32 bytes long.';
<add> $result = Security::encrypt($txt, $key);
<add> $this->assertNotEquals($txt, $result, 'Should be encrypted.');
<add> $this->assertNotEquals($result, Security::encrypt($txt, $key), 'Each result is unique.');
<add> $this->assertEquals($txt, Security::decrypt($result, $key));
<add> }
<add>
<add>/**
<add> * Test that short keys cause errors
<add> *
<add> * @expectedException CakeException
<add> * @expectedExceptionMessage Invalid key for encrypt(), key must be at least 256 bits (32 bytes) long.
<add> * @return void
<add> */
<add> public function testEncryptInvalidKey() {
<add> $txt = 'The quick brown fox jumped over the lazy dog.';
<add> $key = 'this is too short';
<add> Security::encrypt($txt, $key);
<add> }
<add>
<add>/**
<add> * Test that empty data cause errors
<add> *
<add> * @expectedException CakeException
<add> * @expectedExceptionMessage The data to encrypt cannot be empty.
<add> * @return void
<add> */
<add> public function testEncryptInvalidData() {
<add> $txt = '';
<add> $key = 'This is a key that is long enough to be ok.';
<add> Security::encrypt($txt, $key);
<add> }
<add>
<add>
<add>/**
<add> * Test that short keys cause errors
<add> *
<add> * @expectedException CakeException
<add> * @expectedExceptionMessage Invalid key for decrypt(), key must be at least 256 bits (32 bytes) long.
<add> * @return void
<add> */
<add> public function testDecryptInvalidKey() {
<add> $txt = 'The quick brown fox jumped over the lazy dog.';
<add> $key = 'this is too short';
<add> Security::decrypt($txt, $key);
<add> }
<add>
<add>/**
<add> * Test that empty data cause errors
<add> *
<add> * @expectedException CakeException
<add> * @expectedExceptionMessage The data to decrypt cannot be empty.
<add> * @return void
<add> */
<add> public function testDecryptInvalidData() {
<add> $txt = '';
<add> $key = 'This is a key that is long enough to be ok.';
<add> Security::decrypt($txt, $key);
<add> }
<add>
<ide> }
<ide><path>lib/Cake/Utility/Security.php
<ide> protected static function _crypt($password, $salt = false) {
<ide> return crypt($password, $salt);
<ide> }
<ide>
<add>/**
<add> * Encrypt a value using AES-256.
<add> *
<add> * *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes.
<add> * Any trailing null bytes will be removed on decryption due to how PHP pads messages
<add> * with nulls prior to encryption.
<add> *
<add> * @param string $plain The value to encrypt.
<add> * @param string $key The 256 bit/32 byte key to use as a cipher key.
<add> * @return string Encrypted data.
<add> * @throws CakeException On invalid data or key.
<add> */
<add> public static function encrypt($plain, $key) {
<add> static::_checkKey($key, 'encrypt()');
<add> if (empty($plain)) {
<add> throw new CakeException(__d('cake_dev', 'The data to encrypt cannot be empty.'));
<add> }
<add> $key = substr($key, 0, 32);
<add> $algorithm = MCRYPT_RIJNDAEL_128;
<add> $mode = MCRYPT_MODE_CBC;
<add>
<add> $ivSize = mcrypt_get_iv_size($algorithm, $mode);
<add> $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
<add> return $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv);
<add> }
<add>
<add>/**
<add> * Check the encryption key for proper length.
<add> *
<add> * @param string $key
<add> * @param string $method The method the key is being checked for.
<add> * @return void
<add> * @throws CakeException When key length is not 256 bit/32 bytes
<add> */
<add> protected static function _checkKey($key, $method) {
<add> if (strlen($key) < 32) {
<add> throw new CakeException(__d('cake_dev', 'Invalid key for %s, key must be at least 256 bits (32 bytes) long.', $method));
<add> }
<add> }
<add>
<add>/**
<add> * Decrypt a value using AES-256.
<add> *
<add> * @param string $cipher The ciphertext to decrypt.
<add> * @param string $key The 256 bit/32 byte key to use as a cipher key.
<add> * @return string Decrypted data. Any trailing null bytes will be removed.
<add> * @throws CakeException On invalid data or key.
<add> */
<add> public static function decrypt($cipher, $key) {
<add> static::_checkKey($key, 'decrypt()');
<add> if (empty($cipher)) {
<add> throw new CakeException(__d('cake_dev', 'The data to decrypt cannot be empty.'));
<add> }
<add> $key = substr($key, 0, 32);
<add>
<add> $algorithm = MCRYPT_RIJNDAEL_128;
<add> $mode = MCRYPT_MODE_CBC;
<add> $ivSize = mcrypt_get_iv_size($algorithm, $mode);
<add>
<add> $iv = substr($cipher, 0, $ivSize);
<add> $cipher = substr($cipher, $ivSize);
<add> $plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
<add> return rtrim($plain, "\0");
<add> }
<add>
<ide> } | 2 |
Javascript | Javascript | fix lint errors thrown in ci | c0104faa38a61647b57280499fd8dcb84eebec32 | <ide><path>api-server/server/middlewares/jwt-authorizaion.test.js
<add>/* global describe xdescribe it expect */
<ide> import { isWhiteListedPath } from './jwt-authorization';
<ide>
<ide> describe('jwt-authorization', () => {
<ide> describe('jwt-authorization', () => {
<ide> });
<ide> });
<ide>
<del> xdescribe('authorizeByJWT')
<add> xdescribe('authorizeByJWT');
<ide> });
<ide><path>api-server/server/middlewares/jwt-authorization.js
<ide> const apiProxyRE = /^\/internal\/|^\/external\//;
<ide> const newsShortLinksRE = /^\/internal\/n\/|^\/internal\/p\?/;
<ide> const loopbackAPIPathRE = /^\/internal\/api\//;
<ide>
<del>const _whiteListREs = [
<del> newsShortLinksRE,
<del> loopbackAPIPathRE
<del>];
<add>const _whiteListREs = [newsShortLinksRE, loopbackAPIPathRE];
<ide>
<del>export function isWhiteListedPath(path, whiteListREs= _whiteListREs) {
<del> return whiteListREs.some(re => re.test(path))
<add>export function isWhiteListedPath(path, whiteListREs = _whiteListREs) {
<add> return whiteListREs.some(re => re.test(path));
<ide> }
<ide>
<add>export default () =>
<add> function authorizeByJWT(req, res, next) {
<add> const { path } = req;
<add> if (apiProxyRE.test(path) && !isWhiteListedPath(path)) {
<add> const cookie =
<add> (req.signedCookies && req.signedCookies['jwt_access_token']) ||
<add> (req.cookie && req.cookie['jwt_access_token']);
<ide>
<del>export default () => function authorizeByJWT(req, res, next) {
<del> const { path } = req;
<del> if (apiProxyRE.test(path) && !isWhiteListedPath(path)) {
<del> const cookie = req.signedCookies && req.signedCookies['jwt_access_token'] ||
<del> req.cookie && req.cookie['jwt_access_token'];
<del>
<del> if (!cookie) {
<del> throw wrapHandledError(
<del> new Error('Access token is required for this request'),
<del> {
<del> type: 'info',
<del> redirect: `${homeLocation}/signin`,
<del> message: 'Access token is required for this request',
<del> status: 403
<del> }
<del> );
<del> }
<del> let token;
<del> try {
<del> token = jwt.verify(cookie, process.env.JWT_SECRET);
<del> } catch (err) {
<del> throw wrapHandledError(
<del> new Error(err.message),
<del> {
<add> if (!cookie) {
<add> throw wrapHandledError(
<add> new Error('Access token is required for this request'),
<add> {
<add> type: 'info',
<add> redirect: `${homeLocation}/signin`,
<add> message: 'Access token is required for this request',
<add> status: 403
<add> }
<add> );
<add> }
<add> let token;
<add> try {
<add> token = jwt.verify(cookie, process.env.JWT_SECRET);
<add> } catch (err) {
<add> throw wrapHandledError(new Error(err.message), {
<ide> type: 'info',
<ide> redirect: `${homeLocation}/signin`,
<ide> message: 'Your access token is invalid',
<ide> status: 403
<del> }
<del> );
<del> }
<del> const { accessToken: {created, ttl, userId }} = token;
<del> const valid = isBefore(Date.now(), Date.parse(created) + ttl);
<del> if (!valid) {
<del> throw wrapHandledError(
<del> new Error('Access token is no longer vaild'),
<del> {
<add> });
<add> }
<add> const {
<add> accessToken: { created, ttl, userId }
<add> } = token;
<add> const valid = isBefore(Date.now(), Date.parse(created) + ttl);
<add> if (!valid) {
<add> throw wrapHandledError(new Error('Access token is no longer vaild'), {
<ide> type: 'info',
<ide> redirect: `${homeLocation}/signin`,
<ide> message: 'Access token is no longer vaild',
<ide> status: 403
<del> }
<del> );
<del> }
<del> if (!req.user) {
<del> const User = loopback.getModelByType('User');
<del> return User.findById(userId)
<del> .then(user => {
<del> if (user) {
<del> user.points = user.progressTimestamps.length;
<del> req.user = user;
<del> }
<del> return;
<del> })
<del> .then(next)
<del> .catch(next);
<del> } else {
<del> return next();
<add> });
<add> }
<add> if (!req.user) {
<add> const User = loopback.getModelByType('User');
<add> return User.findById(userId)
<add> .then(user => {
<add> if (user) {
<add> user.points = user.progressTimestamps.length;
<add> req.user = user;
<add> }
<add> return;
<add> })
<add> .then(next)
<add> .catch(next);
<add> } else {
<add> return next();
<add> }
<ide> }
<del> }
<del> return next();
<del>};
<add> return next();
<add> };
<ide><path>client/src/utils/ajax.js
<ide> import axios from 'axios';
<ide>
<del>const base = `/internal`;
<add>const base = '/internal';
<ide>
<ide> function get(path) {
<ide> return axios.get(`${base}${path}`);
<ide> export function getArticleById(shortId) {
<ide>
<ide> /** POST **/
<ide>
<del>
<ide> export function postReportUser(body) {
<ide> return post('/user/report-user', body);
<ide> } | 3 |
Python | Python | add missing tokenizer exceptions (resolves ) | edc596d9a77cf0281b3641297fd5abd62a74edf2 | <ide><path>spacy/en/tokenizer_exceptions.py
<ide> {ORTH: "are", LEMMA: "be", TAG: "VBP", "number": 2},
<ide> {ORTH: "is", LEMMA: "be", TAG: "VBZ"},
<ide> {ORTH: "was", LEMMA: "be"},
<del> {ORTH: "were", LEMMA: "be"}
<add> {ORTH: "were", LEMMA: "be"},
<add> {ORTH: "have"},
<add> {ORTH: "has", LEMMA: "have"},
<add> {ORTH: "dare"}
<ide> ]:
<ide> verb_data_tc = dict(verb_data)
<ide> verb_data_tc[ORTH] = verb_data_tc[ORTH].title() | 1 |
Javascript | Javascript | allow publishing with `beta` tag | 96ca8d9155043e4636308edd6501fde67ce40aa5 | <ide><path>scripts/release/publish-commands/parse-params.js
<ide> module.exports = () => {
<ide> case 'next':
<ide> case 'experimental':
<ide> case 'alpha':
<add> case 'beta':
<ide> case 'untagged':
<ide> break;
<ide> default: | 1 |
Javascript | Javascript | reset meta on recompile | 862478e3b4956caa10527d760baf775c2d2f79b2 | <ide><path>lib/NormalModule.js
<ide> NormalModule.prototype.build = function build(options, compilation, resolver, fs
<ide> _this.error = null;
<ide> _this.errors.length = 0;
<ide> _this.warnings.length = 0;
<add> _this.meta = {};
<ide> return _this.doBuild(options, compilation, resolver, fs, function(err) {
<ide> _this.dependencies.length = 0;
<ide> _this.variables.length = 0; | 1 |
Text | Text | add notes to contributing docs | e80b353085c460c5ab7e9b4d22249f01176c5eb1 | <ide><path>docs/topics/contributing.md
<ide> Some tips on good issue reporting:
<ide> * When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
<ide> * Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
<ide> * If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
<add>* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintainence overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
<add>* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
<ide>
<ide> ## Triaging issues
<ide>
<ide> Getting involved in triaging incoming issues is a good way to start contributing
<ide> * Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
<ide> * If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
<ide> * If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?
<add>* If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.
<ide>
<ide> # Development
<ide> | 1 |
Text | Text | fix email with name format in guides. [ci skip] | ac6180ec1b25563405cbcb868804a098424e3a0f | <ide><path>guides/source/action_mailer_basics.md
<ide> The same format can be used to set carbon copy (Cc:) and blind carbon copy
<ide>
<ide> Sometimes you wish to show the name of the person instead of just their email
<ide> address when they receive the email. The trick to doing that is to format the
<del>email address in the format `"Full Name <email>"`.
<add>email address in the format `"Full Name" <email>`.
<ide>
<ide> ```ruby
<ide> def welcome_email(user) | 1 |
Text | Text | update cryptocurrency chinese index.md | 2baac0f8fe2fd9021fd6f5a069bdcb26e84d0422 | <ide><path>guide/chinese/blockchain/cryptocurrency/index.md
<ide> localeTitle: Cryptocurrency
<ide> ---
<ide> ## Cryptocurrency
<ide>
<del>> 宣布首次发布比特币,这是一种新的电子现金系统,它使用点对点网络来防止双重支出。它完全是分散的,没有服务器或中央权限。
<add>> 宣告首次发布比特币,这是一种新的电子现金系统,它使用点对点网络来防止双重支出。它完全是去中心化的,没有服务器或中央权限。
<ide> >
<del>> \- Satoshi Nakamoto,2009年1月9日,在SourceForge上宣布比特币。
<add>> \- Satoshi Nakamoto,2009年1月9日,在SourceForge上宣告发布比特币。
<ide>
<del>加密货币是数字货币的一个子集,它作为双方之间的交换媒介。它被称为加密货币,因为利用密码术来保护其交易。有各种加密货币,包括LiteCoin,Dash,以太坊,Ripple,以及目前最流行的比特币。这是进行无信任交易的完美方式,因为它不涉及任何第三方。
<add>加密货币是数字货币的一个子集,它作为双方之间的交换媒介。它被称为加密货币,因为利用密码术来保护其交易。例如,有各种加密货币,包括LiteCoin,Dash,以太坊,Ripple,以及目前最流行的比特币。这是进行无信任和匿名交易的完美方式,因为它不涉及任何第三方。
<ide>
<ide> 与普通货币不同,加密货币可以作为分数交换。例如,交易可达0.00007 Btc甚至更低。
<ide>
<ide> localeTitle: Cryptocurrency
<ide> [Cryptocurrency](https://en.wikipedia.org/wiki/Cryptocurrency)
<ide> [加密货币终极指南](https://blockgeeks.com/guides/what-is-cryptocurrency)
<ide>
<del>[比特币](https://en.wikipedia.org/wiki/Bitcoin)
<ide>\ No newline at end of file
<add>[比特币](https://en.wikipedia.org/wiki/Bitcoin) | 1 |
Python | Python | fix word typos in comments | 90db98304e06a60a3c578e9f55fe139524a4c3f8 | <ide><path>sorts/bead_sort.py
<ide> """
<del>Bead sort only works for sequences of nonegative integers.
<add>Bead sort only works for sequences of non-negative integers.
<ide> https://en.wikipedia.org/wiki/Bead_sort
<ide> """
<ide>
<ide><path>sorts/odd_even_transposition_single_threaded.py
<ide> """
<ide> Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
<ide>
<del>This is a non-parallelized implementation of odd-even transpostiion sort.
<add>This is a non-parallelized implementation of odd-even transposition sort.
<ide>
<ide> Normally the swaps in each set happen simultaneously, without that the algorithm
<ide> is no better than bubble sort.
<ide><path>sorts/topological_sort.py
<ide>
<ide>
<ide> def topological_sort(start, visited, sort):
<del> """Perform topolical sort on a directed acyclic graph."""
<add> """Perform topological sort on a directed acyclic graph."""
<ide> current = start
<ide> # add current to visited
<ide> visited.append(current)
<ide><path>strings/prefix_function.py
<ide> def prefix_function(input_string: str) -> list:
<ide> """
<ide> For the given string this function computes value for each index(i),
<del> which represents the longest coincidence of prefix and sufix
<add> which represents the longest coincidence of prefix and suffix
<ide> for given substring (input_str[0...i])
<ide>
<ide> For the value of the first element the algorithm always returns 0
<ide> def prefix_function(input_string: str) -> list:
<ide> def longest_prefix(input_str: str) -> int:
<ide> """
<ide> Prefix-function use case
<del> Finding longest prefix which is sufix as well
<add> Finding longest prefix which is suffix as well
<ide>
<ide> >>> longest_prefix("aabcdaabc")
<ide> 4 | 4 |
Go | Go | remove cache opti that cause wrong cache miss | 881fdc59edf39ba8d87b44b05db7fcd95661d083 | <ide><path>server.go
<ide> func (srv *Server) ImageDelete(name string) error {
<ide> }
<ide>
<ide> func (srv *Server) ImageGetCached(imgId string, config *Config) (*Image, error) {
<del> byParent, err := srv.runtime.graph.ByParent()
<add>
<add> // Retrieve all images
<add> images, err := srv.runtime.graph.All()
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<add> // Store the tree in a map of map (map[parentId][childId])
<add> imageMap := make(map[string]map[string]struct{})
<add> for _, img := range images {
<add> if _, exists := imageMap[img.Parent]; !exists {
<add> imageMap[img.Parent] = make(map[string]struct{})
<add> }
<add> imageMap[img.Parent][img.Id] = struct{}{}
<add> }
<add>
<ide> // Loop on the children of the given image and check the config
<del> for _, img := range byParent[imgId] {
<add> for elem := range imageMap[imgId] {
<add> img, err := srv.runtime.graph.Get(elem)
<add> if err != nil {
<add> return nil, err
<add> }
<ide> if CompareConfig(&img.ContainerConfig, config) {
<ide> return img, nil
<ide> } | 1 |
Python | Python | update create_global_jinja_loader docstring, #321 | f6798885e6cc97bccd1e0fd861b54b01fcdb9605 | <ide><path>flask/app.py
<ide> def create_global_jinja_loader(self):
<ide> """Creates the loader for the Jinja2 environment. Can be used to
<ide> override just the loader and keeping the rest unchanged. It's
<ide> discouraged to override this function. Instead one should override
<del> the :meth:`create_jinja_loader` function instead.
<add> the :meth:`jinja_loader` function instead.
<ide>
<ide> The global loader dispatches between the loaders of the application
<ide> and the individual blueprints. | 1 |
PHP | PHP | fix 0/'0' not being patched properly | b2ed6a289e40ed12509a0364a09e0610e667e377 | <ide><path>src/ORM/Marshaller.php
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> } elseif ($columnType) {
<ide> $converter = Type::build($columnType);
<ide> $value = $converter->marshal($value);
<del> if ($original == $value) {
<add> $isObject = is_object($value);
<add> if (
<add> (!$isObject && $original === $value) ||
<add> ($isObject && $original == $value)
<add> ) {
<ide> continue;
<ide> }
<ide> }
<ide><path>tests/TestCase/ORM/MarshallerTest.php
<ide> public function testMergeSimple() {
<ide> $this->assertFalse($result->isNew(), 'Should not change the entity state');
<ide> }
<ide>
<add>/**
<add> * Provides empty values.
<add> *
<add> * @return array
<add> */
<add> public function emptyProvider() {
<add> return [
<add> [0],
<add> ['0'],
<add> ];
<add> }
<add>
<add>/**
<add> * Test merging empty values into an entity.
<add> *
<add> * @dataProvider emptyProvider
<add> * @return void
<add> */
<add> public function testMergeFalseyValues($value) {
<add> $marshall = new Marshaller($this->articles);
<add> $entity = new Entity();
<add> $entity->accessible('*', true);
<add>
<add> $entity = $marshall->merge($entity, ['author_id' => $value]);
<add> $this->assertTrue($entity->dirty('author_id'), 'Field should be dirty');
<add> $this->assertSame(0, $entity->get('author_id'), 'Value should be zero');
<add> }
<add>
<ide> /**
<ide> * Tests that merge respects the entity accessible methods
<ide> * | 2 |
Java | Java | replace slf4j with acl tilesconfigurer for tiles 3 | fb05c7b33c469d5a7826ff8efe3168329617b6b5 | <ide><path>spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java
<ide> import javax.servlet.ServletContext;
<ide> import javax.servlet.jsp.JspFactory;
<ide>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<ide> import org.apache.tiles.TilesContainer;
<ide> import org.apache.tiles.TilesException;
<ide> import org.apache.tiles.access.TilesAccess;
<ide> import org.apache.tiles.request.ApplicationResource;
<ide> import org.apache.tiles.startup.DefaultTilesInitializer;
<ide> import org.apache.tiles.startup.TilesInitializer;
<del>import org.slf4j.Logger;
<del>import org.slf4j.LoggerFactory;
<ide> import org.springframework.beans.BeanUtils;
<ide> import org.springframework.beans.BeanWrapper;
<ide> import org.springframework.beans.PropertyAccessorFactory;
<ide> public class TilesConfigurer implements ServletContextAware, InitializingBean, D
<ide> ClassUtils.isPresent("javax.servlet.jsp.JspApplicationContext", TilesConfigurer.class.getClassLoader()) &&
<ide> ClassUtils.isPresent("org.apache.tiles.el.ELAttributeEvaluator", TilesConfigurer.class.getClassLoader());
<ide>
<del> protected final Logger logger = LoggerFactory.getLogger(getClass());
<add> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<ide> private TilesInitializer tilesInitializer;
<ide> | 1 |
Ruby | Ruby | remove inner uncaptured group | 17aa90a2c591d922b293a73bdf68e0bfeb0e1301 | <ide><path>Library/Homebrew/version.rb
<ide> def self._parse(spec)
<ide>
<ide> # date-based versioning
<ide> # e.g. ltopers-v2017-04-14.tar.gz
<del> m = /-v?((?:\d{4}-\d{2}-\d{2}))/.match(stem)
<add> m = /-v?(?:\d{4}-\d{2}-\d{2})/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. lame-398-1 | 1 |
Text | Text | demonstrate dangers of `buffer.slice()` | 087939471a47d7059223a5f52c933d37cbe547a9 | <ide><path>doc/api/buffer.md
<ide> console.log(copiedBuf.toString());
<ide>
<ide> console.log(buf.toString());
<ide> // Prints: buffer
<add>
<add>// With buf.slice(), the original buffer is modified.
<add>const notReallyCopiedBuf = buf.slice();
<add>notReallyCopiedBuf[0]++;
<add>console.log(notReallyCopiedBuf.toString());
<add>// Prints: cuffer
<add>console.log(buf.toString());
<add>// Also prints: cuffer (!)
<ide> ```
<ide>
<ide> ```cjs
<ide> console.log(copiedBuf.toString());
<ide>
<ide> console.log(buf.toString());
<ide> // Prints: buffer
<add>
<add>// With buf.slice(), the original buffer is modified.
<add>const notReallyCopiedBuf = buf.slice();
<add>notReallyCopiedBuf[0]++;
<add>console.log(notReallyCopiedBuf.toString());
<add>// Prints: cuffer
<add>console.log(buf.toString());
<add>// Also prints: cuffer (!)
<ide> ```
<ide>
<ide> ### `buf.swap16()` | 1 |
Mixed | Ruby | add x-original-to to mail using mailgun recipient | 667d69cc5b0527d0c3d0887cd175114e9310d519 | <ide><path>actionmailbox/CHANGELOG.md
<add>* Mailgun ingress now passes through the envelope recipient as `X-Original-To`.
<add>
<add> *Rikki Pitt*
<add>
<ide> * Deprecate `Rails.application.credentials.action_mailbox.api_key` and `MAILGUN_INGRESS_API_KEY` in favor of `Rails.application.credentials.action_mailbox.signing_key` and `MAILGUN_INGRESS_SIGNING_KEY`.
<ide>
<ide> *Matthijs Vos*
<ide><path>actionmailbox/app/controllers/action_mailbox/ingresses/mailgun/inbound_emails_controller.rb
<ide> class Ingresses::Mailgun::InboundEmailsController < ActionMailbox::BaseControlle
<ide> before_action :authenticate
<ide>
<ide> def create
<del> ActionMailbox::InboundEmail.create_and_extract_message_id! params.require("body-mime")
<add> ActionMailbox::InboundEmail.create_and_extract_message_id! mail
<ide> end
<ide>
<ide> private
<add> def mail
<add> params.require("body-mime").tap do |raw_email|
<add> raw_email.prepend("X-Original-To: ", params.require(:recipient), "\n") if params.key?(:recipient)
<add> end
<add> end
<add>
<ide> def authenticate
<ide> head :unauthorized unless authenticated?
<ide> end
<ide><path>actionmailbox/test/controllers/ingresses/mailgun/inbound_emails_controller_test.rb
<ide> class ActionMailbox::Ingresses::Mailgun::InboundEmailsControllerTest < ActionDis
<ide> assert_equal "0CB459E0-0336-41DA-BC88-E6E28C697DDB@37signals.com", inbound_email.message_id
<ide> end
<ide>
<add> test "add X-Original-To to email from Mailgun" do
<add> assert_difference -> { ActionMailbox::InboundEmail.count }, +1 do
<add> travel_to "2018-10-09 15:15:00 EDT"
<add> post rails_mailgun_inbound_emails_url, params: {
<add> timestamp: 1539112500,
<add> token: "7VwW7k6Ak7zcTwoSoNm7aTtbk1g67MKAnsYLfUB7PdszbgR5Xi",
<add> signature: "ef24c5225322217bb065b80bb54eb4f9206d764e3e16abab07f0a64d1cf477cc",
<add> "body-mime" => file_fixture("../files/welcome.eml").read,
<add> recipient: "replies@example.com"
<add> }
<add> end
<add>
<add> assert_response :no_content
<add>
<add> inbound_email = ActionMailbox::InboundEmail.last
<add> mail = Mail.from_source(inbound_email.raw_email.download)
<add> assert_equal "replies@example.com", mail.header["X-Original-To"].decoded
<add> end
<add>
<ide> test "rejecting a delayed inbound email from Mailgun" do
<ide> assert_no_difference -> { ActionMailbox::InboundEmail.count } do
<ide> travel_to "2018-10-09 15:26:00 EDT" | 3 |
Text | Text | fix broken markup [ci skip] | 22483b86a6c779743b30e2f23bb46accfbf96b28 | <ide><path>activesupport/CHANGELOG.md
<ide> * `Array#to_sentence` no longer returns a frozen string.
<ide>
<ide> Before:
<add>
<ide> ['one', 'two'].to_sentence.frozen?
<ide> # => true
<ide>
<ide> After:
<add>
<ide> ['one', 'two'].to_sentence.frozen?
<ide> # => false
<ide> | 1 |
Ruby | Ruby | get all resources in all formulae | 59165ed3ec78466b0536f347dcbeb60cde7587cc | <ide><path>Library/Homebrew/dev-cmd/livecheck.rb
<ide> def livecheck
<ide> formulae = args.cask? ? [] : Formula.installed
<ide> casks = args.formula? ? [] : Cask::Caskroom.casks
<ide> formulae + casks
<add> elsif args.resources?
<add> resources = Formula.all do |formula|
<add> formula.resources.any do |resource|
<add> if resource.livecheckable?
<add> p resource
<add> end
<add> end
<add> end
<ide> elsif args.all?
<ide> formulae = args.cask? ? [] : Formula.all
<ide> casks = args.formula? ? [] : Cask::Cask.all
<ide> def livecheck
<ide> else
<ide> raise UsageError, "A watchlist file is required when no arguments are given."
<ide> end
<add> p formulae_and_casks_to_check.class
<add> p formulae_and_casks_to_check.length
<add> p formulae_and_casks_to_check[0].class
<add> p formulae_and_casks_to_check[0]
<add>
<ide> formulae_and_casks_to_check = formulae_and_casks_to_check.sort_by do |formula_or_cask|
<ide> formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name
<ide> end
<ide> def livecheck
<ide> verbose: args.verbose?,
<ide> }.compact
<ide>
<del> Livecheck.run_checks(formulae_and_casks_to_check, **options)
<add> # Livecheck.run_checks(formulae_and_casks_to_check, **options)
<ide> end
<ide> end | 1 |
PHP | PHP | pass response in laravel done event | 17bd505ff6d331530232a5da8e3c0a28220f1e64 | <ide><path>laravel/laravel.php
<ide> |
<ide> */
<ide>
<del>Event::fire('laravel.done');
<ide>\ No newline at end of file
<add>Event::fire('laravel.done', array($response));
<ide>\ No newline at end of file
<ide><path>laravel/profiling/profiler.php
<ide> public static function attach()
<ide> // We'll attach the profiler to the "done" event so that we can easily
<ide> // attach the profiler output to the end of the output sent to the
<ide> // browser. This will display the profiler's nice toolbar.
<del> Event::listen('laravel.done', function()
<add> Event::listen('laravel.done', function($response)
<ide> {
<ide> echo Profiler::render();
<ide> }); | 2 |
Text | Text | fix broken links on using immutable.js docs | 885a2db6ef8721bb8facd1a6df2fcff979237ee4 | <ide><path>docs/recipes/UsingImmutableJS.md
<ide> hide_title: true
<ide>
<ide> ## Table of Contents
<ide>
<del>- [Why should I use an immutable-focused library such as Immutable.JS?](#why-should-i-use-an-immutable-focused-library-such-as-immutable-js)
<del>- [Why should I choose Immutable.JS as an immutable library?](#why-should-i-choose-immutable-js-as-an-immutable-library)
<del>- [What are the issues with using Immutable.JS?](#what-are-the-issues-with-using-immutable-js)
<del>- [Is Immutable.JS worth the effort?](#is-using-immutable-js-worth-the-effort)
<del>- [What are some opinionated Best Practices for using Immutable.JS with Redux?](#what-are-some-opinionated-best-practices-for-using-immutable-js-with-redux)
<add>- [Why should I use an immutable-focused library such as Immutable.JS?](#why-should-i-use-an-immutable-focused-library-such-as-immutablejs)
<add>- [Why should I choose Immutable.JS as an immutable library?](#why-should-i-choose-immutablejs-as-an-immutable-library)
<add>- [What are the issues with using Immutable.JS?](#what-are-the-issues-with-using-immutablejs)
<add>- [Is Immutable.JS worth the effort?](#is-using-immutablejs-worth-the-effort)
<add>- [What are some opinionated Best Practices for using Immutable.JS with Redux?](#what-are-some-opinionated-best-practices-for-using-immutablejs-with-redux)
<ide>
<ide> ## Why should I use an immutable-focused library such as Immutable.JS?
<ide>
<ide> Once you encapsulate your data with Immutable.JS, you have to use Immutable.JS
<ide>
<ide> This has the effect of spreading Immutable.JS across your entire codebase, including potentially your components, where you may prefer not to have such external dependencies. Your entire codebase must know what is, and what is not, an Immutable.JS object. It also makes removing Immutable.JS from your app difficult in the future, should you ever need to.
<ide>
<del>This issue can be avoided by [uncoupling your application logic from your data structures](https://medium.com/@dtinth/immutable-js-persistent-data-structures-and-structural-sharing-6d163fbd73d2#.z1g1ofrsi), as outlined in the [best practices section](#immutable-js-best-practices) below.
<add>This issue can be avoided by [uncoupling your application logic from your data structures](https://medium.com/@dtinth/immutable-js-persistent-data-structures-and-structural-sharing-6d163fbd73d2#.z1g1ofrsi), as outlined in the [best practices section](#what-are-some-opinionated-best-practices-for-using-immutablejs-with-redux) below.
<ide>
<ide> ### No Destructuring or Spread Operators
<ide>
<ide> function mapStateToProps(state) {
<ide>
<ide> When the shallow check fails, React-Redux will cause the component to re-render. Using `toJS()` in `mapStateToProps` in this way, therefore, will always cause the component to re-render, even if the value never changes, impacting heavily on performance.
<ide>
<del>This can be prevented by using `toJS()` in a Higher Order Component, as discussed in the [Best Practices section](#immutable-js-best-practices) below.
<add>This can be prevented by using `toJS()` in a Higher Order Component, as discussed in the [Best Practices section](#what-are-some-opinionated-best-practices-for-using-immutablejs-with-redux) below.
<ide>
<ide> #### Further Information
<ide> | 1 |
Python | Python | add basic benchmarks for take and putmask | 9fc60fb5462beff905a582536033f40030bc7291 | <ide><path>benchmarks/benchmarks/bench_itemselection.py
<add>from __future__ import absolute_import, division, print_function
<add>
<add>from .common import Benchmark, TYPES1
<add>
<add>import numpy as np
<add>
<add>
<add>class Take(Benchmark):
<add> params = [
<add> [(1000, 1), (1000, 2), (2, 1000, 1), (1000, 3)],
<add> ["raise", "wrap", "clip"],
<add> TYPES1]
<add> param_names = ["shape", "mode", "dtype"]
<add>
<add> def setup(self, shape, mode, dtype):
<add> self.arr = np.ones(shape, dtype)
<add> self.indices = np.arange(1000)
<add>
<add> def time_contiguous(self, shape, mode, dtype):
<add> self.arr.take(self.indices, axis=-2, mode=mode)
<add>
<add>
<add>class PutMask(Benchmark):
<add> params = [
<add> [True, False],
<add> TYPES1]
<add> param_names = ["values_is_scalar", "dtype"]
<add>
<add> def setup(self, values_is_scalar, dtype):
<add> if values_is_scalar:
<add> self.vals = np.array(1., dtype=dtype)
<add> else:
<add> self.vals = np.ones(1000, dtype=dtype)
<add>
<add> self.arr = np.ones(1000, dtype=dtype)
<add>
<add> self.dense_mask = np.ones(1000, dtype="bool")
<add> self.sparse_mask = np.zeros(1000, dtype="bool")
<add>
<add> def time_dense(self, values_is_scalar, dtype):
<add> np.putmask(self.arr, self.dense_mask, self.vals)
<add>
<add> def time_sparse(self, values_is_scalar, dtype):
<add> np.putmask(self.arr, self.sparse_mask, self.vals)
<add> | 1 |
PHP | PHP | fix | 07177e94983f20d478026dc93278c05f6f18c0dd | <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
<ide> public function firstOrFail($columns = ['*'])
<ide> return $model;
<ide> }
<ide>
<del> throw new ModelNotFoundException;
<add> throw (new ModelNotFoundException)->setModel(get_class($this->parent));
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
<ide> public function firstOrFail($columns = ['*'])
<ide> return $model;
<ide> }
<ide>
<del> throw new ModelNotFoundException;
<add> throw (new ModelNotFoundException)->setModel(get_class($this->parent));
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabaseEloquentBelongsToManyTest.php
<ide> public function testCreateMethodCreatesNewModelAndInsertsAttachmentRecord()
<ide> $this->assertEquals($model, $relation->create(['attributes'], ['joining']));
<ide> }
<ide>
<add> public function testFindOrFailThrowsException()
<add> {
<add> $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['find'], $this->getRelationArguments());
<add> $relation->expects($this->once())->method('find')->with('foo')->will($this->returnValue(null));
<add>
<add> $this->setExpectedException(\Illuminate\Database\Eloquent\ModelNotFoundException::class);
<add>
<add> try {
<add> $relation->findOrFail('foo');
<add> } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
<add> $this->assertNotEmpty($e->getModel());
<add>
<add> throw $e;
<add> }
<add> }
<add>
<add> public function testFirstOrFailThrowsException()
<add> {
<add> $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['first'], $this->getRelationArguments());
<add> $relation->expects($this->once())->method('first')->with(['id' => 'foo'])->will($this->returnValue(null));
<add>
<add> $this->setExpectedException(\Illuminate\Database\Eloquent\ModelNotFoundException::class);
<add>
<add> try {
<add> $relation->firstOrFail(['id' => 'foo']);
<add> } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
<add> $this->assertNotEmpty($e->getModel());
<add>
<add> throw $e;
<add> }
<add> }
<add>
<ide> public function testFindOrNewMethodFindsModel()
<ide> {
<ide> $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['find'], $this->getRelationArguments());
<ide><path>tests/Database/DatabaseEloquentHasManyThroughTest.php
<ide> public function testFirstMethod()
<ide> $this->assertEquals('first', $relation->first());
<ide> }
<ide>
<add> public function testFindOrFailThrowsException()
<add> {
<add> $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\HasManyThrough', ['find'], $this->getRelationArguments());
<add> $relation->expects($this->once())->method('find')->with('foo')->will($this->returnValue(null));
<add>
<add> $this->setExpectedException(\Illuminate\Database\Eloquent\ModelNotFoundException::class);
<add>
<add> try {
<add> $relation->findOrFail('foo');
<add> } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
<add> $this->assertNotEmpty($e->getModel());
<add>
<add> throw $e;
<add> }
<add> }
<add>
<add> public function testFirstOrFailThrowsException()
<add> {
<add> $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\HasManyThrough', ['first'], $this->getRelationArguments());
<add> $relation->expects($this->once())->method('first')->with(['id' => 'foo'])->will($this->returnValue(null));
<add>
<add> $this->setExpectedException(\Illuminate\Database\Eloquent\ModelNotFoundException::class);
<add>
<add> try {
<add> $relation->firstOrFail(['id' => 'foo']);
<add> } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
<add> $this->assertNotEmpty($e->getModel());
<add>
<add> throw $e;
<add> }
<add> }
<add>
<ide> public function testFindMethod()
<ide> {
<ide> $relation = m::mock('Illuminate\Database\Eloquent\Relations\HasManyThrough[first]', $this->getRelationArguments()); | 4 |
Text | Text | add sense360 to list of users | a38687024ae69c5eeea41460b40291a88485093c | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> * [Jampp](https://github.com/jampp)
<ide> * [LingoChamp](http://www.liulishuo.com/) [[@haitaoyao](https://github.com/haitaoyao)]
<ide> * Lyft
<add>* [Sense360](https://github.com/Sense360) [[@kamilmroczek](https://github.com/KamilMroczek)]
<ide> * Stripe [@jbalogh]
<ide> * [WeTransfer](https://github.com/WeTransfer) [[@jochem](https://github.com/jochem)]
<ide> * Wooga | 1 |
Text | Text | add v3.16.5 to changelog.md | efdbce3d1321652b0b9ad55a5837d8fd9cb15b42 | <ide><path>CHANGELOG.md
<ide> - [#18694](https://github.com/emberjs/ember.js/pull/18694) [BUGFIX] Ensure tag updates are buffered, remove error message
<ide> - [#18709](https://github.com/emberjs/ember.js/pull/18709) [BUGFIX] Fix `this` in `@tracked` initializer
<ide>
<add>### v3.16.5 (March 23, 2020)
<add>
<add>- [#18831](https://github.com/emberjs/ember.js/pull/18831) [BUGFIX] Fix transpilation issues (e.g. `_createSuper` is not a function) when used with Babel 7.9.0+.
<add>
<ide> ### v3.16.4 (March 22, 2020)
<ide>
<ide> - [#18741](https://github.com/emberjs/ember.js/pull/18741) [BUGFIX] Don't setup mandatory setters on array indexes | 1 |
Ruby | Ruby | call it compile_methods! and do the same on am | 6067d1620075c1c311bbae01993453cd80967804 | <ide><path>actionmailer/lib/action_mailer/railtie.rb
<ide> class Railtie < Rails::Railtie
<ide> options.javascripts_dir ||= paths.public.javascripts.to_a.first
<ide> options.stylesheets_dir ||= paths.public.stylesheets.to_a.first
<ide>
<add> # make sure readers methods get compiled
<add> options.asset_path ||= nil
<add> options.asset_host ||= nil
<add>
<ide> ActiveSupport.on_load(:action_mailer) do
<ide> include AbstractController::UrlFor
<ide> extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
<ide> include app.routes.mounted_helpers
<ide> options.each { |k,v| send("#{k}=", v) }
<ide> end
<ide> end
<add>
<add> initializer "action_mailer.compile_config_methods" do
<add> ActiveSupport.on_load(:action_mailer) do
<add> config.compile_methods! if config.respond_to?(:compile_methods!)
<add> end
<add> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_controller/railtie.rb
<ide> class Railtie < Rails::Railtie
<ide> end
<ide> end
<ide>
<del> config.after_initialize do
<add> initializer "action_controller.compile_config_methods" do
<ide> ActiveSupport.on_load(:action_controller) do
<del> config.crystalize! if config.respond_to?(:crystalize!)
<add> config.compile_methods! if config.respond_to?(:compile_methods!)
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/configurable.rb
<ide> module Configurable
<ide> extend ActiveSupport::Concern
<ide>
<ide> class Configuration < ActiveSupport::InheritableOptions
<del> def crystalize!
<del> self.class.crystalize!(keys.reject {|key| respond_to?(key)})
<add> def compile_methods!
<add> self.class.compile_methods!(keys.reject {|key| respond_to?(key)})
<ide> end
<ide>
<ide> # compiles reader methods so we don't have to go through method_missing
<del> def self.crystalize!(keys)
<add> def self.compile_methods!(keys)
<ide> keys.each do |key|
<ide> class_eval <<-RUBY, __FILE__, __LINE__ + 1
<ide> def #{key}; _get(#{key.inspect}); end
<ide><path>activesupport/test/configurable_test.rb
<ide> class Child < Parent
<ide> assert !child.config.respond_to?(:bar)
<ide> assert !child.new.config.respond_to?(:bar)
<ide>
<del> parent.config.crystalize!
<add> parent.config.compile_methods!
<ide> assert_equal :foo, parent.config.bar
<ide> assert_equal :foo, child.new.config.bar
<ide> | 4 |
Text | Text | add syntax of inheritance to article | b04cc579a6a323dfdb1b4364f416b09cc1778eaa | <ide><path>guide/english/java/inheritance/index.md
<ide> Java inheritance refers to the ability of a Java Class to `inherit` the properti
<ide>
<ide> Thus, inheritance gives Java the cool capability of _re-using_ code, or sharing code between classes!
<ide>
<add>## Syntax
<add>```java
<add>class Subclass-name extends Superclass-name
<add>{
<add> //methods and fields
<add>}
<add>```
<add>
<add>The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.
<add>
<add>In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.
<add>
<add>
<ide> Let's describe it with the classic example of a `Vehicle` class and a `Car` class :
<ide>
<ide> ```java | 1 |
Ruby | Ruby | move common stuff to extend/env.rb | eebc04ec9bfaca32024e2cb80ebf52b8ee68a7c9 | <ide><path>Library/Homebrew/build.rb
<ide> def main
<ide>
<ide> require 'hardware'
<ide> require 'keg'
<del> require 'superenv'
<add> require 'extend/ENV'
<ide>
<ide> # Force any future invocations of sudo to require the user's password to be
<ide> # re-entered. This is in-case any build script call sudo. Certainly this is
<ide><path>Library/Homebrew/cmd/--env.rb
<del>require 'superenv'
<add>require 'extend/ENV'
<ide> require 'hardware'
<ide>
<ide> module Homebrew extend self
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> require 'formula'
<ide> require 'utils'
<del>require 'superenv'
<add>require 'extend/ENV'
<ide> require 'formula_cellar_checks'
<ide>
<ide> module Homebrew extend self
<ide><path>Library/Homebrew/cmd/sh.rb
<del>require 'superenv'
<add>require 'extend/ENV'
<ide> require 'formula'
<ide>
<ide> module Homebrew extend self
<ide><path>Library/Homebrew/extend/ENV.rb
<ide> require 'hardware'
<add>require 'superenv'
<add>
<add>def superenv?
<add> return false if MacOS::Xcode.without_clt? && MacOS.sdk_path.nil?
<add> return false unless Superenv.bin && Superenv.bin.directory?
<add> return false if ARGV.include? "--env=std"
<add> true
<add>end
<add>
<add>module EnvActivation
<add> def activate_extensions!
<add> if superenv?
<add> extend(Superenv)
<add> else
<add> extend(HomebrewEnvExtension)
<add> prepend 'PATH', "#{HOMEBREW_PREFIX}/bin", ':' unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin'
<add> end
<add> end
<add>end
<add>
<add>ENV.extend(EnvActivation)
<ide>
<ide> module HomebrewEnvExtension
<ide> SAFE_CFLAGS_FLAGS = "-w -pipe"
<ide><path>Library/Homebrew/requirement.rb
<ide> require 'dependable'
<ide> require 'dependency'
<ide> require 'build_environment'
<add>require 'extend/ENV'
<ide>
<ide> # A base class for non-formula requirements needed by formulae.
<ide> # A "fatal" requirement is one that will fail the build if it is not present.
<ide> def yielder
<ide> if instance_variable_defined?(:@satisfied)
<ide> @satisfied
<ide> elsif @options[:build_env]
<del> require 'superenv'
<ide> ENV.with_build_environment do
<ide> ENV.userpaths!
<ide> yield @proc
<ide><path>Library/Homebrew/superenv.rb
<del>require 'extend/ENV'
<ide> require 'macos'
<ide>
<ide> ### Why `superenv`?
<ide> # 7) Simpler formula that *just work*
<ide> # 8) Build-system agnostic configuration of the tool-chain
<ide>
<del>def superenv?
<del> return false if MacOS::Xcode.without_clt? && MacOS.sdk_path.nil?
<del> return false unless Superenv.bin && Superenv.bin.directory?
<del> return false if ARGV.include? "--env=std"
<del> true
<del>end
<del>
<del>module EnvActivation
<del> def activate_extensions!
<del> if superenv?
<del> extend(Superenv)
<del> else
<del> extend(HomebrewEnvExtension)
<del> prepend 'PATH', "#{HOMEBREW_PREFIX}/bin", ':' unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin'
<del> end
<del> end
<del>end
<del>
<del>ENV.extend(EnvActivation)
<del>
<ide> module Superenv
<ide> attr_accessor :keg_only_deps, :deps, :x11
<ide> alias_method :x11?, :x11 | 7 |
Javascript | Javascript | allow onclick on next/link component's child | 669225263dfea787812c494759706f913e4c080a | <ide><path>lib/link.js
<ide> export default class Link extends Component {
<ide> // This will return the first child, if multiple are provided it will throw an error
<ide> const child = Children.only(children)
<ide> const props = {
<del> onClick: this.linkClicked
<add> onClick: (e) => {
<add> if (child.props && typeof child.props.onClick === 'function') {
<add> child.props.onClick(e)
<add> }
<add> if (!e.defaultPrevented) {
<add> this.linkClicked(e)
<add> }
<add> }
<ide> }
<ide>
<ide> // If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
<ide><path>test/integration/basic/pages/nav/index.js
<ide> export default class extends Component {
<ide> <Link href='/nav/as-path' as='/as/path'><a id='as-path-link' style={linkStyle}>As Path</a></Link>
<ide> <Link href='/nav/as-path'><a id='as-path-link-no-as' style={linkStyle}>As Path (No as)</a></Link>
<ide> <Link href='/nav/as-path-using-router'><a id='as-path-using-router-link' style={linkStyle}>As Path (Using Router)</a></Link>
<add> <Link href='/nav/on-click'><a id='on-click-link' style={linkStyle}>A element with onClick</a></Link>
<ide> <button
<ide> onClick={() => this.visitQueryStringPage()}
<ide> style={linkStyle}
<ide><path>test/integration/basic/pages/nav/on-click.js
<add>import { Component } from 'react'
<add>import Link from 'next/link'
<add>
<add>let count = 0
<add>
<add>export default class OnClick extends Component {
<add> static getInitialProps ({ res }) {
<add> if (res) return { count: 0 }
<add> count += 1
<add>
<add> return { count }
<add> }
<add>
<add> render () {
<add> return (
<add> <div id='on-click-page'>
<add> <Link href='/nav/on-click'>
<add> <a id='on-click-link' onClick={() => ++count}>Self Reload</a>
<add> </Link>
<add> <Link href='/nav/on-click'>
<add> <a id='on-click-link-prevent-default' onClick={(e) => { e.preventDefault(); ++count }}>Self Reload</a>
<add> </Link>
<add> <p>COUNT: {this.props.count}</p>
<add> </div>
<add> )
<add> }
<add>}
<ide><path>test/integration/basic/test/client-navigation.js
<ide> export default (context, render) => {
<ide> })
<ide> })
<ide>
<add> describe('with onClick action', () => {
<add> it('should reload the page and perform additional action', async () => {
<add> const browser = await webdriver(context.appPort, '/nav/on-click')
<add> const defaultCount = await browser.elementByCss('p').text()
<add> expect(defaultCount).toBe('COUNT: 0')
<add>
<add> const countAfterClicked = await browser
<add> .elementByCss('#on-click-link').click()
<add> .elementByCss('p').text()
<add>
<add> // counts (one click + onClick handler)
<add> expect(countAfterClicked).toBe('COUNT: 2')
<add> browser.close()
<add> })
<add>
<add> it('should not reload if default was prevented', async () => {
<add> const browser = await webdriver(context.appPort, '/nav/on-click')
<add> const defaultCount = await browser.elementByCss('p').text()
<add> expect(defaultCount).toBe('COUNT: 0')
<add>
<add> const countAfterClicked = await browser
<add> .elementByCss('#on-click-link-prevent-default').click()
<add> .elementByCss('p').text()
<add>
<add> // counter is increased but there was no reload
<add> expect(countAfterClicked).toBe('COUNT: 0')
<add>
<add> const countAfterClickedAndReloaded = await browser
<add> .elementByCss('#on-click-link').click() // +2
<add> .elementByCss('p').text()
<add>
<add> // counts (onClick handler, no reload)
<add> expect(countAfterClickedAndReloaded).toBe('COUNT: 3')
<add> browser.close()
<add> })
<add>
<add> it('should always replace the state and perform additional action', async () => {
<add> const browser = await webdriver(context.appPort, '/nav')
<add>
<add> const countAfterClicked = await browser
<add> .elementByCss('#on-click-link').click() // 1
<add> .waitForElementByCss('#on-click-page')
<add> .elementByCss('#on-click-link').click() // 3
<add> .elementByCss('#on-click-link').click() // 5
<add> .elementByCss('p').text()
<add>
<add> // counts (page change + two clicks + onClick handler)
<add> expect(countAfterClicked).toBe('COUNT: 5')
<add>
<add> // Since we replace the state, back button would simply go us back to /nav
<add> await browser
<add> .back()
<add> .waitForElementByCss('.nav-home')
<add>
<add> browser.close()
<add> })
<add> })
<add>
<ide> describe('with hash changes', () => {
<ide> describe('when hash change via Link', () => {
<ide> it('should not run getInitialProps', async () => { | 4 |
Ruby | Ruby | use arel rather than generate sql strings | cdf6cf01cb47bdcbc1e011c8f5f72b161f12bf9c | <ide><path>activerecord/lib/active_record/associations/class_methods/join_dependency.rb
<ide> def join_base
<ide> join_parts.first
<ide> end
<ide>
<del> def columns(connection)
<add> def columns
<ide> join_parts.collect { |join_part|
<add> table = Arel::Nodes::TableAlias.new join_part.aliased_table_name, nil
<ide> join_part.column_names_with_alias.collect{ |column_name, aliased_name|
<del> "#{connection.quote_table_name join_part.aliased_table_name}.#{connection.quote_column_name column_name} AS #{aliased_name}"
<add> table[column_name].as aliased_name
<ide> }
<ide> }.flatten
<ide> end
<ide><path>activerecord/lib/active_record/relation/finder_methods.rb
<ide> def construct_relation_for_association_calculations
<ide> end
<ide>
<ide> def construct_relation_for_association_find(join_dependency)
<del> relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns(connection))
<add> relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
<ide> apply_join_dependency(relation, join_dependency)
<ide> end
<ide> | 2 |
PHP | PHP | add priority to email | 31417c2567aa72d1289141cb20d4416a91defb27 | <ide><path>src/Mailer/Email.php
<ide> class Email implements JsonSerializable, Serializable
<ide> */
<ide> protected $_boundary = null;
<ide>
<add> /**
<add> * Contains the optional priority of the email.
<add> *
<add> * @var int|null
<add> */
<add> protected $_priority = null;
<add>
<ide> /**
<ide> * An array mapping url schemes to fully qualified Transport class names
<ide> *
<ide> public function getHeaders(array $include = [])
<ide> }
<ide> }
<ide>
<add> if ($this->_priority) {
<add> $headers['X-Priority'] = $this->_priority;
<add> }
<add>
<ide> if ($include['subject']) {
<ide> $headers['Subject'] = $this->_subject;
<ide> }
<ide> public function message($type = null)
<ide> return $this->_message;
<ide> }
<ide>
<add> /**
<add> * Sets priority.
<add> *
<add> * @param int|null $priority 1 (highest) to 5 (lowest)
<add> * @return $this
<add> */
<add> public function setPriority($priority) {
<add> $this->_priority = $priority;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Gets priority.
<add> *
<add> * @return int
<add> */
<add> public function getPriority() {
<add> return $this->_priority;
<add> }
<add>
<ide> /**
<ide> * Sets transport configuration.
<ide> *
<ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> class EmailTest extends TestCase
<ide>
<ide> public $fixtures = ['core.users'];
<ide>
<add> /**
<add> * @var \Cake\Mailer\Email
<add> */
<add> protected $Email;
<add>
<add> /**
<add> * @var array
<add> */
<add> protected $transports = [];
<add>
<ide> /**
<ide> * setUp
<ide> *
<ide> class EmailTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->CakeEmail = new TestEmail();
<add> $this->Email = new TestEmail();
<ide>
<ide> $this->transports = [
<ide> 'debug' => [
<ide> public function tearDown()
<ide> */
<ide> public function testFrom()
<ide> {
<del> $this->assertSame([], $this->CakeEmail->from());
<add> $this->assertSame([], $this->Email->from());
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<add> $this->Email->from('cake@cakephp.org');
<ide> $expected = ['cake@cakephp.org' => 'cake@cakephp.org'];
<del> $this->assertSame($expected, $this->CakeEmail->from());
<add> $this->assertSame($expected, $this->Email->from());
<ide>
<del> $this->CakeEmail->from(['cake@cakephp.org']);
<del> $this->assertSame($expected, $this->CakeEmail->from());
<add> $this->Email->from(['cake@cakephp.org']);
<add> $this->assertSame($expected, $this->Email->from());
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org', 'CakePHP');
<add> $this->Email->from('cake@cakephp.org', 'CakePHP');
<ide> $expected = ['cake@cakephp.org' => 'CakePHP'];
<del> $this->assertSame($expected, $this->CakeEmail->from());
<add> $this->assertSame($expected, $this->Email->from());
<ide>
<del> $result = $this->CakeEmail->from(['cake@cakephp.org' => 'CakePHP']);
<del> $this->assertSame($expected, $this->CakeEmail->from());
<del> $this->assertSame($this->CakeEmail, $result);
<add> $result = $this->Email->from(['cake@cakephp.org' => 'CakePHP']);
<add> $this->assertSame($expected, $this->Email->from());
<add> $this->assertSame($this->Email, $result);
<ide>
<ide> $this->setExpectedException('InvalidArgumentException');
<del> $result = $this->CakeEmail->from(['cake@cakephp.org' => 'CakePHP', 'fail@cakephp.org' => 'From can only be one address']);
<add> $result = $this->Email->from(['cake@cakephp.org' => 'CakePHP', 'fail@cakephp.org' => 'From can only be one address']);
<ide> }
<ide>
<ide> /**
<ide> public function testFromWithColonsAndQuotes()
<ide> $address = [
<ide> 'info@example.com' => '70:20:00 " Forum'
<ide> ];
<del> $this->CakeEmail->from($address);
<del> $this->assertEquals($address, $this->CakeEmail->from());
<del> $this->CakeEmail->to('info@example.com')
<add> $this->Email->from($address);
<add> $this->assertEquals($address, $this->Email->from());
<add> $this->Email->to('info@example.com')
<ide> ->subject('Test email')
<ide> ->transport('debug');
<ide>
<del> $result = $this->CakeEmail->send();
<add> $result = $this->Email->send();
<ide> $this->assertContains('From: "70:20:00 \" Forum" <info@example.com>', $result['headers']);
<ide> }
<ide>
<ide> public function testFromWithColonsAndQuotes()
<ide> */
<ide> public function testSender()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->assertSame([], $this->CakeEmail->sender());
<add> $this->Email->reset();
<add> $this->assertSame([], $this->Email->sender());
<ide>
<del> $this->CakeEmail->sender('cake@cakephp.org', 'Name');
<add> $this->Email->sender('cake@cakephp.org', 'Name');
<ide> $expected = ['cake@cakephp.org' => 'Name'];
<del> $this->assertSame($expected, $this->CakeEmail->sender());
<add> $this->assertSame($expected, $this->Email->sender());
<ide>
<del> $headers = $this->CakeEmail->getHeaders(['from' => true, 'sender' => true]);
<add> $headers = $this->Email->getHeaders(['from' => true, 'sender' => true]);
<ide> $this->assertFalse($headers['From']);
<ide> $this->assertSame('Name <cake@cakephp.org>', $headers['Sender']);
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org', 'CakePHP');
<del> $headers = $this->CakeEmail->getHeaders(['from' => true, 'sender' => true]);
<add> $this->Email->from('cake@cakephp.org', 'CakePHP');
<add> $headers = $this->Email->getHeaders(['from' => true, 'sender' => true]);
<ide> $this->assertSame('CakePHP <cake@cakephp.org>', $headers['From']);
<ide> $this->assertSame('', $headers['Sender']);
<ide> }
<ide> public function testSender()
<ide> */
<ide> public function testTo()
<ide> {
<del> $this->assertSame([], $this->CakeEmail->to());
<add> $this->assertSame([], $this->Email->to());
<ide>
<del> $result = $this->CakeEmail->to('cake@cakephp.org');
<add> $result = $this->Email->to('cake@cakephp.org');
<ide> $expected = ['cake@cakephp.org' => 'cake@cakephp.org'];
<del> $this->assertSame($expected, $this->CakeEmail->to());
<del> $this->assertSame($this->CakeEmail, $result);
<add> $this->assertSame($expected, $this->Email->to());
<add> $this->assertSame($this->Email, $result);
<ide>
<del> $this->CakeEmail->to('cake@cakephp.org', 'CakePHP');
<add> $this->Email->to('cake@cakephp.org', 'CakePHP');
<ide> $expected = ['cake@cakephp.org' => 'CakePHP'];
<del> $this->assertSame($expected, $this->CakeEmail->to());
<add> $this->assertSame($expected, $this->Email->to());
<ide>
<ide> $list = [
<ide> 'root@localhost' => 'root',
<ide> public function testTo()
<ide> 'cake-php@googlegroups.com' => 'Cake Groups',
<ide> 'root@cakephp.org'
<ide> ];
<del> $this->CakeEmail->to($list);
<add> $this->Email->to($list);
<ide> $expected = [
<ide> 'root@localhost' => 'root',
<ide> 'bjørn@hammeröath.com' => 'Bjorn',
<ide> 'cake.php@cakephp.org' => 'Cake PHP',
<ide> 'cake-php@googlegroups.com' => 'Cake Groups',
<ide> 'root@cakephp.org' => 'root@cakephp.org'
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->to());
<add> $this->assertSame($expected, $this->Email->to());
<ide>
<del> $this->CakeEmail->addTo('jrbasso@cakephp.org');
<del> $this->CakeEmail->addTo('mark_story@cakephp.org', 'Mark Story');
<del> $this->CakeEmail->addTo('foobar@ætdcadsl.dk');
<del> $result = $this->CakeEmail->addTo(['phpnut@cakephp.org' => 'PhpNut', 'jose_zap@cakephp.org']);
<add> $this->Email->addTo('jrbasso@cakephp.org');
<add> $this->Email->addTo('mark_story@cakephp.org', 'Mark Story');
<add> $this->Email->addTo('foobar@ætdcadsl.dk');
<add> $result = $this->Email->addTo(['phpnut@cakephp.org' => 'PhpNut', 'jose_zap@cakephp.org']);
<ide> $expected = [
<ide> 'root@localhost' => 'root',
<ide> 'bjørn@hammeröath.com' => 'Bjorn',
<ide> public function testTo()
<ide> 'phpnut@cakephp.org' => 'PhpNut',
<ide> 'jose_zap@cakephp.org' => 'jose_zap@cakephp.org'
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->to());
<del> $this->assertSame($this->CakeEmail, $result);
<add> $this->assertSame($expected, $this->Email->to());
<add> $this->assertSame($this->Email, $result);
<ide> }
<ide>
<ide> /**
<ide> public static function invalidEmails()
<ide> */
<ide> public function testInvalidEmail($value)
<ide> {
<del> $this->CakeEmail->to($value);
<add> $this->Email->to($value);
<ide> }
<ide>
<ide> /**
<ide> public function testInvalidEmail($value)
<ide> */
<ide> public function testInvalidEmailAdd($value)
<ide> {
<del> $this->CakeEmail->addTo($value);
<add> $this->Email->addTo($value);
<ide> }
<ide>
<ide> /**
<ide> public function testInvalidEmailAdd($value)
<ide> public function testEmailPattern()
<ide> {
<ide> $regex = '/.+@.+\..+/i';
<del> $this->assertSame($regex, $this->CakeEmail->emailPattern($regex)->emailPattern());
<add> $this->assertSame($regex, $this->Email->emailPattern($regex)->emailPattern());
<ide> }
<ide>
<ide> /**
<ide> public function testCustomEmailValidation()
<ide> {
<ide> $regex = '/^[\.a-z0-9!#$%&\'*+\/=?^_`{|}~-]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]{2,6}$/i';
<ide>
<del> $this->CakeEmail->emailPattern($regex)->to('pass.@example.com');
<add> $this->Email->emailPattern($regex)->to('pass.@example.com');
<ide> $this->assertSame([
<ide> 'pass.@example.com' => 'pass.@example.com',
<del> ], $this->CakeEmail->to());
<add> ], $this->Email->to());
<ide>
<del> $this->CakeEmail->addTo('pass..old.docomo@example.com');
<add> $this->Email->addTo('pass..old.docomo@example.com');
<ide> $this->assertSame([
<ide> 'pass.@example.com' => 'pass.@example.com',
<ide> 'pass..old.docomo@example.com' => 'pass..old.docomo@example.com',
<del> ], $this->CakeEmail->to());
<add> ], $this->Email->to());
<ide>
<del> $this->CakeEmail->reset();
<add> $this->Email->reset();
<ide> $emails = [
<ide> 'pass.@example.com',
<ide> 'pass..old.docomo@example.com'
<ide> public function testCustomEmailValidation()
<ide> '.extend.@example.com',
<ide> '.docomo@example.com'
<ide> ];
<del> $this->CakeEmail->emailPattern($regex)->to($emails);
<add> $this->Email->emailPattern($regex)->to($emails);
<ide> $this->assertSame([
<ide> 'pass.@example.com' => 'pass.@example.com',
<ide> 'pass..old.docomo@example.com' => 'pass..old.docomo@example.com',
<del> ], $this->CakeEmail->to());
<add> ], $this->Email->to());
<ide>
<del> $this->CakeEmail->addTo($additionalEmails);
<add> $this->Email->addTo($additionalEmails);
<ide> $this->assertSame([
<ide> 'pass.@example.com' => 'pass.@example.com',
<ide> 'pass..old.docomo@example.com' => 'pass..old.docomo@example.com',
<ide> '.extend.@example.com' => '.extend.@example.com',
<ide> '.docomo@example.com' => '.docomo@example.com',
<del> ], $this->CakeEmail->to());
<add> ], $this->Email->to());
<ide> }
<ide>
<ide> /**
<ide> public function testUnsetEmailPattern()
<ide> */
<ide> public function testFormatAddress()
<ide> {
<del> $result = $this->CakeEmail->formatAddress(['cake@cakephp.org' => 'cake@cakephp.org']);
<add> $result = $this->Email->formatAddress(['cake@cakephp.org' => 'cake@cakephp.org']);
<ide> $expected = ['cake@cakephp.org'];
<ide> $this->assertSame($expected, $result);
<ide>
<del> $result = $this->CakeEmail->formatAddress(['cake@cakephp.org' => 'cake@cakephp.org', 'php@cakephp.org' => 'php@cakephp.org']);
<add> $result = $this->Email->formatAddress(['cake@cakephp.org' => 'cake@cakephp.org', 'php@cakephp.org' => 'php@cakephp.org']);
<ide> $expected = ['cake@cakephp.org', 'php@cakephp.org'];
<ide> $this->assertSame($expected, $result);
<ide>
<del> $result = $this->CakeEmail->formatAddress(['cake@cakephp.org' => 'CakePHP', 'php@cakephp.org' => 'Cake']);
<add> $result = $this->Email->formatAddress(['cake@cakephp.org' => 'CakePHP', 'php@cakephp.org' => 'Cake']);
<ide> $expected = ['CakePHP <cake@cakephp.org>', 'Cake <php@cakephp.org>'];
<ide> $this->assertSame($expected, $result);
<ide>
<del> $result = $this->CakeEmail->formatAddress(['me@example.com' => 'Last, First']);
<add> $result = $this->Email->formatAddress(['me@example.com' => 'Last, First']);
<ide> $expected = ['"Last, First" <me@example.com>'];
<ide> $this->assertSame($expected, $result);
<ide>
<del> $result = $this->CakeEmail->formatAddress(['me@example.com' => '"Last" First']);
<add> $result = $this->Email->formatAddress(['me@example.com' => '"Last" First']);
<ide> $expected = ['"\"Last\" First" <me@example.com>'];
<ide> $this->assertSame($expected, $result);
<ide>
<del> $result = $this->CakeEmail->formatAddress(['me@example.com' => 'Last First']);
<add> $result = $this->Email->formatAddress(['me@example.com' => 'Last First']);
<ide> $expected = ['Last First <me@example.com>'];
<ide> $this->assertSame($expected, $result);
<ide>
<del> $result = $this->CakeEmail->formatAddress(['cake@cakephp.org' => 'ÄÖÜTest']);
<add> $result = $this->Email->formatAddress(['cake@cakephp.org' => 'ÄÖÜTest']);
<ide> $expected = ['=?UTF-8?B?w4TDlsOcVGVzdA==?= <cake@cakephp.org>'];
<ide> $this->assertSame($expected, $result);
<ide>
<del> $result = $this->CakeEmail->formatAddress(['cake@cakephp.org' => '日本語Test']);
<add> $result = $this->Email->formatAddress(['cake@cakephp.org' => '日本語Test']);
<ide> $expected = ['=?UTF-8?B?5pel5pys6KqeVGVzdA==?= <cake@cakephp.org>'];
<ide> $this->assertSame($expected, $result);
<ide> }
<ide> public function testFormatAddress()
<ide> */
<ide> public function testFormatAddressJapanese()
<ide> {
<del> $this->CakeEmail->headerCharset = 'ISO-2022-JP';
<del> $result = $this->CakeEmail->formatAddress(['cake@cakephp.org' => '日本語Test']);
<add> $this->Email->headerCharset = 'ISO-2022-JP';
<add> $result = $this->Email->formatAddress(['cake@cakephp.org' => '日本語Test']);
<ide> $expected = ['=?ISO-2022-JP?B?GyRCRnxLXDhsGyhCVGVzdA==?= <cake@cakephp.org>'];
<ide> $this->assertSame($expected, $result);
<ide>
<del> $result = $this->CakeEmail->formatAddress(['cake@cakephp.org' => '寿限無寿限無五劫の擦り切れ海砂利水魚の水行末雲来末風来末食う寝る処に住む処やぶら小路の藪柑子パイポパイポパイポのシューリンガンシューリンガンのグーリンダイグーリンダイのポンポコピーのポンポコナーの長久命の長助']);
<add> $result = $this->Email->formatAddress(['cake@cakephp.org' => '寿限無寿限無五劫の擦り切れ海砂利水魚の水行末雲来末風来末食う寝る処に住む処やぶら小路の藪柑子パイポパイポパイポのシューリンガンシューリンガンのグーリンダイグーリンダイのポンポコピーのポンポコナーの長久命の長助']);
<ide> $expected = ["=?ISO-2022-JP?B?GyRCPHc4Qkw1PHc4Qkw1OF45ZSROOyQkakBaJGwzJDo9TXg/ZTV7GyhC?=\r\n" .
<ide> " =?ISO-2022-JP?B?GyRCJE4/ZTlUS3YxQE1oS3ZJd01oS3Y/KSQmPzIkaz1oJEs9OyRgGyhC?=\r\n" .
<ide> " =?ISO-2022-JP?B?GyRCPWgkZCRWJGk+Lk8pJE5pLjQ7O1IlUSUkJV0lUSUkJV0lUSUkGyhC?=\r\n" .
<ide> public function testFormatAddressJapanese()
<ide> */
<ide> public function testAddresses()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->from('cake@cakephp.org', 'CakePHP');
<del> $this->CakeEmail->replyTo('replyto@cakephp.org', 'ReplyTo CakePHP');
<del> $this->CakeEmail->readReceipt('readreceipt@cakephp.org', 'ReadReceipt CakePHP');
<del> $this->CakeEmail->returnPath('returnpath@cakephp.org', 'ReturnPath CakePHP');
<del> $this->CakeEmail->to('to@cakephp.org', 'To, CakePHP');
<del> $this->CakeEmail->cc('cc@cakephp.org', 'Cc CakePHP');
<del> $this->CakeEmail->bcc('bcc@cakephp.org', 'Bcc CakePHP');
<del> $this->CakeEmail->addTo('to2@cakephp.org', 'To2 CakePHP');
<del> $this->CakeEmail->addCc('cc2@cakephp.org', 'Cc2 CakePHP');
<del> $this->CakeEmail->addBcc('bcc2@cakephp.org', 'Bcc2 CakePHP');
<del>
<del> $this->assertSame($this->CakeEmail->from(), ['cake@cakephp.org' => 'CakePHP']);
<del> $this->assertSame($this->CakeEmail->replyTo(), ['replyto@cakephp.org' => 'ReplyTo CakePHP']);
<del> $this->assertSame($this->CakeEmail->readReceipt(), ['readreceipt@cakephp.org' => 'ReadReceipt CakePHP']);
<del> $this->assertSame($this->CakeEmail->returnPath(), ['returnpath@cakephp.org' => 'ReturnPath CakePHP']);
<del> $this->assertSame($this->CakeEmail->to(), ['to@cakephp.org' => 'To, CakePHP', 'to2@cakephp.org' => 'To2 CakePHP']);
<del> $this->assertSame($this->CakeEmail->cc(), ['cc@cakephp.org' => 'Cc CakePHP', 'cc2@cakephp.org' => 'Cc2 CakePHP']);
<del> $this->assertSame($this->CakeEmail->bcc(), ['bcc@cakephp.org' => 'Bcc CakePHP', 'bcc2@cakephp.org' => 'Bcc2 CakePHP']);
<del>
<del> $headers = $this->CakeEmail->getHeaders(array_fill_keys(['from', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'], true));
<add> $this->Email->reset();
<add> $this->Email->from('cake@cakephp.org', 'CakePHP');
<add> $this->Email->replyTo('replyto@cakephp.org', 'ReplyTo CakePHP');
<add> $this->Email->readReceipt('readreceipt@cakephp.org', 'ReadReceipt CakePHP');
<add> $this->Email->returnPath('returnpath@cakephp.org', 'ReturnPath CakePHP');
<add> $this->Email->to('to@cakephp.org', 'To, CakePHP');
<add> $this->Email->cc('cc@cakephp.org', 'Cc CakePHP');
<add> $this->Email->bcc('bcc@cakephp.org', 'Bcc CakePHP');
<add> $this->Email->addTo('to2@cakephp.org', 'To2 CakePHP');
<add> $this->Email->addCc('cc2@cakephp.org', 'Cc2 CakePHP');
<add> $this->Email->addBcc('bcc2@cakephp.org', 'Bcc2 CakePHP');
<add>
<add> $this->assertSame($this->Email->from(), ['cake@cakephp.org' => 'CakePHP']);
<add> $this->assertSame($this->Email->replyTo(), ['replyto@cakephp.org' => 'ReplyTo CakePHP']);
<add> $this->assertSame($this->Email->readReceipt(), ['readreceipt@cakephp.org' => 'ReadReceipt CakePHP']);
<add> $this->assertSame($this->Email->returnPath(), ['returnpath@cakephp.org' => 'ReturnPath CakePHP']);
<add> $this->assertSame($this->Email->to(), ['to@cakephp.org' => 'To, CakePHP', 'to2@cakephp.org' => 'To2 CakePHP']);
<add> $this->assertSame($this->Email->cc(), ['cc@cakephp.org' => 'Cc CakePHP', 'cc2@cakephp.org' => 'Cc2 CakePHP']);
<add> $this->assertSame($this->Email->bcc(), ['bcc@cakephp.org' => 'Bcc CakePHP', 'bcc2@cakephp.org' => 'Bcc2 CakePHP']);
<add>
<add> $headers = $this->Email->getHeaders(array_fill_keys(['from', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'], true));
<ide> $this->assertSame($headers['From'], 'CakePHP <cake@cakephp.org>');
<ide> $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP <replyto@cakephp.org>');
<ide> $this->assertSame($headers['Disposition-Notification-To'], 'ReadReceipt CakePHP <readreceipt@cakephp.org>');
<ide> public function testAddresses()
<ide> */
<ide> public function testMessageId()
<ide> {
<del> $this->CakeEmail->messageId(true);
<del> $result = $this->CakeEmail->getHeaders();
<add> $this->Email->messageId(true);
<add> $result = $this->Email->getHeaders();
<ide> $this->assertTrue(isset($result['Message-ID']));
<ide>
<del> $this->CakeEmail->messageId(false);
<del> $result = $this->CakeEmail->getHeaders();
<add> $this->Email->messageId(false);
<add> $result = $this->Email->getHeaders();
<ide> $this->assertFalse(isset($result['Message-ID']));
<ide>
<del> $result = $this->CakeEmail->messageId('<my-email@localhost>');
<del> $this->assertSame($this->CakeEmail, $result);
<del> $result = $this->CakeEmail->getHeaders();
<add> $result = $this->Email->messageId('<my-email@localhost>');
<add> $this->assertSame($this->Email, $result);
<add> $result = $this->Email->getHeaders();
<ide> $this->assertSame('<my-email@localhost>', $result['Message-ID']);
<ide>
<del> $result = $this->CakeEmail->messageId();
<add> $result = $this->Email->messageId();
<ide> $this->assertSame('<my-email@localhost>', $result);
<ide> }
<ide>
<add> /**
<add> * @return void
<add> */
<add> public function testPriority() {
<add> $this->Email->setPriority(4);
<add>
<add> $this->assertSame(4, $this->Email->getPriority());
<add>
<add> $result = $this->Email->getHeaders();
<add> $this->assertTrue(isset($result['X-Priority']));
<add> }
<add>
<ide> /**
<ide> * testMessageIdInvalid method
<ide> *
<ide> public function testMessageId()
<ide> */
<ide> public function testMessageIdInvalid()
<ide> {
<del> $this->CakeEmail->messageId('my-email@localhost');
<add> $this->Email->messageId('my-email@localhost');
<ide> }
<ide>
<ide> /**
<ide> public function testMessageIdInvalid()
<ide> */
<ide> public function testDomain()
<ide> {
<del> $result = $this->CakeEmail->domain();
<add> $result = $this->Email->domain();
<ide> $expected = env('HTTP_HOST') ? env('HTTP_HOST') : php_uname('n');
<ide> $this->assertSame($expected, $result);
<ide>
<del> $this->CakeEmail->domain('example.org');
<del> $result = $this->CakeEmail->domain();
<add> $this->Email->domain('example.org');
<add> $result = $this->Email->domain();
<ide> $expected = 'example.org';
<ide> $this->assertSame($expected, $result);
<ide> }
<ide> public function testDomain()
<ide> */
<ide> public function testMessageIdWithDomain()
<ide> {
<del> $this->CakeEmail->domain('example.org');
<del> $result = $this->CakeEmail->getHeaders();
<add> $this->Email->domain('example.org');
<add> $result = $this->Email->getHeaders();
<ide> $expected = '@example.org>';
<ide> $this->assertTextContains($expected, $result['Message-ID']);
<ide>
<ide> $_SERVER['HTTP_HOST'] = 'example.org';
<del> $result = $this->CakeEmail->getHeaders();
<add> $result = $this->Email->getHeaders();
<ide> $this->assertTextContains('example.org', $result['Message-ID']);
<ide>
<ide> $_SERVER['HTTP_HOST'] = 'example.org:81';
<del> $result = $this->CakeEmail->getHeaders();
<add> $result = $this->Email->getHeaders();
<ide> $this->assertTextNotContains(':81', $result['Message-ID']);
<ide> }
<ide>
<ide> public function testMessageIdWithDomain()
<ide> */
<ide> public function testSubject()
<ide> {
<del> $this->CakeEmail->subject('You have a new message.');
<del> $this->assertSame('You have a new message.', $this->CakeEmail->subject());
<add> $this->Email->subject('You have a new message.');
<add> $this->assertSame('You have a new message.', $this->Email->subject());
<ide>
<del> $this->CakeEmail->subject('You have a new message, I think.');
<del> $this->assertSame($this->CakeEmail->subject(), 'You have a new message, I think.');
<del> $this->CakeEmail->subject(1);
<del> $this->assertSame('1', $this->CakeEmail->subject());
<add> $this->Email->subject('You have a new message, I think.');
<add> $this->assertSame($this->Email->subject(), 'You have a new message, I think.');
<add> $this->Email->subject(1);
<add> $this->assertSame('1', $this->Email->subject());
<ide>
<ide> $input = 'هذه رسالة بعنوان طويل مرسل للمستلم';
<del> $this->CakeEmail->subject($input);
<add> $this->Email->subject($input);
<ide> $expected = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?=';
<del> $this->assertSame($expected, $this->CakeEmail->subject());
<del> $this->assertSame($input, $this->CakeEmail->getOriginalSubject());
<add> $this->assertSame($expected, $this->Email->subject());
<add> $this->assertSame($input, $this->Email->getOriginalSubject());
<ide> }
<ide>
<ide> /**
<ide> public function testSubjectJapanese()
<ide> {
<ide> mb_internal_encoding('UTF-8');
<ide>
<del> $this->CakeEmail->headerCharset = 'ISO-2022-JP';
<del> $this->CakeEmail->subject('日本語のSubjectにも対応するよ');
<add> $this->Email->headerCharset = 'ISO-2022-JP';
<add> $this->Email->subject('日本語のSubjectにも対応するよ');
<ide> $expected = '=?ISO-2022-JP?B?GyRCRnxLXDhsJE4bKEJTdWJqZWN0GyRCJEskYkJQMX4kOSRrJGgbKEI=?=';
<del> $this->assertSame($expected, $this->CakeEmail->subject());
<add> $this->assertSame($expected, $this->Email->subject());
<ide>
<del> $this->CakeEmail->subject('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?');
<add> $this->Email->subject('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?');
<ide> $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
<ide> " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
<ide> " =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=";
<del> $this->assertSame($expected, $this->CakeEmail->subject());
<add> $this->assertSame($expected, $this->Email->subject());
<ide> }
<ide>
<ide> /**
<ide> public function testSubjectJapanese()
<ide> */
<ide> public function testHeaders()
<ide> {
<del> $this->CakeEmail->messageId(false);
<del> $this->CakeEmail->setHeaders(['X-Something' => 'nice']);
<add> $this->Email->messageId(false);
<add> $this->Email->setHeaders(['X-Something' => 'nice']);
<ide> $expected = [
<ide> 'X-Something' => 'nice',
<ide> 'Date' => date(DATE_RFC2822),
<ide> 'MIME-Version' => '1.0',
<ide> 'Content-Type' => 'text/plain; charset=UTF-8',
<ide> 'Content-Transfer-Encoding' => '8bit'
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->getHeaders());
<add> $this->assertSame($expected, $this->Email->getHeaders());
<ide>
<del> $this->CakeEmail->addHeaders(['X-Something' => 'very nice', 'X-Other' => 'cool']);
<add> $this->Email->addHeaders(['X-Something' => 'very nice', 'X-Other' => 'cool']);
<ide> $expected = [
<ide> 'X-Something' => 'very nice',
<ide> 'X-Other' => 'cool',
<ide> public function testHeaders()
<ide> 'Content-Type' => 'text/plain; charset=UTF-8',
<ide> 'Content-Transfer-Encoding' => '8bit'
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->getHeaders());
<add> $this->assertSame($expected, $this->Email->getHeaders());
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->assertSame($expected, $this->CakeEmail->getHeaders());
<add> $this->Email->from('cake@cakephp.org');
<add> $this->assertSame($expected, $this->Email->getHeaders());
<ide>
<ide> $expected = [
<ide> 'From' => 'cake@cakephp.org',
<ide> public function testHeaders()
<ide> 'Content-Type' => 'text/plain; charset=UTF-8',
<ide> 'Content-Transfer-Encoding' => '8bit'
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->getHeaders(['from' => true]));
<add> $this->assertSame($expected, $this->Email->getHeaders(['from' => true]));
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org', 'CakePHP');
<add> $this->Email->from('cake@cakephp.org', 'CakePHP');
<ide> $expected['From'] = 'CakePHP <cake@cakephp.org>';
<del> $this->assertSame($expected, $this->CakeEmail->getHeaders(['from' => true]));
<add> $this->assertSame($expected, $this->Email->getHeaders(['from' => true]));
<ide>
<del> $this->CakeEmail->to(['cake@cakephp.org', 'php@cakephp.org' => 'CakePHP']);
<add> $this->Email->to(['cake@cakephp.org', 'php@cakephp.org' => 'CakePHP']);
<ide> $expected = [
<ide> 'From' => 'CakePHP <cake@cakephp.org>',
<ide> 'To' => 'cake@cakephp.org, CakePHP <php@cakephp.org>',
<ide> public function testHeaders()
<ide> 'Content-Type' => 'text/plain; charset=UTF-8',
<ide> 'Content-Transfer-Encoding' => '8bit'
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->getHeaders(['from' => true, 'to' => true]));
<add> $this->assertSame($expected, $this->Email->getHeaders(['from' => true, 'to' => true]));
<ide>
<del> $this->CakeEmail->charset = 'ISO-2022-JP';
<add> $this->Email->charset = 'ISO-2022-JP';
<ide> $expected = [
<ide> 'From' => 'CakePHP <cake@cakephp.org>',
<ide> 'To' => 'cake@cakephp.org, CakePHP <php@cakephp.org>',
<ide> public function testHeaders()
<ide> 'Content-Type' => 'text/plain; charset=ISO-2022-JP',
<ide> 'Content-Transfer-Encoding' => '7bit'
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->getHeaders(['from' => true, 'to' => true]));
<add> $this->assertSame($expected, $this->Email->getHeaders(['from' => true, 'to' => true]));
<ide>
<del> $result = $this->CakeEmail->setHeaders([]);
<add> $result = $this->Email->setHeaders([]);
<ide> $this->assertInstanceOf('Cake\Mailer\Email', $result);
<ide> }
<ide>
<ide> public function testHeaders()
<ide> */
<ide> public function testTemplate()
<ide> {
<del> $this->CakeEmail->template('template', 'layout');
<add> $this->Email->template('template', 'layout');
<ide> $expected = ['template' => 'template', 'layout' => 'layout'];
<del> $this->assertSame($expected, $this->CakeEmail->template());
<add> $this->assertSame($expected, $this->Email->template());
<ide>
<del> $this->CakeEmail->template('new_template');
<add> $this->Email->template('new_template');
<ide> $expected = ['template' => 'new_template', 'layout' => 'layout'];
<del> $this->assertSame($expected, $this->CakeEmail->template());
<add> $this->assertSame($expected, $this->Email->template());
<ide>
<del> $this->CakeEmail->template('template', null);
<add> $this->Email->template('template', null);
<ide> $expected = ['template' => 'template', 'layout' => false];
<del> $this->assertSame($expected, $this->CakeEmail->template());
<add> $this->assertSame($expected, $this->Email->template());
<ide>
<del> $this->CakeEmail->template(null, null);
<add> $this->Email->template(null, null);
<ide> $expected = ['template' => '', 'layout' => false];
<del> $this->assertSame($expected, $this->CakeEmail->template());
<add> $this->assertSame($expected, $this->Email->template());
<ide> }
<ide>
<ide> /**
<ide> public function testTemplate()
<ide> */
<ide> public function testTheme()
<ide> {
<del> $this->assertNull($this->CakeEmail->theme());
<add> $this->assertNull($this->Email->theme());
<ide>
<del> $this->CakeEmail->theme('default');
<add> $this->Email->theme('default');
<ide> $expected = 'default';
<del> $this->assertSame($expected, $this->CakeEmail->theme());
<add> $this->assertSame($expected, $this->Email->theme());
<ide> }
<ide>
<ide> /**
<ide> public function testTheme()
<ide> */
<ide> public function testViewVars()
<ide> {
<del> $this->assertSame([], $this->CakeEmail->viewVars());
<add> $this->assertSame([], $this->Email->viewVars());
<ide>
<del> $this->CakeEmail->viewVars(['value' => 12345]);
<del> $this->assertSame(['value' => 12345], $this->CakeEmail->viewVars());
<add> $this->Email->viewVars(['value' => 12345]);
<add> $this->assertSame(['value' => 12345], $this->Email->viewVars());
<ide>
<del> $this->CakeEmail->viewVars(['name' => 'CakePHP']);
<del> $this->assertEquals(['value' => 12345, 'name' => 'CakePHP'], $this->CakeEmail->viewVars());
<add> $this->Email->viewVars(['name' => 'CakePHP']);
<add> $this->assertEquals(['value' => 12345, 'name' => 'CakePHP'], $this->Email->viewVars());
<ide>
<del> $this->CakeEmail->viewVars(['value' => 4567]);
<del> $this->assertSame(['value' => 4567, 'name' => 'CakePHP'], $this->CakeEmail->viewVars());
<add> $this->Email->viewVars(['value' => 4567]);
<add> $this->assertSame(['value' => 4567, 'name' => 'CakePHP'], $this->Email->viewVars());
<ide> }
<ide>
<ide> /**
<ide> public function testViewVars()
<ide> */
<ide> public function testAttachments()
<ide> {
<del> $this->CakeEmail->attachments(CAKE . 'basics.php');
<add> $this->Email->attachments(CAKE . 'basics.php');
<ide> $expected = [
<ide> 'basics.php' => [
<ide> 'file' => CAKE . 'basics.php',
<ide> 'mimetype' => 'text/x-php'
<ide> ]
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->attachments());
<add> $this->assertSame($expected, $this->Email->attachments());
<ide>
<del> $this->CakeEmail->attachments([]);
<del> $this->assertSame([], $this->CakeEmail->attachments());
<add> $this->Email->attachments([]);
<add> $this->assertSame([], $this->Email->attachments());
<ide>
<del> $this->CakeEmail->attachments([
<add> $this->Email->attachments([
<ide> ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain']
<ide> ]);
<del> $this->CakeEmail->addAttachments(CORE_PATH . 'config' . DS . 'bootstrap.php');
<del> $this->CakeEmail->addAttachments([CORE_PATH . 'config' . DS . 'bootstrap.php']);
<del> $this->CakeEmail->addAttachments([
<add> $this->Email->addAttachments(CORE_PATH . 'config' . DS . 'bootstrap.php');
<add> $this->Email->addAttachments([CORE_PATH . 'config' . DS . 'bootstrap.php']);
<add> $this->Email->addAttachments([
<ide> 'other.txt' => CORE_PATH . 'config' . DS . 'bootstrap.php',
<ide> 'license' => CORE_PATH . 'LICENSE.txt'
<ide> ]);
<ide> public function testAttachments()
<ide> 'other.txt' => ['file' => CORE_PATH . 'config' . DS . 'bootstrap.php', 'mimetype' => 'text/x-php'],
<ide> 'license' => ['file' => CORE_PATH . 'LICENSE.txt', 'mimetype' => 'text/plain']
<ide> ];
<del> $this->assertSame($expected, $this->CakeEmail->attachments());
<add> $this->assertSame($expected, $this->Email->attachments());
<ide>
<ide> $this->setExpectedException('InvalidArgumentException');
<del> $this->CakeEmail->attachments([['nofile' => CAKE . 'basics.php', 'mimetype' => 'text/plain']]);
<add> $this->Email->attachments([['nofile' => CAKE . 'basics.php', 'mimetype' => 'text/plain']]);
<ide> }
<ide>
<ide> /**
<ide> public function testAttachments()
<ide> */
<ide> public function testTransport()
<ide> {
<del> $result = $this->CakeEmail->transport('debug');
<del> $this->assertSame($this->CakeEmail, $result);
<add> $result = $this->Email->transport('debug');
<add> $this->assertSame($this->Email, $result);
<ide>
<del> $result = $this->CakeEmail->transport();
<add> $result = $this->Email->transport();
<ide> $this->assertInstanceOf('Cake\Mailer\Transport\DebugTransport', $result);
<ide>
<ide> $instance = $this->getMockBuilder('Cake\Mailer\Transport\DebugTransport')->getMock();
<del> $this->CakeEmail->transport($instance);
<del> $this->assertSame($instance, $this->CakeEmail->transport());
<add> $this->Email->transport($instance);
<add> $this->assertSame($instance, $this->Email->transport());
<ide> }
<ide>
<ide> /**
<ide> public function testTransport()
<ide> */
<ide> public function testTransportInvalid()
<ide> {
<del> $this->CakeEmail->transport('Invalid');
<add> $this->Email->transport('Invalid');
<ide> }
<ide>
<ide> /**
<ide> public function testTransportInvalid()
<ide> */
<ide> public function testTransportInstanceInvalid()
<ide> {
<del> $this->CakeEmail->transport(new \StdClass());
<add> $this->Email->transport(new \StdClass());
<ide> }
<ide>
<ide> /**
<ide> public function testTransportInstanceInvalid()
<ide> */
<ide> public function testTransportTypeInvalid()
<ide> {
<del> $this->CakeEmail->transport(123);
<add> $this->Email->transport(123);
<ide> }
<ide>
<ide> /**
<ide> public function testTransportMissingClassName()
<ide> Email::dropTransport('debug');
<ide> Email::configTransport('debug', []);
<ide>
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->transport('debug');
<ide> }
<ide>
<ide> /**
<ide> public function testConfigErrorOnDuplicate()
<ide> public function testProfile()
<ide> {
<ide> $config = ['test' => 'ok', 'test2' => true];
<del> $this->CakeEmail->profile($config);
<del> $this->assertSame($this->CakeEmail->profile(), $config);
<add> $this->Email->profile($config);
<add> $this->assertSame($this->Email->profile(), $config);
<ide>
<ide> $config = ['test' => 'test@example.com'];
<del> $this->CakeEmail->profile($config);
<add> $this->Email->profile($config);
<ide> $expected = ['test' => 'test@example.com', 'test2' => true];
<del> $this->assertSame($expected, $this->CakeEmail->profile());
<add> $this->assertSame($expected, $this->Email->profile());
<ide> }
<ide>
<ide> /**
<ide> public function testUseConfigString()
<ide> 'helpers' => ['Html', 'Form'],
<ide> ];
<ide> Email::config('test', $config);
<del> $this->CakeEmail->profile('test');
<add> $this->Email->profile('test');
<ide>
<del> $result = $this->CakeEmail->to();
<add> $result = $this->Email->to();
<ide> $this->assertEquals($config['to'], $result);
<ide>
<del> $result = $this->CakeEmail->from();
<add> $result = $this->Email->from();
<ide> $this->assertEquals($config['from'], $result);
<ide>
<del> $result = $this->CakeEmail->subject();
<add> $result = $this->Email->subject();
<ide> $this->assertEquals($config['subject'], $result);
<ide>
<del> $result = $this->CakeEmail->theme();
<add> $result = $this->Email->theme();
<ide> $this->assertEquals($config['theme'], $result);
<ide>
<del> $result = $this->CakeEmail->transport();
<add> $result = $this->Email->transport();
<ide> $this->assertInstanceOf('Cake\Mailer\Transport\DebugTransport', $result);
<ide>
<del> $result = $this->CakeEmail->helpers();
<add> $result = $this->Email->helpers();
<ide> $this->assertEquals($config['helpers'], $result);
<ide> }
<ide>
<ide> public function testUseConfigString()
<ide> */
<ide> public function testSendWithNoContentDoesNotOverwriteViewVar()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('you@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->emailFormat('text');
<del> $this->CakeEmail->template('default');
<del> $this->CakeEmail->viewVars([
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('you@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->emailFormat('text');
<add> $this->Email->template('default');
<add> $this->Email->viewVars([
<ide> 'content' => 'A message to you',
<ide> ]);
<ide>
<del> $result = $this->CakeEmail->send();
<add> $result = $this->Email->send();
<ide> $this->assertContains('A message to you', $result['message']);
<ide> }
<ide>
<ide> public function testSendWithNoContentDoesNotOverwriteViewVar()
<ide> */
<ide> public function testSendWithContent()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<ide>
<del> $result = $this->CakeEmail->send("Here is my body, with multi lines.\nThis is the second line.\r\n\r\nAnd the last.");
<add> $result = $this->Email->send("Here is my body, with multi lines.\nThis is the second line.\r\n\r\nAnd the last.");
<ide> $expected = ['headers', 'message'];
<ide> $this->assertEquals($expected, array_keys($result));
<ide> $expected = "Here is my body, with multi lines.\r\nThis is the second line.\r\n\r\nAnd the last.\r\n\r\n";
<ide> public function testSendWithContent()
<ide> $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: '));
<ide> $this->assertTrue((bool)strpos($result['headers'], 'To: '));
<ide>
<del> $result = $this->CakeEmail->send("Other body");
<add> $result = $this->Email->send("Other body");
<ide> $expected = "Other body\r\n\r\n";
<ide> $this->assertSame($expected, $result['message']);
<ide> $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: '));
<ide> $this->assertTrue((bool)strpos($result['headers'], 'To: '));
<ide>
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $result = $this->CakeEmail->send(['Sending content', 'As array']);
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $result = $this->Email->send(['Sending content', 'As array']);
<ide> $expected = "Sending content\r\nAs array\r\n\r\n\r\n";
<ide> $this->assertSame($expected, $result['message']);
<ide> }
<ide> public function testSendWithContent()
<ide> */
<ide> public function testSendWithoutFrom()
<ide> {
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->send("Forgot to set From");
<add> $this->Email->transport('debug');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->send("Forgot to set From");
<ide> }
<ide>
<ide> /**
<ide> public function testSendWithoutFrom()
<ide> */
<ide> public function testSendWithoutTo()
<ide> {
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->send("Forgot to set To");
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->send("Forgot to set To");
<ide> }
<ide>
<ide> /**
<ide> public function testSendWithoutTo()
<ide> */
<ide> public function testSendWithoutTransport()
<ide> {
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->send("Forgot to set To");
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->send("Forgot to set To");
<ide> }
<ide>
<ide> /**
<ide> public function testSendWithoutTransport()
<ide> */
<ide> public function testSendNoTemplateWithAttachments()
<ide> {
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->emailFormat('text');
<del> $this->CakeEmail->attachments([CAKE . 'basics.php']);
<del> $result = $this->CakeEmail->send('Hello');
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->emailFormat('text');
<add> $this->Email->attachments([CAKE . 'basics.php']);
<add> $result = $this->Email->send('Hello');
<ide>
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
<ide> $expected = "--$boundary\r\n" .
<ide> "Content-Type: text/plain; charset=UTF-8\r\n" .
<ide> public function testSendNoTemplateWithAttachments()
<ide>
<ide> public function testSendNoTemplateWithDataStringAttachment()
<ide> {
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->emailFormat('text');
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->emailFormat('text');
<ide> $data = file_get_contents(TEST_APP . 'webroot/img/cake.power.gif');
<del> $this->CakeEmail->attachments(['cake.icon.gif' => [
<add> $this->Email->attachments(['cake.icon.gif' => [
<ide> 'data' => $data,
<ide> 'mimetype' => 'image/gif'
<ide> ]]);
<del> $result = $this->CakeEmail->send('Hello');
<add> $result = $this->Email->send('Hello');
<ide>
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
<ide> $expected = "--$boundary\r\n" .
<ide> "Content-Type: text/plain; charset=UTF-8\r\n" .
<ide> public function testSendNoTemplateWithDataStringAttachment()
<ide> */
<ide> public function testSendNoTemplateWithAttachmentsAsBoth()
<ide> {
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->emailFormat('both');
<del> $this->CakeEmail->attachments([CORE_PATH . 'VERSION.txt']);
<del> $result = $this->CakeEmail->send('Hello');
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->emailFormat('both');
<add> $this->Email->attachments([CORE_PATH . 'VERSION.txt']);
<add> $result = $this->Email->send('Hello');
<ide>
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
<ide> $expected = "--$boundary\r\n" .
<ide> "Content-Type: multipart/alternative; boundary=\"alt-$boundary\"\r\n" .
<ide> public function testSendNoTemplateWithAttachmentsAsBoth()
<ide> */
<ide> public function testSendWithInlineAttachments()
<ide> {
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->emailFormat('both');
<del> $this->CakeEmail->attachments([
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->emailFormat('both');
<add> $this->Email->attachments([
<ide> 'cake.png' => [
<ide> 'file' => CORE_PATH . 'VERSION.txt',
<ide> 'contentId' => 'abc123'
<ide> ]
<ide> ]);
<del> $result = $this->CakeEmail->send('Hello');
<add> $result = $this->Email->send('Hello');
<ide>
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
<ide> $expected = "--$boundary\r\n" .
<ide> "Content-Type: multipart/related; boundary=\"rel-$boundary\"\r\n" .
<ide> public function testSendWithInlineAttachments()
<ide> */
<ide> public function testSendWithInlineAttachmentsHtmlOnly()
<ide> {
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->emailFormat('html');
<del> $this->CakeEmail->attachments([
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->emailFormat('html');
<add> $this->Email->attachments([
<ide> 'cake.png' => [
<ide> 'file' => CORE_PATH . 'VERSION.txt',
<ide> 'contentId' => 'abc123'
<ide> ]
<ide> ]);
<del> $result = $this->CakeEmail->send('Hello');
<add> $result = $this->Email->send('Hello');
<ide>
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
<ide> $expected = "--$boundary\r\n" .
<ide> "Content-Type: multipart/related; boundary=\"rel-$boundary\"\r\n" .
<ide> public function testSendWithInlineAttachmentsHtmlOnly()
<ide> */
<ide> public function testSendWithNoContentDispositionAttachments()
<ide> {
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->emailFormat('text');
<del> $this->CakeEmail->attachments([
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->emailFormat('text');
<add> $this->Email->attachments([
<ide> 'cake.png' => [
<ide> 'file' => CORE_PATH . 'VERSION.txt',
<ide> 'contentDisposition' => false
<ide> ]
<ide> ]);
<del> $result = $this->CakeEmail->send('Hello');
<add> $result = $this->Email->send('Hello');
<ide>
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']);
<ide> $expected = "--$boundary\r\n" .
<ide> "Content-Type: text/plain; charset=UTF-8\r\n" .
<ide> public function testSendWithLog()
<ide>
<ide> Log::config('email', $log);
<ide>
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->to('me@cakephp.org');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['log' => 'debug']);
<del> $result = $this->CakeEmail->send($message);
<add> $this->Email->transport('debug');
<add> $this->Email->to('me@cakephp.org');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['log' => 'debug']);
<add> $result = $this->Email->send($message);
<ide> }
<ide>
<ide> /**
<ide> public function testSendWithLogAndScope()
<ide>
<ide> Log::config('email', $log);
<ide>
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->to('me@cakephp.org');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['log' => ['scope' => 'email']]);
<del> $this->CakeEmail->send($message);
<add> $this->Email->transport('debug');
<add> $this->Email->to('me@cakephp.org');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['log' => ['scope' => 'email']]);
<add> $this->Email->send($message);
<ide> }
<ide>
<ide> /**
<ide> public function testSendWithLogAndScope()
<ide> */
<ide> public function testSendRender()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->template('default', 'default');
<del> $result = $this->CakeEmail->send();
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->template('default', 'default');
<add> $result = $this->Email->send();
<ide>
<ide> $this->assertContains('This email was sent using the CakePHP Framework', $result['message']);
<ide> $this->assertContains('Message-ID: ', $result['headers']);
<ide> public function testSendRender()
<ide> */
<ide> public function testSendRenderNoLayout()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->config(['empty']);
<del> $this->CakeEmail->template('default', null);
<del> $result = $this->CakeEmail->send('message body.');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->config(['empty']);
<add> $this->Email->template('default', null);
<add> $result = $this->Email->send('message body.');
<ide>
<ide> $this->assertContains('message body.', $result['message']);
<ide> $this->assertNotContains('This email was sent using the CakePHP Framework', $result['message']);
<ide> public function testSendRenderNoLayout()
<ide> */
<ide> public function testSendRenderBoth()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->template('default', 'default');
<del> $this->CakeEmail->emailFormat('both');
<del> $result = $this->CakeEmail->send();
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->template('default', 'default');
<add> $this->Email->emailFormat('both');
<add> $result = $this->Email->send();
<ide>
<ide> $this->assertContains('Message-ID: ', $result['headers']);
<ide> $this->assertContains('To: ', $result['headers']);
<ide>
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertContains('Content-Type: multipart/alternative; boundary="' . $boundary . '"', $result['headers']);
<ide>
<ide> $expected = "--$boundary\r\n" .
<ide> public function testSendRenderBoth()
<ide> */
<ide> public function testSendRenderJapanese()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->template('default', 'japanese');
<del> $this->CakeEmail->charset = 'ISO-2022-JP';
<del> $result = $this->CakeEmail->send();
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->template('default', 'japanese');
<add> $this->Email->charset = 'ISO-2022-JP';
<add> $result = $this->Email->send();
<ide>
<ide> $expected = mb_convert_encoding('CakePHP Framework を使って送信したメールです。 http://cakephp.org.', 'ISO-2022-JP');
<ide> $this->assertContains($expected, $result['message']);
<ide> public function testSendRenderJapanese()
<ide> public function testSendRenderThemed()
<ide> {
<ide> Plugin::load('TestTheme');
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->theme('TestTheme');
<del> $this->CakeEmail->template('themed', 'default');
<del> $result = $this->CakeEmail->send();
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->theme('TestTheme');
<add> $this->Email->template('themed', 'default');
<add> $result = $this->Email->send();
<ide>
<ide> $this->assertContains('In TestTheme', $result['message']);
<ide> $this->assertContains('/test_theme/img/test.jpg', $result['message']);
<ide> public function testSendRenderThemed()
<ide> */
<ide> public function testSendRenderWithHTML()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->emailFormat('html');
<del> $this->CakeEmail->template('html', 'default');
<del> $result = $this->CakeEmail->send();
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->emailFormat('html');
<add> $this->Email->template('html', 'default');
<add> $result = $this->Email->send();
<ide>
<ide> $this->assertTextContains('<h1>HTML Ipsum Presents</h1>', $result['message']);
<ide> $this->assertLineLengths($result['message']);
<ide> public function testSendRenderWithHTML()
<ide> */
<ide> public function testSendRenderWithVars()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->template('custom', 'default');
<del> $this->CakeEmail->viewVars(['value' => 12345]);
<del> $result = $this->CakeEmail->send();
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->template('custom', 'default');
<add> $this->Email->viewVars(['value' => 12345]);
<add> $result = $this->Email->send();
<ide>
<ide> $this->assertContains('Here is your value: 12345', $result['message']);
<ide> }
<ide> public function testSendRenderWithVars()
<ide> */
<ide> public function testSendRenderWithVarsJapanese()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->template('japanese', 'default');
<del> $this->CakeEmail->viewVars(['value' => '日本語の差し込み123']);
<del> $this->CakeEmail->charset = 'ISO-2022-JP';
<del> $result = $this->CakeEmail->send();
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->template('japanese', 'default');
<add> $this->Email->viewVars(['value' => '日本語の差し込み123']);
<add> $this->Email->charset = 'ISO-2022-JP';
<add> $result = $this->Email->send();
<ide>
<ide> $expected = mb_convert_encoding('ここにあなたの設定した値が入ります: 日本語の差し込み123', 'ISO-2022-JP');
<ide> $this->assertTrue((bool)strpos($result['message'], $expected));
<ide> public function testSendRenderWithVarsJapanese()
<ide> */
<ide> public function testSendRenderWithHelpers()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<ide> $timestamp = time();
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->template('custom_helper', 'default');
<del> $this->CakeEmail->viewVars(['time' => $timestamp]);
<del>
<del> $result = $this->CakeEmail->helpers(['Time']);
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->template('custom_helper', 'default');
<add> $this->Email->viewVars(['time' => $timestamp]);
<add>
<add> $result = $this->Email->helpers(['Time']);
<ide> $this->assertInstanceOf('Cake\Mailer\Email', $result);
<ide>
<del> $result = $this->CakeEmail->send();
<add> $result = $this->Email->send();
<ide> $dateTime = new \DateTime;
<ide> $dateTime->setTimestamp($timestamp);
<ide> $this->assertTrue((bool)strpos($result['message'], 'Right now: ' . $dateTime->format($dateTime::ATOM)));
<ide>
<del> $result = $this->CakeEmail->helpers();
<add> $result = $this->Email->helpers();
<ide> $this->assertEquals(['Time'], $result);
<ide> }
<ide>
<ide> public function testSendRenderWithHelpers()
<ide> */
<ide> public function testSendRenderWithImage()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->template('image');
<del> $this->CakeEmail->emailFormat('html');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->template('image');
<add> $this->Email->emailFormat('html');
<ide> $server = env('SERVER_NAME') ? env('SERVER_NAME') : 'localhost';
<ide>
<ide> if (env('SERVER_PORT') && env('SERVER_PORT') != 80) {
<ide> $server .= ':' . env('SERVER_PORT');
<ide> }
<ide>
<ide> $expected = '<img src="http://' . $server . '/img/image.gif" alt="cool image" width="100" height="100"';
<del> $result = $this->CakeEmail->send();
<add> $result = $this->Email->send();
<ide> $this->assertContains($expected, $result['message']);
<ide> }
<ide>
<ide> public function testSendRenderPlugin()
<ide> {
<ide> Plugin::load(['TestPlugin', 'TestPluginTwo', 'TestTheme']);
<ide>
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<ide>
<del> $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'default')->send();
<add> $result = $this->Email->template('TestPlugin.test_plugin_tpl', 'default')->send();
<ide> $this->assertContains('Into TestPlugin.', $result['message']);
<ide> $this->assertContains('This email was sent using the CakePHP Framework', $result['message']);
<ide>
<del> $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'TestPlugin.plug_default')->send();
<add> $result = $this->Email->template('TestPlugin.test_plugin_tpl', 'TestPlugin.plug_default')->send();
<ide> $this->assertContains('Into TestPlugin.', $result['message']);
<ide> $this->assertContains('This email was sent using the TestPlugin.', $result['message']);
<ide>
<del> $result = $this->CakeEmail->template('TestPlugin.test_plugin_tpl', 'plug_default')->send();
<add> $result = $this->Email->template('TestPlugin.test_plugin_tpl', 'plug_default')->send();
<ide> $this->assertContains('Into TestPlugin.', $result['message']);
<ide> $this->assertContains('This email was sent using the TestPlugin.', $result['message']);
<ide>
<del> $this->CakeEmail->template(
<add> $this->Email->template(
<ide> 'TestPlugin.test_plugin_tpl',
<ide> 'TestPluginTwo.default'
<ide> );
<del> $result = $this->CakeEmail->send();
<add> $result = $this->Email->send();
<ide> $this->assertContains('Into TestPlugin.', $result['message']);
<ide> $this->assertContains('This email was sent using TestPluginTwo.', $result['message']);
<ide>
<ide> // test plugin template overridden by theme
<del> $this->CakeEmail->theme('TestTheme');
<del> $result = $this->CakeEmail->send();
<add> $this->Email->theme('TestTheme');
<add> $result = $this->Email->send();
<ide>
<ide> $this->assertContains('Into TestPlugin. (themed)', $result['message']);
<ide>
<del> $this->CakeEmail->viewVars(['value' => 12345]);
<del> $result = $this->CakeEmail->template('custom', 'TestPlugin.plug_default')->send();
<add> $this->Email->viewVars(['value' => 12345]);
<add> $result = $this->Email->template('custom', 'TestPlugin.plug_default')->send();
<ide> $this->assertContains('Here is your value: 12345', $result['message']);
<ide> $this->assertContains('This email was sent using the TestPlugin.', $result['message']);
<ide>
<ide> $this->setExpectedException('Cake\View\Exception\MissingTemplateException');
<del> $this->CakeEmail->template('test_plugin_tpl', 'plug_default')->send();
<add> $this->Email->template('test_plugin_tpl', 'plug_default')->send();
<ide> }
<ide>
<ide> /**
<ide> public function testSendRenderPlugin()
<ide> */
<ide> public function testSendMultipleMIME()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<ide>
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->template('custom', 'default');
<del> $this->CakeEmail->profile([]);
<del> $this->CakeEmail->viewVars(['value' => 12345]);
<del> $this->CakeEmail->emailFormat('both');
<del> $this->CakeEmail->send();
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->template('custom', 'default');
<add> $this->Email->profile([]);
<add> $this->Email->viewVars(['value' => 12345]);
<add> $this->Email->emailFormat('both');
<add> $this->Email->send();
<ide>
<del> $message = $this->CakeEmail->message();
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $message = $this->Email->message();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertFalse(empty($boundary));
<ide> $this->assertContains('--' . $boundary, $message);
<ide> $this->assertContains('--' . $boundary . '--', $message);
<ide>
<del> $this->CakeEmail->attachments(['fake.php' => __FILE__]);
<del> $this->CakeEmail->send();
<add> $this->Email->attachments(['fake.php' => __FILE__]);
<add> $this->Email->send();
<ide>
<del> $message = $this->CakeEmail->message();
<del> $boundary = $this->CakeEmail->getBoundary();
<add> $message = $this->Email->message();
<add> $boundary = $this->Email->getBoundary();
<ide> $this->assertFalse(empty($boundary));
<ide> $this->assertContains('--' . $boundary, $message);
<ide> $this->assertContains('--' . $boundary . '--', $message);
<ide> public function testSendMultipleMIME()
<ide> */
<ide> public function testSendAttachment()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile([]);
<del> $this->CakeEmail->attachments([CAKE . 'basics.php']);
<del> $result = $this->CakeEmail->send('body');
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile([]);
<add> $this->Email->attachments([CAKE . 'basics.php']);
<add> $result = $this->Email->send('body');
<ide> $expected = "Content-Disposition: attachment; filename=\"basics.php\"\r\n" .
<ide> "Content-Type: text/x-php\r\n" .
<ide> "Content-Transfer-Encoding: base64\r\n";
<ide> $this->assertContains($expected, $result['message']);
<ide>
<del> $this->CakeEmail->attachments(['my.file.txt' => CAKE . 'basics.php']);
<del> $result = $this->CakeEmail->send('body');
<add> $this->Email->attachments(['my.file.txt' => CAKE . 'basics.php']);
<add> $result = $this->Email->send('body');
<ide> $expected = "Content-Disposition: attachment; filename=\"my.file.txt\"\r\n" .
<ide> "Content-Type: text/x-php\r\n" .
<ide> "Content-Transfer-Encoding: base64\r\n";
<ide> $this->assertContains($expected, $result['message']);
<ide>
<del> $this->CakeEmail->attachments(['file.txt' => ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain']]);
<del> $result = $this->CakeEmail->send('body');
<add> $this->Email->attachments(['file.txt' => ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain']]);
<add> $result = $this->Email->send('body');
<ide> $expected = "Content-Disposition: attachment; filename=\"file.txt\"\r\n" .
<ide> "Content-Type: text/plain\r\n" .
<ide> "Content-Transfer-Encoding: base64\r\n";
<ide> $this->assertContains($expected, $result['message']);
<ide>
<del> $this->CakeEmail->attachments(['file2.txt' => ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain', 'contentId' => 'a1b1c1']]);
<del> $result = $this->CakeEmail->send('body');
<add> $this->Email->attachments(['file2.txt' => ['file' => CAKE . 'basics.php', 'mimetype' => 'text/plain', 'contentId' => 'a1b1c1']]);
<add> $result = $this->Email->send('body');
<ide> $expected = "Content-Disposition: inline; filename=\"file2.txt\"\r\n" .
<ide> "Content-Type: text/plain\r\n" .
<ide> "Content-Transfer-Encoding: base64\r\n" .
<ide> public function testDeliver()
<ide> */
<ide> public function testMessage()
<ide> {
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to(['you@cakephp.org' => 'You']);
<del> $this->CakeEmail->subject('My title');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->template('default', 'default');
<del> $this->CakeEmail->emailFormat('both');
<del> $this->CakeEmail->send();
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to(['you@cakephp.org' => 'You']);
<add> $this->Email->subject('My title');
<add> $this->Email->profile(['empty']);
<add> $this->Email->template('default', 'default');
<add> $this->Email->emailFormat('both');
<add> $this->Email->send();
<ide>
<ide> $expected = '<p>This email was sent using the <a href="http://cakephp.org">CakePHP Framework</a></p>';
<del> $this->assertContains($expected, $this->CakeEmail->message(Email::MESSAGE_HTML));
<add> $this->assertContains($expected, $this->Email->message(Email::MESSAGE_HTML));
<ide>
<ide> $expected = 'This email was sent using the CakePHP Framework, http://cakephp.org.';
<del> $this->assertContains($expected, $this->CakeEmail->message(Email::MESSAGE_TEXT));
<add> $this->assertContains($expected, $this->Email->message(Email::MESSAGE_TEXT));
<ide>
<del> $message = $this->CakeEmail->message();
<add> $message = $this->Email->message();
<ide> $this->assertContains('Content-Type: text/plain; charset=UTF-8', $message);
<ide> $this->assertContains('Content-Type: text/html; charset=UTF-8', $message);
<ide>
<ide> // UTF-8 is 8bit
<ide> $this->assertTrue($this->_checkContentTransferEncoding($message, '8bit'));
<ide>
<del> $this->CakeEmail->charset = 'ISO-2022-JP';
<del> $this->CakeEmail->send();
<del> $message = $this->CakeEmail->message();
<add> $this->Email->charset = 'ISO-2022-JP';
<add> $this->Email->send();
<add> $message = $this->Email->message();
<ide> $this->assertContains('Content-Type: text/plain; charset=ISO-2022-JP', $message);
<ide> $this->assertContains('Content-Type: text/html; charset=ISO-2022-JP', $message);
<ide>
<ide> public function testMessage()
<ide> */
<ide> public function testReset()
<ide> {
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->theme('TestTheme');
<del> $this->CakeEmail->emailPattern('/.+@.+\..+/i');
<del> $this->assertSame(['cake@cakephp.org' => 'cake@cakephp.org'], $this->CakeEmail->to());
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->theme('TestTheme');
<add> $this->Email->emailPattern('/.+@.+\..+/i');
<add> $this->assertSame(['cake@cakephp.org' => 'cake@cakephp.org'], $this->Email->to());
<ide>
<del> $this->CakeEmail->reset();
<del> $this->assertSame([], $this->CakeEmail->to());
<del> $this->assertFalse($this->CakeEmail->theme());
<del> $this->assertSame(Email::EMAIL_PATTERN, $this->CakeEmail->emailPattern());
<add> $this->Email->reset();
<add> $this->assertSame([], $this->Email->to());
<add> $this->assertFalse($this->Email->theme());
<add> $this->assertSame(Email::EMAIL_PATTERN, $this->Email->emailPattern());
<ide> }
<ide>
<ide> /**
<ide> public function testReset()
<ide> */
<ide> public function testResetWithCharset()
<ide> {
<del> $this->CakeEmail->charset = 'ISO-2022-JP';
<del> $this->CakeEmail->reset();
<add> $this->Email->charset = 'ISO-2022-JP';
<add> $this->Email->reset();
<ide>
<del> $this->assertSame('utf-8', $this->CakeEmail->charset, $this->CakeEmail->charset);
<del> $this->assertNull($this->CakeEmail->headerCharset, $this->CakeEmail->headerCharset);
<add> $this->assertSame('utf-8', $this->Email->charset, $this->Email->charset);
<add> $this->assertNull($this->Email->headerCharset, $this->Email->headerCharset);
<ide> }
<ide>
<ide> /**
<ide> public function testResetWithCharset()
<ide> public function testWrap()
<ide> {
<ide> $text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac turpis orci, non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.';
<del> $result = $this->CakeEmail->wrap($text, Email::LINE_LENGTH_SHOULD);
<add> $result = $this->Email->wrap($text, Email::LINE_LENGTH_SHOULD);
<ide> $expected = [
<ide> 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac turpis orci,',
<ide> 'non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.',
<ide> public function testWrap()
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $text = 'Lorem ipsum dolor sit amet, consectetur < adipiscing elit. Donec ac turpis orci, non commodo odio. Morbi nibh nisi, vehicula > pellentesque accumsan amet.';
<del> $result = $this->CakeEmail->wrap($text, Email::LINE_LENGTH_SHOULD);
<add> $result = $this->Email->wrap($text, Email::LINE_LENGTH_SHOULD);
<ide> $expected = [
<ide> 'Lorem ipsum dolor sit amet, consectetur < adipiscing elit. Donec ac turpis',
<ide> 'orci, non commodo odio. Morbi nibh nisi, vehicula > pellentesque accumsan',
<ide> public function testWrap()
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $text = '<p>Lorem ipsum dolor sit amet,<br> consectetur adipiscing elit.<br> Donec ac turpis orci, non <b>commodo</b> odio. <br /> Morbi nibh nisi, vehicula pellentesque accumsan amet.<hr></p>';
<del> $result = $this->CakeEmail->wrap($text, Email::LINE_LENGTH_SHOULD);
<add> $result = $this->Email->wrap($text, Email::LINE_LENGTH_SHOULD);
<ide> $expected = [
<ide> '<p>Lorem ipsum dolor sit amet,<br> consectetur adipiscing elit.<br> Donec ac',
<ide> 'turpis orci, non <b>commodo</b> odio. <br /> Morbi nibh nisi, vehicula',
<ide> public function testWrap()
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac <a href="http://cakephp.org">turpis</a> orci, non commodo odio. Morbi nibh nisi, vehicula pellentesque accumsan amet.';
<del> $result = $this->CakeEmail->wrap($text, Email::LINE_LENGTH_SHOULD);
<add> $result = $this->Email->wrap($text, Email::LINE_LENGTH_SHOULD);
<ide> $expected = [
<ide> 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac',
<ide> '<a href="http://cakephp.org">turpis</a> orci, non commodo odio. Morbi nibh',
<ide> public function testWrap()
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $text = 'Lorem ipsum <a href="http://www.cakephp.org/controller/action/param1/param2" class="nice cool fine amazing awesome">ok</a>';
<del> $result = $this->CakeEmail->wrap($text, Email::LINE_LENGTH_SHOULD);
<add> $result = $this->Email->wrap($text, Email::LINE_LENGTH_SHOULD);
<ide> $expected = [
<ide> 'Lorem ipsum',
<ide> '<a href="http://www.cakephp.org/controller/action/param1/param2" class="nice cool fine amazing awesome">',
<ide> public function testWrap()
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $text = 'Lorem ipsum withonewordverybigMorethanthelineshouldsizeofrfcspecificationbyieeeavailableonieeesite ok.';
<del> $result = $this->CakeEmail->wrap($text, Email::LINE_LENGTH_SHOULD);
<add> $result = $this->Email->wrap($text, Email::LINE_LENGTH_SHOULD);
<ide> $expected = [
<ide> 'Lorem ipsum',
<ide> 'withonewordverybigMorethanthelineshouldsizeofrfcspecificationbyieeeavailableonieeesite',
<ide> public function testWrap()
<ide> */
<ide> public function testRenderWithLayoutAndAttachment()
<ide> {
<del> $this->CakeEmail->emailFormat('html');
<del> $this->CakeEmail->template('html', 'default');
<del> $this->CakeEmail->attachments([CAKE . 'basics.php']);
<del> $result = $this->CakeEmail->render([]);
<add> $this->Email->emailFormat('html');
<add> $this->Email->template('html', 'default');
<add> $this->Email->attachments([CAKE . 'basics.php']);
<add> $result = $this->Email->render([]);
<ide> $this->assertNotEmpty($result);
<ide>
<del> $result = $this->CakeEmail->getBoundary();
<add> $result = $this->Email->getBoundary();
<ide> $this->assertRegExp('/^[0-9a-f]{32}$/', $result);
<ide> }
<ide>
<ide> public function testConstructWithConfigArray()
<ide> 'subject' => 'Test mail subject',
<ide> 'transport' => 'debug',
<ide> ];
<del> $this->CakeEmail = new Email($configs);
<add> $this->Email = new Email($configs);
<ide>
<del> $result = $this->CakeEmail->to();
<add> $result = $this->Email->to();
<ide> $this->assertEquals([$configs['to'] => $configs['to']], $result);
<ide>
<del> $result = $this->CakeEmail->from();
<add> $result = $this->Email->from();
<ide> $this->assertEquals($configs['from'], $result);
<ide>
<del> $result = $this->CakeEmail->subject();
<add> $result = $this->Email->subject();
<ide> $this->assertEquals($configs['subject'], $result);
<ide>
<del> $result = $this->CakeEmail->transport();
<add> $result = $this->Email->transport();
<ide> $this->assertInstanceOf('Cake\Mailer\Transport\DebugTransport', $result);
<ide>
<del> $result = $this->CakeEmail->send('This is the message');
<add> $result = $this->Email->send('This is the message');
<ide>
<ide> $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: '));
<ide> $this->assertTrue((bool)strpos($result['headers'], 'To: '));
<ide> public function testConfigArrayWithLayoutWithoutTemplate()
<ide> 'transport' => 'debug',
<ide> 'layout' => 'custom'
<ide> ];
<del> $this->CakeEmail = new Email($configs);
<add> $this->Email = new Email($configs);
<ide>
<del> $result = $this->CakeEmail->template();
<add> $result = $this->Email->template();
<ide> $this->assertEquals('', $result['template']);
<ide> $this->assertEquals($configs['layout'], $result['layout']);
<ide> }
<ide> public function testConstructWithConfigString()
<ide> ];
<ide> Email::config('test', $configs);
<ide>
<del> $this->CakeEmail = new Email('test');
<add> $this->Email = new Email('test');
<ide>
<del> $result = $this->CakeEmail->to();
<add> $result = $this->Email->to();
<ide> $this->assertEquals([$configs['to'] => $configs['to']], $result);
<ide>
<del> $result = $this->CakeEmail->from();
<add> $result = $this->Email->from();
<ide> $this->assertEquals($configs['from'], $result);
<ide>
<del> $result = $this->CakeEmail->subject();
<add> $result = $this->Email->subject();
<ide> $this->assertEquals($configs['subject'], $result);
<ide>
<del> $result = $this->CakeEmail->transport();
<add> $result = $this->Email->transport();
<ide> $this->assertInstanceOf('Cake\Mailer\Transport\DebugTransport', $result);
<ide>
<del> $result = $this->CakeEmail->send('This is the message');
<add> $result = $this->Email->send('This is the message');
<ide>
<ide> $this->assertTrue((bool)strpos($result['headers'], 'Message-ID: '));
<ide> $this->assertTrue((bool)strpos($result['headers'], 'To: '));
<ide> public function testConstructWithConfigString()
<ide> */
<ide> public function testViewRender()
<ide> {
<del> $result = $this->CakeEmail->viewRender();
<add> $result = $this->Email->viewRender();
<ide> $this->assertEquals('Cake\View\View', $result);
<ide>
<del> $result = $this->CakeEmail->viewRender('Cake\View\ThemeView');
<add> $result = $this->Email->viewRender('Cake\View\ThemeView');
<ide> $this->assertInstanceOf('Cake\Mailer\Email', $result);
<ide>
<del> $result = $this->CakeEmail->viewRender();
<add> $result = $this->Email->viewRender();
<ide> $this->assertEquals('Cake\View\ThemeView', $result);
<ide> }
<ide>
<ide> public function testViewRender()
<ide> */
<ide> public function testEmailFormat()
<ide> {
<del> $result = $this->CakeEmail->emailFormat();
<add> $result = $this->Email->emailFormat();
<ide> $this->assertEquals('text', $result);
<ide>
<del> $result = $this->CakeEmail->emailFormat('html');
<add> $result = $this->Email->emailFormat('html');
<ide> $this->assertInstanceOf('Cake\Mailer\Email', $result);
<ide>
<del> $result = $this->CakeEmail->emailFormat();
<add> $result = $this->Email->emailFormat();
<ide> $this->assertEquals('html', $result);
<ide>
<ide> $this->setExpectedException('InvalidArgumentException');
<del> $result = $this->CakeEmail->emailFormat('invalid');
<add> $result = $this->Email->emailFormat('invalid');
<ide> }
<ide>
<ide> /**
<ide> public function testBodyEncodingIso2022JpMs()
<ide>
<ide> protected function _checkContentTransferEncoding($message, $charset)
<ide> {
<del> $boundary = '--' . $this->CakeEmail->getBoundary();
<add> $boundary = '--' . $this->Email->getBoundary();
<ide> $result['text'] = false;
<ide> $result['html'] = false;
<ide> $length = count($message);
<ide> protected function _checkContentTransferEncoding($message, $charset)
<ide> */
<ide> public function testEncode()
<ide> {
<del> $this->CakeEmail->headerCharset = 'ISO-2022-JP';
<del> $result = $this->CakeEmail->encode('日本語');
<add> $this->Email->headerCharset = 'ISO-2022-JP';
<add> $result = $this->Email->encode('日本語');
<ide> $expected = '=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?=';
<ide> $this->assertSame($expected, $result);
<ide>
<del> $this->CakeEmail->headerCharset = 'ISO-2022-JP';
<del> $result = $this->CakeEmail->encode('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?');
<add> $this->Email->headerCharset = 'ISO-2022-JP';
<add> $result = $this->Email->encode('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?');
<ide> $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
<ide> " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
<ide> " =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=";
<ide> public function testEncode()
<ide> */
<ide> public function testDecode()
<ide> {
<del> $this->CakeEmail->headerCharset = 'ISO-2022-JP';
<del> $result = $this->CakeEmail->decode('=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?=');
<add> $this->Email->headerCharset = 'ISO-2022-JP';
<add> $result = $this->Email->decode('=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?=');
<ide> $expected = '日本語';
<ide> $this->assertSame($expected, $result);
<ide>
<del> $this->CakeEmail->headerCharset = 'ISO-2022-JP';
<del> $result = $this->CakeEmail->decode("=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
<add> $this->Email->headerCharset = 'ISO-2022-JP';
<add> $result = $this->Email->decode("=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" .
<ide> " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" .
<ide> " =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?=");
<ide> $expected = '長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?';
<ide> public function testDecode()
<ide> */
<ide> public function testCharset()
<ide> {
<del> $this->CakeEmail->charset('UTF-8');
<del> $this->assertSame($this->CakeEmail->charset(), 'UTF-8');
<add> $this->Email->charset('UTF-8');
<add> $this->assertSame($this->Email->charset(), 'UTF-8');
<ide>
<del> $this->CakeEmail->charset('ISO-2022-JP');
<del> $this->assertSame($this->CakeEmail->charset(), 'ISO-2022-JP');
<add> $this->Email->charset('ISO-2022-JP');
<add> $this->assertSame($this->Email->charset(), 'ISO-2022-JP');
<ide>
<del> $charset = $this->CakeEmail->charset('Shift_JIS');
<add> $charset = $this->Email->charset('Shift_JIS');
<ide> $this->assertSame($charset, 'Shift_JIS');
<ide> }
<ide>
<ide> public function testCharset()
<ide> */
<ide> public function testHeaderCharset()
<ide> {
<del> $this->CakeEmail->headerCharset('UTF-8');
<del> $this->assertSame($this->CakeEmail->headerCharset(), 'UTF-8');
<add> $this->Email->headerCharset('UTF-8');
<add> $this->assertSame($this->Email->headerCharset(), 'UTF-8');
<ide>
<del> $this->CakeEmail->headerCharset('ISO-2022-JP');
<del> $this->assertSame($this->CakeEmail->headerCharset(), 'ISO-2022-JP');
<add> $this->Email->headerCharset('ISO-2022-JP');
<add> $this->assertSame($this->Email->headerCharset(), 'ISO-2022-JP');
<ide>
<del> $charset = $this->CakeEmail->headerCharset('Shift_JIS');
<add> $charset = $this->Email->headerCharset('Shift_JIS');
<ide> $this->assertSame($charset, 'Shift_JIS');
<ide> }
<ide>
<ide> public function testWrapLongLine()
<ide> {
<ide> $message = '<a href="http://cakephp.org">' . str_repeat('x', Email::LINE_LENGTH_MUST) . "</a>";
<ide>
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('Wordwrap Test');
<del> $this->CakeEmail->profile(['empty']);
<del> $result = $this->CakeEmail->send($message);
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('Wordwrap Test');
<add> $this->Email->profile(['empty']);
<add> $result = $this->Email->send($message);
<ide> $expected = "<a\r\n" . 'href="http://cakephp.org">' . str_repeat('x', Email::LINE_LENGTH_MUST - 26) . "\r\n" .
<ide> str_repeat('x', 26) . "\r\n</a>\r\n\r\n";
<ide> $this->assertEquals($expected, $result['message']);
<ide> public function testWrapLongLine()
<ide> $length = strlen($str1) + strlen($str2);
<ide> $message = $str1 . str_repeat('x', Email::LINE_LENGTH_MUST - $length - 1) . $str2;
<ide>
<del> $result = $this->CakeEmail->send($message);
<add> $result = $this->Email->send($message);
<ide> $expected = "{$message}\r\n\r\n";
<ide> $this->assertEquals($expected, $result['message']);
<ide> $this->assertLineLengths($result['message']);
<ide>
<ide> $message = $str1 . str_repeat('x', Email::LINE_LENGTH_MUST - $length) . $str2;
<ide>
<del> $result = $this->CakeEmail->send($message);
<add> $result = $this->Email->send($message);
<ide> $expected = "{$message}\r\n\r\n";
<ide> $this->assertEquals($expected, $result['message']);
<ide> $this->assertLineLengths($result['message']);
<ide>
<ide> $message = $str1 . str_repeat('x', Email::LINE_LENGTH_MUST - $length + 1) . $str2;
<ide>
<del> $result = $this->CakeEmail->send($message);
<add> $result = $this->Email->send($message);
<ide> $expected = $str1 . str_repeat('x', Email::LINE_LENGTH_MUST - $length + 1) . sprintf("\r\n%s\r\n\r\n", trim($str2));
<ide> $this->assertEquals($expected, $result['message']);
<ide> $this->assertLineLengths($result['message']);
<ide> public function testWrapWithTagsAcrossLines()
<ide> $length = strlen($str);
<ide> $message = $str . str_repeat('x', Email::LINE_LENGTH_MUST + 1);
<ide>
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('Wordwrap Test');
<del> $this->CakeEmail->profile(['empty']);
<del> $result = $this->CakeEmail->send($message);
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('Wordwrap Test');
<add> $this->Email->profile(['empty']);
<add> $result = $this->Email->send($message);
<ide> $message = str_replace("\r\n", "\n", substr($message, 0, -9));
<ide> $message = str_replace("\n", "\r\n", $message);
<ide> $expected = "{$message}\r\nxxxxxxxxx\r\n\r\n";
<ide> public function testWrapIncludeLessThanSign()
<ide> $length = strlen($str);
<ide> $message = $str . str_repeat('x', Email::LINE_LENGTH_MUST - $length + 1);
<ide>
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('Wordwrap Test');
<del> $this->CakeEmail->profile(['empty']);
<del> $result = $this->CakeEmail->send($message);
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('Wordwrap Test');
<add> $this->Email->profile(['empty']);
<add> $result = $this->Email->send($message);
<ide> $message = substr($message, 0, -1);
<ide> $expected = "{$message}\r\nx\r\n\r\n";
<ide> $this->assertEquals($expected, $result['message']);
<ide> public function testWrapForJapaneseEncoding()
<ide>
<ide> $message = mb_convert_encoding('受け付けました', 'iso-2022-jp', 'UTF-8');
<ide>
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('Wordwrap Test');
<del> $this->CakeEmail->profile(['empty']);
<del> $this->CakeEmail->charset('iso-2022-jp');
<del> $this->CakeEmail->headerCharset('iso-2022-jp');
<del> $result = $this->CakeEmail->send($message);
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('Wordwrap Test');
<add> $this->Email->profile(['empty']);
<add> $this->Email->charset('iso-2022-jp');
<add> $this->Email->headerCharset('iso-2022-jp');
<add> $result = $this->Email->send($message);
<ide> $expected = "{$message}\r\n\r\n";
<ide> $this->assertEquals($expected, $result['message']);
<ide> }
<ide> public function testZeroOnlyLinesNotBeingEmptied()
<ide> {
<ide> $message = "Lorem\r\n0\r\n0\r\nipsum";
<ide>
<del> $this->CakeEmail->reset();
<del> $this->CakeEmail->transport('debug');
<del> $this->CakeEmail->from('cake@cakephp.org');
<del> $this->CakeEmail->to('cake@cakephp.org');
<del> $this->CakeEmail->subject('Wordwrap Test');
<del> $result = $this->CakeEmail->send($message);
<add> $this->Email->reset();
<add> $this->Email->transport('debug');
<add> $this->Email->from('cake@cakephp.org');
<add> $this->Email->to('cake@cakephp.org');
<add> $this->Email->subject('Wordwrap Test');
<add> $result = $this->Email->send($message);
<ide> $expected = "{$message}\r\n\r\n";
<ide> $this->assertEquals($expected, $result['message']);
<ide> }
<ide> public function testJsonSerialize()
<ide> </framework>
<ide> XML;
<ide>
<del> $this->CakeEmail->reset()
<add> $this->Email->reset()
<ide> ->to(['cakephp@cakephp.org' => 'CakePHP'])
<ide> ->from('noreply@cakephp.org')
<ide> ->replyTo('cakephp@cakephp.org')
<ide> public function testJsonSerialize()
<ide> ]
<ide> ]);
<ide>
<del> $this->CakeEmail->viewBuilder()
<add> $this->Email->viewBuilder()
<ide> ->template('default')
<ide> ->layout('test');
<ide>
<del> $result = json_decode(json_encode($this->CakeEmail), true);
<add> $result = json_decode(json_encode($this->Email), true);
<ide> $this->assertContains('test', $result['viewVars']['exception']);
<ide> unset($result['viewVars']['exception']);
<ide>
<ide> public function testJsonSerialize()
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = json_decode(json_encode(unserialize(serialize($this->CakeEmail))), true);
<add> $result = json_decode(json_encode(unserialize(serialize($this->Email))), true);
<ide> $this->assertContains('test', $result['viewVars']['exception']);
<ide> unset($result['viewVars']['exception']);
<ide> $this->assertEquals($expected, $result); | 2 |
Javascript | Javascript | update version to 1.12.0 | 020aaa53e1fe89d318557b1be0267777cc0127e8 | <ide><path>d3.js
<del>(function(){d3 = {version: "1.11.1"}; // semver
<add>(function(){d3 = {version: "1.12.0"}; // semver
<ide> if (!Date.now) Date.now = function() {
<ide> return +new Date();
<ide> };
<ide><path>d3.min.js
<del>(function(){function bS(){return"circle"}function bR(){return 64}function bP(a){return[a.x,a.y]}function bO(a){return a.endAngle}function bN(a){return a.startAngle}function bM(a){return a.radius}function bL(a){return a.target}function bK(a){return a.source}function bJ(){return 0}function bI(a,b,c){a.push("C",bE(bF,b),",",bE(bF,c),",",bE(bG,b),",",bE(bG,c),",",bE(bH,b),",",bE(bH,c))}function bE(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bD(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bE(bH,g),",",bE(bH,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bI(b,g,h);return b.join("")}function bC(a){if(a.length<3)return bv(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bI(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bI(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bI(b,h,i);return b.join("")}function bB(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bA(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bv(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bz(a,b,c){return a.length<3?bv(a):a[0]+bA(a,bB(a,b))}function by(a,b){return a.length<3?bv(a):a[0]+bA((a.push(a[0]),a),bB([a[a.length-2]].concat(a,[a[1]]),b))}function bx(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bw(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bv(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bt(a){return a[1]}function bs(a){return a[0]}function br(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bq(a){return a.endAngle}function bp(a){return a.startAngle}function bo(a){return a.outerRadius}function bn(a){return a.innerRadius}function bg(a){return function(b){return-Math.pow(-b,a)}}function bf(a){return function(b){return Math.pow(b,a)}}function be(a){return-Math.log(-a)/Math.LN10}function bd(a){return Math.log(a)/Math.LN10}function bb(){var a=null,b=Y,c=Infinity;while(b)b.flush?b=a?a.next=b.next:Y=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function ba(){var a,b=Date.now(),c=null,d=Y;while(d)a=b-d.then,a>d.delay&&(d.flush=d.callback(a)),d=(c=d).next;var e=bb()-b;e>24?(isFinite(e)&&(clearTimeout($),$=setTimeout(ba,e)),Z=0):(Z=1,bc(ba))}function _(a,b){var c=Date.now(),d=!1,e,f=Y;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(Y={callback:a,then:c,delay:b,next:Y}),Z||($=clearTimeout($),Z=1,bc(ba))}}function X(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function W(a){function n(b){var g=!0,l=-1;a.each(function(){if(i[++l]!=2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){g=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!=c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a==1){i[l]=2;if(n.active==c){var r=n.owner;r==c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),V=c,h.end.dispatch.apply(this,arguments),V=0,n.owner=r}}}});return g}var b={},c=V||++U,d={},e=[],f=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),_(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,X(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,X(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=W(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=W(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=g;return b.delay(0).duration(250)}function T(a){return{__data__:a}}function S(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function R(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return Q(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function Q(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return Q(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return Q(c)}a.select=function(a){return b(function(b){return N(a,b)})},a.selectAll=function(a){return c(function(b){return O(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return Q(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=T(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=T(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=T(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=Q(e);k.enter=function(){return R(d)},k.exit=function(){return Q(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){var a=f(this.className.replace(e," "));this.className=a.length?a:null}function g(){var a=this.className;e.lastIndex=0,e.test(a)||(this.className=f(a+" "+b))}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){e.lastIndex=0;return e.test(this.className)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=S.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c){var d=b.indexOf("."),e=d==-1?b:b.substring(0,d),f="__on"+b;return a.each(function(a,b){function d(d){var e=d3.event;d3.event=d;try{c.call(this,a,b)}finally{d3.event=e}}this[f]&&this.removeEventListener(e,this[f],!1),c&&this.addEventListener(e,this[f]=d,!1)})},a.transition=function(){return W(a)},a.call=g;return a}function M(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return C(g(a+120),g(a),g(a-120))}function L(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function K(a,b,c){return{h:a,s:b,l:c,toString:L}}function H(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function G(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return K(g,h,i)}function F(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(H(h[0]),H(h[1]),H(h[2]))}}if(i=I[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)=="#"&&(a.length==4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length==7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function E(a){return a<16?"0"+a.toString(16):a.toString(16)}function D(){return"#"+E(this.r)+E(this.g)+E(this.b)}function C(a,b,c){return{r:a,g:b,b:c,toString:D}}function B(a){return a in A||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function x(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function w(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function v(a){return 1-Math.sqrt(1-a*a)}function u(a){return a?Math.pow(2,10*(a-1))-.001:0}function t(a){return 1-Math.cos(a*Math.PI/2)}function s(a){return function(b){return Math.pow(b,a)}}function r(a){return a}function q(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function p(a){return function(b){return 1-a(1-b)}}function k(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function i(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function g(a){a.apply(this,(arguments[0]=this,arguments));return this}function f(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function e(a){return a==null}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.11.1"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:0},d3.descending=function(a,b){return b<a?-1:b>a?1:0},d3.min=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],f,g=-1,h=a.length;arguments.length<2&&(b=e);while(++g<h)b.call(d,f=a[g],g)?d=[]:(d.length||c.push(d),d.push(f));return c},d3.range=function(a,b,c){arguments.length==1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(h,"\\$&")};var h=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState==4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=i(c);return b},d3.format=function(a){var b=j.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i=="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i=="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+j.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=k(a)),a=j+a}else{g&&(a=k(a)),a=j+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var j=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l=s(2),m=s(3),n={linear:function(){return r},poly:s,quad:function(){return l},cubic:function(){return m},sin:function(){return t},exp:function(){return u},circle:function(){return v},elastic:w,back:x,bounce:function(){return y}},o={"in":function(a){return a},out:p,"in-out":q,"out-in":function(a){return q(p(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return o[d](n[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in I||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;z.lastIndex=0;for(d=0;c=z.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=z.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=z.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length==1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return M(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=B(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var z=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,A={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length==1?F(""+a,C,M):C(~~a,~~b,~~c)};var I={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var J in I)I[J]=F(I[J],C,M);d3.hsl=function(a,b,c){return arguments.length==1?F(""+a,G,K):K(+a,+b,+c)};var N=function(a,b){return b.querySelector(a)},O=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(N=function(a,b){return Sizzle(a,b)[0]},O=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var P=Q([[document]]);P[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?P.select(a):Q([[a]])},d3.selectAll=function(b){return typeof b=="string"?P.selectAll(b):Q([a(b)])},d3.transition=P.transition;var U=0,V=0,Y=null,Z,$;d3.timer=function(a){_(a,0)};var bc=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function k(c){var d=Math.min(a,b),e=Math.max(a,b),f=e-d,g=Math.pow(10,Math.floor(Math.log(f/c)/Math.LN10)),h=c/(f/g);h<=.15?g*=10:h<=.35?g*=5:h<=.75&&(g*=2);return{start:Math.ceil(d/g)*g,stop:Math.floor(e/g)*g+g*.5,step:g}}function j(b){b=(b-a)*e;return h(i?Math.max(0,Math.min(1,b)):b)}var a=0,b=1,c=0,d=1,e=1,f=1,g=d3.interpolate,h=g(c,d),i=!1;j.invert=function(b){return(b-c)*f+a},j.domain=function(g){if(!arguments.length)return[a,b];a=+g[0],b=+g[1],e=1/(b-a),f=(b-a)/(d-c);return j},j.range=function(e){if(!arguments.length)return[c,d];c=e[0],d=e[1],f=(b-a)/(d-c),h=g(c,d);return j},j.rangeRound=function(a){return j.range(a).interpolate(d3.interpolateRound)},j.clamp=function(a){if(!arguments.length)return i;i=a;return j},j.interpolate=function(a){if(!arguments.length)return g;h=(g=a)(c,d);return j},j.ticks=function(a){var b=k(a);return d3.range(b.start,b.stop,b.step)},j.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(k(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return j},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bd,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?be:bd,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===be){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bd.pow=function(a){return Math.pow(10,a)},be.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bg:bf;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bh)},d3.scale.category20=function(){return d3.scale.ordinal().range(bi)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bj)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bk)};var bh=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bi=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bj=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bk=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bl,h=d.apply(this,arguments)+bl,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bm?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bn,b=bo,c=bp,d=bq;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bl;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bl=-Math.PI/2,bm=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(br(this,c,a,b),e)}var a=bs,b=bt,c="linear",d=bu[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=bu[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var bu={linear:bv,"step-before":bw,"step-after":bx,basis:bC,"basis-closed":bD,cardinal:bz,"cardinal-closed"
<add>(function(){function bS(){return"circle"}function bR(){return 64}function bP(a){return[a.x,a.y]}function bO(a){return a.endAngle}function bN(a){return a.startAngle}function bM(a){return a.radius}function bL(a){return a.target}function bK(a){return a.source}function bJ(){return 0}function bI(a,b,c){a.push("C",bE(bF,b),",",bE(bF,c),",",bE(bG,b),",",bE(bG,c),",",bE(bH,b),",",bE(bH,c))}function bE(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bD(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bE(bH,g),",",bE(bH,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bI(b,g,h);return b.join("")}function bC(a){if(a.length<3)return bv(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bI(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bI(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bI(b,h,i);return b.join("")}function bB(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bA(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bv(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bz(a,b,c){return a.length<3?bv(a):a[0]+bA(a,bB(a,b))}function by(a,b){return a.length<3?bv(a):a[0]+bA((a.push(a[0]),a),bB([a[a.length-2]].concat(a,[a[1]]),b))}function bx(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bw(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bv(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bt(a){return a[1]}function bs(a){return a[0]}function br(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bq(a){return a.endAngle}function bp(a){return a.startAngle}function bo(a){return a.outerRadius}function bn(a){return a.innerRadius}function bg(a){return function(b){return-Math.pow(-b,a)}}function bf(a){return function(b){return Math.pow(b,a)}}function be(a){return-Math.log(-a)/Math.LN10}function bd(a){return Math.log(a)/Math.LN10}function bb(){var a=null,b=Y,c=Infinity;while(b)b.flush?b=a?a.next=b.next:Y=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function ba(){var a,b=Date.now(),c=null,d=Y;while(d)a=b-d.then,a>d.delay&&(d.flush=d.callback(a)),d=(c=d).next;var e=bb()-b;e>24?(isFinite(e)&&(clearTimeout($),$=setTimeout(ba,e)),Z=0):(Z=1,bc(ba))}function _(a,b){var c=Date.now(),d=!1,e,f=Y;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(Y={callback:a,then:c,delay:b,next:Y}),Z||($=clearTimeout($),Z=1,bc(ba))}}function X(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function W(a){function n(b){var g=!0,l=-1;a.each(function(){if(i[++l]!=2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){g=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!=c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a==1){i[l]=2;if(n.active==c){var r=n.owner;r==c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),V=c,h.end.dispatch.apply(this,arguments),V=0,n.owner=r}}}});return g}var b={},c=V||++U,d={},e=[],f=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),_(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,X(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,X(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=W(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=W(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=g;return b.delay(0).duration(250)}function T(a){return{__data__:a}}function S(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function R(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return Q(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function Q(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return Q(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return Q(c)}a.select=function(a){return b(function(b){return N(a,b)})},a.selectAll=function(a){return c(function(b){return O(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return Q(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=T(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=T(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=T(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=Q(e);k.enter=function(){return R(d)},k.exit=function(){return Q(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){var a=f(this.className.replace(e," "));this.className=a.length?a:null}function g(){var a=this.className;e.lastIndex=0,e.test(a)||(this.className=f(a+" "+b))}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){e.lastIndex=0;return e.test(this.className)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=S.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c){var d=b.indexOf("."),e=d==-1?b:b.substring(0,d),f="__on"+b;return a.each(function(a,b){function d(d){var e=d3.event;d3.event=d;try{c.call(this,a,b)}finally{d3.event=e}}this[f]&&this.removeEventListener(e,this[f],!1),c&&this.addEventListener(e,this[f]=d,!1)})},a.transition=function(){return W(a)},a.call=g;return a}function M(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return C(g(a+120),g(a),g(a-120))}function L(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function K(a,b,c){return{h:a,s:b,l:c,toString:L}}function H(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function G(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return K(g,h,i)}function F(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(H(h[0]),H(h[1]),H(h[2]))}}if(i=I[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)=="#"&&(a.length==4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length==7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function E(a){return a<16?"0"+a.toString(16):a.toString(16)}function D(){return"#"+E(this.r)+E(this.g)+E(this.b)}function C(a,b,c){return{r:a,g:b,b:c,toString:D}}function B(a){return a in A||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function x(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function w(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function v(a){return 1-Math.sqrt(1-a*a)}function u(a){return a?Math.pow(2,10*(a-1))-.001:0}function t(a){return 1-Math.cos(a*Math.PI/2)}function s(a){return function(b){return Math.pow(b,a)}}function r(a){return a}function q(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function p(a){return function(b){return 1-a(1-b)}}function k(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function i(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function g(a){a.apply(this,(arguments[0]=this,arguments));return this}function f(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function e(a){return a==null}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.12.0"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:0},d3.descending=function(a,b){return b<a?-1:b>a?1:0},d3.min=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],f,g=-1,h=a.length;arguments.length<2&&(b=e);while(++g<h)b.call(d,f=a[g],g)?d=[]:(d.length||c.push(d),d.push(f));return c},d3.range=function(a,b,c){arguments.length==1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(h,"\\$&")};var h=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState==4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=i(c);return b},d3.format=function(a){var b=j.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i=="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i=="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+j.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=k(a)),a=j+a}else{g&&(a=k(a)),a=j+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var j=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l=s(2),m=s(3),n={linear:function(){return r},poly:s,quad:function(){return l},cubic:function(){return m},sin:function(){return t},exp:function(){return u},circle:function(){return v},elastic:w,back:x,bounce:function(){return y}},o={"in":function(a){return a},out:p,"in-out":q,"out-in":function(a){return q(p(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return o[d](n[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in I||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;z.lastIndex=0;for(d=0;c=z.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=z.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=z.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length==1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return M(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=B(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var z=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,A={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length==1?F(""+a,C,M):C(~~a,~~b,~~c)};var I={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var J in I)I[J]=F(I[J],C,M);d3.hsl=function(a,b,c){return arguments.length==1?F(""+a,G,K):K(+a,+b,+c)};var N=function(a,b){return b.querySelector(a)},O=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(N=function(a,b){return Sizzle(a,b)[0]},O=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var P=Q([[document]]);P[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?P.select(a):Q([[a]])},d3.selectAll=function(b){return typeof b=="string"?P.selectAll(b):Q([a(b)])},d3.transition=P.transition;var U=0,V=0,Y=null,Z,$;d3.timer=function(a){_(a,0)};var bc=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function k(c){var d=Math.min(a,b),e=Math.max(a,b),f=e-d,g=Math.pow(10,Math.floor(Math.log(f/c)/Math.LN10)),h=c/(f/g);h<=.15?g*=10:h<=.35?g*=5:h<=.75&&(g*=2);return{start:Math.ceil(d/g)*g,stop:Math.floor(e/g)*g+g*.5,step:g}}function j(b){b=(b-a)*e;return h(i?Math.max(0,Math.min(1,b)):b)}var a=0,b=1,c=0,d=1,e=1,f=1,g=d3.interpolate,h=g(c,d),i=!1;j.invert=function(b){return(b-c)*f+a},j.domain=function(g){if(!arguments.length)return[a,b];a=+g[0],b=+g[1],e=1/(b-a),f=(b-a)/(d-c);return j},j.range=function(e){if(!arguments.length)return[c,d];c=e[0],d=e[1],f=(b-a)/(d-c),h=g(c,d);return j},j.rangeRound=function(a){return j.range(a).interpolate(d3.interpolateRound)},j.clamp=function(a){if(!arguments.length)return i;i=a;return j},j.interpolate=function(a){if(!arguments.length)return g;h=(g=a)(c,d);return j},j.ticks=function(a){var b=k(a);return d3.range(b.start,b.stop,b.step)},j.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(k(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return j},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bd,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?be:bd,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===be){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bd.pow=function(a){return Math.pow(10,a)},be.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bg:bf;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bh)},d3.scale.category20=function(){return d3.scale.ordinal().range(bi)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bj)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bk)};var bh=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bi=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bj=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bk=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bl,h=d.apply(this,arguments)+bl,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bm?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bn,b=bo,c=bp,d=bq;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bl;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bl=-Math.PI/2,bm=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(br(this,c,a,b),e)}var a=bs,b=bt,c="linear",d=bu[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=bu[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var bu={linear:bv,"step-before":bw,"step-after":bx,basis:bC,"basis-closed":bD,cardinal:bz,"cardinal-closed"
<ide> :by},bF=[0,2/3,1/3,0],bG=[0,1/3,2/3,0],bH=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(br(this,d,a,c),f)+"L"+e(br(this,d,a,b).reverse(),f)+"Z"}var a=bs,b=bJ,c=bt,d="linear",e=bu[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=bu[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bl,k=e.call(a,h,g)+bl;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=bK,b=bL,c=bM,d=bp,e=bq;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=bK,b=bL,c=bP;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.mouse=function(a){var b=(a.ownerSVGElement||a).createSVGPoint();if(bQ<0&&(window.scrollX||window.scrollY)){var c=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),d=c[0][0].getScreenCTM();bQ=!d.f&&!d.e,c.remove()}bQ?(b.x=d3.event.pageX,b.y=d3.event.pageY):(b.x=d3.event.clientX,b.y=d3.event.clientY),b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var bQ=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function c(c,d){return(bT[a.call(this,c,d)]||bT.circle)(b.call(this,c,d))}var a=bS,b=bR;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var bT={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*bV)),c=b*bV;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/bU),c=b*bU/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/bU),c=b*bU/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},bU=Math.sqrt(3),bV=Math.tan(30*Math.PI/180)})()
<ide>\ No newline at end of file
<ide><path>src/core/core.js
<del>d3 = {version: "1.11.1"}; // semver
<add>d3 = {version: "1.12.0"}; // semver | 3 |
Python | Python | add license='bsd' to setup.py | 5d5d23eef072ab0832b7fa26e3a665c63d614739 | <ide><path>setup.py
<ide> def run(self):
<ide> author_email=celery.__contact__,
<ide> url=celery.__homepage__,
<ide> platforms=["any"],
<add> license="BSD",
<ide> packages=find_packages(exclude=['ez_setup']),
<ide> scripts=["bin/celeryd", "bin/celeryinit"],
<ide> zip_safe=False, | 1 |
Javascript | Javascript | reuse pythonexecutable variable | b7bd11a8839a82879cdc9e029aca26061e8434c1 | <ide><path>script/utils/verify-requirements.js
<ide> var path = require('path');
<ide> var fs = require('fs');
<ide> var cp = require('child_process');
<ide> var execFile = cp.execFile;
<del>var pythonPath = process.env.PYTHON;
<add>var pythonExecutable = process.env.PYTHON;
<ide>
<ide> module.exports = function(cb) {
<ide> verifyNode();
<ide> function verifyPython27(cb) {
<ide> cb();
<ide> }
<ide> else {
<del> var pythonExecutable;
<del> if (!pythonPath) {
<add> if (!pythonExecutable) {
<ide> var systemDrive = process.env.SystemDrive || 'C:\\';
<del> pythonPath = path.join(systemDrive, 'Python27');
<add> pythonExecutable = path.join(systemDrive, 'Python27');
<ide>
<del> if (fs.existsSync(pythonPath)) {
<del> pythonExecutable = path.join(pythonPath, 'python');
<add> if (fs.existsSync(pythonExecutable)) {
<add> pythonExecutable = path.join(pythonExecutable, 'python');
<ide> }
<ide> else {
<ide> pythonExecutable = 'python';
<ide> }
<ide> }
<del> else {
<del> pythonExecutable = pythonPath;
<del> }
<ide>
<ide> checkPythonVersion(pythonExecutable, cb);
<ide> } | 1 |
Go | Go | stop controllers at end of test | a0f9caec99e343e219c47161190a99f561a85632 | <ide><path>libnetwork/sandbox_test.go
<ide> func getTestEnv(t *testing.T, opts ...[]NetworkOption) (NetworkController, []Net
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> t.Cleanup(c.Stop)
<ide>
<ide> if len(opts) == 0 {
<ide> return c, nil
<ide><path>libnetwork/store_linux_test.go
<ide> func TestNoPersist(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatalf("Error new controller: %v", err)
<ide> }
<add> defer ctrl.Stop()
<ide> nw, err := ctrl.NewNetwork("host", "host", "", NetworkOptionPersist(false))
<ide> if err != nil {
<ide> t.Fatalf("Error creating default \"host\" network: %v", err)
<ide><path>libnetwork/store_test.go
<ide> func testLocalBackend(t *testing.T, provider, url string, storeConfig *store.Con
<ide> if err != nil {
<ide> t.Fatalf("Error new controller: %v", err)
<ide> }
<add> defer ctrl.Stop()
<ide> nw, err := ctrl.NewNetwork("host", "host", "")
<ide> if err != nil {
<ide> t.Fatalf("Error creating default \"host\" network: %v", err)
<ide> func testLocalBackend(t *testing.T, provider, url string, storeConfig *store.Con
<ide> if err != nil {
<ide> t.Fatalf("Error creating controller: %v", err)
<ide> }
<add> defer ctrl.Stop()
<ide> if _, err = ctrl.NetworkByID(nw.ID()); err != nil {
<ide> t.Fatalf("Error getting network %v", err)
<ide> }
<ide> func TestMultipleControllersWithSameStore(t *testing.T) {
<ide> }
<ide> defer ctrl1.Stop()
<ide> // Use the same boltdb file without closing the previous controller
<del> _, err = New(cfgOptions...)
<add> ctrl2, err := New(cfgOptions...)
<ide> if err != nil {
<ide> t.Fatalf("Local store must support concurrent controllers")
<ide> }
<add> ctrl2.Stop()
<ide> } | 3 |
Ruby | Ruby | convert javarequirement test to spec | 9c1db3c820f715f62f550ba1e54f16f9b89bc6ed | <ide><path>Library/Homebrew/test/os/mac/java_requirement_spec.rb
<add>require "requirements/java_requirement"
<add>require "fileutils"
<add>
<add>describe JavaRequirement do
<add> subject { described_class.new(%w[1.8]) }
<add> let(:java_home) { Dir.mktmpdir }
<add> let(:java_home_path) { Pathname.new(java_home) }
<add>
<add> before(:each) do
<add> FileUtils.mkdir java_home_path/"bin"
<add> FileUtils.touch java_home_path/"bin/java"
<add> allow(subject).to receive(:preferred_java).and_return(java_home_path/"bin/java")
<add> expect(subject).to be_satisfied
<add> end
<add>
<add> after(:each) { java_home_path.rmtree }
<add>
<add> specify "Apple Java environment" do
<add> expect(ENV).to receive(:prepend_path)
<add> expect(ENV).to receive(:append_to_cflags)
<add>
<add> subject.modify_build_environment
<add> expect(ENV["JAVA_HOME"]).to eq(java_home)
<add> end
<add>
<add> specify "Oracle Java environment" do
<add> FileUtils.mkdir java_home_path/"include"
<add> expect(ENV).to receive(:prepend_path)
<add> expect(ENV).to receive(:append_to_cflags).twice
<add>
<add> subject.modify_build_environment
<add> expect(ENV["JAVA_HOME"]).to eq(java_home)
<add> end
<add>end
<ide><path>Library/Homebrew/test/os/mac/java_requirement_test.rb
<del>require "testing_env"
<del>require "requirements/java_requirement"
<del>require "fileutils"
<del>
<del>class OSMacJavaRequirementTests < Homebrew::TestCase
<del> def setup
<del> super
<del> @java_req = JavaRequirement.new(%w[1.8])
<del> @tmp_java_home = mktmpdir
<del> @tmp_pathname = Pathname.new(@tmp_java_home)
<del> FileUtils.mkdir @tmp_pathname/"bin"
<del> FileUtils.touch @tmp_pathname/"bin/java"
<del> @java_req.stubs(:preferred_java).returns(@tmp_pathname/"bin/java")
<del> @java_req.satisfied?
<del> end
<del>
<del> def test_java_env_apple
<del> ENV.expects(:prepend_path)
<del> ENV.expects(:append_to_cflags)
<del> @java_req.modify_build_environment
<del> assert_equal ENV["JAVA_HOME"], @tmp_java_home
<del> end
<del>
<del> def test_java_env_oracle
<del> FileUtils.mkdir @tmp_pathname/"include"
<del> ENV.expects(:prepend_path)
<del> ENV.expects(:append_to_cflags).twice
<del> @java_req.modify_build_environment
<del> assert_equal ENV["JAVA_HOME"], @tmp_java_home
<del> end
<del>end | 2 |
Javascript | Javascript | add contexttag field to fiber type | f1df675b9343163f56aa22e705c3d82b7d026948 | <ide><path>src/renderers/shared/fiber/ReactFiber.js
<ide> import type {ReactFragment} from 'ReactTypes';
<ide> import type {ReactCoroutine, ReactYield} from 'ReactCoroutine';
<ide> import type {ReactPortal} from 'ReactPortal';
<ide> import type {TypeOfWork} from 'ReactTypeOfWork';
<add>import type {TypeOfContext} from 'ReactTypeOfContext';
<ide> import type {TypeOfSideEffect} from 'ReactTypeOfSideEffect';
<ide> import type {PriorityLevel} from 'ReactPriorityLevel';
<ide> import type {UpdateQueue} from 'ReactFiberUpdateQueue';
<ide>
<del>var ReactTypeOfWork = require('ReactTypeOfWork');
<ide> var {
<ide> IndeterminateComponent,
<ide> ClassComponent,
<ide> var {
<ide> CoroutineComponent,
<ide> YieldComponent,
<ide> Fragment,
<del>} = ReactTypeOfWork;
<add>} = require('ReactTypeOfWork');
<ide>
<ide> var {NoWork} = require('ReactPriorityLevel');
<ide>
<del>var {NoEffect} = require('ReactTypeOfSideEffect');
<add>var {
<add> NoContext,
<add>} = require('ReactTypeOfContext');
<add>
<add>var {
<add> NoEffect,
<add>} = require('ReactTypeOfSideEffect');
<ide>
<ide> var {cloneUpdateQueue} = require('ReactFiberUpdateQueue');
<ide>
<ide> export type Fiber = {
<ide> // The state used to create the output
<ide> memoizedState: any,
<ide>
<add> // Bitmask that describes properties about the fiber and its subtree. E.g. the
<add> // AsyncUpdates flag indicates whether the subtree should be async-by-default.
<add> // When a fiber is created, it inherits the contextTag of its parent.
<add> // Additional flags can be set at creation time, but after than
<add> // the value should remain unchanged throughout the fiber's lifetime,
<add> // particularly before its child fibers are created.
<add> contextTag: TypeOfContext,
<add>
<ide> // Effect
<ide> effectTag: TypeOfSideEffect,
<ide>
<ide> var createFiber = function(tag: TypeOfWork, key: null | string): Fiber {
<ide> updateQueue: null,
<ide> memoizedState: null,
<ide>
<add> contextTag: NoContext,
<add>
<ide> effectTag: NoEffect,
<ide> nextEffect: null,
<ide> firstEffect: null,
<ide> exports.cloneFiber = function(
<ide> alt.memoizedProps = fiber.memoizedProps;
<ide> alt.memoizedState = fiber.memoizedState;
<ide>
<add> alt.contextTag = fiber.contextTag;
<add>
<ide> if (__DEV__) {
<ide> alt._debugID = fiber._debugID;
<ide> alt._debugSource = fiber._debugSource;
<ide><path>src/renderers/shared/fiber/isomorphic/ReactTypeOfContext.js
<add>/**
<add> * Copyright 2013-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactTypeOfContext
<add> * @flow
<add> */
<add>
<add>'use strict';
<add>
<add>export type TypeOfContext = 0 | 1;
<add>
<add>module.exports = {
<add> NoContext: 0,
<add> AsyncUpdates: 1,
<add>}; | 2 |
Ruby | Ruby | fix broken list formatting [ci skip] | f5d79d765043e4fabfae977fa8884162839fc01c | <ide><path>actionview/lib/action_view/helpers/rendering_helper.rb
<ide> module RenderingHelper
<ide> # * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
<ide> # * <tt>:text</tt> - Renders the text passed in out.
<ide> # * <tt>:plain</tt> - Renders the text passed in out. Setting the content
<del> # type as <tt>text/plain</tt>.
<add> # type as <tt>text/plain</tt>.
<ide> # * <tt>:html</tt> - Renders the html safe string passed in out, otherwise
<del> # performs html escape on the string first. Setting the content type as
<del> # <tt>text/html</tt>.
<add> # performs html escape on the string first. Setting the content type as
<add> # <tt>text/html</tt>.
<ide> # * <tt>:body</tt> - Renders the text passed in, and inherits the content
<del> # type of <tt>text/html</tt> from <tt>ActionDispatch::Response</tt>
<del> # object.
<add> # type of <tt>text/html</tt> from <tt>ActionDispatch::Response</tt>
<add> # object.
<ide> #
<ide> # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
<ide> # as the locals hash. | 1 |
Ruby | Ruby | fix deprecation warning on actionpack request test | eab5a3877e4c23b3988ad4dec7c8d0ff8645adf7 | <ide><path>actionpack/test/dispatch/request_test.rb
<ide> def url_for(options = {})
<ide> private
<ide> def stub_request(env = {})
<ide> ip_spoofing_check = env.key?(:ip_spoofing_check) ? env.delete(:ip_spoofing_check) : true
<del> @trusted_proxies ||= nil
<del> ip_app = ActionDispatch::RemoteIp.new(Proc.new { }, ip_spoofing_check, @trusted_proxies)
<add> @additional_trusted_proxy ||= nil
<add> trusted_proxies = ActionDispatch::RemoteIp::TRUSTED_PROXIES + [@additional_trusted_proxy]
<add> ip_app = ActionDispatch::RemoteIp.new(Proc.new { }, ip_spoofing_check, trusted_proxies)
<ide> ActionDispatch::Http::URL.tld_length = env.delete(:tld_length) if env.key?(:tld_length)
<ide>
<ide> ip_app.call(env)
<ide> class RequestIP < BaseRequestTest
<ide> end
<ide>
<ide> test "remote ip with user specified trusted proxies String" do
<del> @trusted_proxies = "67.205.106.73"
<add> @additional_trusted_proxy = "67.205.106.73"
<ide>
<ide> request = stub_request "REMOTE_ADDR" => "3.4.5.6",
<ide> "HTTP_X_FORWARDED_FOR" => "67.205.106.73"
<ide> class RequestIP < BaseRequestTest
<ide> end
<ide>
<ide> test "remote ip v6 with user specified trusted proxies String" do
<del> @trusted_proxies = "fe80:0000:0000:0000:0202:b3ff:fe1e:8329"
<add> @additional_trusted_proxy = "fe80:0000:0000:0000:0202:b3ff:fe1e:8329"
<ide>
<ide> request = stub_request "REMOTE_ADDR" => "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
<ide> "HTTP_X_FORWARDED_FOR" => "fe80:0000:0000:0000:0202:b3ff:fe1e:8329"
<ide> class RequestIP < BaseRequestTest
<ide> end
<ide>
<ide> test "remote ip with user specified trusted proxies Regexp" do
<del> @trusted_proxies = /^67\.205\.106\.73$/i
<add> @additional_trusted_proxy = /^67\.205\.106\.73$/i
<ide>
<ide> request = stub_request "REMOTE_ADDR" => "67.205.106.73",
<ide> "HTTP_X_FORWARDED_FOR" => "3.4.5.6"
<ide> class RequestIP < BaseRequestTest
<ide> end
<ide>
<ide> test "remote ip v6 with user specified trusted proxies Regexp" do
<del> @trusted_proxies = /^fe80:0000:0000:0000:0202:b3ff:fe1e:8329$/i
<add> @additional_trusted_proxy = /^fe80:0000:0000:0000:0202:b3ff:fe1e:8329$/i
<ide>
<ide> request = stub_request "REMOTE_ADDR" => "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
<ide> "HTTP_X_FORWARDED_FOR" => "fe80:0000:0000:0000:0202:b3ff:fe1e:8329" | 1 |
Javascript | Javascript | fix typo in test-child-process-stdout-flush | 8cdbf014bd40c679970f6a73173a80d15e5f2275 | <ide><path>test/simple/test-child-process-stdout-flush.js
<ide> child.stderr.on('data', function(data) {
<ide> assert.ok(false);
<ide> });
<ide>
<del>child.stderr.setEncoding('utf8');
<add>child.stdout.setEncoding('utf8');
<ide> child.stdout.on('data', function(data) {
<ide> count += data.length;
<ide> console.log(count); | 1 |
Ruby | Ruby | fix typo in isolated engine docs | 45b4ebc7df1b0e25a38862d61566d8b380cb3798 | <ide><path>railties/lib/rails/engine.rb
<ide> module Rails
<ide> #
<ide> # Additionally, an isolated engine will set its name according to namespace, so
<ide> # MyEngine::Engine.engine_name will be "my_engine". It will also set MyEngine.table_name_prefix
<del> # to "my_engine_", changing the MyEngine::Article model to use the my_engine_article table.
<add> # to "my_engine_", changing the MyEngine::Article model to use the my_engine_articles table.
<ide> #
<ide> # == Using Engine's routes outside Engine
<ide> # | 1 |
Text | Text | add note regarding non-existant fonts | 7a02d93db4025387adfbc91fb2bc5e250f0a0672 | <ide><path>docs/general/fonts.md
<ide> let chart = new Chart(ctx, {
<ide> | `defaultFontFamily` | `String` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Default font family for all text.
<ide> | `defaultFontSize` | `Number` | `12` | Default font size (in px) for text. Does not apply to radialLinear scale point labels.
<ide> | `defaultFontStyle` | `String` | `'normal'` | Default font style. Does not apply to tooltip title or footer. Does not apply to chart title.
<add>
<add>## Non-Existant Fonts
<add>
<add>If a font is specified for a chart that does exist on the system, the browser will not apply the font when it is set. If you notice odd fonts appearing in your charts, check that the font you are applying exists on your system. See [issue 3318](https://github.com/chartjs/Chart.js/issues/3318) for more details. | 1 |
Text | Text | update configuration docs | 8d193d542bf923489855b9d026eef0f2e82b2fee | <ide><path>docs/internals/configuration.md
<ide> ### Reading Config Settings
<ide>
<ide> If you are writing a package that you want to make configurable, you'll need to
<del>read config settings. You can read a value from `config` with `config.get`:
<add>read config settings via the `atom.config` global. You can read the current
<add>value of a namespaced config key with `atom.config.get`:
<ide>
<ide> ```coffeescript
<ide> # read a value with `config.get`
<ide> @showInvisibles() if config.get "edtior.showInvisibles"
<ide> ```
<ide>
<del>Or you can use `observeConfig` to track changes from a view object.
<add>Or you can use the `::observeConfig` to track changes from any view object.
<ide>
<ide> ```coffeescript
<ide> class MyView extends View
<ide> class MyView extends View
<ide> @adjustFontSize()
<ide> ```
<ide>
<del>The `observeConfig` method will call the given callback immediately with the
<add>The `::observeConfig` method will call the given callback immediately with the
<ide> current value for the specified key path, and it will also call it in the future
<ide> whenever the value of that key path changes.
<ide>
<ide> You can add the ability to observe config values to non-view classes by
<ide> extending their prototype with the `ConfigObserver` mixin:
<ide>
<ide> ```coffeescript
<del>ConfigObserver = require 'config-observer'
<del>_.extend MyClass.prototype, ConfigObserver
<add>{ConfigObserver} = require 'atom'
<add>
<add>class MyClass
<add> ConfigObserver.includeInto(this)
<add>
<add> constructor: ->
<add> @observeConfig 'editor.showInvisibles', -> # ...
<add>
<add> destroy: ->
<add> @unobserveConfig()
<ide> ```
<ide>
<ide> ### Writing Config Settings
<ide>
<del>As discussed above, the config database is automatically populated from
<del>`config.cson` when Atom is started, but you can programmatically write to it in
<del>the following way:
<add>The `atom.config` database is populated on startup from `~/.atom/config.cson`,
<add>but you can programmatically write to it with `atom.config.set`:
<ide>
<ide> ```coffeescript
<ide> # basic key update
<del>config.set("core.showInvisibles", true)
<add>atom.config.set("core.showInvisibles", true)
<add>```
<ide>
<del>config.pushAtKeyPath("core.disabledPackages", "wrap-guide")
<add>You should never mutate the value of a config key, because that would circumvent
<add>the notification of observers. You can however use methods like `pushAtKeyPath`,
<add>`unshiftAtKeyPath`, and `removeAtKeyPath` to manipulate mutable config values.
<add>
<add>```coffeescript
<add>atom.config.pushAtKeyPath("core.disabledPackages", "wrap-guide")
<add>atom.config.removeAtKeyPath("core.disabledPackages", "terminal")
<ide> ```
<ide>
<ide> You can also use `setDefaults`, which will assign default values for keys that
<del>are always overridden by values assigned with `set`. Defaults are not written out
<del>to the the `config.json` file to prevent it from becoming cluttered.
<add>are always overridden by values assigned with `set`. Defaults are not written
<add>out to the the `config.json` file to prevent it from becoming cluttered.
<ide>
<ide> ```coffeescript
<ide> config.setDefaults("editor", fontSize: 18, showInvisibles: true) | 1 |
Text | Text | correct code indent | 76db7d4c590957c7e81ce521a1ab5bfb6760afaf | <ide><path>docs/tutorial/1-serialization.md
<ide> For the purposes of this tutorial we're going to start by creating a simple `Sni
<ide> default='python',
<ide> max_length=100)
<ide> style = models.CharField(choices=STYLE_CHOICES,
<del> default='friendly',
<del> max_length=100)
<add> default='friendly',
<add> max_length=100)
<ide>
<ide> class Meta:
<ide> ordering = ('created',) | 1 |
Text | Text | add references to outside c++ guides | 0f8eaa4712c575951a703f175daaf0a4e66198a0 | <ide><path>CPP_STYLE_GUIDE.md
<ide>
<ide> ## Table of Contents
<ide>
<add>* [Guides and References](#guides-and-references)
<ide> * [Formatting](#formatting)
<ide> * [Left-leaning (C++ style) asterisks for pointer declarations](#left-leaning-c-style-asterisks-for-pointer-declarations)
<ide> * [C++ style comments](#c-style-comments)
<ide> * [Avoid throwing JavaScript errors in C++ methods](#avoid-throwing-javascript-errors-in-c)
<ide> * [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods)
<ide>
<del>Unfortunately, the C++ linter (based on
<del>[Google’s `cpplint`](https://github.com/google/styleguide)), which can be run
<del>explicitly via `make lint-cpp`, does not currently catch a lot of rules that are
<del>specific to the Node.js C++ code base. This document explains the most common of
<del>these rules:
<add>
<add>## Guides and References
<add>
<add>The Node.js C++ codebase strives to be consistent in its use of language
<add>features and idioms, as well as have some specific guidelines for the use of
<add>runtime features.
<add>
<add>Coding guidelines are based on the following guides (highest priority first):
<add>1. This document
<add>2. The [Google C++ Style Guide][]
<add>3. The ISO [C++ Core Guidelines][]
<add>
<add>In general code should follow the C++ Core Guidelines, unless overridden by the
<add>Google C++ Style Guide or this document. At the moment these guidelines are
<add>checked manually by reviewers, with the goal to validate this with automatic
<add>tools.
<ide>
<ide> ## Formatting
<ide>
<add>Unfortunately, the C++ linter (based on [Google’s `cpplint`][]), which can be
<add>run explicitly via `make lint-cpp`, does not currently catch a lot of rules that
<add>are specific to the Node.js C++ code base. This document explains the most
<add>common of these rules:
<add>
<ide> ### Left-leaning (C++ style) asterisks for pointer declarations
<ide>
<ide> `char* buffer;` instead of `char *buffer;`
<ide> not inside of nested calls.
<ide>
<ide> Using C++ `throw` is not allowed.
<ide>
<add>
<add>[C++ Core Guidelines]: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
<add>[Google C++ Style Guide]: https://google.github.io/styleguide/cppguide.html
<add>[Google’s `cpplint`]: https://github.com/google/styleguide
<ide> [errors]: https://github.com/nodejs/node/blob/master/doc/guides/using-internal-errors.md | 1 |
Text | Text | fix comments about the black formatter | 8f2c9932e09948a046f8d11b18f7c634ee4161fe | <ide><path>CONTRIBUTING.md
<ide> We want your work to be readable by others; therefore, we encourage you to note
<ide> - Expand acronyms because __gcd()__ is hard to understand but __greatest_common_divisor()__ is not.
<ide> - Please follow the [Python Naming Conventions](https://pep8.org/#prescriptive-naming-conventions) so variable_names and function_names should be lower_case, CONSTANTS in UPPERCASE, ClassNames should be CamelCase, etc.
<ide>
<del>
<del>
<ide> - We encourage the use of Python [f-strings](https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python) where the make the code easier to read.
<ide>
<del>
<del>
<del>- Please consider running [__psf/black__](https://github.com/python/black) on your Python file(s) before submitting your pull request. This is not yet a requirement but it does make your code more readable and automatically aligns it with much of [PEP 8](https://www.python.org/dev/peps/pep-0008/). There are other code formatters (autopep8, yapf) but the __black__ style is now the recommendation of the Python Core Team. To use it,
<add>- Please consider running [__psf/black__](https://github.com/python/black) on your Python file(s) before submitting your pull request. This is not yet a requirement but it does make your code more readable and automatically aligns it with much of [PEP 8](https://www.python.org/dev/peps/pep-0008/). There are other code formatters (autopep8, yapf) but the __black__ formatter is now hosted by the Python Software Foundation. To use it,
<ide>
<ide> ```bash
<ide> pip3 install black # only required the first time
<ide> We want your work to be readable by others; therefore, we encourage you to note
<ide> flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
<ide> ```
<ide>
<del>
<del>
<ide> - Original code submission require docstrings or comments to describe your work.
<ide>
<ide> - More on docstrings and comments:
<ide>
<del> If you are using a Wikipedia article or some other source material to create your algorithm, please add the URL in a docstring or comment to help your reader.
<add> If you used a Wikipedia article or some other source material to create your algorithm, please add the URL in a docstring or comment to help your reader.
<ide>
<ide> The following are considered to be bad and may be requested to be improved:
<ide>
<ide> We want your work to be readable by others; therefore, we encourage you to note
<ide>
<ide> This is too trivial. Comments are expected to be explanatory. For comments, you can write them above, on or below a line of code, as long as you are consistent within the same piece of code.
<ide>
<del> We encourage you to put docstrings inside your functions but please pay attention to indentation of docstrings. The following is acceptable in this case:
<add> We encourage you to put docstrings inside your functions but please pay attention to indentation of docstrings. The following is a good example:
<ide>
<ide> ```python
<del> def sumab(a, b):
<add> def sum_ab(a, b):
<ide> """
<del> This function returns the sum of two integers a and b
<del> Return: a + b
<add> Return the sum of two integers a and b.
<ide> """
<ide> return a + b
<ide> ```
<ide>
<ide> - Write tests (especially [__doctests__](https://docs.python.org/3/library/doctest.html)) to illustrate and verify your work. We highly encourage the use of _doctests on all functions_.
<ide>
<ide> ```python
<del> def sumab(a, b):
<add> def sum_ab(a, b):
<ide> """
<del> This function returns the sum of two integers a and b
<del> Return: a + b
<del> >>> sumab(2, 2)
<add> Returns the sum of two integers a and b
<add> >>> sum_ab(2, 2)
<ide> 4
<del> >>> sumab(-2, 3)
<add> >>> sum_ab(-2, 3)
<ide> 1
<del> >>> sumab(4.9, 5.1)
<add> >>> sum_ab(4.9, 5.1)
<ide> 10.0
<ide> """
<ide> return a + b
<ide> We want your work to be readable by others; therefore, we encourage you to note
<ide>
<ide> ```python
<ide> def sumab(a: int, b: int) --> int:
<del> pass
<add> pass
<ide> ```
<ide>
<del>
<del>
<ide> - [__List comprehensions and generators__](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) are preferred over the use of `lambda`, `map`, `filter`, `reduce` but the important thing is to demonstrate the power of Python in code that is easy to read and maintain.
<ide>
<del>
<del>
<ide> - Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms.
<ide> - If you need a third party module that is not in the file __requirements.txt__, please add it to that file as part of your submission.
<ide>
<ide> We want your work to be readable by others; therefore, we encourage you to note
<ide> - Strictly use snake_case (underscore_separated) in your file_name, as it will be easy to parse in future using scripts.
<ide> - Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure.
<ide> - If possible, follow the standard *within* the folder you are submitting to.
<del>
<del>
<del>
<ide> - If you have modified/added code work, make sure the code compiles before submitting.
<ide> - If you have modified/added documentation work, ensure your language is concise and contains no grammar errors.
<ide> - Do not update the README.md or DIRECTORY.md file which will be periodically autogenerated by our Travis CI processes.
<ide> - Add a corresponding explanation to [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation) (Optional but recommended).
<ide> - All submissions will be tested with [__mypy__](http://www.mypy-lang.org) so we encourage to add [__Python type hints__](https://docs.python.org/3/library/typing.html) where it makes sense to do so.
<ide>
<del>
<del>
<ide> - Most importantly,
<ide> - **Be consistent in the use of these guidelines when submitting.**
<ide> - **Join** [Gitter](https://gitter.im/TheAlgorithms) **now!** | 1 |
Java | Java | update the jetty websocket adapter | 164a9f938ccef29923476a4cf50565d4fa54d528 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/MessageHandlingException.java
<ide> */
<ide> public class MessageHandlingException extends MessagingException {
<ide>
<add> private static final long serialVersionUID = 690969923668400297L;
<add>
<ide>
<ide> public MessageHandlingException(Message<?> message, String description, Throwable cause) {
<ide> super(message, description, cause);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/BrokerAvailabilityEvent.java
<ide> */
<ide> public class BrokerAvailabilityEvent extends ApplicationEvent {
<ide>
<add> private static final long serialVersionUID = -8156742505179181002L;
<add>
<ide> private final boolean brokerAvailable;
<ide>
<add>
<ide> /**
<ide> * Creates a new {@code BrokerAvailabilityEvent}.
<ide> *
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/AbstractWebSocketMessage.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.socket;
<add>
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ObjectUtils;
<add>
<add>/**
<add> * A message that can be handled or sent on a WebSocket connection.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 4.0
<add> */
<add>public abstract class AbstractWebSocketMessage<T> implements WebSocketMessage<T> {
<add>
<add> private final T payload;
<add>
<add> private final boolean last;
<add>
<add>
<add> /**
<add> * Create a new WebSocket message with the given payload.
<add> *
<add> * @param payload the non-null payload
<add> */
<add> AbstractWebSocketMessage(T payload) {
<add> this(payload, true);
<add> }
<add>
<add> /**
<add> * Create a new WebSocket message given payload representing the full or partial
<add> * message content. When the {@code isLast} boolean flag is set to {@code false}
<add> * the message is sent as partial content and more partial messages will be
<add> * expected until the boolean flag is set to {@code true}.
<add> *
<add> * @param payload the non-null payload
<add> * @param isLast if the message is the last of a series of partial messages
<add> */
<add> AbstractWebSocketMessage(T payload, boolean isLast) {
<add> Assert.notNull(payload, "payload is required");
<add> this.payload = payload;
<add> this.last = isLast;
<add> }
<add>
<add>
<add> /**
<add> * Return the message payload, never be {@code null}.
<add> */
<add> public T getPayload() {
<add> return this.payload;
<add> }
<add>
<add> /**
<add> * Whether this is the last part of a message sent as a series of partial messages.
<add> */
<add> public boolean isLast() {
<add> return this.last;
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> return AbstractWebSocketMessage.class.hashCode() * 13 + ObjectUtils.nullSafeHashCode(this.payload);
<add> }
<add>
<add> @Override
<add> public boolean equals(Object other) {
<add> if (this == other) {
<add> return true;
<add> }
<add> if (!(other instanceof AbstractWebSocketMessage)) {
<add> return false;
<add> }
<add> AbstractWebSocketMessage otherMessage = (AbstractWebSocketMessage) other;
<add> return ObjectUtils.nullSafeEquals(this.payload, otherMessage.payload);
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> return getClass().getSimpleName() + " payload= " + toStringPayload()
<add> + ", length=" + getPayloadSize() + ", last=" + isLast() + "]";
<add> }
<add>
<add> protected abstract String toStringPayload();
<add>
<add> protected abstract int getPayloadSize();
<add>
<add>}
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/BinaryMessage.java
<ide> import java.nio.ByteBuffer;
<ide>
<ide> /**
<del> * A {@link WebSocketMessage} that contains a binary {@link ByteBuffer} payload.
<add> * A binary WebSocket message.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public final class BinaryMessage extends WebSocketMessage<ByteBuffer> {
<del>
<del> private byte[] bytes;
<add>public final class BinaryMessage extends AbstractWebSocketMessage<ByteBuffer> {
<ide>
<ide>
<ide> /**
<del> * Create a new {@link BinaryMessage} instance.
<add> * Create a new binary WebSocket message with the given ByteBuffer payload.
<add> *
<ide> * @param payload the non-null payload
<ide> */
<ide> public BinaryMessage(ByteBuffer payload) {
<del> this(payload, true);
<add> super(payload, true);
<ide> }
<ide>
<ide> /**
<del> * Create a new {@link BinaryMessage} instance.
<add> * Create a new binary WebSocket message with the given payload representing the
<add> * full or partial message content. When the {@code isLast} boolean flag is set
<add> * to {@code false} the message is sent as partial content and more partial
<add> * messages will be expected until the boolean flag is set to {@code true}.
<add> *
<ide> * @param payload the non-null payload
<ide> * @param isLast if the message is the last of a series of partial messages
<ide> */
<ide> public BinaryMessage(ByteBuffer payload, boolean isLast) {
<ide> super(payload, isLast);
<del> this.bytes = null;
<ide> }
<ide>
<ide> /**
<del> * Create a new {@link BinaryMessage} instance.
<del> * @param payload the non-null payload
<add> * Create a new binary WebSocket message with the given byte[] payload.
<add> *
<add> * @param payload a non-null payload; note that this value is not copied so care
<add> * must be taken not to modify the array.
<ide> */
<ide> public BinaryMessage(byte[] payload) {
<del> this(payload, 0, (payload == null ? 0 : payload.length), true);
<add> this(payload, true);
<ide> }
<ide>
<ide> /**
<del> * Create a new {@link BinaryMessage} instance.
<del> * @param payload the non-null payload
<add> * Create a new binary WebSocket message with the given byte[] payload representing
<add> * the full or partial message content. When the {@code isLast} boolean flag is set
<add> * to {@code false} the message is sent as partial content and more partial
<add> * messages will be expected until the boolean flag is set to {@code true}.
<add> *
<add> * @param payload a non-null payload; note that this value is not copied so care
<add> * must be taken not to modify the array.
<ide> * @param isLast if the message is the last of a series of partial messages
<ide> */
<ide> public BinaryMessage(byte[] payload, boolean isLast) {
<del> this(payload, 0, (payload == null ? 0 : payload.length), isLast);
<add> this(payload, 0, ((payload == null) ? 0 : payload.length), isLast);
<ide> }
<ide>
<ide> /**
<del> * Create a new {@link BinaryMessage} instance by wrapping an existing byte array.
<del> * @param payload a non-null payload, NOTE: this value is not copied so care must be
<del> * taken not to modify the array.
<del> * @param offset the offet into the array where the payload starts
<del> * @param len the length of the array considered for the payload
<add> * Create a new binary WebSocket message by wrapping an existing byte array.
<add> *
<add> * @param payload a non-null payload; note that this value is not copied so care
<add> * must be taken not to modify the array.
<add> * @param offset the offset into the array where the payload starts
<add> * @param length the length of the array considered for the payload
<ide> * @param isLast if the message is the last of a series of partial messages
<ide> */
<del> public BinaryMessage(byte[] payload, int offset, int len, boolean isLast) {
<del> super(payload != null ? ByteBuffer.wrap(payload, offset, len) : null, isLast);
<del> if(offset == 0 && len == payload.length) {
<del> this.bytes = payload;
<del> }
<add> public BinaryMessage(byte[] payload, int offset, int length, boolean isLast) {
<add> super((payload != null) ? ByteBuffer.wrap(payload, offset, length) : null, isLast);
<ide> }
<ide>
<ide>
<del> /**
<del> * Returns access to the message payload as a byte array. NOTE: the returned array
<del> * should be considered read-only and should not be modified.
<del> */
<del> public byte[] getByteArray() {
<del> if(this.bytes == null && getPayload() != null) {
<del> this.bytes = getRemainingBytes(getPayload());
<del> }
<del> return this.bytes;
<del> }
<del>
<del> private byte[] getRemainingBytes(ByteBuffer payload) {
<del> byte[] result = new byte[getPayload().remaining()];
<del> getPayload().get(result);
<del> return result;
<del> }
<del>
<ide> @Override
<ide> protected int getPayloadSize() {
<del> return (getPayload() != null) ? getPayload().remaining() : 0;
<add> return getPayload().remaining();
<ide> }
<ide>
<ide> @Override
<ide> protected String toStringPayload() {
<del> return (getPayload() != null) ? getPayload().toString() : null;
<add> return getPayload().toString();
<ide> }
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/PingMessage.java
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public final class PingMessage extends WebSocketMessage<ByteBuffer> {
<add>public final class PingMessage extends AbstractWebSocketMessage<ByteBuffer> {
<ide>
<ide>
<add> /**
<add> * Create a new ping message with an empty payload.
<add> */
<add> public PingMessage() {
<add> super(ByteBuffer.allocate(0));
<add> }
<add>
<add> /**
<add> * Create a new ping message with the given ByteBuffer payload.
<add> *
<add> * @param payload the non-null payload
<add> */
<ide> public PingMessage(ByteBuffer payload) {
<ide> super(payload);
<ide> }
<ide>
<add>
<ide> @Override
<ide> protected int getPayloadSize() {
<del> return (getPayload() != null) ? getPayload().remaining() : 0;
<add> return getPayload().remaining();
<ide> }
<ide>
<ide> @Override
<ide> protected String toStringPayload() {
<del> return (getPayload() != null) ? getPayload().toString() : null;
<add> return getPayload().toString();
<ide> }
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/PongMessage.java
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public final class PongMessage extends WebSocketMessage<ByteBuffer> {
<add>public final class PongMessage extends AbstractWebSocketMessage<ByteBuffer> {
<ide>
<ide>
<add> /**
<add> * Create a new pong message with an empty payload.
<add> */
<add> public PongMessage() {
<add> super(ByteBuffer.allocate(0));
<add> }
<add>
<add> /**
<add> * Create a new pong message with the given ByteBuffer payload.
<add> *
<add> * @param payload the non-null payload
<add> */
<ide> public PongMessage(ByteBuffer payload) {
<ide> super(payload);
<ide> }
<ide>
<add>
<ide> @Override
<ide> protected int getPayloadSize() {
<ide> return (getPayload() != null) ? getPayload().remaining() : 0;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/ReaderTextMessage.java
<del>/*
<del> * Copyright 2002-2013 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.web.socket;
<del>
<del>/**
<del> * A {@link WebSocketMessage} that contains a textual {@link String} payload.
<del> *
<del> * @author Rossen Stoyanchev
<del> * @since 4.0
<del> */
<del>public final class ReaderTextMessage extends WebSocketMessage<String> {
<del>
<del> /**
<del> * Create a new {@link ReaderTextMessage} instance.
<del> * @param payload the non-null payload
<del> */
<del> public ReaderTextMessage(CharSequence payload) {
<del> super(payload.toString(), true);
<del> }
<del>
<del> /**
<del> * Create a new {@link ReaderTextMessage} instance.
<del> * @param payload the non-null payload
<del> * @param isLast whether this the last part of a message received or transmitted in parts
<del> */
<del> public ReaderTextMessage(CharSequence payload, boolean isLast) {
<del> super(payload.toString(), isLast);
<del> }
<del>
<del>
<del> @Override
<del> protected int getPayloadSize() {
<del> return getPayload().length();
<del> }
<del>
<del> @Override
<del> protected String toStringPayload() {
<del> return (getPayloadSize() > 10) ? getPayload().substring(0, 10) + ".." : getPayload();
<del> }
<del>
<del>}
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/TextMessage.java
<ide> package org.springframework.web.socket;
<ide>
<ide> /**
<del> * A {@link WebSocketMessage} that contains a textual {@link String} payload.
<add> * A text WebSocket message.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public final class TextMessage extends WebSocketMessage<String> {
<add>public final class TextMessage extends AbstractWebSocketMessage<String> {
<add>
<ide>
<ide> /**
<del> * Create a new {@link TextMessage} instance.
<add> * Create a new text WebSocket message from the given CharSequence payload.
<add> *
<ide> * @param payload the non-null payload
<ide> */
<ide> public TextMessage(CharSequence payload) {
<ide> super(payload.toString(), true);
<ide> }
<ide>
<ide> /**
<del> * Create a new {@link TextMessage} instance.
<add> * Create a new text WebSocket message with the given payload representing the
<add> * full or partial message content. When the {@code isLast} boolean flag is set
<add> * to {@code false} the message is sent as partial content and more partial
<add> * messages will be expected until the boolean flag is set to {@code true}.
<add> *
<ide> * @param payload the non-null payload
<del> * @param isLast whether this the last part of a message received or transmitted in parts
<add> * @param isLast whether this the last part of a series of partial messages
<ide> */
<ide> public TextMessage(CharSequence payload, boolean isLast) {
<ide> super(payload.toString(), isLast);
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketHandler.java
<ide>
<ide> /**
<ide> * A handler for WebSocket messages and lifecycle events.
<del> *
<del> * <p>Implementations of this interface are encouraged to handle exceptions locally where
<add> * <p>
<add> * Implementations of this interface are encouraged to handle exceptions locally where
<ide> * it makes sense or alternatively let the exception bubble up in which case by default
<ide> * the exception is logged and the session closed with
<ide> * {@link CloseStatus#SERVER_ERROR SERVER_ERROR(1011)}. The exception handling
<ide> public interface WebSocketHandler {
<ide> void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception;
<ide>
<ide> /**
<del> * Whether the WebSocketHandler handles messages in parts.
<add> * Whether the WebSocketHandler handles partial messages. If this flag is set to
<add> * {@code true} and the underlying WebSocket server supports partial messages,
<add> * then a large WebSocket message, or one of an unknown size may be split and
<add> * maybe received over multiple calls to
<add> * {@link #handleMessage(WebSocketSession, WebSocketMessage)}. The flag
<add> * {@link org.springframework.web.socket.WebSocketMessage#isLast()} indicates if
<add> * the message is partial and whether it is the last part.
<ide> */
<ide> boolean supportsPartialMessages();
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketMessage.java
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public abstract class WebSocketMessage<T> {
<del>
<del> private final T payload;
<del>
<del> private final boolean last;
<del>
<del>
<del> /**
<del> * Create a new {@link WebSocketMessage} instance with the given payload.
<del> */
<del> WebSocketMessage(T payload) {
<del> this(payload, true);
<del> }
<del>
<del> /**
<del> * Create a new {@link WebSocketMessage} instance with the given payload.
<del> * @param payload a non-null payload
<del> */
<del> WebSocketMessage(T payload, boolean isLast) {
<del> Assert.notNull(payload, "payload is required");
<del> this.payload = payload;
<del> this.last = isLast;
<del> }
<del>
<add>public interface WebSocketMessage<T> {
<ide>
<ide> /**
<ide> * Returns the message payload. This will never be {@code null}.
<ide> */
<del> public T getPayload() {
<del> return this.payload;
<del> }
<add> T getPayload();
<ide>
<ide> /**
<del> * Whether this is the last part of a message, when partial message support on a
<del> * {@link WebSocketHandler} is enabled. If partial message support is not enabled the
<del> * returned value is always {@code true}.
<add> * When partial message support is available and requested via
<add> * {@link org.springframework.web.socket.WebSocketHandler#supportsPartialMessages()},
<add> * this method returns {@literal true} if the current message is the last part of
<add> * the complete WebSocket message sent by the client. Otherwise {@literal false}
<add> * is returned if partial message support is either not available or not enabled.
<ide> */
<del> public boolean isLast() {
<del> return this.last;
<del> }
<del>
<del> @Override
<del> public int hashCode() {
<del> return WebSocketMessage.class.hashCode() * 13 + ObjectUtils.nullSafeHashCode(this.payload);
<del> }
<del>
<del> @Override
<del> public boolean equals(Object other) {
<del> if (this == other) {
<del> return true;
<del> }
<del> if (!(other instanceof WebSocketMessage)) {
<del> return false;
<del> }
<del> WebSocketMessage otherMessage = (WebSocketMessage) other;
<del> return ObjectUtils.nullSafeEquals(this.payload, otherMessage.payload);
<del> }
<del>
<del> @Override
<del> public String toString() {
<del> return getClass().getSimpleName() + " payload= " + toStringPayload()
<del> + ", length=" + getPayloadSize() + ", last=" + isLast() + "]";
<del> }
<del>
<del> protected abstract String toStringPayload();
<del>
<del> protected abstract int getPayloadSize();
<add> boolean isLast();
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/AbstractWebSocketSesssion.java
<ide> /**
<ide> * An abstract base class for implementations of {@link WebSocketSession}.
<ide> *
<del> * @param T the type of the native (or delegate) WebSocket session
<del> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/JettyWebSocketHandlerAdapter.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide> import org.eclipse.jetty.websocket.api.Session;
<del>import org.eclipse.jetty.websocket.api.WebSocketListener;
<add>import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
<add>import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
<add>import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
<add>import org.eclipse.jetty.websocket.api.annotations.OnWebSocketFrame;
<add>import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
<add>import org.eclipse.jetty.websocket.api.annotations.WebSocket;
<add>import org.eclipse.jetty.websocket.api.extensions.Frame;
<add>import org.eclipse.jetty.websocket.common.OpCode;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.socket.BinaryMessage;
<ide> import org.springframework.web.socket.CloseStatus;
<add>import org.springframework.web.socket.PongMessage;
<ide> import org.springframework.web.socket.TextMessage;
<ide> import org.springframework.web.socket.WebSocketHandler;
<ide> import org.springframework.web.socket.support.ExceptionWebSocketHandlerDecorator;
<ide>
<add>import java.nio.ByteBuffer;
<add>
<ide> /**
<ide> * Adapts {@link WebSocketHandler} to the Jetty 9 WebSocket API.
<ide> *
<del> * @author Phillip Webb
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public class JettyWebSocketHandlerAdapter implements WebSocketListener {
<add>@WebSocket
<add>public class JettyWebSocketHandlerAdapter {
<ide>
<ide> private static final Log logger = LogFactory.getLog(JettyWebSocketHandlerAdapter.class);
<ide>
<ide> public class JettyWebSocketHandlerAdapter implements WebSocketListener {
<ide>
<ide>
<ide> public JettyWebSocketHandlerAdapter(WebSocketHandler webSocketHandler, JettyWebSocketSession wsSession) {
<add>
<ide> Assert.notNull(webSocketHandler, "webSocketHandler must not be null");
<ide> Assert.notNull(wsSession, "wsSession must not be null");
<add>
<ide> this.webSocketHandler = webSocketHandler;
<ide> this.wsSession = wsSession;
<ide> }
<ide>
<ide>
<del> @Override
<add> @OnWebSocketConnect
<ide> public void onWebSocketConnect(Session session) {
<ide> try {
<ide> this.wsSession.initializeNativeSession(session);
<ide> public void onWebSocketConnect(Session session) {
<ide> }
<ide> }
<ide>
<del> @Override
<add> @OnWebSocketMessage
<ide> public void onWebSocketText(String payload) {
<ide> TextMessage message = new TextMessage(payload);
<ide> try {
<ide> public void onWebSocketText(String payload) {
<ide> }
<ide> }
<ide>
<del> @Override
<del> public void onWebSocketBinary(byte[] payload, int offset, int len) {
<del> BinaryMessage message = new BinaryMessage(payload, offset, len, true);
<add> @OnWebSocketMessage
<add> public void onWebSocketBinary(byte[] payload, int offset, int length) {
<add> BinaryMessage message = new BinaryMessage(payload, offset, length, true);
<ide> try {
<ide> this.webSocketHandler.handleMessage(this.wsSession, message);
<ide> }
<ide> public void onWebSocketBinary(byte[] payload, int offset, int len) {
<ide> }
<ide> }
<ide>
<del> @Override
<add> @OnWebSocketFrame
<add> public void onWebSocketFrame(Frame frame) {
<add> if (OpCode.PONG == frame.getOpCode()) {
<add> PongMessage message = new PongMessage(frame.getPayload());
<add> try {
<add> this.webSocketHandler.handleMessage(this.wsSession, message);
<add> }
<add> catch (Throwable t) {
<add> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, t, logger);
<add> }
<add> }
<add> }
<add>
<add> @OnWebSocketClose
<ide> public void onWebSocketClose(int statusCode, String reason) {
<ide> CloseStatus closeStatus = new CloseStatus(statusCode, reason);
<ide> try {
<ide> public void onWebSocketClose(int statusCode, String reason) {
<ide> }
<ide> }
<ide>
<del> @Override
<add> @OnWebSocketError
<ide> public void onWebSocketError(Throwable cause) {
<ide> try {
<ide> this.webSocketHandler.handleTransportError(this.wsSession, cause);
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/support/WebSocketHttpHeaders.java
<ide> */
<ide> public class WebSocketHttpHeaders extends HttpHeaders {
<ide>
<add> private static final long serialVersionUID = -6644521016187828916L;
<add>
<ide> public static final String SEC_WEBSOCKET_ACCEPT = "Sec-WebSocket-Accept";
<ide>
<ide> public static final String SEC_WEBSOCKET_EXTENSIONS = "Sec-WebSocket-Extensions";
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/server/config/WebSocketConfigurationTests.java
<ide> public void registerWebSocketHandler() throws Exception {
<ide> new WebSocketHandlerAdapter(), getWsBaseUrl() + "/ws").get();
<ide>
<ide> TestWebSocketHandler serverHandler = this.wac.getBean(TestWebSocketHandler.class);
<del> assertTrue(serverHandler.latch.await(2, TimeUnit.SECONDS));
<add> assertTrue(serverHandler.connectLatch.await(2, TimeUnit.SECONDS));
<ide>
<ide> session.close();
<ide> }
<ide> public void registerWebSocketHandlerWithSockJS() throws Exception {
<ide> new WebSocketHandlerAdapter(), getWsBaseUrl() + "/sockjs/websocket").get();
<ide>
<ide> TestWebSocketHandler serverHandler = this.wac.getBean(TestWebSocketHandler.class);
<del> assertTrue(serverHandler.latch.await(2, TimeUnit.SECONDS));
<add> assertTrue(serverHandler.connectLatch.await(2, TimeUnit.SECONDS));
<ide>
<ide> session.close();
<ide> }
<ide> public TestWebSocketHandler serverHandler() {
<ide>
<ide> private static class TestWebSocketHandler extends WebSocketHandlerAdapter {
<ide>
<del> private CountDownLatch latch = new CountDownLatch(1);
<add> private CountDownLatch connectLatch = new CountDownLatch(1);
<ide>
<ide> @Override
<ide> public void afterConnectionEstablished(WebSocketSession session) throws Exception {
<del> this.latch.countDown();
<add> this.connectLatch.countDown();
<ide> }
<ide> }
<ide> | 14 |
Javascript | Javascript | add fast internal array join method | 01652ccc682d2ed678d43a22d1ceb33776c0d4b1 | <ide><path>lib/internal/util.js
<ide> function promisify(original) {
<ide>
<ide> promisify.custom = kCustomPromisifiedSymbol;
<ide>
<add>// The build-in Array#join is slower in v8 6.0
<add>function join(output, separator) {
<add> var str = '';
<add> if (output.length !== 0) {
<add> for (var i = 0; i < output.length - 1; i++) {
<add> // It is faster not to use a template string here
<add> str += output[i];
<add> str += separator;
<add> }
<add> str += output[i];
<add> }
<add> return str;
<add>}
<add>
<ide> module.exports = {
<ide> assertCrypto,
<ide> cachedResult,
<ide> module.exports = {
<ide> normalizeEncoding,
<ide> objectToString,
<ide> promisify,
<add> join,
<ide>
<ide> // Symbol used to customize promisify conversion
<ide> customPromisifyArgs: kCustomPromisifyArgsSymbol, | 1 |
PHP | PHP | correct testtask tests | a56ec8d6cf371684f65a88fc718611f3575f3786 | <ide><path>lib/Cake/Test/Case/Console/Command/Task/TestTaskTest.php
<ide> public function testBakeControllerTest() {
<ide> $this->assertContains("App::uses('TestTaskCommentsController', 'Controller')", $result);
<ide> $this->assertContains('class TestTaskCommentsControllerTest extends ControllerTestCase', $result);
<ide>
<del> $this->assertContains('function setUp()', $result);
<del> $this->assertContains("\$this->TestTaskComments = new TestTaskCommentsController()", $result);
<del> $this->assertContains("\$this->TestTaskComments->constructClasses()", $result);
<add> $this->assertNotContains('function setUp()', $result);
<add> $this->assertNotContains("\$this->TestTaskComments = new TestTaskCommentsController()", $result);
<add> $this->assertNotContains("\$this->TestTaskComments->constructClasses()", $result);
<ide>
<del> $this->assertContains('function tearDown()', $result);
<del> $this->assertContains('unset($this->TestTaskComments)', $result);
<add> $this->assertNotContains('function tearDown()', $result);
<add> $this->assertNotContains('unset($this->TestTaskComments)', $result);
<ide>
<ide> $this->assertContains("'app.test_task_article'", $result);
<ide> $this->assertContains("'plugin.test_task.test_task_comment'", $result);
<ide> public function testBakeHelperTest() {
<ide> */
<ide> public function testGenerateConstructor() {
<ide> $result = $this->Task->generateConstructor('controller', 'PostsController', null);
<del> $expected = array('', "new PostsController();\n", "\$this->Posts->constructClasses();\n");
<add> $expected = array('', '', '');
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->Task->generateConstructor('model', 'Post', null); | 1 |
Javascript | Javascript | replace the iframe resizer by divs | 2c52209ba73cc9b190608319dbba0593f3df455e | <ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide> listeners[type] = listener;
<ide> });
<ide>
<del> // Responsiveness is currently based on the use of an iframe, however this method causes
<del> // performance issues and could be troublesome when used with ad blockers. So make sure
<del> // that the user is still able to create a chart without iframe when responsive is false.
<add> // Elements used to detect size change should not be injected for non responsive charts.
<ide> // See https://github.com/chartjs/Chart.js/issues/2210
<ide> if (me.options.responsive) {
<ide> listener = function() {
<ide><path>src/platforms/platform.dom.js
<ide> function throttled(fn, thisArg) {
<ide> };
<ide> }
<ide>
<add>// Implementation based on https://github.com/marcj/css-element-queries
<ide> function createResizer(handler) {
<del> var iframe = document.createElement('iframe');
<del> iframe.className = 'chartjs-hidden-iframe';
<del> iframe.style.cssText =
<del> 'display:block;' +
<del> 'overflow:hidden;' +
<del> 'border:0;' +
<del> 'margin:0;' +
<del> 'top:0;' +
<add> var resizer = document.createElement('div');
<add> var cls = CSS_PREFIX + 'size-monitor';
<add> var maxSize = 1000000;
<add> var style =
<add> 'position:absolute;' +
<ide> 'left:0;' +
<del> 'bottom:0;' +
<add> 'top:0;' +
<ide> 'right:0;' +
<del> 'height:100%;' +
<del> 'width:100%;' +
<del> 'position:absolute;' +
<add> 'bottom:0;' +
<add> 'overflow:hidden;' +
<ide> 'pointer-events:none;' +
<add> 'visibility:hidden;' +
<ide> 'z-index:-1;';
<ide>
<del> // Prevent the iframe to gain focus on tab.
<del> // https://github.com/chartjs/Chart.js/issues/3090
<del> iframe.tabIndex = -1;
<del>
<del> // Prevent iframe from gaining focus on ItemMode keyboard navigation
<del> // Accessibility bug fix
<del> iframe.setAttribute('aria-hidden', 'true');
<del>
<del> // If the iframe is re-attached to the DOM, the resize listener is removed because the
<del> // content is reloaded, so make sure to install the handler after the iframe is loaded.
<del> // https://github.com/chartjs/Chart.js/issues/3521
<del> addEventListener(iframe, 'load', function() {
<del> addEventListener(iframe.contentWindow || iframe, 'resize', handler);
<del> // The iframe size might have changed while loading, which can also
<del> // happen if the size has been changed while detached from the DOM.
<add> resizer.style.cssText = style;
<add> resizer.className = cls;
<add> resizer.innerHTML =
<add> '<div class="' + cls + '-expand" style="' + style + '">' +
<add> '<div style="' +
<add> 'position:absolute;' +
<add> 'width:' + maxSize + 'px;' +
<add> 'height:' + maxSize + 'px;' +
<add> 'left:0;' +
<add> 'top:0">' +
<add> '</div>' +
<add> '</div>' +
<add> '<div class="' + cls + '-shrink" style="' + style + '">' +
<add> '<div style="' +
<add> 'position:absolute;' +
<add> 'width:200%;' +
<add> 'height:200%;' +
<add> 'left:0; ' +
<add> 'top:0">' +
<add> '</div>' +
<add> '</div>';
<add>
<add> var expand = resizer.childNodes[0];
<add> var shrink = resizer.childNodes[1];
<add>
<add> resizer._reset = function() {
<add> expand.scrollLeft = maxSize;
<add> expand.scrollTop = maxSize;
<add> shrink.scrollLeft = maxSize;
<add> shrink.scrollTop = maxSize;
<add> };
<add> var onScroll = function() {
<add> resizer._reset();
<ide> handler();
<del> });
<add> };
<add>
<add> addEventListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
<add> addEventListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
<ide>
<del> return iframe;
<add> return resizer;
<ide> }
<ide>
<ide> // https://davidwalsh.name/detect-node-insertion
<ide> function addResizeListener(node, listener, chart) {
<ide> if (container && container !== resizer.parentNode) {
<ide> container.insertBefore(resizer, container.firstChild);
<ide> }
<add>
<add> // The container size might have changed, let's reset the resizer state.
<add> resizer._reset();
<ide> }
<ide> });
<ide> }
<ide><path>test/specs/core.controller.tests.js
<ide> describe('Chart', function() {
<ide>
<ide> waitForResize(chart, function() {
<ide> var resizer = wrapper.firstChild;
<del> expect(resizer.tagName).toBe('IFRAME');
<add> expect(resizer.className).toBe('chartjs-size-monitor');
<add> expect(resizer.tagName).toBe('DIV');
<ide> expect(chart).toBeChartOfSize({
<ide> dw: 455, dh: 355,
<ide> rw: 455, rh: 355,
<ide> describe('Chart', function() {
<ide> var wrapper = chart.canvas.parentNode;
<ide> var resizer = wrapper.firstChild;
<ide> expect(wrapper.childNodes.length).toBe(2);
<del> expect(resizer.tagName).toBe('IFRAME');
<add> expect(resizer.className).toBe('chartjs-size-monitor');
<add> expect(resizer.tagName).toBe('DIV');
<ide>
<ide> chart.destroy();
<ide> | 3 |
Ruby | Ruby | add pinned version to outdated output | 70446d9112c0d42ca1ab469af07716bb7281169e | <ide><path>Library/Homebrew/cmd/outdated.rb
<ide> def print_outdated(formulae)
<ide> "#{full_name} (#{kegs.map(&:version).join(", ")})"
<ide> end.join(", ")
<ide>
<del> puts "#{outdated_versions} < #{current_version}"
<add> pinned_version = " [pinned at #{f.pinned_version}]" if f.pinned?
<add>
<add> puts "#{outdated_versions} < #{current_version}#{pinned_version}"
<ide> else
<ide> puts f.full_installed_specified_name
<ide> end
<ide><path>Library/Homebrew/test/cmd/outdated_spec.rb
<ide> .and be_a_success
<ide> end
<ide> end
<add>
<add> context "pinned formula, verbose output" do
<add> it "prints out the pinned version" do
<add> setup_test_formula "testball"
<add> (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath
<add>
<add> shutup do
<add> expect { brew "pin", "testball" }.to be_a_success
<add> end
<add>
<add> expect { brew "outdated", "--verbose" }
<add> .to output("testball (0.0.1) < 0.1 [pinned at 0.0.1]\n").to_stdout
<add> .and not_to_output.to_stderr
<add> .and be_a_success
<add> end
<add> end
<ide> end | 2 |
PHP | PHP | fix cs error | ba06069e6884d21ca99c04ea6b343b1eb5257139 | <ide><path>tests/TestCase/Http/Middleware/SessionCsrfProtectionMiddlewareTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Http\Middleware;
<ide>
<del>use Cake\Http\Cookie\Cookie;
<del>use Cake\Http\Cookie\CookieInterface;
<ide> use Cake\Http\Exception\InvalidCsrfTokenException;
<ide> use Cake\Http\Middleware\SessionCsrfProtectionMiddleware;
<ide> use Cake\Http\Response;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<del>use Laminas\Diactoros\Response as DiactorosResponse;
<del>use Laminas\Diactoros\Response\RedirectResponse;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use TestApp\Http\TestRequestHandler;
<ide> | 1 |
Javascript | Javascript | use a mock for filewatcher | 44b051d98d5fec5887e7fea482237a927a118643 | <ide><path>packager/react-packager/src/DependencyResolver/__tests__/Module-test.js
<ide> jest
<ide> .dontMock('../fastfs')
<ide> .dontMock('../replacePatterns')
<ide> .dontMock('../DependencyGraph/docblock')
<del> .dontMock('../../FileWatcher')
<ide> .dontMock('../Module');
<ide>
<ide> jest
<ide> var Module = require('../Module');
<ide> var ModuleCache = require('../ModuleCache');
<ide> var Promise = require('promise');
<ide> var fs = require('fs');
<del>var FileWatcher = require('../../FileWatcher');
<ide>
<ide> describe('Module', () => {
<del> const fileWatcher = new FileWatcher(['/root']);
<add> const fileWatcher = {
<add> on: () => this,
<add> isWatchman: () => Promise.resolve(false),
<add> };
<ide>
<ide> describe('Async Dependencies', () => {
<ide> function expectAsyncDependenciesToEqual(expected) {
<ide><path>packager/react-packager/src/DependencyResolver/fastfs.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<ide> 'use strict';
<ide>
<ide> const Promise = require('promise');
<ide><path>packager/react-packager/src/__mocks__/fs.js
<ide> fs.stat.mockImpl(function(filepath, callback) {
<ide> var mtime = {
<ide> getTime: function() {
<ide> return Math.ceil(Math.random() * 10000000);
<del> }
<add> },
<ide> };
<ide>
<ide> if (node.SYMLINK) { | 3 |
Python | Python | add eval and parallel dataset | 1635e56144ad4289faa7441f20c4b27a02e41dac | <ide><path>research/deep_speech/data/dataset.py
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<add>import functools
<add>import multiprocessing
<add>
<ide> import numpy as np
<ide> import scipy.io.wavfile as wavfile
<ide> from six.moves import xrange # pylint: disable=redefined-builtin
<ide> import tensorflow as tf
<ide>
<del># pylint: disable=g-bad-import-order
<del>from data.featurizer import AudioFeaturizer
<del>from data.featurizer import TextFeaturizer
<add>import data.featurizer as featurizer # pylint: disable=g-bad-import-order
<ide>
<ide>
<ide> class AudioConfig(object):
<ide> def __init__(self,
<ide> frame_length: an integer for the length of a spectrogram frame, in ms.
<ide> frame_step: an integer for the frame stride, in ms.
<ide> fft_length: an integer for the number of fft bins.
<del> normalize: a boolean for whether apply normalization on the audio tensor.
<add> normalize: a boolean for whether apply normalization on the audio feature.
<ide> spect_type: a string for the type of spectrogram to be extracted.
<ide> """
<ide>
<ide> def __init__(self, audio_config, data_path, vocab_file_path):
<ide> self.vocab_file_path = vocab_file_path
<ide>
<ide>
<add>def _normalize_audio_feature(audio_feature):
<add> """Perform mean and variance normalization on the spectrogram feature.
<add>
<add> Args:
<add> audio_feature: a numpy array for the spectrogram feature.
<add>
<add> Returns:
<add> a numpy array of the normalized spectrogram.
<add> """
<add> mean = np.mean(audio_feature, axis=0)
<add> var = np.var(audio_feature, axis=0)
<add> normalized = (audio_feature - mean) / (np.sqrt(var) + 1e-6)
<add>
<add> return normalized
<add>
<add>
<add>def _preprocess_audio(
<add> audio_file_path, audio_sample_rate, audio_featurizer, normalize):
<add> """Load the audio file in memory and compute spectrogram feature."""
<add> tf.logging.info(
<add> "Extracting spectrogram feature for {}".format(audio_file_path))
<add> sample_rate, data = wavfile.read(audio_file_path)
<add> assert sample_rate == audio_sample_rate
<add> if data.dtype not in [np.float32, np.float64]:
<add> data = data.astype(np.float32) / np.iinfo(data.dtype).max
<add> feature = featurizer.compute_spectrogram_feature(
<add> data, audio_featurizer.frame_length, audio_featurizer.frame_step,
<add> audio_featurizer.fft_length)
<add> if normalize:
<add> feature = _normalize_audio_feature(feature)
<add> return feature
<add>
<add>
<add>def _preprocess_transcript(transcript, token_to_index):
<add> """Process transcript as label features."""
<add> return featurizer.compute_label_feature(transcript, token_to_index)
<add>
<add>
<add>def _preprocess_data(dataset_config, audio_featurizer, token_to_index):
<add> """Generate a list of waveform, transcript pair.
<add>
<add> Each dataset file contains three columns: "wav_filename", "wav_filesize",
<add> and "transcript". This function parses the csv file and stores each example
<add> by the increasing order of audio length (indicated by wav_filesize).
<add> AS the waveforms are ordered in increasing length, audio samples in a
<add> mini-batch have similar length.
<add>
<add> Args:
<add> dataset_config: an instance of DatasetConfig.
<add> audio_featurizer: an instance of AudioFeaturizer.
<add> token_to_index: the mapping from character to its index
<add>
<add> Returns:
<add> features and labels array processed from the audio/text input.
<add> """
<add>
<add> file_path = dataset_config.data_path
<add> sample_rate = dataset_config.audio_config.sample_rate
<add> normalize = dataset_config.audio_config.normalize
<add>
<add> with tf.gfile.Open(file_path, "r") as f:
<add> lines = f.read().splitlines()
<add> lines = [line.split("\t") for line in lines]
<add> # Skip the csv header.
<add> lines = lines[1:]
<add> # Sort input data by the length of waveform.
<add> lines.sort(key=lambda item: int(item[1]))
<add>
<add> # Use multiprocessing for feature/label extraction
<add> num_cores = multiprocessing.cpu_count()
<add> pool = multiprocessing.Pool(processes=num_cores)
<add>
<add> features = pool.map(
<add> functools.partial(
<add> _preprocess_audio, audio_sample_rate=sample_rate,
<add> audio_featurizer=audio_featurizer, normalize=normalize),
<add> [line[0] for line in lines])
<add> labels = pool.map(
<add> functools.partial(
<add> _preprocess_transcript, token_to_index=token_to_index),
<add> [line[2] for line in lines])
<add>
<add> pool.terminate()
<add> return features, labels
<add>
<add>
<ide> class DeepSpeechDataset(object):
<ide> """Dataset class for training/evaluation of DeepSpeech model."""
<ide>
<ide> def __init__(self, dataset_config):
<del> """Initialize the class.
<del>
<del> Each dataset file contains three columns: "wav_filename", "wav_filesize",
<del> and "transcript". This function parses the csv file and stores each example
<del> by the increasing order of audio length (indicated by wav_filesize).
<add> """Initialize the DeepSpeechDataset class.
<ide>
<ide> Args:
<ide> dataset_config: DatasetConfig object.
<ide> """
<ide> self.config = dataset_config
<ide> # Instantiate audio feature extractor.
<del> self.audio_featurizer = AudioFeaturizer(
<add> self.audio_featurizer = featurizer.AudioFeaturizer(
<ide> sample_rate=self.config.audio_config.sample_rate,
<ide> frame_length=self.config.audio_config.frame_length,
<ide> frame_step=self.config.audio_config.frame_step,
<del> fft_length=self.config.audio_config.fft_length,
<del> spect_type=self.config.audio_config.spect_type)
<add> fft_length=self.config.audio_config.fft_length)
<ide> # Instantiate text feature extractor.
<del> self.text_featurizer = TextFeaturizer(
<add> self.text_featurizer = featurizer.TextFeaturizer(
<ide> vocab_file=self.config.vocab_file_path)
<ide>
<ide> self.speech_labels = self.text_featurizer.speech_labels
<del> self.features, self.labels = self._preprocess_data(self.config.data_path)
<add> self.features, self.labels = _preprocess_data(
<add> self.config,
<add> self.audio_featurizer,
<add> self.text_featurizer.token_to_idx
<add> )
<add>
<ide> self.num_feature_bins = (
<ide> self.features[0].shape[1] if len(self.features) else None)
<ide>
<del> def _preprocess_data(self, file_path):
<del> """Generate a list of waveform, transcript pair.
<del>
<del> Note that the waveforms are ordered in increasing length, so that audio
<del> samples in a mini-batch have similar length.
<del>
<del> Args:
<del> file_path: a string specifying the csv file path for a data set.
<del>
<del> Returns:
<del> features and labels array processed from the audio/text input.
<del> """
<del>
<del> with tf.gfile.Open(file_path, "r") as f:
<del> lines = f.read().splitlines()
<del> lines = [line.split("\t") for line in lines]
<del> # Skip the csv header.
<del> lines = lines[1:]
<del> # Sort input data by the length of waveform.
<del> lines.sort(key=lambda item: int(item[1]))
<del> features = [self._preprocess_audio(line[0]) for line in lines]
<del> labels = [self._preprocess_transcript(line[2]) for line in lines]
<del> return features, labels
<del>
<del> def _normalize_audio_tensor(self, audio_tensor):
<del> """Perform mean and variance normalization on the spectrogram tensor.
<del>
<del> Args:
<del> audio_tensor: a tensor for the spectrogram feature.
<del>
<del> Returns:
<del> a tensor for the normalized spectrogram.
<del> """
<del> mean, var = tf.nn.moments(audio_tensor, axes=[0])
<del> normalized = (audio_tensor - mean) / (tf.sqrt(var) + 1e-6)
<del> return normalized
<del>
<del> def _preprocess_audio(self, audio_file_path):
<del> """Load the audio file in memory."""
<del> tf.logging.info(
<del> "Extracting spectrogram feature for {}".format(audio_file_path))
<del> sample_rate, data = wavfile.read(audio_file_path)
<del> assert sample_rate == self.config.audio_config.sample_rate
<del> if data.dtype not in [np.float32, np.float64]:
<del> data = data.astype(np.float32) / np.iinfo(data.dtype).max
<del> feature = self.audio_featurizer.featurize(data)
<del> if self.config.audio_config.normalize:
<del> feature = self._normalize_audio_tensor(feature)
<del> return tf.Session().run(
<del> feature) # return a numpy array rather than a tensor
<del>
<del> def _preprocess_transcript(self, transcript):
<del> return self.text_featurizer.featurize(transcript)
<del>
<ide>
<ide> def input_fn(batch_size, deep_speech_dataset, repeat=1):
<ide> """Input function for model training and evaluation.
<ide><path>research/deep_speech/data/featurizer.py
<ide> from __future__ import print_function
<ide>
<ide> import codecs
<del>import functools
<ide> import numpy as np
<del>import tensorflow as tf
<add>from scipy import signal
<add>
<add>
<add>def compute_spectrogram_feature(waveform, frame_length, frame_step, fft_length):
<add> """Compute the spectrograms for the input waveform."""
<add> _, _, stft = signal.stft(
<add> waveform,
<add> nperseg=frame_length,
<add> noverlap=frame_step,
<add> nfft=fft_length)
<add>
<add> # Perform transpose to set its shape as [time_steps, feature_num_bins]
<add> spectrogram = np.transpose(np.absolute(stft), (1, 0))
<add> return spectrogram
<ide>
<ide>
<ide> class AudioFeaturizer(object):
<ide> def __init__(self,
<ide> sample_rate=16000,
<ide> frame_length=25,
<ide> frame_step=10,
<del> fft_length=None,
<del> window_fn=functools.partial(
<del> tf.contrib.signal.hann_window, periodic=True),
<del> spect_type="linear"):
<add> fft_length=None):
<ide> """Initialize the audio featurizer class according to the configs.
<ide>
<ide> Args:
<ide> sample_rate: an integer specifying the sample rate of the input waveform.
<ide> frame_length: an integer for the length of a spectrogram frame, in ms.
<ide> frame_step: an integer for the frame stride, in ms.
<ide> fft_length: an integer for the number of fft bins.
<del> window_fn: windowing function.
<del> spect_type: a string for the type of spectrogram to be extracted.
<del> Currently only support 'linear', otherwise will raise a value error.
<del>
<del> Raises:
<del> ValueError: In case of invalid arguments for `spect_type`.
<ide> """
<del> if spect_type != "linear":
<del> raise ValueError("Unsupported spectrogram type: %s" % spect_type)
<del> self.window_fn = window_fn
<ide> self.frame_length = int(sample_rate * frame_length / 1e3)
<ide> self.frame_step = int(sample_rate * frame_step / 1e3)
<ide> self.fft_length = fft_length if fft_length else int(2**(np.ceil(
<ide> np.log2(self.frame_length))))
<ide>
<del> def featurize(self, waveform):
<del> """Extract spectrogram feature tensors from the waveform."""
<del> return self._compute_linear_spectrogram(waveform)
<ide>
<del> def _compute_linear_spectrogram(self, waveform):
<del> """Compute the linear-scale, magnitude spectrograms for the input waveform.
<del>
<del> Args:
<del> waveform: a float32 audio tensor.
<del> Returns:
<del> a float 32 tensor with shape [len, num_bins]
<del> """
<del>
<del> # `stfts` is a complex64 Tensor representing the Short-time Fourier
<del> # Transform of each signal in `signals`. Its shape is
<del> # [?, fft_unique_bins] where fft_unique_bins = fft_length // 2 + 1.
<del> stfts = tf.contrib.signal.stft(
<del> waveform,
<del> frame_length=self.frame_length,
<del> frame_step=self.frame_step,
<del> fft_length=self.fft_length,
<del> window_fn=self.window_fn,
<del> pad_end=True)
<del>
<del> # An energy spectrogram is the magnitude of the complex-valued STFT.
<del> # A float32 Tensor of shape [?, 257].
<del> magnitude_spectrograms = tf.abs(stfts)
<del> return magnitude_spectrograms
<del>
<del> def _compute_mel_filterbank_features(self, waveform):
<del> """Compute the mel filterbank features."""
<del> raise NotImplementedError("MFCC feature extraction not supported yet.")
<add>def compute_label_feature(text, token_to_idx):
<add> """Convert string to a list of integers."""
<add> tokens = list(text.strip().lower())
<add> feats = [token_to_idx[token] for token in tokens]
<add> return feats
<ide>
<ide>
<ide> class TextFeaturizer(object):
<ide> def __init__(self, vocab_file):
<ide> self.idx_to_token[idx] = line
<ide> self.speech_labels += line
<ide> idx += 1
<del>
<del> def featurize(self, text):
<del> """Convert string to a list of integers."""
<del> tokens = list(text.strip().lower())
<del> feats = [self.token_to_idx[token] for token in tokens]
<del> return feats
<ide><path>research/deep_speech/decoder.py
<add>
<add># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
<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>"""Deep speech decoder."""
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>from nltk.metrics import distance
<add>from six.moves import xrange
<add>import tensorflow as tf
<add>
<add>
<add>class DeepSpeechDecoder(object):
<add> """Basic decoder class from which all other decoders inherit.
<add>
<add> Implements several helper functions. Subclasses should implement the decode()
<add> method.
<add> """
<add>
<add> def __init__(self, labels, blank_index=28, space_index=27):
<add> """Decoder initialization.
<add>
<add> Arguments:
<add> labels (string): mapping from integers to characters.
<add> blank_index (int, optional): index for the blank '_' character.
<add> Defaults to 0.
<add> space_index (int, optional): index for the space ' ' character.
<add> Defaults to 28.
<add> """
<add> # e.g. labels = "[a-z]' _"
<add> self.labels = labels
<add> self.int_to_char = dict([(i, c) for (i, c) in enumerate(labels)])
<add> self.blank_index = blank_index
<add> self.space_index = space_index
<add>
<add> def convert_to_strings(self, sequences, sizes=None):
<add> """Given a list of numeric sequences, returns the corresponding strings."""
<add> strings = []
<add> for x in xrange(len(sequences)):
<add> seq_len = sizes[x] if sizes is not None else len(sequences[x])
<add> string = self._convert_to_string(sequences[x], seq_len)
<add> strings.append(string)
<add> return strings
<add>
<add> def _convert_to_string(self, sequence, sizes):
<add> return ''.join([self.int_to_char[sequence[i]] for i in range(sizes)])
<add>
<add> def process_strings(self, sequences, remove_repetitions=False):
<add> """Process strings.
<add>
<add> Given a list of strings, removes blanks and replace space character with
<add> space. Option to remove repetitions (e.g. 'abbca' -> 'abca').
<add>
<add> Arguments:
<add> sequences: list of 1-d array of integers
<add> remove_repetitions (boolean, optional): If true, repeating characters
<add> are removed. Defaults to False.
<add>
<add> Returns:
<add> The processed string.
<add> """
<add> processed_strings = []
<add> for sequence in sequences:
<add> string = self.process_string(remove_repetitions, sequence).strip()
<add> processed_strings.append(string)
<add> return processed_strings
<add>
<add> def process_string(self, remove_repetitions, sequence):
<add> """Process each given sequence."""
<add> seq_string = ''
<add> for i, char in enumerate(sequence):
<add> if char != self.int_to_char[self.blank_index]:
<add> # if this char is a repetition and remove_repetitions=true,
<add> # skip.
<add> if remove_repetitions and i != 0 and char == sequence[i - 1]:
<add> pass
<add> elif char == self.labels[self.space_index]:
<add> seq_string += ' '
<add> else:
<add> seq_string += char
<add> return seq_string
<add>
<add> def wer(self, output, target):
<add> """Computes the Word Error Rate (WER).
<add>
<add> WER is defined as the edit distance between the two provided sentences after
<add> tokenizing to words.
<add>
<add> Args:
<add> output: string of the decoded output.
<add> target: a string for the true transcript.
<add>
<add> Returns:
<add> A float number for the WER of the current sentence pair.
<add> """
<add> # Map each word to a new char.
<add> words = set(output.split() + target.split())
<add> word2char = dict(zip(words, range(len(words))))
<add>
<add> new_output = [chr(word2char[w]) for w in output.split()]
<add> new_target = [chr(word2char[w]) for w in target.split()]
<add>
<add> return distance.edit_distance(''.join(new_output), ''.join(new_target))
<add>
<add> def cer(self, output, target):
<add> """Computes the Character Error Rate (CER).
<add>
<add> CER is defined as the edit distance between the given strings.
<add>
<add> Args:
<add> output: a string of the decoded output.
<add> target: a string for the ground truth transcript.
<add>
<add> Returns:
<add> A float number denoting the CER for the current sentence pair.
<add> """
<add> return distance.edit_distance(output, target)
<add>
<add> def batch_wer(self, decoded_output, targets):
<add> """Compute the aggregate WER for each batch.
<add>
<add> Args:
<add> decoded_output: 2d array of integers for the decoded output of a batch.
<add> targets: 2d array of integers for the labels of a batch.
<add>
<add> Returns:
<add> A float number for the aggregated WER for the current batch output.
<add> """
<add> # Convert numeric representation to string.
<add> decoded_strings = self.convert_to_strings(decoded_output)
<add> decoded_strings = self.process_strings(
<add> decoded_strings, remove_repetitions=True)
<add> target_strings = self.convert_to_strings(targets)
<add> target_strings = self.process_strings(
<add> target_strings, remove_repetitions=True)
<add> wer = 0
<add> for i in xrange(len(decoded_strings)):
<add> wer += self.wer(decoded_strings[i], target_strings[i]) / float(
<add> len(target_strings[i].split()))
<add> return wer
<add>
<add> def batch_cer(self, decoded_output, targets):
<add> """Compute the aggregate CER for each batch.
<add>
<add> Args:
<add> decoded_output: 2d array of integers for the decoded output of a batch.
<add> targets: 2d array of integers for the labels of a batch.
<add>
<add> Returns:
<add> A float number for the aggregated CER for the current batch output.
<add> """
<add> # Convert numeric representation to string.
<add> decoded_strings = self.convert_to_strings(decoded_output)
<add> decoded_strings = self.process_strings(
<add> decoded_strings, remove_repetitions=True)
<add> target_strings = self.convert_to_strings(targets)
<add> target_strings = self.process_strings(
<add> target_strings, remove_repetitions=True)
<add> cer = 0
<add> for i in xrange(len(decoded_strings)):
<add> cer += self.cer(decoded_strings[i], target_strings[i]) / float(
<add> len(target_strings[i]))
<add> return cer
<add>
<add> def decode(self, sequences, sizes=None):
<add> """Perform sequence decoding.
<add>
<add> Given a matrix of character probabilities, returns the decoder's best guess
<add> of the transcription.
<add>
<add> Arguments:
<add> sequences: 2D array of character probabilities, where sequences[c, t] is
<add> the probability of character c at time t.
<add> sizes(optional): Size of each sequence in the mini-batch.
<add>
<add> Returns:
<add> string: sequence of the model's best guess for the transcription.
<add> """
<add> strings = self.convert_to_strings(sequences, sizes)
<add> return self.process_strings(strings, remove_repetitions=True)
<add>
<add>
<add>class GreedyDecoder(DeepSpeechDecoder):
<add> """Greedy decoder."""
<add>
<add> def decode(self, logits, seq_len):
<add> # Reshape to [max_time, batch_size, num_classes]
<add> logits = tf.transpose(logits, (1, 0, 2))
<add> decoded, _ = tf.nn.ctc_greedy_decoder(logits, seq_len)
<add> decoded_dense = tf.Session().run(tf.sparse_to_dense(
<add> decoded[0].indices, decoded[0].dense_shape, decoded[0].values))
<add> result = self.convert_to_strings(decoded_dense)
<add> return self.process_strings(result, remove_repetitions=True), decoded_dense
<ide><path>research/deep_speech/deep_speech.py
<ide> # pylint: enable=g-bad-import-order
<ide>
<ide> import data.dataset as dataset
<add>import decoder
<ide> import deep_speech_model
<ide> from official.utils.flags import core as flags_core
<ide> from official.utils.logs import hooks_helper
<ide> from official.utils.logs import logger
<ide> from official.utils.misc import distribution_utils
<add>from official.utils.misc import model_helpers
<ide>
<ide> # Default vocabulary file
<ide> _VOCABULARY_FILE = os.path.join(
<ide> os.path.dirname(__file__), "data/vocabulary.txt")
<add># Evaluation metrics
<add>_WER_KEY = "WER"
<add>_CER_KEY = "CER"
<add>
<add>
<add>def evaluate_model(
<add> estimator, batch_size, speech_labels, targets, input_fn_eval):
<add> """Evaluate the model performance using WER anc CER as metrics.
<add>
<add> WER: Word Error Rate
<add> CER: Character Error Rate
<add>
<add> Args:
<add> estimator: estimator to evaluate.
<add> batch_size: size of a mini-batch.
<add> speech_labels: a string specifying all the character in the vocabulary.
<add> targets: a list of list of integers for the featurized transcript.
<add> input_fn_eval: data input function for evaluation.
<add>
<add> Returns:
<add> Evaluation result containing 'wer' and 'cer' as two metrics.
<add> """
<add> # Get predictions
<add> predictions = estimator.predict(
<add> input_fn=input_fn_eval, yield_single_examples=False)
<add>
<add> y_preds = []
<add> input_lengths = []
<add> for p in predictions:
<add> y_preds.append(p["y_pred"])
<add> input_lengths.append(p["ctc_input_length"])
<add>
<add> num_of_examples = len(targets)
<add> total_wer, total_cer = 0, 0
<add> greedy_decoder = decoder.GreedyDecoder(speech_labels)
<add> for i in range(len(y_preds)):
<add> # Compute the CER and WER for the current batch,
<add> # and aggregate to total_cer, total_wer.
<add> y_pred_tensor = tf.convert_to_tensor(y_preds[i])
<add> batch_targets = targets[i * batch_size : (i + 1) * batch_size]
<add> seq_len = tf.squeeze(input_lengths[i], axis=1)
<add>
<add> # Perform decoding
<add> _, decoded_output = greedy_decoder.decode(
<add> y_pred_tensor, seq_len)
<add>
<add> # Compute CER.
<add> batch_cer = greedy_decoder.batch_cer(decoded_output, batch_targets)
<add> total_cer += batch_cer
<add> # Compute WER.
<add> batch_wer = greedy_decoder.batch_wer(decoded_output, batch_targets)
<add> total_wer += batch_wer
<add>
<add> # Get mean value
<add> total_cer /= num_of_examples
<add> total_wer /= num_of_examples
<add>
<add> global_step = estimator.get_variable_value(tf.GraphKeys.GLOBAL_STEP)
<add> eval_results = {
<add> _WER_KEY: total_wer,
<add> _CER_KEY: total_cer,
<add> tf.GraphKeys.GLOBAL_STEP: global_step,
<add> }
<add>
<add> return eval_results
<ide>
<ide>
<ide> def convert_keras_to_estimator(keras_model, num_gpus):
<ide> def input_fn_train():
<ide> return dataset.input_fn(
<ide> per_device_batch_size, train_speech_dataset)
<ide>
<del> def input_fn_eval(): # #pylint: disable=unused-variable
<add> def input_fn_eval():
<ide> return dataset.input_fn(
<ide> per_device_batch_size, eval_speech_dataset)
<ide>
<ide> def input_fn_eval(): # #pylint: disable=unused-variable
<ide>
<ide> estimator.train(input_fn=input_fn_train, hooks=train_hooks)
<ide>
<del> # Evaluate (TODO)
<del> # tf.logging.info("Starting to evaluate.")
<add> # Evaluation
<add> tf.logging.info("Starting to evaluate...")
<add>
<add> eval_results = evaluate_model(
<add> estimator, flags_obj.batch_size, eval_speech_dataset.speech_labels,
<add> eval_speech_dataset.labels, input_fn_eval)
<ide>
<del> # eval_results = evaluate_model(
<del> # estimator, keras_model, data_set.speech_labels, [], input_fn_eval)
<add> # Log the WER and CER results.
<add> benchmark_logger.log_evaluation_result(eval_results)
<add> tf.logging.info(
<add> "Iteration {}: WER = {:.2f}, CER = {:.2f}".format(
<add> cycle_index + 1, eval_results[_WER_KEY], eval_results[_CER_KEY]))
<ide>
<del> # benchmark_logger.log_evaluation_result(eval_results)
<ide> # If some evaluation threshold is met
<del> # Log the HR and NDCG results.
<del> # wer = eval_results[_WER_KEY]
<del> # cer = eval_results[_CER_KEY]
<del> # tf.logging.info(
<del> # "Iteration {}: WER = {:.2f}, CER = {:.2f}".format(
<del> # cycle_index + 1, wer, cer))
<del> # if model_helpers.past_stop_threshold(FLAGS.wer_threshold, wer):
<del> # break
<add> if model_helpers.past_stop_threshold(
<add> flags_obj.wer_threshold, eval_results[_WER_KEY]):
<add> break
<ide>
<ide> # Clear the session explicitly to avoid session delete error
<ide> tf.keras.backend.clear_session()
<ide> def define_deep_speech_flags():
<ide> flags_core.set_defaults(
<ide> model_dir="/tmp/deep_speech_model/",
<ide> export_dir="/tmp/deep_speech_saved_model/",
<del> train_epochs=10,
<del> batch_size=32,
<add> train_epochs=2,
<add> batch_size=4,
<ide> hooks="")
<ide>
<ide> # Deep speech flags | 4 |
Text | Text | fix some bullet points so they render correctly | a247af9c97be92f91242db51f4a9545db1bda702 | <ide><path>docs/sources/introduction/understanding-docker.md
<ide> Docker images are then built from these base images using a simple, descriptive
<ide> set of steps we call *instructions*. Each instruction creates a new layer in our
<ide> image. Instructions include actions like:
<ide>
<del>* Run a command. * Add a file or directory. * Create an environment variable. *
<del>What process to run when launching a container from this image.
<add>* Run a command.
<add>* Add a file or directory.
<add>* Create an environment variable.
<add>* What process to run when launching a container from this image.
<ide>
<ide> These instructions are stored in a file called a `Dockerfile`. Docker reads this
<ide> `Dockerfile` when you request a build of an image, executes the instructions, and | 1 |
Python | Python | fix typo in exception | f36c16f2debd65c2f9c011b07ca72a77b300db4e | <ide><path>celery/backends/base.py
<ide> def exception_to_python(self, exc):
<ide> try:
<ide> exc_type = exc['exc_type']
<ide> except KeyError as e:
<del> raise ValueError("Exception information must include"
<add> raise ValueError("Exception information must include "
<ide> "the exception type") from e
<ide> if exc_module is None:
<ide> cls = create_exception_cls( | 1 |
Java | Java | use context from entry point for prerendering | f58c496e07845e5fb765f051246160077fcf98e4 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> public <T extends View> int addRootView(
<ide> ThemedReactContext reactContext =
<ide> new ThemedReactContext(
<ide> mReactApplicationContext, rootView.getContext(), reactRootView.getSurfaceID(), rootTag);
<del> mMountingManager.startSurface(rootTag, rootView, reactContext);
<add> mMountingManager.startSurface(rootTag, reactContext, rootView);
<ide> String moduleName = reactRootView.getJSModuleName();
<ide> if (ENABLE_FABRIC_LOGS) {
<ide> FLog.d(TAG, "Starting surface for module: %s and reactTag: %d", moduleName, rootTag);
<ide> public <T extends View> int startSurface(
<ide> if (ENABLE_FABRIC_LOGS) {
<ide> FLog.d(TAG, "Starting surface for module: %s and reactTag: %d", moduleName, rootTag);
<ide> }
<del> mMountingManager.startSurface(rootTag, rootView, reactContext);
<add> mMountingManager.startSurface(rootTag, reactContext, rootView);
<ide>
<ide> // If startSurface is executed in the UIThread then, it uses the ViewportOffset from the View,
<ide> // Otherwise Fabric relies on calling {@link Binding#setConstraints} method to update the
<ide> public <T extends View> int startSurface(
<ide> return rootTag;
<ide> }
<ide>
<del> public void startSurface(final SurfaceHandler surfaceHandler, final @Nullable View rootView) {
<add> public void startSurface(
<add> final SurfaceHandler surfaceHandler, final Context context, final @Nullable View rootView) {
<ide> final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag();
<ide>
<del> if (rootView == null) {
<del> mMountingManager.startSurface(rootTag);
<del> } else {
<del> Context context = rootView.getContext();
<del> ThemedReactContext reactContext =
<del> new ThemedReactContext(
<del> mReactApplicationContext, context, surfaceHandler.getModuleName(), rootTag);
<del> mMountingManager.startSurface(rootTag, rootView, reactContext);
<del> }
<add> ThemedReactContext reactContext =
<add> new ThemedReactContext(
<add> mReactApplicationContext, context, surfaceHandler.getModuleName(), rootTag);
<add> mMountingManager.startSurface(rootTag, reactContext, rootView);
<ide>
<ide> surfaceHandler.setSurfaceId(rootTag);
<ide> if (surfaceHandler instanceof SurfaceHandlerBinding) {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java
<ide> public MountingManager(
<ide> mMountItemExecutor = mountItemExecutor;
<ide> }
<ide>
<del> /** Starts surface and attaches the root view. */
<del> @AnyThread
<del> public void startSurface(
<del> final int surfaceId, @NonNull final View rootView, ThemedReactContext themedReactContext) {
<del> SurfaceMountingManager mountingManager = startSurface(surfaceId);
<del> mountingManager.attachRootView(rootView, themedReactContext);
<del> }
<del>
<ide> /**
<ide> * Starts surface without attaching the view. All view operations executed against that surface
<ide> * will be queued until the view is attached.
<ide> */
<ide> @AnyThread
<del> public SurfaceMountingManager startSurface(final int surfaceId) {
<add> public SurfaceMountingManager startSurface(
<add> final int surfaceId, ThemedReactContext reactContext, @Nullable View rootView) {
<ide> SurfaceMountingManager surfaceMountingManager =
<ide> new SurfaceMountingManager(
<ide> surfaceId,
<ide> mJSResponderHandler,
<ide> mViewManagerRegistry,
<ide> mRootViewManager,
<del> mMountItemExecutor);
<add> mMountItemExecutor,
<add> reactContext);
<ide>
<ide> // There could technically be a race condition here if addRootView is called twice from
<ide> // different threads, though this is (probably) extremely unlikely, and likely an error.
<ide> public SurfaceMountingManager startSurface(final int surfaceId) {
<ide> }
<ide>
<ide> mMostRecentSurfaceMountingManager = mSurfaceIdToManager.get(surfaceId);
<add>
<add> if (rootView != null) {
<add> surfaceMountingManager.attachRootView(rootView, reactContext);
<add> }
<add>
<ide> return surfaceMountingManager;
<ide> }
<ide>
<ide> public void updateProps(int reactTag, @Nullable ReadableMap props) {
<ide> }
<ide>
<ide> /**
<del> * Clears the JS Responder specified by {@link #setJSResponder(int, int, int, boolean)}. After
<del> * this method is called, all the touch events are going to be handled by JS.
<add> * Clears the JS Responder specified by {@link SurfaceMountingManager#setJSResponder}. After this
<add> * method is called, all the touch events are going to be handled by JS.
<ide> */
<ide> @UiThread
<ide> public void clearJSResponder() {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.java
<ide> public SurfaceMountingManager(
<ide> @NonNull JSResponderHandler jsResponderHandler,
<ide> @NonNull ViewManagerRegistry viewManagerRegistry,
<ide> @NonNull RootViewManager rootViewManager,
<del> @NonNull MountItemExecutor mountItemExecutor) {
<add> @NonNull MountItemExecutor mountItemExecutor,
<add> @NonNull ThemedReactContext reactContext) {
<ide> mSurfaceId = surfaceId;
<ide>
<ide> mJSResponderHandler = jsResponderHandler;
<ide> mViewManagerRegistry = viewManagerRegistry;
<ide> mRootViewManager = rootViewManager;
<ide> mMountItemExecutor = mountItemExecutor;
<add> mThemedReactContext = reactContext;
<ide> }
<ide>
<ide> public boolean isStopped() { | 3 |
Ruby | Ruby | handle untarred bzip2 files | cb5da28b5cdf7a76e9e1220e6701b4b905ce04a3 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def stage
<ide> end
<ide> end
<ide> end
<add> when :bzip2_only
<add> with_system_path do
<add> target = File.basename(basename_without_params, ".bz2")
<add>
<add> IO.popen("bunzip2 -f '#{tarball_path}' -c") do |pipe|
<add> File.open(target, "wb") do |f|
<add> buf = ""
<add> f.write(buf) while pipe.read(1024, buf)
<add> end
<add> end
<add> end
<ide> when :gzip, :bzip2, :compress, :tar
<ide> # Assume these are also tarred
<ide> # TODO check if it's really a tar archive
<ide><path>Library/Homebrew/extend/pathname.rb
<ide> def compression_type
<ide> # If the filename ends with .gz not preceded by .tar
<ide> # then we want to gunzip but not tar
<ide> return :gzip_only
<add> when ".bz2"
<add> return :bzip2_only
<ide> end
<ide>
<ide> # Get enough of the file to detect common file types | 2 |
PHP | PHP | apply fixes from styleci | 105037b619bb1e180e79e2e0c634294d1859b406 | <ide><path>src/Illuminate/Foundation/Testing/DatabaseTransactions.php
<ide> public function beginDatabaseTransaction()
<ide> $connection->unsetEventDispatcher();
<ide> $connection->beginTransaction();
<ide> $connection->setEventDispatcher($dispatcher);
<del>
<add>
<ide> if ($this->app->resolved('db.transactions')) {
<ide> $this->app->make('db.transactions')->callbacksShouldIgnore(
<ide> $this->app->make('db.transactions')->getTransactions()->first() | 1 |
Go | Go | remove transaction id update from savemetadata() | 0db6cc85edfccb16ce5308eea767530e1a3f6906 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) allocateTransactionId() uint64 {
<ide> return devices.NewTransactionId
<ide> }
<ide>
<add>func (devices *DeviceSet) updatePoolTransactionId() error {
<add> if devices.NewTransactionId != devices.TransactionId {
<add> if err := devicemapper.SetTransactionId(devices.getPoolDevName(), devices.TransactionId, devices.NewTransactionId); err != nil {
<add> return fmt.Errorf("Error setting devmapper transaction ID: %s", err)
<add> }
<add> devices.TransactionId = devices.NewTransactionId
<add> }
<add> return nil
<add>}
<add>
<ide> func (devices *DeviceSet) removeMetadata(info *DevInfo) error {
<ide> if err := os.RemoveAll(devices.metadataFile(info)); err != nil {
<ide> return fmt.Errorf("Error removing metadata file %s: %s", devices.metadataFile(info), err)
<ide> func (devices *DeviceSet) saveMetadata(info *DevInfo) error {
<ide> if err := devices.writeMetaFile(jsonData, devices.metadataFile(info)); err != nil {
<ide> return err
<ide> }
<del>
<del> if devices.NewTransactionId != devices.TransactionId {
<del> if err = devicemapper.SetTransactionId(devices.getPoolDevName(), devices.TransactionId, devices.NewTransactionId); err != nil {
<del> return fmt.Errorf("Error setting devmapper transition ID: %s", err)
<del> }
<del> devices.TransactionId = devices.NewTransactionId
<del> }
<ide> return nil
<ide> }
<ide>
<ide> func (devices *DeviceSet) registerDevice(id int, hash string, size uint64) (*Dev
<ide> return nil, err
<ide> }
<ide>
<add> if err := devices.updatePoolTransactionId(); err != nil {
<add> // Remove unused device
<add> devices.devicesLock.Lock()
<add> delete(devices.Devices, hash)
<add> devices.devicesLock.Unlock()
<add> devices.removeMetadata(info)
<add> return nil, err
<add> }
<add>
<ide> return info, nil
<ide> }
<ide> | 1 |
Javascript | Javascript | collapse object initialization in xplat | e7d9e4dbb5cf8a9a5d615cd15e23ec107fa1ae1c | <ide><path>Libraries/Utilities/__tests__/stringifySafe-test.js
<ide> describe('stringifySafe', () => {
<ide> });
<ide>
<ide> it('stringifySafe stringifies circular objects with toString', () => {
<del> const arg = {};
<add> const arg: {arg?: {...}} = {...null};
<ide> arg.arg = arg;
<ide> const result = stringifySafe(arg);
<ide> expect(result).toEqual('[object Object]');
<ide><path>packages/react-native-codegen/src/parsers/flow/components/index.js
<ide> */
<ide>
<ide> 'use strict';
<del>import type {CommandOptions} from './options';
<ide> import type {TypeDeclarationMap} from '../utils';
<del>
<add>import type {CommandOptions} from './options';
<ide> import type {ComponentSchemaBuilderConfig} from './schema.js';
<add>
<add>const {getTypes} = require('../utils');
<ide> const {getCommands} = require('./commands');
<ide> const {getEvents} = require('./events');
<del>const {getProps, getPropProperties} = require('./props');
<del>const {getCommandOptions, getOptions} = require('./options');
<ide> const {getExtendsProps, removeKnownExtends} = require('./extends');
<del>const {getTypes} = require('../utils');
<add>const {getCommandOptions, getOptions} = require('./options');
<add>const {getPropProperties, getProps} = require('./props');
<ide>
<ide> function findComponentConfig(ast) {
<ide> const foundConfigs = [];
<ide> function findComponentConfig(ast) {
<ide> const typeArgumentParams = declaration.typeArguments.params;
<ide> const funcArgumentParams = declaration.arguments;
<ide>
<del> const nativeComponentType = {};
<del> nativeComponentType.propsTypeName = typeArgumentParams[0].id.name;
<del> nativeComponentType.componentName = funcArgumentParams[0].value;
<add> const nativeComponentType: {[string]: string} = {
<add> propsTypeName: typeArgumentParams[0].id.name,
<add> componentName: funcArgumentParams[0].value,
<add> };
<ide> if (funcArgumentParams.length > 1) {
<ide> nativeComponentType.optionsExpression = funcArgumentParams[1];
<ide> }
<ide><path>packages/react-native-codegen/src/parsers/typescript/components/index.js
<ide> */
<ide>
<ide> 'use strict';
<del>import type {CommandOptions} from './options';
<ide> import type {TypeDeclarationMap} from '../utils';
<del>
<add>import type {CommandOptions} from './options';
<ide> import type {ComponentSchemaBuilderConfig} from './schema.js';
<add>
<add>const {getTypes} = require('../utils');
<ide> const {getCommands} = require('./commands');
<ide> const {getEvents} = require('./events');
<del>const {getProps, getPropProperties} = require('./props');
<del>const {getCommandOptions, getOptions} = require('./options');
<ide> const {getExtendsProps, removeKnownExtends} = require('./extends');
<del>const {getTypes} = require('../utils');
<add>const {getCommandOptions, getOptions} = require('./options');
<add>const {getPropProperties, getProps} = require('./props');
<ide>
<ide> function findComponentConfig(ast) {
<ide> const foundConfigs = [];
<ide> function findComponentConfig(ast) {
<ide> const typeArgumentParams = declaration.typeParameters.params;
<ide> const funcArgumentParams = declaration.arguments;
<ide>
<del> const nativeComponentType = {};
<del> nativeComponentType.propsTypeName = typeArgumentParams[0].typeName.name;
<del> nativeComponentType.componentName = funcArgumentParams[0].value;
<add> const nativeComponentType: {[string]: string} = {
<add> propsTypeName: typeArgumentParams[0].typeName.name,
<add> componentName: funcArgumentParams[0].value,
<add> };
<ide> if (funcArgumentParams.length > 1) {
<ide> nativeComponentType.optionsExpression = funcArgumentParams[1];
<ide> } | 3 |
Ruby | Ruby | add test cases for #in? and #presence_in | f64819524716c14061914584db66ac2a3e1e72b2 | <ide><path>activesupport/test/core_ext/object/inclusion_test.rb
<ide> class B
<ide> end
<ide> class C < B
<ide> end
<add> class D
<add> end
<ide>
<ide> def test_in_module
<ide> assert A.in?(B)
<ide> assert A.in?(C)
<ide> assert !A.in?(A)
<add> assert !A.in?(D)
<ide> end
<ide>
<ide> def test_no_method_catching
<ide> def test_no_method_catching
<ide> def test_presence_in
<ide> assert_equal "stuff", "stuff".presence_in(%w( lots of stuff ))
<ide> assert_nil "stuff".presence_in(%w( lots of crap ))
<add> assert_raise(ArgumentError) { 1.presence_in(1) }
<ide> end
<ide> end | 1 |
Javascript | Javascript | pass user to api and foursquare api pages | 594760b2e6428d4cd36d879a5f5e73dec4cb43b6 | <ide><path>controllers/api.js
<ide> var foursquareAccessToken = 'MY_FOURSQUARE_ACCESS_TOKEN';
<ide>
<ide> exports.apiBrowser = function(req, res) {
<ide> res.render('api', {
<del> title: 'API Browser'
<add> title: 'API Browser',
<add> user: req.user
<ide> });
<ide> };
<ide>
<ide>
<ide> exports.foursquare = function(req, res) {
<ide>
<ide> res.render('api/foursquare', {
<del> title: 'Foursquare API'
<add> title: 'Foursquare API',
<add> user: req.user
<ide> });
<ide>
<ide> }; | 1 |
Ruby | Ruby | fix uninstallation of non-formula kegs | 8fbf3a43c39f74e75aae0530c3ef3a9aebe2cd59 | <ide><path>Library/Homebrew/cmd/uninstall.rb
<ide> def uninstall
<ide> keg.lock do
<ide> puts "Uninstalling #{keg}..."
<ide> keg.unlink
<del> Formula.factory(keg.fname).unpin
<ide> keg.uninstall
<ide> rm_opt_link keg.fname
<add> unpin keg.fname
<ide> end
<ide> end
<ide> else
<ide> def rm_opt_link name
<ide> optlink.unlink if optlink.symlink?
<ide> end
<ide>
<add> def unpin name
<add> Formula.factory(name).unpin rescue nil
<add> end
<ide> end | 1 |
Javascript | Javascript | pass the version info through the event | c9293e7733502c0551438a41633031c902ab43c6 | <ide><path>spec/auto-update-manager-spec.js
<ide> fdescribe('AutoUpdateManager (renderer)', () => {
<ide> it('subscribes to "did-complete-downloading-update" event', () => {
<ide> const spy = jasmine.createSpy('spy')
<ide> autoUpdateManager.onDidCompleteDownload(spy)
<del> electronAutoUpdater.emit('update-downloaded', null, null, {releaseVersion: '1.2.3'})
<add> electronAutoUpdater.emit('update-downloaded', null, null, '1.2.3')
<ide> waitsFor(() => {
<ide> return spy.callCount === 1
<ide> })
<add> runs(() => {
<add> expect(spy.mostRecentCall.args[0].releaseVersion).toBe('1.2.3')
<add> })
<ide> })
<ide> })
<ide>
<ide> fdescribe('AutoUpdateManager (renderer)', () => {
<ide> autoUpdateManager.onUpdateNotAvailable(spy)
<ide> electronAutoUpdater.emit('checking-for-update')
<ide> electronAutoUpdater.emit('update-available')
<del> electronAutoUpdater.emit('update-downloaded', null, null, {releaseVersion: '1.2.3'})
<add> electronAutoUpdater.emit('update-downloaded', null, null, '1.2.3')
<ide> electronAutoUpdater.emit('update-not-available')
<ide>
<ide> waitsFor(() => {
<ide><path>src/auto-update-manager.js
<ide> export default class AutoUpdateManager {
<ide> updateEventEmitter.onDidBeginCheckingForUpdate(() => {
<ide> this.emitter.emit('did-begin-checking-for-update')
<ide> }),
<del> updateEventEmitter.onDidCompleteDownloadingUpdate(() => {
<del> this.emitter.emit('did-complete-downloading-update')
<add> updateEventEmitter.onDidCompleteDownloadingUpdate((details) => {
<add> this.emitter.emit('did-complete-downloading-update', details)
<ide> }),
<ide> updateEventEmitter.onUpdateNotAvailable(() => {
<ide> this.emitter.emit('update-not-available') | 2 |
Ruby | Ruby | replace mentions of easy_install by pip | 33b2a29e1460ef307254dfab9a849dd972e5a5c8 | <ide><path>Library/Homebrew/blacklist.rb
<ide> def blacklisted? name
<ide> We recommend using a MacTeX distribution: http://www.tug.org/mactex/
<ide> EOS
<ide> when 'pip' then <<-EOS.undent
<del> Install pip with easy_install:
<del>
<del> easy_install pip
<add> pip is installed by `brew install python`
<ide> EOS
<ide> when 'macruby' then <<-EOS.undent
<ide> MacRuby works better when you install their package:
<ide><path>Library/Homebrew/dependencies.rb
<ide> def command_line
<ide> when :lua then "luarocks install"
<ide> when :node then "npm install"
<ide> when :perl then "cpan -i"
<del> when :python then "easy_install"
<add> when :python then "pip install"
<ide> when :rbx then "rbx gem install"
<ide> when :ruby then "gem install"
<ide> end | 2 |
PHP | PHP | simplify path logic | 8b1045a631cf146d7800fba26cdbbe97e15816c9 | <ide><path>lib/Cake/Console/Command/TestShell.php
<ide> protected function _mapFileToCase($file, $category) {
<ide> return false;
<ide> }
<ide>
<add> $_file = realpath($file);
<add> if ($_file) {
<add> $file = $_file;
<add> }
<add>
<ide> $testFile = $testCase = null;
<ide>
<ide> if (preg_match('@Test[\\\/]@', $file)) {
<ide> protected function _mapFileToCase($file, $category) {
<ide> return false;
<ide> }
<ide>
<del> $testFile = preg_replace(
<del> '@(.*)((?:(?:Config|Console|Controller|Lib|Locale|Model|plugins|Plugin|Test|Vendor|View|webroot)[\\\/]).*$|App[-a-z]*$)@',
<del> '\1Test/Case/\2Test.php',
<del> $file
<del> );
<add> if ($category === 'app') {
<add> $testFile = str_replace(APP, APP . 'Test/Case/', $file) . 'Test.php';
<add> } else {
<add> $testFile = preg_replace(
<add> "@((?:plugins|Plugin)[\\/]{$category}[\\/])(.*)$@",
<add> '\1Test/Case/\2Test.php',
<add> $file
<add> );
<add> }
<ide>
<ide> if (!file_exists($testFile)) {
<ide> throw new Exception(__d('cake_dev', 'Test case %s not found', $testFile)); | 1 |
Text | Text | update context menu doc | 7e52c860955bd8084282b52dac8302b06b06080a | <ide><path>docs/creating-a-package.md
<ide> elements until reaching the top of the DOM tree.
<ide> In the example above, the `Add file` item will only appear when the focused item
<ide> or one of its parents has the `tree-view` class applied to it.
<ide>
<del>You can also add separators and submenus to your context menus.
<del>To add a submenu, pass in a `context-menu` object instead of a command:
<add>You can also add separators and submenus to your context menus. To add a
<add>submenu, pass in another object instead of a command. To add a separator, use
<add>`-` for the name and command of the item.
<ide>
<ide> ```coffeescript
<ide> 'context-menu':
<del> '.tree-view':
<del> 'Files':
<del> 'Add file': 'tree-view:add-file'
<ide> '.workspace':
<ide> 'Inspect Element': 'core:inspect'
<del>```
<del>
<del>To add a separator, use a `'-': '-'` structure:
<del>
<del>```coffeescript
<del>'context-menu':
<del> '.tree-view':
<del> 'Add file': 'tree-view:add-file'
<ide> '-': '-'
<del> 'Remove file': 'tree-view:remove-file'
<del> '.workspace':
<del> 'Inspect Element': 'core:inspect'
<add> 'Text':
<add> 'Select All': 'core:select-all'
<add> 'Deleted Selected Text': 'core:delete'
<ide> ```
<ide>
<ide> ## Snippets | 1 |
Python | Python | show less messages in --help-fcompiler | 24b8ecc423d48a06af98be34e97ebda4fee397bc | <ide><path>numpy/distutils/command/config_compiler.py
<ide> def show_fortran_compilers(_cache=[]):
<ide> # Using cache to prevent infinite recursion
<ide> if _cache: return
<ide> _cache.append(1)
<del>
<add> log.set_verbosity(-2)
<ide> from numpy.distutils.fcompiler import show_fcompilers
<ide> import distutils.core
<ide> dist = distutils.core._setup_distribution | 1 |
Javascript | Javascript | count space for line numbers correctly | 5b230007adba91163a2f49dbdd9a16d5834fd322 | <ide><path>lib/_debugger.js
<ide> Interface.prototype.debugEval = function(code, context, filename, callback) {
<ide>
<ide> // Utils
<ide>
<del>// Returns number of digits (+1)
<del>function intChars(n) {
<del> // TODO dumb:
<del> if (n < 50) {
<del> return 3;
<del> } else if (n < 950) {
<del> return 4;
<del> } else if (n < 9950) {
<del> return 5;
<del> } else {
<del> return 6;
<del> }
<del>}
<del>
<ide> // Adds spaces and prefix to number
<del>function leftPad(n, prefix) {
<add>// maxN is a maximum number we should have space for
<add>function leftPad(n, prefix, maxN) {
<ide> var s = n.toString(),
<del> nchars = intChars(n),
<add> nchars = Math.max(2, String(maxN).length) + 1,
<ide> nspaces = nchars - s.length - 1;
<ide>
<del> prefix || (prefix = ' ');
<del>
<ide> for (var i = 0; i < nspaces; i++) {
<ide> prefix += ' ';
<ide> }
<ide> Interface.prototype.list = function(delta) {
<ide> prefixChar = '*';
<ide> }
<ide>
<del> self.print(leftPad(lineno, prefixChar) + ' ' + line);
<add> self.print(leftPad(lineno, prefixChar, to) + ' ' + line);
<ide> }
<ide> self.resume();
<ide> });
<ide> Interface.prototype.watchers = function() {
<ide> if (verbose) self.print('Watchers:');
<ide>
<ide> self._watchers.forEach(function(watcher, i) {
<del> self.print(leftPad(i, ' ') + ': ' + watcher + ' = ' +
<add> self.print(leftPad(i, ' ', self._watchers.length - 1) +
<add> ': ' + watcher + ' = ' +
<ide> JSON.stringify(values[i]));
<ide> });
<ide> | 1 |
Javascript | Javascript | improve read() performance further | 382f84a7f87296fe81e247051ccfc830d71fabca | <ide><path>lib/internal/streams/buffer_list.js
<ide> module.exports = class BufferList {
<ide>
<ide> // Consumes a specified amount of bytes or characters from the buffered data.
<ide> consume(n, hasStrings) {
<del> var ret;
<del> if (n < this.head.data.length) {
<add> const data = this.head.data;
<add> if (n < data.length) {
<ide> // `slice` is the same for buffers and strings.
<del> ret = this.head.data.slice(0, n);
<del> this.head.data = this.head.data.slice(n);
<del> } else if (n === this.head.data.length) {
<add> const slice = data.slice(0, n);
<add> this.head.data = data.slice(n);
<add> return slice;
<add> }
<add> if (n === data.length) {
<ide> // First chunk is a perfect match.
<del> ret = this.shift();
<del> } else {
<del> // Result spans more than one buffer.
<del> ret = hasStrings ? this._getString(n) : this._getBuffer(n);
<add> return this.shift();
<ide> }
<del> return ret;
<add> // Result spans more than one buffer.
<add> return hasStrings ? this._getString(n) : this._getBuffer(n);
<ide> }
<ide>
<ide> first() { | 1 |
Javascript | Javascript | use defined function to remove duplicates | 2f143e0ff0e292261915cff52a4350ba1bb4a46f | <ide><path>packages/ember-metal/lib/computed.js
<ide> function keysForDep(obj, depsMeta, depKey) {
<ide>
<ide> /* return obj[META_KEY].deps */
<ide> function metaForDeps(obj, meta) {
<del> var deps = meta.deps;
<del> // If the current object has no dependencies...
<del> if (!deps) {
<del> // initialize the dependencies with a pointer back to
<del> // the current object
<del> deps = meta.deps = {};
<del> } else if (!meta.hasOwnProperty('deps')) {
<del> // otherwise if the dependencies are inherited from the
<del> // object's superclass, clone the deps
<del> deps = meta.deps = o_create(deps);
<del> }
<del> return deps;
<add> return keysForDep(obj, meta, 'deps');
<ide> }
<ide>
<ide> function addDependentKeys(desc, obj, keyName, meta) { | 1 |
Go | Go | use prefix naming for rm tests | cc54b77fce1ab0d6bfa78947ee46ffdd104f21c5 | <ide><path>integration-cli/docker_cli_rm_test.go
<ide> import (
<ide> "testing"
<ide> )
<ide>
<del>func TestRemoveContainerWithRemovedVolume(t *testing.T) {
<add>func TestRmContainerWithRemovedVolume(t *testing.T) {
<ide> cmd := exec.Command(dockerBinary, "run", "--name", "losemyvolumes", "-v", "/tmp/testing:/test", "busybox", "true")
<ide> if _, err := runCommand(cmd); err != nil {
<ide> t.Fatal(err)
<ide> func TestRemoveContainerWithRemovedVolume(t *testing.T) {
<ide> logDone("rm - removed volume")
<ide> }
<ide>
<del>func TestRemoveContainerWithVolume(t *testing.T) {
<add>func TestRmContainerWithVolume(t *testing.T) {
<ide> cmd := exec.Command(dockerBinary, "run", "--name", "foo", "-v", "/srv", "busybox", "true")
<ide> if _, err := runCommand(cmd); err != nil {
<ide> t.Fatal(err)
<ide> func TestRemoveContainerWithVolume(t *testing.T) {
<ide> logDone("rm - volume")
<ide> }
<ide>
<del>func TestRemoveRunningContainer(t *testing.T) {
<add>func TestRmRunningContainer(t *testing.T) {
<ide> createRunningContainer(t, "foo")
<ide>
<ide> // Test cannot remove running container
<ide> func TestRemoveRunningContainer(t *testing.T) {
<ide> logDone("rm - running container")
<ide> }
<ide>
<del>func TestForceRemoveRunningContainer(t *testing.T) {
<add>func TestRmForceRemoveRunningContainer(t *testing.T) {
<ide> createRunningContainer(t, "foo")
<ide>
<ide> // Stop then remove with -s
<ide> func TestForceRemoveRunningContainer(t *testing.T) {
<ide> logDone("rm - running container with --force=true")
<ide> }
<ide>
<del>func TestContainerOrphaning(t *testing.T) {
<add>func TestRmContainerOrphaning(t *testing.T) {
<ide> dockerfile1 := `FROM busybox:latest
<ide> ENTRYPOINT ["/bin/true"]`
<ide> img := "test-container-orphaning"
<ide> func TestContainerOrphaning(t *testing.T) {
<ide> logDone("rm - container orphaning")
<ide> }
<ide>
<del>func TestDeleteTagWithExistingContainers(t *testing.T) {
<add>func TestRmTagWithExistingContainers(t *testing.T) {
<ide> container := "test-delete-tag"
<ide> newtag := "busybox:newtag"
<ide> bb := "busybox:latest" | 1 |
Javascript | Javascript | improve .inspect() array grouping | 87a22cff77f923d69797c29a766b21f63f8dc5a9 | <ide><path>lib/internal/util/inspect.js
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> }
<ide>
<ide> const res = reduceToSingleString(
<del> ctx, output, base, braces, extrasType, recurseTimes);
<add> ctx, output, base, braces, extrasType, recurseTimes, value);
<ide> const budget = ctx.budget[ctx.indentationLvl] || 0;
<ide> const newLength = budget + res.length;
<ide> ctx.budget[ctx.indentationLvl] = newLength;
<ide> function formatError(err, constructor, tag, ctx) {
<ide> return stack;
<ide> }
<ide>
<del>function groupArrayElements(ctx, output) {
<add>function groupArrayElements(ctx, output, value) {
<ide> let totalLength = 0;
<ide> let maxLength = 0;
<ide> let i = 0;
<ide> function groupArrayElements(ctx, output) {
<ide> (totalLength / actualMax > 5 || maxLength <= 6)) {
<ide>
<ide> const approxCharHeights = 2.5;
<del> const bias = 1;
<add> const biasedMax = Math.max(actualMax - 4, 1);
<ide> // Dynamically check how many columns seem possible.
<ide> const columns = Math.min(
<ide> // Ideally a square should be drawn. We expect a character to be about 2.5
<ide> // times as high as wide. This is the area formula to calculate a square
<ide> // which contains n rectangles of size `actualMax * approxCharHeights`.
<ide> // Divide that by `actualMax` to receive the correct number of columns.
<del> // The added bias slightly increases the columns for short entries.
<add> // The added bias increases the columns for short entries.
<ide> Math.round(
<ide> Math.sqrt(
<del> approxCharHeights * (actualMax - bias) * outputLength
<del> ) / (actualMax - bias)
<add> approxCharHeights * biasedMax * outputLength
<add> ) / biasedMax
<ide> ),
<ide> // Do not exceed the breakLength.
<ide> Math.floor((ctx.breakLength - ctx.indentationLvl) / actualMax),
<ide> // Limit array grouping for small `compact` modes as the user requested
<ide> // minimal grouping.
<del> ctx.compact * 3,
<del> // Limit the columns to a maximum of ten.
<del> 10
<add> ctx.compact * 4,
<add> // Limit the columns to a maximum of fifteen.
<add> 15
<ide> );
<ide> // Return with the original output if no grouping should happen.
<ide> if (columns <= 1) {
<ide> return output;
<ide> }
<del> // Calculate the maximum length of all entries that are visible in the first
<del> // column of the group.
<ide> const tmp = [];
<del> let firstLineMaxLength = dataLen[0];
<del> for (i = columns; i < dataLen.length; i += columns) {
<del> if (dataLen[i] > firstLineMaxLength)
<del> firstLineMaxLength = dataLen[i];
<add> const maxLineLength = [];
<add> for (let i = 0; i < columns; i++) {
<add> let lineMaxLength = 0;
<add> for (let j = i; j < output.length; j += columns) {
<add> if (dataLen[j] > lineMaxLength)
<add> lineMaxLength = dataLen[j];
<add> }
<add> lineMaxLength += separatorSpace;
<add> maxLineLength[i] = lineMaxLength;
<add> }
<add> let order = 'padStart';
<add> if (value !== undefined) {
<add> for (let i = 0; i < output.length; i++) {
<add> // eslint-disable-next-line valid-typeof
<add> if (typeof value[i] !== 'number' && typeof value[i] !== 'bigint') {
<add> order = 'padEnd';
<add> break;
<add> }
<add> }
<ide> }
<ide> // Each iteration creates a single line of grouped entries.
<del> for (i = 0; i < outputLength; i += columns) {
<del> // Calculate extra color padding in case it's active. This has to be done
<del> // line by line as some lines might contain more colors than others.
<del> let colorPadding = output[i].length - dataLen[i];
<del> // Add padding to the first column of the output.
<del> let str = output[i].padStart(firstLineMaxLength + colorPadding, ' ');
<add> for (let i = 0; i < outputLength; i += columns) {
<ide> // The last lines may contain less entries than columns.
<ide> const max = Math.min(i + columns, outputLength);
<del> for (var j = i + 1; j < max; j++) {
<del> colorPadding = output[j].length - dataLen[j];
<del> str += `, ${output[j].padStart(maxLength + colorPadding, ' ')}`;
<add> let str = '';
<add> let j = i;
<add> for (; j < max - 1; j++) {
<add> // Calculate extra color padding in case it's active. This has to be
<add> // done line by line as some lines might contain more colors than
<add> // others.
<add> const padding = maxLineLength[j - i] + output[j].length - dataLen[j];
<add> str += `${output[j]}, `[order](padding, ' ');
<add> }
<add> if (order === 'padStart') {
<add> const padding = maxLineLength[j - i] +
<add> output[j].length -
<add> dataLen[j] -
<add> separatorSpace;
<add> str += output[j].padStart(padding, ' ');
<add> } else {
<add> str += output[j];
<ide> }
<ide> tmp.push(str);
<ide> }
<ide> function isBelowBreakLength(ctx, output, start, base) {
<ide> }
<ide>
<ide> function reduceToSingleString(
<del> ctx, output, base, braces, extrasType, recurseTimes) {
<add> ctx, output, base, braces, extrasType, recurseTimes, value) {
<ide> if (ctx.compact !== true) {
<ide> if (typeof ctx.compact === 'number' && ctx.compact >= 1) {
<ide> // Memorize the original output length. In case the the output is grouped,
<ide> function reduceToSingleString(
<ide> // Group array elements together if the array contains at least six
<ide> // separate entries.
<ide> if (extrasType === kArrayExtrasType && entries > 6) {
<del> output = groupArrayElements(ctx, output);
<add> output = groupArrayElements(ctx, output, value);
<ide> }
<ide> // `ctx.currentDepth` is set to the most inner depth of the currently
<ide> // inspected object part while `recurseTimes` is the actual current depth
<ide><path>test/parallel/test-util-inspect.js
<ide> if (typeof Symbol !== 'undefined') {
<ide> {
<ide> const x = new Uint8Array(101);
<ide> assert(util.inspect(x).endsWith('1 more item\n]'));
<del> assert(!util.inspect(x, { maxArrayLength: 101 }).endsWith('1 more item\n]'));
<add> assert(!util.inspect(x, { maxArrayLength: 101 }).includes('1 more item'));
<ide> assert.strictEqual(util.inspect(x, { maxArrayLength: 0 }),
<ide> 'Uint8Array [ ... 101 more items ]');
<del> assert(!util.inspect(x, { maxArrayLength: null }).endsWith('1 more item\n]'));
<del> assert(util.inspect(x, { maxArrayLength: Infinity }).endsWith(' 0, 0\n]'));
<add> assert(!util.inspect(x, { maxArrayLength: null }).includes('1 more item'));
<add> assert(util.inspect(x, { maxArrayLength: Infinity }).endsWith(' 0, 0\n]'));
<ide> }
<ide>
<ide> {
<ide> assert.strictEqual(util.inspect('"\'${a}'), "'\"\\'${a}'");
<ide> [WeakMap, [[[{}, {}]]], '{ <items unknown> }'],
<ide> [BigInt64Array,
<ide> [10],
<del> '[\n 0n, 0n, 0n,\n 0n, 0n, 0n,\n 0n, 0n, 0n,\n 0n\n]'],
<add> '[\n 0n, 0n, 0n, 0n, 0n,\n 0n, 0n, 0n, 0n, 0n\n]'],
<ide> [Date, ['Sun, 14 Feb 2010 11:48:40 GMT'], '2010-02-14T11:48:40.000Z'],
<ide> [Date, ['invalid_date'], 'Invalid Date']
<ide> ].forEach(([base, input, rawExpected]) => {
<ide> assert.strictEqual(
<ide> ' b: [ 1, 2, [ 1, 2, { a: 1, b: 2, c: 3 } ] ],',
<ide> " c: [ 'foo', 4, 444444 ],",
<ide> ' d: [',
<del> ' 0, 1, 4, 3, 16, 5, 36,',
<del> ' 7, 64, 9, 100, 11, 144, 13,',
<del> ' 196, 15, 256, 17, 324, 19, 400,',
<del> ' 21, 484, 23, 576, 25, 676, 27,',
<del> ' 784, 29, 900, 31, 1024, 33, 1156,',
<del> ' 35, 1296, 37, 1444, 39, 1600, 41,',
<del> ' 1764, 43, 1936, 45, 2116, 47, 2304,',
<del> ' 49, 2500, 51, 2704, 53, 2916, 55,',
<del> ' 3136, 57, 3364, 59, 3600, 61, 3844,',
<del> ' 63, 4096, 65, 4356, 67, 4624, 69,',
<del> ' 4900, 71, 5184, 73, 5476, 75, 5776,',
<del> ' 77, 6084, 79, 6400, 81, 6724, 83,',
<del> ' 7056, 85, 7396, 87, 7744, 89, 8100,',
<del> ' 91, 8464, 93, 8836, 95, 9216, 97,',
<del> ' 9604, 99,',
<add> ' 0, 1, 4, 3, 16, 5, 36, 7, 64,',
<add> ' 9, 100, 11, 144, 13, 196, 15, 256, 17,',
<add> ' 324, 19, 400, 21, 484, 23, 576, 25, 676,',
<add> ' 27, 784, 29, 900, 31, 1024, 33, 1156, 35,',
<add> ' 1296, 37, 1444, 39, 1600, 41, 1764, 43, 1936,',
<add> ' 45, 2116, 47, 2304, 49, 2500, 51, 2704, 53,',
<add> ' 2916, 55, 3136, 57, 3364, 59, 3600, 61, 3844,',
<add> ' 63, 4096, 65, 4356, 67, 4624, 69, 4900, 71,',
<add> ' 5184, 73, 5476, 75, 5776, 77, 6084, 79, 6400,',
<add> ' 81, 6724, 83, 7056, 85, 7396, 87, 7744, 89,',
<add> ' 8100, 91, 8464, 93, 8836, 95, 9216, 97, 9604,',
<add> ' 99,',
<ide> ' ... 1 more item',
<ide> ' ],',
<ide> ' e: [',
<ide> assert.strictEqual(
<ide> " 'foobar baz'",
<ide> ' ],',
<ide> ' h: [',
<del> ' 100, 0, 1,',
<del> ' 2, 3, 4,',
<del> ' 5, 6, 7,',
<del> ' 8',
<add> ' 100, 0, 1, 2, 3,',
<add> ' 4, 5, 6, 7, 8',
<ide> ' ],',
<ide> ' long: [',
<ide> " 'This text is too long for grouping!',",
<ide> assert.strictEqual(
<ide>
<ide> expected = [
<ide> '[',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 1,',
<del> ' 1, 1, 123456789',
<add> ' 1, 1, 1,',
<add> ' 1, 1, 1,',
<add> ' 1, 1, 1,',
<add> ' 1, 1, 1,',
<add> ' 1, 1, 1,',
<add> ' 1, 1, 1,',
<add> ' 1, 1, 1,',
<add> ' 1, 1, 1,',
<add> ' 1, 1, 123456789',
<ide> ']'
<ide> ].join('\n');
<ide>
<ide> assert.strictEqual(
<ide> ' b: { x: \u001b[33m5\u001b[39m, c: \u001b[36m[Object]\u001b[39m }',
<ide> ' },',
<ide> ' b: [',
<del> " \u001b[32m'foobar'\u001b[39m, \u001b[32m'baz'\u001b[39m,",
<del> " \u001b[32m'foobar'\u001b[39m, \u001b[32m'baz'\u001b[39m,",
<del> " \u001b[32m'foobar'\u001b[39m, \u001b[32m'baz'\u001b[39m,",
<del> " \u001b[32m'foobar'\u001b[39m, \u001b[32m'baz'\u001b[39m,",
<add> " \u001b[32m'foobar'\u001b[39m, \u001b[32m'baz'\u001b[39m,",
<add> " \u001b[32m'foobar'\u001b[39m, \u001b[32m'baz'\u001b[39m,",
<add> " \u001b[32m'foobar'\u001b[39m, \u001b[32m'baz'\u001b[39m,",
<add> " \u001b[32m'foobar'\u001b[39m, \u001b[32m'baz'\u001b[39m,",
<ide> " \u001b[32m'foobar'\u001b[39m",
<ide> ' ]',
<ide> '}',
<ide> assert.strictEqual(
<ide>
<ide> expected = [
<ide> '[',
<del> ' \u001b[33m0\u001b[39m, \u001b[33m1\u001b[39m, \u001b[33m2\u001b[39m,',
<del> ' \u001b[33m3\u001b[39m, \u001b[33m4\u001b[39m, \u001b[33m5\u001b[39m,',
<del> ' \u001b[33m6\u001b[39m, \u001b[33m7\u001b[39m, \u001b[33m8\u001b[39m,',
<del> ' \u001b[33m9\u001b[39m, \u001b[33m10\u001b[39m, \u001b[33m11\u001b[39m,',
<del> ' \u001b[33m12\u001b[39m, \u001b[33m13\u001b[39m, \u001b[33m14\u001b[39m,',
<del> ' \u001b[33m15\u001b[39m, \u001b[33m16\u001b[39m, \u001b[33m17\u001b[39m,',
<del> ' \u001b[33m18\u001b[39m, \u001b[33m19\u001b[39m, \u001b[33m20\u001b[39m,',
<del> ' \u001b[33m21\u001b[39m, \u001b[33m22\u001b[39m, \u001b[33m23\u001b[39m,',
<del> ' \u001b[33m24\u001b[39m, \u001b[33m25\u001b[39m, \u001b[33m26\u001b[39m,',
<del> ' \u001b[33m27\u001b[39m, \u001b[33m28\u001b[39m, \u001b[33m29\u001b[39m,',
<del> ' \u001b[33m30\u001b[39m, \u001b[33m31\u001b[39m, \u001b[33m32\u001b[39m,',
<del> ' \u001b[33m33\u001b[39m, \u001b[33m34\u001b[39m, \u001b[33m35\u001b[39m,',
<del> ' \u001b[33m36\u001b[39m, \u001b[33m37\u001b[39m, \u001b[33m38\u001b[39m,',
<del> ' \u001b[33m39\u001b[39m, \u001b[33m40\u001b[39m, \u001b[33m41\u001b[39m,',
<del> ' \u001b[33m42\u001b[39m, \u001b[33m43\u001b[39m, \u001b[33m44\u001b[39m,',
<del> ' \u001b[33m45\u001b[39m, \u001b[33m46\u001b[39m, \u001b[33m47\u001b[39m,',
<del> ' \u001b[33m48\u001b[39m, \u001b[33m49\u001b[39m, \u001b[33m50\u001b[39m,',
<del> ' \u001b[33m51\u001b[39m, \u001b[33m52\u001b[39m, \u001b[33m53\u001b[39m,',
<del> ' \u001b[33m54\u001b[39m, \u001b[33m55\u001b[39m, \u001b[33m56\u001b[39m,',
<del> ' \u001b[33m57\u001b[39m, \u001b[33m58\u001b[39m, \u001b[33m59\u001b[39m',
<add> /* eslint-disable max-len */
<add> ' \u001b[33m0\u001b[39m, \u001b[33m1\u001b[39m, \u001b[33m2\u001b[39m, \u001b[33m3\u001b[39m,',
<add> ' \u001b[33m4\u001b[39m, \u001b[33m5\u001b[39m, \u001b[33m6\u001b[39m, \u001b[33m7\u001b[39m,',
<add> ' \u001b[33m8\u001b[39m, \u001b[33m9\u001b[39m, \u001b[33m10\u001b[39m, \u001b[33m11\u001b[39m,',
<add> ' \u001b[33m12\u001b[39m, \u001b[33m13\u001b[39m, \u001b[33m14\u001b[39m, \u001b[33m15\u001b[39m,',
<add> ' \u001b[33m16\u001b[39m, \u001b[33m17\u001b[39m, \u001b[33m18\u001b[39m, \u001b[33m19\u001b[39m,',
<add> ' \u001b[33m20\u001b[39m, \u001b[33m21\u001b[39m, \u001b[33m22\u001b[39m, \u001b[33m23\u001b[39m,',
<add> ' \u001b[33m24\u001b[39m, \u001b[33m25\u001b[39m, \u001b[33m26\u001b[39m, \u001b[33m27\u001b[39m,',
<add> ' \u001b[33m28\u001b[39m, \u001b[33m29\u001b[39m, \u001b[33m30\u001b[39m, \u001b[33m31\u001b[39m,',
<add> ' \u001b[33m32\u001b[39m, \u001b[33m33\u001b[39m, \u001b[33m34\u001b[39m, \u001b[33m35\u001b[39m,',
<add> ' \u001b[33m36\u001b[39m, \u001b[33m37\u001b[39m, \u001b[33m38\u001b[39m, \u001b[33m39\u001b[39m,',
<add> ' \u001b[33m40\u001b[39m, \u001b[33m41\u001b[39m, \u001b[33m42\u001b[39m, \u001b[33m43\u001b[39m,',
<add> ' \u001b[33m44\u001b[39m, \u001b[33m45\u001b[39m, \u001b[33m46\u001b[39m, \u001b[33m47\u001b[39m,',
<add> ' \u001b[33m48\u001b[39m, \u001b[33m49\u001b[39m, \u001b[33m50\u001b[39m, \u001b[33m51\u001b[39m,',
<add> ' \u001b[33m52\u001b[39m, \u001b[33m53\u001b[39m, \u001b[33m54\u001b[39m, \u001b[33m55\u001b[39m,',
<add> ' \u001b[33m56\u001b[39m, \u001b[33m57\u001b[39m, \u001b[33m58\u001b[39m, \u001b[33m59\u001b[39m',
<add> /* eslint-enable max-len */
<ide> ']'
<ide> ].join('\n');
<ide>
<ide> assert.strictEqual(
<ide> );
<ide> expected = [
<ide> '[',
<del> " 'Object', 'Function', 'Array',",
<del> " 'Number', 'parseFloat', 'parseInt',",
<del> " 'Infinity', 'NaN', 'undefined',",
<del> " 'Boolean', 'String', 'Symbol',",
<del> " 'Date', 'Promise', 'RegExp',",
<del> " 'Error', 'EvalError', 'RangeError',",
<del> " 'ReferenceError', 'SyntaxError', 'TypeError',",
<del> " 'URIError', 'JSON', 'Math',",
<del> " 'console', 'Intl', 'ArrayBuffer',",
<del> " 'Uint8Array', 'Int8Array', 'Uint16Array',",
<del> " 'Int16Array', 'Uint32Array', 'Int32Array',",
<del> " 'Float32Array', 'Float64Array', 'Uint8ClampedArray',",
<del> " 'BigUint64Array', 'BigInt64Array', 'DataView',",
<del> " 'Map', 'BigInt', 'Set',",
<del> " 'WeakMap', 'WeakSet', 'Proxy',",
<del> " 'Reflect', 'decodeURI', 'decodeURIComponent',",
<del> " 'encodeURI', 'encodeURIComponent', 'escape',",
<del> " 'unescape', 'eval', 'isFinite',",
<del> " 'isNaN', 'SharedArrayBuffer', 'Atomics',",
<del> " 'globalThis', 'WebAssembly', 'global',",
<del> " 'process', 'GLOBAL', 'root',",
<del> " 'Buffer', 'URL', 'URLSearchParams',",
<del> " 'TextEncoder', 'TextDecoder', 'clearInterval',",
<del> " 'clearTimeout', 'setInterval', 'setTimeout',",
<del> " 'queueMicrotask', 'clearImmediate', 'setImmediate',",
<del> " 'module', 'require', 'assert',",
<del> " 'async_hooks', 'buffer', 'child_process',",
<del> " 'cluster', 'crypto', 'dgram',",
<del> " 'dns', 'domain', 'events',",
<del> " 'fs', 'http', 'http2',",
<del> " 'https', 'inspector', 'net',",
<del> " 'os', 'path', 'perf_hooks',",
<del> " 'punycode', 'querystring', 'readline',",
<del> " 'repl', 'stream', 'string_decoder',",
<del> " 'tls', 'trace_events', 'tty',",
<del> " 'url', 'v8', 'vm',",
<del> " 'worker_threads', 'zlib', '_',",
<del> " '_error', 'util'",
<add> " 'Object', 'Function', 'Array',",
<add> " 'Number', 'parseFloat', 'parseInt',",
<add> " 'Infinity', 'NaN', 'undefined',",
<add> " 'Boolean', 'String', 'Symbol',",
<add> " 'Date', 'Promise', 'RegExp',",
<add> " 'Error', 'EvalError', 'RangeError',",
<add> " 'ReferenceError', 'SyntaxError', 'TypeError',",
<add> " 'URIError', 'JSON', 'Math',",
<add> " 'console', 'Intl', 'ArrayBuffer',",
<add> " 'Uint8Array', 'Int8Array', 'Uint16Array',",
<add> " 'Int16Array', 'Uint32Array', 'Int32Array',",
<add> " 'Float32Array', 'Float64Array', 'Uint8ClampedArray',",
<add> " 'BigUint64Array', 'BigInt64Array', 'DataView',",
<add> " 'Map', 'BigInt', 'Set',",
<add> " 'WeakMap', 'WeakSet', 'Proxy',",
<add> " 'Reflect', 'decodeURI', 'decodeURIComponent',",
<add> " 'encodeURI', 'encodeURIComponent', 'escape',",
<add> " 'unescape', 'eval', 'isFinite',",
<add> " 'isNaN', 'SharedArrayBuffer', 'Atomics',",
<add> " 'globalThis', 'WebAssembly', 'global',",
<add> " 'process', 'GLOBAL', 'root',",
<add> " 'Buffer', 'URL', 'URLSearchParams',",
<add> " 'TextEncoder', 'TextDecoder', 'clearInterval',",
<add> " 'clearTimeout', 'setInterval', 'setTimeout',",
<add> " 'queueMicrotask', 'clearImmediate', 'setImmediate',",
<add> " 'module', 'require', 'assert',",
<add> " 'async_hooks', 'buffer', 'child_process',",
<add> " 'cluster', 'crypto', 'dgram',",
<add> " 'dns', 'domain', 'events',",
<add> " 'fs', 'http', 'http2',",
<add> " 'https', 'inspector', 'net',",
<add> " 'os', 'path', 'perf_hooks',",
<add> " 'punycode', 'querystring', 'readline',",
<add> " 'repl', 'stream', 'string_decoder',",
<add> " 'tls', 'trace_events', 'tty',",
<add> " 'url', 'v8', 'vm',",
<add> " 'worker_threads', 'zlib', '_',",
<add> " '_error', 'util'",
<ide> ']'
<ide> ].join('\n');
<ide> | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.