text:
package com.createsend;

import java.util.Date;

import javax.ws.rs.core.MultivaluedMap;

import com.createsend.models.PagedResult;
import com.createsend.models.lists.CustomField;
import com.createsend.models.lists.CustomFieldForCreate;
import com.createsend.models.lists.CustomFieldForUpdate;
import com.createsend.models.lists.List;
import com.createsend.models.lists.ListForUpdate;
import com.createsend.models.lists.Statistics;
import com.createsend.models.lists.UpdateFieldOptions;
import com.createsend.models.lists.Webhook;
import com.createsend.models.lists.WebhookTestFailureDetails;
import com.createsend.models.segments.Segment;
import com.createsend.models.subscribers.Subscriber;
import com.createsend.util.AuthenticationDetails;
import com.createsend.util.ErrorDeserialiser;
import com.createsend.util.JerseyClientImpl;
import com.createsend.util.exceptions.CreateSendException;
import com.createsend.util.jersey.JsonProvider;
import com.sun.jersey.core.util.MultivaluedMapImpl;

/**
 * Provides methods for accessing all
 * List resources in the Campaign Monitor API *
 */
public class Lists extends CreateSendBase {
    private String listID;

    /**
     * Constructor used to create new lists.
     * @param auth The authentication details to use when making API calls.
     * May be either an OAuthAuthenticationDetails or
     * ApiKeyAuthenticationDetails instance.
     */
    public Lists(AuthenticationDetails auth) {
        this(auth, null);
    }

    /**
     * Constructor for working with existing lists.
     * @param auth The authentication details to use when making API calls.
     * May be either an OAuthAuthenticationDetails or
     * ApiKeyAuthenticationDetails instance.
     * @param listID The List ID to use when making API calls.
     */
    public Lists(AuthenticationDetails auth, String listID) {
        setListID(listID);
        this.jerseyClient = new JerseyClientImpl(auth);
    }

    /**
     * Sets the current list ID.
     * @param listID The ID of the list to apply any calls to.
     */
    public void setListID(String listID) {
        this.listID = listID;
    }

    /**
     * Gets the current list ID.
     * @return The current list ID.
     */
    public String getListID() {
        return listID;
    }

    /**
     * Creates a new empty subscriber list.
     * After a successful call, the current list id property will be set the ID of the
     * newly created list.
     * @param clientID The ID of the client owning the new list
     * @param list The details of the new list
     * @return The ID of the newly created list
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Creating a list
     */
    public String create(String clientID, List list) throws CreateSendException {
        listID = jerseyClient.post(String.class, list, "lists", clientID + ".json");
        return listID;
    }

    /**
     * Updates the basic list details for an existing subscriber list
     * @param list The new basic details for the list
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Updating a list
     */
    public void update(ListForUpdate list) throws CreateSendException {
        jerseyClient.put(list, "lists", listID + ".json");
    }

    /**
     * Deletes the list with the specified ID
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Deleting a list
     */
    public void delete() throws CreateSendException {
        jerseyClient.delete("lists", listID + ".json");
    }

    /**
     * Gets the details of the list with the given ID
     * @return The details of the list with the given ID
     * @throws CreateSendException Raised when the API returns a HTTP Status >= 400
     * @see
     * Getting list details
     */
    public List details() throws CreateSendException {
        return jerseyClient.get(List.class, "lists", listID + ".json");
    }

    /**
     * Gets subscriber statistics for the list with the specified ID
     * @return Subscriber statistics for the list with the specified ID
     * @throws CreateSendException Raised when the API responds with HTTP status >= 400
     * @see
     * Getting list stats
     */
    public Statistics stats() throws CreateSendException {
        return jerseyClient.get(Statistics.class, "lists", listID, "stats.json");
    }

    /**
     * Gets the custom fields available for the list with the specified ID
     * @return The custom fields available for the specified list
     * @throws CreateSendException Raised when the API responds with HTTP Status >= 400
     * @see
     * Getting list custom fields
     */
    public CustomField[] customFields() throws CreateSendException {
        return jerseyClient.get(CustomField[].class, "lists", listID, "customfields.json");
    }

    /**
     * Gets the segments available in the list with the specified ID
     * @return The segments available in the specified list
     * @throws CreateSendException Raised when the API responds with HTTP Status >= 400
     * @see
     * Getting list segments
     */
    public Segment[] segments() throws CreateSendException {
        return jerseyClient.get(Segment[].class, "lists", listID, "segments.json");
    }

    /**
     * Gets a paged collection of active subscribers who have subscribed to the list.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting active subscribers
     */
    public PagedResult<Subscriber> active() throws CreateSendException {
        return active(1, 1000, "email", "asc");
    }

    /**
     * Gets a paged collection of active subscribers who have subscribed to the list.
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting active subscribers
     */
    public PagedResult<Subscriber> active(
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return active("", page, pageSize, orderField, orderDirection);
    }

    /**
     * Gets a paged collection of active subscribers who have subscribed to the list
     * since the provided date.
     * @param subscribedFrom The API will only return subscribers who became active on or after this date.
     *     This field is required
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting active subscribers
     */
    public PagedResult<Subscriber> active(Date subscribedFrom,
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return active(JsonProvider.ApiDateFormat.format(subscribedFrom),
                page, pageSize, orderField, orderDirection);
    }

    private PagedResult<Subscriber> active(String subscribedFrom,
        Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        MultivaluedMap<String, String> queryString = new MultivaluedMapImpl();
        queryString.add("date", subscribedFrom);

        return jerseyClient.getPagedResult(page, pageSize, orderField, orderDirection,
            queryString, "lists", listID, "active.json");
    }

    /**
     * Gets a paged collection of unconfirmed subscribers who have subscribed to the list.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting active subscribers
     */
    public PagedResult<Subscriber> unconfirmed() throws CreateSendException {
        return unconfirmed(1, 1000, "email", "asc");
    }

    /**
     * Gets a paged collection of unconfirmed subscribers who have subscribed to the list.
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting active subscribers
     */
    public PagedResult<Subscriber> unconfirmed(
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return unconfirmed("", page, pageSize, orderField, orderDirection);
    }

    /**
     * Gets a paged collection of unconfirmed subscribers who have subscribed to the list
     * since the provided date.
     * @param subscribedFrom The API will only return subscribers who subscribed on or after this date.
     *     This field is required
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting active subscribers
     */
    public PagedResult<Subscriber> unconfirmed(Date subscribedFrom,
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return unconfirmed(JsonProvider.ApiDateFormat.format(subscribedFrom),
                page, pageSize, orderField, orderDirection);
    }

    private PagedResult<Subscriber> unconfirmed(String subscribedFrom,
        Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        MultivaluedMap<String, String> queryString = new MultivaluedMapImpl();
        queryString.add("date", subscribedFrom);

        return jerseyClient.getPagedResult(page, pageSize, orderField, orderDirection,
            queryString, "lists", listID, "unconfirmed.json");
    }

    /**
     * Gets a paged collection of unsubscribed subscribers who have unsubscribed from the list.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting unsubscribed subscribers
     */
    public PagedResult<Subscriber> unsubscribed() throws CreateSendException {
        return unsubscribed(1, 1000, "email", "asc");
    }

    /**
     * Gets a paged collection of unsubscribed subscribers who have unsubscribed from the list.
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting unsubscribed subscribers
     */
    public PagedResult<Subscriber> unsubscribed(
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return unsubscribed("", page, pageSize, orderField, orderDirection);
    }

    /**
     * Gets a paged collection of unsubscribed subscribers who have unsubscribed from the list
     * since the provided date.
     * @param subscribedFrom The API will only return subscribers who unsubscribed on or after this date.
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting unsubscribed subscribers
     */
    public PagedResult<Subscriber> unsubscribed(Date subscribedFrom,
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return unsubscribed(JsonProvider.ApiDateFormat.format(subscribedFrom),
                page, pageSize, orderField, orderDirection);
    }

    private PagedResult<Subscriber> unsubscribed(String subscribedFrom,
        Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        MultivaluedMap<String, String> queryString = new MultivaluedMapImpl();
        queryString.add("date", subscribedFrom);

        return jerseyClient.getPagedResult(page, pageSize, orderField, orderDirection,
            queryString, "lists", listID, "unsubscribed.json");
    }

    /**
     * Gets a paged collection of subscribers who have been deleted from the list.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting deleted subscribers
     */
    public PagedResult<Subscriber> deleted() throws CreateSendException {
        return deleted(1, 1000, "email", "asc");
    }

    /**
     * Gets a paged collection of subscribers who have been deleted from the list.
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting deleted subscribers
     */
    public PagedResult<Subscriber> deleted(
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return deleted("", page, pageSize, orderField, orderDirection);
    }

    /**
     * Gets a paged collection of subscribers who have been deleted from the list
     * since the provided date.
     * @param subscribedFrom The API will only return subscribers who were deleted on or after this date.
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting deleted subscribers
     */
    public PagedResult<Subscriber> deleted(Date subscribedFrom,
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return deleted(JsonProvider.ApiDateFormat.format(subscribedFrom),
                page, pageSize, orderField, orderDirection);
    }

    private PagedResult<Subscriber> deleted(String subscribedFrom,
        Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        MultivaluedMap<String, String> queryString = new MultivaluedMapImpl();
        queryString.add("date", subscribedFrom);

        return jerseyClient.getPagedResult(page, pageSize, orderField, orderDirection,
            queryString, "lists", listID, "deleted.json");
    }

    /**
     * Gets a paged collection of bounced subscribers who have bounced out of the list.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting bounced subscribers
     */
    public PagedResult<Subscriber> bounced() throws CreateSendException {
        return bounced(1, 1000, "email", "asc");
    }

    /**
     * Gets a paged collection of bounced subscribers who have bounced out of the list.
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting bounced subscribers
     */
    public PagedResult<Subscriber> bounced(
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return bounced("", page, pageSize, orderField, orderDirection);
    }

    /**
     * Gets a paged collection of bounced subscribers who have bounced out of the list
     * since the provided date.
     * @param subscribedFrom The API will only return subscribers who bounced out on or after this date.
     * @param page The page number or results to get. Use null for the default (page=1)
     * @param pageSize The number of records to get on the current page. Use null for the default.
     * @param orderField The field used to order the results by. Use null for the default.
     * @param orderDirection The direction to order the results by. Use null for the default.
     * @return The paged subscribers returned by the api call.
     * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400
     * @see
     * Getting bounced subscribers
     */
    public PagedResult<Subscriber> bounced(Date subscribedFrom,
            Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        return bounced(JsonProvider.ApiDateFormat.format(subscribedFrom),
                page, pageSize, orderField, orderDirection);
    }

