text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.implementation;

import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.network.fluent.HubVirtualNetworkConnectionsClient;
import com.azure.resourcemanager.network.fluent.models.HubVirtualNetworkConnectionInner;
import com.azure.resourcemanager.network.models.ErrorException;
import com.azure.resourcemanager.network.models.ListHubVirtualNetworkConnectionsResult;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in HubVirtualNetworkConnectionsClient. */
public final class HubVirtualNetworkConnectionsClientImpl implements HubVirtualNetworkConnectionsClient {
    private final ClientLogger logger = new ClientLogger(HubVirtualNetworkConnectionsClientImpl.class);

    /** The proxy service used to perform REST calls. */
    private final HubVirtualNetworkConnectionsService service;

    /** The service client containing this operation class. */
    private final NetworkManagementClientImpl client;

    /**
     * Initializes an instance of HubVirtualNetworkConnectionsClientImpl.
     *
     * @param client the instance of the service client containing this operation class.
     */
    HubVirtualNetworkConnectionsClientImpl(NetworkManagementClientImpl client) {
        this.service =
            RestProxy
                .create(
                    HubVirtualNetworkConnectionsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
        this.client = client;
    }

    /**
     * The interface defining all the services for NetworkManagementClientHubVirtualNetworkConnections to be used by the
     * proxy service to perform REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "NetworkManagementCli")
    private interface HubVirtualNetworkConnectionsService {
        @Headers({"Content-Type: application/json"})
        @Get(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs"
                + "/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ErrorException.class)
        Mono<Response<HubVirtualNetworkConnectionInner>> get(
            @HostParam("$host") String endpoint,
            @PathParam("subscriptionId") String subscriptionId,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("virtualHubName") String virtualHubName,
            @PathParam("connectionName") String connectionName,
            @QueryParam("api-version") String apiVersion,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Get(
            "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs"
                + "/{virtualHubName}/hubVirtualNetworkConnections")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ErrorException.class)
        Mono<Response<ListHubVirtualNetworkConnectionsResult>> list(
            @HostParam("$host") String endpoint,
            @PathParam("subscriptionId") String subscriptionId,
            @PathParam("resourceGroupName") String resourceGroupName,
            @PathParam("virtualHubName") String virtualHubName,
            @QueryParam("api-version") String apiVersion,
            @HeaderParam("Accept") String accept,
            Context context);

        @Headers({"Content-Type: application/json"})
        @Get("{nextLink}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ErrorException.class)
        Mono<Response<ListHubVirtualNetworkConnectionsResult>> listNext(
            @PathParam(value = "nextLink", encoded = true) String nextLink,
            @HostParam("$host") String endpoint,
            @HeaderParam("Accept") String accept,
            Context context);
    }

    /**
     * Retrieves the details of a HubVirtualNetworkConnection.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @param connectionName The name of the vpn connection.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return hubVirtualNetworkConnection Resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<HubVirtualNetworkConnectionInner>> getWithResponseAsync(
        String resourceGroupName, String virtualHubName, String connectionName) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (virtualHubName == null) {
            return Mono.error(new IllegalArgumentException("Parameter virtualHubName is required and cannot be null."));
        }
        if (connectionName == null) {
            return Mono.error(new IllegalArgumentException("Parameter connectionName is required and cannot be null."));
        }
        final String apiVersion = "2018-11-01";
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .get(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            resourceGroupName,
                            virtualHubName,
                            connectionName,
                            apiVersion,
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Retrieves the details of a HubVirtualNetworkConnection.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @param connectionName The name of the vpn connection.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return hubVirtualNetworkConnection Resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<HubVirtualNetworkConnectionInner>> getWithResponseAsync(
        String resourceGroupName, String virtualHubName, String connectionName, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (virtualHubName == null) {
            return Mono.error(new IllegalArgumentException("Parameter virtualHubName is required and cannot be null."));
        }
        if (connectionName == null) {
            return Mono.error(new IllegalArgumentException("Parameter connectionName is required and cannot be null."));
        }
        final String apiVersion = "2018-11-01";
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .get(
                this.client.getEndpoint(),
                this.client.getSubscriptionId(),
                resourceGroupName,
                virtualHubName,
                connectionName,
                apiVersion,
                accept,
                context);
    }

    /**
     * Retrieves the details of a HubVirtualNetworkConnection.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @param connectionName The name of the vpn connection.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return hubVirtualNetworkConnection Resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<HubVirtualNetworkConnectionInner> getAsync(
        String resourceGroupName, String virtualHubName, String connectionName) {
        return getWithResponseAsync(resourceGroupName, virtualHubName, connectionName)
            .flatMap(
                (Response<HubVirtualNetworkConnectionInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Retrieves the details of a HubVirtualNetworkConnection.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @param connectionName The name of the vpn connection.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return hubVirtualNetworkConnection Resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public HubVirtualNetworkConnectionInner get(
        String resourceGroupName, String virtualHubName, String connectionName) {
        return getAsync(resourceGroupName, virtualHubName, connectionName).block();
    }

    /**
     * Retrieves the details of a HubVirtualNetworkConnection.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @param connectionName The name of the vpn connection.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return hubVirtualNetworkConnection Resource.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<HubVirtualNetworkConnectionInner> getWithResponse(
        String resourceGroupName, String virtualHubName, String connectionName, Context context) {
        return getWithResponseAsync(resourceGroupName, virtualHubName, connectionName, context).block();
    }

    /**
     * Retrieves the details of all HubVirtualNetworkConnections.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<HubVirtualNetworkConnectionInner>> listSinglePageAsync(
        String resourceGroupName, String virtualHubName) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (virtualHubName == null) {
            return Mono.error(new IllegalArgumentException("Parameter virtualHubName is required and cannot be null."));
        }
        final String apiVersion = "2018-11-01";
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .list(
                            this.client.getEndpoint(),
                            this.client.getSubscriptionId(),
                            resourceGroupName,
                            virtualHubName,
                            apiVersion,
                            accept,
                            context))
            .<PagedResponse<HubVirtualNetworkConnectionInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Retrieves the details of all HubVirtualNetworkConnections.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<HubVirtualNetworkConnectionInner>> listSinglePageAsync(
        String resourceGroupName, String virtualHubName, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        if (resourceGroupName == null) {
            return Mono
                .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
        }
        if (virtualHubName == null) {
            return Mono.error(new IllegalArgumentException("Parameter virtualHubName is required and cannot be null."));
        }
        final String apiVersion = "2018-11-01";
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .list(
                this.client.getEndpoint(),
                this.client.getSubscriptionId(),
                resourceGroupName,
                virtualHubName,
                apiVersion,
                accept,
                context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }

    /**
     * Retrieves the details of all HubVirtualNetworkConnections.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedFlux<HubVirtualNetworkConnectionInner> listAsync(String resourceGroupName, String virtualHubName) {
        return new PagedFlux<>(
            () -> listSinglePageAsync(resourceGroupName, virtualHubName),
            nextLink -> listNextSinglePageAsync(nextLink));
    }

    /**
     * Retrieves the details of all HubVirtualNetworkConnections.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<HubVirtualNetworkConnectionInner> listAsync(
        String resourceGroupName, String virtualHubName, Context context) {
        return new PagedFlux<>(
            () -> listSinglePageAsync(resourceGroupName, virtualHubName, context),
            nextLink -> listNextSinglePageAsync(nextLink, context));
    }

    /**
     * Retrieves the details of all HubVirtualNetworkConnections.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<HubVirtualNetworkConnectionInner> list(String resourceGroupName, String virtualHubName) {
        return new PagedIterable<>(listAsync(resourceGroupName, virtualHubName));
    }

    /**
     * Retrieves the details of all HubVirtualNetworkConnections.
     *
     * @param resourceGroupName The resource group name of the VirtualHub.
     * @param virtualHubName The name of the VirtualHub.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<HubVirtualNetworkConnectionInner> list(
        String resourceGroupName, String virtualHubName, Context context) {
        return new PagedIterable<>(listAsync(resourceGroupName, virtualHubName, context));
    }

    /**
     * Get the next page of items.
     *
     * @param nextLink The nextLink parameter.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<HubVirtualNetworkConnectionInner>> listNextSinglePageAsync(String nextLink) {
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context))
            .<PagedResponse<HubVirtualNetworkConnectionInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Get the next page of items.
     *
     * @param nextLink The nextLink parameter.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<HubVirtualNetworkConnectionInner>> listNextSinglePageAsync(
        String nextLink, Context context) {
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .listNext(nextLink, this.client.getEndpoint(), accept, context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().nextLink(),
                        null));
    }
}


text:
import pandas as pd
import re
from pandas import DataFrame
from datetime import datetime, timedelta
from merge_similar_messages import merge_messages
from util import load_json_by_line, json_load, json_dump

def clean_interaction_data(input_path, output_path):
    obj = load_json_by_line(input_path)
    df = DataFrame(obj)
    df['timestamp'] = df['datetime']
    df['datetime'] = df['timestamp'].map(
        lambda ts: str(datetime.fromtimestamp(ts))
        )
    df.to_json(output_path, orient="records")

def convert_interaction_user_id_to_string(df):
    df['sender_id'] = df['sender_id'].map(str)
    df['recipient_ids'] = df['recipient_ids'].map(
        lambda ids: map(str, ids)
        )
    return df

def convert_people_user_id_to_string(df):
    df['id'] = df['id'].map(str)
    return df

reg_exps = [re.compile(r'-{2,}\s*' + s)
            for s in ('original message',
                      'forwarded')
            ]
reg_exps.append(
    re.compile('*************************'.replace('*', '\\*'))
    )

email = '[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+'
datetime = '\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}(:\d{2})?\s*[aApP][mM]'
reg_exps.append(
    re.compile('<?{}>?.*{}'.format(email,
                               datetime))
)
reg_exps.append(
    re.compile('{}.*[Tt][Oo].*<?{}>?'.format(datetime,
                                         email))
)

def truncate_message(text):
    text_lower = text.lower()
    for reg in reg_exps:
        for m in reg.finditer(text_lower):
            return text[:m.start()]
    return text

def process_message_body(df):
    df['body'] = df['body'].map(truncate_message)
    df['body'] = df['body'].map(lambda b: b.replace('=20', ''))
    return df

def filter_and_save(df):
    # df = process_message_body(df)
    # df = df[df['body'].map(len) > 10]  # filter short body

    # potential: 14557
    black_list = [256, 1175]
    for s in black_list:
        df = df[df['sender_id'] != s]

    df.to_json('data/enron/interactions.json',
               orient="records")

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--dataset')
    args = parser.parse_args()

    df = pd.read_json('data/{}/interactions.json'.format(args.dataset))
    df = merge_messages(
        df,
        timedelta(weeks=4),
        70,
        'datetime'
        )
    df.to_json('data/{}/interactions.json'.format(args.dataset))
    # frequent_senders = df['sender_id'].value_counts().index[20:40]
    # for s in frequent_senders:
    #     print(s)
    #     print(df[df['sender_id'] == s]['subject'][:10])
    #     print('*' * 20)

    # filter_and_save(df)

redpajama_set_name: RedPajamaGithub


text:
<?php

require("deploy_config.php");

class Deploy {

	public $config;

	public $tempFolder;		//Folder where zip will be downloaded
	public $zipFile;		//Name and path of the downloaded zipped source

	public $repoBranch;		//repo's branch
	public $repoUrl; 		//URL from repo
	public $repoUser;		//For authentication in the repo
	public $repoPass;		//For authentication in the repo

	public $destination;	//Folder where proyect will be placed, if it already exist's it will be moved to...
	public $oldDeploys;		//Folder where old proyects will be moved
	public $sourceFolder;	//Folder that conatins source files inside repo

	public $wasError;		//Indicates whether there was an error or not
	public $emails;			//Emails to notify when deploy has finished
	public $errorMessage;

	public function Deploy($config)
	{
		$this->config = $config;

		$this->repoBranch = $config["repo"]["branch"];
		$this->tempFolder = $config["path"]["temp"];
		$this->zipFile = $this->repoBranch .".zip";

		$this->repoUrl = $config["repo"]["url"];
		$this->repoUser = $config["repo"]["user"];
		$this->repoPass = $config["repo"]["pass"];

		$this->sourceFolder = $config["path"]["source"];
		$this->destination = $config["path"]["destination"];
		$this->oldDeploys = $config["path"]["old"];

		$this->wasError = false;
		$this->emails = $config["emails"];
	}

	public function makeDeploy()
	{

		try{
			if(is_dir($this->tempFolder)){
				throw new Exception("Deploy already in progress", 1);
			}

			$this->download();
			$this->unzip();
			$this->moveOld();
			$this->moveNew();

		}catch(Exception $e){
			$this->errorMessage = $e->getMessage();
			$this->wasError = true;
		}

		try{
			$this->deleteTemp();
		}catch(Exception $e){
			$this->wasError = true;
			$this->errorMessage = $e->getMessage();
		}

		$this->notify();
	}

	/* Downloads the repo to temp folder using username and password*/
	public function download()
	{
		createFolder($this->tempFolder);
		$fp = fopen($this->tempFolder .$this->zipFile, 'w');

		// set download url of repository for the relating node
		$ch = curl_init($this->repoUrl .$this->zipFile);

		// http authentication to access the download
		curl_setopt($ch, CURLOPT_USERPWD, $this->repoUser .":" .$this->repoPass);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

	 	// disable ssl verification if your server doesn't have it
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		// save the transfered zip folder
		curl_setopt($ch, CURLOPT_FILE, $fp);

		// run the curl command
		$result = curl_exec($ch);	//returns true / false

		// close curl and file functions
		curl_close($ch);
		fclose($fp);
		if(!$result){
			throw new Exception("Error al descargar el archivo", 1);
		}
	}

	/* Unzip the repo */
	public function unzip()
	{
		$zip = new ZipArchive;
		$res = $zip->open($this->tempFolder .$this->zipFile);
		if ($res === TRUE) {
			$zip->extractTo($this->tempFolder);
			$zip->close();
			return;
		}

		throw new Exception("Error while trying to decompress");
	}

	public function moveOld()
	{
		/* If directory doesn't exist, do nothing*/
		if(!is_dir($this->destination)){
			return;
		}

		/* Create the old folder */
		createFolder($this->oldDeploys);
		$date = getdate();

		/* Move the old files to the olds folder*/
		$name = $this->oldDeploys .substr($this->destination, 0, -1) ."_" .$date['year'] ."_" .$date['mon'] ."_" .$date['mday'] ."_" .$date[0];
		if(!rename($this->destination, $name)){
			throw new Exception("Error while moving old proyect", 1);
		}
	}

	/* Moves all new files*/
	public function moveNew()
	{
		/*
		* Bitbucket sadly ads random characters, so it has to guess...
		*/
		$dirs = scandir($this->tempFolder);
		foreach ($dirs as $dir) {
			if($dir != "." && $dir != ".." && $dir != ($this->zipFile)){
				if(rename($this->tempFolder. $dir ."/" .$this->sourceFolder, $this->destination)){
					return;
				}
			}
		}
		throw new Exception("Error while trying to move new deploy");
	}

	public function deleteTemp()
	{
		if(!deleteDirectory($this->tempFolder)){
			throw new Exception("Couldn't delete temp folder", 1);
		}
	}

	public function notify()
	{
		if(sizeof($this->emails)>0){
			if($this->wasError){
				$msg = "Deploy finished with error: $this->errorMessage";
			}else{
				$msg = "Deploy finished OK";
			}
			mail (implode(", ", $this->emails) , "Deploy finished", $msg);
		}
	}

}

function createFolder($dir){
	if(!is_dir($dir)){
		if(!mkdir($dir, 0777, true)){
			throw new Exception("No se pudo crear la carpeta", 1);
		}
	}
}

/* Deletes a not empty directory*/
function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }

    }

    return rmdir($dir);
}

