text:
package org.elasticsearch.search.aggregations.metrics;

import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.aggregations.AggregationTestScriptsPlugin;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.bucket.filter.Filter;
import org.elasticsearch.search.aggregations.bucket.global.Global;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Order;
import org.elasticsearch.search.aggregations.metrics.stats.Stats;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.Collections.emptyMap;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.filter;
import static org.elasticsearch.search.aggregations.AggregationBuilders.global;
import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram;
import static org.elasticsearch.search.aggregations.AggregationBuilders.stats;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.sameInstance;

public class StatsIT extends AbstractNumericTestCase {
    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return Collections.singleton(AggregationTestScriptsPlugin.class);
    }

    @Override
    public void testEmptyAggregation() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx")
                .setQuery(matchAllQuery())
                .addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0).subAggregation(stats("stats").field("value")))
                .execute().actionGet();

        assertShardExecutionState(searchResponse, 0);

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
        Histogram histo = searchResponse.getAggregations().get("histo");
        assertThat(histo, notNullValue());
        Histogram.Bucket bucket = histo.getBuckets().get(1);
        assertThat(bucket, notNullValue());

        Stats stats = bucket.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getCount(), equalTo(0L));
        assertThat(stats.getSum(), equalTo(0.0));
        assertThat(stats.getMin(), equalTo(Double.POSITIVE_INFINITY));
        assertThat(stats.getMax(), equalTo(Double.NEGATIVE_INFINITY));
        assertThat(Double.isNaN(stats.getAvg()), is(true));
    }

    @Override
    public void testUnmapped() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx_unmapped")
                .setQuery(matchAllQuery())
                .addAggregation(stats("stats").field("value"))
                .execute().actionGet();

        assertShardExecutionState(searchResponse, 0);

        assertThat(searchResponse.getHits().getTotalHits(), equalTo(0L));

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo(Double.NaN));
        assertThat(stats.getMin(), equalTo(Double.POSITIVE_INFINITY));
        assertThat(stats.getMax(), equalTo(Double.NEGATIVE_INFINITY));
        assertThat(stats.getSum(), equalTo(0.0));
        assertThat(stats.getCount(), equalTo(0L));
    }

    public void testPartiallyUnmapped() {
        Stats s1 = client().prepareSearch("idx")
                .addAggregation(stats("stats").field("value")).get()
                .getAggregations().get("stats");
        Stats s2 = client().prepareSearch("idx", "idx_unmapped")
                .addAggregation(stats("stats").field("value")).get()
                .getAggregations().get("stats");
        assertEquals(s1.getAvg(), s2.getAvg(), 1e-10);
        assertEquals(s1.getCount(), s2.getCount());
        assertEquals(s1.getMin(), s2.getMin(), 0d);
        assertEquals(s1.getMax(), s2.getMax(), 0d);
    }

    @Override
    public void testSingleValuedField() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(stats("stats").field("value"))
                .execute().actionGet();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10));
        assertThat(stats.getMin(), equalTo(1.0));
        assertThat(stats.getMax(), equalTo(10.0));
        assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10));
        assertThat(stats.getCount(), equalTo(10L));
    }

    public void testSingleValuedField_WithFormatter() throws Exception {

        SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery())
                .addAggregation(stats("stats").format("0000.0").field("value")).execute().actionGet();

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) / 10));
        assertThat(stats.getAvgAsString(), equalTo("0005.5"));
        assertThat(stats.getMin(), equalTo(1.0));
        assertThat(stats.getMinAsString(), equalTo("0001.0"));
        assertThat(stats.getMax(), equalTo(10.0));
        assertThat(stats.getMaxAsString(), equalTo("0010.0"));
        assertThat(stats.getSum(), equalTo((double) 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10));
        assertThat(stats.getSumAsString(), equalTo("0055.0"));
        assertThat(stats.getCount(), equalTo(10L));
        assertThat(stats.getCountAsString(), equalTo("0010.0"));
    }

    @Override
    public void testSingleValuedFieldGetProperty() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery())
                .addAggregation(global("global").subAggregation(stats("stats").field("value"))).execute().actionGet();

        assertHitCount(searchResponse, 10);

        Global global = searchResponse.getAggregations().get("global");
        assertThat(global, notNullValue());
        assertThat(global.getName(), equalTo("global"));
        assertThat(global.getDocCount(), equalTo(10L));
        assertThat(global.getAggregations(), notNullValue());
        assertThat(global.getAggregations().asMap().size(), equalTo(1));

        Stats stats = global.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        Stats statsFromProperty = (Stats) ((InternalAggregation)global).getProperty("stats");
        assertThat(statsFromProperty, notNullValue());
        assertThat(statsFromProperty, sameInstance(stats));
        double expectedAvgValue = (double) (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) / 10;
        assertThat(stats.getAvg(), equalTo(expectedAvgValue));
        assertThat((double) ((InternalAggregation)global).getProperty("stats.avg"), equalTo(expectedAvgValue));
        double expectedMinValue = 1.0;
        assertThat(stats.getMin(), equalTo(expectedMinValue));
        assertThat((double) ((InternalAggregation)global).getProperty("stats.min"), equalTo(expectedMinValue));
        double expectedMaxValue = 10.0;
        assertThat(stats.getMax(), equalTo(expectedMaxValue));
        assertThat((double) ((InternalAggregation)global).getProperty("stats.max"), equalTo(expectedMaxValue));
        double expectedSumValue = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
        assertThat(stats.getSum(), equalTo(expectedSumValue));
        assertThat((double) ((InternalAggregation)global).getProperty("stats.sum"), equalTo(expectedSumValue));
        long expectedCountValue = 10;
        assertThat(stats.getCount(), equalTo(expectedCountValue));
        assertThat((double) ((InternalAggregation)global).getProperty("stats.count"), equalTo((double) expectedCountValue));
    }

    @Override
    public void testSingleValuedFieldPartiallyUnmapped() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx", "idx_unmapped")
                .setQuery(matchAllQuery())
                .addAggregation(stats("stats").field("value"))
                .execute().actionGet();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10));
        assertThat(stats.getMin(), equalTo(1.0));
        assertThat(stats.getMax(), equalTo(10.0));
        assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10));
        assertThat(stats.getCount(), equalTo(10L));
    }

    @Override
    public void testSingleValuedFieldWithValueScript() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(
                        stats("stats")
                                .field("value")
                                .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value + 1", emptyMap())))
                .get();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10));
        assertThat(stats.getMin(), equalTo(2.0));
        assertThat(stats.getMax(), equalTo(11.0));
        assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11));
        assertThat(stats.getCount(), equalTo(10L));
    }

    @Override
    public void testSingleValuedFieldWithValueScriptWithParams() throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("inc", 1);
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(
                        stats("stats")
                                .field("value")
                                .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value + inc", params)))
                .get();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10));
        assertThat(stats.getMin(), equalTo(2.0));
        assertThat(stats.getMax(), equalTo(11.0));
        assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11));
        assertThat(stats.getCount(), equalTo(10L));
    }

    @Override
    public void testMultiValuedField() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(stats("stats").field("values"))
                .execute().actionGet();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11+3+4+5+6+7+8+9+10+11+12) / 20));
        assertThat(stats.getMin(), equalTo(2.0));
        assertThat(stats.getMax(), equalTo(12.0));
        assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11+3+4+5+6+7+8+9+10+11+12));
        assertThat(stats.getCount(), equalTo(20L));
    }

    @Override
    public void testMultiValuedFieldWithValueScript() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(
                        stats("stats")
                                .field("values")
                                .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value - 1", emptyMap())))
                .get();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10+2+3+4+5+6+7+8+9+10+11) / 20));
        assertThat(stats.getMin(), equalTo(1.0));
        assertThat(stats.getMax(), equalTo(11.0));
        assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10+2+3+4+5+6+7+8+9+10+11));
        assertThat(stats.getCount(), equalTo(20L));
    }

    @Override
    public void testMultiValuedFieldWithValueScriptWithParams() throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("dec", 1);
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(
                        stats("stats")
                                .field("values")
                                .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value - dec", params)))
                .get();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10+2+3+4+5+6+7+8+9+10+11) / 20));
        assertThat(stats.getMin(), equalTo(1.0));
        assertThat(stats.getMax(), equalTo(11.0));
        assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10+2+3+4+5+6+7+8+9+10+11));
        assertThat(stats.getCount(), equalTo(20L));
    }

    @Override
    public void testScriptSingleValued() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(
                        stats("stats")
                                .script(new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "doc['value'].value", emptyMap())))
                .get();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10));
        assertThat(stats.getMin(), equalTo(1.0));
        assertThat(stats.getMax(), equalTo(10.0));
        assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10));
        assertThat(stats.getCount(), equalTo(10L));
    }

    @Override
    public void testScriptSingleValuedWithParams() throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("inc", 1);

        Script script = new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "doc['value'].value + inc", params);

        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(stats("stats").script(script))
                .get();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11) / 10));
        assertThat(stats.getMin(), equalTo(2.0));
        assertThat(stats.getMax(), equalTo(11.0));
        assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11));
        assertThat(stats.getCount(), equalTo(10L));
    }

    @Override
    public void testScriptMultiValued() throws Exception {
        Script script = new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "doc['values'].values", emptyMap());

        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(stats("stats").script(script))
                .get();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (2+3+4+5+6+7+8+9+10+11+3+4+5+6+7+8+9+10+11+12) / 20));
        assertThat(stats.getMin(), equalTo(2.0));
        assertThat(stats.getMax(), equalTo(12.0));
        assertThat(stats.getSum(), equalTo((double) 2+3+4+5+6+7+8+9+10+11+3+4+5+6+7+8+9+10+11+12));
        assertThat(stats.getCount(), equalTo(20L));
    }

    @Override
    public void testScriptMultiValuedWithParams() throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("dec", 1);

        Script script = new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "[ doc['value'].value, doc['value'].value - dec ]",
            params);

        SearchResponse searchResponse = client().prepareSearch("idx")
                .setQuery(matchAllQuery())
                .addAggregation(
                        stats("stats")
                                .script(script))
                .get();

        assertShardExecutionState(searchResponse, 0);

        assertHitCount(searchResponse, 10);

        Stats stats = searchResponse.getAggregations().get("stats");
        assertThat(stats, notNullValue());
        assertThat(stats.getName(), equalTo("stats"));
        assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10+0+1+2+3+4+5+6+7+8+9) / 20));
        assertThat(stats.getMin(), equalTo(0.0));
        assertThat(stats.getMax(), equalTo(10.0));
        assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10+0+1+2+3+4+5+6+7+8+9));
        assertThat(stats.getCount(), equalTo(20L));
    }

    @Override
    public void testOrderByEmptyAggregation() throws Exception {
        SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery())
                .addAggregation(terms("terms").field("value").order(Order.compound(Order.aggregation("filter>stats.avg", true)))
                        .subAggregation(filter("filter", termQuery("value", 100)).subAggregation(stats("stats").field("value"))))
                .get();

        assertHitCount(searchResponse, 10);

        Terms terms = searchResponse.getAggregations().get("terms");
        assertThat(terms, notNullValue());
        List<Terms.Bucket> buckets = terms.getBuckets();
        assertThat(buckets, notNullValue());
        assertThat(buckets.size(), equalTo(10));

        for (int i = 0; i < 10; i++) {
            Terms.Bucket bucket = buckets.get(i);
            assertThat(bucket, notNullValue());
            assertThat(bucket.getKeyAsNumber(), equalTo((long) i + 1));
            assertThat(bucket.getDocCount(), equalTo(1L));
            Filter filter = bucket.getAggregations().get("filter");
            assertThat(filter, notNullValue());
            assertThat(filter.getDocCount(), equalTo(0L));
            Stats stats = filter.getAggregations().get("stats");
            assertThat(stats, notNullValue());
            assertThat(stats.getMin(), equalTo(Double.POSITIVE_INFINITY));
            assertThat(stats.getMax(), equalTo(Double.NEGATIVE_INFINITY));
            assertThat(stats.getAvg(), equalTo(Double.NaN));
            assertThat(stats.getSum(), equalTo(0.0));
            assertThat(stats.getCount(), equalTo(0L));

        }
    }

    private void assertShardExecutionState(SearchResponse response, int expectedFailures) throws Exception {
        ShardSearchFailure[] failures = response.getShardFailures();
        if (failures.length != expectedFailures) {
            for (ShardSearchFailure failure : failures) {
                logger.error((Supplier<?>) () -> new ParameterizedMessage("Shard Failure: {}", failure), failure.getCause());
            }
            fail("Unexpected shard failures!");
        }
        assertThat("Not all shards are initialized", response.getSuccessfulShards(), equalTo(response.getTotalShards()));
    }

    /**
     * Make sure that a request using a script does not get cached and a request
     * not using a script does get cached.
     */
    public void testDontCacheScripts() throws Exception {
        assertAcked(prepareCreate("cache_test_idx").addMapping("type", "d", "type=long")
                .setSettings(Settings.builder().put("requests.cache.enable", true).put("number_of_shards", 1).put("number_of_replicas", 1))
                .get());
        indexRandom(true, client().prepareIndex("cache_test_idx", "type", "1").setSource("s", 1),
                client().prepareIndex("cache_test_idx", "type", "2").setSource("s", 2));

        // Make sure we are starting with a clear cache
        assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
                .getHitCount(), equalTo(0L));
        assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
                .getMissCount(), equalTo(0L));

        // Test that a request using a script does not get cached
        SearchResponse r = client().prepareSearch("cache_test_idx").setSize(0).addAggregation(
                stats("foo").field("d").script(
                    new Script(ScriptType.INLINE, AggregationTestScriptsPlugin.NAME, "_value + 1", Collections.emptyMap()))).get();
        assertSearchResponse(r);

        assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
                .getHitCount(), equalTo(0L));
        assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
                .getMissCount(), equalTo(0L));

        // To make sure that the cache is working test that a request not using
        // a script is cached
        r = client().prepareSearch("cache_test_idx").setSize(0).addAggregation(stats("foo").field("d")).get();
        assertSearchResponse(r);

        assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
                .getHitCount(), equalTo(0L));
        assertThat(client().admin().indices().prepareStats("cache_test_idx").setRequestCache(true).get().getTotal().getRequestCache()
                .getMissCount(), equalTo(1L));
    }
}


