text:
package mock.media;

import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.rtp.*;
import org.jitsi.impl.neomedia.transform.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.device.*;
import org.jitsi.service.neomedia.format.*;
import org.jitsi.service.neomedia.rtp.*;

import java.net.*;
import java.util.*;

/**
 *
 * @author Pawel Domas
 * @author Lyubomir Marinov
 */
public class MockMediaStream
    extends AbstractMediaStream
{
    private MockMediaStreamStats streamStats = new MockMediaStreamStats();

    @Override
    public void addDynamicRTPPayloadType(byte rtpPayloadType,
                                         MediaFormat format)
    {
    }

    @Override
    public void addDynamicRTPPayloadTypeOverride(byte originalPt,
                                                 byte overloadPt)
    {
    }

    @Override
    public void addRTPExtension(byte extensionID, RTPExtension rtpExtension)
    {
    }

    @Override
    public void clearDynamicRTPPayloadTypes()
    {
    }

    @Override
    public void close()
    {
    }

    @Override
    public void configureSSRCRewriting(
            Set<Integer> ssrcGroup,
            Integer ssrcTargetPrimary,
            Map<Integer, Byte> ssrc2fec,
            Map<Integer, Byte> ssrc2red,
            Map<Integer, Integer> rtxGroups,
            Integer ssrcTargetRTX)
    {
    }

    @Override
    public RawPacketCache getPacketCache()
    {
        return null;
    }

    @Override
    public RetransmissionRequester getRetransmissionRequester()
    {
        return null;
    }

    @Override
    public Map<Byte, RTPExtension> getActiveRTPExtensions()
    {
        return null;
    }

    @Override
    public MediaDevice getDevice()
    {
        return null;
    }

    @Override
    public MediaDirection getDirection()
    {
        return null;
    }

    @Override
    public Map<Byte, MediaFormat> getDynamicRTPPayloadTypes()
    {
        return new HashMap<>();
    }

    @Override
    public MediaFormat getFormat()
    {
        return null;
    }

    @Override
    public long getLocalSourceID()
    {
        return 0;
    }

    @Override
    public MediaStreamStats getMediaStreamStats()
    {
        return streamStats;
    }

    @Override
    public InetSocketAddress getRemoteControlAddress()
    {
        return null;
    }

    @Override
    public InetSocketAddress getRemoteDataAddress()
    {
        return null;
    }

    @Override
    public long getRemoteSourceID()
    {
        return 0;
    }

    @Override
    public List<Long> getRemoteSourceIDs()
    {
        return null;
    }

    @Override
    public SrtpControl getSrtpControl()
    {
        return null;
    }

    @Override
    public StreamRTPManager getStreamRTPManager()
    {
        return null;
    }

    @Override
    public MediaStreamTarget getTarget()
    {
        return null;
    }

    @Override
    public StreamConnector.Protocol getTransportProtocol()
    {
        return null;
    }

    @Override
    public void injectPacket(RawPacket pkt, boolean data, TransformEngine after)
    {
    }

    @Override
    public boolean isMute()
    {
        return false;
    }

    @Override
    public boolean isStarted()
    {
        return false;
    }

    @Override
    public void removeReceiveStreamForSsrc(long ssrc)
    {
    }

    @Override
    public void setConnector(StreamConnector connector)
    {
    }

    @Override
    public void setDevice(MediaDevice device)
    {
    }

    @Override
    public void setDirection(MediaDirection direction)
    {
    }

    @Override
    public void setExternalTransformer(TransformEngine transformEngine)
    {
    }

    @Override
    public void setFormat(MediaFormat format)
    {
    }

    @Override
    public void setMute(boolean mute)
    {
    }

    @Override
    public void setRTPTranslator(RTPTranslator rtpTranslator)
    {
    }

    @Override
    public void setSSRCFactory(SSRCFactory ssrcFactory)
    {
    }

    @Override
    public void setTarget(MediaStreamTarget target)
    {
    }

    @Override
    public void start()
    {
    }

    @Override
    public void stop()
    {
    }
}


text:
package com.microsoft.azure.management.mediaservices.v2018_30_30_preview.implementation;

import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.management.mediaservices.v2018_30_30_preview.ApiErrorException;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.Path;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * An instance of this class provides access to all the operations defined
 * in LiveOutputs.
 */
public class LiveOutputsInner {
    /** The Retrofit service to perform REST calls. */
    private LiveOutputsService service;
    /** The service client containing this operation class. */
    private AzureMediaServicesImpl client;

    /**
     * Initializes an instance of LiveOutputsInner.
     *
     * @param retrofit the Retrofit instance built from a Retrofit Builder.
     * @param client the instance of the service client containing this operation class.
     */
    public LiveOutputsInner(Retrofit retrofit, AzureMediaServicesImpl client) {
        this.service = retrofit.create(LiveOutputsService.class);
        this.client = client;
    }