$deploy = new Deploy($config);
$deploy->makeDeploy();


text:
package javaobject;

import org.apache.geode.cache.Declarable;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.FunctionAdapter;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.ResultSender;
import org.apache.geode.cache.execute.RegionFunctionContext;
import org.apache.geode.internal.cache.execute.PartitionedRegionFunctionResultSender;
import org.apache.geode.internal.cache.PartitionedRegionHelper;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.cache.partition.PartitionRegionHelper;
import java.util.ArrayList;
import java.util.Properties;
import java.util.*;

public class FEOnRegionPrSHOP_OptimizeForWrite extends FunctionAdapter implements Declarable{

  public void execute(FunctionContext context) {
    RegionFunctionContext regionContext = (RegionFunctionContext)context;
    PartitionedRegionFunctionResultSender rs = (PartitionedRegionFunctionResultSender)regionContext.getResultSender();
	ResultSender sender = context.getResultSender();
    PartitionedRegion pr = (PartitionedRegion)regionContext.getDataSet();

	// Use this for debugging if bucketIds dont match.
	/*Set keys = regionContext.getFilter();
    System.out.println("Context " + keys);
    ArrayList vals = new ArrayList();
    Iterator itr = keys.iterator();
    while (itr.hasNext()) {
      Object k = itr.next();
	  Integer bucketId = new Integer(PartitionedRegionHelper.getHashKey(pr, k));
  	  System.out.println("CPPTEST: found BucketId: " + bucketId);
  	  List bucketListOnNode = pr.getLocalPrimaryBucketsListTestOnly();
  	  System.out.println("CPPTEST: bucketListOnNode size is: " + bucketListOnNode.size());
	  Iterator it=bucketListOnNode.iterator();
      while(it.hasNext())
      {
        Integer value=(Integer)it.next();
        System.out.println("Value :"+value);
      }
  	  if (!bucketListOnNode.contains(bucketId)) {
 		System.out.println("CPPTEST: Wrong BucketId from list");
		sender.lastResult(false);
		return;
  	  }
	  if (PartitionRegionHelper.getPrimaryMemberForKey(pr, k) == null) {
      System.out.println("CPPTEST: Wrong BucketId from member");
	  sender.lastResult(false);
	  return;
      }
    }*/
    sender.lastResult(rs.isLocallyExecuted());	 //This is single hop indication.
  }

  public String getId() {
    return "FEOnRegionPrSHOP_OptimizeForWrite";
  }

  public boolean optimizeForWrite() {
    return true;
  }