text:
namespace AsterNET.Manager.Event
{
    public class MeetmeMuteEvent : AbstractMeetmeEvent
    {
        public MeetmeMuteEvent(ManagerConnection source)
            : base(source)
        {
        }

        public bool Status { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.axis.wsdl.toJava;

import org.apache.axis.Version;
import org.apache.axis.utils.Messages;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Emitter knows about WSDL writers, one each for PortType, Binding, Service,
 * Definition, Type.  But for some of these WSDL types, Wsdl2java generates
 * multiple files.  Each of these files has a corresponding writer that extends
 * JavaWriter.  So the Java WSDL writers (JavaPortTypeWriter, JavaBindingWriter,
 * etc.) each calls a file writer (JavaStubWriter, JavaSkelWriter, etc.) for
 * each file that that WSDL generates.
 *
For example, when Emitter calls JavaWriterFactory for a Binding Writer, it
 * returns a JavaBindingWriter.  JavaBindingWriter, in turn, contains a
 * JavaStubWriter, JavaSkelWriter, and JavaImplWriter since a Binding may cause
 * a stub, skeleton, and impl template to be generated.
 *
Note that the writers that are given to Emitter by JavaWriterFactory DO NOT
 * extend JavaWriter.  They simply implement Writer and delegate the actual
 * task of writing to extensions of JavaWriter.
 *
All of Wsdl2java's Writer implementations follow a common behaviour.
 * JavaWriter is the abstract base class that dictates this common behaviour.
 * Many of the files generated are .java files, so this abstract class -
 * JavaClassWriter - exists.  It extends JavaWriter and adds a bit of Java-
 * relative behaviour.  This behaviour is primarily placed within the generate
 * method.  The generate method calls, in succession (note:  the starred methods
 * are the ones you are probably most interested in):
 *

 *
 getFileName
 *
 This method is abstract in JavaWriter, but JavaClassWriter implements
 * this method.  Subclasses should have no need to override it.  It
 * returns the fully-qualified file name based on the fully-qualified
 * classname + ".java".
 *
 isFileGenerated(file)
 *
 You should not need to override this method.  It checks to see whether
 * this file is in the List returned by emitter.getGeneratedFileNames.
 *
 registerFile(file)
 *
 You should not need to override this method.  It registers this file by
 * calling emitter.getGeneratedFileInfo().add(...).
 *
 * verboseMessage(file)
 *
 You may override this method if you want to provide more information.
 * The generate method only calls verboseMessage if verbose is turned on.
 *
 getPrintWriter(file)
 *
 You should not need to override this method.  Given the file name, it
 * creates a PrintWriter for it.
 *
 writeFileHeader(pw)
 *
 JavaClassWriter implements this method, so you should not need to
 * override it.  This method generates a javadoc giving the filename and
 * a comment stating that this file is generated by WSDL2Java, and it
 * generates the class definition including the opening curly brace..
 *
 * writeFileBody(pw)
 *
 This is an abstract method that must be implemented by the subclass.
 * This is where the body of a file is generated.
 *
 * writeFileFooter(pw)
 *
 JavaClassWriter implements this method, so you should not need to
 * override it.  It generates the closing curly brace for the class.
 *
 closePrintWriter(pw)
 *
 You should not need to override this method.  It simply closes the
 * PrintWriter.
 *

 *

 * Additional behaviour that JavaClassWriter introduces beyond JavaWriter is
 * related to the class header and definition:
 *

 *
 writeHeaderComments
 *
 Write the header comments, such as the file name and that the file was
 * generated by WSDL2Java.  You need not override this method unless you
 * want a tailored comment.
 *
 writePackage
 *
 Write the package statement, if necessary.  You should not need to
 * override this method.
 *
 getClassModifiers
 *
 Modifiers, such as "public", "final", "abstract" would be returned by
 * this method.  The default implementation only generates "public ", so
 * any subclass that needs more must override this method.
 *
 getClassText
 *
 This simply returns "class ".  If anything else is desired, for
 * instance, JavaInterfaceWriter prefers "interface ", then this method
 * must be overridden.
 *
 getExtendsText
 *
 The default implementation returns "".  If a subclass desires to list
 * a set of classes this one extends, then this method must be overridden.
 *
 getImplementsText
 *
 Same as getExtendsText except for the implements clause.
 *

 */
public abstract class JavaClassWriter extends JavaWriter {

    /** Field namespaces */
    protected Namespaces namespaces;

    /** Field className */
    protected String className;

    /** Field packageName */
    protected String packageName;

    /**
     * Constructor.
     *
     * @param emitter       The emitter instance
     * @param fullClassName The fully qualified class name of the class
     *                      to be generated.
     * @param type
     */
    protected JavaClassWriter(Emitter emitter, String fullClassName,
                              String type) {

        super(emitter, type);

        this.namespaces = emitter.getNamespaces();
        this.packageName = Utils.getJavaPackageName(fullClassName);
        this.className = Utils.getJavaLocalName(fullClassName);
    }    // ctor

    /**
     * Return the file name as a string of the form:
     * "<directory-ized fully-qualified classname>.java"
     *
     * @return
     */
    protected String getFileName() {
        return namespaces.toDir(packageName) + className + ".java";
    }    // getFileName

    /**
     * You should not need to override this method.
     * It registers the given file by calling
     * emitter.getGeneratedFileInfo().add(...).
     * JavaClassWriter overrides this method from JavaWriter because
     * it add class name to the registration information.
     *
     * @param file
     */
    protected void registerFile(String file) {

        final String pkg = getPackage();
        String fqClass;
        if (pkg != null && pkg.length() > 0) {
            fqClass = pkg + '.' + getClassName();
        } else {
            fqClass = getClassName();
        }

        emitter.getGeneratedFileInfo().add(file, fqClass, type);
    }    // registerFile

    /**
     * Write a common header, including the package name, the class
     * declaration, and the opening curly brace.
     *
     * @param pw
     * @throws IOException
     */
    protected void writeFileHeader(PrintWriter pw) throws IOException {

        writeHeaderComments(pw);
        writePackage(pw);

        // print class declaration
        pw.println(getClassModifiers() + getClassText() + getClassName() + ' '
                + getExtendsText() + getImplementsText() + "{");
    }    // writeFileHeader

    /**
     * Write the header comments.
     *
     * @param pw
     * @throws IOException
     */
    protected void writeHeaderComments(PrintWriter pw) throws IOException {

        String localFile = getFileName();
        int lastSepChar = localFile.lastIndexOf(File.separatorChar);

        if (lastSepChar >= 0) {
            localFile = localFile.substring(lastSepChar + 1);
        }

        pw.println("/**");
        pw.println(" * " + localFile);
        pw.println(" *");
        pw.println(" * " + Messages.getMessage("wsdlGenLine00"));
        pw.println(" * "
                + Messages.getMessage("wsdlGenLine01",
                        Version.getVersionText()));
        pw.println(" */");
        pw.println();
    }    // writeHeaderComments

    /**
     * Write the package declaration statement.
     *
     * @param pw
     * @throws IOException
     */
    protected void writePackage(PrintWriter pw) throws IOException {

        final String pkg = getPackage();
        if (pkg != null && pkg.length() > 0) {
            pw.println("package " + pkg + ";");
            pw.println();
        }
    }    // writePackage

    /**
     * Return "public ".  If more modifiers are needed, this method must be
     * overridden.
     *
     * @return
     */
    protected String getClassModifiers() {
        return "public ";
    }    // getClassModifiers

    /**
     * Return "class ".  If "interface " is needed instead, this method must be
     * overridden.
     *
     * @return
     */
    protected String getClassText() {
        return "class ";
    }    // getClassString

    /**
     * Returns the appropriate extends clause.  This default implementation
     * simply returns "", but if you want "extends <class/interface list> "
     * then you must override this method.
     *
     * @return ""
     */
    protected String getExtendsText() {
        return "";
    }    // getExtendsText

    /**
     * Returns the appropriate implements clause.  This default implementation
     * simply returns "", but if you want "implements <interface list> " then
     * you must override this method.
     *
     * @return ""
     */
    protected String getImplementsText() {
        return "";
    }    // getImplementsText

    /**
     * Returns the package name.
     *
     * @return
     */
    protected String getPackage() {
        return packageName;
    }    // getPackage

    /**
     * Returns the class name.
     *
     * @return
     */
    protected String getClassName() {
        return className;
    }    // getClassName

    /**
     * Generate the closing curly brace.
     *
     * @param pw
     * @throws IOException
     */
    protected void writeFileFooter(PrintWriter pw) throws IOException {
        super.writeFileFooter(pw);
        pw.println('}');
    }    // writeFileFooter
}    // abstract class JavaClassWriter


text:
package nom.bdezonia.zorbage.algorithm.resample;

import java.math.BigDecimal;

import nom.bdezonia.zorbage.algebra.ScaleByDouble;
import nom.bdezonia.zorbage.algorithm.GridIterator;
import nom.bdezonia.zorbage.data.DimensionedDataSource;
import nom.bdezonia.zorbage.data.DimensionedStorage;
import nom.bdezonia.zorbage.misc.ThreadingUtils;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.sampling.SamplingIterator;
import nom.bdezonia.zorbage.tuple.Tuple2;
import nom.bdezonia.zorbage.type.real.highprec.HighPrecisionAlgebra;
import nom.bdezonia.zorbage.algebra.Addition;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Allocatable;

/**
 *
 * @author Barry DeZonia
 *
 */
public class ResampleLinear {

	// do not instantiate

	private ResampleLinear() { }

	/**
	 * Linearly resamples one multidim dataset into another multidim dataset using 2 points per axis.
	 * The algorithm computes a series of linear interpolated values, 1 per dimension, from the two
	 * nearest points along that dimension. Then that series of values is averaged.
	 * Note: The input datasource should be padded. This algorithm can poke outside the input boundaries.
	 *
	 * @param alg
	 * @param newDims
	 * @param input
	 * @param maxPieces
	 * @return
	 */
	public static <T extends Algebra<T,U> & Addition<U> & ScaleByDouble<U>,
					U extends Allocatable<U>>
		DimensionedDataSource<U> compute(T alg, long[] newDims, DimensionedDataSource<U> input, int maxPieces)
	{
		int numD = input.numDimensions();

		if (newDims.length != numD)
			throw new IllegalArgumentException("mismatched dims in Resample");

		U value = alg.construct();

		DimensionedDataSource<U> output = DimensionedStorage.allocate(input.storageType(), value, newDims);

		int index = -1;
		long maxDim = -1;
		for (int i = 0; i < numD; i++) {
			long dim = newDims[i];
			if (dim > maxDim) {
				index = i;
				maxDim = dim;
			}
		}
		if (maxDim <= 0)
			throw new IllegalArgumentException("invalid data dimensions");

		Tuple2<Integer,Long> arrangement =
				ThreadingUtils.arrange(numD,
										input.rawData().accessWithOneThread() ||
										output.rawData().accessWithOneThread());
		int pieces = arrangement.a();
		long elemsPerPiece = arrangement.b();

		final Thread[] threads = new Thread[pieces];
		long start = 0;
		for (int i = 0; i < pieces; i++) {
			long[] min = new long[numD];
			long[] max = new long[numD];
			for (int j = 0; j < numD; j++) {
				max[j] = newDims[j] - 1;
			}
			long end;
			// last piece?
			if (i == pieces-1) {
				end = maxDim-1;
			}
			else {
				end = start + elemsPerPiece - 1;
			}
			min[index] = start;
			max[index] = end;
			Computer<T,U> computer = new Computer<T,U>(alg, newDims, min, max, input, output);
			threads[i] = new Thread(computer);
			start = end + 1;
		}

		for (int i = 0; i < threads.length; i++) {
			threads[i].start();
		}

		for (int i = 0; i < threads.length; i++) {
			try {
				threads[i].join();
			} catch(InterruptedException e) {
				throw new IllegalArgumentException("Thread execution error in ParallelResampler");
			}
		}

		return output;
	}

	private static class Computer<T extends Algebra<T,U> & Addition<U> & ScaleByDouble<U>, U> implements Runnable {

		private final int numD;
		private final long[] newDims;
		private final long[] min;
		private final long[] max;
		private final T alg;
		private final DimensionedDataSource<U> input;
		private final DimensionedDataSource<U> output;

		public Computer(T alg, long[] newDims, long[] min, long[] max, DimensionedDataSource<U> input, DimensionedDataSource<U> output) {
			this.numD = newDims.length;
			this.newDims = newDims;
			this.min = min;
			this.max = max;
			this.alg = alg;
			this.input = input;
			this.output = output;
		}

		@Override
		public void run() {
			U value = alg.construct();
			IntegerIndex inputPoint = new IntegerIndex(numD);
			IntegerIndex outputPoint = new IntegerIndex(numD);
			long[] inputDims = new long[numD];
			for (int i = 0; i < numD; i++) {
				inputDims[i] = input.dimension(i);
			}
			SamplingIterator<IntegerIndex> iter = GridIterator.compute(min, max);
			while (iter.hasNext()) {
				iter.next(outputPoint);
				computeValue(alg, input, inputDims, inputPoint, newDims, outputPoint, value);
				output.set(outputPoint, value);
			}
		}

		private void computeValue(T alg, DimensionedDataSource<U> input, long[] inputDims, IntegerIndex inputPoint,
								long[] outputDims, IntegerIndex outputPoint, U outVal)
		{
			int numD = inputDims.length;

			BigDecimal[] coords = new BigDecimal[numD];

			// find the in between point
			for (int i = 0; i < numD; i++) {
				coords[i] = BigDecimal.valueOf(outputPoint.get(i));
				coords[i] = coords[i].divide(BigDecimal.valueOf(outputDims[i]-1),HighPrecisionAlgebra.getContext());
				coords[i] = coords[i].multiply(BigDecimal.valueOf(inputDims[i]-1));
			}

			// get the base coord
			for (int i = 0; i < numD; i++) {
				inputPoint.set(i, coords[i].longValue());
			}

			// must find the various points and do a sum
			alg.zero().call(outVal);
			sum(alg, input, numD, coords, inputPoint, outVal);

			// now turn sum into average
			double scale = 1.0 / numD;
			alg.scaleByDouble().call(scale, outVal, outVal);
		}

		private void sum(T alg, DimensionedDataSource<U> input, int numD, BigDecimal[] coords,
								IntegerIndex inputPoint, U outVal)
		{
			U tmp = alg.construct();

			for (int i = 0; i < numD; i++) {

				// calc t
				BigDecimal t = coords[i].remainder(BigDecimal.ONE);

				// calc "left" point's contribution
				inputPoint.set(i, inputPoint.get(i)); // treat current cell as "left"
				input.get(inputPoint, tmp);
				double scale = 1.0 - t.doubleValue();
				alg.scaleByDouble().call(scale, tmp, tmp);

				// add to sum
				alg.add().call(outVal, tmp, outVal);

				// calc "right" point's contribution
				inputPoint.set(i, inputPoint.get(i) + 1); // go "right" 1 cell
				input.get(inputPoint, tmp);
				scale = t.doubleValue();
				alg.scaleByDouble().call(scale, tmp, tmp);

				// add to sum
				alg.add().call(outVal, tmp, outVal);

				// reset point
				inputPoint.set(i, inputPoint.get(i) - 1); // undo go "right"
			}
		}
	}
}


text:
Server = "Ladle"
ServerVersion = "0.1.2"

-- load required modules
socket = require('socket')

-- load server components
ladleutil = require('ladleutil')

-- load configuration file
-- TODO: have a default array with config and merge with the loaded one
if ladleutil.fileExists('config.lua') then
	config = require('config')
else
	config = nil
end

-- load extensions
extensions = {}

function getHandler(request)
	local handler = nil
	for k,ext in pairs(extensions) do
		if ext["id"] ~= "generic" and ext.match(request["uri"])
		then
			handler = ext.handler
			break
		end
	end
	-- no specific match, use generic handler
	if not handler
	then
		handler = extensions["generic"].handler
	end
	return handler
end

-- checks whether the root index file is requested and finds an appropriate
-- one if needed
function checkURI(uri)
	-- if index file was requested
	-- loop til' the first index.* file found
	if(uri == "")
	then
		if ladleutil.fileExists(config["webroot"] .. "index.html")
		then
			uri = "index.html"
		else
			local wrootIndex = ladleutil.scandir(config["webroot"])
			local chosenIndex = ""

			for k,v in pairs(wrootIndex) do
			if v:match("^index.*")
			then
				chosenIndex = "" .. v
				break
			end
			end
			uri = chosenIndex
		end
	end
	return uri
end

function serve(request, client)

	request["uri"] = checkURI(request["uri"])

	-- find an appropriate handler in extensions
	local handler = getHandler(request)

	-- Got a handler, run it
	handler(request, client, config)

	-- done with client, close request
	client:close()
end

function clientHandler(client)
	-- set timeout - 1 minute.
	client:settimeout(60)
	-- receive request from client
	local request_text, err = ladleutil.receiveHTTPRequest(client)

	-- if there's no error, begin serving content or kill server
	if not err then
		-- parse request
		local request = ladleutil.parseRequest(request_text)
		-- run a prep [e.g. for POST with files - download files]
		ladleutil.prepMain(request, client)
		-- begin serving content
		serve(request, client)
	end
end

-- TODO: maybe implement keepalive?
function waitReceive(server)
	-- loop while waiting for a client request
	while 1 do
		-- accept a client request
		local client = server:accept()
		clientHandler(client)
	end
end

function loadExtensions()
	local extdir = "extensions/"
	local files = ladleutil.scandir(extdir)
	for i,v in pairs(files) do
		if v:match("^.+%.lua$")
		then
			local extfile = io.open(extdir .. v, "r")
			local extcode
			if extfile
			then
				extcode = extfile:read("*all")
			end

			if extcode
			then
				local extf, message = load(extcode)
				if not message
				then
					local ext = extf()
					extensions[ext['id']] = ext
					ladleutil.trace(("Extension %q loaded successfully"):format(ext['name']))
				else
					ladleutil.trace(("Failed to load extension %s: %q"):format(v, message))
				end
			end
		end
	end
end

-- start web server
function main(arg1)
	loadExtensions()

	-- command line argument overrides config file entry:
	local port = arg1
	-- if no port specified on command line, use config entry:
	if port == nil then port = config['port'] end
	-- if still no port, fall back to default port, 80:
	if port == nil then port = 80 end

	-- load hostname from config file:
	local hostname = config['hostname']
	if hostname == nil then hostname = '*' end -- fall back to default

	if config["webroot"] == "" or config["webroot"] == nil
	then
		config["webroot"] = "www/"
	end

	-- display initial program information
	ladleutil.trace(("%s web server v%s"):format(Server,ServerVersion))
	ladleutil.trace("Copyright (c) 2008 Samuel Saint-Pettersen")
	ladleutil.trace("Copyright (c) 2015 Daniel Rempel")

	-- create tcp socket on localhost:$port
	local server = socket.bind(hostname, port)
	if not server
	then
		ladleutil.trace("Failed to bind to given hostname:port")
		os.exit(1)
	end

	-- display message to web server is running
	ladleutil.trace(("Serving on %s:%d"):format(hostname,port))
	waitReceive(server) -- begin waiting for client requests
end

-- invoke program starting point:
-- parameter is command-line argument for port number
main(arg[1])


text:
package com.haxademic.demo.draw.color;

import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.app.config.AppSettings;
import com.haxademic.core.app.config.Config;
import com.haxademic.core.debug.DebugView;
import com.haxademic.core.draw.color.ColorUtil;
import com.haxademic.core.draw.color.EasingColor;
import com.haxademic.core.render.FrameLoop;
import com.haxademic.core.ui.UI;

public class Demo_EasingColor
extends PAppletHax {
	public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	protected EasingColor colorHaxEasing;
	protected String EASING = "EASING";

	protected void config() {
		Config.setProperty( AppSettings.WIDTH, 640 );
		Config.setProperty( AppSettings.HEIGHT, 640 );
		Config.setProperty( AppSettings.SHOW_UI, true );
	}

	protected void firstFrame() {
		// init easing color obj in various ways
//		colorHaxEasing = new EasingColor("#00ff00", 10);
//		colorHaxEasing = new EasingColor(0x00ff00, 10);
//		colorHaxEasing = new EasingColor("#ff00ff00", 10);
//		colorHaxEasing = new EasingColor(0, 255, 0, 255);
		colorHaxEasing = new EasingColor(0, 255, 0);

		// add UI
		UI.addSlider(EASING, 0.2f, 0.001f, 10, 0.001f, false);
	}

	protected void drawApp() {
		// change color on interval
		if(FrameLoop.frameModLooped(120)) {
			int newColor = ColorUtil.colorFromHex(ColorUtil.randomHex());
			colorHaxEasing.setTargetInt(newColor);
			DebugView.setValue("newHex", newColor);
		}

		// update easing from UI & color object
		DebugView.setValue("colorHaxEasing.isComplete()", colorHaxEasing.isComplete());
		colorHaxEasing.setEaseFactor(UI.value(EASING));
		colorHaxEasing.update();

		// draw color
		float padding = 100;
		p.background(0);
		p.fill(colorHaxEasing.colorInt());
		p.rect(padding, padding, p.width - padding * 2, p.height - padding * 2);
	}

}


text:
using System;
using BudgetAnalyser.Engine.Budget;
using BudgetAnalyser.Engine.Ledger;
using BudgetAnalyser.Engine.Statement;
using JetBrains.Annotations;

namespace BudgetAnalyser.Engine.Widgets
{
    /// <summary>
    ///     Exports summarised data from Ledger and Transactions to a file and uploads it to web storage.
    /// </summary>
    /// <seealso cref="BudgetAnalyser.Engine.Widgets.Widget" />
    public sealed class UpdateMobileDataWidget : Widget
    {
        private const string WidgetLabel = "Upload mobile data";

        /// <summary>
        ///     Initializes a new instance of the <see cref="CurrentFileWidget" /> class.
        /// </summary>
        public UpdateMobileDataWidget()
        {
            Category = WidgetGroup.MonthlyTrackingSectionName;
            Dependencies = new[] { typeof(LedgerBook), typeof(StatementModel), typeof(BudgetCollection), typeof(GlobalFilterCriteria) };
            DetailedText = WidgetLabel;
            Sequence = 10;
            Clickable = true;
            Enabled = false;
            ImageResourceName = "MobileImage";
        }

        /// <summary>
        ///     The current Budget Collection held by this widget
        /// </summary>
        public BudgetCollection BudgetCollection { get; private set; }

        /// <summary>
        ///     The current filter as held by this widget
        /// </summary>
        public GlobalFilterCriteria Filter { get; private set; }

        /// <summary>
        ///     The current Ledger Book held by this widget
        /// </summary>
        public LedgerBook LedgerBook { get; private set; }

        /// <summary>
        ///     The current Statement Model held by this widget
        /// </summary>
        public StatementModel StatementModel { get; private set; }

        private bool lockActive = false;

        /// <summary>
        /// This method is used to disable the widget while upload is active.
        /// </summary>
        public void LockWhileUploading(bool @lock)
        {
            this.lockActive = @lock;
            Enabled = !this.lockActive;
            DetailedText = this.lockActive ? "Uploading..." : WidgetLabel;
        }

        /// <summary>
        ///     Updates the widget with new input.
        /// </summary>
        /// <exception cref="System.ArgumentNullException"></exception>
        public override void Update([NotNull] params object[] input)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            Enabled = false;

            if (!ValidateUpdateInput(input)) return;

            LedgerBook = (LedgerBook) input[0];
            StatementModel = (StatementModel) input[1];
            BudgetCollection = (BudgetCollection) input[2];
            Filter = (GlobalFilterCriteria) input[3];

            if (LedgerBook == null || StatementModel == null || BudgetCollection == null || Filter == null) return;

            Enabled = true;
        }
    }
}


text:
layout: post
title:  "Singleton pattern"
date:   2016-02-09 13:00:00
author: Ludo Bermejo
categories: Patterns
tags:	patterns
cover:  "assets/singleton-pattern.jpg"
---

Oh my! I totally forgot this pattern, one of the most used in interviews :D

With this pattern you can reduce the amount of instances of a particular object. You will use only one. And this one instance is called singleton. This pattern was usually used in the past but now it's a little obsolete, cos in the present we a are using `Module pattern` and `Dependency injection` patterns in javascript. But I suppose it can be useful in some scenarios.

Now, how can we create a singleton object in javascript?