    /**
     * The interface defining all the services for LiveOutputs to be
     * used by Retrofit to perform actually REST calls.
     */
    interface LiveOutputsService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.LiveOutputs list" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs")
        Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("liveEventName") String liveEventName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.LiveOutputs get" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs/{liveOutputName}")
        Observable<Response<ResponseBody>> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("liveEventName") String liveEventName, @Path("liveOutputName") String liveOutputName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.LiveOutputs create" })
        @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs/{liveOutputName}")
        Observable<Response<ResponseBody>> create(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("liveEventName") String liveEventName, @Path("liveOutputName") String liveOutputName, @Query("api-version") String apiVersion, @Body LiveOutputInner parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.LiveOutputs beginCreate" })
        @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs/{liveOutputName}")
        Observable<Response<ResponseBody>> beginCreate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("liveEventName") String liveEventName, @Path("liveOutputName") String liveOutputName, @Query("api-version") String apiVersion, @Body LiveOutputInner parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.LiveOutputs delete" })
        @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs/{liveOutputName}", method = "DELETE", hasBody = true)
        Observable<Response<ResponseBody>> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("liveEventName") String liveEventName, @Path("liveOutputName") String liveOutputName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.LiveOutputs beginDelete" })
        @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs/{liveOutputName}", method = "DELETE", hasBody = true)
        Observable<Response<ResponseBody>> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("liveEventName") String liveEventName, @Path("liveOutputName") String liveOutputName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.mediaservices.v2018_30_30_preview.LiveOutputs listNext" })
        @GET
        Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList<LiveOutputInner> object if successful.
     */
    public PagedList<LiveOutputInner> list(final String resourceGroupName, final String accountName, final String liveEventName) {
        ServiceResponse<Page<LiveOutputInner>> response = listSinglePageAsync(resourceGroupName, accountName, liveEventName).toBlocking().single();
        return new PagedList<LiveOutputInner>(response.body()) {
            @Override
            public Page<LiveOutputInner> nextPage(String nextPageLink) {
                return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<LiveOutputInner>> listAsync(final String resourceGroupName, final String accountName, final String liveEventName, final ListOperationCallback<LiveOutputInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listSinglePageAsync(resourceGroupName, accountName, liveEventName),
            new Func1<String, Observable<ServiceResponse<Page<LiveOutputInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<LiveOutputInner>>> call(String nextPageLink) {
                    return listNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<LiveOutputInner> object
     */
    public Observable<Page<LiveOutputInner>> listAsync(final String resourceGroupName, final String accountName, final String liveEventName) {
        return listWithServiceResponseAsync(resourceGroupName, accountName, liveEventName)
            .map(new Func1<ServiceResponse<Page<LiveOutputInner>>, Page<LiveOutputInner>>() {
                @Override
                public Page<LiveOutputInner> call(ServiceResponse<Page<LiveOutputInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<LiveOutputInner> object
     */
    public Observable<ServiceResponse<Page<LiveOutputInner>>> listWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String liveEventName) {
        return listSinglePageAsync(resourceGroupName, accountName, liveEventName)
            .concatMap(new Func1<ServiceResponse<Page<LiveOutputInner>>, Observable<ServiceResponse<Page<LiveOutputInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<LiveOutputInner>>> call(ServiceResponse<Page<LiveOutputInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
    ServiceResponse<PageImpl<LiveOutputInner>> * @param resourceGroupName The name of the resource group within the Azure subscription.
    ServiceResponse<PageImpl<LiveOutputInner>> * @param accountName The Media Services account name.
    ServiceResponse<PageImpl<LiveOutputInner>> * @param liveEventName The name of the Live Event.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList<LiveOutputInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<LiveOutputInner>>> listSinglePageAsync(final String resourceGroupName, final String accountName, final String liveEventName) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (liveEventName == null) {
            throw new IllegalArgumentException("Parameter liveEventName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.list(this.client.subscriptionId(), resourceGroupName, accountName, liveEventName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<LiveOutputInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<LiveOutputInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<LiveOutputInner>> result = listDelegate(response);
                        return Observable.just(new ServiceResponse<Page<LiveOutputInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<PageImpl<LiveOutputInner>> listDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<PageImpl<LiveOutputInner>, ApiErrorException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<PageImpl<LiveOutputInner>>() { }.getType())
                .registerError(ApiErrorException.class)
                .build(response);
    }

    /**
     * Get Live Output.
     * Gets a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the LiveOutputInner object if successful.
     */
    public LiveOutputInner get(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        return getWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName).toBlocking().single().body();
    }

    /**
     * Get Live Output.
     * Gets a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<LiveOutputInner> getAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, final ServiceCallback<LiveOutputInner> serviceCallback) {
        return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName), serviceCallback);
    }

    /**
     * Get Live Output.
     * Gets a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the LiveOutputInner object
     */
    public Observable<LiveOutputInner> getAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        return getWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName).map(new Func1<ServiceResponse<LiveOutputInner>, LiveOutputInner>() {
            @Override
            public LiveOutputInner call(ServiceResponse<LiveOutputInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Get Live Output.
     * Gets a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the LiveOutputInner object
     */
    public Observable<ServiceResponse<LiveOutputInner>> getWithServiceResponseAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (liveEventName == null) {
            throw new IllegalArgumentException("Parameter liveEventName is required and cannot be null.");
        }
        if (liveOutputName == null) {
            throw new IllegalArgumentException("Parameter liveOutputName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.get(this.client.subscriptionId(), resourceGroupName, accountName, liveEventName, liveOutputName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LiveOutputInner>>>() {
                @Override
                public Observable<ServiceResponse<LiveOutputInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<LiveOutputInner> clientResponse = getDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<LiveOutputInner> getDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<LiveOutputInner, ApiErrorException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<LiveOutputInner>() { }.getType())
                .register(404, new TypeToken<Void>() { }.getType())
                .registerError(ApiErrorException.class)
                .build(response);
    }

    /**
     * Create Live Output.
     * Creates a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param parameters Live Output properties needed for creation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the LiveOutputInner object if successful.
     */
    public LiveOutputInner create(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters) {
        return createWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName, parameters).toBlocking().last().body();
    }

    /**
     * Create Live Output.
     * Creates a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param parameters Live Output properties needed for creation.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<LiveOutputInner> createAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters, final ServiceCallback<LiveOutputInner> serviceCallback) {
        return ServiceFuture.fromResponse(createWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName, parameters), serviceCallback);
    }

    /**
     * Create Live Output.
     * Creates a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param parameters Live Output properties needed for creation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<LiveOutputInner> createAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters) {
        return createWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName, parameters).map(new Func1<ServiceResponse<LiveOutputInner>, LiveOutputInner>() {
            @Override
            public LiveOutputInner call(ServiceResponse<LiveOutputInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Create Live Output.
     * Creates a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param parameters Live Output properties needed for creation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<ServiceResponse<LiveOutputInner>> createWithServiceResponseAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (liveEventName == null) {
            throw new IllegalArgumentException("Parameter liveEventName is required and cannot be null.");
        }
        if (liveOutputName == null) {
            throw new IllegalArgumentException("Parameter liveOutputName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        if (parameters == null) {
            throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
        }
        Validator.validate(parameters);
        Observable<Response<ResponseBody>> observable = service.create(this.client.subscriptionId(), resourceGroupName, accountName, liveEventName, liveOutputName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent());
        return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<LiveOutputInner>() { }.getType());
    }

    /**
     * Create Live Output.
     * Creates a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param parameters Live Output properties needed for creation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the LiveOutputInner object if successful.
     */
    public LiveOutputInner beginCreate(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters) {
        return beginCreateWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName, parameters).toBlocking().single().body();
    }

    /**
     * Create Live Output.
     * Creates a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param parameters Live Output properties needed for creation.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<LiveOutputInner> beginCreateAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters, final ServiceCallback<LiveOutputInner> serviceCallback) {
        return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName, parameters), serviceCallback);
    }

    /**
     * Create Live Output.
     * Creates a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param parameters Live Output properties needed for creation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the LiveOutputInner object
     */
    public Observable<LiveOutputInner> beginCreateAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters) {
        return beginCreateWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName, parameters).map(new Func1<ServiceResponse<LiveOutputInner>, LiveOutputInner>() {
            @Override
            public LiveOutputInner call(ServiceResponse<LiveOutputInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Create Live Output.
     * Creates a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param parameters Live Output properties needed for creation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the LiveOutputInner object
     */
    public Observable<ServiceResponse<LiveOutputInner>> beginCreateWithServiceResponseAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (liveEventName == null) {
            throw new IllegalArgumentException("Parameter liveEventName is required and cannot be null.");
        }
        if (liveOutputName == null) {
            throw new IllegalArgumentException("Parameter liveOutputName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        if (parameters == null) {
            throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
        }
        Validator.validate(parameters);
        return service.beginCreate(this.client.subscriptionId(), resourceGroupName, accountName, liveEventName, liveOutputName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LiveOutputInner>>>() {
                @Override
                public Observable<ServiceResponse<LiveOutputInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<LiveOutputInner> clientResponse = beginCreateDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<LiveOutputInner> beginCreateDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<LiveOutputInner, ApiErrorException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<LiveOutputInner>() { }.getType())
                .register(202, new TypeToken<LiveOutputInner>() { }.getType())
                .registerError(ApiErrorException.class)
                .build(response);
    }

    /**
     * Delete Live Output.
     * Deletes a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     */
    public void delete(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        deleteWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName).toBlocking().last().body();
    }

    /**
     * Delete Live Output.
     * Deletes a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<Void> deleteAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, final ServiceCallback<Void> serviceCallback) {
        return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName), serviceCallback);
    }

    /**
     * Delete Live Output.
     * Deletes a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<Void> deleteAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        return deleteWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Delete Live Output.
     * Deletes a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (liveEventName == null) {
            throw new IllegalArgumentException("Parameter liveEventName is required and cannot be null.");
        }
        if (liveOutputName == null) {
            throw new IllegalArgumentException("Parameter liveOutputName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        Observable<Response<ResponseBody>> observable = service.delete(this.client.subscriptionId(), resourceGroupName, accountName, liveEventName, liveOutputName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent());
        return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
    }

    /**
     * Delete Live Output.
     * Deletes a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     */
    public void beginDelete(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName).toBlocking().single().body();
    }

    /**
     * Delete Live Output.
     * Deletes a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, final ServiceCallback<Void> serviceCallback) {
        return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName), serviceCallback);
    }

    /**
     * Delete Live Output.
     * Deletes a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<Void> beginDeleteAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        return beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Delete Live Output.
     * Deletes a Live Output.
     *
     * @param resourceGroupName The name of the resource group within the Azure subscription.
     * @param accountName The Media Services account name.
     * @param liveEventName The name of the Live Event.
     * @param liveOutputName The name of the Live Output.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (liveEventName == null) {
            throw new IllegalArgumentException("Parameter liveEventName is required and cannot be null.");
        }
        if (liveOutputName == null) {
            throw new IllegalArgumentException("Parameter liveOutputName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.beginDelete(this.client.subscriptionId(), resourceGroupName, accountName, liveEventName, liveOutputName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = beginDeleteDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<Void, ApiErrorException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<Void>() { }.getType())
                .register(202, new TypeToken<Void>() { }.getType())
                .register(204, new TypeToken<Void>() { }.getType())
                .registerError(ApiErrorException.class)
                .build(response);
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList<LiveOutputInner> object if successful.
     */
    public PagedList<LiveOutputInner> listNext(final String nextPageLink) {
        ServiceResponse<Page<LiveOutputInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
        return new PagedList<LiveOutputInner>(response.body()) {
            @Override
            public Page<LiveOutputInner> nextPage(String nextPageLink) {
                return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @param serviceFuture the ServiceFuture object tracking the Retrofit calls
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<LiveOutputInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<LiveOutputInner>> serviceFuture, final ListOperationCallback<LiveOutputInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listNextSinglePageAsync(nextPageLink),
            new Func1<String, Observable<ServiceResponse<Page<LiveOutputInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<LiveOutputInner>>> call(String nextPageLink) {
                    return listNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<LiveOutputInner> object
     */
    public Observable<Page<LiveOutputInner>> listNextAsync(final String nextPageLink) {
        return listNextWithServiceResponseAsync(nextPageLink)
            .map(new Func1<ServiceResponse<Page<LiveOutputInner>>, Page<LiveOutputInner>>() {
                @Override
                public Page<LiveOutputInner> call(ServiceResponse<Page<LiveOutputInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<LiveOutputInner> object
     */
    public Observable<ServiceResponse<Page<LiveOutputInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
        return listNextSinglePageAsync(nextPageLink)
            .concatMap(new Func1<ServiceResponse<Page<LiveOutputInner>>, Observable<ServiceResponse<Page<LiveOutputInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<LiveOutputInner>>> call(ServiceResponse<Page<LiveOutputInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * List Live Outputs.
     * Lists the Live Outputs in the Live Event.
     *
    ServiceResponse<PageImpl<LiveOutputInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList<LiveOutputInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<LiveOutputInner>>> listNextSinglePageAsync(final String nextPageLink) {
        if (nextPageLink == null) {
            throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
        }
        String nextUrl = String.format("%s", nextPageLink);
        return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<LiveOutputInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<LiveOutputInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<LiveOutputInner>> result = listNextDelegate(response);
                        return Observable.just(new ServiceResponse<Page<LiveOutputInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<PageImpl<LiveOutputInner>> listNextDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<PageImpl<LiveOutputInner>, ApiErrorException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<PageImpl<LiveOutputInner>>() { }.getType())
                .registerError(ApiErrorException.class)
                .build(response);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package hex.tree.isofor;

import hex.ModelCategory;
import hex.ModelMetrics;
import hex.genmodel.utils.DistributionFamily;
import hex.tree.SharedTreeModel;
import water.Key;
import water.fvec.Frame;
import water.util.SBPrintStream;

public class IsolationForestModel extends SharedTreeModel<IsolationForestModel, IsolationForestModel.IsolationForestParameters, IsolationForestModel.IsolationForestOutput> {

  public static class IsolationForestParameters extends SharedTreeModel.SharedTreeParameters {
    public String algoName() { return "IsolationForest"; }
    public String fullName() { return "Isolation Forest"; }
    public String javaName() { return IsolationForestModel.class.getName(); }
    public int _mtries;
    public long _sample_size;

    public IsolationForestParameters() {
      super();
      _mtries = -1;
      _sample_size = 256;
      _max_depth = 8; // log2(_sample_size)
      _sample_rate = -1;
      _min_rows = 1;
      _min_split_improvement = 0;
      _nbins = 2;
      _nbins_cats = 2;
      // _nbins_top_level = 2;
      _histogram_type = HistogramType.Random;
      _distribution = DistributionFamily.gaussian;
    }
  }

  public static class IsolationForestOutput extends SharedTreeModel.SharedTreeOutput {
    public long _max_path_length;
    public long _min_path_length;

    public IsolationForestOutput(IsolationForest b) { super(b); }

    @Override
    public ModelCategory getModelCategory() {
      return ModelCategory.AnomalyDetection;
    }
  }

  public IsolationForestModel(Key<IsolationForestModel> selfKey, IsolationForestParameters parms, IsolationForestOutput output ) { super(selfKey, parms, output); }

  @Override
  public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) {
    return new ModelMetricsAnomaly.MetricBuilderAnomaly();
  }

  @Override
  protected String[] makeScoringNames(){
    return new String[]{"predict", "mean_length"};
  }

  @Override
  protected String[][] makeScoringDomains(Frame adaptFrm, boolean computeMetrics, String[] names) {
    assert names.length == 2;
    return new String[2][];
  }

  /** Bulk scoring API for one row.  Chunks are all compatible with the model,
   *  and expect the last Chunks are for the final distribution and prediction.
   *  Default method is to just load the data into the tmp array, then call
   *  subclass scoring logic. */
  @Override protected double[] score0(double[] data, double[] preds, double offset, int ntrees) {
    super.score0(data, preds, offset, ntrees);
    if (ntrees >= 1) preds[1] = preds[0] / ntrees;
    preds[0] = normalizePathLength(preds[0]);
    return preds;
  }

  final double normalizePathLength(double pathLength) {
    if (_output._max_path_length > _output._min_path_length) {
      return  (_output._max_path_length - pathLength) / (_output._max_path_length - _output._min_path_length);
    } else {
      return 1;
    }
  }

  @Override protected void toJavaUnifyPreds(SBPrintStream body) {
    throw new UnsupportedOperationException("Isolation Forest support only MOJOs.");
  }

  @Override
  public IsolationForestMojoWriter getMojo() {
    return new IsolationForestMojoWriter(this);
  }

}


text:
database of NeuroNexus probe files from NiPOD database

## CSV Files

- `NiPOD-ProbeSpec-denormalized.csv` contains the geometry info for each of the probes

Each of the other CSV files is a table from the NiPOD database

## Notebooks

- `getting the geometries.ipynb` generates klustakwik prb files for each of probes in `NiPOD-ProbeSpec-denormalized.csv`
- `denormalizing.ipynb` merges the CSV files together to create `NiPOD-ProbeSpec-denormalized.csv`
- `getting electrode geometries.ipynb` accesses the NiPOD database and dumps the data into CSV files


text:
'''
    Network sensor plugin

    Generates the Network usage stats
'''
from ptop.core import Plugin
import psutil

class NetworkSensor(Plugin):
    def __init__(self,**kwargs):
        super(NetworkSensor,self).__init__(**kwargs)
        # there will be two parts of the returned value, one will be text and other graph
        # there can be many text (key,value) pairs to display corresponding to each key
        self.currentValue['text'] = {}
        self._sent_bytes_in_mb = 0
        self._received_bytes_in_mb = 0

    # overriding the update method
    def update(self):
        # network usage
        network_usage = psutil.net_io_counters()
        current_sent_bytes_in_mb = round(network_usage[0]*0.000001,4)
        current_received_bytes_in_mb = round(network_usage[1]*0.000001,4)
        # update the network speeds
        self.currentValue['text']['upload_speed_in_mb'] = str(round(current_sent_bytes_in_mb-self._sent_bytes_in_mb,2))
        self.currentValue['text']['download_speed_in_mb'] = str(round(current_received_bytes_in_mb-self._received_bytes_in_mb,2))
        self._sent_bytes_in_mb = current_sent_bytes_in_mb
        self._received_bytes_in_mb = current_received_bytes_in_mb

network_sensor = NetworkSensor(name='Network',sensorType='chart',interval=1)


text:
require 'static_model'

class Language < StaticModel::Base
  self.load_path = File.join(File.dirname(File.expand_path(__FILE__)), '../../data')
end


text:
title: Boost the Performance of an AngularJS Application Using Immutable Data - Part 2
author: minko_gechev
layout: post
categories:
  - JavaScript
  - AngularJS
  - Immutability
  - Functional Programming
  - Performance
  - Benchpress
tags:
  - Immutable.js
  - JavaScript
  - AngularJS
  - Benchpress
---

A few weeks ago I posted the article ["Boost the Performance of an AngularJS Application Using Immutable Data"](http://blog.mgechev.com/2015/03/02/immutability-in-angularjs-immutablejs/). It shows how to speedup your AngularJS application when having a lot of bindings to big data collections. The idea behind the optimization is quite simple - create a new collection when the data changes. This way you can reduce the watchers execution from `O(n)` to `O(1)`.

In the post I did simple profiling using the built-in `Date` but it didn't give enough information in exactly which cases it is more suitable to use immutable data and when you should bet on the standard collections. It also didn't include any information about the garbage collection, although we know that using immutable collections will eventually lead to highly intensive memory management. All the code for the benchmarks and the charts [generation is available in my GitHub account](https://github.com/mgechev/benchpress-angularjs-immutable).

On ng-conf 2015, [Jeff Cross, gave a talk about Benchpress](https://www.youtube.com/watch?v=x1PJn5qMUT4), which fits perfectly in my profiling purposes. Basically, benchpress uses the [WebDriver](http://www.seleniumhq.org/projects/webdriver/) for [Selenium](http://www.seleniumhq.org/), through [`protractor`](https://github.com/angular/protractor) to profile your application. It can run multiple samples of the code you want to profile in order to take the mean and give you a meaningful result. It also includes a few output values, most useful in our case are:

- `scriptTime` - the execution time of your script
- `gcTime` - time required for garbage collection of given sample

Benchpress can render the output of the benchmarks as tables, printed onto the `stdout` or save it into json files.

## Benchmarks

With every collection you can have the following primitive operations:

- **C**reate collection
- **R**ead collection
- **U**pdate collection
- **D**elete collection

We can read given collection in JavaScript or render it inside a template. If we get a new collection each time we change (update) the current one, we have an immutable collection. This means that if we want to check if the collection have changed compared to the last time we've seen it we simply need to compare the current reference of the collection with the previous one (before the change was made):

{% highlight JavaScript %}
let list = Immutable.List([1, 2, 3]);
let changed = list.set(1, 3);
console.log(list === changed); // false
{% endhighlight %}

### Side note

*But what if:

{% highlight javascript %}

var a = [1, 2, 3];
function changeA() {
  a = [1, 2, 3];
}
var oldA = a;
changeA();
console.log(a === oldA); // false
console.log(angular.equals(a, oldA)); // true

{% endhighlight %}

So, if we strictly want to perform given action **only** when the structure of the collection or the data inside it have changed (not only the reference) we will need to loop over both collections (old one and new one) and check whether they contains the same data.*

If we delete, update or create additional entries in the collection, this is considered as update. If we use immutable data, a new collection will be returned on each such manipulation:

{% highlight javascript %}
let list = Immutable.List([1, 2, 3]);

// update
let list1 = list.set(1, 42);
console.log(list === list1); // false
console.log(list.toJS()); // [ 1, 2, 3 ]
console.log(list1.toJS()); // [ 1, 42, 3 ]

// remove
let list2 = list.delete(0);
console.log(list === list2); // false
console.log(list.toJS()); // [ 1, 2, 3 ]
console.log(list2.toJS()); // [ 2, 3 ]

// insert (create entry)
let list3 = list.push(4);
console.log(list === list3); // false
console.log(list.toJS()); // [ 1, 2, 3 ]
console.log(list3.toJS()); // [ 1, 2, 3, 4 ]

{% endhighlight %}

That said, we can build a sample script, which will be used for profiling. Initially we will create a single collection and attach watchers to it. Once this is done, `protractor` will start clicking a button, which will update a random element of the collection. Here is our `SampleCtrl`, which is responsible for initialization and handling the update requests:

{% highlight javascript %}
var benchmarks = angular.module('benchmarks', ['immutable']);

function SampleCtrl($scope, $location) {
  'use strict';
  var dataSize = parseInt($location.search().dataSize, 10);
  var bindingsCount = parseInt($location.search().bindingsCount || 0);
  var watchers = {
    immutable: [],
    standard: []
  };

  function addWatchers(expr, count, collection) {
    for (var i = 0; i < count; i += 1) {
      collection.push($scope.$watch(function () {
        return $scope[expr];
      }, function () {
      }, false));
    }
  }

  function addCollectionWatchers(expr, count, collection) {
    for (var i = 0; i < count; i += 1) {
      collection.push($scope.$watchCollection(expr, function () {
      }));
    }
  }

  function clearWatchers(watchers) {
    var listeners = watchers || [];
    listeners.forEach(function (l) {
      l();
    });
  }

  // Math.random() returns element in the interval [0, 1)
  function generateRandomIndx(length) {
    return Math.floor(Math.random() * length);
  }

  // Updates the current value of the `standard` collection
  $scope.updateStandard = function () {
    if (!$scope.standard) {
      $scope.standard = generateData(dataSize);
    } else {
      var idx = generateRandomIndx(dataSize);
      $scope.standard[idx] = Math.random();
    }
  };

  // Updates the current value of the `immutable` collection
  $scope.updateImmutable = function () {
    if (!$scope.immutable) {
      $scope.immutable = Immutable.List(generateData(dataSize));
    } else {
      // We can cache the plain collection here
      var idx = generateRandomIndx(dataSize);
      $scope.immutable = $scope.immutable.set(idx, Math.random());
    }
  };

  // In case we are running benchmark, which changes the array
  if ($location.search().testType === 'update') {
    var dataType = $location.search().dataType;
    switch (dataType) {
      case 'immutable':
        addWatchers(dataType, bindingsCount, watchers.immutable);
        break;
      default:
        addCollectionWatchers(dataType, bindingsCount, watchers.standard);
    }
  }

  // Clears the `immutable` collection and removes all
  // listeners attached to it (except ng-repeat in the template).
  function clearImmutable() {
    $scope.immutable = null;
    clearWatchers(watchers.immutable);
    watchers.immutable = [];
  }

  // Clears the `standard` collection and removes all
  // listeners attached to it (except ng-repeat in the template).
  function clearStandard() {
    $scope.standard = null;
    clearWatchers(watchers.standard);
    watchers.standard = [];
  }

  // Clears the both collections and all attached listeners to them.
  $scope.clear = function () {
    clearStandard();
    clearImmutable();
  };
}

benchmarks
  .controller('SampleCtrl', SampleCtrl)

{% endhighlight %}

And the template...

{% highlight html %}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title></title>

  <button id="clear-btn" data-ng-click="clear()">Clear</button>
  <button id="update-immutable-btn" data-ng-click="updateImmutable()">
    Update Immutable
  </button>
  <button id="update-standard-btn" data-ng-click="updateStandard()">
    Update Standard
  </button>

{% endhighlight %}

There are three main variables, which has the strongest impact over such benchmark in AngularJS:

- type of the collection (mutable, immutable)
- size of the collection
- count of the bindings added to the collection

In order to get clear understanding of what bindings count and collection size should make us prefer `Immutable.js` over the standard collections, I run the benchmarks with the following collections' sizes: `5, 10, 20, 50, 100, 500, 1000, 2000, 5000, 10000, 100000` and bindings count: `5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100`.

**Application with 100 bindings might sounds not realistic to you but keep in mind that AngularJS adds bindings for (almost) all directives in your templates (`ng-hide`, `ng-show`, `ng-bind`, `ng-repeat`, `ng-class`, `ng-model`, etc.). Each `$digest` loop will lead to traversal of your data structures. For more information on this topic review the AngularJS source code or watch ["Sasqwatch is Real" by William Scott Moss](https://www.youtube.com/watch?v=wbcJfg-d5nI).**

## Results Representation

So far so good. The only thing left is to configure benchpress but this is pretty much a straightforward process. You can find my configuration scripts [here](https://github.com/mgechev/benchpress-angularjs-immutable/tree/master/benchmarks) and Jeff's [here](https://github.com/jeffbcross/benchpress-tree). Note that it is not required to use benchpress with Angular, you can use it with any other framework or even without one.

After you've successfully configured benchpress and start protractor you should see something like:

![](/images/boost-angularjs-immutable-data/protractor-running.gif)

After we run the benchmarks and set the output directory, all the logs will be saved in there, in json format. What we can do is to aggregate the raw results (for example get the mean) and output them in another file or print them on the screen. This seems fine but visual representation is always better. For rendering the data as charts I used node.js with [`node-canvas`](https://github.com/Automattic/node-canvas). Later I found that there's a ["hacked" version of Chart.js, which could be run in node](https://www.npmjs.com/package/nchart). The glue code for rendering benchpress logs onto Chart.js charts seems generic enough and it may get handy to anyone else, so next couple of weeks I may publish it as npm module.

## Exploring the Results

The results contain the script running time and the garbage collection time, mostly because of the immutable data.

### Script Time

This metric will have the strongest impact on the application's performance, since the script time is single threaded. On the charts below are illustrated the script metrics concerning the script running time of the benchmarks above. The horizontal axis (x-axis) shows the bindings count and the vertical axis (y-axis) illustrates the script running time (in ms).

#### 5 entries

[![5 entries](/images/boost-angularjs-immutable-data/scripttime-data-size-5.png)](/images/boost-angularjs-immutable-data/scripttime-data-size-5.png)

When having a collection with 5 entries the running time of the script using immutable list is almost double the running time of a standard array. When the bindings counts get bigger there are no significant changes in the time required for running the scripts (both immutable and standard array).
Basically when we have 100 bindings (+1 with the watcher added by `ng-repeat`) the AngularJS change detection mechanism needs to perform 5 * 100 iterations (in the worst case) in order to verify that the current value of the array is equals to the previous one for the standard array and a 100 comparisons (one for each binding using `===`) in order to detect changes in the immutable data. Since we have overhead caused by the creation of new immutable list on change, the running time of the script using immutable data is bigger.

#### 20 entries

[![20 entries](/images/boost-angularjs-immutable-data/scripttime-data-size-20.png)](/images/boost-angularjs-immutable-data/scripttime-data-size-20.png)

There are no significant changes in the results of the benchmark, which runs script with array/list with 20 entries. The only noticeable difference here is that the running time of the script using standard array gets significantly bigger when we increase the bindings count. Again, when we have 100 bindings and 20 element array we get 20 * 100 iterations in order to detect change, compared to 20 * 5 with only 5 bindings.

#### 50 entries

[![50 entries](/images/boost-angularjs-immutable-data/scripttime-data-size-50.png)](/images/boost-angularjs-immutable-data/scripttime-data-size-50.png)

This is the first benchmark, which results show better performance of the immutable list compared to the standard one. In case of 100 bindings the immutable list wins!

#### 100 entries

[![100 entries](/images/boost-angularjs-immutable-data/scripttime-data-size-100.png)](/images/boost-angularjs-immutable-data/scripttime-data-size-100.png)

Here the competition gets ruthless! We see how much bigger the running time of the script using standard array gets when we have large amount of bindings. Anyway, still the standard array looks like the winner.

#### 500 entries

[![500 entries](/images/boost-angularjs-immutable-data/scripttime-data-size-500.png)](/images/boost-angularjs-immutable-data/scripttime-data-size-500.png)

It looks like the supreme champion in this benchmark is the immutable array! You still have to watch out whether you have only a few bindings to the collection but definitely if you have more than 10 you should consider using immutable data.

#### 10,000 entries

[![10,000 entries](/images/boost-angularjs-immutable-data/scripttime-data-size-10000.png)](/images/boost-angularjs-immutable-data/scripttime-data-size-10000.png)

After 20 bindings the running time of the script using standard array gets crazy big! You can see how it gets bigger and bigger with every next binding, although the running time of the script using immutable list stays constant. I'd definitely recommend you to use immutable data with such big collections.

### Garbage Collection Time

![](/images/one-does-not-simply-profile-the-script-running-time.png)

This metric indicates the time required for garbage collection. I'm exposing this metric as secondary one because the user may not notice directly the impact of the garbage collection time during her experience using our application.
It is interesting that the information we got from the benchmarks doesn't imply any significant advantage of the standard array compared to the immutable list.

I will not provide further explanation for the following sections because I think they are self explanatory. However, if you have any troubles understanding them or you think they deserve further discussions you're welcome to drop a line as a comment or reach me over e-mail (take a look at the [About](http://blog.mgechev.com/about/) section above).

#### 5 entries

[![5 entries](/images/boost-angularjs-immutable-data/gctime-data-size-5.png)](/images/boost-angularjs-immutable-data/gctime-data-size-5.png)

#### 50 entries

[![50 entries](/images/boost-angularjs-immutable-data/gctime-data-size-50.png)](/images/boost-angularjs-immutable-data/gctime-data-size-50.png)

#### 100 entries

[![100 entries](/images/boost-angularjs-immutable-data/gctime-data-size-100.png)](/images/boost-angularjs-immutable-data/gctime-data-size-100.png)

#### 500 entries

[![500 entries](/images/boost-angularjs-immutable-data/gctime-data-size-500.png)](/images/boost-angularjs-immutable-data/gctime-data-size-500.png)

#### 1,0000 entries

[![1,000 entries](/images/boost-angularjs-immutable-data/gctime-data-size-10000.png)](/images/boost-angularjs-immutable-data/gctime-data-size-10000.png)

## Conclusion

Some of the ideas brought to us by the functional paradigm, such as: pure functions, referential transparency, immutable data, etc. constantly find broader and broader applications in building user interface. As we explored in details in the [two parts of this blog post on using immutable data with AngularJS](http://blog.mgechev.com/2015/03/02/immutability-in-angularjs-immutablejs/), immutability could be quite helpful when we have a lot of bindings on a big data collection. However, in the general use case I'd recommend usage of standard arrays.

The immutable data helps us speedup the watchers from `O(n)` (looping over the whole data structure) to `O(1)` (comparing only references, since on change a new immutable data structure will be created) but it also has its drawbacks:

- overhead of the creation of the new data structure on change
- overhead of the performed garbage collection (which wasn't such a big deal, as show above)

But can't we build something, which takes the best of both worlds? Can't we build a specialized data structure used for super fast data binding, which doesn't require creation of new instance on change but still allows `O(1)` check for change? This is what I'm going to explore in the last blog post of this series.

## Parts of the series:

- [Boost the Performance of an AngularJS Application Using Immutable Data - Part 1](http://blog.mgechev.com/2015/03/02/immutability-in-angularjs-immutablejs/)
- [Boost the Performance of an AngularJS Application Using Immutable Data - Part 2](http://blog.mgechev.com/2015/04/11/immutability-in-angularjs-immutablejs-part-2/)
- [Even Faster AngularJS Data Structures](http://blog.mgechev.com/2015/04/20/fast-angular-data-structures-versionable/)


text:
> This document is inspired by [elasticsearch/CONTRIBUTING.md](https://github.com/elastic/elasticsearch/blob/master/CONTRIBUTING.md)

Adding a `CONTRIBUTING.md` to a Github repository enables a link to that file in the pull request or create an issue page. This document should guide potential contributors toward making a successful and meaningful impact on the project, and can save maintainers time and hassle caused by improper pull requests and issues. You can learn more about the features that are enabled by Github when this file is present [here](https://help.github.com/articles/setting-guidelines-for-repository-contributors/).

## How to contribute

There are many ways to contribute, from writing tutorials or blog posts, improving the documentation, [submitting Github issues](https://help.github.com/articles/creating-an-issue/), bug reports, feature requests and writing code.

## License

This repository uses the [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html).

## Bug reports

If you think you've found a bug in the software, first make sure you're testing against the *latest* version of the software -- your issue may have been fixed already. If it's not, please check out the issues list on Github and search for similar issues that have already been opened. If there are no issues then please [submit a Github issue](https://help.github.com/articles/creating-an-issue/).

If you can provide a small test case it would greatly help the reproduction of a bug, as well as a a screenshot, and any other information you can provide.

## Feature Requests

If there are features that do not exist yet, we are definitely open to feature requests and detailed proposals. [Open an issue](https://help.github.com/articles/creating-an-issue/) on our Github which describes the feature or proposal in detail, answer questions like why? how?

## Contributing Code and Documentation Changes

Bug fixes, patches and new features are welcome. Please find or open an issue about it first. Talk about what exactly want to do, someone may already be working on it, or there might be some issues that you need to be aware of before implementing the fix.

There are many ways to fix a problem and it is important to find the best approach before writing a ton of code.

##### Documentation Changes

For small documentation changes and fixes, these can be done quickly following this video guide on [how to contribute to Open Source in 1 minute on Github](https://www.youtube.com/watch?v=kRYk1-yKwWs).

### Forking the repository

[How to fork a repository](https://help.github.com/articles/fork-a-repo/).

### Submitting changes

1. Review & Test changes
    * If the code changed, then test it. If documentation changed, then preview the rendered Markdown.
2. Commiting
    * Follow the [Conventional Commits](CONVENTIONAL_COMMITS.md) guidelines to create a commit message.
3. Sign the CLA
    * Make sure you've signed the repository's Contributor License Agreement. We are not asking you to assign copyright to us, but to give us the right to distribute your code without restriction. We ask this of all contributors in order to assure our users of the origin and continuing existence of the code. You only need to sign the CLA once.
4. Submit a pull request
    * Push local changes to your forked repository and make a pull request. Follow the [Convention Commits](CONVENTIONAL_COMMITS.md) guidelines for naming Github pull requests and what to put in the body.

## Releasing

Follow the release process is outlined in [RELEASING.md](RELEASING.md) to create a release.


text:
<?php
/**
 * @category    Xi
 * @package     Xi_Doctrine
 * @subpackage  Xi_Doctrine_StateMachine
 * @author      Eevert Saukkokoski <eevert.saukkokoski@brainalliance.com>
 */
class Xi_Doctrine_StateMachine_Exception extends Xi_Doctrine_Exception
{}


text:
package com.taotao.portal.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.utils.TaotaoResult;
import com.taotao.portal.service.IContentService;
import com.taotao.portal.service.IUserService;

@Controller
public class PageController {

	@Autowired
	private IContentService contentService;

	@Autowired
	private IUserService userService;

	@RequestMapping("/index")
	public String showIndex(Model model) {
		model.addAttribute("ad1", contentService.getContentList());
		return "index";
	}

	@RequestMapping("/user/logout/{token}")
	public String logout(@PathVariable String token, Model model, HttpServletRequest request, HttpServletResponse response) {
		model.addAttribute("ad1", contentService.getContentList());
		userService.logout(token, request, response);
		return "index";
	}

	@RequestMapping(value="/post", method=RequestMethod.POST)
	@ResponseBody
	public TaotaoResult testPost() {
		return TaotaoResult.ok();
	}

	@RequestMapping(value="/postwithparam", method=RequestMethod.POST)
	@ResponseBody
	public String testPostWithParam(String username, String password) {
		return "username:" + username + ", password:" + password;
	}
}


text:
r"""
:Copyright:

 Copyright 2014 - 2016
 Andr\xe9 Malo or his licensors, as applicable

:License:

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

=====================
 Scheduler Utilities
=====================

Collection of scheduler-internal utilities.
"""
if __doc__:  # pragma: no cover
    # pylint: disable = redefined-builtin
    __doc__ = __doc__.encode('ascii').decode('unicode_escape')
__author__ = r"Andr\xe9 Malo".encode('ascii').decode('unicode_escape')
__docformat__ = "restructuredtext en"

import datetime as _dt
import time as _time

try:  # pragma: no cover
    import pytz as _pytz
except ImportError:  # pragma: no cover
    _pytz = None

class DelayedJob(object):
    """
    Ordering wrapper for job inside the scheduled queue

    :IVariables:
      `job` : any
        The wrapped job
    """

    def __init__(self, job):
        """
        Initilization

        :Parameters:
          `job` : any
            The job to wrap
        """
        self.job = job
        self.not_before = scheduled_time(job)

    def __lt__(self, other):
        """
        Compare jobs by schedule time

        :Parameters:
          `other` : `DelayedJob`
            The job to compare ourself to

        :Return: Is this job "smaller" than the other?
        :Rtype: ``bool``
        """
        return self.not_before < other.not_before

class QueuedJob(object):
    """
    Ordering wrapper for job inside the main queue

    :IVariables:
      `job` : any
        The wrapped job
    """

    def __init__(self, job):
        """
        Initilization

        :Parameters:
          `job` : any
            The job to wrap
        """
        self.job = job

    def __lt__(self, other):
        """
        Compare jobs by importance and then ID

        :Parameters:
          `other` : `QueuedJob`
            The job to compare ourself to

        :Return: Is this job "smaller" than the othe?
        :Rtype: ``bool``
        """
        return (
            self.job.importance > other.job.importance
            or
            self.job.id < other.job.id
        )

def scheduled_time(job):
    """
    Determined the scheduled time for a job

    :Parameters:
      `job` : `JobInterface`
        Job to inspect

    :Return: Scheduled time of the job in seconds since epoch
    :Rtype: ``int``
    """
    time_now = int(_time.time())
    not_before = job.not_before
    if not not_before:
        return time_now

    try:
        not_before = int(not_before)
    except (TypeError, ValueError):
        now = _dt.datetime.utcnow()
        if not_before.tzinfo is not None:
            if _pytz is None:
                raise RuntimeError("Need pytz for timezone support")
            # pylint: disable = no-value-for-parameter
            now = _pytz.UTC.localize(now)
        not_before = max(0, int((not_before - now).total_seconds()))

    return time_now + not_before


text:
<% _.each(collection, function(comment){ %>

    <a href="/comments/<%= comment.get('id') %>"><%= comment.get('text') %>

<% }) %>


text:
require 'spec_helper'
require 'facter/util/collection'
require 'facter/util/nothing_loader'

describe Facter::Util::Collection do
  let(:external_loader) { Facter::Util::NothingLoader.new }
  let(:internal_loader) do
    load = Facter::Util::Loader.new
    load.stubs(:load).returns nil
    load.stubs(:load_all).returns nil
    load
  end
  let(:collection) { Facter::Util::Collection.new(internal_loader, external_loader) }

  it "should delegate its load_all method to its loader" do
    internal_loader.expects(:load_all)

    collection.load_all
  end

  describe "when adding facts" do
    it "should create a new fact if no fact with the same name already exists" do
      collection.add(:myname)
      collection.fact(:myname).name.should == :myname
    end

    it "should accept options" do
      collection.add(:myname, :timeout => 1) { }
    end

    it "passes resolution specific options to the fact" do
      fact = Facter::Util::Fact.new(:myname)
      Facter::Util::Fact.expects(:new).with(:myname, {:timeout => 'myval'}).returns fact

      fact.expects(:add).with({:timeout => 'myval'})

      collection.add(:myname, :timeout => "myval") {}
    end

    describe "and a block is provided" do
      it "should use the block to add a resolution to the fact" do
        fact = mock 'fact'
        fact.stubs(:extract_ldapname_option!)
        Facter::Util::Fact.expects(:new).returns fact

        fact.expects(:add)

        collection.add(:myname) {}
      end

      it "should discard resolutions that throw an exception when added" do
        Facter.expects(:warn).with(regexp_matches(/Unable to add resolve .* kaboom!/))
        expect {
          collection.add('yay') do
            raise "kaboom!"
          end
        }.to_not raise_error
        expect(collection.value('yay')).to be_nil
      end
    end
  end

  describe "when only defining facts" do
    it "creates a new fact if no such fact exists" do
      fact = Facter::Util::Fact.new(:newfact)
      Facter::Util::Fact.expects(:new).with(:newfact, {}).returns fact
      expect(collection.define_fact(:newfact)).to equal fact
    end

    it "returns an existing fact if the fact has already been defined" do
      fact = collection.define_fact(:newfact)
      expect(collection.define_fact(:newfact)).to equal fact
    end

    it "passes options to newly generated facts" do
      Facter.stubs(:warnonce)
      fact = collection.define_fact(:newfact, :ldapname => 'NewFact')
      expect(fact.ldapname).to eq 'NewFact'
    end

    it "logs a warning if the fact could not be defined" do
      Facter.expects(:warn).with("Unable to add fact newfact: kaboom!")

      collection.define_fact(:newfact) do
        raise "kaboom!"
      end
    end
  end

  describe "when retrieving facts" do
    before do
      @fact = collection.add("YayNess")
    end

    it "should return the fact instance specified by the name" do
      collection.fact("YayNess").should equal(@fact)
    end

    it "should be case-insensitive" do
      collection.fact("yayness").should equal(@fact)
    end

    it "should treat strings and symbols equivalently" do
      collection.fact(:yayness).should equal(@fact)
    end

    it "should use its loader to try to load the fact if no fact can be found" do
      collection.internal_loader.expects(:load).with(:testing)
      collection.fact("testing")
    end

    it "should return nil if it cannot find or load the fact" do
      collection.internal_loader.expects(:load).with(:testing)
      collection.fact("testing").should be_nil
    end
  end

  describe "when returning a fact's value" do
    before do
      @fact = collection.add("YayNess", :value => "result")
    end

    it "should return the result of calling :value on the fact" do
      collection.value("YayNess").should == "result"
    end

    it "should be case-insensitive" do
      collection.value("yayness").should == "result"
    end

    it "should treat strings and symbols equivalently" do
      collection.value(:yayness).should == "result"
    end
  end

  it "should return the fact's value when the array index method is used" do
    collection.add("myfact", :value => "foo")

    collection["myfact"].should == "foo"
  end

  it "should have a method for flushing all facts" do
    fact = collection.add("YayNess")

    fact.expects(:flush)

    collection.flush
  end

  it "should have a method that returns all fact names" do
    collection.add(:one)
    collection.add(:two)

    collection.list.sort { |a,b| a.to_s <=> b.to_s }.should == [:one, :two]
  end

  describe "when returning a hash of values" do
    it "should return a hash of fact names and values with the fact names as strings" do
      collection.add(:one, :value => "me")

      collection.to_hash.should == {"one" => "me"}
    end

    it "should not include facts that did not return a value" do
      collection.add(:two, :value => nil)

      collection.to_hash.should_not be_include(:two)
    end
  end

  describe "when iterating over facts" do
    before do
      collection.add(:one, :value => "ONE")
      collection.add(:two, :value => "TWO")
    end

    it "should yield each fact name and the fact value" do
      facts = {}
      collection.each do |fact, value|
        facts[fact] = value
      end
      facts.should == {"one" => "ONE", "two" => "TWO"}
    end

    it "should convert the fact name to a string" do
      facts = {}
      collection.each do |fact, value|
        fact.should be_instance_of(String)
      end
    end

    it "should only yield facts that have values" do
      collection.add(:nil_fact, :value => nil)
      facts = {}
      collection.each do |fact, value|
        facts[fact] = value
      end

      facts.should_not be_include("nil_fact")
    end
  end

  describe "when no facts are loaded" do
    it "should warn when no facts were loaded" do
      Facter.expects(:warnonce).with("No facts loaded from #{internal_loader.search_path.join(File::PATH_SEPARATOR)}").once

      collection.fact("one")
    end
  end

  describe "external facts" do
    let(:external_loader) { SingleFactLoader.new(:test_fact, "fact value") }
    let(:collection) { Facter::Util::Collection.new(internal_loader, external_loader) }

    it "loads when a specific fact is requested" do
      collection.fact(:test_fact).value.should == "fact value"
    end

    it "loads when facts are listed" do
      collection.list.should == [:test_fact]
    end

    it "loads when all facts are iterated over" do
      facts = []
      collection.each { |fact_name, fact_value| facts << [fact_name, fact_value] }

      facts.should == [["test_fact", "fact value"]]
    end

    it "are loaded only once" do
      external_loader.expects(:load).with(collection)

      collection.load_all
      collection.load_all
    end

    it "are reloaded after flushing" do
      external_loader.expects(:load).with(collection).twice

      collection.load_all
      collection.flush
      collection.load_all
    end
  end

  class SingleFactLoader
    def initialize(name, value)
      @name = name
      @value = value
    end

    def load(collection)
      collection.add(@name, :value => @value)
    end
  end
end


text:
using System;
using Windows.UI.Xaml.Data;

namespace CJia.MobileMedicalDoctor.App.Common
{
    /// <summary>
    /// 从 true 转换为 false 以及进行相反转换的值转换器。
    /// </summary>
    public sealed class BooleanNegationConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return !(value is bool && (bool)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return !(value is bool && (bool)value);
        }
    }
}