  public void init(Properties arg0) {
  }
}


text:
INSERT INTO `auth_item_child` (`parent`, `child`) VALUES
('admin', 'caixa'),
('admin', 'cardapio'),
('admin', 'categoria'),
('admin', 'compra'),
('admin', 'conta'),
('admin', 'contasapagar'),
('admin', 'contasareceber'),
('admin', 'historicosituacao'),
('admin', 'insumo'),
('admin', 'itemcardapio'),
('admin', 'itempedido'),
('admin', 'loja'),
('admin', 'mesa'),
('admin', 'pagamento'),
('admin', 'pedido'),
('admin', 'produto'),
('admin', 'relatorio'),
('admin', 'tipocustofixo'),
('admin', 'user'),
('caixa', 'create-caixa'),
('caixa', 'delete-caixa'),
('caixa', 'fechar-caixa'),
('caixa', 'index-caixa'),
('caixa', 'update-caixa'),
('caixa', 'view-caixa'),
('cardapio', 'create-cardapio'),
('cardapio', 'delete-cardapio'),
('cardapio', 'index-cardapio'),
('cardapio', 'update-cardapio'),
('cardapio', 'view-cardapio'),
('categoria', 'create-categoria'),
('categoria', 'delete-categoria'),
('categoria', 'index-categoria'),
('categoria', 'update-categoria'),
('categoria', 'view-categoria'),
('compra', 'create-compra'),
('compra', 'delete-compra'),
('compra', 'index-compra'),
('compra', 'update-compra'),
('compra', 'view-compra'),
('conta', 'contasapagar'),
('conta', 'contasareceber'),
('conta', 'create-conta'),
('conta', 'delete-conta'),
('conta', 'index-conta'),
('conta', 'update-conta'),
('conta', 'view-conta'),
('contasapagar', 'create-contasapagar'),
('contasapagar', 'custofixo'),
('contasapagar', 'delete-contasapagar'),
('contasapagar', 'index-contasapagar'),
('contasapagar', 'update-contasapagar'),
('contasapagar', 'view-contasapagar'),
('contasareceber', 'create-contasareceber'),
('contasareceber', 'delete-contasareceber'),
('contasareceber', 'index-contasareceber'),
('contasareceber', 'pagamento'),
('contasareceber', 'update-contasareceber'),
('contasareceber', 'view-contasareceber'),
('custofixo', 'create-custofixo'),
('custofixo', 'delete-custofixo'),
('custofixo', 'index-custofixo'),
('custofixo', 'tipocustofixo'),
('custofixo', 'update-custofixo'),
('custofixo', 'view-custofixo'),
('despesa', 'create-despesa'),
('despesa', 'delete-despesa'),
('despesa', 'index-despesa'),
('despesa', 'update-despesa'),
('despesa', 'view-despesa'),
('formapagamento', 'create-formapagamento'),
('formapagamento', 'delete-formapagamento'),
('formapagamento', 'index-formapagamento'),
('formapagamento', 'update-formapagamento'),
('formapagamento', 'view-formapagamento'),
('historicosituacao', 'create-historicosituacao'),
('historicosituacao', 'delete-historicosituacao'),
('historicosituacao', 'index-historicosituacao'),
('historicosituacao', 'update-historicosituacao'),
('historicosituacao', 'view-historicosituacao'),
('insumo', 'create-insumo'),
('insumo', 'delete-insumo'),
('insumo', 'index-insumo'),
('insumo', 'update-insumo'),
('insumo', 'view-insumo'),
('itemcardapio', 'create-itemcardapio'),
('itemcardapio', 'delete-itemcardapio'),
('itemcardapio', 'index-itemcardapio'),
('itemcardapio', 'update-itemcardapio'),
('itemcardapio', 'view-itemcardapio'),
('itempedido', 'create-itempedido'),
('itempedido', 'delete-itempedido'),
('itempedido', 'index-itempedido'),
('itempedido', 'update-itempedido'),
('itempedido', 'view-itempedido'),
('loja', 'create-loja'),
('loja', 'delete-loja'),
('loja', 'index-loja'),
('loja', 'update-loja'),
('loja', 'view-loja'),
('mesa', 'create-mesa'),
('mesa', 'delete-mesa'),
('mesa', 'index-mesa'),
('mesa', 'update-mesa'),
('mesa', 'view-mesa'),
('pagamento', 'create-pagamento'),
('pagamento', 'delete-pagamento'),
('pagamento', 'formapagamento'),
('pagamento', 'index-pagamento'),
('pagamento', 'update-pagamento'),
('pagamento', 'view-pagamento'),
('pedido', 'create-pedido'),
('pedido', 'delete-pedido'),
('pedido', 'index-pedido'),
('pedido', 'update-pedido'),
('pedido', 'view-pedido'),
('produto', 'alterarprodutovenda'),
('produto', 'avaliacaoproduto'),
('produto', 'cadastrarnovoproduto'),
('produto', 'cadastrarprodutovenda'),
('produto', 'create-produto'),
('produto', 'definirvalorprodutovenda'),
('produto', 'delete-produto'),
('produto', 'index-produto'),
('produto', 'listadeinsumos'),
('produto', 'listadeprodutosporinsumo'),
('produto', 'produtosvenda'),
('produto', 'update-produto'),
('produto', 'view-produto'),
('relatorio', 'create-relatorio'),
('relatorio', 'delete-relatorio'),
('relatorio', 'index-relatorio'),
('relatorio', 'relatoriocontasareceber'),
('relatorio', 'update-relatorio'),
('relatorio', 'view-relatorio'),
('tipocustofixo', 'create-tipocustofixo'),
('tipocustofixo', 'delete-tipocustofixo'),
('tipocustofixo', 'index-tipocustofixo'),
('tipocustofixo', 'update-tipocustofixo'),
('tipocustofixo', 'view-tipocustofixo'),
('user', 'create-user'),
('user', 'delete-user'),
('user', 'index-user'),
('user', 'update-user'),
('user', 'view-user');