    var DarthVader = (function () {
        var instance;
        function create() {
            var random = Math.round(Math.random()*1000);
            function whatDoYouThinkAboutYoda() {
                return "it's a nasty greeny thing";
            }
            function whatDoYouThinkAboutLuke() {
                return "i'm his father";
            }
            function giveMeARandomNumber() {
                return random;
            }
            return {

                whatDoYouThinkAboutYoda: whatDoYouThinkAboutYoda,
                whatDoYouThinkAboutLuke: whatDoYouThinkAboutLuke,
                giveMeARandomNumber: giveMeARandomNumber
            }
        }

        return {
            getInstance: function () {
                if (!instance) {
                    instance = create();
                }
                return instance;
            }
        };
    })();

    var darthVader1 = DarthVader.getInstance();
    var darthVader2 = DarthVader.getInstance();

    console.log("YODA: " + darthVader1.whatDoYouThinkAboutYoda());
    console.log("LUKE: " + darthVader2.whatDoYouThinkAboutLuke());

    console.log("Darth 1, GIVE ME A RANDOM NUMBER: " + darthVader1.giveMeARandomNumber());
    console.log("Darth 2, GIVE ME A RANDOM NUMBER: " + darthVader1.giveMeARandomNumber());

Ok, this is the result of this script:

