text:
package com.microsoft.azure.management.sql.v2017_03_01_preview.implementation;

import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.management.sql.v2017_03_01_preview.CreateDatabaseRestorePointDefinition;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
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.POST;
import retrofit2.http.Query;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * An instance of this class provides access to all the operations defined
 * in RestorePoints.
 */
public class RestorePointsInner {
    /** The Retrofit service to perform REST calls. */
    private RestorePointsService service;
    /** The service client containing this operation class. */
    private SqlManagementClientImpl client;

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

    /**
     * The interface defining all the services for RestorePoints to be
     * used by Retrofit to perform actually REST calls.
     */
    interface RestorePointsService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sql.v2017_03_01_preview.RestorePoints listByDatabase" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/restorePoints")
        Observable<Response<ResponseBody>> listByDatabase(@Path("resourceGroupName") String resourceGroupName, @Path("serverName") String serverName, @Path("databaseName") String databaseName, @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.sql.v2017_03_01_preview.RestorePoints create" })
        @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/restorePoints")
        Observable<Response<ResponseBody>> create(@Path("resourceGroupName") String resourceGroupName, @Path("serverName") String serverName, @Path("databaseName") String databaseName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateDatabaseRestorePointDefinition parameters, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sql.v2017_03_01_preview.RestorePoints beginCreate" })
        @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/restorePoints")
        Observable<Response<ResponseBody>> beginCreate(@Path("resourceGroupName") String resourceGroupName, @Path("serverName") String serverName, @Path("databaseName") String databaseName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateDatabaseRestorePointDefinition parameters, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sql.v2017_03_01_preview.RestorePoints get" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/restorePoints/{restorePointName}")
        Observable<Response<ResponseBody>> get(@Path("resourceGroupName") String resourceGroupName, @Path("serverName") String serverName, @Path("databaseName") String databaseName, @Path("restorePointName") String restorePointName, @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.sql.v2017_03_01_preview.RestorePoints delete" })
        @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/restorePoints/{restorePointName}", method = "DELETE", hasBody = true)
        Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("serverName") String serverName, @Path("databaseName") String databaseName, @Path("restorePointName") String restorePointName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * Gets a list of database restore points.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the List<RestorePointInner> object if successful.
     */
    public List<RestorePointInner> listByDatabase(String resourceGroupName, String serverName, String databaseName) {
        return listByDatabaseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).toBlocking().single().body();
    }

    /**
     * Gets a list of database restore points.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<RestorePointInner>> listByDatabaseAsync(String resourceGroupName, String serverName, String databaseName, final ServiceCallback<List<RestorePointInner>> serviceCallback) {
        return ServiceFuture.fromResponse(listByDatabaseWithServiceResponseAsync(resourceGroupName, serverName, databaseName), serviceCallback);
    }

    /**
     * Gets a list of database restore points.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the List<RestorePointInner> object
     */
    public Observable<List<RestorePointInner>> listByDatabaseAsync(String resourceGroupName, String serverName, String databaseName) {
        return listByDatabaseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<List<RestorePointInner>>, List<RestorePointInner>>() {
            @Override
            public List<RestorePointInner> call(ServiceResponse<List<RestorePointInner>> response) {
                return response.body();
            }
        });
    }

    /**
     * Gets a list of database restore points.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the List<RestorePointInner> object
     */
    public Observable<ServiceResponse<List<RestorePointInner>>> listByDatabaseWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (serverName == null) {
            throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
        }
        if (databaseName == null) {
            throw new IllegalArgumentException("Parameter databaseName 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.listByDatabase(resourceGroupName, serverName, databaseName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<RestorePointInner>>>>() {
                @Override
                public Observable<ServiceResponse<List<RestorePointInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl1<RestorePointInner>> result = listByDatabaseDelegate(response);
                        List<RestorePointInner> items = null;
                        if (result.body() != null) {
                            items = result.body().items();
                        }
                        ServiceResponse<List<RestorePointInner>> clientResponse = new ServiceResponse<List<RestorePointInner>>(items, result.response());
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * Creates a restore point for a data warehouse.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointLabel The restore point label to apply
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the RestorePointInner object if successful.
     */
    public RestorePointInner create(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) {
        return createWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointLabel).toBlocking().last().body();
    }

    /**
     * Creates a restore point for a data warehouse.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointLabel The restore point label to apply
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<RestorePointInner> createAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel, final ServiceCallback<RestorePointInner> serviceCallback) {
        return ServiceFuture.fromResponse(createWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointLabel), serviceCallback);
    }

    /**
     * Creates a restore point for a data warehouse.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointLabel The restore point label to apply
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<RestorePointInner> createAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) {
        return createWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointLabel).map(new Func1<ServiceResponse<RestorePointInner>, RestorePointInner>() {
            @Override
            public RestorePointInner call(ServiceResponse<RestorePointInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Creates a restore point for a data warehouse.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointLabel The restore point label to apply
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<ServiceResponse<RestorePointInner>> createWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (serverName == null) {
            throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
        }
        if (databaseName == null) {
            throw new IllegalArgumentException("Parameter databaseName 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 (restorePointLabel == null) {
            throw new IllegalArgumentException("Parameter restorePointLabel is required and cannot be null.");
        }
        CreateDatabaseRestorePointDefinition parameters = new CreateDatabaseRestorePointDefinition();
        parameters.withRestorePointLabel(restorePointLabel);
        Observable<Response<ResponseBody>> observable = service.create(resourceGroupName, serverName, databaseName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent());
        return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<RestorePointInner>() { }.getType());
    }

    /**
     * Creates a restore point for a data warehouse.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointLabel The restore point label to apply
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the RestorePointInner object if successful.
     */
    public RestorePointInner beginCreate(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) {
        return beginCreateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointLabel).toBlocking().single().body();
    }

    /**
     * Creates a restore point for a data warehouse.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointLabel The restore point label to apply
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<RestorePointInner> beginCreateAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel, final ServiceCallback<RestorePointInner> serviceCallback) {
        return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointLabel), serviceCallback);
    }

    /**
     * Creates a restore point for a data warehouse.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointLabel The restore point label to apply
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the RestorePointInner object
     */
    public Observable<RestorePointInner> beginCreateAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) {
        return beginCreateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointLabel).map(new Func1<ServiceResponse<RestorePointInner>, RestorePointInner>() {
            @Override
            public RestorePointInner call(ServiceResponse<RestorePointInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Creates a restore point for a data warehouse.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointLabel The restore point label to apply
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the RestorePointInner object
     */
    public Observable<ServiceResponse<RestorePointInner>> beginCreateWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (serverName == null) {
            throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
        }
        if (databaseName == null) {
            throw new IllegalArgumentException("Parameter databaseName 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 (restorePointLabel == null) {
            throw new IllegalArgumentException("Parameter restorePointLabel is required and cannot be null.");
        }
        CreateDatabaseRestorePointDefinition parameters = new CreateDatabaseRestorePointDefinition();
        parameters.withRestorePointLabel(restorePointLabel);
        return service.beginCreate(resourceGroupName, serverName, databaseName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RestorePointInner>>>() {
                @Override
                public Observable<ServiceResponse<RestorePointInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<RestorePointInner> clientResponse = beginCreateDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * Gets a restore point.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointName The name of the restore point.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the RestorePointInner object if successful.
     */
    public RestorePointInner get(String resourceGroupName, String serverName, String databaseName, String restorePointName) {
        return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointName).toBlocking().single().body();
    }

    /**
     * Gets a restore point.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointName The name of the restore point.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<RestorePointInner> getAsync(String resourceGroupName, String serverName, String databaseName, String restorePointName, final ServiceCallback<RestorePointInner> serviceCallback) {
        return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointName), serviceCallback);
    }

    /**
     * Gets a restore point.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointName The name of the restore point.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the RestorePointInner object
     */
    public Observable<RestorePointInner> getAsync(String resourceGroupName, String serverName, String databaseName, String restorePointName) {
        return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointName).map(new Func1<ServiceResponse<RestorePointInner>, RestorePointInner>() {
            @Override
            public RestorePointInner call(ServiceResponse<RestorePointInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Gets a restore point.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointName The name of the restore point.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the RestorePointInner object
     */
    public Observable<ServiceResponse<RestorePointInner>> getWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName, String restorePointName) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (serverName == null) {
            throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
        }
        if (databaseName == null) {
            throw new IllegalArgumentException("Parameter databaseName is required and cannot be null.");
        }
        if (restorePointName == null) {
            throw new IllegalArgumentException("Parameter restorePointName 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, serverName, databaseName, restorePointName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RestorePointInner>>>() {
                @Override
                public Observable<ServiceResponse<RestorePointInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<RestorePointInner> clientResponse = getDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * Deletes a restore point.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointName The name of the restore point.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     */
    public void delete(String resourceGroupName, String serverName, String databaseName, String restorePointName) {
        deleteWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointName).toBlocking().single().body();
    }

    /**
     * Deletes a restore point.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointName The name of the restore point.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<Void> deleteAsync(String resourceGroupName, String serverName, String databaseName, String restorePointName, final ServiceCallback<Void> serviceCallback) {
        return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointName), serviceCallback);
    }

    /**
     * Deletes a restore point.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointName The name of the restore point.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<Void> deleteAsync(String resourceGroupName, String serverName, String databaseName, String restorePointName) {
        return deleteWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointName).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Deletes a restore point.
     *
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param databaseName The name of the database.
     * @param restorePointName The name of the restore point.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName, String restorePointName) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (serverName == null) {
            throw new IllegalArgumentException("Parameter serverName is required and cannot be null.");
        }
        if (databaseName == null) {
            throw new IllegalArgumentException("Parameter databaseName is required and cannot be null.");
        }
        if (restorePointName == null) {
            throw new IllegalArgumentException("Parameter restorePointName 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, serverName, databaseName, restorePointName, 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())
                .registerError(CloudException.class)
                .build(response);
    }

}


text:
package io.searchbox.snapshot;

/**
 * @author happyprg(hongsgo@gmail.com)
 */
public class SnapshotStatus extends AbstractSnapshotAction {

    protected SnapshotStatus(Builder builder) {
        super(builder);
    }

    @Override
    protected String buildURI() {
        return super.buildURI() + "/_status";
    }

    @Override
    public String getRestMethodName() {
        return "GET";
    }

    public static class Builder extends AbstractSnapshotAction.MultipleSnapshotBuilder<SnapshotStatus, Builder> {
        public Builder(String repository) {
            super(repository);
        }

        @Override
        public SnapshotStatus build() {
            return new SnapshotStatus(this);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
    /**
     * Created by JetBrains PhpStorm.
     * User: robert
     * Date: 10/10/13
     * Time: 8:13 AM
     * To change this template use File | Settings | File Templates.
     */

    class Driver {

        protected $_parent;

        private $_methods = array();
        private $_props = array();

        private static $_reflections = array();

        public function decorate($parent) {
            $this->_parent = $parent;
            $class         = get_class($parent);

            if(!isset(self::$_reflections[$class])) {
                $r = new ReflectionObject($parent);
                foreach($r->getMethods() as $method) {
                    if($method->isPublic()) {
                        $this->_methods[] = $method->getName();
                    }
                }
                foreach($r->getProperties() as $prop) {
                    if($prop->isPublic()) {
                        $this->_props[] = $prop->getName();
                    }
                }
                self::$_reflections[$class] = array($this->_methods, $this->_props);
            } else {
                list($this->_methods, $this->_props) = self::$_reflections[$class];
            }
        }

        public function __get($var) {
            if(in_array($var, $this->_props)) {
                return $this->_parent->$var;
            }
        }

        public function __call($method, $args = array()) {
            if(in_array($method, $this->_methods)) {
                return call_user_func_array(array($this->_parent, $method), $args);
            }
            $trace = debug_backtrace();
            ExceptionHandler::handle(E_ERROR, "no such method " . $method, $trace[1]['file'], $trace[1]['line']);
            exit;
        }

        public function __set($var, $val) {
            if(in_array($var, $this->_props)) {
                $this->_parent->$var = $val;
            }
        }

    }


text:
require 'test_helper'

class KeywordTest < ActiveSupport::TestCase
end


text:
package org.apache.jackrabbit.oak.segment.file.tar;

import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMapWithExpectedSize;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static com.google.common.collect.Maps.newTreeMap;
import static com.google.common.collect.Sets.newHashSet;
import static java.nio.ByteBuffer.wrap;
import static java.util.Collections.singletonList;
import static org.apache.jackrabbit.oak.segment.file.tar.GCGeneration.newGCGeneration;
import static org.apache.jackrabbit.oak.segment.file.tar.TarConstants.BLOCK_SIZE;
import static org.apache.jackrabbit.oak.segment.file.tar.TarConstants.GRAPH_MAGIC;
import static org.apache.jackrabbit.oak.segment.file.tar.index.IndexLoader.newIndexLoader;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;

import javax.annotation.Nonnull;

import com.google.common.base.Predicate;
import com.google.common.base.Stopwatch;
import org.apache.commons.io.FileUtils;
import org.apache.jackrabbit.oak.segment.file.tar.binaries.BinaryReferencesIndex;
import org.apache.jackrabbit.oak.segment.file.tar.binaries.BinaryReferencesIndexLoader;
import org.apache.jackrabbit.oak.segment.file.tar.binaries.InvalidBinaryReferencesIndexException;
import org.apache.jackrabbit.oak.segment.file.tar.index.Index;
import org.apache.jackrabbit.oak.segment.file.tar.index.IndexEntry;
import org.apache.jackrabbit.oak.segment.file.tar.index.IndexLoader;
import org.apache.jackrabbit.oak.segment.file.tar.index.InvalidIndexException;
import org.apache.jackrabbit.oak.segment.util.ReaderAtEnd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class TarReader implements Closeable {

    private static final Logger log = LoggerFactory.getLogger(TarReader.class);

    private static final IndexLoader indexLoader = newIndexLoader(BLOCK_SIZE);

    /**
     * Pattern of the segment entry names. Note the trailing (\\..*)? group
     * that's included for compatibility with possible future extensions.
     */
    private static final Pattern NAME_PATTERN = Pattern.compile(
            "([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"
            + "(\\.([0-9a-f]{8}))?(\\..*)?");

    private static int getEntrySize(int size) {
        return BLOCK_SIZE + size + TarWriter.getPaddingSize(size);
    }

    static TarReader open(File file, boolean memoryMapping, IOMonitor ioMonitor) throws IOException {
        TarReader reader = openFirstFileWithValidIndex(singletonList(file), memoryMapping, ioMonitor);
        if (reader != null) {
            return reader;
        } else {
            throw new IOException("Failed to open tar file " + file);
        }
    }

    /**
     * Creates a {@link TarReader} instance for reading content from a tar file.
     * If there exist multiple generations of the same tar file, they are all
     * passed to this method. The latest generation with a valid tar index
     * (which is a good indication of general validity of the file) is opened
     * and the other generations are removed to clean things up. If none of the
     * generations has a valid index, then something must have gone wrong and
     * we'll try recover as much content as we can from the existing tar
     * generations.
     *
     * @param files         The generations of the same TAR file.
     * @param memoryMapping If {@code true}, opens the TAR file with memory
     *                      mapping enabled.
     * @param recovery      Strategy for recovering a damaged TAR file.
     * @param ioMonitor     Callbacks to track internal operations for the open
     *                      TAR file.
     * @return An instance of {@link TarReader}.
     */
    static TarReader open(Map<Character, File> files, boolean memoryMapping, TarRecovery recovery, IOMonitor ioMonitor) throws IOException {
        SortedMap<Character, File> sorted = newTreeMap();
        sorted.putAll(files);

        List<File> list = newArrayList(sorted.values());
        Collections.reverse(list);

        TarReader reader = openFirstFileWithValidIndex(list, memoryMapping, ioMonitor);
        if (reader != null) {
            return reader;
        }

        // no generation has a valid index, so recover as much as we can
        log.warn("Could not find a valid tar index in {}, recovering...", list);
        LinkedHashMap<UUID, byte[]> entries = newLinkedHashMap();
        for (File file : sorted.values()) {
            collectFileEntries(file, entries, true);
        }

        // regenerate the first generation based on the recovered data
        File file = sorted.values().iterator().next();
        generateTarFile(entries, file, recovery, ioMonitor);

        reader = openFirstFileWithValidIndex(singletonList(file), memoryMapping, ioMonitor);
        if (reader != null) {
            return reader;
        } else {
            throw new IOException("Failed to open recovered tar file " + file);
        }
    }

    static TarReader openRO(Map<Character, File> files, boolean memoryMapping, TarRecovery recovery, IOMonitor ioMonitor) throws IOException {
        // for readonly store only try the latest generation of a given
        // tar file to prevent any rollback or rewrite
        File file = files.get(Collections.max(files.keySet()));
        TarReader reader = openFirstFileWithValidIndex(singletonList(file), memoryMapping, ioMonitor);
        if (reader != null) {
            return reader;
        }
        log.warn("Could not find a valid tar index in {}, recovering read-only", file);
        // collecting the entries (without touching the original file) and
        // writing them into an artificial tar file '.ro.bak'
        LinkedHashMap<UUID, byte[]> entries = newLinkedHashMap();
        collectFileEntries(file, entries, false);
        file = findAvailGen(file, ".ro.bak");
        generateTarFile(entries, file, recovery, ioMonitor);
        reader = openFirstFileWithValidIndex(singletonList(file), memoryMapping, ioMonitor);
        if (reader != null) {
            return reader;
        }
        throw new IOException("Failed to open tar file " + file);
    }

    /**
     * Collects all entries from the given file and optionally backs-up the
     * file, by renaming it to a ".bak" extension
     *
     * @param file    The TAR file.
     * @param entries The map where the recovered entries will be collected
     *                into.
     * @param backup  If {@code true}, performs a backup of the TAR file.
     */
    private static void collectFileEntries(File file, LinkedHashMap<UUID, byte[]> entries, boolean backup) throws IOException {
        log.info("Recovering segments from tar file {}", file);
        try {
            RandomAccessFile access = new RandomAccessFile(file, "r");
            try {
                recoverEntries(file, access, entries);
            } finally {
                access.close();
            }
        } catch (IOException e) {
            log.warn("Could not read tar file {}, skipping...", file, e);
        }

        if (backup) {
            backupSafely(file);
        }
    }

    /**
     * Regenerates a tar file from a list of entries.
     *
     * @param entries   Map of entries to recover. The entries will be recovered
     *                  in the iteration order of this {@link LinkedHashMap}.
     * @param file      The output file that will contain the recovered
     *                  entries.
     * @param recovery  The recovery strategy to execute.
     * @param ioMonitor An instance of {@link IOMonitor}.
     */
    private static void generateTarFile(LinkedHashMap<UUID, byte[]> entries, File file, TarRecovery recovery, IOMonitor ioMonitor) throws IOException {
        log.info("Regenerating tar file {}", file);

        try (TarWriter writer = new TarWriter(file, ioMonitor)) {
            for (Entry<UUID, byte[]> entry : entries.entrySet()) {
                try {
                    recovery.recoverEntry(entry.getKey(), entry.getValue(), new EntryRecovery() {

                        @Override
                        public void recoverEntry(long msb, long lsb, byte[] data, int offset, int size, GCGeneration generation) throws IOException {
                            writer.writeEntry(msb, lsb, data, offset, size, generation);
                        }

                        @Override
                        public void recoverGraphEdge(UUID from, UUID to) {
                            writer.addGraphEdge(from, to);
                        }

                        @Override
                        public void recoverBinaryReference(GCGeneration generation, UUID segmentId, String reference) {
                            writer.addBinaryReference(generation, segmentId, reference);
                        }

                    });
                } catch (IOException e) {
                    throw new IOException(String.format("Unable to recover entry %s for file %s", entry.getKey(), file), e);
                }
            }
        }
    }

    /**
     * Backup this tar file for manual inspection. Something went wrong earlier
     * so we want to prevent the data from being accidentally removed or
     * overwritten.
     *
     * @param file File to backup.
     */
    private static void backupSafely(File file) throws IOException {
        File backup = findAvailGen(file, ".bak");
        log.info("Backing up {} to {}", file, backup.getName());
        if (!file.renameTo(backup)) {
            log.warn("Renaming failed, so using copy to backup {}", file);
            FileUtils.copyFile(file, backup);
            if (!file.delete()) {
                throw new IOException(
                        "Could not remove broken tar file " + file);
            }
        }
    }

    /**
     * Fine next available generation number so that a generated file doesn't
     * overwrite another existing file.
     *
     * @param file The file to backup.
     * @param ext  The extension of the backed up file.
     */
    private static File findAvailGen(File file, String ext) {
        File parent = file.getParentFile();
        String name = file.getName();
        File backup = new File(parent, name + ext);
        for (int i = 2; backup.exists(); i++) {
            backup = new File(parent, name + "." + i + ext);
        }
        return backup;
    }

    private static TarReader openFirstFileWithValidIndex(List<File> files, boolean memoryMapping, IOMonitor ioMonitor) {
        for (File file : files) {
            String name = file.getName();
            try {
                RandomAccessFile access = new RandomAccessFile(file, "r");
                try {
                    Index index = loadAndValidateIndex(access, name);
                    if (index == null) {
                        log.info("No index found in tar file {}, skipping...", name);
                    } else {
                        // found a file with a valid index, drop the others
                        for (File other : files) {
                            if (other != file) {
                                log.info("Removing unused tar file {}", other.getName());
                                other.delete();
                            }
                        }

                        if (memoryMapping) {
                            try {
                                FileAccess mapped = new FileAccess.Mapped(access);
                                return new TarReader(file, mapped, index, ioMonitor);
                            } catch (IOException e) {
                                log.warn("Failed to mmap tar file {}. Falling back to normal file " +
                                        "IO, which will negatively impact repository performance. " +
                                        "This problem may have been caused by restrictions on the " +
                                        "amount of virtual memory available to the JVM. Please make " +
                                        "sure that a 64-bit JVM is being used and that the process " +
                                        "has access to unlimited virtual memory (ulimit option -v).",
                                        name, e);
                            }
                        }

                        FileAccess random = new FileAccess.Random(access);
                        // prevent the finally block from closing the file
                        // as the returned TarReader will take care of that
                        access = null;
                        return new TarReader(file, random, index, ioMonitor);
                    }
                } finally {
                    if (access != null) {
                        access.close();
                    }
                }
            } catch (IOException e) {
                log.warn("Could not read tar file {}, skipping...", name, e);
            }
        }

        return null;
    }

    /**
     * Tries to read an existing index from the given tar file. The index is
     * returned if it is found and looks valid (correct checksum, passes sanity
     * checks).
     *
     * @param file The TAR file.
     * @param name Name of the TAR file, for logging purposes.
     * @return An instance of {@link ByteBuffer} populated with the content of
     * the index. If the TAR doesn't contain any index, {@code null} is returned
     * instead.
     */
    private static Index loadAndValidateIndex(RandomAccessFile file, String name) throws IOException {
        long length = file.length();

        if (length % BLOCK_SIZE != 0) {
            log.warn("Unable to load index of file {}: Invalid alignment", name);
            return null;
        }
        if (length < 6 * BLOCK_SIZE) {
            log.warn("Unable to load index of file {}: File too short", name);
            return null;
        }
        if (length > Integer.MAX_VALUE) {
            log.warn("Unable to load index of file {}: File too long", name);
            return null;
        }

        ReaderAtEnd r = (whence, size) -> {
            ByteBuffer buffer = ByteBuffer.allocate(size);
            file.seek(length - 2 * BLOCK_SIZE - whence);
            file.readFully(buffer.array());
            return buffer;
        };

        try {
            return indexLoader.loadIndex(r);
        } catch (InvalidIndexException e) {
            log.warn("Unable to load index of file {}: {}", name, e.getMessage());
        }

        return null;
    }

    /**
     * Scans through the tar file, looking for all segment entries.
     *
     * @param file    The path of the TAR file.
     * @param access  The contents of the TAR file.
     * @param entries The map that will contain the recovered entries. The
     *                entries are inserted in the {@link LinkedHashMap} in the
     *                order they appear in the TAR file.
     */
    private static void recoverEntries(File file, RandomAccessFile access, LinkedHashMap<UUID, byte[]> entries) throws IOException {
        byte[] header = new byte[BLOCK_SIZE];
        while (access.getFilePointer() + BLOCK_SIZE <= access.length()) {
            // read the tar header block
            access.readFully(header);

            // compute the header checksum
            int sum = 0;
            for (int i = 0; i < BLOCK_SIZE; i++) {
                sum += header[i] & 0xff;
            }

            // identify possible zero block
            if (sum == 0 && access.getFilePointer() + 2 * BLOCK_SIZE == access.length()) {
                return; // found the zero blocks at the end of the file
            }

            // replace the actual stored checksum with spaces for comparison
            for (int i = 148; i < 148 + 8; i++) {
                sum -= header[i] & 0xff;
                sum += ' ';
            }

            byte[] checkbytes = String.format("%06o\0 ", sum).getBytes(UTF_8);
            for (int i = 0; i < checkbytes.length; i++) {
                if (checkbytes[i] != header[148 + i]) {
                    log.warn("Invalid entry checksum at offset {} in tar file {}, skipping...",
                             access.getFilePointer() - BLOCK_SIZE, file);
                }
            }

            // The header checksum passes, so read the entry name and size
            ByteBuffer buffer = wrap(header);
            String name = readString(buffer, 100);
            buffer.position(124);
            int size = readNumber(buffer, 12);
            if (access.getFilePointer() + size > access.length()) {
                // checksum was correct, so the size field should be accurate
                log.warn("Partial entry {} in tar file {}, ignoring...", name, file);
                return;
            }

            Matcher matcher = NAME_PATTERN.matcher(name);
            if (matcher.matches()) {
                UUID id = UUID.fromString(matcher.group(1));

                String checksum = matcher.group(3);
                if (checksum != null || !entries.containsKey(id)) {
                    byte[] data = new byte[size];
                    access.readFully(data);

                    // skip possible padding to stay at block boundaries
                    long position = access.getFilePointer();
                    long remainder = position % BLOCK_SIZE;
                    if (remainder != 0) {
                        access.seek(position + (BLOCK_SIZE - remainder));
                    }

                    if (checksum != null) {
                        CRC32 crc = new CRC32();
                        crc.update(data);
                        if (crc.getValue() != Long.parseLong(checksum, 16)) {
                            log.warn("Checksum mismatch in entry {} of tar file {}, skipping...",
                                     name, file);
                            continue;
                        }
                    }

                    entries.put(id, data);
                }
            } else if (!name.equals(file.getName() + ".idx")) {
                log.warn("Unexpected entry {} in tar file {}, skipping...",
                         name, file);
                long position = access.getFilePointer() + size;
                long remainder = position % BLOCK_SIZE;
                if (remainder != 0) {
                    position += BLOCK_SIZE - remainder;
                }
                access.seek(position);
            }
        }
    }

    private final File file;

    private final FileAccess access;

    private final Index index;

    private volatile boolean hasGraph;

    private final IOMonitor ioMonitor;

    private TarReader(File file, FileAccess access, Index index, IOMonitor ioMonitor) {
        this.file = file;
        this.access = access;
        this.index = index;
        this.ioMonitor = ioMonitor;
    }

    long size() {
        return file.length();
    }

    /**
     * Reads and returns the identifier of every segment included in the index
     * of this TAR file.
     *
     * @return An instance of {@link Set}.
     */
    Set<UUID> getUUIDs() {
        return index.getUUIDs();
    }

    /**
     * Check if the requested entry exists in this TAR file.
     *
     * @param msb The most significant bits of the entry identifier.
     * @param lsb The least significant bits of the entry identifier.
     * @return {@code true} if the entry exists in this TAR file, {@code false}
     * otherwise.
     */
    boolean containsEntry(long msb, long lsb) {
        return findEntry(msb, lsb) != -1;
    }

    /**
     * If the given segment is in this file, get the byte buffer that allows
     * reading it.
     * <p>
     * Whether or not this will read from the file depends on whether memory
     * mapped files are used or not.
     *
     * @param msb the most significant bits of the segment id
     * @param lsb the least significant bits of the segment id
     * @return the byte buffer, or null if not in this file.
     */
    ByteBuffer readEntry(long msb, long lsb) throws IOException {
        int idx = findEntry(msb, lsb);
        if (idx == -1) {
            return null;
        }
        return readEntry(msb, lsb, index.entry(idx));
    }

    private ByteBuffer readEntry(long msb, long lsb, IndexEntry entry) throws IOException {
        return readSegment(msb, lsb, entry.getPosition(), entry.getLength());
    }

    /**
     * Find the position of the given entry in this TAR file.
     *
     * @param msb The most significant bits of the entry identifier.
     * @param lsb The least significant bits of the entry identifier.
     * @return The position of the entry in the TAR file, or {@code -1} if the
     * entry is not found.
     */
    private int findEntry(long msb, long lsb) {
        return index.findEntry(msb, lsb);
    }

    /**
     * Read the entries in this TAR file.
     *
     * @return An array of {@link TarEntry}.
     */
    @Nonnull
    TarEntry[] getEntries() {
        TarEntry[] entries = new TarEntry[index.count()];
        for (int i = 0; i < entries.length; i++) {
            IndexEntry e = index.entry(i);
            entries[i]  = new TarEntry(
                    e.getMsb(),
                    e.getLsb(),
                    e.getPosition(),
                    e.getLength(),
                    newGCGeneration(
                            e.getGeneration(),
                            e.getFullGeneration(),
                            e.isCompacted()
                    )
            );
        }
        Arrays.sort(entries, TarEntry.OFFSET_ORDER);
        return entries;
    }

    /**
     * Read the references of an entry in this TAR file.
     *
     * @param id    The identifier of the entry.
     * @param graph The content of the graph of this TAR file.
     * @return The references of the provided TAR entry.
     */
    @Nonnull
    private static List<UUID> getReferences(UUID id, Map<UUID, List<UUID>> graph) {
        List<UUID> references = graph.get(id);

        if (references == null) {
            return Collections.emptyList();
        }

        return references;
    }

    /**
     * Collect the references of those BLOBs that are reachable from the entries
     * in this TAR file.
     * <p>
     * The user-provided {@link Predicate} determines if entries belonging to a
     * specific generation should be inspected for binary references of not.
     * Given a generation number as input, if the predicate returns {@code
     * true}, entries from that generation will be skipped. If the predicate
     * returns {@code false}, entries from that generation will be inspected for
     * references.
     * <p>
     * The provided {@link Consumer} is callback object that will be invoked for
     * every reference found in the inspected entries.
     *
     * @param collector      An instance of {@link Consumer}.
     * @param skipGeneration An instance of {@link Predicate}.
     */
    void collectBlobReferences(@Nonnull Consumer<String> collector, Predicate<GCGeneration> skipGeneration) {
        BinaryReferencesIndex references = getBinaryReferences();

        if (references == null) {
            return;
        }

        references.forEach((generation, full, compacted, segment, reference) -> {
            if (skipGeneration.apply(newGCGeneration(generation, full, compacted))) {
                return;
            }
            collector.accept(reference);
        });
    }

    /**
     * Mark entries that can be reclaimed.
     * <p>
     * A data segment is reclaimable iff its generation is in the {@code
     * reclaimGeneration} predicate. A bulk segment is reclaimable if it is not
     * in {@code bulkRefs} or if it is transitively reachable through a non
     * reclaimable data segment.
     * <p>
     * The algorithm implemented by this method uses a couple of supporting data
     * structures.
     * <p>
     * The first of the supporting data structures is the set of bulk segments
     * to keep. When this method is invoked, this set initially contains the set
     * of bulk segments that are currently in use. The algorithm removes a
     * reference from this set if the corresponding bulk segment is not
     * referenced (either directly or transitively) from a marked data segment.
     * The algorithm adds a reference to this set if a marked data segment is
     * references the corresponding bulk segment. When this method returns, the
     * references in this set represent bulk segments that are currently in use
     * and should not be removed.
     * <p>
     * The second of the supporting data structures is the set of segments to
     * reclaim. This set contains references to bulk and data segments. A
     * reference to a bulk segment is added if the bulk segment is not
     * referenced (either directly or transitively) by marked data segment. A
     * reference to a data segment is added if the user-provided predicate
     * returns {@code true} for that segment. When this method returns, this set
     * contains segments that are not marked and can be removed.
     *
     * @param references  The set of bulk segments to keep.
     * @param reclaimable The set of segments to remove.
     * @param context     An instance of {@link CleanupContext}.
     */
    void mark(Set<UUID> references, Set<UUID> reclaimable, CleanupContext context) throws IOException {
        Map<UUID, List<UUID>> graph = getGraph();
        TarEntry[] entries = getEntries();
        for (int i = entries.length - 1; i >= 0; i--) {
            // A bulk segments is *always* written before any data segment referencing it.
            // Backward iteration ensures we see all references to bulk segments before
            // we see the bulk segment itself. Therefore we can remove a bulk reference
            // from the bulkRefs set once we encounter it, which save us some memory and
            // CPU on subsequent look-ups.
            TarEntry entry = entries[i];
            UUID id = new UUID(entry.msb(), entry.lsb());
            if (context.shouldReclaim(id, entry.generation(), references.remove(id))) {
                reclaimable.add(id);
            } else {
                for (UUID refId : getReferences(id, graph)) {
                    if (context.shouldFollow(id, refId)) {
                        references.add(refId);
                    }
                }
            }
        }
    }

    /**
     * Try to remove every segment contained in a user-provided set.
     * <p>
     * This method might refuse to remove the segments under the following
     * circumstances.
     * <p>
     * First, if this TAR files does not contain any of the segments that are
     * supposed to be removed. In this case, the method returns {@code null}.
     * <p>
     * Second, if this method contains some of the segments that are supposed to
     * be removed, but the reclaimable space is be less than 1/4 of the current
     * size of the TAR file. In this case, this method returns this {@link
     * TarReader}.
     * <p>
     * Third, if this TAR file is in the highest generation possible ('z') and
     * thus a new generation for this TAR file can't be created. In this case,
     * the method returns this {@link TarReader}.
     * <p>
     * Fourth, if a new TAR file has been created but it is unreadable for
     * unknown reasons. In this case, this method returns this {@link
     * TarReader}.
     * <p>
     * If none of the above conditions apply, this method returns a new {@link
     * TarReader} instance tha points to a TAR file that doesn't contain the
     * removed segments. The returned {@link TarReader} will belong to the next
     * generation of this {@link TarReader}. In this case, the {@code reclaimed}
     * set will be updated to contain the identifiers of the segments that were
     * removed from this TAR file.
     *
     * @param reclaim   Set of segment sto reclaim.
     * @param reclaimed Set of reclaimed segments. It will be update if this TAR
     *                  file is rewritten.
     * @return Either this {@link TarReader}, or a new instance of {@link
     * TarReader}, or {@code null}.
     */
    TarReader sweep(@Nonnull Set<UUID> reclaim, @Nonnull Set<UUID> reclaimed) throws IOException {
        String name = file.getName();
        log.debug("Cleaning up {}", name);

        Set<UUID> cleaned = newHashSet();
        int afterSize = 0;
        int beforeSize = 0;
        int afterCount = 0;

        TarEntry[] entries = getEntries();
        for (int i = 0; i < entries.length; i++) {
            TarEntry entry = entries[i];
            beforeSize += getEntrySize(entry.size());
            UUID id = new UUID(entry.msb(), entry.lsb());
            if (reclaim.contains(id)) {
                cleaned.add(id);
                entries[i] = null;
            } else {
                afterSize += getEntrySize(entry.size());
                afterCount += 1;
            }
        }

        if (afterCount == 0) {
            log.debug("None of the entries of {} are referenceable.", name);
            return null;
        }
        if (afterSize >= beforeSize * 3 / 4 && hasGraph()) {
            // the space savings are not worth it at less than 25%,
            // unless this tar file lacks a pre-compiled segment graph
            // in which case we'll always generate a new tar file with
            // the graph to speed up future garbage collection runs.
            log.debug("Not enough space savings. ({}/{}). Skipping clean up of {}",
                    access.length() - afterSize, access.length(), name);
            return this;
        }
        if (!hasGraph()) {
            log.warn("Recovering {}, which is missing its graph.", name);
        }

        int pos = name.length() - "a.tar".length();
        char generation = name.charAt(pos);
        if (generation == 'z') {
            log.debug("No garbage collection after reaching generation z: {}", name);
            return this;
        }

        File newFile = new File(
                file.getParentFile(),
                name.substring(0, pos) + (char) (generation + 1) + ".tar");

        log.debug("Writing new generation {}", newFile.getName());
        TarWriter writer = new TarWriter(newFile, ioMonitor);
        for (TarEntry entry : entries) {
            if (entry != null) {
                long msb = entry.msb();
                long lsb = entry.lsb();
                int offset = entry.offset();
                int size = entry.size();
                GCGeneration gen = entry.generation();
                byte[] data = new byte[size];
                readSegment(msb, lsb, offset, size).get(data);
                writer.writeEntry(msb, lsb, data, 0, size, gen);
            }
        }

        // Reconstruct the graph index for non-cleaned segments.

        Map<UUID, List<UUID>> graph = getGraph();

        for (Entry<UUID, List<UUID>> e : graph.entrySet()) {
            if (cleaned.contains(e.getKey())) {
                continue;
            }

            Set<UUID> vertices = newHashSet();

            for (UUID vertex : e.getValue()) {
                if (cleaned.contains(vertex)) {
                    continue;
                }

                vertices.add(vertex);
            }

            for (UUID vertex : vertices) {
                writer.addGraphEdge(e.getKey(), vertex);
            }
        }

        // Reconstruct the binary reference index for non-cleaned segments.

        BinaryReferencesIndex references = getBinaryReferences();

        if (references != null) {
            references.forEach((gen, full, compacted, id, reference) -> {
                if (cleaned.contains(id)) {
                    return;
                }
                writer.addBinaryReference(newGCGeneration(gen, full, compacted), id, reference);
            });
        }

        writer.close();

        TarReader reader = openFirstFileWithValidIndex(singletonList(newFile), access.isMemoryMapped(), ioMonitor);
        if (reader != null) {
            reclaimed.addAll(cleaned);
            return reader;
        } else {
            log.warn("Failed to open cleaned up tar file {}", file);
            return this;
        }
    }

    @Override
    public void close() throws IOException {
        access.close();
    }

    /**
     * Loads and parses the optional pre-compiled graph entry from the given tar
     * file.
     *
     * @return The parsed graph, or {@code null} if one was not found.
     */
    Map<UUID, List<UUID>> getGraph() throws IOException {
        ByteBuffer graph = loadGraph();
        if (graph == null) {
            return null;
        } else {
            return parseGraph(graph);
        }
    }

    private boolean hasGraph() {
        if (!hasGraph) {
            try {
                loadGraph();
            } catch (IOException ignore) { }
        }
        return hasGraph;
    }

    private int getIndexEntrySize() {
        return getEntrySize(index.size());
    }

    private int getGraphEntrySize() {
        ByteBuffer buffer;

        try {
            buffer = loadGraph();
        } catch (IOException e) {
            log.warn("Exception while loading pre-compiled tar graph", e);
            return 0;
        }

        if (buffer == null) {
            return 0;
        }

        return getEntrySize(buffer.getInt(buffer.limit() - 8));
    }

    /**
     * Read the index of binary references from this TAR file.
     * <p>
     * The index of binary references is a two-level map. The key to the first
     * level of the map is the generation. The key to the second level of the
     * map is the identifier of a data segment in this TAR file. The value of
     * the second-level map is the set of binary references contained in the
     * segment.
     *
     * @return An instance of {@link Map}.
     */
    BinaryReferencesIndex getBinaryReferences() {
        BinaryReferencesIndex index = null;
        try {
            index = loadBinaryReferences();
        } catch (InvalidBinaryReferencesIndexException | IOException e) {
            log.warn("Exception while loading binary reference", e);
        }
        return index;
    }

    private BinaryReferencesIndex loadBinaryReferences() throws IOException, InvalidBinaryReferencesIndexException {
        int end = access.length() - 2 * BLOCK_SIZE - getIndexEntrySize() - getGraphEntrySize();
        return BinaryReferencesIndexLoader.loadBinaryReferencesIndex((whence, size) -> access.read(end - whence, size));
    }

    /**
     * Loads the optional pre-compiled graph entry from the given tar file.
     *
     * @return graph buffer, or {@code null} if one was not found
     * @throws IOException if the tar file could not be read
     */
    private ByteBuffer loadGraph() throws IOException {
        int pos = access.length() - 2 * BLOCK_SIZE - getIndexEntrySize();

        ByteBuffer meta = access.read(pos - 16, 16);

        int crc32 = meta.getInt();
        int count = meta.getInt();
        int bytes = meta.getInt();
        int magic = meta.getInt();

        if (magic != GRAPH_MAGIC) {
            log.warn("Invalid graph magic number in {}", file);
            return null;
        }

        if (count < 0) {
            log.warn("Invalid number of entries in {}", file);
            return null;
        }

        if (bytes < 4 + count * 34) {
            log.warn("Invalid entry size in {}", file);
            return null;
        }

        ByteBuffer graph = access.read(pos - bytes, bytes);

        byte[] b = new byte[bytes - 16];

        graph.mark();
        graph.get(b);
        graph.reset();

        CRC32 checksum = new CRC32();
        checksum.update(b);

        if (crc32 != (int) checksum.getValue()) {
            log.warn("Invalid graph checksum in tar file {}", file);
            return null;
        }

        hasGraph = true;

        return graph;
    }

    private ByteBuffer readSegment(long msb, long lsb, int offset, int size) throws IOException {
        ioMonitor.beforeSegmentRead(file, msb, lsb, size);
        Stopwatch stopwatch = Stopwatch.createStarted();
        ByteBuffer buffer = access.read(offset, size);
        long elapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);
        ioMonitor.afterSegmentRead(file, msb, lsb, size, elapsed);
        return buffer;
    }

    private static Map<UUID, List<UUID>> parseGraph(ByteBuffer buffer) {
        int nEntries = buffer.getInt(buffer.limit() - 12);

        Map<UUID, List<UUID>> graph = newHashMapWithExpectedSize(nEntries);

        for (int i = 0; i < nEntries; i++) {
            long msb = buffer.getLong();
            long lsb = buffer.getLong();
            int nVertices = buffer.getInt();

            List<UUID> vertices = newArrayListWithCapacity(nVertices);

            for (int j = 0; j < nVertices; j++) {
                long vMsb = buffer.getLong();
                long vLsb = buffer.getLong();
                vertices.add(new UUID(vMsb, vLsb));
            }

            graph.put(new UUID(msb, lsb), vertices);
        }

        return graph;
    }

    private static String readString(ByteBuffer buffer, int fieldSize) {
        byte[] b = new byte[fieldSize];
        buffer.get(b);
        int n = 0;
        while (n < fieldSize && b[n] != 0) {
            n++;
        }
        return new String(b, 0, n, UTF_8);
    }

    private static int readNumber(ByteBuffer buffer, int fieldSize) {
        byte[] b = new byte[fieldSize];
        buffer.get(b);
        int number = 0;
        for (int i = 0; i < fieldSize; i++) {
            int digit = b[i] & 0xff;
            if ('0' <= digit && digit <= '7') {
                number = number * 8 + digit - '0';
            } else {
                break;
            }
        }
        return number;
    }

    /**
     * Return the path of this TAR file.
     *
     * @return An instance of {@link File}.
     */
    File getFile() {
        return file;
    }

    //------------------------------------------------------------< Object >--

    @Override
    public String toString() {
        return file.toString();
    }

}


text:
package it.polimi.modaclouds.space4cloud.milp.ssh;

import it.polimi.modaclouds.space4cloud.milp.Configuration;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

//this class allows to execute commands on AMPL server
public class ExecSSH {

	// main execution function
	// returns in List<Strings> all answers of the server
	public List<String> mainExec(String command) throws Exception {
		if (Configuration.isRunningLocally())
			return localExec(command);

		List<String> res = new ArrayList<String>();

		// creating session with username, server's address and port (22 by
		// default)
		JSch jsch = new JSch();
		Session session = jsch.getSession(Configuration.SSH_USER_NAME, Configuration.SSH_HOST, 22);
		session.setPassword(Configuration.SSH_PASSWORD);

//			// this class sets visual forms for interactions with users
//			// required by implementation
//			UserInfo ui = new MyUserInfo() {
//				public void showMessage(String message) {
//					JOptionPane.showMessageDialog(null, message);
//				}
//
//				public boolean promptYesNo(String message) {
//					Object[] options = { "yes", "no" };
//					int foo = JOptionPane.showOptionDialog(null, message,
//							"Warning", JOptionPane.DEFAULT_OPTION,
//							JOptionPane.WARNING_MESSAGE, null, options,
//							options[0]);
//					return foo == 0;
//				}
//			};
//			session.setUserInfo(ui);

		// disabling of certificate checks
		session.setConfig("StrictHostKeyChecking", "no");
		// creating connection
		session.connect();

		// creating channel in execution mod
		Channel channel = session.openChannel("exec");
		// sending command which runs bash-script in Configuration.RUN_WORKING_DIRECTORY directory
		((ChannelExec) channel).setCommand(command);
		// taking input stream
		channel.setInputStream(null);
		((ChannelExec) channel).setErrStream(System.err);
		InputStream in = channel.getInputStream();
		// connecting channel
		channel.connect();
		// read buffer
		byte[] tmp = new byte[1024];

		// reading channel while server responses smth or until it does not
		// close connection
		while (true) {
			while (in.available() > 0) {
				int i = in.read(tmp, 0, 1024);
				if (i < 0)
					break;
				res.add(new String(tmp, 0, i));
			}
			if (channel.isClosed()) {
				res.add("exit-status: " + channel.getExitStatus());
				break;
			}
			try {
				Thread.sleep(1000);
			} catch (Exception ee) {
			}
		}
		// closing connection
		channel.disconnect();
		session.disconnect();

		return res;
	}

	public List<String> localExec(String command) throws Exception {
		List<String> res = new ArrayList<String>();
		ProcessBuilder pb = new ProcessBuilder(command.split(" "));
		pb.redirectErrorStream(true);

		Process p = pb.start();
		BufferedReader stream = new BufferedReader(new InputStreamReader(p.getInputStream()));
		String line = stream.readLine();
		while (line != null) {
			res.add(line);
			line = stream.readLine();
		}
		stream.close();

		return res;
	}
}


text:
#ifndef _Browser_Display_Selection_h
#define _Browser_Display_Selection_h

// Browser_Display_Selection.h
//------------------------------------------

#ifndef ISO_CPP_HEADERS
#include <string.h>
#else /* ISO_CPP_HEADERS */
#include <cstring>
using namespace std;
#endif /* ISO_CPP_HEADERS */

#ifndef _prototypes_h
#include <prototypes.h>
#endif
#ifndef _gtDlgTemplate_h
#include <gtDlgTemplate.h>
#endif
#ifndef _gtTogB_h
#include <gtTogB.h>
#endif
#ifndef _gtHorzBox_h
#include <gtHorzBox.h>
#endif
#ifndef _gtLabel_h
#include <gtLabel.h>
#endif
#ifndef _gtStringEd_h
#include <gtStringEd.h>
#endif
#ifndef _gtPushButton_h
#include <gtPushButton.h>
#endif
#ifndef _gtToggleBox_h
#include <gtToggleBox.h>
#endif
#ifndef _oodt_ui_decls_h
#include <oodt_ui_decls.h>
#endif

#ifndef __viewGraHeader_h
#include <viewGraHeader.h>
#endif

#ifndef _psetNotifyView_h
#include <psetNotifyView.h>
#endif

BEGIN_C_DECL
void popup_Browser_Display_Selection PROTO((void *arg_viewp, void *popup_node));
END_C_DECL

class Browser_Display_Selection {
    gtLabel	*toplabel;
    gtHorzBox	*togslot, *togslot2, *filtslot;
    gtToggleBox	*tog1, *tog2, *tog3;
    gtToggleButton	*tb1, *tb2, *tb3;
    gtStringEditor	*text1;
    void       *popup_node, *viewp;
    psetNotifyView* notifier;

  public:
    gtDialogTemplate	*shell;
    Browser_Display_Selection(viewGraHeader* viewp);//argument distinguishes caller/type of view.
    void init(void *, void *);
    static void sanity_CB(gtToggleButton *tb, gtEvent *, void *cd, gtReason);
    static void OK_CB(gtPushButton *tb, gtEvent *, void *cd, gtReason);
    static void Apply_CB(gtPushButton *, gtEvent *, void *cd, gtReason);
    static void Cancel_CB(gtPushButton *, gtEvent *, void *cd, gtReason);
    static void text_CB(gtStringEditor *, gtEvent *, void *cd, gtReason);
	static void view_deleted_CB(void*, psetNotifyView*);
    void sanity_check();
    void get_current_options();
    void do_it();
};

typedef Browser_Display_Selection* Browser_Display_Selection_Ptr;

#endif // _Browser_Display_Selection_h


text:
    <button type="button" class="btn btn-default btn-sm" ng-click="status.open = !status.open">Toggle last panel</button>
    <button type="button" class="btn btn-default btn-sm" ng-click="status.isFirstDisabled = ! status.isFirstDisabled">Enable / Disable first panel</button>

      <input type="checkbox" ng-model="oneAtATime">
      Open only one at a time

  <uib-accordion close-others="oneAtATime">
    <uib-accordion-group heading="Static Header, initially expanded" is-open="status.isFirstOpen" is-disabled="status.isFirstDisabled">
      This content is straight in the template.
    </uib-accordion-group>
    <uib-accordion-group heading="{{group.title}}" ng-repeat="group in groups">
      {{group.content}}
    </uib-accordion-group>
    <uib-accordion-group heading="Dynamic Body Content">

The body of the uib-accordion group grows to fit the contents

      <button type="button" class="btn btn-default btn-sm" ng-click="addItem()">Add Item</button>

{{item}}

    </uib-accordion-group>
    <uib-accordion-group heading="Custom template" template-url="group-template.html">
      Hello
    </uib-accordion-group>
    <uib-accordion-group heading="Delete account" panel-class="panel-danger">

Please, to delete your account, click the button below

      <button class="btn btn-danger">Delete</button>
    </uib-accordion-group>
    <uib-accordion-group is-open="status.open">
      <uib-accordion-heading>
        I can have markup, too!
      </uib-accordion-heading>
      This is just some content to illustrate fancy headings.
    </uib-accordion-group>
  </uib-accordion>


text:
\section{API}

\subsection{Update DOM \bf{wf:update}}
You can update part of the page or DOM element with a given
element or even raw HTML. You can also use {\bf \#dtl}
or {\bf \#eex} template elements for HTML generation to
replace DOM. Here is an example of simple {\bf \#span} element
with an HTML counterpart:

\vspace{1\baselineskip}
\begin{lstlisting}
    wf:update(history,[#span{body="Hello"}]).
\end{lstlisting}
\vspace{1\baselineskip}

It generates DOM update script and sends it to
WebSocket channel for evaluation:

\vspace{1\baselineskip}
\begin{lstlisting}
    document.querySelector('#history')
            .outerHTML = 'Hello';
\end{lstlisting}
\vspace{1\baselineskip}

Companions are also provided for updating head and tail
of the elements list: {\bf wf:insert\_top/2} and
{\bf wf:insert\_bottom/2}. These are translated to appropriate
JavaScript methods {\bf insertBefore} and {\bf appendChild} during rendering.

\vspace{1\baselineskip}
\begin{lstlisting}
    wf:insert_top(history,
        #panel{id=banner, body= [
            #span{ id=text,
                   body = wf:f("User ~s logged in.",[wf:user()]) },
            #button{id=logout, body="Logout", postback=logout },
            #br{} ]}),
\end{lstlisting}
\vspace{1\baselineskip}

Remember to envelop all elements in common root element before inserts.

\paragraph{}
For relative updates use {\bf wf:insert\_before/2} and {\bf wf:insert\_after/2}.
To remove an element use {\bf wf:remove/2}.
Updates are covered in detail in {\bf Section 7}.

\paragraph{\bf Element Naming}
You can specify element's id with Erlang atoms,
lists or binaries. During rendering the value will be converted
with {\bf wf:to\_list}. Conversion will be consistent only if you use atoms.
Otherwise you need to care about illegal symbols for element accessors.

\paragraph{}
During page updates you can create additional elements with
runtime generated event handlers, perform HTML rendering for
template elements or even use distributed map/reduce to calculate view.
You have to be aware that heavy operations will consume
more power in the browser, but you can save it by rendering
HTML on server-side. All DOM updates API works both using
JavaScript/OTP and server pages.

\paragraph{}
List of elements you can use is given in {\bf Section 7}. You can also create
your own elements with a custom render function.

\subsection{Wire JavaScript \bf{wf:wire}}
Just like HTML is generated from Elements, Actions are rendered into
JavaScript to handle events raised in the browser. Actions are always
transformed into JavaScript and sent through WebSockets pipe.

\subsection*{Direct Wiring}
There are two types of actions. First class are direct JavaScript
strings provided directly as Erlang lists or via JavaScript/OTP
transformations.

\vspace{1\baselineskip}
\begin{lstlisting}
    wf:wire("window.location='http://synrc.com'").
\end{lstlisting}

\subsection*{Actions Render}
Second class actions are in fact Erlang records
rendered during page load, server events or client events.

\vspace{1\baselineskip}
\begin{lstlisting}
    wf:wire(#alert{text="Hello!"}).
\end{lstlisting}
\vspace{1\baselineskip}

However basic N2O actions that are part of N2O API, {\bf wf:update} and {\bf wf:redirect},
are implemented as Erlang records as given in the example. If you need deferred
rendering of JavaScript, you can use Erlang records instead of direct wiring with
Erlang lists or JavaScript/OTP.

\paragraph{}
Any action, wired with {\bf wf:wire}, is enveloped in {\bf \#wire\{actions=[]\}},
which is also an action capable of polymorphic rendering of custom or built-in actions, specified in the list.
Following nested action embedding is also valid:

\vspace{1\baselineskip}
\begin{lstlisting}
    wf:wire(#wire{actions=[#alert{text="N2O"}]}).
\end{lstlisting}
\vspace{1\baselineskip}

\subsection{Async Processes {\bf wf:async} and {\bf wf:flush}}
These create Erlang processes, which communicate with the primary page
process by sending messages. {\bf wf:flush} should be called to redirect all updates and
wire actions to the page process.
Usually you send messages to Async processes over N2O
message bus, but you can use any of these options.

\vspace{1\baselineskip}
\begin{lstlisting}
    body() ->
        {ok,Pid} = wf:async("looper",fun() -> loop(0) end),
      [ #span   { id=counter },
        #button { id=sendButton, body="Send", postback={inc,Pid} } ].

    event({inc,Pid}) -> wf:reg(room), Pid ! inc.

    loop(Counter) ->
        Body = wf:to_list(Counter),
        receive inc ->
             wf:update(counter, #span { id=counter, body=Body }),
             wf:flush(room) end, loop(Counter+1).
\end{lstlisting}

\paragraph{\bf Process Naming.} The name of async process is globally unique. There are two
versions, {\bf wf:async/1} and {\bf wf:async/2}. In the given example
the name of async process is specified as ``looper'', otherwise,
if the first parameter was not specified, the default name ``comet'' will be used.

\subsection{Message Bus {\bf wf:reg} and {\bf wf:send}}
N2O uses GProc process registry for managing async processes pools.
It is used as a PubSub message bus for N2O communications, but later you can switch to robust RabbitMQ.
You can associate a process with the pool with {\bf wf:reg} and send a message to the pool with {\bf wf:send}.

\vspace{1\baselineskip}
\begin{lstlisting}
    loop() ->
        receive M ->
            wf:info(?MODULE, "P: ~p, M: ~p",[self(),M]) end, loop().
\end{lstlisting}

Now you can test it

\begin{lstlisting}
    > spawn(fun() -> wf:reg(topic), loop() end).
    > spawn(fun() -> wf:reg(topic), loop() end).
    > wf:send(topic,"Hello").
\end{lstlisting}

It should print in REPL something like:

\begin{lstlisting}
    > [info] P: <0.2012.0>, M: "Hello"
    > [info] P: <0.2015.0>, M: "Hello"
\end{lstlisting}

\subsection{Parse URL and Context parameters {\bf wf:q} and {\bf wf:qp}}
These are used to extract URL parameters or read from the process context. {\bf wf:q} extracts variables
from the context stored by controls postbacks. {\bf wf:qp} extracts variables from HTTP forms.

\subsection{Render {\bf wf:render}}
Render elements or actions with common render.

\subsection{Redirects {\bf wf:redirect}}
Redirects are implemented not with HTTP headers, but with JavaScript action modifying {\bf window.location}.
This saves login context information which is sent in the first packet upon establishing a WebSocket connection.

\subsection{Session Information {\bf wf:session}}
Store any session information in ETS tables. Use {\bf wf:user}, {\bf wf:role} for
login and authorization. Consult {\bf AVZ} library documentation.

\subsection{Bridge information {\bf wf:header} and {\bf wf:cookie}}
You can read and issue cookie and headers information using internal Web-Server routines.
You can also read peer IP with {\bf wf:peer}. Usually you do Bridge operations
inside handlers or endpoints.

\begin{lstlisting}
    wf:cookies_req(?REQ),
    wf:cookie_req(Name,Value,Path,TTL,Req)
\end{lstlisting}

You can set cookies for the page using public cookies API during initial page rendering.

\begin{lstlisting}
    body() -> wf:cookie("user","Joe"), [].
\end{lstlisting}

You should use wiring inside WebSocket events:

\begin{lstlisting}
    event(_) ->
        wf:wire(wf:f("document.cookie='~s=~s'",["user","Joe"])).
\end{lstlisting}


text:
package options

import "time"

// CountOptions represents all possible options to the Count() function.
type CountOptions struct {
	Collation *Collation     // Specifies a collation
	Hint      interface{}    // The index to use
	Limit     *int64         // The maximum number of documents to count
	MaxTime   *time.Duration // The maximum amount of time to allow the operation to run
	Skip      *int64         // The number of documents to skip before counting
}

// Count returns a pointer to a new CountOptions
func Count() *CountOptions {
	return &CountOptions{}
}

// SetCollation specifies a collation
// Valid for server versions >= 3.4
func (co *CountOptions) SetCollation(c *Collation) *CountOptions {
	co.Collation = c
	return co
}

// SetHint specifies the index to use
func (co *CountOptions) SetHint(h interface{}) *CountOptions {
	co.Hint = h
	return co
}

// SetLimit specifies the maximum number of documents to count
func (co *CountOptions) SetLimit(i int64) *CountOptions {
	co.Limit = &i
	return co
}

// SetMaxTime specifies the maximum amount of time to allow the operation to run
func (co *CountOptions) SetMaxTime(d time.Duration) *CountOptions {
	co.MaxTime = &d
	return co
}

// SetSkip specifies the number of documents to skip before counting
func (co *CountOptions) SetSkip(i int64) *CountOptions {
	co.Skip = &i
	return co
}

// MergeCountOptions combines the argued CountOptions into a single CountOptions in a last-one-wins fashion
func MergeCountOptions(opts ...*CountOptions) *CountOptions {
	countOpts := Count()
	for _, co := range opts {
		if co == nil {
			continue
		}
		if co.Collation != nil {
			countOpts.Collation = co.Collation
		}
		if co.Hint != nil {
			countOpts.Hint = co.Hint
		}
		if co.Limit != nil {
			countOpts.Limit = co.Limit
		}
		if co.MaxTime != nil {
			countOpts.MaxTime = co.MaxTime
		}
		if co.Skip != nil {
			countOpts.Skip = co.Skip
		}
	}

	return countOpts
}


text:
This is the partial for view 1

Data Binding

<input ng-model="inputData" placeholder="ng-model">

<input ng-value="inputData" placeholder="ng-value">

{{inputData}}

Ng-repeat | Sort By: Name
Asc
Desc
| Sort By: Title
Asc
Desc

    {{$index}} : {{person.name}} - {{person.title}}

Route Info: {{routeInfo()}}


text:
package org.apache.batik.svggen;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.batik.ext.awt.image.spi.ImageWriter;
import org.apache.batik.ext.awt.image.spi.ImageWriterRegistry;

/**
 * This implementation of the abstract AbstractImageHandlerEncoder
 * class creates PNG images in the image directory and sets the
 * url pointing to that file in the xlink:href attributes of the
 * image elements it handles.
 *
 * @author Vincent Hardy
 * @version $Id$
 * @see             org.apache.batik.svggen.SVGGraphics2D
 * @see             org.apache.batik.svggen.ImageHandlerJPEGEncoder
 * @see             org.apache.batik.svggen.ImageHandlerPNGEncoder
 */
public class ImageHandlerPNGEncoder extends AbstractImageHandlerEncoder {
    /**
     * @param imageDir directory where this handler should generate images.
     *        If null, an IllegalArgumentException is thrown.
     * @param urlRoot root for the urls that point to images created by this
     *        image handler. If null, then the url corresponding to imageDir
     *        is used.
     */
    public ImageHandlerPNGEncoder(String imageDir, String urlRoot)
        throws SVGGraphics2DIOException {
        super(imageDir, urlRoot);
    }

    /**
     * @return the suffix used by this encoder. E.g., ".png" for
     * ImageHandlerPNGEncoder.
     */
    public final String getSuffix(){
        return ".png";
    }

    /**
     * @return the prefix used by this encoder. E.g., "pngImage" for
     * ImageHandlerPNGEncoder.
     */
    public final String getPrefix(){
        return "pngImage";
    }

    /**
     * Derived classes should implement this method and encode the input
     * BufferedImage as needed
     */
    public void encodeImage(BufferedImage buf, File imageFile)
        throws SVGGraphics2DIOException {
        try {
            OutputStream os = new FileOutputStream(imageFile);
            try {
                ImageWriter writer = ImageWriterRegistry.getInstance()
                    .getWriterFor("image/png");
                writer.writeImage(buf, os);

            } finally {
                os.close();
            }
        } catch (IOException e) {
            throw new SVGGraphics2DIOException(ERR_WRITE+imageFile.getName());
        }
    }

    /**
     * This method creates a BufferedImage with an alpha channel, as this is
     * supported by PNG.
     */
    public BufferedImage buildBufferedImage(Dimension size){
        return new BufferedImage(size.width, size.height,
                                 BufferedImage.TYPE_INT_ARGB);
    }
}


text:
  Étainhus est
      une ville située dans le département de Seine-Maritime en Haute-Normandie. Elle totalisait 1 043 habitants en 2008.

La ville propose quelques  équipements, elle dispose, entre autres, de un terrain de sport.

Le parc d'habitations, à Étainhus, était réparti en 2011 en 22 appartements et 399 maisons soit
 un marché plutôt équilibré.

À coté de Étainhus sont localisées les communes de
Angerville-l'Orcher à 3 km, 1 289 habitants,
Saint-Gilles-de-la-Neuville localisée à 4 km, 625 habitants,
Épretot à 3 km, 721 habitants,
Graimbouville à 1 km, 564 habitants,
Manéglise à 4 km, 1 151 habitants,
Berville localisée à 2 km, 541 habitants,
 entre autres. De plus, Étainhus est située à seulement 16 km de Le Havre.

À Étainhus, le prix moyen à la vente d'un appartement se situe à zero € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 582 € du m². À la location la valorisation moyenne se situe à 10 € du m² par mois.