text:
// Resolution switching support for videojs
//
// In this plugin I'm really going out of my way to *not* override the
// core videojs namespace and to *not* change the core API.  As a
// result this plugin is not as efficient as it might be.  It
// initializes itself *for each player* as scoped variables inside the
// plugin closure and grafts itself on to *the instance on which it was
// called* rather than on the videojs player prototype.  I don't expect
// this to be a big deal for anybody.
videojs.plugin('resolutions', function(options) {
  var player = this;

  // 'reduce' utility method
  // @param {Array} array to iterate over
  // @param {Function} iterator function for collector
  // @param {Array|Object|Number|String} initial collector
  // @return collector
  vjs.reduce = function(arr, fn, init, n) {
    if (!arr || arr.length === 0) { return; }
    for (var i=0,j=arr.length; i<j; i++) {
      init = fn.call(arr, init, arr[i], i);
    }
    return init;
  };

  this.resolutions_ = {
    options_: {},

    // takes an existing stream and stops the download entirely
    // without killing the player or disposing of the tech
    stopStream: function(){
      switch(player.techName){
      case "Html5":
        break;
      case "Flash":
        player.tech.el_.vjs_stop();
        break;
      }

      // this may cause flash or the native player to emit errors but
      // they are harmless
      player.src("");
    },

    // it is necessary to remove the sources from the DOM after
    // parsing them because otherwise the native player may be
    // inclined to stream both sources
    removeSources: function(el){
      var videoEl = player.el_.getElementsByTagName("video")[0];

      if (player.techName !== "Html5" || !videoEl) return;

      var srcs = videoEl.getElementsByTagName("source");
      for(var i=0;i<srcs.length;i++){
        videoEl.removeChild(srcs[i]);
      }
    },

    // buckets all parsed sources by their type ("video/mp4", for example)
    // @param {Array} array of sources:
    // [
    //   {
    //     "data-res": "HD",
    //     "type": "video/mp4",
    //     "src": "http://some_video_url_hd"
    //   },
    //   {
    //     "data-default": "true",
    //     "data-res": "SD",
    //     "type": "video/mp4",
    //     "src": "http://some_video_url_sd"
    //   },
    //   {
    //     "data-default": "true",
    //     "data-res": "SD",
    //     "type": "video/ogv",
    //     "src": "http://some_video_url_sd"
    //   }
    // ]
    // @return sources grouped by type:
    // {
    //   "video/mp4": [
    //       {
    //           "data-res": "HD",
    //           "type": "video/mp4",
    //           "src": "http://some_video_url_hd"
    //       },
    //       {
    //           "data-default": "true",
    //           "data-res": "SD",
    //           "type": "video/mp4",
    //           "src": "http://some_video_url_sd"
    //       }
    //   ]
    //   "video/ogv": [
    //       {
    //           "data-res": "SD",
    //           "type": "video/ogv",
    //           "src": "http://some_video_url_sd"
    //       }
    //   ]
    // }
    bucketByTypes: function(sources){
      return vjs.reduce(sources, function(init, val, i){
        (init[val.type] = init[val.type] || []).push(val);
        return init;
      }, {}, player);
    },

    // takes parsed sources and selects the most appropriate source
    // taking into account resolution, technology support, and the
    // user's previous selections.  also indexes the sources
    // @param {Array} array of sources:
    // [
    //   {
    //     "data-res": "HD",
    //     "type": "video/mp4",
    //     "src": "http://some_video_url_hd"
    //   },
    //   {
    //     "data-default": "true",
    //     "data-res": "SD",
    //     "type": "video/mp4",
    //     "src": "http://some_video_url_sd"
    //   },
    //   {
    //     "data-default": "true",
    //     "data-res": "SD",
    //     "type": "video/ogv",
    //     "src": "http://some_video_url_sd"
    //   }
    // ]
    // @return {Object} single source:
    // {
    //  "data-res": "HD",
    //  "type": "video/mp4",
    //  "src": "http://some_video_url_jd",
    //  "index": 0
    // }
    selectSource: function(sources){
      this.removeSources();

      var sourcesByType = this.bucketByTypes(sources);
      var typeAndTech   = this.selectTypeAndTech(sources);

      if (!typeAndTech) return false;

      // even though we choose the best resolution for the user here, we
      // should remember the resolutions so that we can potentially
      // change resolution later
      this.options_['sourceResolutions'] = sourcesByType[typeAndTech.type];

      return this.selectResolution(this.options_['sourceResolutions']);
    },

    // takes parsed sources and returns the most appropriate
    // technology and video type
    // @param {Array} array of sources:
    // [
    //   {
    //     "data-res": "HD",
    //     "type": "video/mp4",
    //     "src": "http://some_video_url_hd"
    //   },
    //   {
    //     "data-default": "true",
    //     "data-res": "SD",
    //     "type": "video/mp4",
    //     "src": "http://some_video_url_sd"
    //   },
    //   {
    //     "data-default": "true",
    //     "data-res": "SD",
    //     "type": "video/ogv",
    //     "src": "http://some_video_url_sd"
    //   }
    // ]
    // @return {Object} type/tech:
    // {
    //  "type": "video/ogv",
    //  "tech": "Html5"
    // }
    selectTypeAndTech: function(sources) {
      var techName;
      var tech;

      for (var i=0,j=player.options_['techOrder'];i<j.length;i++) {
        techName = videojs.capitalize(j[i]);
        tech     = window['videojs'][techName];

        // Check if the browser supports this technology
        if (tech.isSupported()) {
          // Loop through each source object
          for (var a=0,b=sources;a<b.length;a++) {
            var source = b[a];
            // Check if source can be played with this technology
            if (tech['canPlaySource'](source)) {
              return { type: source.type, tech: techName };
            }
          }
        }
      }
    },

    // takes an array of sources of homogeneous type (ie. a complete
    // "bucket" from the output of bucketByTypes) and returns the best
    // source, taking into account the user's previous preferences
    // stored in local storage
    // @param {Array} homogeneous sources:
    // [
    //   {
    //       "data-res": "HD",
    //       "type": "video/mp4",
    //       "src": "http://some_video_url_hd"
    //   },
    //   {
    //       "data-default": "true",
    //       "data-res": "SD",
    //       "type": "video/mp4",
    //       "src": "http://some_video_url_sd"
    //   }
    // ]
    // @return {Object} singular best source:
    // {
    //     "data-default": "true",
    //     "data-res": "SD",
    //     "type": "video/mp4",
    //     "src": "http://some_video_url_sd"
    //     "index": 1
    // }
    selectResolution: function(typeSources) {
      var defaultRes = 0;
      var supportsLocalStorage = !!window.localStorage;

      // check to see if any sources are marked as default
      videojs.obj.each(typeSources, function(i, s){
        // add the index here so we can reference it later
        s.index = parseInt(i, 10);

        if (s['data-default']) defaultRes = s.index;
      }, player);

      // if the user has previously selected a preference, check if
      // that preference is available. if not, use the source marked
      // default
      var preferredRes = defaultRes;

      // trying to follow the videojs code conventions of if statements
      if (supportsLocalStorage){
        var storedRes = parseInt(window.localStorage.getItem('videojs_preferred_res'), 10);

        if (!isNaN(storedRes))
          preferredRes = storedRes;
      }

      var maxRes    = (typeSources.length - 1);
      var actualRes = preferredRes > maxRes ? maxRes : preferredRes;

      return typeSources[actualRes];
    }
  };

  // convenience method
  // @return {String} cached resolution label:
  // "SD"
  player.resolution = function(){
      return this.cache_.src.res;
  };

  // takes a source and switches the player's stream to it on the fly
  // @param {Object} singular source:
  // {
  //     "data-default": "true",
  //    "data-res": "SD",
  //     "type": "video/mp4",
  //     "src": "http://some_video_url_sd"
  // }
  player.changeResolution = function(new_source){
    // has the exact same source been chosen?
    if (this.cache_.src === new_source.src){
      this.trigger('resolutionchange');
      return this; // basically a no-op
    }

    // remember our position and playback state
    var curTime      = this.currentTime();
    var remainPaused = this.paused();

    // pause playback
    this.pause();

    // attempts to stop the download of the existing video
    this.resolutions_.stopStream();

    // HTML5 tends to not recover from reloading the tech but it can
    // generally handle changing src.  Flash generally cannot handle
    // changing src but can reload its tech.
    if (this.techName === "Html5"){
      this.src(new_source.src);
    } else {
      this.loadTech(this.techName, {src: new_source.src});
    }

    // when the technology is re-started, kick off the new stream
    this.ready(function() {
      this.one('loadeddata', vjs.bind(this, function() {
        this.currentTime(curTime);
      }));

      this.trigger('resolutionchange');

      if (!remainPaused) {
        this.load();
        this.play();
      }

      // remember this selection
      vjs.setLocalStorage('videojs_preferred_res', parseInt(new_source.index, 10));
    });
  };

  /* Resolution Menu Items
  ================================================================================ */
  var ResolutionMenuItem = videojs.MenuItem.extend({
    init: function(player, options){
      // Modify options for parent MenuItem class's init.
      options['label'] = options.source['data-res'];
      videojs.MenuItem.call(this, player, options);

      this.source = options.source;
      this.resolution = options.source['data-res'];

      this.player_.one('loadstart', vjs.bind(this, this.update));
      this.player_.on('resolutionchange', vjs.bind(this, this.update));
    }
  });

  ResolutionMenuItem.prototype.onClick = function(){
    videojs.MenuItem.prototype.onClick.call(this);
    this.player_.changeResolution(this.source);
  };

  ResolutionMenuItem.prototype.update = function(){
    var player = this.player_;
    if ((player.cache_['src'] === this.source.src)) {
      this.selected(true);
    } else {
      this.selected(false);
    }
  };

  /* Resolutions Button
  ================================================================================ */
  var ResolutionButton = videojs.MenuButton.extend({
    init: function(player, options) {
      videojs.MenuButton.call(this, player, options);

      if (this.items.length <= 1) {
        this.hide();
      }
    }
  });

  ResolutionButton.prototype.sourceResolutions_;

  ResolutionButton.prototype.sourceResolutions = function() {
    return this.sourceResolutions_;
  };

  ResolutionButton.prototype.onClick = function(e){
    // Only proceed if the target of the click was a DIV (just the button and its inner div, not the menu)
    // This prevents the menu from opening and closing when one of the menu items is clicked.
    if (e.target.className.match(/vjs-control-content/)) {

      // Toggle the 'touched' class
      this[this.el_.className.match(/touched/) ? "removeClass" : "addClass"]("touched");
    } else {

      // Remove the 'touched' class from all control bar buttons with menus to hide any already visible...
      var buttons = document.getElementsByClassName('vjs-menu-button');
      for(var i=0;i<buttons.length;i++){
        videojs.removeClass(buttons[i], 'touched');
      }

      this.removeClass('touched');
    }
  };

  ResolutionButton.prototype.createItems = function(){
    var resolutions = this.sourceResolutions_ = this.player_.resolutions_.options_['sourceResolutions'];
    var items = [];
    for (var i = 0; i < resolutions.length; i++) {
      items.push(new ResolutionMenuItem(this.player_, {
        'source': this.sourceResolutions_[i]
      }));
    }
    return items;
  };

  /**
   * @constructor
   */
  ResolutionsButton = ResolutionButton.extend({
    /** @constructor */
    init: function(player, options, ready){
      ResolutionButton.call(this, player, options, ready);
      this.el_.setAttribute('aria-label','Resolutions Menu');
      this.el_.setAttribute('id',"vjs-resolutions-button");
    }
  });

  ResolutionsButton.prototype.kind_ = 'resolutions';
  ResolutionsButton.prototype.buttonText = 'Resolutions';
  ResolutionsButton.prototype.className = 'vjs-resolutions-button';

  // Add Button to controlBar
  videojs.obj.merge(player.controlBar.options_['children'], {
    'resolutionsButton': {}
  });

  // let's get the party started!
  // we have to grab the parsed sources and select the source with our
  // resolution-aware source selector
  var source = player.resolutions_.selectSource(player.options_['sources']);

  // when the player is ready, add the resolution button to the control bar
  player.ready(function(){
    player.changeResolution(source);
    var button = new ResolutionsButton(player);
    player.controlBar.addChild(button);
  });
});


text:
"""The base file related data source object from which all MayaVi data
sources derive.

"""
# Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
# Copyright (c) 2005, Enthought, Inc.
# License: BSD Style.