    YODA: it's a nasty greeny thing
    LUKE: i'm his father
    Darth 1, GIVE ME A RANDOM NUMBER: 229
    Darth 2, GIVE ME A RANDOM NUMBER: 229

As you can see, Darth 1 and Darth 2 returns exactly the same number. That's not because they are clones, but because they are exactly the same object!

TADAAAA!!!


text:
<?php

Prado::using('System.Web.UI.TForm');

/**
 * @package System.Web.UI
 */
class TFormTest extends PHPUnit_Framework_TestCase {

	public function testOnInit() {
		throw new PHPUnit_Framework_IncompleteTestError();
	}

	public function testRender() {
		throw new PHPUnit_Framework_IncompleteTestError();
	}

	public function testSetAndGetDefaultButton() {
		throw new PHPUnit_Framework_IncompleteTestError();
	}

	public function testSetAndGetMethod() {
		throw new PHPUnit_Framework_IncompleteTestError();
	}

	public function testSetAndGetEnctype() {
		throw new PHPUnit_Framework_IncompleteTestError();
	}

	public function testGetName() {
		throw new PHPUnit_Framework_IncompleteTestError();
	}

}


text:
class CommentsScenario < Scenario::Base
  uses :pages

  def load
    create_record Comment, :first, :page_id => 1, :author => 'Jim Gay', :author_email => 'test@spec.com', :content => "That's all I have to say about that."
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Egatea 17: 6 (1932)

#### Original name
Hydnum denticulatum var. brasiliense Rick

### Remarks
null


text:
using Mordo.Desktop.MessageProcessing;
using Mordo.Utils;
using System;

namespace Mordo.Desktop.ViewModels
{
    partial class MainViewModel
    {
        public RelayCommand ConnectCommand { get; set; }
        public RelayCommand DisconnectCommand { get; set; }
        public RelayCommand SendStartAutoCommand { get; set; }
        public RelayCommand SendStopAutoCommand { get; set; }
        public RelayCommand SendResetCommand { get; set; }
        public RelayCommand SendManualCommand { get; set; }
        public RelayCommand SendOpenFrameCommand { get; set; }
        public RelayCommand SendCloseFrameCommand { get; set; }
        public RelayCommand SendManualForwardCommand { get; set; }
        public RelayCommand SendManualRightCommand { get; set; }
        public RelayCommand SendManualBackwardCommand { get; set; }
        public RelayCommand SendManualLeftCommand { get; set; }
        public RelayCommand SendManualStopCommand { get; set; }
        public RelayCommand SendPidForwardCommand { get; set; }
        public RelayCommand SendPidBackwardCommand { get; set; }
        public RelayCommand SendPidWheelVelocityCommand { get; set; }
        public RelayCommand SendPidKtir { get; set; }
        public RelayCommand SendPwmCommand { get; set; }
        public RelayCommand SendStopFastCommand { get; set; }
        public RelayCommand SendStopSlowCommand { get; set; }
        public RelayCommand SendPidSettingsCommand { get; set; }