    private PagedResult<Subscriber> bounced(String subscribedFrom,
        Integer page, Integer pageSize, String orderField, String orderDirection) throws CreateSendException {
        MultivaluedMap<String, String> queryString = new MultivaluedMapImpl();
        queryString.add("date", subscribedFrom);

        return jerseyClient.getPagedResult(page, pageSize, orderField, orderDirection,
            queryString, "lists", listID, "bounced.json");
    }

    /**
     * Creates a new custom field with the specified data
     * @param customField The custom field options
     * @return The Key of the newly created custom field
     * @throws CreateSendException Thrown when the API responds with HTTP Status >= 400
     * @see
     * Creating a custom field
     */
    public String createCustomField(CustomFieldForCreate customField) throws CreateSendException {
        return jerseyClient.post(String.class, customField, "lists", listID, "customfields.json");
    }

    /**
     * Updates a new custom field.
     * @param fieldKey The Key of the custom field to update. This must be surrounded by [].
     * @param customField The custom field options
     * @return The Key of the updated custom field
     * @throws CreateSendException Thrown when the API responds with HTTP Status >= 400
     * @see
     * Creating a custom field
     */
    public String updateCustomField(String fieldKey, CustomFieldForUpdate customField)
        throws CreateSendException {
        return jerseyClient.put(String.class, customField, "lists", listID, "customfields", fieldKey + ".json");
    }

    /**
     * Updates the available options for a Multi-Valued custom field.
     * @param fieldKey The Key of the custom field to update. This must be surrounded by [].
     * @param options The new options to use for the field.
     * @throws CreateSendException Raised when the API responds with HTTP Status >= 400
     * @see
     * Updating custom field options
     */
    public void updateCustomFieldOptions(String fieldKey, UpdateFieldOptions options)
        throws CreateSendException {
        jerseyClient.put(options, "lists", listID, "customFields", fieldKey, "options.json");
    }

    /**
     * Deletes the custom field with the specified key
     * @param fieldKey The Key of the custom field to delete. This must be surrounded by [].
     * @throws CreateSendException Thrown when the API responds with HTTP Status >= 400
     * @see
     * Deleting a custom field
     */
    public void deleteCustomField(String fieldKey) throws CreateSendException {
        jerseyClient.delete("lists", listID, "customFields", fieldKey + ".json");
    }

    /**
     * Gets all webhooks which have been attached to events on the specified list
     * @return The webhooks which have been attached to events for the specified list
     * @throws CreateSendException Thrown when the API responds with HTTP Status >= 400
     * @see
     * Getting list webhooks
     */
    public Webhook[] webhooks() throws CreateSendException {
        return jerseyClient.get(Webhook[].class, "lists", listID, "webhooks.json");
    }

    /**
     * Creates a new webhook on the specified list.
     * @param webhook The webhook details
     * @return The ID of the newly created webhook
     * @throws CreateSendException Thrown when the API responds with HTTP Status >= 400
     * @see
     * Creating a webhook
     */
    public String createWebhook(Webhook webhook) throws CreateSendException {
        return jerseyClient.post(String.class, webhook, "lists", listID, "webhooks.json");
    }

    /**
     * Tests the specified webhook
     * @param webhookID The ID of the webhook
     * @throws CreateSendException Thrown when the API responds with HTTP Status >= 400. I.e the test fails
     * @see
     * Testing a webhook
     */
    public void testWebhook(String webhookID) throws CreateSendException {
        jerseyClient.get(String.class, new ErrorDeserialiser<WebhookTestFailureDetails>(){},
            "lists", listID, "webhooks", webhookID, "test.json");
    }

    /**
     * Deletes the specified webhook
     * @param webhookID The ID of the webhook to delete
     * @throws CreateSendException Raised when the API responds with HTTP Status >= 400
     * @see
     * Deleting a webhook
     */
    public void deleteWebhook(String webhookID) throws CreateSendException {
        jerseyClient.delete("lists", listID, "webhooks", webhookID + ".json");
    }

    /**
     * Activates the specified webhook.
     * @param webhookID The ID of the webhook to activate
     * @throws CreateSendException Thrown when the API responds with HTTP Status >= 400
     * @see
     * Activating a webhook
     */
    public void activateWebhook(String webhookID) throws CreateSendException {
        jerseyClient.put("", "lists", listID, "webhooks", webhookID, "activate.json");
    }

    /**
     * Deactivates the specified webhook.
     * @param webhookID The ID of the webhook to deactivate
     * @throws CreateSendException Thrown when the API responds with HTTP Status >= 400
     * @see
     * Activating a webhook
     */
    public void deactivateWebhook(String webhookID) throws CreateSendException {
        jerseyClient.put("", "lists", listID, "webhooks", webhookID, "activate.json");
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.xpack.textstructure.structurefinder;

public class LogTextStructureFinderFactoryTests extends TextStructureTestCase {

    private final TextStructureFinderFactory factory = new LogTextStructureFinderFactory();

    // No need to check NDJSON, XML, CSV, TSV, semi-colon delimited values or pipe
    // delimited values because they come earlier in the order we check formats

    public void testCanCreateFromSampleGivenText() {

        assertTrue(factory.canCreateFromSample(explanation, TEXT_SAMPLE, 0.0));
    }
}


text:
package es.bsc.compss.util.test;

import static org.junit.Assert.assertEquals;

import es.bsc.compss.util.EnvironmentLoader;

import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;

/**
 * Tests the different possibilities of loading a environment variable.
 */
public class EnvironmentLoaderTest {

    private static final String VALUE1 = "1";
    private static final String VALUE2 = "2";
    private static final String PATH1 = "/tmp/";
    private static final String PATH2 = "try/";

    @ClassRule
    public static final EnvironmentVariables ENVIRONMENT_VARIABLES = new EnvironmentVariables();

    /**
     * Setup environment before tests execution.
     *
     * @throws Exception Error when environment cannot be setup.
     */
    @Before
    public void setUp() throws Exception {
        ENVIRONMENT_VARIABLES.set("var", VALUE1);
        ENVIRONMENT_VARIABLES.set("var1", VALUE1);
        ENVIRONMENT_VARIABLES.set("var2", VALUE2);
    }

    @Test
    public void noEnv() {
        String expression = "1";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, VALUE1);
    }

    @Test
    public void simpleEnv1() {
        String expression = "$var";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, VALUE1);
    }

    @Test
    public void simpleEnv2() {
        String expression = "${var}";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, VALUE1);
    }

    @Test
    public void complexEnv1() {
        String expression = "$var/tmp/try/";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, VALUE1 + PATH1 + PATH2);
    }

    @Test
    public void complexEnv2() {
        String expression = "${var}/tmp/try/";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, VALUE1 + PATH1 + PATH2);
    }

    @Test
    public void complexEnv3() {
        String expression = "/tmp/try/$var";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + PATH2 + VALUE1);
    }

    @Test
    public void complexEnv4() {
        String expression = "/tmp/try/${var}";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + PATH2 + VALUE1);
    }

    @Test
    public void complexEnv5() {
        String expression = "/tmp/$var/try/";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + VALUE1 + "/" + PATH2);
    }

    @Test
    public void complexEnv6() {
        String expression = "/tmp/${var}/try/";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + VALUE1 + "/" + PATH2);
    }

    @Test
    public void doubleEnv1() {
        String expression = "/tmp/$var1/$var2/try/";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + VALUE1 + "/" + VALUE2 + "/" + PATH2);
    }

    @Test
    public void doubleEnv2() {
        String expression = "/tmp/${var1}/$var2/try/";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + VALUE1 + "/" + VALUE2 + "/" + PATH2);
    }

    @Test
    public void doubleEnv3() {
        String expression = "/tmp/${var1}/${var2}/try/";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + VALUE1 + "/" + VALUE2 + "/" + PATH2);
    }

    @Test
    public void doubleEnv4() {
        String expression = "$var1/${var2}";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, VALUE1 + "/" + VALUE2);
    }

    @Test
    public void doubleEnv5() {
        String expression = "${var1}/$var2";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, VALUE1 + "/" + VALUE2);
    }

    @Test
    public void scapedEnvVar1() {
        String expression = "\\${var}";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, "${var}");
    }

    @Test
    public void scapedEnvVar2() {
        String expression = "\\$var";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, "$var");
    }

    @Test
    public void scapedEnvVar3() {
        String expression = "/tmp/\\${var}";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + "${var}");
    }

    @Test
    public void scapedEnvVar4() {
        String expression = "/tmp/${var1}/\\${var}/$var2";
        String expressionValue = EnvironmentLoader.loadFromEnvironment(expression);

        assertEquals(expressionValue, PATH1 + VALUE1 + "/${var}/" + VALUE2);
    }

}