# Standard library imports.
import re
from os.path import split, join, isfile
from glob import glob

# Enthought library imports.
from traits.api import List, Str, Instance, Int, Range
from traitsui.api import Group, Item, FileEditor
from apptools.persistence.state_pickler import set_state
from apptools.persistence.file_path import FilePath

# Local imports
from mayavi.core.source import Source
from mayavi.core.common import handle_children_state

######################################################################
# Utility functions.
######################################################################
def get_file_list(file_name):
    """ Given a file name, this function treats the file as a part of
    a series of files based on the index of the file and tries to
    determine the list of files in the series.  The file name of a
    file in a time series must be of the form 'some_name[0-9]*.ext'.
    That is the integers at the end of the file determine what part of
    the time series the file belongs to.  The files are then sorted as
    per this index."""

    # The matching is done only for the basename of the file.
    f_dir, f_base = split(file_name)
    # Find the head and tail of the file pattern.
    head = re.sub("[0-9]+[^0-9]*$", "", f_base)
    tail = re.sub("^.*[0-9]+", "", f_base)
    pattern = head+"[0-9]*"+tail
    # Glob the files for the pattern.
    _files = glob(join(f_dir, pattern))

    # A simple function to get the index from the file.
    def _get_index(f, head=head, tail=tail):
        base = split(f)[1]
        result = base.replace(head, '')
        return float(result.replace(tail, ''))

    # Before sorting make sure the files in the globbed series are
    # really part of a timeseries.  This can happen in cases like so:
    # 5_2_1.vtk and 5_2_1s.vtk will be globbed but 5_2_1s.vtk is
    # obviously not a valid time series file.
    files = []
    for x in _files:
        try:
            _get_index(x)
        except ValueError:
            pass
        else:
            files.append(x)

    # Sort the globbed files based on the index value.
    def file_sort(x, y):
        x1 = _get_index(x)
        y1 = _get_index(y)
        if x1 > y1:
            return 1
        elif y1 > x1:
            return -1
        else:
            return 0

    files.sort(file_sort)
    return files

######################################################################
# `FileDataSource` class.
######################################################################
class FileDataSource(Source):

    # The version of this class.  Used for persistence.
    __version__ = 0

    # The list of file names for the timeseries.
    file_list = List(Str, desc='a list of files belonging to a time series')

    # The current time step (starts with 0).  This trait is a dummy
    # and is dynamically changed when the `file_list` trait changes.
    # This is done so the timestep bounds are linked to the number of
    # the files in the file list.
    timestep = Range(value=0,
                     low='_min_timestep',
                     high='_max_timestep',
                     enter_set=True, auto_set=False,
                     desc='the current time step')

    base_file_name=Str('', desc="the base name of the file",
                       enter_set=True, auto_set=False,
                       editor=FileEditor())

    # A timestep view group that may be included by subclasses.
    time_step_group = Group(Item(name='file_path', style='readonly'),
                            Item(name='timestep',
                                 defined_when='len(object.file_list) > 1')
                            )

    ##################################################
    # Private traits.
    ##################################################

    # The current file name.  This is not meant to be touched by the
    # user.
    file_path = Instance(FilePath, (), desc='the current file name')

    _min_timestep = Int(0)
    _max_timestep = Int(0)

    ######################################################################
    # `object` interface
    ######################################################################
    def __get_pure_state__(self):
        d = super(FileDataSource, self).__get_pure_state__()
        # These are obtained dynamically, so don't pickle them.
        for x in ['file_list', 'timestep']:
            d.pop(x, None)
        return d

    def __set_pure_state__(self, state):
        # Use the saved path to initialize the file_list and timestep.
        fname = state.file_path.abs_pth
        if not isfile(fname):
            msg = 'Could not find file at %s\n'%fname
            msg += 'Please move the file there and try again.'
            raise IOError, msg

        self.initialize(fname)
        # Now set the remaining state without touching the children.
        set_state(self, state, ignore=['children', 'file_path'])
        # Setup the children.
        handle_children_state(self.children, state.children)
        # Setup the children's state.
        set_state(self, state, first=['children'], ignore=['*'])

    ######################################################################
    # `FileDataSource` interface
    ######################################################################
    def initialize(self, base_file_name):
        """Given a single filename which may or may not be part of a
        time series, this initializes the list of files.  This method
        need not be called to initialize the data.
        """
        self.base_file_name = base_file_name

    ######################################################################
    # Non-public interface
    ######################################################################
    def _file_list_changed(self, value):
        # Change the range of the timestep suitably to reflect new list.
        n_files = len(self.file_list)
        timestep = min(self.timestep, n_files)
        self._max_timestep = max(n_files -1, 0)
        if self.timestep == timestep:
            self._timestep_changed(timestep)
        else:
            self.timestep = timestep

    def _file_list_items_changed(self, list_event):
        self._file_list_changed(self.file_list)

    def _timestep_changed(self, value):
        file_list = self.file_list
        if len(file_list) > 0:
            self.file_path = FilePath(file_list[value])
        else:
            self.file_path = FilePath('')

    def _base_file_name_changed(self,value):
        self.file_list = get_file_list(value)
        if len(self.file_list) == 0:
            self.file_list = [value]
        try:
            self.timestep = self.file_list.index(value)
        except ValueError:
            self.timestep = 0


text:
In cotonic all independent components need to communicate with each other,
because there is no way of knowing where a message originates from.

## UBF(A)

In https://github.com/zotonic/zotonic we use UBF(A) messages to communicate
between the javascript world and the erlang world. UBF(A) is a great binary format,
and easily parsable. This made it an ideal candidate to use as an over the wire
language between javascript and zotonic.

For more information on UBF(A) see: http://armstrongonsoftware.blogspot.nl/2008/07/ubf-and-vm-opcocde-design.html
and the original specification: http://www.erlang.se/workshop/2002/Armstrong.pdf

We would like to continue to use UBF because it allows:

  * Very easy parsing of complex data types
  * Efficient over the wire encoding.
  * The possibility to define a protocol with typed messages and adding external type/contract checkers.

## UBF(A) and Cryptography

In order to use UBF(A) for a cryptographic purposes it is needed to specify a rigourous encoding. Adding whitespace
to UBF(A) encoded messages does not change the meaning of the message, but one extra spaces would completely
alter any cryptographic hash.

In order to survive addtion of semantically meaningless characters like whitespace and comments we need to
define a  canonical form of UBF(A). This would basically be UBF without unneeded whitespace and comments.

## Or use CBOR en COSE?

TODO


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using FluentAssertions;
using NetFusion.Common.Extensions.Reflection;
using Xunit;

namespace CommonTests.Extensions.Reflection
{
    public class MemberTests
    {
        [Fact]
        public void CanDetermine_IfNullableType()
        {
            typeof(TestClass).GetProperty("Sequence").IsNullable().Should().BeTrue();
            typeof(TestClass).GetProperty("Name").IsNullable().Should().BeTrue();
            typeof(TestClass).GetProperty("DateRequested").IsNullable().Should().BeTrue();
            typeof(TestClass).GetProperty("Total").IsNullable().Should().BeFalse();
        }

        [Fact]
        public void CanDetermine_IfMemberMarkedRequired()
        {
            typeof(TestClass).GetProperty("Name").IsMarkedRequired().Should().BeTrue();
        }

        [Fact]
        public void CanDetermine_IfEnumerableType()
        {
            typeof(TestClass).GetProperty("Name").IsEnumerable().Should().BeFalse();
            typeof(TestClass).GetProperty("MissedSequences").IsEnumerable().Should().BeTrue();
            typeof(TestClass).GetProperty("Total").IsEnumerable().Should().BeFalse();
            typeof(TestClass).GetProperty("Rates").IsEnumerable().Should().BeTrue();
            typeof(TestClass).GetProperty("Ages").IsEnumerable().Should().BeTrue();
        }

        [Fact]
        public void CanDetermine_EnumerableOfType()
        {
            typeof(TestClass).GetProperty("Name").GetEnumerableType().Should().BeNull();
            typeof(TestClass).GetProperty("MissedSequences").GetEnumerableType().Should().Be(typeof(int));
            typeof(TestClass).GetProperty("Total").GetEnumerableType().Should().BeNull();
            typeof(TestClass).GetProperty("Rates").GetEnumerableType().Should().Be(typeof(decimal));
            typeof(TestClass).GetProperty("Ages").GetEnumerableType().Should().Be(typeof(int));
        }

        private class TestClass
        {
            public int? Sequence { get; set; }

            [Required]
            public string Name { get; set; }
            public DateTime? DateRequested { get; set; }
            public int Total { get; set; }

            public List<int> MissedSequences { get; set; }
            public IReadOnlyCollection<decimal> Rates { get; set; }
            public int[] Ages { get; set; }
        }
    }
}