        public void RegisterCommands()
        {
            ConnectCommand = new RelayCommand(ExecuteConnectCommand, CanExecuteConnectCommand);
            DisconnectCommand = new RelayCommand(ExecuteDisconnectCommand, CanExecuteDisconnectCommand);
            SendStartAutoCommand = SendMessageCommand(b => b.StartAuto());
            SendStopAutoCommand = SendMessageCommand(b => b.StopAuto());
            SendResetCommand = SendMessageCommand(b => b.Reset());
            SendManualCommand = SendMessageCommand(b => b.Manual());
            SendOpenFrameCommand = SendMessageCommand(b => b.OpenFrame());
            SendCloseFrameCommand = SendMessageCommand(b => b.CloseFrame());
            SendManualForwardCommand = SendMessageCommand(b => b.ManualForward());
            SendManualRightCommand = SendMessageCommand(b => b.ManualRight());
            SendManualBackwardCommand = SendMessageCommand(b => b.ManualBackward());
            SendManualLeftCommand = SendMessageCommand(b => b.ManualLeft());
            SendManualStopCommand = SendMessageCommand(b => b.ManualStop());
            SendPidForwardCommand = SendMessageCommand(b => b.DrivePidForward(CommandSettings.PidForward));
            SendPidBackwardCommand = SendMessageCommand(b => b.DrivePidBackward(CommandSettings.PidBackward));
            SendPidWheelVelocityCommand = SendMessageCommand(b => b.DriveConsantWheelVelocity(CommandSettings.VelocityLeft, CommandSettings.VelocityRight));
            SendPidKtir = SendMessageCommand(b => b.SideKtir());
            SendPwmCommand = SendMessageCommand(b => b.Pwm(CommandSettings.PwmL, CommandSettings.PwmR));
            SendStopFastCommand = SendMessageCommand(b => b.StopFast());
            SendStopSlowCommand = SendMessageCommand(b => b.StopSlow());
            SendPidSettingsCommand = SendMessageCommand(b => b.SetSettings());
        }

        public RelayCommand SendMessageCommand(Func<IMessageBuilder, string> func)
        {
            return new RelayCommand(
                o =>
                {
                    var msg = func(_messageBuilder);
                    _communicator.SendMessage(msg);
                },
                o => _communicator.IsConnected);
        }

        private bool CanExecuteDisconnectCommand(object o)
        {
            return _communicator.IsConnected;
        }

        private void ExecuteDisconnectCommand(object o)
        {
            _communicator.Disconnect();
        }

        private bool CanExecuteConnectCommand(object o)
        {
            return !_communicator.IsConnected
                && ConnectionSettings.BaudRate > 0
                && ! string.IsNullOrWhiteSpace(ConnectionSettings.Port);
        }

        private void ExecuteConnectCommand(object o)
        {
            _communicator.Connect(ConnectionSettings.BaudRate, ConnectionSettings.Port);
        }
    }
}


text:
@interface ARCSolidFillStyle : ARCStyle {
  UIColor* _color;
}

@property (nonatomic, retain) UIColor* color;

+ (ARCSolidFillStyle*)styleWithColor:(UIColor*)color next:(ARCStyle*)next;

@end


text:
<?php
/**
 * An helper file for your Eloquent Models
 * Copy the phpDocs from this file to the correct Model,
 * And remove them from this file, to prevent double declarations.
 *
 * @author Barry vd. Heuvel <barryvdh@gmail.com>
 */


text:
package org.jkiss.dbeaver.ext.mockdata.model;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;
import org.jkiss.utils.CommonUtils;

import java.util.*;

public class MockGeneratorRegistry
{
    static final String TAG_GENERATOR = "generator"; //$NON-NLS-1$

    public static final String FK_GENERATOR_ID = "fkGenerator"; //$NON-NLS-1$

    private static final Log log = Log.getLog(MockGeneratorRegistry.class);

    private static MockGeneratorRegistry instance = null;

    public synchronized static MockGeneratorRegistry getInstance()
    {
        if (instance == null) {
            instance = new MockGeneratorRegistry();
            instance.loadExtensions(Platform.getExtensionRegistry());
        }
        return instance;
    }