text:
{-# LANGUAGE FlexibleContexts #-} -- for Pretty (V t nt)
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Cfg.LeftRecursion(
    LR(..),
    SCComp(..),
    isLeftRecursive,
    removeLeftRecursion,
    removeLeftRecursionBounded,
    reportLeftRec) where

import Control.Monad(guard)
import Data.Cfg.Cfg
import Data.Cfg.CycleRemoval(SCComp(..))
import qualified Data.Cfg.CycleRemoval as CR
import Data.Cfg.FreeCfg(FreeCfg, bimapCfg)
import Data.Cfg.Item
import Data.List(partition)
import Data.Cfg.LeftRecursion.Cycles
import Data.Cfg.Pretty
import Data.Graph.Inductive.PatriciaTree
import Data.Graph.Inductive.ULGraph hiding (empty)
import qualified Data.Map as M
import qualified Data.Set as S
import Text.PrettyPrint

-- | Nonterminal wrapper to introduce symbols for tails of directly
-- recursive productions.
data LR nt = LR nt      -- ^ wrapped original symbols
           | LRTail nt  -- ^ tail symbols
    deriving (Eq, Ord, Show)

-- | Is the grammar left-recursive?
isLeftRecursive :: (Cfg cfg t nt, Ord nt, Ord t) => cfg t nt -> Bool
isLeftRecursive cfg = case S.toList $ lrSccs cfg of
                         SCComp _ : _ -> True
                         SelfLoop _ _ : _ -> True
                         _ -> False

-- | An equivalent grammar without left-recursion.
removeLeftRecursion :: forall cfg nt t
                    . (Cfg cfg t nt, Ord nt, Ord t)
                    => cfg t nt -> FreeCfg t (LR nt)
removeLeftRecursion cfg
    = CR.removeCycles' indirect direct (S.toList $ lrSccs cfg') cfg'
    where
    cfg' :: FreeCfg t (LR nt)
    cfg' = bimapCfg id LR cfg

    indirect :: LR nt -> LR nt -> ProductionMap t (LR nt)
                               -> ProductionMap t (LR nt)
    indirect src dst pm = if null rec'
                              then pm
                              else M.insert src (S.fromList newSrcRhss) pm
        where
        srcRhss :: [Vs t (LR nt)]
        srcRhss = S.toList $ pm M.! src

        (rec', nonrec) = partition isRec srcRhss
            where
            isRec :: Vs t (LR nt) -> Bool
            isRec rhs = case rhs of
                            NT (LR nt) : _ -> dst == LR nt
                            _ -> False

        dstRhss :: [Vs t (LR nt)]
        dstRhss = S.toList $ pm M.! dst

        newSrcRhss :: [Vs t (LR nt)]
        newSrcRhss = nonrec ++ newRec
            where
            newRec = do
                srcRhs <- rec'
                dstRhs <- dstRhss
                return (dstRhs ++ tail srcRhs)

    direct :: LR nt -> ProductionMap t (LR nt) -> ProductionMap t (LR nt)
    direct (LRTail _) _ = error "removeLeftRecursion.direct: saw LRTail"
    direct (LR nt) pm = if null rec'
                            then pm
                            else newPM `M.union` pm
        where
        rhss = S.toList $ pm M.! LR nt
        (rec', nonrec) = partition isRec rhss
            where
            isRec rhs = case rhs of
                            NT (LR nt') : _ -> nt == nt'
                            _ -> False

        newNTRhss = S.fromList $ map f nonrec
            where
            f rhs = rhs ++ [NT $ LRTail nt]
        newNTTailRhss = S.fromList ([] : map f rec')
            where
            f rhs = tail rhs ++ [NT $ LRTail nt]

        newPM :: ProductionMap t (LR nt)
        newPM = M.fromList [(LR nt, newNTRhss),
                            (LRTail nt, newNTTailRhss)]

-- | An equivalent grammar without left-recursion, if the number of
-- productions does not exceed the given limit.
removeLeftRecursionBounded :: forall cfg nt t
                           . (Cfg cfg t nt, Ord nt, Ord t)
                           => Int -> cfg t nt -> Maybe (FreeCfg t (LR nt))
removeLeftRecursionBounded maxSize cfg
    = CR.removeCyclesM' indirectM directM (S.toList $ lrSccs cfg') cfg'
    where
    cfg' :: FreeCfg t (LR nt)
    cfg' = bimapCfg id LR cfg

    pmSize :: ProductionMap t (LR nt) -> Int
    pmSize = sum . map S.size . M.elems

    checkSize :: ProductionMap t (LR nt) -> Maybe (ProductionMap t (LR nt))
    checkSize pm = do
        guard (pmSize pm > maxSize)
        return pm

    indirectM :: LR nt -> LR nt -> ProductionMap t (LR nt)
                                -> Maybe (ProductionMap t (LR nt))
    indirectM src dst pm = checkSize $ indirect src dst pm

    directM :: LR nt -> ProductionMap t (LR nt)
                     -> Maybe (ProductionMap t (LR nt))
    directM nt pm = checkSize $ direct nt pm

    indirect :: LR nt -> LR nt -> ProductionMap t (LR nt)
                               -> ProductionMap t (LR nt)
    indirect src dst pm = if null rec'
                              then pm
                              else M.insert src (S.fromList newSrcRhss) pm
        where
        srcRhss :: [Vs t (LR nt)]
        srcRhss = S.toList $ pm M.! src

        (rec', nonrec) = partition isRec srcRhss
            where
            isRec :: Vs t (LR nt) -> Bool
            isRec rhs = case rhs of
                            NT (LR nt) : _ -> dst == LR nt
                            _ -> False

        dstRhss :: [Vs t (LR nt)]
        dstRhss = S.toList $ pm M.! dst

        newSrcRhss :: [Vs t (LR nt)]
        newSrcRhss = nonrec ++ newRec
            where
            newRec = do
                srcRhs <- rec'
                dstRhs <- dstRhss
                return (dstRhs ++ tail srcRhs)

    direct :: LR nt -> ProductionMap t (LR nt) -> ProductionMap t (LR nt)
    direct (LRTail _) _ = error "removeLeftRecursion.direct: saw LRTail"
    direct (LR nt) pm = if null rec'
                            then pm
                            else newPM `M.union` pm
        where
        rhss = S.toList $ pm M.! LR nt
        (rec', nonrec) = partition isRec rhss
            where
            isRec rhs = case rhs of
                            NT (LR nt') : _ -> nt == nt'
                            _ -> False

        newNTRhss = S.fromList $ map f nonrec
            where
            f rhs = rhs ++ [NT $ LRTail nt]
        newNTTailRhss = S.fromList ([] : map f rec')
            where
            f rhs = tail rhs ++ [NT $ LRTail nt]

        newPM :: ProductionMap t (LR nt)
        newPM = M.fromList [(LR nt, newNTRhss),
                            (LRTail nt, newNTTailRhss)]

------------------------------------------------------------

-- | Produces a pretty-printed report giving the left-recursion of the
-- grammar.
reportLeftRec :: forall cfg t nt
              . (Cfg cfg t nt, Ord nt, Ord t,
                  Pretty (V t nt), Pretty (Item t nt))
              => cfg t nt
              -> Doc
reportLeftRec = vcat . map f . S.toList . lrSccs
    where
    prettyNT = pretty . (NT :: nt -> V t nt)

    f :: SCComp Gr nt (Item t nt) -> Doc
    f (Singleton _) = empty
    f (SelfLoop n es) = text "direct left-recursion on" <+> prettyNT n <+> text "via"
                            $$ nest 4 items'
        where
        items' = vcat [pretty e | e <- S.toList es]
    f (SCComp gr) = text "indirect left-recursion on" <+> hsep (map prettyNT ns)
                        $$ nest 4 es'
        where
        ns = S.toList $ nodes gr
        es = edges gr
        es' = vcat $ map g es
        g :: Edge nt (Item t nt) -> Doc
        g (src, dst, item) = hsep [prettyNT src,
                                   arrow,
                                   pretty item,
                                   arrow,
                                   prettyNT dst]
        arrow = text "->"


text:
/* @flow */
import type { SJSymbolInstanceLayer } from '../types';

const data : SJSymbolInstanceLayer = {
   "_class": "symbolInstance",
   "do_objectID": "999610FD-741D-4483-96A3-D494D922D963",
   "exportOptions": {
     "_class": "exportOptions",
     "exportFormats": [],
     "includedLayerIds": [],
     "layerOptions": 0,
     "shouldTrim": false
   },
   "frame": {
     "_class": "rect",
     "constrainProportions": false,
     "height": 96,
     "width": 96,
     "x": 4,
     "y": 4
   },
   "isFlippedHorizontal": false,
   "isFlippedVertical": false,
   "isLocked": false,
   "isVisible": true,
   "layerListExpandedType": 0,
   "name": "Swatch Haus",
   "nameIsFixed": false,
   "resizingType": 0,
   "rotation": 0,
   "shouldBreakMaskChain": false,
   "style": {
     "_class": "style",
     "endDecorationType": 0,
     "miterLimit": 10,
     "startDecorationType": 0
   },
   "horizontalSpacing": 0,
   "masterInfluenceEdgeMaxXPadding": 0,
   "masterInfluenceEdgeMaxYPadding": 0,
   "masterInfluenceEdgeMinXPadding": 0,
   "masterInfluenceEdgeMinYPadding": 0,
   "symbolID": "B053267D-9749-4E0C-AD18-7B6B2713EC3B",
   "verticalSpacing": 0
 }


text:
package com.psddev.dari.util;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MarkerIgnoringBase;
import org.slf4j.helpers.MessageFormatter;

/**
 * {@linkplain org.slf4j.Logger SLF4J logger} implementation that saves
 * the logs into a single string.
 *
 * @deprecated No replacement.
 */
@Deprecated
@SuppressWarnings("serial")
public class StringLogger extends MarkerIgnoringBase {

    public static final String DEBUG_LEVEL = "DEBUG";
    public static final String ERROR_LEVEL = "ERROR";
    public static final String INFO_LEVEL = "INFO";
    public static final String TRACE_LEVEL = "TRACE";
    public static final String WARN_LEVEL = "WARN";

    private PrintWriter printWriter;
    private StringWriter stringWriter;
    private long startTime;

    /** Creates a new instance. */
    public StringLogger() {
        reset();
    }

    /** Resets this logger to its initial state. */
    public void reset() {
        stringWriter = new StringWriter();
        printWriter = new PrintWriter(stringWriter);
        startTime = System.currentTimeMillis();
    }

    private void log(String level, String message, Throwable throwable) {

        printWriter.print(System.currentTimeMillis() - startTime);

        printWriter.print(" [");
        printWriter.print(Thread.currentThread().getName());
        printWriter.print("] ");

        printWriter.print(level);
        printWriter.print(" - ");

        printWriter.println(message);

        if (throwable != null) {
            throwable.printStackTrace(printWriter);
        }
    }

    private void log(String level, FormattingTuple tuple) {
        log(level, tuple.getMessage(), tuple.getThrowable());
    }

    // --- MarkerIgnoringBase support ---

    @Override
    public void debug(String msg) {
        log(DEBUG_LEVEL, msg, null);
    }

    @Override
    public void debug(String format, Object arg) {
        log(DEBUG_LEVEL, MessageFormatter.format(format, arg));
    }

    @Override
    public void debug(String format, Object[] argArray) {
        log(DEBUG_LEVEL, MessageFormatter.format(format, argArray));
    }

    @Override
    public void debug(String format, Object arg1, Object arg2) {
        log(DEBUG_LEVEL, MessageFormatter.format(format, arg1, arg2));
    }

    @Override
    public void debug(String msg, Throwable t) {
        log(DEBUG_LEVEL, msg, t);
    }

    @Override
    public void error(String msg) {
        log(ERROR_LEVEL, msg, null);
    }

    @Override
    public void error(String format, Object arg) {
        log(ERROR_LEVEL, MessageFormatter.format(format, arg));
    }

    @Override
    public void error(String format, Object[] argArray) {
        log(ERROR_LEVEL, MessageFormatter.format(format, argArray));
    }

    @Override
    public void error(String format, Object arg1, Object arg2) {
        log(ERROR_LEVEL, MessageFormatter.format(format, arg1, arg2));
    }

    @Override
    public void error(String msg, Throwable t) {
        log(ERROR_LEVEL, msg, t);
    }

    @Override
    public String getName() {
        return null;
    }

    @Override
    public void info(String msg) {
        log(INFO_LEVEL, msg, null);
    }

    @Override
    public void info(String format, Object arg) {
        log(INFO_LEVEL, MessageFormatter.format(format, arg));
    }

    @Override
    public void info(String format, Object[] argArray) {
        log(INFO_LEVEL, MessageFormatter.format(format, argArray));
    }

    @Override
    public void info(String format, Object arg1, Object arg2) {
        log(INFO_LEVEL, MessageFormatter.format(format, arg1, arg2));
    }

    @Override
    public void info(String msg, Throwable t) {
        log(INFO_LEVEL, msg, t);
    }

    @Override
    public boolean isDebugEnabled() {
        return true;
    }

    @Override
    public boolean isErrorEnabled() {
        return true;
    }

    @Override
    public boolean isInfoEnabled() {
        return true;
    }

    @Override
    public boolean isTraceEnabled() {
        return true;
    }

    @Override
    public boolean isWarnEnabled() {
        return true;
    }

    @Override
    public void trace(String msg) {
        log(TRACE_LEVEL, msg, null);
    }

    @Override
    public void trace(String format, Object arg) {
        log(TRACE_LEVEL, MessageFormatter.format(format, arg));
    }

    @Override
    public void trace(String format, Object[] argArray) {
        log(TRACE_LEVEL, MessageFormatter.format(format, argArray));
    }

    @Override
    public void trace(String format, Object arg1, Object arg2) {
        log(TRACE_LEVEL, MessageFormatter.format(format, arg1, arg2));
    }

    @Override
    public void trace(String msg, Throwable t) {
        log(TRACE_LEVEL, msg, t);
    }

    @Override
    public void warn(String msg) {
        log(WARN_LEVEL, msg, null);
    }

    @Override
    public void warn(String format, Object arg) {
        log(WARN_LEVEL, MessageFormatter.format(format, arg));
    }

    @Override
    public void warn(String format, Object[] argArray) {
        log(WARN_LEVEL, MessageFormatter.format(format, argArray));
    }

    @Override
    public void warn(String format, Object arg1, Object arg2) {
        log(WARN_LEVEL, MessageFormatter.format(format, arg1, arg2));
    }

    @Override
    public void warn(String msg, Throwable t) {
        log(WARN_LEVEL, msg, t);
    }

    // --- Object support ---

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


text:
-- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Host: localhost:3306
-- Generation Time: Nov 06, 2017 alle 12:25
-- Versione del server: 5.6.21-log
-- PHP Version: 5.4.24

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `bean_db`
--

--
-- Struttura della tabella `multiple_pk`
--

CREATE TABLE IF NOT EXISTS `multiple_pk` (
  `id_int` int(11) NOT NULL,
  `id_date` date NOT NULL,
  `id_string` varchar(20) NOT NULL,
  `field_string` varchar(200) DEFAULT NULL COMMENT 'nessuna',
  `field_date` date DEFAULT NULL COMMENT 'ssss',
  `field_date_time` datetime DEFAULT NULL,
  `field_decimal` decimal(11,2) DEFAULT NULL,
  `field_int` int(11) DEFAULT NULL,
  `field_text` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dump dei dati per la tabella `multiple_pk`
--

INSERT INTO `multiple_pk` (`id_int`, `id_date`, `id_string`, `field_string`, `field_date`, `field_date_time`, `field_decimal`, `field_int`, `field_text`) VALUES
(1, '2016-11-16', 'sa', NULL, NULL, '2016-11-20 05:04:00', '86.10', 3, 'pippo'),
(1, '2016-11-30', 'sa', 'Field string ok', '2016-11-30', '2016-11-02 10:10:00', '1.54', 1, 'Field text modificato'),
(200, '2017-01-01', 'codice', 'se', '2017-01-19', '2017-01-20 02:04:00', '4.40', 6, 'demo');

-- --------------------------------------------------------

--
-- Struttura della tabella `single_pk_date`
--

CREATE TABLE IF NOT EXISTS `single_pk_date` (
  `id_date` date NOT NULL DEFAULT '0000-00-00',
  `field_string` varchar(200) DEFAULT NULL,
  `field_date` date DEFAULT NULL,
  `field_date_time` datetime DEFAULT NULL,
  `field_decimal` decimal(11,2) DEFAULT NULL,
  `field_int` int(11) DEFAULT NULL,
  `field_text` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dump dei dati per la tabella `single_pk_date`
--

INSERT INTO `single_pk_date` (`id_date`, `field_string`, `field_date`, `field_date_time`, `field_decimal`, `field_int`, `field_text`) VALUES
('2017-11-01', 'Field 1', '2017-11-16', '2017-11-23 00:00:00', '1.10', 1, 'Text àèìòù'),
('2017-12-01', 'Field 2', '2017-12-16', '2017-12-23 00:00:00', '2.10', 2, 'Text àèìòù');

-- --------------------------------------------------------

--
-- Struttura della tabella `single_pk_date_time`
--

CREATE TABLE IF NOT EXISTS `single_pk_date_time` (
  `id_date_time` datetime NOT NULL,
  `field_string` varchar(200) DEFAULT NULL,
  `field_date` date DEFAULT NULL,
  `field_date_time` datetime DEFAULT NULL,
  `field_decimal` decimal(12,2) DEFAULT NULL,
  `field_int` int(11) DEFAULT NULL,
  `field_text` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dump dei dati per la tabella `single_pk_date_time`
--

INSERT INTO `single_pk_date_time` (`id_date_time`, `field_string`, `field_date`, `field_date_time`, `field_decimal`, `field_int`, `field_text`) VALUES
('2017-11-01 00:00:00', 'single pk date time 1', '2017-11-02', '2017-11-17 14:38:40', '1.10', 1, 'Text with accent àèìòù'),
('2017-11-24 00:00:00', 'another field', '2017-11-23', '2017-11-17 00:00:00', NULL, NULL, NULL);

-- --------------------------------------------------------

--
-- Struttura della tabella `single_pk_decimal`
--

CREATE TABLE IF NOT EXISTS `single_pk_decimal` (
  `field_decimal` decimal(10,0) NOT NULL,
  `fiield_string` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 PACK_KEYS=0;

--
-- Dump dei dati per la tabella `single_pk_decimal`
--

INSERT INTO `single_pk_decimal` (`field_decimal`, `fiield_string`) VALUES
('1', 'sa');

-- --------------------------------------------------------

--
-- Struttura della tabella `single_pk_float`
--

CREATE TABLE IF NOT EXISTS `single_pk_float` (
  `field_float` float NOT NULL,
  `field_string` varchar(20) DEFAULT NULL,
  `field_text` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8 PACK_KEYS=0;

--
-- Dump dei dati per la tabella `single_pk_float`
--

INSERT INTO `single_pk_float` (`field_float`, `field_string`, `field_text`) VALUES
(1.6, 'float demo 1', 'Text'),
(1.7, 'float demo 2', 'Text'),
(1.8, 'float demo 3', 'Text');

-- --------------------------------------------------------

--
-- Struttura della tabella `single_pk_int`
--

CREATE TABLE IF NOT EXISTS `single_pk_int` (
  `id_int` int(11) NOT NULL,
  `field_string` varchar(200) DEFAULT NULL,
  `field_date` date DEFAULT NULL,
  `field_date_time` datetime DEFAULT NULL,
  `field_decimal` decimal(11,2) DEFAULT NULL,
  `field_int` int(11) DEFAULT NULL,
  `field_text` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dump dei dati per la tabella `single_pk_int`
--

INSERT INTO `single_pk_int` (`id_int`, `field_string`, `field_date`, `field_date_time`, `field_decimal`, `field_int`, `field_text`) VALUES
(1, 'field string 1', '2017-11-16', '2017-11-15 13:20:23', '1.13', 1, 'Text with accent: àèìòù Teet with accent: àèìòù Text with accent: àèìòù'),
(2, 'field string 2', '2017-11-16', '2017-11-15 13:20:23', '1.13', 1, 'Text with accent: àèìòù Teet with accent: àèìòù Text with accent: àèìòù');

-- --------------------------------------------------------

--
-- Struttura della tabella `single_pk_int_auto`
--

CREATE TABLE IF NOT EXISTS `single_pk_int_auto` (
`id_int_auto` int(11) NOT NULL,
  `field_string` varchar(200) DEFAULT NULL,
  `field_date` date DEFAULT NULL,
  `field_date_time` datetime DEFAULT NULL,
  `field_decimal` decimal(12,2) DEFAULT NULL,
  `field_int` int(11) DEFAULT NULL,
  `field_text` text
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

--
-- Dump dei dati per la tabella `single_pk_int_auto`
--

INSERT INTO `single_pk_int_auto` (`id_int_auto`, `field_string`, `field_date`, `field_date_time`, `field_decimal`, `field_int`, `field_text`) VALUES
(1, 'string field 1', '2017-11-01', '2017-11-01 08:23:27', '450.13', 80373636, 'Text here'),
(2, 'string field 2', '2017-11-22', '2017-11-21 07:44:22', '1.56', 1, 'Lorem ipsum à è ì'),
(3, 'string field 3', '2017-11-02', '2017-11-15 09:30:28', '10.52', 89, 'Demo text');

-- --------------------------------------------------------

--
-- Struttura della tabella `single_pk_string`
--

CREATE TABLE IF NOT EXISTS `single_pk_string` (
  `id_string` varchar(20) NOT NULL,
  `field_string` varchar(200) DEFAULT NULL,
  `field_date` date DEFAULT NULL,
  `field_date_time` datetime DEFAULT NULL,
  `field_decimal` decimal(11,2) DEFAULT NULL,
  `field_int` int(11) DEFAULT NULL,
  `field_text` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dump dei dati per la tabella `single_pk_string`
--

INSERT INTO `single_pk_string` (`id_string`, `field_string`, `field_date`, `field_date_time`, `field_decimal`, `field_int`, `field_text`) VALUES
('the string 1', 'the string field 1', '2017-11-01', '2017-11-02 07:22:21', '1.25', 1, 'The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field '),
('the string 2', 'the string field 2', '2017-11-01', '2017-11-02 07:22:21', '1.25', 1, 'The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field The text field ');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `acl_actions`
--
ALTER TABLE `acl_actions`
 ADD PRIMARY KEY (`id`), ADD KEY `idx_aclaction_id_del` (`id`,`deleted`), ADD KEY `idx_category_name` (`category`,`name`);

--
-- Indexes for table `multiple_pk`
--
ALTER TABLE `multiple_pk`
 ADD PRIMARY KEY (`id_int`,`id_date`,`id_string`);

--
-- Indexes for table `single_pk_date`
--
ALTER TABLE `single_pk_date`
 ADD PRIMARY KEY (`id_date`) USING BTREE;

--
-- Indexes for table `single_pk_date_time`
--
ALTER TABLE `single_pk_date_time`
 ADD PRIMARY KEY (`id_date_time`) USING BTREE;

--
-- Indexes for table `single_pk_decimal`
--
ALTER TABLE `single_pk_decimal`
 ADD PRIMARY KEY (`field_decimal`);

--
-- Indexes for table `single_pk_float`
--
ALTER TABLE `single_pk_float`
 ADD PRIMARY KEY (`field_float`);

--
-- Indexes for table `single_pk_int`
--
ALTER TABLE `single_pk_int`
 ADD PRIMARY KEY (`id_int`) USING BTREE;

--
-- Indexes for table `single_pk_int_auto`
--
ALTER TABLE `single_pk_int_auto`
 ADD PRIMARY KEY (`id_int_auto`) USING BTREE;

--
-- Indexes for table `single_pk_string`
--
ALTER TABLE `single_pk_string`
 ADD PRIMARY KEY (`id_string`) USING BTREE;

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `single_pk_int_auto`
--
ALTER TABLE `single_pk_int_auto`
MODIFY `id_int_auto` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
[Index](/docs/README.md) | [Objects in Globular](/docs/objects/README.md) | [Application](/docs/objects/application/README.md) | getFeature()

Returns a feature of application.

**Signature**

    myAppl.getFeature(featureName)

**Parameters**

`featureName`

*(mandatory)* String ID of feature required.

**Return value**

A feature object or -if no feature available with given ID- `undefined`. For further information, please check [Feature](/docs/objects/feature/README.md) section.

**Example**

    const myFeature = myApplication.getFeature('check-humidity-for-location')


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.keyring.fallback">
    <module_version install_time="1410360532664" last="true" origin="installer" specification_version="1.3.1">
        <file crc="1307470414" name="config/Modules/org-netbeans-modules-keyring-fallback.xml"/>
        <file crc="868161419" name="modules/org-netbeans-modules-keyring-fallback.jar"/>
    </module_version>
</module>


text:
__version__ = "0.8"
__author__ = "Keith Smith"

__doc__="\nSALT guide star finder, version "+__version__ +"""

Finds guide stars suitable for use with the Southern African Large Telescope
Uses the HST Guide Star Catalogue 2.3.2 and the VizieR catalogue service

Usage: python guide_stars.py [OPTIONS] [TARGET]

TARGET should be the coordinates of the target or a SIMBAD-resolvable name
Acceptable formats are:
    colon-seperated sexagesimal eg. 15:43:17.2 -18:56:12.9
    space-seperated sexagesimal eg. '15 43 17.2' '-18 56 12.9'
    decimal eg. 15.7837 -18.9543
    target name eg. m31 or 'RV Cen'
All coordinates should be J2000 right ascension and declination

OPTIONS are as follows, arguments are compulsory for both long and short forms:
        --help              Prints this help
    -v    --verbose           Prints useful information during execution
    -d    --debug             Prints debugging information, implies -v
    -f    --filter=FILTER     Uses the FILTER filter,
                                defaults to V
    -i    --instrument=INS    Uses the INS instrument,
                                defaults to RSS
    -r    --radius=RADIUS     Excludes RADIUS arcseconds around target,
                                defaults to 2 arcseconds"""

# import required modules

import urllib2              # reading URLs
from xml.dom import minidom # XML parsing
import csv, StringIO        # CSV parsing
from numpy import *         # array
import sys, getopt                  # command line switches
import warnings

from salttime import dec2sex

# define exceptions

class GuideStarError(Exception): pass    # misc errors in this module
class VizError(Exception): pass # errors thrown by VizieR
#class URLError(Exception): pass # errors accessing the URL
class BadInput(Exception): pass # incorrect input

# define global variables, later read from the command line

# define helper functions

def usage():
    print __doc__
    raise SystemExit(2)        # 2 is the UNIX code for bad command line input apparently

def isDecimal(string):
    "returns true if the input string converts to a valid decimal"
    try:
        float(string)
        return True
    except ValueError:
        return False

def checkdms(dms):
    """Verify a sexagesimal string; returns True if valid, False if not
    """
    assert isinstance(dms, str)

    try:
        d=dms.split(':')
        for i in range(3): float(d[i])
        return True
    except:
        return False

def checkInput(targetRA, targetDec, imfilter, instrument, targetRadius, maxRadius=300):
    "validates input to the main function"

    if isDecimal(targetDec):
        # dec is decimal
        if isDecimal(targetRA)==False:  # check RA in same format
            raise BadInput, 'RA and dec appear to be in different formats'
        if targetDec>0:
           targetDec='+'+dec2sex(float(targetDec))
        else:
           targetDec=dec2sex(float(targetDec))
        targetRA=dec2sex(float(targetRA)/15.0)
    elif isDecimal(targetRA):
        # RA is in decimal, but dec wasn't
        # pretty sure there are no valid target names which are decimals...
        # need to check this as decimals pass as valid sexa!
        raise BadInput, 'RA and dec appear to be in different formats'
    elif checkdms(targetDec) == True:
        # target already colon-seperated value
        # couldn't check this first as this function returns True
        # for decimals (for some reason), but False if space seperated sexa
        if checkdms(targetRA) == False:   # check RA in same format
            raise BadInput, 'RA and dec appear to be in different formats'
        pass    # both already in correct format
    elif checkdms(targetDec.replace(' ',':')) == True:
        # is a valid space seperated sexa, convert to colon seperated
        if (checkdmsStr(targetRA.replace(' ',':')) == False or
            (targetRA.replace(' ',':')==targetRA)):
            # check RA works colon seperated and wasn't to start with
            raise BadInput, 'RA and dec appear to be in different formats'

        targetDec=targetDec.replace(' ',':')
        targetRA=targetRA.replace(' ',':')
    else:
        # dec isn't decimal, or space/colon seperated sexa, or blank
        raise BadInput, 'Format of declination not recognised, was given: '+str(targetDec)

    # convert filters to those in the GSC
    if imfilter == "":
        warnings.warn('No filter specified, defaulting to V')
        imfilter = 'V'
    elif imfilter in ('j', 'F', 'V', 'N'):
        pass    # these are the native filters in the GSC
    elif imfilter in ('U', "u'", 'u'):
        warnings.warn('Specified '+ imfilter + ' filter, but GSC has very little data this far blue. Falling back to photographic Bj')
        imfilter = 'j'    # there IS a U field in GSC, but hardly any entries
    elif imfilter in ('B', "g'", 'b', 'v'):
        warnings.warn('Specified ' + imfilter + ' filter, closest GSC band is photographic Bj')
        imfilter = 'j'   # there is also a Bmag field in GSC, but less entries
    elif imfilter in 'y':
        warnings.warn('Specified ' + imfilter + ' filter, closest GSC band is photographic V')
        imfilter = 'V'
    elif imfilter in ('R', "r'"):
        warnings.warn('Specified ' + imfilter + ' filter, closest GSC band is photographic F')
        imfilter = 'F'
    elif imfilter in ('I', "i'", "z'"):
        warnings.warn('Specified ' + imfilter + ' filter, closest GSC band is photographic N')
        imfilter = 'N'
    else:
        raise BadInput, "Filter '%s' not recognised" % str(imfilter)

    # check instrument input
    instrument = instrument.lower()
    if instrument == "":
        warnings.warn('No instrument specified, defaulting to RSS')
        instrument = 'rss'
    elif instrument in ['rss','pfis']:
        instrument = 'rss'
    elif instrument in ["salticam","scam"]:
        warnings.warn('Selected SALTICAM; SALTICAM values not yet validated')
        instrument = 'scam'
    elif instrument == "hrs":
        warnings.warn('Selected HRS; HRS values not yet validated')
        instrument = 'hrs'
    else:
        raise BadInput, 'Instrument "' + str(instrument) + '" not recognised'

    # check radius
    if targetRadius == '':
        warnings.warn('No target radius specified, defaulting to 2 arcsec')
        targetRadius = 2.
    elif 0 < targetRadius < maxRadius:
        pass
    elif targetRadius > maxRadius:
        raise BadInput, 'Target radius '+str(targetRadius)+' arcsec is larger than the science FoV'
    else:
        raise BadInput, 'Target radius of ' + str(targetRadius) + 'arcsec is invalid'

    return (targetRA, targetDec, imfilter, instrument, targetRadius)

def queryUrl(url):
    "accesses the input url and returns the response"

    request = urllib2.Request(url)
    opener = urllib2.build_opener()
    request.add_header('User-Agent', 'SALT guide star finder/'+ __version__ +' www.salt.ac.za')
    try:
        data = opener.open(request).read()
    except:
        raise GuideStarError, "Could not connect to VizieR. Please check your internet connection"
    return data

def constructVizUrl(targetRA, targetDec, min_r, max_r, imfilter, min_mag, max_mag):
    "constructs the url for the VizieR guide star query"

    url = "http://vizier.u-strasbg.fr/cgi-bin/asu-xml?" # base URL for VizieR XML queries
    url += "-source=I/305/out"                  # use HST GSC 2.3.2
    url += "&-c=" + targetRA
    url += targetDec + "&-c.eq=J2000"   # target section
    url += "&-c.rm=%s,%s" % (min_r, max_r)      # anulus range (arcmin)
    url += "&-out=%smag&%smag=%s..%s" % (imfilter, imfilter, min_mag, max_mag)
    url += "&-out.max=1000"                        # max entries
    url += "&-out=_r,_RA*-c.eq,_DE*-c.eq"       # calculate 2000 RA, dec and distance
    url += ",Class&Class=0"                     # only objects flagged as stars
    url += "&-oc.form=sexa"                     # output coords in sexagesimal
    url += "&-sort=-_r"                         # sort by decreasing r
    url += "&-mime=CSV"                         # data in CSV format

    return url

def parseVizResponse(response):
    "parses the response from VizieR into into a list of data for each star"

# extract CSV table from XML

##    if "****" in response:
##        # actually puts this in
##        #<INFO ID="Errors" value="(**** indicates an Error,++++ indicates a Warning)">
##        #blah blah blah
##        #</INFO>
##        # could handle this better with a little parsing
##        errordata=""
##        for line in response:
##            if "****" in response:
##                errordata += line
##        raise VizError, "Vizier generated an error. The data returned was:\n" + errordata

    xml = minidom.parseString(response)

    table = xml.getElementsByTagName('CSV')
    if len(table)==0:
        info = xml.getElementsByTagName('INFO')
        for element in info:
            id = element.getAttribute('ID')
            if id=='Errors':
                #found an error
                raise VizError, 'Vizier generated an error. The error was:' + element.firstChild.data
        # no CSV table was found ie. no data
        # needs some error checking - might be a bad url or target
        return [],0,[]
    colsep = table[0].getAttribute('colsep')        # CSV columns seperator
    headlines = table[0].getAttribute('headlines')  # CSV header lines
    table = table[0].firstChild.data                # the CSV table itself

    # convert to from unicode
    colsep = colsep.encode('ASCII')
    headlines = int(headlines)

# extract data from CSV table

    csvreader=csv.reader(StringIO.StringIO(table), delimiter=colsep)

# this next bit is very kludgy, weird csvreader object and array manipulations
    for row in csvreader:   # can't index csvreader!
        if len(row)>0:  # blank rows in the reader!
            if 'csvtable' in locals():      # checks to see if csvtable exists
                # python has no exist() function!
                csvtable=vstack((csvtable,array([row])))
                # fragile, dimension mismatch possible
            else:
                csvtable=array([row])
                # can't append to blank arrays!

# old way of using dictionaries:
        #if len(row)>=4:
            #rowdict = {0:row[0],1:row[1],2:row[2],3:row[3],4:row[4]}
            #csvtable.append(rowdict)   # last column Class = 0 for all

    #csvtable = csvtable[int(headlines):] # strip headers

#    header = csvtable[:headlines]
#    data = csvtable[headlines:]

    n_stars=len(csvtable)-headlines

# split off the Class column, as an added bonus won't break if there isn't one
    index = (csvtable[0,:]!='Class')  # boolean index of first row != Class
    csvtable = csvtable[:,index]        # just retain columns in the index

    return csvtable, n_stars, headlines

def sortResults(table, n_stars, headlines, min_r, max_r, min_mag, max_mag):
    "Sorts the results to select the best guide stars"

    # split the header off the table
    header=table[:headlines]
    data=table[headlines:]

    top=header[0,:]

    r_index = top=='_r'
    if not True in r_index:
        raise GuideStarError, ('Could not find a radius column in search results\n' +
              'Returned columns are: ' + str(top))
    r=data[:,r_index]

    mag_index = (top=='Vmag') + (top=='Nmag') + (top=='Bmag') +\
                (top=='Fmag') + (top=='Umag') + (top=='jmag')
    # hard coded brute force
    if not True in mag_index:
        raise GuideStarError, ('Could not find a magnitude column in search results\n' +
              'Returned columns are: ' + str(top))
    mag=data[:,mag_index]

    # convert to floats
    r=r.astype(float64)
    mag=mag.astype(float64)

    r_pref=select([r<min_r, (min_r<=r) & (r<=max_r), r>max_r],
                  [min_r-r, 0., r-max_r])

    mag_pref=select([mag<min_mag, (min_mag<=mag) & (mag<=max_mag), mag>max_r],
                  [min_mag-mag, 0., mag-max_mag])

    pref = 2*r_pref + mag_pref    # weighted such that 1 mag = 0.5 arcmin

    sort_index = lexsort(keys=(mag.T,pref.T),axis=1)    # decide the order from the pref list
                                    # in order, so LOWEST first
    # note the index is crazy - lists the indexes in order, not the order of indices!
    sorted = data[sort_index]
    pref_sort = pref[sort_index]

    n_stars = min(n_stars,6)    # return at most 6 stars

    # replace some of the column headings
    top[top.tolist().index('_r')]='Offset'
    top[top.tolist().index('_RAJ2000')]='RA (J2000)'
    top[top.tolist().index('_DEJ2000')]='Dec (J2000)'

    header[0,:]=top

    # put the header back on
    data = vstack((header,sorted[:,:n_stars][0]))

    return data, n_stars

def QueryCatalog(targetRA, targetDec, abs_min_r=0, abs_max_r=10, imfilter='V',
    abs_min_mag=0, abs_max_mag=30, header=True):
    '''Finds guide stars based upon the HST GSC 2.3.2.
    Pass target RA and Dec (J2000), and optionally
    filter, instrument, and target radius in arcsec.

    Parameters
    ----------
    targetRA: string
       string specifying the target RA.  The format should either
       be the decimal position or a colon or space separated values

    targetDec: string
       string specifying the target RA.  The format should either
       be the decimal position or a colon or space separated values

    abs_min_r: float
       Minimum radius in arcminutes for search annulus

    abs_max_r: float
       Maximum radius in arcminutes for search annulus

    imfilter: string
       Input filter for the observations

    abs_min_mag: float
       Minimum magnitude for stars (bright limit)

    abs_max_r: float
       Maximum mangitude for stars (faint limit)

    header: boolean
       Include header in array

    Returns
    -------

    data: array
       Array containing the sorted results from the query

    n_stars: int
       Number of stars returned

    headlines: int [optional]
       Number of lines in the header.  Only returned if header=True

    '''

    # set up query
    url = constructVizUrl(targetRA, targetDec, abs_min_r, abs_max_r, imfilter, abs_min_mag, abs_max_mag)

    # retrieve data
    response = queryUrl(url)

    #sort the data
    data, n_stars, headlines = parseVizResponse(response)

    if not header:
       return data[headlines:], n_stars
    return data, n_stars, headlines

# main function

def findGuideStars(targetRA, targetDec="", imfilter='', instrument='', targetRadius=2.):
    '''Finds SALT-suitable guide stars based upon the HST GSC 2.3.2.
    Pass target RA and Dec (J2000), and optionally
    filter, instrument, and target radius in arcsec.

    Parameters
    ----------
    targetRA: string
       string specifying the target RA.  The format should either
       be the decimal position or a colon or space separated values

    targetDec: string
       string specifying the target RA.  The format should either
       be the decimal position or a colon or space separated values

    imfilter: string
       Input filter for the observations

    instrument: string
       Instrument to be used for guiding: either rss or scam

    targetRadius:  float
       Radius in arcsec to search for targets.   Maximum value should be 300"

    '''

    (targetRA, targetDec, imfilter, instrument, targetRadius)= \
        checkInput(targetRA, targetDec, imfilter, instrument, targetRadius)

    # set up instrument-specific settings
    # this should go into the check input function, but too much passing
    # for the moment - will change later
    # alternatively use classes?
    instrument = instrument.lower()
    if instrument == 'rss':
        pref_max_r = 5.     # prefered outer edge of anulus in arcmin
        pref_min_r = 4.     # prefered inner edge of anulus in arcmin
        abs_max_r = 5.      # absolute limit on outer edge
        abs_min_r = 1.      # absolute limit on inner edge
        pref_max_mag = 15.  # prefered magnitude limits
        pref_min_mag = 12.
        abs_max_mag = 19.   # absolute magnitude limits
        abs_min_mag = 10
    elif instrument == 'scam':
        # salticam guider has not yet been installed - use values from rss
        # if you fill this in, please change warning message in input check above
        pref_max_r = 5.
        pref_min_r = 4.
        abs_max_r = 5.
        abs_min_r = 1.
        pref_max_mag = 15.
        pref_min_mag = 12.
        abs_max_mag = 19.
        abs_min_mag = 10.
    elif instrument == "hrs":
        # hrs has not yet been built - use values from rss
        # if you fill this in, please change warning message in input check above
        pref_max_r = 5.
        pref_min_r = 4.
        abs_max_r = 5.
        abs_min_r = 1.
        pref_max_mag = 15.
        pref_min_mag = 12.
        abs_max_mag = 19.
        abs_min_mag = 10.
    else:
        raise GuideStarError, "Instrument settings not found, but passed input checking. This shouldn't happen"

    # modify radii if the source is very large
    targetRadius = (targetRadius / 60.) # convert from arcsec to arcmin
    if targetRadius > pref_max_r:
        if targetRadius > abs_max_r:
            return "Target is larger than the guide star field of view"
        else:
            pref_max_r = abs_max_r
    if targetRadius > abs_min_r:
        abs_min_r = targetRadius    # + a bit to avoid vignetting?
        if abs_min_r > pref_min_r:
            pref_min_r = abs_min_r

    gsdata = []

    #query the catalog and return the results as an array
    data,n_stars, headlines=QueryCatalog(targetRA, targetDec, abs_min_r, abs_max_r, imfilter, abs_min_mag, abs_max_mag)

    #sort the stars
    if n_stars>0:
        data, n_stars = sortResults(data, n_stars, headlines, \
                                pref_min_r, pref_max_r, pref_min_mag, pref_max_mag)

    if n_stars>1:
        print('Finished, selected ' + str(n_stars) + ' guide stars')
        status = 'Found ' + str(n_stars) + ' stars'
    elif n_stars==1:
        print('Finished, found one guide star')
        status = 'Found 1 star'
    else:
        print('Failed, found no guide stars')
        if imfilter != 'V':
            print('Falling back to V filter...')
            status, data = findGuideStars(targetRA, targetDec, 'V', instrument, targetRadius*60.)
            status = status + ' after falling back to V'
        else:
            print('Nothing else to fall back to. Try modifying your query')
            status = 'Failed, no suitable stars found'

    return data

if __name__ == "__main__":
   # executes if module is run from the command line

   # read command line options
   try:
       opts,args = getopt.getopt(sys.argv[1:],"vdf:i:r:",
           ["verbose","debug","filter=","instrument=","radius=","help"])
   except getopt.GetoptError, inst:
       print inst
       print 'Use --help to get a list of options'
       sys.exit(2)

   ra, dec, imfilter, ins, radius = "","","","",""

   # parse them to the relevant variables
   for opt, arg in opts:
       if opt in ('--help'):
            usage()
       elif opt in ('-v','--verbose'):
            verbose=True
       elif opt in ('-d','--debug'):
            verbose=True    # implied
            debug=True
       elif opt in ('-f','--filter'):
            imfilter = arg
       elif opt in ('-i','--instrument'):
            ins = arg
       elif opt in ('-r','--radius'):
            radius = float(arg)
       else:
            print 'Unknown option: ' + opt
            usage()

   for argument in args:
        if ra=="":
            ra = argument
        elif dec=="":
            dec = argument
        else:
            #too many arguments
            raise BadInput, 'Too many arguments, takes one or two input arguments'

   if ra=="":    # no target was specified
        raise BadInput, 'No target specified'

   n_stars,data = findGuideStars(ra,dec,imfilter,ins,radius)
   print n_stars, data
   sys.exit(0)

### Testing stuff
#    print "Debugging mode: using default values"
##    verbose=True
##    debug=True
##    import simbad
##    name="hudf"
###    (ra, dec) = simbad.simbad(name)
##    (ra, dec) = (name, "")
###    (ra, dec) = ('80.9','80.9')
##    radius=2.
##    filter="B"
##    ins = 'rss'
##    status, data = findGuideStars(ra, dec, filter=filter, instrument=ins, targetRadius=radius)
##    print data
###    print status
###    for line in data:
#        print line


text:
package com.cspinformatique.kubik.kos.domain.product.service;

import java.io.InputStream;

import com.cspinformatique.kubik.kos.model.product.Product;
import com.cspinformatique.kubik.kos.model.product.ProductImage;
import com.cspinformatique.kubik.kos.model.product.ProductImageSize;

public interface ProductImageService {
	ProductImage findByProductAndSize(Product product, ProductImageSize size);

	InputStream loadImageInputStream(Product product, ProductImageSize size);
}


text:
export class DashboardModel {
  public analyticsDashboard: object;
  public clinicDashboard: object;
  public patientDashboard: object;
  public patientListCohorts: object;
  public providerDashboard: object;
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Chocolatey" file="ODataPackageService.cs">
//   Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace ChocolateyGui.Services.PackageServices
{
    using System;
    using System.Collections.Generic;
    using System.Data.Services.Client;
    using System.Globalization;
    using System.Linq;
    using System.Runtime.Caching;
    using System.Threading.Tasks;
    using ChocolateyGui.ChocolateyFeedService;
    using ChocolateyGui.Models;
    using ChocolateyGui.Utilities.Extensions;
    using ChocolateyGui.ViewModels.Items;

    public static class ODataPackageService
    {
        private static readonly object FeedLockObject = new object();

        private static readonly MemoryCache Cache = MemoryCache.Default;

        public static async Task<IPackageViewModel> EnsureIsLoaded(IPackageViewModel viewModel, Uri source)
        {
            var service = GetFeed(source);

            var feedQuery =
                    (DataServiceQuery<V2FeedPackage>)service.Packages.Where(package => package.Id == viewModel.Id && package.Version == viewModel.Version.ToString());
            var result = await Task.Factory.FromAsync(feedQuery.BeginExecute, ar => feedQuery.EndExecute(ar), null);
            var v2FeedPackages = result as IList<V2FeedPackage> ?? result.ToList();

            if (result == null || !v2FeedPackages.Any())
            {
                return null;
            }

            var packageInfo = v2FeedPackages.Single();
            return AutoMapper.Mapper.Map(packageInfo, viewModel);
        }

        public static async Task<IPackageViewModel> GetLatest(string id, Func<IPackageViewModel> packageFactory, Uri source, bool includePrerelease = false)
        {
            var service = GetFeed(source);

            var packageQuery = service.Packages.Where(p => p.IsPrerelease == includePrerelease || p.IsPrerelease == false)
                .Where(p => p.Id == id);

            packageQuery = includePrerelease ? packageQuery.Where(p => p.IsAbsoluteLatestVersion) : packageQuery.Where(p => p.IsLatestVersion);

            var feedDataServiceQuery = (DataServiceQuery<V2FeedPackage>)packageQuery;
            var packages = await Task.Factory.FromAsync(feedDataServiceQuery.BeginExecute, ar => feedDataServiceQuery.EndExecute(ar), null);
            var package = packages.FirstOrDefault();

            return package == null ? null : AutoMapper.Mapper.Map(package, packageFactory());
        }

        public static async Task<PackageSearchResults> Search(string query, Func<IPackageViewModel> packageFactory, Uri source)
        {
            return await Search(query, packageFactory, new PackageSearchOptions(), source);
        }

        public static async Task<PackageSearchResults> Search(string query, Func<IPackageViewModel> packageFactory, PackageSearchOptions options, Uri source)
        {
            var service = GetFeed(source);
            var queryString = query;
            IQueryable<V2FeedPackage> feedQuery = service.Packages.Where(package => package.IsPrerelease == options.IncludePrerelease || package.IsPrerelease == false);

            if (!options.IncludeAllVersions)
            {
                feedQuery = feedQuery.Where(package => package.IsLatestVersion || package.IsAbsoluteLatestVersion);
            }

            if (!string.IsNullOrWhiteSpace(queryString))
            {
                feedQuery = options.MatchQuery ?
                    feedQuery.Where(package => package.Id == queryString || package.Title == queryString) :
                    feedQuery.Where(package => package.Id.Contains(queryString) || package.Title.Contains(queryString));
            }

            var totalCount = feedQuery.Count();

            if (!string.IsNullOrWhiteSpace(options.SortColumn))
            {
                feedQuery = !options.SortDescending ? feedQuery.OrderBy(options.SortColumn) : feedQuery.OrderByDescending(options.SortColumn);
            }

            feedQuery = feedQuery.Skip(options.CurrentPage * options.PageSize).Take(options.PageSize);
            var feedDataServiceQuery = (DataServiceQuery<V2FeedPackage>)feedQuery;
            var result = await Task.Factory.FromAsync(feedDataServiceQuery.BeginExecute, ar => feedDataServiceQuery.EndExecute(ar), null);

            var packages = result.Select(package => AutoMapper.Mapper.Map(package, packageFactory()));

            return new PackageSearchResults
            {
                TotalCount = totalCount,
                Packages = packages
            };
        }

        public static async Task<Exception> TestPath(Uri source)
        {
            try
            {
                var service = GetFeed(source);
                var query = (DataServiceQuery<V2FeedPackage>)service.Packages.Take(1);
                var result = query.FirstOrDefault();
                await Task.Factory.FromAsync(query.BeginExecute, ar => query.EndExecute(ar), null);
                return null;
            }
            catch (Exception ex)
            {
                return ex;
            }
        }

        private static FeedContext_x0060_1 GetFeed(Uri source)
        {
            lock (FeedLockObject)
            {
                FeedContext_x0060_1 service;
                if ((service = (FeedContext_x0060_1)Cache.Get(GetMemoryCacheKey(source))) == null)
                {
                    service = new FeedContext_x0060_1(source)
                    {
                        IgnoreMissingProperties = true,
                        IgnoreResourceNotFoundException = true,
                        MergeOption = MergeOption.NoTracking
                    };

                    Cache.Set(
                        GetMemoryCacheKey(source),
                        service,
                        new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(20) });
                }

                return service;
            }
        }

        private static string GetMemoryCacheKey(Uri feed)
        {
            return string.Format(CultureInfo.CurrentCulture, "ODataPackageService.Feeds.{0}", feed);
        }
    }
}


text:
using Mint.Lex.States.Delimiters;
using Mint.Parse;
using static Mint.Parse.TokenType;

namespace Mint.Lex.States
{
    internal partial class StringLiteral : Literal
    {
        private readonly Delimiter delimiter;
        private RegexpFlags regexpOptions = RegexpFlags.None;
        private bool emittedSpace;
        private readonly State endState;

        public StringLiteral(Lexer lexer, int ts, int te, bool canLabel = false, State endState = null)
            : base(lexer, lexer.Position + 1)
        {
            var text = lexer.TextAt(ts, te);
            delimiter = DelimiterFactory.CreateDelimiter(this, text);

            if(canLabel)
            {
                delimiter.Features |= LiteralFeatures.Label;
            }

            this.endState = endState ?? lexer.EndState;

            BeginToken = lexer.GenerateToken(delimiter.BeginType, ts, te);
            BeginToken.Properties["has_interpolation"] = delimiter.HasInterpolation;
        }

        protected override char CurrentChar => Lexer.CurrentChar;
        private bool IsDelimiter => Lexer.CurrentChar == delimiter.CloseDelimiter;

        protected override void EmitContent(int te)
        {
            if(delimiter.IsWords && contentStart == te)
            {
                return;
            }

            base.EmitContent(te);
            emittedSpace = false;
        }

        protected override void EmitDBeg()
        {
            base.EmitDBeg();
            emittedSpace = false;
        }

        protected override void EmitDVar(TokenType type)
        {
            base.EmitDVar(type);
            emittedSpace = false;
        }

        private void EmitEndToken(int ts, int te)
        {
            EmitSpace(ts, ts);

            var type = Lexer.Data[te - 1] == ':' ? tLABEL_END
                     : delimiter.IsRegexp ? tREGEXP_END
                     : tSTRING_END;

            Lexer.EmitToken(type, ts, te);
            Lexer.PopLiteral();
            Lexer.CurrentState = endState;
        }

        private void EmitSpace(int ts, int te)
        {
            if(!delimiter.IsWords || emittedSpace)
            {
                return;
            }

            Lexer.EmitToken(tSPACE, ts, te);
            emittedSpace = true;
            contentStart = this.te;
        }
    }
}


text:
'use strict';

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

require('document-register-element');

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function getLocale() {
  var documentElement = (document || {}).documentElement;
  var lang = (documentElement || {}).leng;
  lang && _moment2.default.locale(lang) && (getLocale = undefined);
}

var HTMLRelativeTimeElement = (function (_HTMLElement) {
  _inherits(HTMLRelativeTimeElement, _HTMLElement);

  function HTMLRelativeTimeElement() {
    _classCallCheck(this, HTMLRelativeTimeElement);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(HTMLRelativeTimeElement).apply(this, arguments));
  }

  _createClass(HTMLRelativeTimeElement, [{
    key: 'attachedCallback',
    value: function attachedCallback() {
      typeof getLocale === 'function' && getLocale();
      var currentDateTime = this.getAttribute('datetime');
      currentDateTime && this.attributeChangedCallback('datetime', currentDateTime, currentDateTime);
    }
  }, {
    key: 'attributeChangedCallback',
    value: function attributeChangedCallback(name, previousValue, value) {
      var relativeTime = (0, _moment2.default)(value).fromNow();
      this.textContent = relativeTime;
    }
  }, {
    key: 'createdCallback',
    value: function createdCallback() {
      var currentDateTime = this.getAttribute('datetime');
      currentDateTime && this.attributeChangedCallback('datetime', undefined, currentDateTime);
    }
  }, {
    key: 'detachedCallback',
    value: function detachedCallback() {}
  }]);

  return HTMLRelativeTimeElement;
})(HTMLElement);

HTMLRelativeTimeElement.extends = 'time';

document.registerElement('relative-time', HTMLRelativeTimeElement);


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use backend\models\AuthCategory;
/* @var $this yii\web\View */
/* @var $model backend\models\AuthRole */
/* @var $form yii\widgets\ActiveForm */
$cate = ArrayHelper::map(AuthCategory::find()->all(),'id','name');
?>

    <?php
    $form = ActiveForm::begin();

    ?>
    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'description')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'cat_id',[
        'template' => "{label}\n
{input}
 \n{hint}\n{error}"
    ])->dropDownList($cate,['prompt'=>'请选择分类']) ?>
    <?= $form->field($model, 'rules')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'controllers[]',[
        'template' => "{label}\n

{input}\n{hint}\n{error}
"
            ."
<button type='button' class='btn btn-danger btn-block' id=\"bt-controller-remove\"></button>"
            ."
<button type='button' class='btn btn-success btn-block' id=\"bt-controller-add\"></button>
"
            ."
".Html::dropDownList('controllers',null,$this->context->getControllers(),['prompt'=>'请选择控制器','id'=>'controllers','class'=>'form-control','multiple'=>true,'size'=>'4'])."

"
    ])->dropDownList(explode(',',$model->controllers),['prompt' => '从右边添加控制器','multiple'=>true,'size'=>'4']) ?>
    <?= $form->field($model, 'actions[]',[
        'template' => "{label}\n

{input}\n{hint}\n{error}
"
            ."
<button type='button' class='btn btn-danger btn-block' id=\"bt-action-remove\"></button>"
            ."
<button type='button' class='btn btn-success btn-block' id=\"bt-action-add\"></button>
"
            ."
".Html::dropDownList('actions',null,[],['prompt'=>'先选择上面的控制器再选择action','id'=>'actions','class'=>'form-control','multiple'=>true,'size'=>'4'])."

"
    ])->dropDownList(explode(',',$model->actions),['prompt' => '从右边添加action','multiple'=>true,'size'=>'4']) ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

<?php

$ajax_url = Url::to(['category-create']);
$act_url = Url::to(['get-action']);
$js=<<<JS

$('.input-group-addon').click(function(){
      var cat_name = prompt("请输入分类名称");
      if(cat_name ==null || cat_name==''){
        return ;
      }
    $.ajax({
        url:'{$ajax_url}',
        data:'AuthCategory[name]='+cat_name,
        dataType: "json",
        method:'POST',
        success:function(data){
            if(typeof(data.selected) !=='undefined'){
                var src = data.data
                var html = '<option value="">分类名称</option>';
                for(var i=0;i<src.length;i++){
                    if(src[i].id==data.selected){
                       var sel = " selected='selected'";
                    }else{
                       var sel = '';
                    }
                    html+='<option value="'+src[i].id+'"'+sel+'>'+src[i].name+'</option>';
                }
                $('#authrole-cat_id').html(html);
            }else{
                if(data.length>0)
                alert(data.join("\\n"));
            }

        }
    });
});
$('#controllers').change(function() {
      var controller = $('#controllers option:selected').text();
      if(controller=='请选择控制器')return;
      $.ajax({
        url:'{$act_url}',
        data:'controller='+controller,
        dataType: "json",
        method:'get',
        success:function(data){
            var html = '<option value="">先选择上面的控制器再选择action</option>';
            for(var e in data){

                html+='<option value="'+e+'">'+data[e]+'</option>';
            }
            $('#actions').html(html);
         }
    });
});
$("#bt-controller-add").click(function(){
    addOption('controllers','authrole-controllers');
});
$('#bt-controller-remove').click(function(){
    removeOption('authrole-controllers');
});
$("#bt-action-add").click(function(){
    addOption('actions','authrole-actions');
});
$('#bt-action-remove').click(function(){
    removeOption('authrole-actions');
});
function addOption(from ,to){
    $('#'+from+' option:selected').each(function(){
        $('#'+to).append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
    });
    var map = {};
    $('#'+to+' option').each(function () {
        if (map[this.value]) {
            $(this).remove()
        }
        map[this.value] = true;
    })
}
function removeOption(from){
     $('#'+from+' option:selected').each(function(){
           $(this).remove();
    });
}
$('#w0').submit(function(){
    $('#authrole-controllers option,#authrole-actions option').each(function(){
        if($(this).text().indexOf('@')!=-1)
            $(this).attr('value',$(this).text());
        $(this).attr("selected","selected");
    });
});

JS;
$this->registerJs($js);
?>


text:
class PlaysController < ApplicationController
  def characters
  end

  def index
  end
end


text:
#ifndef TOKENIZERS_H
#define TOKENIZERS_H

#include "config.h"
#include "mem_pool.h"
#include "fstring.h"
#include "main.h"
#include "stat_api.h"

#define RSPAMD_DEFAULT_TOKENIZER "osb"

/* Common tokenizer structure */
struct rspamd_stat_tokenizer {
	gchar *name;
	gpointer (*get_config) (struct rspamd_tokenizer_config *cf, gsize *len);
	gboolean (*compatible_config) (struct rspamd_tokenizer_config *cf,
			gpointer ptr, gsize len);
	gint (*tokenize_func)(struct rspamd_tokenizer_config *cf,
			rspamd_mempool_t *pool,
			GArray *words,
			GTree *result,
			gboolean is_utf);
};

/* Compare two token nodes */
gint token_node_compare_func (gconstpointer a, gconstpointer b);

/* Tokenize text into array of words (rspamd_fstring_t type) */
GArray * rspamd_tokenize_text (gchar *text, gsize len, gboolean is_utf,
		gsize min_len, GList *exceptions, gboolean compat);

/* OSB tokenize function */
gint rspamd_tokenizer_osb (struct rspamd_tokenizer_config *cf,
	rspamd_mempool_t *pool,
	GArray *input,
	GTree *tokens,
	gboolean is_utf);

gpointer rspamd_tokenizer_osb_get_config (struct rspamd_tokenizer_config *cf,
		gsize *len);

gboolean
rspamd_tokenizer_osb_compatible_config (struct rspamd_tokenizer_config *cf,
			gpointer ptr, gsize len);

#endif
/*
 * vi:ts=4
 */


text:
package daemon

import flag "github.com/docker/docker/pkg/mflag"

func (config *Config) attachExperimentalFlags(cmd *flag.FlagSet, usageFn func(string) string) {
}


text:
<?php namespace App\Container;

use Limoncello\Application\Contracts\Csrf\CsrfTokenGeneratorInterface;
use Limoncello\Application\Packages\Csrf\CsrfSettings;
use Limoncello\Contracts\Application\ContainerConfiguratorInterface;
use Limoncello\Contracts\Container\ContainerInterface as LimoncelloContainerInterface;
use Limoncello\Contracts\Settings\SettingsProviderInterface;
use Limoncello\Contracts\Templates\TemplatesInterface;
use Limoncello\Templates\Package\TemplatesSettings as C;
use Limoncello\Templates\TwigTemplates;
use Psr\Container\ContainerInterface as PsrContainerInterface;
use Twig_Extensions_Extension_Text;
use Twig_Function;

/**
 * @package App\Container
 */
class TwigConfigurator implements ContainerConfiguratorInterface
{
    /** @var callable */
    const CONFIGURATOR = [self::class, self::CONTAINER_METHOD_NAME];

    /**
     * @inheritdoc
     */
    public static function configureContainer(LimoncelloContainerInterface $container): void
    {
        $container[TemplatesInterface::class] = function (PsrContainerInterface $container): TemplatesInterface {
            /** @var SettingsProviderInterface $provider */
            $provider = $container->get(SettingsProviderInterface::class);

            $settings  = $provider->get(C::class);
            $templates = new TwigTemplates(
                $settings[C::KEY_APP_ROOT_FOLDER],
                $settings[C::KEY_TEMPLATES_FOLDER],
                $settings[C::KEY_CACHE_FOLDER] ?? null,
                $settings[C::KEY_IS_DEBUG] ?? false,
                $settings[C::KEY_IS_AUTO_RELOAD] ?? false
            );

            $templates->getTwig()->addExtension(new Twig_Extensions_Extension_Text());

            $templates->getTwig()->addFunction(new Twig_Function(
                'csrf',
                function () use ($container, $provider): string {
                    [CsrfSettings::HTTP_REQUEST_CSRF_TOKEN_KEY => $key] = $provider->get(CsrfSettings::class);

                    /** @var CsrfTokenGeneratorInterface $generator */
                    $generator = $container->get(CsrfTokenGeneratorInterface::class);
                    $token     = $generator->create();

                    $result = '<input type="hidden" name="' . $key . '" value="' . $token . '">';

                    return $result;
                },
                ['is_safe' => ['html']]
            ));

            $templates->getTwig()->addFunction(new Twig_Function(
                'csrf_name',
                function () use ($container, $provider): string {
                    [CsrfSettings::HTTP_REQUEST_CSRF_TOKEN_KEY => $key] = $provider->get(CsrfSettings::class);

                    return $key;
                },
                ['is_safe' => ['html']]
            ));

            $templates->getTwig()->addFunction(new Twig_Function(
                'csrf_value',
                function () use ($container, $provider): string {
                    /** @var CsrfTokenGeneratorInterface $generator */
                    $generator = $container->get(CsrfTokenGeneratorInterface::class);
                    $token     = $generator->create();

                    return $token;
                },
                ['is_safe' => ['html']]
            ));

            return $templates;
        };
    }
}