text:
class TimeSlotsController < ApplicationController
  layout 'shifts'

  before_filter :require_department_admin

  def index
    @period_start = params[:date] ? Date.parse(params[:date]).previous_sunday : Date.today.previous_sunday
    #TODO:simplify this stuff:
    @dept_start_hour = current_department.department_config.schedule_start / 60
    @dept_end_hour = current_department.department_config.schedule_end / 60
    @hours_per_day = (@dept_end_hour - @dept_start_hour)
    @block_length = current_department.department_config.time_increment
    @blocks_per_hour = 60/@block_length.to_f
    @blocks_per_day = @hours_per_day * @blocks_per_hour
    @hidden_timeslots = [] #for timeslots that don't show up on the view
  end

  def show
    @time_slot = TimeSlot.find(params[:id])
  end

  def new
    @time_slot = TimeSlot.new
    @period_start = params[:date] ? Date.parse(params[:date]).previous_sunday.to_date : Date.today.previous_sunday.to_date
  end

  def create
    errors = []
    parse_date_and_time_output(params[:time_slot])
    join_date_and_time(params[:time_slot])
    @time_slot = TimeSlot.new(params[:time_slot])
    if !@time_slot.save
      errors << "Error saving timeslot"
    end

    respond_to do |format|
      format.html do
          if errors.empty?
            flash[:notice] = "Successfully created timeslot(s)."
          else
            flash[:error] =  "Error: "+errors*"
"
          end
          redirect_to time_slots_path
      end
      format.js do
          if errors.empty?
            @dept_start_hour = current_department.department_config.schedule_start / 60
            @dept_end_hour = current_department.department_config.schedule_end / 60
            @hours_per_day = (@dept_end_hour - @dept_start_hour)
            if (@time_slot.start.beginning_of_day + current_department.department_config.schedule_start.minutes) <= @time_slot.start ##in the normal day (up to midnight)
              @time_slot_day = @time_slot.start.to_date
            else #after midnight
              @time_slot_day = @time_slot.start.to_date - 1.day
            end
          else
            render :update do |page|
              ajax_alert(page, "error: timeslot could not be saved
"+errors*"
")
            end
          end
      end
    end
  end

  def edit
    @time_slot = TimeSlot.find(params[:id])
  end

  def update
    @time_slot = TimeSlot.find(params[:id])
    parse_date_and_time_output(params[:time_slot])
    join_date_and_time(params[:time_slot])
    # if it was after midnight to begin with, then there is a problem... why?
    if (@time_slot.start.beginning_of_day + current_department.department_config.schedule_start.minutes) <= @time_slot.start ##in the normal day (up to midnight)
      @time_slot_day = @time_slot.start.to_date
    else #after midnight
      @time_slot_day = @time_slot.start.to_date - 1.day
    end
    if @time_slot.update_attributes(params[:time_slot])
      respond_to do |format|
        format.js
        format.html do
          flash[:notice] = "Successfully updated timeslot."
          redirect_to @time_slot
        end
      end
    else
      respond_to do |format|
        format.js do
          error_string = ""
          @time_slot.errors.each do |attr_name, message|
            error_string += "

#{attr_name}: #{message}"
          end
          @ajax_error_message = "error: updated time slot could not be saved."+error_string
          render :update
        end
        format.html {render action: 'edit'}
      end
    end

  end

  def destroy
    @time_slot = TimeSlot.find(params[:id])
    @time_slot.destroy
    respond_to do |format|
      format.html {flash[:notice] = "Successfully destroyed timeslot."; redirect_to time_slots_url}
      format.js #remove partial from view
    end
  end
end


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class VaultConfig(AppConfig):
    name = 'vault'


text:
import discord
import os

# Session
session = 'Blankbot'
client = discord.Client()
token = 'MTkzNDQ1NTk5ODcyMjg2NzIw.CkXfwQ.610VHj2W49WR9IUzAWWcBL1APrg'
sinc_invite = 'https://discord.gg/0zv7gFjB5rch8L2I'

# Channels
bots = '193969061808308224'

@client.event
async def on_ready():
    # Wake-up
    await client.send_message(
        client.get_channel(bots),
        session + ' session is active'
    )

@client.event
async def on_message(message):
    # Shortcuts
    channel = message.channel
    author = message.author
    content = message.content
    # Console
    print("[%s] %s: %s" % (channel, author, content))

    # ADMIN Commands
    if channel.id == bots:
        # Force exit
        if content.startswith('!stop' + session):
            await client.send_message(client.get_channel(bots), session + ' session stopped')
            os._exit(0)

        # Editor check
        if content.startswith('!session'):
            await client.send_message(client.get_channel(bots), 'Current session: ' + session)

# Login/Join
client.accept_invite(sinc_invite)
client.run(token)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>TOMSender</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

bftsmart.tom

Class TOMSender

java.lang.Object

bftsmart.tom.TOMSender

All Implemented Interfaces:

bftsmart.communication.client.ReplyReceiver

Direct Known Subclasses:

ServiceProxy

public abstract class TOMSender
extends java.lang.Object
implements bftsmart.communication.client.ReplyReceiver

This class is used to multicast messages to replicas and receive replies.

Constructor Summary

Constructors

Constructor and Description

TOMSender()

Creates a new instance of TOMulticastSender

 TODO: This may really be empty?

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
close()

int
generateOperationId()

int
generateRequestId(bftsmart.tom.core.messages.TOMMessageType type)

bftsmart.communication.client.CommunicationSystemClientSide
getCommunicationSystem()

int
getProcessId()

int
getSession()

bftsmart.reconfiguration.ClientViewController
getViewManager()

void
init(int processId)

This method initializes the object
 TODO: Ask if this method cannot be protected (compiles, but....)

void
init(int processId,
    java.lang.String configHome)

void
sendMessageToTargets(byte[] m,
                    int reqId,
                    int[] targets,
                    bftsmart.tom.core.messages.TOMMessageType type)

void
sendMessageToTargets(byte[] m,
                    int reqId,
                    int operationId,
                    int[] targets,
                    bftsmart.tom.core.messages.TOMMessageType type)

void
TOMulticast(byte[] m,
           int reqId,
           int operationId,
           bftsmart.tom.core.messages.TOMMessageType reqType)

void
TOMulticast(byte[] m,
           int reqId,
           bftsmart.tom.core.messages.TOMMessageType reqType)

Multicast data to the group of replicas

void
TOMulticast(bftsmart.tom.core.messages.TOMMessage sm)

Multicast a TOMMessage to the group of replicas

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface bftsmart.communication.client.ReplyReceiver

replyReceived

Constructor Detail

TOMSender

public TOMSender()

Creates a new instance of TOMulticastSender

 TODO: This may really be empty?

Method Detail

close

public void close()

getCommunicationSystem

public bftsmart.communication.client.CommunicationSystemClientSide getCommunicationSystem()

getViewManager

public bftsmart.reconfiguration.ClientViewController getViewManager()

init

public void init(int processId)

This method initializes the object
 TODO: Ask if this method cannot be protected (compiles, but....)

Parameters:

processId - ID of the process

init

public void init(int processId,
                 java.lang.String configHome)

getProcessId

public int getProcessId()

generateRequestId

public int generateRequestId(bftsmart.tom.core.messages.TOMMessageType type)

generateOperationId

public int generateOperationId()

TOMulticast

public void TOMulticast(bftsmart.tom.core.messages.TOMMessage sm)

Multicast a TOMMessage to the group of replicas

Parameters:

sm - Message to be multicast

TOMulticast

public void TOMulticast(byte[] m,
                        int reqId,
                        bftsmart.tom.core.messages.TOMMessageType reqType)

Multicast data to the group of replicas

Parameters:

m - Data to be multicast

reqId - unique integer that identifies this request

reqType - TOM_NORMAL, TOM_READONLY or TOM_RECONFIGURATION

TOMulticast

public void TOMulticast(byte[] m,
                        int reqId,
                        int operationId,
                        bftsmart.tom.core.messages.TOMMessageType reqType)

sendMessageToTargets

public void sendMessageToTargets(byte[] m,
                                 int reqId,
                                 int[] targets,
                                 bftsmart.tom.core.messages.TOMMessageType type)

sendMessageToTargets

public void sendMessageToTargets(byte[] m,
                                 int reqId,
                                 int operationId,
                                 int[] targets,
                                 bftsmart.tom.core.messages.TOMMessageType type)

getSession

public int getSession()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
require_dependency 'tuttle/application_controller'
require 'tuttle/version'

module Tuttle
  class HomeController < ApplicationController

    def index
    end

  end
end


text:
#undef DEBUG

#include <linux/config.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/adb.h>
#include <linux/pmu.h>
#include <linux/interrupt.h>
#include <linux/mc146818rtc.h>
#include <linux/bcd.h>

#include <asm/sections.h>
#include <asm/prom.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/machdep.h>
#include <asm/time.h>

#include "maple.h"

#ifdef DEBUG
#define DBG(x...) printk(x)
#else
#define DBG(x...)
#endif

extern void GregorianDay(struct rtc_time * tm);

static int maple_rtc_addr;

static int maple_clock_read(int addr)
{
	outb_p(addr, maple_rtc_addr);
	return inb_p(maple_rtc_addr+1);
}

static void maple_clock_write(unsigned long val, int addr)
{
	outb_p(addr, maple_rtc_addr);
	outb_p(val, maple_rtc_addr+1);
}

void maple_get_rtc_time(struct rtc_time *tm)
{
	int uip, i;

	/* The Linux interpretation of the CMOS clock register contents:
	 * When the Update-In-Progress (UIP) flag goes from 1 to 0, the
	 * RTC registers show the second which has precisely just started.
	 * Let's hope other operating systems interpret the RTC the same way.
	 */

	/* Since the UIP flag is set for about 2.2 ms and the clock
	 * is typically written with a precision of 1 jiffy, trying
	 * to obtain a precision better than a few milliseconds is
	 * an illusion. Only consistency is interesting, this also
	 * allows to use the routine for /dev/rtc without a potential
	 * 1 second kernel busy loop triggered by any reader of /dev/rtc.
	 */

	for (i = 0; i<1000000; i++) {
		uip = maple_clock_read(RTC_FREQ_SELECT);
		tm->tm_sec = maple_clock_read(RTC_SECONDS);
		tm->tm_min = maple_clock_read(RTC_MINUTES);
		tm->tm_hour = maple_clock_read(RTC_HOURS);
		tm->tm_mday = maple_clock_read(RTC_DAY_OF_MONTH);
		tm->tm_mon = maple_clock_read(RTC_MONTH);
		tm->tm_year = maple_clock_read(RTC_YEAR);
		uip |= maple_clock_read(RTC_FREQ_SELECT);
		if ((uip & RTC_UIP)==0)
			break;
	}

	if (!(maple_clock_read(RTC_CONTROL) & RTC_DM_BINARY)
	    || RTC_ALWAYS_BCD) {
		BCD_TO_BIN(tm->tm_sec);
		BCD_TO_BIN(tm->tm_min);
		BCD_TO_BIN(tm->tm_hour);
		BCD_TO_BIN(tm->tm_mday);
		BCD_TO_BIN(tm->tm_mon);
		BCD_TO_BIN(tm->tm_year);
	  }
	if ((tm->tm_year + 1900) < 1970)
		tm->tm_year += 100;

	GregorianDay(tm);
}

int maple_set_rtc_time(struct rtc_time *tm)
{
	unsigned char save_control, save_freq_select;
	int sec, min, hour, mon, mday, year;

	spin_lock(&rtc_lock);

	save_control = maple_clock_read(RTC_CONTROL); /* tell the clock it's being set */

	maple_clock_write((save_control|RTC_SET), RTC_CONTROL);

	save_freq_select = maple_clock_read(RTC_FREQ_SELECT); /* stop and reset prescaler */

	maple_clock_write((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);

	sec = tm->tm_sec;
	min = tm->tm_min;
	hour = tm->tm_hour;
	mon = tm->tm_mon;
	mday = tm->tm_mday;
	year = tm->tm_year;

	if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
		BIN_TO_BCD(sec);
		BIN_TO_BCD(min);
		BIN_TO_BCD(hour);
		BIN_TO_BCD(mon);
		BIN_TO_BCD(mday);
		BIN_TO_BCD(year);
	}
	maple_clock_write(sec, RTC_SECONDS);
	maple_clock_write(min, RTC_MINUTES);
	maple_clock_write(hour, RTC_HOURS);
	maple_clock_write(mon, RTC_MONTH);
	maple_clock_write(mday, RTC_DAY_OF_MONTH);
	maple_clock_write(year, RTC_YEAR);

	/* The following flags have to be released exactly in this order,
	 * otherwise the DS12887 (popular MC146818A clone with integrated
	 * battery and quartz) will not reset the oscillator and will not
	 * update precisely 500 ms later. You won't find this mentioned in
	 * the Dallas Semiconductor data sheets, but who believes data
	 * sheets anyway ...                           -- Markus Kuhn
	 */
	maple_clock_write(save_control, RTC_CONTROL);
	maple_clock_write(save_freq_select, RTC_FREQ_SELECT);

	spin_unlock(&rtc_lock);

	return 0;
}

static struct resource rtc_iores = {
	.name = "rtc",
	.flags = IORESOURCE_BUSY,
};

unsigned long __init maple_get_boot_time(void)
{
	struct rtc_time tm;
	struct device_node *rtcs;

	rtcs = of_find_compatible_node(NULL, "rtc", "pnpPNP,b00");
	if (rtcs) {
		struct resource r;
		if (of_address_to_resource(rtcs, 0, &r)) {
			printk(KERN_EMERG "Maple: Unable to translate RTC"
			       " address\n");
			goto bail;
		}
		if (!(r.flags & IORESOURCE_IO)) {
			printk(KERN_EMERG "Maple: RTC address isn't PIO!\n");
			goto bail;
		}
		maple_rtc_addr = r.start;
		printk(KERN_INFO "Maple: Found RTC at IO 0x%x\n",
		       maple_rtc_addr);
	}
 bail:
	if (maple_rtc_addr == 0) {
		maple_rtc_addr = RTC_PORT(0); /* legacy address */
		printk(KERN_INFO "Maple: No device node for RTC, assuming "
		       "legacy address (0x%x)\n", maple_rtc_addr);
	}

	rtc_iores.start = maple_rtc_addr;
	rtc_iores.end = maple_rtc_addr + 7;
	request_resource(&ioport_resource, &rtc_iores);

	maple_get_rtc_time(&tm);
	return mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
		      tm.tm_hour, tm.tm_min, tm.tm_sec);
}