    private final List<MockGeneratorDescriptor> generators = new ArrayList<>();

    private MockGeneratorRegistry()
    {
    }

    private void loadExtensions(IExtensionRegistry registry)
    {
        Set<String> replacedSet = new HashSet<>();

        IConfigurationElement[] extConfigs = registry.getConfigurationElementsFor(MockGeneratorDescriptor.EXTENSION_ID);
        for (IConfigurationElement ext : extConfigs) {
            // Load functions
            if (TAG_GENERATOR.equals(ext.getName())) {
                MockGeneratorDescriptor generatorDescriptor = new MockGeneratorDescriptor(ext);
                this.generators.add(generatorDescriptor);

                String[] replaces = generatorDescriptor.getReplaces();
                if (replaces != null) {
                    replacedSet.addAll(Arrays.asList(replaces));
                }

                if (!CommonUtils.isEmpty(generatorDescriptor.getPresets())) {
                    for (MockGeneratorDescriptor.Preset preset : generatorDescriptor.getPresets()) {
                        this.generators.add(new MockGeneratorDescriptor(ext, preset));
                    }
                }
            }
        }

        for (String replaced : replacedSet) {
            MockGeneratorDescriptor generator = getGenerator(replaced);
            if (generator != null) {
                this.generators.remove(generator);
            }
        }
    }

    public void dispose()
    {
        generators.clear();
    }

    /**
     * Find generator by data source and some typed object (e.g. attribute)
     */
    @Nullable
    public MockGeneratorDescriptor findGenerator(DBPDataSource dataSource, DBSTypedObject typedObject) {
        for (MockGeneratorDescriptor descriptor : generators) {

            if (((!descriptor.isGlobal() && descriptor.supportsDataSource(dataSource) && descriptor.supportsType(typedObject)) ||
                    (descriptor.isGlobal() && descriptor.supportsType(typedObject))))
            {
                return descriptor;
            }
        }
        return null;
    }

    public List<MockGeneratorDescriptor> findAllGenerators(DBPDataSource dataSource, DBSTypedObject typedObject) {

        List<MockGeneratorDescriptor> result = new ArrayList<>();
        for (MockGeneratorDescriptor descriptor : generators) {
            if (FK_GENERATOR_ID.equalsIgnoreCase(descriptor.getId())) {
                continue;
            }

            if (((!descriptor.isGlobal() && descriptor.supportsDataSource(dataSource) && descriptor.supportsType(typedObject)) ||
                (descriptor.isGlobal() && descriptor.supportsType(typedObject))))
            {
                result.add(descriptor);
            }
        }
        return result;
    }

