text:
package com.microsoft.azure.management.keyvault.implementation;

import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceCall;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.Resource;
import com.microsoft.rest.ServiceCall;
import com.microsoft.rest.ServiceCallback;
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 Vaults.
 */
public final class VaultsInner {
    /** The Retrofit service to perform REST calls. */
    private VaultsService service;
    /** The service client containing this operation class. */
    private KeyVaultManagementClientImpl client;

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

    /**
     * The interface defining all the services for Vaults to be
     * used by Retrofit to perform actually REST calls.
     */
    interface VaultsService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.keyvault.Vaults createOrUpdate" })
        @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}")
        Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Body VaultCreateOrUpdateParametersInner 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.keyvault.Vaults delete" })
        @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}", method = "DELETE", hasBody = true)
        Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @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.keyvault.Vaults get" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}")
        Observable<Response<ResponseBody>> get(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @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.keyvault.Vaults listByResourceGroup" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults")
        Observable<Response<ResponseBody>> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("$top") Integer top, @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.keyvault.Vaults list" })
        @GET("subscriptions/{subscriptionId}/resources")
        Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("$filter") String filter, @Query("$top") Integer top, @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.keyvault.Vaults listByResourceGroupNext" })
        @GET
        Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @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.keyvault.Vaults listNext" })
        @GET
        Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * Create or update a key vault in the specified subscription.
     *
     * @param resourceGroupName The name of the Resource Group to which the server belongs.
     * @param vaultName Name of the vault
     * @param parameters Parameters to create or update the vault
     * @return the VaultInner object if successful.
     */
    public VaultInner createOrUpdate(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters) {
        return createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, parameters).toBlocking().single().body();
    }

    /**
     * Create or update a key vault in the specified subscription.
     *
     * @param resourceGroupName The name of the Resource Group to which the server belongs.
     * @param vaultName Name of the vault
     * @param parameters Parameters to create or update the vault
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<VaultInner> createOrUpdateAsync(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters, final ServiceCallback<VaultInner> serviceCallback) {
        return ServiceCall.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, parameters), serviceCallback);
    }

    /**
     * Create or update a key vault in the specified subscription.
     *
     * @param resourceGroupName The name of the Resource Group to which the server belongs.
     * @param vaultName Name of the vault
     * @param parameters Parameters to create or update the vault
     * @return the observable to the VaultInner object
     */
    public Observable<VaultInner> createOrUpdateAsync(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters) {
        return createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, parameters).map(new Func1<ServiceResponse<VaultInner>, VaultInner>() {
            @Override
            public VaultInner call(ServiceResponse<VaultInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Create or update a key vault in the specified subscription.
     *
     * @param resourceGroupName The name of the Resource Group to which the server belongs.
     * @param vaultName Name of the vault
     * @param parameters Parameters to create or update the vault
     * @return the observable to the VaultInner object
     */
    public Observable<ServiceResponse<VaultInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (vaultName == null) {
            throw new IllegalArgumentException("Parameter vaultName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() 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.createOrUpdate(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VaultInner>>>() {
                @Override
                public Observable<ServiceResponse<VaultInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<VaultInner> clientResponse = createOrUpdateDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * Deletes the specified Azure key vault.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param vaultName The name of the vault to delete
     */
    public void delete(String resourceGroupName, String vaultName) {
        deleteWithServiceResponseAsync(resourceGroupName, vaultName).toBlocking().single().body();
    }

    /**
     * Deletes the specified Azure key vault.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param vaultName The name of the vault to delete
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<Void> deleteAsync(String resourceGroupName, String vaultName, final ServiceCallback<Void> serviceCallback) {
        return ServiceCall.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, vaultName), serviceCallback);
    }

    /**
     * Deletes the specified Azure key vault.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param vaultName The name of the vault to delete
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<Void> deleteAsync(String resourceGroupName, String vaultName) {
        return deleteWithServiceResponseAsync(resourceGroupName, vaultName).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Deletes the specified Azure key vault.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param vaultName The name of the vault to delete
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String vaultName) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (vaultName == null) {
            throw new IllegalArgumentException("Parameter vaultName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() 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.delete(resourceGroupName, vaultName, this.client.subscriptionId(), 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 = deleteDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<Void> deleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<Void>() { }.getType())
                .build(response);
    }

    /**
     * Gets the specified Azure key vault.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param vaultName The name of the vault.
     * @return the VaultInner object if successful.
     */
    public VaultInner get(String resourceGroupName, String vaultName) {
        return getWithServiceResponseAsync(resourceGroupName, vaultName).toBlocking().single().body();
    }

    /**
     * Gets the specified Azure key vault.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param vaultName The name of the vault.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<VaultInner> getAsync(String resourceGroupName, String vaultName, final ServiceCallback<VaultInner> serviceCallback) {
        return ServiceCall.fromResponse(getWithServiceResponseAsync(resourceGroupName, vaultName), serviceCallback);
    }

    /**
     * Gets the specified Azure key vault.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param vaultName The name of the vault.
     * @return the observable to the VaultInner object
     */
    public Observable<VaultInner> getAsync(String resourceGroupName, String vaultName) {
        return getWithServiceResponseAsync(resourceGroupName, vaultName).map(new Func1<ServiceResponse<VaultInner>, VaultInner>() {
            @Override
            public VaultInner call(ServiceResponse<VaultInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Gets the specified Azure key vault.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param vaultName The name of the vault.
     * @return the observable to the VaultInner object
     */
    public Observable<ServiceResponse<VaultInner>> getWithServiceResponseAsync(String resourceGroupName, String vaultName) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (vaultName == null) {
            throw new IllegalArgumentException("Parameter vaultName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() 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(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VaultInner>>>() {
                @Override
                public Observable<ServiceResponse<VaultInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<VaultInner> clientResponse = getDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @return the PagedList<VaultInner> object if successful.
     */
    public PagedList<VaultInner> listByResourceGroup(final String resourceGroupName) {
        ServiceResponse<Page<VaultInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single();
        return new PagedList<VaultInner>(response.body()) {
            @Override
            public Page<VaultInner> nextPage(String nextPageLink) {
                return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<List<VaultInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<VaultInner> serviceCallback) {
        return AzureServiceCall.fromPageResponse(
            listByResourceGroupSinglePageAsync(resourceGroupName),
            new Func1<String, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(String nextPageLink) {
                    return listByResourceGroupNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @return the observable to the PagedList<VaultInner> object
     */
    public Observable<Page<VaultInner>> listByResourceGroupAsync(final String resourceGroupName) {
        return listByResourceGroupWithServiceResponseAsync(resourceGroupName)
            .map(new Func1<ServiceResponse<Page<VaultInner>>, Page<VaultInner>>() {
                @Override
                public Page<VaultInner> call(ServiceResponse<Page<VaultInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @return the observable to the PagedList<VaultInner> object
     */
    public Observable<ServiceResponse<Page<VaultInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) {
        return listByResourceGroupSinglePageAsync(resourceGroupName)
            .concatMap(new Func1<ServiceResponse<Page<VaultInner>>, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(ServiceResponse<Page<VaultInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<VaultInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        final Integer top = null;
        return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), top, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<VaultInner>> result = listByResourceGroupDelegate(response);
                        return Observable.just(new ServiceResponse<Page<VaultInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param top Maximum number of results to return.
     * @return the PagedList<VaultInner> object if successful.
     */
    public PagedList<VaultInner> listByResourceGroup(final String resourceGroupName, final Integer top) {
        ServiceResponse<Page<VaultInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName, top).toBlocking().single();
        return new PagedList<VaultInner>(response.body()) {
            @Override
            public Page<VaultInner> nextPage(String nextPageLink) {
                return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param top Maximum number of results to return.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<List<VaultInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top, final ListOperationCallback<VaultInner> serviceCallback) {
        return AzureServiceCall.fromPageResponse(
            listByResourceGroupSinglePageAsync(resourceGroupName, top),
            new Func1<String, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(String nextPageLink) {
                    return listByResourceGroupNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param top Maximum number of results to return.
     * @return the observable to the PagedList<VaultInner> object
     */
    public Observable<Page<VaultInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top) {
        return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top)
            .map(new Func1<ServiceResponse<Page<VaultInner>>, Page<VaultInner>>() {
                @Override
                public Page<VaultInner> call(ServiceResponse<Page<VaultInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param resourceGroupName The name of the Resource Group to which the vault belongs.
     * @param top Maximum number of results to return.
     * @return the observable to the PagedList<VaultInner> object
     */
    public Observable<ServiceResponse<Page<VaultInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName, final Integer top) {
        return listByResourceGroupSinglePageAsync(resourceGroupName, top)
            .concatMap(new Func1<ServiceResponse<Page<VaultInner>>, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(ServiceResponse<Page<VaultInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
    ServiceResponse<PageImpl<VaultInner>> * @param resourceGroupName The name of the Resource Group to which the vault belongs.
    ServiceResponse<PageImpl<VaultInner>> * @param top Maximum number of results to return.
     * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<VaultInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName, final Integer top) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() 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.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), top, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<VaultInner>> result = listByResourceGroupDelegate(response);
                        return Observable.just(new ServiceResponse<Page<VaultInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @return the PagedList<Resource> object if successful.
     */
    public PagedList<Resource> list() {
        ServiceResponse<Page<Resource>> response = listSinglePageAsync().toBlocking().single();
        return new PagedList<Resource>(response.body()) {
            @Override
            public Page<Resource> nextPage(String nextPageLink) {
                return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<List<Resource>> listAsync(final ListOperationCallback<Resource> serviceCallback) {
        return AzureServiceCall.fromPageResponse(
            listSinglePageAsync(),
            new Func1<String, Observable<ServiceResponse<Page<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(String nextPageLink) {
                    return listNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @return the observable to the PagedList<Resource> object
     */
    public Observable<Page<Resource>> listAsync() {
        return listWithServiceResponseAsync()
            .map(new Func1<ServiceResponse<Page<Resource>>, Page<Resource>>() {
                @Override
                public Page<Resource> call(ServiceResponse<Page<Resource>> response) {
                    return response.body();
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @return the observable to the PagedList<Resource> object
     */
    public Observable<ServiceResponse<Page<Resource>>> listWithServiceResponseAsync() {
        return listSinglePageAsync()
            .concatMap(new Func1<ServiceResponse<Page<Resource>>, Observable<ServiceResponse<Page<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(ServiceResponse<Page<Resource>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @return the PagedList<Resource> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<Resource>>> listSinglePageAsync() {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        final String filter = "resourceType eq 'Microsoft.KeyVault/vaults'";
        final String apiVersion = "2015-11-01";
        final Integer top = null;
        return service.list(this.client.subscriptionId(), filter, top, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<Resource>> result = listDelegate(response);
                        return Observable.just(new ServiceResponse<Page<Resource>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param top Maximum number of results to return.
     * @return the PagedList<Resource> object if successful.
     */
    public PagedList<Resource> list(final Integer top) {
        ServiceResponse<Page<Resource>> response = listSinglePageAsync(top).toBlocking().single();
        return new PagedList<Resource>(response.body()) {
            @Override
            public Page<Resource> nextPage(String nextPageLink) {
                return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param top Maximum number of results to return.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<List<Resource>> listAsync(final Integer top, final ListOperationCallback<Resource> serviceCallback) {
        return AzureServiceCall.fromPageResponse(
            listSinglePageAsync(top),
            new Func1<String, Observable<ServiceResponse<Page<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(String nextPageLink) {
                    return listNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param top Maximum number of results to return.
     * @return the observable to the PagedList<Resource> object
     */
    public Observable<Page<Resource>> listAsync(final Integer top) {
        return listWithServiceResponseAsync(top)
            .map(new Func1<ServiceResponse<Page<Resource>>, Page<Resource>>() {
                @Override
                public Page<Resource> call(ServiceResponse<Page<Resource>> response) {
                    return response.body();
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param top Maximum number of results to return.
     * @return the observable to the PagedList<Resource> object
     */
    public Observable<ServiceResponse<Page<Resource>>> listWithServiceResponseAsync(final Integer top) {
        return listSinglePageAsync(top)
            .concatMap(new Func1<ServiceResponse<Page<Resource>>, Observable<ServiceResponse<Page<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(ServiceResponse<Page<Resource>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
    ServiceResponse<PageImpl<Resource>> * @param top Maximum number of results to return.
     * @return the PagedList<Resource> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<Resource>>> listSinglePageAsync(final Integer top) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        final String filter = "resourceType eq 'Microsoft.KeyVault/vaults'";
        final String apiVersion = "2015-11-01";
        return service.list(this.client.subscriptionId(), filter, top, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<Resource>> result = listDelegate(response);
                        return Observable.just(new ServiceResponse<Page<Resource>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @return the PagedList<VaultInner> object if successful.
     */
    public PagedList<VaultInner> listByResourceGroupNext(final String nextPageLink) {
        ServiceResponse<Page<VaultInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single();
        return new PagedList<VaultInner>(response.body()) {
            @Override
            public Page<VaultInner> nextPage(String nextPageLink) {
                return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @param serviceCall the ServiceCall object tracking the Retrofit calls
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<List<VaultInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceCall<List<VaultInner>> serviceCall, final ListOperationCallback<VaultInner> serviceCallback) {
        return AzureServiceCall.fromPageResponse(
            listByResourceGroupNextSinglePageAsync(nextPageLink),
            new Func1<String, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(String nextPageLink) {
                    return listByResourceGroupNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @return the observable to the PagedList<VaultInner> object
     */
    public Observable<Page<VaultInner>> listByResourceGroupNextAsync(final String nextPageLink) {
        return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
            .map(new Func1<ServiceResponse<Page<VaultInner>>, Page<VaultInner>>() {
                @Override
                public Page<VaultInner> call(ServiceResponse<Page<VaultInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @return the observable to the PagedList<VaultInner> object
     */
    public Observable<ServiceResponse<Page<VaultInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) {
        return listByResourceGroupNextSinglePageAsync(nextPageLink)
            .concatMap(new Func1<ServiceResponse<Page<VaultInner>>, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(ServiceResponse<Page<VaultInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription and within the specified resource group.
     *
    ServiceResponse<PageImpl<VaultInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<VaultInner>>> listByResourceGroupNextSinglePageAsync(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.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VaultInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<VaultInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<VaultInner>> result = listByResourceGroupNextDelegate(response);
                        return Observable.just(new ServiceResponse<Page<VaultInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @return the PagedList<Resource> object if successful.
     */
    public PagedList<Resource> listNext(final String nextPageLink) {
        ServiceResponse<Page<Resource>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
        return new PagedList<Resource>(response.body()) {
            @Override
            public Page<Resource> nextPage(String nextPageLink) {
                return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @param serviceCall the ServiceCall object tracking the Retrofit calls
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @return the {@link ServiceCall} object
     */
    public ServiceCall<List<Resource>> listNextAsync(final String nextPageLink, final ServiceCall<List<Resource>> serviceCall, final ListOperationCallback<Resource> serviceCallback) {
        return AzureServiceCall.fromPageResponse(
            listNextSinglePageAsync(nextPageLink),
            new Func1<String, Observable<ServiceResponse<Page<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(String nextPageLink) {
                    return listNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @return the observable to the PagedList<Resource> object
     */
    public Observable<Page<Resource>> listNextAsync(final String nextPageLink) {
        return listNextWithServiceResponseAsync(nextPageLink)
            .map(new Func1<ServiceResponse<Page<Resource>>, Page<Resource>>() {
                @Override
                public Page<Resource> call(ServiceResponse<Page<Resource>> response) {
                    return response.body();
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @return the observable to the PagedList<Resource> object
     */
    public Observable<ServiceResponse<Page<Resource>>> listNextWithServiceResponseAsync(final String nextPageLink) {
        return listNextSinglePageAsync(nextPageLink)
            .concatMap(new Func1<ServiceResponse<Page<Resource>>, Observable<ServiceResponse<Page<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(ServiceResponse<Page<Resource>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * The List operation gets information about the vaults associated with the subscription.
     *
    ServiceResponse<PageImpl<Resource>> * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @return the PagedList<Resource> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<Resource>>> 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<Resource>>>>() {
                @Override
                public Observable<ServiceResponse<Page<Resource>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<Resource>> result = listNextDelegate(response);
                        return Observable.just(new ServiceResponse<Page<Resource>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

}


text:
yum groupinstall 'Development Tools'

yum install -y httpd-devel openssl-devel zlib-devel gcc gcc-c++ curl-devel \
  expat-devel gettext-devel patch readline readline-devel zlib zlib-devel \
  libyaml-devel libffi-devel make bzip2 zlib1g wget

#######################################################
# Build Ruby
#######################################################

# Keep it clean
mkdir /tmp/ruby
cd /tmp/ruby

# Configure libyaml
wget http://pyyaml.org/download/libyaml/yaml-0.1.4.tar.gz
tar xzvf yaml-0.1.4.tar.gz
cd yaml-0.1.4
./configure --prefix=/usr/local
make
make install
cd /tmp/ruby

# build ruby-1.9.3-p484
wget http://cache.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p484.tar.gz
tar -xzf ruby-1.9.3-p484.tar.gz
cd ruby-1.9.3-p484
./configure && make && make install
cd /tmp/ruby

# install ruby-gems 2.1.11
wget http://production.cf.rubygems.org/rubygems/rubygems-2.1.11.tgz
tar -xzf rubygems-2.1.11.tgz
cd rubygems-2.1.11
ruby setup.rb

# clean up
cd /
rm -rf /tmp/ruby

#######################################################
# Install Puppet
#######################################################
gem install puppet --no-rdoc --no-ri

# add the puppet group
groupadd puppet

#######################################################
# Install Chef
#######################################################
gem install chef ohai --no-ri --no-rdoc

#######################################################
# Turn off un-needed services
#######################################################
chkconfig sendmail off
chkconfig vbox-add-x11 off
chkconfig smartd off
chkconfig ntpd off
chkconfig cupsd off

########################################################
# Cleanup for compression
#######################################################
# Remove ruby build libs
yum -y remove zlib-devel openssl-devel readline-devel

# Cleanup other files we do not need
yum -y groupremove "Dialup Networking Support" Editors "Printing Support" "Additional Development" "E-mail server"

# Clean cache
yum clean all

# Clean out all of the caching dirs
rm -rf /var/cache/* /usr/share/doc/*

redpajama_set_name: RedPajamaGithub


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateGroupsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('group_name', 100)->unique();
            $table->boolean('group_state')->default(false);
            $table->enum('group_type', ['curso', 'taller', 'servicio'])->default('curso');
            //$table->text('group_description');

            $table->integer('categ_id', false, true)->nullable();
            $table->foreign('categ_id')->references('id')->on('categories')->onDelete('cascade');

            $table->integer('user_teacher', false, true)->nullable();
            $table->foreign('user_teacher')->references('id')->on('users');

            /*
            $table->integer('user_student', false, true)->nullable();
            $table->foreign('user_student')->references('id')->on('users');
            $table->date('group_begin');
            */

            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('groups');
    }
}


text:
#ifndef KEY_INFO_HPP
#define KEY_INFO_HPP

#include "SignalData.hpp"

class KeyInfo {
  /**
   * Sender(s)
   */
  friend class DbUtil;
  friend class NdbOperation;
  friend class NdbScanOperation;
  friend class NdbIndexScanOperation;
  friend class Restore;

  /**
   * Reciver(s)
   */
  friend class Dbtc;

public:
  STATIC_CONST( HeaderLength = 3 );
  STATIC_CONST( DataLength = 20 );
  STATIC_CONST( MaxSignalLength = HeaderLength + DataLength );

private:
  Uint32 connectPtr;
  Uint32 transId[2];
  Uint32 keyData[DataLength];
};

#endif


text:
define([
    'uijet_dir/uijet',
    'resources',
    'controllers/ItemsList',
    'ui/sheet'
], function (uijet, resources) {

    uijet.Resource('ItemsSearchResult', resources.Items);

    return [{
        type    : 'List',
        config  : {
            element     : '#items_list_header',
            horizontal  : true,
            position    : 'top:27px fluid',
            signals     : {
                pre_select  : function ($selected) {
                    if ( this.$selected && $selected[0] === this.$selected[0] ) {
                        this.$selected.toggleClass('desc');
                    }
                    return {
                        column  : $selected.attr('data-column'),
                        desc    : $selected.hasClass('desc')
                    };
                }
            }
        }
    }, {
        type    : 'List',
        config  : {
            element         : '#items_list',
            mixins          : ['Templated', 'Scrolled'],
            adapters        : ['jqWheelScroll', 'Spin', 'ItemsList'],
            resource        : 'LatestSheet',
            position        : 'fluid',
            fetch_options   : {
                remove  : false,
                cache   : true,
                expires : 8 * 3600,
                data    : {
                    page_by : 4000,
                    parents : 'none'
                }
            },
            search          : {
                fields  : {
                    name        : 10,
                    description : 1,
                    code        : 20
                }
            },
            filters         : {
                search  : 'search'
            },
            sorting         : {
                name        : 'name',
                '-name'     : resources.utils.reverseSorting('name'),
                code        : 'code',
                '-code'     : resources.utils.reverseSorting('code'),
                direction   : 'direction',
                '-direction': resources.utils.reverseSorting('direction'),
                budget      : 'budget',
                '-budget'   : resources.utils.reverseSorting('budget'),
                actual      : 'actual',
                '-actual'   : resources.utils.reverseSorting('actual')
            },
            data_events     : {
                request : function (resource, xhr, options) {
                    if ( this.last_request && this.last_request.state() == 'pending' ) {
                        this.last_request.abort();
                    }
                    this.last_request = xhr;
                },
                reset   : function () {
                    this.has_data = true;
                    delete this.$original_children;
                },
                sort    : function () {
                    uijet.Resource('ItemsListState').set('comments_item', null);
                }
            },
            signals         : {
                post_init       : function () {
                    var state_model = uijet.Resource('ItemsListState');

                    this.scope = window.ITEM.node || null;
                    this.resource.reset(this.resource.parse(window.ITEMS_LIST));
                    this.index();

                    this.options.fetch_options.data.sheets = state_model.get('sheet');

                    this.listenTo(state_model, 'change', function (model, options) {
                        var changed = model.changedAttributes(),
                            search = null,
                            sheet, scope,
                            prev, prev_sheets, prev_sheet;

                        if ( ! changed )
                            return;

                        if ( 'search' in changed ) {
                            search = model.get('search');
                            if ( ! search ) {
                                prev = state_model.previous('search');
                                if ( ! prev ) {
                                    state_model.set('search', null, { silent : true });
                                    return;
                                }
                            }
                        }

                        if ( 'sheet' in changed ) {
                            prev = model.previous('sheet');

                            // make sure we cache the previous sheet
                            if ( prev ) {
                                prev_sheets = uijet.Resource('PreviousSheets');

                                // assigning in purpose to reuse as previous sheet
                                if ( prev_sheet = prev_sheets.get(prev) ) {
                                    // update cache of previous Items collection with current LatestSheet state
                                    prev_sheet.get('items').set(this.resource.models, { remove : false });
                                }
                                else {
                                    prev_sheets.add({
                                        id      : prev,
                                        items   : this.resource.clone()
                                    });
                                }
                            }
                            sheet = model.get('sheet');
                        }
                        else if ( 'scope' in changed ) {
                            scope = model.get('scope');
                        }
                        else if ( ! ('search' in changed) ) {
                            // move along people, nothing to see here
                            return;
                        }

                        this._finally().wake({
                            sheets  : sheet,
                            search  : search,
                            scope   : scope === void 0 ? model.get('scope') : scope || null
                        });
                    });
                },
                pre_wake        : function () {
                    // usually on first load when there's no context, just bail out
                    if ( ! this.context ) return false;

                    var state = uijet.Resource('ItemsListState'),
                        undef = void 0,
                        scope = 'scope' in this.context ? this.context.scope || null : undef,
                        sheet = this.context.sheets,
                        search = this.context.search || state.get('search'),
                        prev_sheet;

                    if ( sheet ) {
                        if ( prev_sheet = uijet.Resource('PreviousSheets').get(sheet) ) {
                            this.resource = prev_sheet.get('items');
                            // register current collection as the new instance
                            uijet.Resource('LatestSheet', this.resource, true);
                            scope = scope === -1 ?
                                this.resource.findWhere({ uuid : state.get('uuid') }).get('node') :
                                scope;
                        }
                        else {
                            // instantiate a new collection
                            this.resource = new resources.Items();
                            // register it
                            uijet.Resource('LatestSheet', this.resource, true);
                        }
                    }
                    // if for some reason scope is still unknown reset it to `null`
                    if ( scope === -1 ) {
                        scope = null;
                    }

                    this.search_active = !!search;

                    delete this.filtered;
                    this.has_data = false;

                    if ( sheet ) {
                        this.sheet_changed = true;
                        this.options.fetch_options.data.sheets = sheet;
                    }

                    if ( search ) {
                        this.options.fetch_options.data.search = search;
                        delete this.options.fetch_options.data.parents;
                    }
                    else {
                        delete this.options.fetch_options.data.search;
                        this.options.fetch_options.data.parents = (scope === undef ? this.scope : scope) || 'none';
                    }

                    // set scope if it's defined in the context
                    scope !== undef && this.setScope(scope);
                },
                pre_update      : 'spin',
                post_fetch_data : function (response) {
                    var scope_changed = this.scope_changed;
                    // after we had to reset because of sheet change make sure turn reset off again
                    if ( this.options.fetch_options.reset ) {
                        this.options.fetch_options.reset = false;
                    }
                    if ( this.search_active ) {
                        this.filter(uijet.Resource('ItemsSearchResult')
                            .reset(response.results)
                            .byAncestor(this.scope));
                    }
                    else {
                        this.filter(this.resource.byParent, this.scope);
                    }

                    if ( scope_changed ) {
                        this.scope_changed = false;
                        this._publishScope();
                    }
                    if ( this.sheet_changed ) {
                        this.sheet_changed = false;
                        scope_changed || this.publish('sheet_changed', null);
                    }

                    this.spinOff();
                },
                post_render     : function () {
                    this.$children = this.$element.children();
                    if ( this.search_active ) {
                        var search_term = uijet.Resource('ItemsListState').get('search');

                        this.publish('filter_count', this.$children.length)
                            ._prepareScrolledSize();

                        uijet.utils.requestAnimFrame( this.toggleHighlight.bind(this, search_term) );
                        uijet.utils.requestAnimFrame( this.scroll.bind(this) );
                    }
                    else {
                        this.scroll();
                    }

                    this._finally();
                },
                pre_select      : function ($selected, e) {
                    var is_comment_button = uijet.$(e.target).hasClass('item_comment_button');

                    if ( is_comment_button ) {
                        uijet.Resource('ItemsListState').set('comments_item', $selected);
                        return false;
                    }
                    else {
                        return +$selected.attr('data-id');
                    }
                },
                post_select     : function ($selected) {
                    var node_id = typeof $selected == 'number' ?
                            $selected :
                            +$selected.attr('data-id') || null;

                    uijet.Resource('ItemsListState').set('scope', node_id);
                }
            },
            app_events      : {
                'items_breadcrumbs.selected'                : 'post_select+',
                'items_breadcrumbs_history_menu.selected'   : 'post_select+',
                'items_list_header.selected'                : 'sortItems+',
                'comment_created'                           : function (response) {
                    var item = this.resource.get(response.item),
                        discussion,
                        sheet_re;
                    if ( item ) {
                        discussion = item.get('discussion') || [];
                        discussion.push(response);
                        item.set('discussion', discussion);

                        // we create a regex to test against keys that contain current sheet in cache
                        sheet_re = RegExp('sheets=' + this.options.fetch_options.data.sheets);

                        // clear all cache related to this sheet - just in case
                        Object.keys(resources.Backbone.fetchCache._cache).forEach(function (key) {
                            if ( sheet_re.test(key) ) {
                                resources.Backbone.fetchCache.clearItem(key);
                            }
                        }, this);

                        // bump the number of comments on the item
                        this.$element
                            .find('[data-item=' + response.item + ']')
                            .find('.item_comment_button')
                                .text(discussion.length);
                    }
                }
            }
        }
    }];

});


text:
#ifndef PARSERMATHHHINCLUDE
#define PARSERMATHHHINCLUDE

// ***************************************************************************
// ***************************************************************************
// This class collects various parser math functions.
// There are two reasons to have this class:
// 1. To keep the command processing class from getting too big.
// 2. Some of these functions are used in more than one class.
// ***************************************************************************
// ***************************************************************************

#include <string>
#include <sstream>
#include <vector>
#include <deque>

namespace PP
{
using std::string;
using std::stringstream;
using std::vector;
using std::deque;

class Parser_math
{

public:
    Parser_math();

    void do_op(int i1, int i2, int i3, deque <Word> &wq, Word &wres,
               stringstream &serr, int &ierr);
    void do_op_relational(int i1, int i2, int i3, deque <Word> &wq,
                          Word &wres, stringstream &serr, int &ierr);
    void do_op_logical(int i1, int i2, int i3, deque <Word> &wq,
                       Word &wres, stringstream &serr, int &ierr);
    void do_op_not(int i2, int i3, deque <Word> &wq,
                   Word &wres, stringstream &serr, int &ierr);

private:

};

} // End of the PP namespace

#endif


text:
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {

using internal::WireFormatLite;

namespace {

// For encodings with fixed sizes, returns that size in bytes.  Otherwise
// returns -1.
int FixedSize(FieldDescriptor::Type type) {
  switch (type) {
    case FieldDescriptor::TYPE_INT32   : return -1;
    case FieldDescriptor::TYPE_INT64   : return -1;
    case FieldDescriptor::TYPE_UINT32  : return -1;
    case FieldDescriptor::TYPE_UINT64  : return -1;
    case FieldDescriptor::TYPE_SINT32  : return -1;
    case FieldDescriptor::TYPE_SINT64  : return -1;
    case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size;
    case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size;
    case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size;
    case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size;
    case FieldDescriptor::TYPE_FLOAT   : return WireFormatLite::kFloatSize;
    case FieldDescriptor::TYPE_DOUBLE  : return WireFormatLite::kDoubleSize;

    case FieldDescriptor::TYPE_BOOL    : return WireFormatLite::kBoolSize;
    case FieldDescriptor::TYPE_ENUM    : return -1;

    case FieldDescriptor::TYPE_STRING  : return -1;
    case FieldDescriptor::TYPE_BYTES   : return -1;
    case FieldDescriptor::TYPE_GROUP   : return -1;
    case FieldDescriptor::TYPE_MESSAGE : return -1;

    // No default because we want the compiler to complain if any new
    // types are added.
  }
  GOOGLE_LOG(FATAL) << "Can't get here.";
  return -1;
}

void SetPrimitiveVariables(const FieldDescriptor* descriptor,
                           map<string, string>* variables,
                           const Options& options) {
  SetCommonFieldVariables(descriptor, variables, options);
  (*variables)["type"] = PrimitiveTypeName(descriptor->cpp_type());
  (*variables)["default"] = DefaultValue(descriptor);
  (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor));
  int fixed_size = FixedSize(descriptor->type());
  if (fixed_size != -1) {
    (*variables)["fixed_size"] = SimpleItoa(fixed_size);
  }
  (*variables)["wire_format_field_type"] =
      "::google::protobuf::internal::WireFormatLite::" + FieldDescriptorProto_Type_Name(
          static_cast<FieldDescriptorProto_Type>(descriptor->type()));
  (*variables)["full_name"] = descriptor->full_name();
}

}  // namespace

// ===================================================================

PrimitiveFieldGenerator::
PrimitiveFieldGenerator(const FieldDescriptor* descriptor,
                        const Options& options)
  : descriptor_(descriptor) {
  SetPrimitiveVariables(descriptor, &variables_, options);
}

PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {}

void PrimitiveFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
  printer->Print(variables_, "$type$ $name$_;\n");
}

void PrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
  printer->Print(variables_,
    "inline $type$ $name$() const$deprecation$;\n"
    "inline void set_$name$($type$ value)$deprecation$;\n");
}

void PrimitiveFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
  printer->Print(variables_,
    "inline $type$ $classname$::$name$() const {\n"
    "  // @@protoc_insertion_point(field_get:$full_name$)\n"
    "  return $name$_;\n"
    "}\n"
    "inline void $classname$::set_$name$($type$ value) {\n"
    "  set_has_$name$();\n"
    "  $name$_ = value;\n"
    "  // @@protoc_insertion_point(field_set:$full_name$)\n"
    "}\n");
}

void PrimitiveFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
  printer->Print(variables_, "$name$_ = $default$;\n");
}

void PrimitiveFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
  printer->Print(variables_, "set_$name$(from.$name$());\n");
}

void PrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
  printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
}

void PrimitiveFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
  printer->Print(variables_, "$name$_ = $default$;\n");
}

void PrimitiveFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
  printer->Print(variables_,
    "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
    "         $type$, $wire_format_field_type$>(\n"
    "       input, &$name$_)));\n"
    "set_has_$name$();\n");
}

void PrimitiveFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
  printer->Print(variables_,
    "::google::protobuf::internal::WireFormatLite::Write$declared_type$("
      "$number$, this->$name$(), output);\n");
}

void PrimitiveFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
  printer->Print(variables_,
    "target = ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray("
      "$number$, this->$name$(), target);\n");
}

void PrimitiveFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
  int fixed_size = FixedSize(descriptor_->type());
  if (fixed_size == -1) {
    printer->Print(variables_,
      "total_size += $tag_size$ +\n"
      "  ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
      "    this->$name$());\n");
  } else {
    printer->Print(variables_,
      "total_size += $tag_size$ + $fixed_size$;\n");
  }
}

// ===================================================================

PrimitiveOneofFieldGenerator::
PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor,
                             const Options& options)
  : PrimitiveFieldGenerator(descriptor, options) {
  SetCommonOneofFieldVariables(descriptor, &variables_);
}

PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {}

void PrimitiveOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
  printer->Print(variables_,
    "inline $type$ $classname$::$name$() const {\n"
    "  if (has_$name$()) {\n"
    "    return $oneof_prefix$$name$_;\n"
    "  }\n"
    "  return $default$;\n"
    "}\n"
    "inline void $classname$::set_$name$($type$ value) {\n"
    "  if (!has_$name$()) {\n"
    "    clear_$oneof_name$();\n"
    "    set_has_$name$();\n"
    "  }\n"
    "  $oneof_prefix$$name$_ = value;\n"
    "}\n");
}

void PrimitiveOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
  printer->Print(variables_, "$oneof_prefix$$name$_ = $default$;\n");
}

void PrimitiveOneofFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
  // Don't print any swapping code. Swapping the union will swap this field.
}

void PrimitiveOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
  printer->Print(
      variables_,
      "  $classname$_default_oneof_instance_->$name$_ = $default$;\n");
}

void PrimitiveOneofFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
  printer->Print(variables_,
    "clear_$oneof_name$();\n"
    "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
    "         $type$, $wire_format_field_type$>(\n"
    "       input, &$oneof_prefix$$name$_)));\n"
    "set_has_$name$();\n");
}

// ===================================================================

RepeatedPrimitiveFieldGenerator::
RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
                                const Options& options)
  : descriptor_(descriptor) {
  SetPrimitiveVariables(descriptor, &variables_, options);

  if (descriptor->options().packed()) {
    variables_["packed_reader"] = "ReadPackedPrimitive";
    variables_["repeated_reader"] = "ReadRepeatedPrimitiveNoInline";
  } else {
    variables_["packed_reader"] = "ReadPackedPrimitiveNoInline";
    variables_["repeated_reader"] = "ReadRepeatedPrimitive";
  }
}

RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {}

void RepeatedPrimitiveFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
  printer->Print(variables_,
    "::google::protobuf::RepeatedField< $type$ > $name$_;\n");
  if (descriptor_->options().packed() && HasGeneratedMethods(descriptor_->file())) {
    printer->Print(variables_,
      "mutable int _$name$_cached_byte_size_;\n");
  }
}

void RepeatedPrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
  printer->Print(variables_,
    "inline $type$ $name$(int index) const$deprecation$;\n"
    "inline void set_$name$(int index, $type$ value)$deprecation$;\n"
    "inline void add_$name$($type$ value)$deprecation$;\n");
  printer->Print(variables_,
    "inline const ::google::protobuf::RepeatedField< $type$ >&\n"
    "    $name$() const$deprecation$;\n"
    "inline ::google::protobuf::RepeatedField< $type$ >*\n"
    "    mutable_$name$()$deprecation$;\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
  printer->Print(variables_,
    "inline $type$ $classname$::$name$(int index) const {\n"
    "  // @@protoc_insertion_point(field_get:$full_name$)\n"
    "  return $name$_.Get(index);\n"
    "}\n"
    "inline void $classname$::set_$name$(int index, $type$ value) {\n"
    "  $name$_.Set(index, value);\n"
    "  // @@protoc_insertion_point(field_set:$full_name$)\n"
    "}\n"
    "inline void $classname$::add_$name$($type$ value) {\n"
    "  $name$_.Add(value);\n"
    "  // @@protoc_insertion_point(field_add:$full_name$)\n"
    "}\n");
  printer->Print(variables_,
    "inline const ::google::protobuf::RepeatedField< $type$ >&\n"
    "$classname$::$name$() const {\n"
    "  // @@protoc_insertion_point(field_list:$full_name$)\n"
    "  return $name$_;\n"
    "}\n"
    "inline ::google::protobuf::RepeatedField< $type$ >*\n"
    "$classname$::mutable_$name$() {\n"
    "  // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
    "  return &$name$_;\n"
    "}\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
  printer->Print(variables_, "$name$_.Clear();\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
  printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
  printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
  // Not needed for repeated fields.
}

void RepeatedPrimitiveFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
  printer->Print(variables_,
    "DO_((::google::protobuf::internal::WireFormatLite::$repeated_reader$<\n"
    "         $type$, $wire_format_field_type$>(\n"
    "       $tag_size$, $tag$, input, this->mutable_$name$())));\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
  printer->Print(variables_,
    "DO_((::google::protobuf::internal::WireFormatLite::$packed_reader$<\n"
    "         $type$, $wire_format_field_type$>(\n"
    "       input, this->mutable_$name$())));\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
  if (descriptor_->options().packed()) {
    // Write the tag and the size.
    printer->Print(variables_,
      "if (this->$name$_size() > 0) {\n"
      "  ::google::protobuf::internal::WireFormatLite::WriteTag("
          "$number$, "
          "::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, "
          "output);\n"
      "  output->WriteVarint32(_$name$_cached_byte_size_);\n"
      "}\n");
  }
  printer->Print(variables_,
      "for (int i = 0; i < this->$name$_size(); i++) {\n");
  if (descriptor_->options().packed()) {
    printer->Print(variables_,
      "  ::google::protobuf::internal::WireFormatLite::Write$declared_type$NoTag(\n"
      "    this->$name$(i), output);\n");
  } else {
    printer->Print(variables_,
      "  ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n"
      "    $number$, this->$name$(i), output);\n");
  }
  printer->Print("}\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
  if (descriptor_->options().packed()) {
    // Write the tag and the size.
    printer->Print(variables_,
      "if (this->$name$_size() > 0) {\n"
      "  target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n"
      "    $number$,\n"
      "    ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
      "    target);\n"
      "  target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(\n"
      "    _$name$_cached_byte_size_, target);\n"
      "}\n");
  }
  printer->Print(variables_,
      "for (int i = 0; i < this->$name$_size(); i++) {\n");
  if (descriptor_->options().packed()) {
    printer->Print(variables_,
      "  target = ::google::protobuf::internal::WireFormatLite::\n"
      "    Write$declared_type$NoTagToArray(this->$name$(i), target);\n");
  } else {
    printer->Print(variables_,
      "  target = ::google::protobuf::internal::WireFormatLite::\n"
      "    Write$declared_type$ToArray($number$, this->$name$(i), target);\n");
  }
  printer->Print("}\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
  printer->Print(variables_,
    "{\n"
    "  int data_size = 0;\n");
  printer->Indent();
  int fixed_size = FixedSize(descriptor_->type());
  if (fixed_size == -1) {
    printer->Print(variables_,
      "for (int i = 0; i < this->$name$_size(); i++) {\n"
      "  data_size += ::google::protobuf::internal::WireFormatLite::\n"
      "    $declared_type$Size(this->$name$(i));\n"
      "}\n");
  } else {
    printer->Print(variables_,
      "data_size = $fixed_size$ * this->$name$_size();\n");
  }

  if (descriptor_->options().packed()) {
    printer->Print(variables_,
      "if (data_size > 0) {\n"
      "  total_size += $tag_size$ +\n"
      "    ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
      "}\n"
      "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
      "_$name$_cached_byte_size_ = data_size;\n"
      "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
      "total_size += data_size;\n");
  } else {
    printer->Print(variables_,
      "total_size += $tag_size$ * this->$name$_size() + data_size;\n");
  }
  printer->Outdent();
  printer->Print("}\n");
}

}  // namespace cpp
}  // namespace compiler
}  // namespace protobuf
}  // namespace google


text:
const configuration = require('../../lib/configuration');
const nock = require('nock');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const _ = require('lodash');

chai.use(chaiAsPromised);
nock.disableNetConnect();
configuration.authorization = 'Token 123123123';

global.nock = nock;
global.expect = chai.expect;
global.configuration = configuration;
global._ = _;

global.gonebusy = require('../../lib/index');

global.testPath = __dirname.slice(0, -8);
global.rootPath = testPath.slice(0, -5);

global.fixturesPath = `${testPath}/fixtures`;


text:
<?php

namespace JamesRezo\WebHelper\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use JamesRezo\WebHelper\Factory;
use JamesRezo\WebHelper\WebServer\NullWebServer;

/**
 * Base WebHelper command.
 */
class BaseCommand extends Command
{
    protected function getPath(InputInterface $input)
    {
        $path = $input->getArgument('path');

        if (empty($path)) {
            $path = explode(PATH_SEPARATOR, getenv('PATH'));
        }

        return $path;
    }

    protected function getWebServer(InputInterface $input, OutputInterface $output)
    {
        $webservername = $input->getArgument('webserver');
        $version = 0;
        if (preg_match(',([^:]+)(:([\.\d]+))$,', $webservername, $matches)) {
            $version = $matches[3];
            $webservername = $matches[1];
        }

        $factory = new Factory();

        $webserver = $factory->createWebServer($webservername, $version);
        if ($webserver instanceof NullWebServer) {
            $output->writeln('<error>Web Server "'.$webservername.'" unknown.</error>');
            $output->writeln(
                '<comment>Known Web Servers are '.
                implode(' or ', $factory->getKnownWebServers()).
                '.</comment>'
            );
        }

        return $webserver;
    }
}


text:
layout: page
title: Code Workshop
navigation:
  show: false
---
<!DOCTYPE html>
<html>
  <head>
    <link rel="canonical" href="{{root_url}}/Utilities/code_workshop.html"/>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta http-equiv="refresh" content="0;url=/docs/Utilities/code_workshop.html" />
  </head>
</html>


text:
using IORAMHelper;
using System.Drawing;
using System.Drawing.Imaging;

/// <summary>
/// Repräsentiert eine Farbpalette (JASC *.pal-Format)
/// </summary>
/// <remarks></remarks>
namespace BitmapLibrary
{
	public class JASCPalette
	{
		private string _header = "";
		private string _version = "";
		private int _anzFarben = 0;

		/// <summary>
		/// Enthält die Farbdaten. Sortierung: FarbID => Array(0 => R, 1 => G, 2 => B)
		/// </summary>
		/// <remarks></remarks>
		public byte[,] _farben;

		/// <summary>
		/// Der Datenpuffer.
		/// </summary>
		private RAMBuffer _buffer;

		/// <summary>
		/// Erstellt eine neue Instanz von JASCPalette aus den angegebenen Daten.
		/// </summary>
		/// <param name="Data">Die Farbdaten als PufferKlasse-Objekt.</param>
		/// <remarks></remarks>
		public JASCPalette(RAMBuffer data)
		{
			_buffer = data;
			ReadPalette();
		}

		/// <summary>
		/// Liest die Farbpalette.
		/// </summary>
		/// <remarks></remarks>
		private void ReadPalette()
		{
			_buffer.Position = 0;

			// Header
			byte aktByte = _buffer.ReadByte();
			while(aktByte != 13 & aktByte != 10)
			{
				_header += (char)(aktByte);
				aktByte = _buffer.ReadByte();
			}

			// Übergehen von Zeilenumbruch (LF)
			_buffer.ReadByte();

			// Version
			aktByte = _buffer.ReadByte();
			while(aktByte != 13 & aktByte != 10)
			{
				_version += (char)(aktByte);
				aktByte = _buffer.ReadByte();
			}

			// Übergehen von Zeilenumbruch (LF)
			_buffer.ReadByte();

			// Anzahl Farben
			string AnzFarbenTemp = "";
			aktByte = _buffer.ReadByte();
			while(aktByte != 13 & aktByte != 10)
			{
				AnzFarbenTemp += (char)(aktByte);
				aktByte = _buffer.ReadByte();
			}
			_anzFarben = int.Parse(AnzFarbenTemp);

			// Übergehen von Zeilenumbruch (LF)
			_buffer.ReadByte();

			// Farbdaten Zeile für Zeile auslesen
			_farben = new byte[_anzFarben, 3];
			for(int i = 0; i < _anzFarben; i++)
			{
				// Rot
				string RTemp = "";
				aktByte = _buffer.ReadByte();
				while(aktByte != 13 & aktByte != 10 & aktByte != 32)
				{
					RTemp += (char)(aktByte);
					aktByte = _buffer.ReadByte();
				}

				// Grün
				string GTemp = "";
				aktByte = _buffer.ReadByte();
				while(aktByte != 13 & aktByte != 10 & aktByte != 32)
				{
					GTemp += (char)(aktByte);
					aktByte = _buffer.ReadByte();
				}

				// Blau
				string BTemp = "";
				aktByte = _buffer.ReadByte();
				while(aktByte != 13 & aktByte != 10 & aktByte != 32)
				{
					BTemp += (char)(aktByte);
					aktByte = _buffer.ReadByte();
				}

				// Bytewerte aus Strings erstellen
				byte R = byte.Parse(RTemp);
				byte G = byte.Parse(GTemp);
				byte B = byte.Parse(BTemp);

				// Werte in Farbarray einfügen
				_farben[i, 0] = R;
				_farben[i, 1] = G;
				_farben[i, 2] = B;

				// Übergehen von Zeilenumbruch (LF)
				_buffer.ReadByte();
			}
		}

		/// <summary>
		/// Erstellt eine .NET-Farbpalette aus der geladenen Palettendatei.
		/// </summary>
		/// <returns></returns>
		public ColorPalette GetColorPalette()
		{
			// Palettenobjekt intialisieren
			ColorPalette Palette = new Bitmap(1, 1, PixelFormat.Format8bppIndexed).Palette;

			// Alle Farben einzeln übertragen
			for(int i = 0; i < _anzFarben; i++)
			{
				// ARGB-Werte bestimmen
				byte A = 0;
				byte R = _farben[i, 0];
				byte G = _farben[i, 1];
				byte B = _farben[i, 2];

				// Eintrag schreiben
				Palette.Entries[i] = Color.FromArgb(A, R, G, B);
			}

			// Fertig
			return Palette;
		}

		#region Eigenschaften

		/// <summary>
		/// Gibt die zur Farb-ID passende Farbe als Color-Objekt zurück.
		/// </summary>
		/// <param name="ColorID">Die ID der abzurufenden Farbe.</param>
		/// <param name="useWhite255Transp">Legt fest, ob Weiß 255 als transparent angegeben werden soll.</param>
		/// <returns></returns>
		/// <remarks></remarks>
		public Color GetColor(ushort ColorID, bool useWhite255Transp = false)
		{
			// Farbe zurückgeben
			return Color.FromArgb((useWhite255Transp && ColorID == 255) ? 0 : 255, _farben[ColorID, 0], _farben[ColorID, 1], _farben[ColorID, 2]);
		}

		#endregion Eigenschaften
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

    <include layout="@layout/layout_main_content"/>

    <!-- 抽屉 -->
    <LinearLayout
            android:id="@+id/drawer_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@color/viewBackgroundColor"
            android:fitsSystemWindows="true"
            android:orientation="vertical">

        <include layout="@layout/view_nav_header"/>

        <wb.app.seek.widgets.DrawerItemView
                android:id="@+id/nav_home"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:divImage="@drawable/ic_home_32"
                app:divText="@string/nav_home"/>

        <wb.app.seek.widgets.DrawerItemView
                android:id="@+id/nav_setting"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:divImage="@drawable/ic_setting_32"
                app:divText="@string/nav_setting"/>

        <wb.app.seek.widgets.DrawerItemView
                android:id="@+id/nav_about"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:divImage="@drawable/ic_about_32"
                app:divText="@string/nav_about"/>

    </LinearLayout>

    <!--<android.support.design.widget.NavigationView-->
    <!--android:id="@+id/nav_view"-->
    <!--android:layout_width="wrap_content"-->
    <!--android:layout_height="match_parent"-->
    <!--android:layout_gravity="start"-->
    <!--android:fitsSystemWindows="true"-->
    <!--app:headerLayout="@layout/view_nav_header"-->
    <!--app:menu="@menu/menu_drawer"/>-->

</android.support.v4.widget.DrawerLayout>


text:
package net.meisen.dissertation.model.util;

/**
 * Iterator used to iterate over integers.
 *
 * @author pmeisen
 *
 */
public interface IIntIterator {

	/**
	 * Is there more?
	 *
	 * @return {@code true}, if there is more, {@code false} otherwise
	 */
	public boolean hasNext();

	/**
	 * Return the next integer.
	 *
	 * @return the integer
	 */
	public int next();

}


text:
package com.douglaswhitehead.controller.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.douglaswhitehead.datalayer.OrderDataLayer;
import com.douglaswhitehead.model.Address;
import com.douglaswhitehead.model.Order;
import com.douglaswhitehead.model.OrderForm;
import com.douglaswhitehead.model.ShoppingCart;
import com.douglaswhitehead.model.ShoppingCartItem;
import com.douglaswhitehead.model.User;

@RestController
@RequestMapping("/data/orders")
public class OrderDataControllerImpl extends AbstractDataController implements OrderDataController {

	@Autowired
	private OrderDataLayer dataLayer;

	@Override
	@RequestMapping(value = "/checkout", method = RequestMethod.GET)
	public Map<String, Object> checkout(final OrderForm orderForm, final HttpServletRequest request, final Device device,
			final HttpServletResponse response) {
		boolean auth = isAuthenticated();
		String cartId;

		if (!checkCartIdCookie(request)) {
			String error = "No cartId cookie.";
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("error", error);
			return map;
		} else {
			Cookie cookie = getCartIdCookie(request);
			cartId = cookie.getValue();
		}

		ShoppingCart cart = cartService.get(UUID.fromString(cartId));

		if (cart.getCartItems() == null || cart.getCartItems().size() == 0) {
			String error = "No items in cart to checkout.";
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("error", error);
			return map;
		}

		User user = null;
		if (auth) {
			user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}

		Map<String, Object> map = new HashMap<String, Object>();

		String digitalData = digitalDataAdapter.adapt(dataLayer.checkout(request, response, device, cart, user));

		map.put("isAuthenticated", auth);
		map.put("cartId", cart.getId().toString());
		map.put("cartSize", calculateCartSize(cart));
		map.put("digitalData", digitalData);

		return map;
	}

	@Override
	@RequestMapping(value = "/complete", method = RequestMethod.POST)
	public Map<String, Object> complete(@RequestBody final OrderForm orderForm, final HttpServletRequest request, final Device device,
			final HttpServletResponse response) {
		boolean auth = isAuthenticated();
		String cartId;

		if (!checkCartIdCookie(request)) {
			String error = "Order error. No cartId cookie.";
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("error", error);
			return map;
		} else {
			Cookie cookie = getCartIdCookie(request);
			cartId = cookie.getValue();
		}

		// in a prod env, we would validate shipping address info here
		// validateShippingAddress();
		Address shippingAddress = new Address(orderForm.getRecipientName(), orderForm.getLine1(), orderForm.getLine2(),
								  orderForm.getCity(), orderForm.getStateProvince(), orderForm.getPostalCode(),
								  orderForm.getCountry());

		// in a prod env, we would validate payment info here (or maybe in a separate form step)
		// validatePaymentInfo();

		ShoppingCart cart = cartService.get(UUID.fromString(cartId));
		User user = null;
		if (auth) {
			user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}

		// simulates placing an order
		// in a prod env, this would be replaced with a real order service and back end
		try {
			// remove items from shopping cart, since they are being purchased
			List<ShoppingCartItem> itemsToRemove = new ArrayList<ShoppingCartItem>();
			if (cart != null) {
				for (ShoppingCartItem item: cart.getCartItems()) {
					for (int i=1;i<=item.getQuantity();i++) {
						itemsToRemove.add(item);
					}
				}
			}
			for (ShoppingCartItem item: itemsToRemove) {
				cartService.removeFromCart(cart.getId(), item.getId());
			}

		    Thread.sleep(5000); // simulate long-running purchase transaction
		} catch(InterruptedException ex) {
		    Thread.currentThread().interrupt();
		}

		// simulate order service response, which would return an order
		Order order = new Order(UUID.randomUUID(), cart.getBasePrice(), cart.getVoucherCode(), cart.getVoucherDiscount(),
					  cart.getCurrency(), cart.getTaxRate(), cart.getShipping(), cart.getShippingMethod(),
					  cart.getPriceWithTax(), cart.getCartTotal(), cart.getCartItems(), shippingAddress);

		Map<String, Object> map = new HashMap<String, Object>();

		String digitalData = digitalDataAdapter.adapt(dataLayer.complete(request, response, device, cart, order, user));

		map.put("isAuthenticated", auth);
		map.put("cartId", cart.getId().toString());
		map.put("cartSize", 0); // cart items is now 0
		map.put("order", order);
		map.put("digitalData", digitalData);

		return map;
	}

}


text:
using Microsoft.SharePoint.Client;
using System;

namespace SP.Client.Linq.Attributes
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = true, AllowMultiple = false)]
    public class ContentTypeAttribute : Attribute
    {
        public ContentTypeAttribute()
        {
        }

        public virtual string Id { get; set; }

        public virtual string Name { get; set; }

        public virtual string Group { get; set; }

        public virtual string ParentId { get; set; }
    }
}