text:
#ifndef QT3DLOGIC_QFRAMEACTION_H
#define QT3DLOGIC_QFRAMEACTION_H

#include <Qt3DCore/qcomponent.h>
#include <Qt3DLogic/qt3dlogic_global.h>

QT_BEGIN_NAMESPACE

namespace Qt3DLogic {

class QLogicAspect;
class QFrameActionPrivate;

namespace Logic {
class Executor;
}

class QT3DLOGICSHARED_EXPORT QFrameAction : public Qt3DCore::QComponent
{
    Q_OBJECT

public:
    explicit QFrameAction(Qt3DCore::QNode *parent = nullptr);
    ~QFrameAction();

protected:
    QFrameAction(QFrameActionPrivate &dd, QNode *parent = nullptr);

Q_SIGNALS:
    void triggered(float dt);

private:
    Q_DECLARE_PRIVATE(QFrameAction)
    void onTriggered(float dt);

    friend class Logic::Executor;
};

} // namespace Qt3DLogic

QT_END_NAMESPACE

#endif // QT3DLOGIC_QFRAMEACTION_H


text:
.plan {
    width: 800px;
    margin: 90px auto;
}

.plan label {
    display: block;
}

.plan ul li {
    list-style-type: decimal-leading-zero;
    margin: 10px 20px;
}

.finish {
    text-decoration: line-through;
}

.plan ul li button:first-child {
    margin-left: 50px;
    margin-right: 15px;
}


text:
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"

/* The critical nesting value is initialised to a non zero value to ensure
interrupts don't accidentally become enabled before the scheduler is started. */
#define portINITIAL_CRITICAL_NESTING  ( ( uint16_t ) 10 )

/* Initial PSW value allocated to a newly created task.
 *   11000110
 *   ||||||||-------------- Fill byte
 *   |||||||--------------- Carry Flag cleared
 *   |||||----------------- In-service priority Flags set to low level
 *   ||||------------------ Register bank Select 0 Flag cleared
 *   |||------------------- Auxiliary Carry Flag cleared
 *   ||-------------------- Register bank Select 1 Flag cleared
 *   |--------------------- Zero Flag set
 *   ---------------------- Global Interrupt Flag set (enabled)
 */
#define portPSW		  ( 0xc6UL )

/* Each task maintains a count of the critical section nesting depth.  Each time
a critical section is entered the count is incremented.  Each time a critical
section is exited the count is decremented - with interrupts only being
re-enabled if the count is zero.

usCriticalNesting will get set to zero when the scheduler starts, but must
not be initialised to zero as that could cause problems during the startup
sequence. */
volatile uint16_t usCriticalNesting = portINITIAL_CRITICAL_NESTING;

/*-----------------------------------------------------------*/

/*
 * Sets up the periodic ISR used for the RTOS tick.
 */
__attribute__((weak)) void vApplicationSetupTimerInterrupt( void );

/*
 * Starts the scheduler by loading the context of the first task to run.
 * (defined in portasm.S).
 */
extern void vPortStartFirstTask( void );

/*-----------------------------------------------------------*/

/*
 * Initialise the stack of a task to look exactly as if a call to
 * portSAVE_CONTEXT had been called.
 *
 * See the header file portable.h.
 */
StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
{
uint32_t *pulLocal;

	/* Stack type and pointers to the stack type are both 2 bytes. */

	/* Parameters are passed in on the stack, and written using a 32bit value
	hence a space is left for the second two bytes. */
	pxTopOfStack--;

	/* Write in the parameter value. */
	pulLocal =  ( uint32_t * ) pxTopOfStack;
	*pulLocal = ( StackType_t ) pvParameters;
	pxTopOfStack--;

	/* The return address, leaving space for the first two bytes of	the
	32-bit value. */
	pxTopOfStack--;
	pulLocal = ( uint32_t * ) pxTopOfStack;
	*pulLocal = ( uint32_t ) 0;
	pxTopOfStack--;

	/* The start address / PSW value is also written in as a 32bit value,
	so leave a space for the second two bytes. */
	pxTopOfStack--;

	/* Task function start address combined with the PSW. */
	pulLocal = ( uint32_t * ) pxTopOfStack;
	*pulLocal = ( ( ( uint32_t ) pxCode ) | ( portPSW << 24UL ) );
	pxTopOfStack--;

	/* An initial value for the AX register. */
	*pxTopOfStack = ( StackType_t ) 0x1111;
	pxTopOfStack--;

	/* An initial value for the HL register. */
	*pxTopOfStack = ( StackType_t ) 0x2222;
	pxTopOfStack--;

	/* CS and ES registers. */
	*pxTopOfStack = ( StackType_t ) 0x0F00;
	pxTopOfStack--;

	/* The remaining general purpose registers bank 0 (DE and BC) and the other
	two register banks...register bank 3 is dedicated for use by interrupts so
	is not saved as part of the task context. */
	pxTopOfStack -= 10;

	/* Finally the critical section nesting count is set to zero when the task
	first starts. */
	*pxTopOfStack = ( StackType_t ) portNO_CRITICAL_SECTION_NESTING;

	/* Return a pointer to the top of the stack that has beene generated so it
	can	be stored in the task control block for the task. */
	return pxTopOfStack;
}
/*-----------------------------------------------------------*/