    /**
     * Find generator by id
     */
    public MockGeneratorDescriptor getGenerator(String id) {
        for (MockGeneratorDescriptor descriptor : generators) {
            if (id.equals(descriptor.getId())) {
                return descriptor;
            }
        }
        return null;
    }

}


text:
package org.elasticsearch.xpack.ml.inference.pytorch.process;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class PyTorchProcessManager {

    private static final Logger logger = LogManager.getLogger(PyTorchProcessManager.class);

    public PyTorchProcessManager() {

    }

    public void start(String taskId) {

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WIQuest.Web.Areas.Admin.Models
{
    public class TrainingExerciseEditModel
    {
        public Guid ExerciseId { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public Guid QuizId { get; set; }

        public bool IsAvailable { get; set; }

        public string FromDate { get; set; }

        public string FromTime { get; set; }

        public string UntilDate { get; set; }

        public string UntilTime { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"-->
              <!--android:layout_width="match_parent"-->
              <!--android:layout_height="match_parent"-->
              <!--android:orientation="vertical"-->
              <!--android:gravity="top">-->

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_refresh_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView" />

</android.support.v4.widget.SwipeRefreshLayout>
<!--</LinearLayout>-->


text:
import json
import logging

from django.http import Http404
from django.utils.functional import wraps
from django.utils.translation import ugettext as _

from desktop.lib.django_util import JsonResponse
from desktop.lib.exceptions_renderable import PopupException
from desktop.lib.i18n import force_unicode

from spark.models import QueryExpired, QueryError, SessionExpired
from desktop.models import Document2, Document

LOG = logging.getLogger(__name__)

def check_document_access_permission():
  def inner(view_func):
    def decorate(request, *args, **kwargs):
      notebook_id = request.GET.get('notebook')
      if not notebook_id:
        notebook_id = json.loads(request.POST.get('notebook', '{}')).get('id')

      try:
        if notebook_id:
          document = Document2.objects.get(id=notebook_id)
          document.doc.get().can_read_or_exception(request.user)
      except Document2.DoesNotExist:
        raise PopupException(_('Document %(id)s does not exist') % {'id': notebook_id})

      return view_func(request, *args, **kwargs)
    return wraps(view_func)(decorate)
  return inner

def check_document_modify_permission():
  def inner(view_func):
    def decorate(request, *args, **kwargs):
      notebook = json.loads(request.POST.get('notebook', '{}'))

      try:
        if notebook.get('id'):
          doc2 = Document2.objects.get(id=notebook['id'])
          doc2.doc.get().can_write_or_exception(request.user)
      except Document.DoesNotExist:
        raise PopupException(_('Job %(id)s does not exist') % {'id': notebook.get('id')})

      return view_func(request, *args, **kwargs)
    return wraps(view_func)(decorate)
  return inner

def api_error_handler(func):
  def decorator(*args, **kwargs):
    response = {}

    try:
      return func(*args, **kwargs)
    except SessionExpired, e:
      response['status'] = -2
    except QueryExpired, e:
      response['status'] = -3
    except QueryError, e:
      response['status'] = 1
      response['message'] = force_unicode(str(e))
    except Exception, e:
      response['status'] = -1
      response['message'] = force_unicode(str(e))
    finally:
      if response:
        return JsonResponse(response)

  return decorator

def json_error_handler(view_fn):
  def decorator(*args, **kwargs):
    try:
      return view_fn(*args, **kwargs)
    except Http404, e:
      raise e
    except Exception, e:
      response = {
        'error': str(e)
      }
      return JsonResponse(response, status=500)
  return decorator


text:
//  --------------------------------------------------------------------------------------------------------------------
//  <copyright file="WhenParsingMsTestResultsFileWithMissingTraits.cs" company="PicklesDoc">
//  Copyright 2011 Jeffrey Cameron
//  Copyright 2012-present PicklesDoc team and community contributors
//
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//  </copyright>
//  --------------------------------------------------------------------------------------------------------------------

using System;

using NFluent;

using NUnit.Framework;

using PicklesDoc.Pickles.ObjectModel;
using PicklesDoc.Pickles.TestFrameworks.MsTest;

namespace PicklesDoc.Pickles.TestFrameworks.UnitTests.MsTest
{
    [TestFixture]
    public class WhenParsingMsTestResultsFileWithMissingTraits : WhenParsingTestResultFiles<MsTestResults>
    {
        public WhenParsingMsTestResultsFileWithMissingTraits()
            : base("MsTest." + "results-example-mstest-missingTraits.trx")
        {
        }

        [Test]
        public void ThenCanReadFeatureResultWithoutThrowingException()
        {
            // Write out the embedded test results file
            var results = ParseResultsFile();

            var feature = new Feature { Name = "Addition" };

            Check.ThatCode(() => results.GetFeatureResult(feature)).DoesNotThrow();
        }
    }
}


text:
namespace base {
namespace test {
class ScopedFeatureList;
}  // namespace test
}  // namespace base

namespace content {

void InitAndEnableRenderDocumentFeature(
    base::test::ScopedFeatureList* feature_list,
    std::string level);

// The list of values to test for the "level" parameter.
std::vector<std::string> RenderDocumentFeatureLevelValues();

// Returns the name for |render_document_level| that's valid for test params
// (only contains alphanumeric characters or underscores).
std::string GetRenderDocumentLevelNameForTestParams(
    std::string render_document_level);

}  // namespace content

#endif  // CONTENT_TEST_RENDER_DOCUMENT_FEATURE_H_


text:
[%# DO NOT EDIT THIS FILE: generated from perlfaq (https://github.com/perl-doc-cats/perlfaq) -%]
    [%-
        # Used to get info from htmlify to ttree
        page.import({
            title    => "perlfaq1",
            section  => "faq",
            description
                => "Perl Frequently Asked Questions, Perl FAQ",
            keywords => "perl, perl faq, perlfaq"
        });
        perlfaq_version = 5.021011;
    -%]

NAME

VERSION

DESCRIPTION

What is Perl?

Who supports Perl? Who develops it? Why is it free?

Which version of Perl should I use?

What are Perl 4, Perl 5, or Perl 6?

What is Perl 6?

How stable is Perl?

How often are new versions of Perl released?

Is Perl difficult to learn?

How does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl?

Can I do [task] in Perl?

When shouldn't I program in Perl?

What's the difference between "perl" and "Perl"?

What is a JAPH?

How can I convince others to use Perl?

AUTHOR AND COPYRIGHT

NAME

perlfaq1 - General Questions About Perl

VERSION

version 5.021011

DESCRIPTION

This section of the FAQ answers very general, high-level questions about Perl.

What is Perl?

Perl is a high-level programming language with an eclectic heritage written by Larry Wall and a cast of thousands.

Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving quick prototyping, system utilities, software tools, system management tasks, database access, graphical programming, networking, and web programming.

Perl derives from the ubiquitous C programming language and to a lesser extent from sed, awk, the Unix shell, and many other tools and languages.

These strengths make it especially popular with web developers and system administrators. Mathematicians, geneticists, journalists, managers and many other people also use Perl.

Who supports Perl? Who develops it? Why is it free?

The original culture of the pre-populist Internet and the deeply-held beliefs of Perl's author, Larry Wall, gave rise to the free and open distribution policy of Perl. Perl is supported by its users. The core, the standard Perl library, the optional modules, and the documentation you're reading now were all written by volunteers.

The core development team (known as the Perl Porters) are a group of highly altruistic individuals committed to producing better software for free than you could hope to purchase for money. You may snoop on pending developments via the archives or read the faq, or you can subscribe to the mailing list by sending perl5-porters-subscribe@perl.org a subscription request (an empty message with no subject is fine).

While the GNU project includes Perl in its distributions, there's no such thing as "GNU Perl". Perl is not produced nor maintained by the Free Software Foundation. Perl's licensing terms are also more open than GNU software's tend to be.

You can get commercial support of Perl if you wish, although for most users the informal support will more than suffice. See the answer to "Where can I buy a commercial version of Perl?" for more information.

Which version of Perl should I use?

(contributed by brian d foy)

There is often a matter of opinion and taste, and there isn't any one answer that fits everyone. In general, you want to use either the current stable release, or the stable release immediately prior to that one. Currently, those are perl5.18.x and perl5.16.x, respectively.

Beyond that, you have to consider several things and decide which is best for you.

If things aren't broken, upgrading perl may break them (or at least issue new warnings).

The latest versions of perl have more bug fixes.

The Perl community is geared toward supporting the most recent releases, so you'll have an easier time finding help for those.

Versions prior to perl5.004 had serious security problems with buffer overflows, and in some cases have CERT advisories (for instance, http://www.cert.org/advisories/CA-1997-17.html ).

The latest versions are probably the least deployed and widely tested, so you may want to wait a few months after their release and see what problems others have if you are risk averse.

The immediate, previous releases (i.e. perl5.14.x ) are usually maintained for a while, although not at the same level as the current releases.

No one is actively supporting Perl 4. Ten years ago it was a dead camel carcass (according to this document). Now it's barely a skeleton as its whitewashed bones have fractured or eroded.

There are really two tracks of perl development: a maintenance version and an experimental version. The maintenance versions are stable, and have an even number as the minor release (i.e. perl5.18.x, where 18 is the minor release). The experimental versions may include features that don't make it into the stable versions, and have an odd number as the minor release (i.e. perl5.19.x, where 19 is the minor release).

What are Perl 4, Perl 5, or Perl 6?

In short, Perl 4 is the parent to both Perl 5 and Perl 6. Perl 5 is the older sibling, and though they are different languages, someone who knows one will spot many similarities in the other.

The number after Perl (i.e. the 5 after Perl 5) is the major release of the perl interpreter as well as the version of the language. Each major version has significant differences that earlier versions cannot support.

The current major release of Perl is Perl 5, first released in 1994. It can run scripts from the previous major release, Perl 4 (March 1991), but has significant differences.

Perl 6 is a reinvention of Perl, it is a language in the same lineage but not compatible. The two are complementary, not mutually exclusive. Perl 6 is not meant to replace Perl 5, and vice versa. See "What is Perl 6?" below to find out more.

See perlhist for a history of Perl revisions.

What is Perl 6?

Perl 6 was originally described as the community's rewrite of Perl 5, however as the language evolved, it became clear that it is a separate language, but in the same language family as Perl 5.

Perl 6 is not intended primarily as a replacement for Perl 5, but as its own thing - and libraries exist to allow you to call Perl 5 code from Perl 6 programs and vice versa.

Contrary to popular belief, Perl 6 and Perl 5 peacefully coexist with one another. Perl 6 has proven to be a fascinating source of ideas for those using Perl 5 (the Moose object system is a well-known example). There is overlap in the communities, and this overlap fosters the tradition of sharing and borrowing that have been instrumental to Perl's success.

If you want to learn more about Perl 6 read the Perl 6 developers page at http://www.perl6.org/ and get involved.

"We're really serious about reinventing everything that needs reinventing." --Larry Wall

How stable is Perl?

Production releases, which incorporate bug fixes and new functionality, are widely tested before release. Since the 5.000 release, we have averaged about one production release per year.

The Perl development team occasionally make changes to the internal core of the language, but all possible efforts are made toward backward compatibility.

How often are new versions of Perl released?

Recently, the plan has been to release a new version of Perl roughly every April, but getting the release right is more important than sticking rigidly to a calendar date, so the release date is somewhat flexible. The historical release dates can be viewed at http://www.cpan.org/src/README.html.

Even numbered minor versions (5.14, 5.16, 5.18) are production versions, and odd numbered minor versions (5.15, 5.17, 5.19) are development versions. Unless you want to try out an experimental feature, you probably never want to install a development version of Perl.

The Perl development team are called Perl 5 Porters, and their organization is described at http://perldoc.perl.org/perlpolicy.html. The organizational rules really just boil down to one: Larry is always right, even when he was wrong.

Is Perl difficult to learn?

No, Perl is easy to start learning --and easy to keep learning. It looks like most programming languages you're likely to have experience with, so if you've ever written a C program, an awk script, a shell script, or even a BASIC program, you're already partway there.

Most tasks only require a small subset of the Perl language. One of the guiding mottos for Perl development is "there's more than one way to do it" (TMTOWTDI, sometimes pronounced "tim toady"). Perl's learning curve is therefore shallow (easy to learn) and long (there's a whole lot you can do if you really want).

Finally, because Perl is frequently (but not always, and certainly not by definition) an interpreted language, you can write your programs and test them without an intermediate compilation step, allowing you to experiment and test/debug quickly and easily. This ease of experimentation flattens the learning curve even more.

Things that make Perl easier to learn: Unix experience, almost any kind of programming experience, an understanding of regular expressions, and the ability to understand other people's code. If there's something you need to do, then it's probably already been done, and a working example is usually available for free. Don't forget Perl modules, either. They're discussed in Part 3 of this FAQ, along with CPAN, which is discussed in Part 2.

How does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl?

Perl can be used for almost any coding problem, even ones which require integrating specialist C code for extra speed. As with any tool it can be used well or badly. Perl has many strengths, and a few weaknesses, precisely which areas are good and bad is often a personal choice.

When choosing a language you should also be influenced by the resources, testing culture and community which surrounds it.

For comparisons to a specific language it is often best to create a small project in both languages and compare the results, make sure to use all the resources of each language, as a language is far more than just it's syntax.

Can I do [task] in Perl?

Perl is flexible and extensible enough for you to use on virtually any task, from one-line file-processing tasks to large, elaborate systems.

For many people, Perl serves as a great replacement for shell scripting. For others, it serves as a convenient, high-level replacement for most of what they'd program in low-level languages like C or C++. It's ultimately up to you (and possibly your management) which tasks you'll use Perl for and which you won't.

If you have a library that provides an API, you can make any component of it available as just another Perl function or variable using a Perl extension written in C or C++ and dynamically linked into your main perl interpreter. You can also go the other direction, and write your main program in C or C++, and then link in some Perl code on the fly, to create a powerful application. See perlembed.

That said, there will always be small, focused, special-purpose languages dedicated to a specific problem domain that are simply more convenient for certain kinds of problems. Perl tries to be all things to all people, but nothing special to anyone. Examples of specialized languages that come to mind include prolog and matlab.

When shouldn't I program in Perl?

One good reason is when you already have an existing application written in another language that's all done (and done well), or you have an application language specifically designed for a certain task (e.g. prolog, make).

If you find that you need to speed up a specific part of a Perl application (not something you often need) you may want to use C, but you can access this from your Perl code with perlxs.

What's the difference between "perl" and "Perl"?

"Perl" is the name of the language. Only the "P" is capitalized. The name of the interpreter (the program which runs the Perl script) is "perl" with a lowercase "p".

You may or may not choose to follow this usage. But never write "PERL", because perl is not an acronym.

What is a JAPH?

(contributed by brian d foy)

JAPH stands for "Just another Perl hacker,", which Randal Schwartz used to sign email and usenet messages starting in the late 1980s. He previously used the phrase with many subjects ("Just another x hacker,"), so to distinguish his JAPH, he started to write them as Perl programs:

    print "Just another Perl hacker,";

Other people picked up on this and started to write clever or obfuscated programs to produce the same output, spinning things quickly out of control while still providing hours of amusement for their creators and readers.

CPAN has several JAPH programs at http://www.cpan.org/misc/japh.

How can I convince others to use Perl?

(contributed by brian d foy)

Appeal to their self interest! If Perl is new (and thus scary) to them, find something that Perl can do to solve one of their problems. That might mean that Perl either saves them something (time, headaches, money) or gives them something (flexibility, power, testability).

In general, the benefit of a language is closely related to the skill of the people using that language. If you or your team can be faster, better, and stronger through Perl, you'll deliver more value. Remember, people often respond better to what they get out of it. If you run into resistance, figure out what those people get out of the other choice and how Perl might satisfy that requirement.

You don't have to worry about finding or paying for Perl; it's freely available and several popular operating systems come with Perl. Community support in places such as Perlmonks ( http://www.perlmonks.com ) and the various Perl mailing lists ( http://lists.perl.org ) means that you can usually get quick answers to your problems.

Finally, keep in mind that Perl might not be the right tool for every job. You're a much better advocate if your claims are reasonable and grounded in reality. Dogmatically advocating anything tends to make people discount your message. Be honest about possible disadvantages to your choice of Perl since any choice has trade-offs.

You might find these links useful:

http://www.perl.org/about.html

http://perltraining.com.au/whyperl.html

AUTHOR AND COPYRIGHT

Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.

This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.

Irrespective of its distribution, all code examples here are in the public domain. You are permitted and encouraged to use this code and any derivatives thereof in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit to the FAQ would be courteous but is not required.

Version: 5.021011


text:
#ifndef _WALKEXP_HH
#define _WALKEXP_HH

// ==========================================================================
// WalkExP class
//
// This is the ExperimentRunner derivative, which sets up and runs the batch
// experiments. The current user interface is setup as follows:
//
// Overall, pulling the left level left aborts the experiment batch.
//
// ***** Experiment setup
// - Triggered by pushing the right lever forward
// - Runs the StartupMachine, which calibrates the robot and stands up.
// - The standup machine is configured to use the leg offset adjustments.
//
// ***** Experiment phase
// - Triggered by pushing the right lever forward
// - The robot continuously goes forward, with left right turning control only
// - Also, depending on the offset control mode, the R/C knob gives leg offset
// control
// - The R/C switch, pulled forward starts a timer.
// - The R/C switch, pushed backward stops the timer.
// - The experiment ends when the left lever is pushed forward.
//
// ***** Wrapup phase
// - The wrapup phase uses the Sitmachine to sit down.
// - Once the SitDown is complete, it waits for user input to indicate
//   experiment success or failure.
// - Right lever is pushed right indicated success,
//   pushed left, indicates failure.
// - The wrapup finishes after the user input and the next experiment proceeds.
//

#include "ExpRunner.hh"
#include "WalkMachine.hh"
#include "RHexWalker.hh"
#include "SitMachine.hh"
#include "StartupMachine.hh"
#include "RemoteControl.hh"
#include "PositionControl.hh"
#include "CalibMachine.hh"
#include "AnalogOutput.hh"
#include "EncoderReader.hh"
#include "Hardware.hh"
#include "basicmath.hh"

// delays for the RC sticks ( in seconds )
#define RIGHT_RC_STICK 0
#define RIGHT_RC_XDIAL 1
#define RIGHT_RC_YDIAL 0
#define RIGHT_STICK_DELAY 0.005

#define LEFT_RC_STICK 1
#define LEFT_RC_XDIAL 3
#define LEFT_RC_YDIAL 2
#define LEFT_STICK_DELAY 0.1

// -----------------------------------------------------------------
// TestExperiment class. Provides the body pitch in radians -------

class WalkExp : public ExpRunner {
public:

  WalkExp( ) : ExpRunner( "walkexp", 0 ) { };
  /* Interface to the particular experiment definition ------- */

  /* State change events */
  bool setupBeginCheck( int num );
  bool experimentBeginCheck( int num );
  bool experimentEndCheck( int num );
  bool wrapupEndCheck( int num );
  bool terminateCheck( int num );
  bool abortCheck( int num ); /* Event to abort the batch */
  bool repeatCheck( int num );

  /* State action methods */
  void initEntry( int num );
  void idleEntry( int num );
  void setupEntry( int num );
  void setupDuring( int num );
  void experimentEntry( int num );
  void experimentDuring( int num );
  void experimentExit( int num );
  void wrapupExit( int num );
  void handleAbort( int num );
  void handleRepeat( int num );

  // Module functionality
  void init( void );

  //  void setFilterParams( FilterParam_t *p ) { filterParams = *p; };

  bool walkIsDone( void );
  void setParameterNames( void );
  void computeParameterValues( uint num );

private:

  // Modules used by the WalkExp
  StartupMachine * sm;
  SitMachine * sitm;
  WalkMachine * wm;
  RHexWalker * rw;
  RemoteControl *rc;
  Hardware * hw;
  CalibMachine *calib[6];

  // Mark for timing
  CLOCK timerMark;
  CLOCK timerMark2;
  CLOCK timerVal;
  CLOCK walkMark;

  // Results of the experiment
  int walkSpeed;
  bool expSuccess;

  WalkParam_t  walkParams;
  Floats       paramValues;

  bool secondPhaseStart;

  // these are the parameter defaults for the walking machine
  WalkParam_t curParams;

  // Parameter sweep configuration.
  int    repeats, cur_repeat, numofexps;
  Floats cpgperiod_range;
  int    cpgperiod_cur;
  Floats sweepangle_range;
  int    sweepangle_cur;
  Floats dutyfactor_range;
  int    dutyfactor_cur;
  Floats legoffset_range;
  int    legoffset_cur;
  Floats smooth_range;
  int    smooth_cur;
  Floats turnoffset_range;
  int    turnoffset_cur;
  Floats turnduty_range;
  int    turnduty_cur;
  Floats turnsweep_range;
  int    turnsweep_cur;
  Floats kp_range;
  int    kp_cur;
  Floats kd_range;
  int    kd_cur;

};

#endif


text:
param (
    [string]$environmentName,
    [string]$resourceFilteringMethod,
    [string]$machineFilter,
    [string]$dacpacFile,
    [string]$targetMethod,
    [string]$serverName,
    [string]$databaseName,
    [string]$sqlUsername,
    [string]$sqlPassword,
    [string]$connectionString,
    [string]$publishProfile,
    [string]$additionalArguments,
    [string]$deployInParallel
    )

Write-Verbose "Entering script DeployToSqlServer.ps1" -Verbose
Write-Verbose "environmentName = $environmentName" -Verbose
Write-Verbose "resourceFilteringMethod = $resourceFilteringMethod" -Verbose
Write-Verbose "machineFilter = $machineFilter" -Verbose
Write-Verbose "dacpacFile = $dacpacFile" -Verbose
Write-Verbose "targetMethod = $targetMethod" -Verbose
Write-Verbose "serverName = $serverName" -Verbose
Write-Verbose "databaseName = $databaseName" -Verbose
Write-Verbose "sqlUsername = $sqlUsername" -Verbose
Write-Verbose "publishProfile = $publishProfile" -Verbose
Write-Verbose "additionalArguments = $additionalArguments" -Verbose
Write-Verbose "deployInParallel = $deployInParallel" -Verbose

import-module "Microsoft.TeamFoundation.DistributedTask.Task.Internal"
import-module "Microsoft.TeamFoundation.DistributedTask.Task.Common"
import-module "Microsoft.TeamFoundation.DistributedTask.Task.DevTestLabs"
Import-Module "Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Internal"
Import-Module "Microsoft.TeamFoundation.DistributedTask.Task.Deployment.RemoteDeployment"

$ErrorActionPreference = 'Stop'

$sqlDeploymentScriptPath = Join-Path "$env:AGENT_HOMEDIRECTORY" "Agent\Worker\Modules\Microsoft.TeamFoundation.DistributedTask.Task.DevTestLabs\Scripts\Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Sql.ps1"

$sqlPackageOnTargetMachineBlock = Get-Content $sqlDeploymentScriptPath | Out-String

$sqlPackageArguments = Get-SqlPackageCommandArguments -dacpacFile $dacpacFile -targetMethod $targetMethod -serverName $serverName -databaseName $databaseName -sqlUsername $sqlUsername -sqlPassword $sqlPassword -connectionString $connectionString -publishProfile $publishProfile -additionalArguments $additionalArguments

$scriptArguments = "-sqlPackageArguments $sqlPackageArguments"

$errorMessage = [string]::Empty

Write-Output ( Get-LocalizedString -Key "Starting deployment of Sql Dacpac File : {0}" -ArgumentList $dacpacFile)

if($resourceFilteringMethod -eq "tags")
{
    $errorMessage = Invoke-RemoteDeployment -environmentName $environmentName -tags $machineFilter -ScriptBlockContent $sqlPackageOnTargetMachineBlock -scriptArguments $scriptArguments -runPowershellInParallel $deployInParallel
}
else
{
    $errorMessage = Invoke-RemoteDeployment -environmentName $environmentName -machineNames $machineFilter -ScriptBlockContent $sqlPackageOnTargetMachineBlock -scriptArguments $scriptArguments -runPowershellInParallel $deployInParallel
}

if(-not [string]::IsNullOrEmpty($errorMessage))
{
    $readmelink = "http://aka.ms/sqlserverdacpackreadme"
    $helpMessage = (Get-LocalizedString -Key "For more info please refer to {0}" -ArgumentList $readmelink)
    throw "$errorMessage $helpMessage"
}

Write-Output ( Get-LocalizedString -Key "Successfully deployed Sql Dacpac File : {0}" -ArgumentList $dacpacFile)


text:
package kr.debop4j.data.ogm.test.massindex.model;

import com.google.common.base.Objects;
import kr.debop4j.core.tools.HashTool;
import kr.debop4j.data.model.AnnotatedEntityBase;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.search.annotations.Indexed;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * kr.debop4j.data.ogm.test.massindex.model.IndexedLabel
 *
 * @author 배성혁 ( sunghyouk.bae@gmail.com )
 * @since 13. 4. 2. 오후 1:16
 */
@Entity
@Indexed
@Getter
@Setter
public class IndexedLabel extends AnnotatedEntityBase {

    private static final long serialVersionUID = -3215016392141137416L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public IndexedLabel() {}

    public IndexedLabel(String name) {
        this.name = name;
    }

    private String name;

    @Override
    public int hashCode() {
        return HashTool.compute(name);
    }

    @Override
    protected Objects.ToStringHelper buildStringHelper() {
        return super.buildStringHelper()
                .add("name", name);
    }
}