portBASE_TYPE xPortStartScheduler( void )
{
	/* Setup the hardware to generate the tick.  Interrupts are disabled when
	this function is called. */
	vApplicationSetupTimerInterrupt();

	/* Restore the context of the first task that is going to run. */
	vPortStartFirstTask();

	/* Execution should not reach here as the tasks are now running! */
	return pdTRUE;
}
/*-----------------------------------------------------------*/

void vPortEndScheduler( void )
{
	/* It is unlikely that the RL78 port will get stopped. */
}
/*-----------------------------------------------------------*/

__attribute__((weak)) void vApplicationSetupTimerInterrupt( void )
{
const uint16_t usClockHz = 15000UL; /* Internal clock. */
const uint16_t usCompareMatch = ( usClockHz / configTICK_RATE_HZ ) + 1UL;

	/* Use the internal 15K clock. */
	OSMC = ( unsigned char ) 0x16;

	#ifdef RTCEN
	{
		/* Supply the interval timer clock. */
		RTCEN = ( unsigned char ) 1U;

		/* Disable INTIT interrupt. */
		ITMK = ( unsigned char ) 1;

		/* Disable ITMC operation. */
		ITMC = ( unsigned char ) 0x0000;

		/* Clear INIT interrupt. */
		ITIF = ( unsigned char ) 0;

		/* Set interval and enable interrupt operation. */
		ITMC = usCompareMatch | 0x8000U;

		/* Enable INTIT interrupt. */
		ITMK = ( unsigned char ) 0;
	}
	#endif

	#ifdef TMKAEN
	{
		/* Supply the interval timer clock. */
		TMKAEN = ( unsigned char ) 1U;

		/* Disable INTIT interrupt. */
		TMKAMK = ( unsigned char ) 1;

		/* Disable ITMC operation. */
		ITMC = ( unsigned char ) 0x0000;

		/* Clear INIT interrupt. */
		TMKAIF = ( unsigned char ) 0;

		/* Set interval and enable interrupt operation. */
		ITMC = usCompareMatch | 0x8000U;

		/* Enable INTIT interrupt. */
		TMKAMK = ( unsigned char ) 0;
	}
	#endif
}
/*-----------------------------------------------------------*/


text:
require File.expand_path('../spec_helper', __dir__)

module Pod::TrunkApp
  class AppController
    get '/ping' do
      'ok'
    end
  end

  describe AppController do
    test_controller! AppController

    it 'allows https URLs' do
      get 'https://example.org/ping'
      last_response.should.be.ok
    end

    it 'allows forwarded HTTP URLs' do
      get 'http://example.org/ping', {}, 'HTTP_X_FORWARDED_PROTO' => 'https'
      last_response.should.be.ok
    end

    it 'redirects HTTP URLs to HTTPS' do
      get 'http://example.org/ping'
      last_response.should.be.redirect?
      last_response.headers['Location'].should == 'https://example.org/ping'
    end
  end
end


text:
package javax.swing.plaf.basic;

import javax.swing.JComponent;
import javax.swing.UIDefaults;
import javax.swing.plaf.ComponentUI;

/**
 * @since 1.4
 */
public class BasicFormattedTextFieldUI extends BasicTextFieldUI
{
  public BasicFormattedTextFieldUI()
  {
    // Nothing to do here.
  }

  public static ComponentUI createUI(JComponent c)
  {
    return new BasicFormattedTextFieldUI();
  }

  /**
   * Returns the prefix for entries in the {@link UIDefaults} table.
   *
   * @return "FormattedTextField"
   */
  protected String getPropertyPrefix()
  {
    return "FormattedTextField";
  }
}


text:
package feri.mazgon.auction.core;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import feri.mazgon.auction.core.domain.Auction;
import feri.mazgon.auction.core.domain.AuctionCategory;
import feri.mazgon.auction.core.domain.User;
import feri.mazgon.auction.util.Util;

@Transactional
@Service
public class InitService implements ApplicationListener<ContextRefreshedEvent> {
	private static final Logger logger = LoggerFactory.getLogger(InitService.class);
	@Value("${db.init}")
	private Boolean DB_INIT;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		logger.info("---- INIT ----");
		logger.info("DB - " + DB_INIT);

		if (DB_INIT)
			databaseInit();
		startDatabaseAuctions();
	}

	private void startDatabaseAuctions() {
		for (Auction a : new Auction().findAll()) {
			try {
				a.saveAndStart();
			} catch (IllegalStateException e) {}
		}
	}

	private void databaseInit() {
		AuctionCategory ac = new AuctionCategory();
		User u = new User();
		Auction a = new Auction();

		List<AuctionCategory> categories = ac.findAll();
		List<User> users = u.findAll();
		List<Auction> auctions = a.findAll();

		if (categories.size() < 1) {
			logger.info("Create auction categories");

			categories.add(new AuctionCategory("Tehnologija"));
			categories.add(new AuctionCategory("Knjige"));
			categories.add(new AuctionCategory("Oblaèila in obutev"));

			for (AuctionCategory i : categories) {
				i.save();
			}
		}
		if (users.size() < 1) {
			logger.info("Create users");

			users.add(new User("lovro.mazgon@gmail.com", "admin", "Lovro", "Mažgon", true));
			users.add(new User("lovro.mazgon@student.um.si", "admin", "Student", "UM", false));

			for (User i : users) {
				i.save();
			}
		}
		if (auctions.size() < 1) {
			logger.info("Create auctions");

			String[] picturePaths = {"/WEB-INF/initPictures/iphone4s.png", "/WEB-INF/initPictures/jobs.jpg", "/WEB-INF/initPictures/armani.jpeg"};

			auctions.add(new Auction("Apple iPhone 4S", "Apple iPhone 4S v zelo dobrem stanju, star dobro leto.", users.get(0), 12000, 0, 5, Util.readPicture(picturePaths[0]), categories.get(0)));
			auctions.add(new Auction("Walter Isaacson: Steve Jobs", "Knjiga je kot nova. Ima mehke platnice, kupljena 3.7.2013.", users.get(0), 700, 0, 5, Util.readPicture(picturePaths[1]), categories.get(1)));
			auctions.add(new Auction("Usnjena jakna (èrna) - Emporio Armani NOVA", "Jakna ni bila nikoli nošena, velikost je M, moška usnjena jakna. Je zelo kvalitetne izdelave, original Emporio Armani.", users.get(1), 5000, 0, 5, Util.readPicture(picturePaths[2]), categories.get(2)));

			for (Auction i : auctions) {
				i.saveAndStart();
			}
		}
	}
}


text:
package com.intel.analytics.bigdl.torch

import com.intel.analytics.bigdl.nn.CMaxTable
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.RandomGenerator._
import com.intel.analytics.bigdl.utils.Table

import scala.collection.mutable.HashMap
import scala.util.Random

@com.intel.analytics.bigdl.tags.Serial
class CMaxTableSpec extends TorchSpec {
    "A CMaxTable Module" should "generate correct output and grad" in {
    torchCheck()
    val seed = 100
    RNG.setSeed(seed)
    val module = new CMaxTable[Double]()

    val input1 = Tensor[Double](5).apply1(e => Random.nextDouble())
    val input2 = Tensor[Double](5).apply1(e => Random.nextDouble())
    val gradOutput = Tensor[Double](5).apply1(e => Random.nextDouble())
    val input = new Table()
    input(1.toDouble) = input1
    input(2.toDouble) = input2

    val start = System.nanoTime()
    val output = module.forward(input)
    val gradInput = module.backward(input, gradOutput)
    val end = System.nanoTime()
    val scalaTime = end - start

    val code = "torch.manualSeed(" + seed + ")\n" +
      "module = nn.CMaxTable()\n" +
      "output = module:forward(input)\n" +
      "gradInput = module:backward(input,gradOutput)"

    val (luaTime, torchResult) = TH.run(code, Map("input" -> input, "gradOutput" -> gradOutput),
      Array("output", "gradInput"))
    val luaOutput1 = torchResult("output").asInstanceOf[Tensor[Double]]
    val luaOutput2 = torchResult("gradInput").asInstanceOf[Table]

    luaOutput1 should be(output)
    luaOutput2 should be (gradInput)

    println("Test case : CMaxTable, Torch : " + luaTime +
      " s, Scala : " + scalaTime / 1e9 + " s")

  }
}