text:
package sorcer.sml.jobs;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sorcer.test.ProjectContext;
import org.sorcer.test.SorcerTestRunner;
import sorcer.arithmetic.provider.Adder;
import sorcer.arithmetic.provider.Multiplier;
import sorcer.arithmetic.provider.Subtractor;
import sorcer.core.SorcerConstants;
import sorcer.core.context.model.ent.ProcModel;
import sorcer.core.provider.*;
import sorcer.core.provider.rendezvous.ServiceJobber;
import sorcer.service.*;
import sorcer.service.Strategy.Access;
import sorcer.service.Strategy.Flow;
import sorcer.service.Strategy.Provision;
import sorcer.service.Strategy.Shell;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static sorcer.co.operator.*;
import static sorcer.co.operator.input;
import static sorcer.eo.operator.*;
import static sorcer.eo.operator.get;
import static sorcer.eo.operator.pipe;
import static sorcer.po.operator.*;
import static sorcer.po.operator.put;

/**
 * @author Mike Sobolewski
 */
@RunWith(SorcerTestRunner.class)
@ProjectContext("examples/sml")
public class NetJobExertions implements SorcerConstants {
	private final static Logger logger = LoggerFactory.getLogger(NetJobExertions.class);

	// two level job composition with PULL and PAR execution
	private static Job createJob(Flow flow, Access access) throws Exception {

		Task t3 = task("t3", sig("subtract", Subtractor.class),
				context("subtract", inVal("arg/x1"), inVal("arg/x2"),
//						outVal("result/y")), strategy(Monitor.YES));
						outVal("result/y")));
		Task t4 = task("t4", sig("multiply", Multiplier.class),
				context("multiply", inVal("arg/x1", 10.0), inVal("arg/x2", 50.0),
//						outVal("result/y")), strategy(Monitor.YES));
						outVal("result/y")));

		Task t5 = task("t5", sig("add", Adder.class),
				context("add", inVal("arg/x1", 20.0), inVal("arg/x2", 80.0),
//						outVal("result/y")), strategy(Monitor.YES));
						outVal("result/y")));

		// Service Composition j1(j2(t4(x1, x2), t5(x1, x2)), t3(x1, x2))
		Job job = job("j1",
//				job("j2", t4, t5, strategy(flow, access, Monitor.YES)),
				t3,
                job("j2", t4, t5, strategy(flow, access)),

                pipe(outPoint(t4, "result/y"), inPoint(t3, "arg/x1")),
				pipe(outPoint(t5, "result/y"), inPoint(t3, "arg/x2")));
//                strategy(Monitor.YES));

		return job;
	}

	public static Exertion createJob() throws Exception {
		return createJob(Flow.SEQ, Access.PUSH);
	}

	@Test
	public void exertJobPushParTest() throws Exception {

		Job job = createJob(Flow.PAR, Access.PUSH);
		job = exert(job);
		//logger.info("job j1: " + job);
		//logger.info("job j1 job context: " + context(job));
		logger.info("job j1 job context: " + upcontext(job));
		//logger.info("job j1 eval @ j1/t3/result/y = " + get(job, "j1/t3/result/y"));
		assertEquals(get(job, "j1/t3/result/y"), 400.00);

	}

	@Test
	public void exertJobPushSeqTest() throws Exception {
		ServiceMogram.debug = true;

		Job job = createJob(Flow.SEQ, Access.PUSH);
//		logger.info("job j1: " + job);
		job = exert(job);
		logger.info("job j1: " + job.describe());
//		logger.info("job j1 job context: " + context(job, "j1/t3));
//		logger.info("job j1 job context: " + upcontext(job));
		//logger.info("job j1 eval @ j1/t3/result/y = " + get(job, "j1/t3/result/y"));
		assertEquals(get(job, "j1/t3/result/y"), 400.00);

	}

	@Test
	public void exertJobPullParTest() throws Exception {

		Job job = createJob(Flow.PAR, Access.PULL);
		job = exert(job);
		//logger.info("job j1: " + job);
		//logger.info("job j1 job context: " + context(job));
		logger.info("job j1 job context: " + upcontext(job));
		//logger.info("job j1 eval @ j1/t3/result/y = " + get(job, "j1/t3/result/y"));
		assertEquals(get(job, "j1/t3/result/y"), 400.00);

	}

	@Test
	public void exertJobPullSeqTest() throws Exception {

		Job job = createJob(Flow.SEQ, Access.PULL);
		job = exert(job);
		//logger.info("job j1: " + job);
		//logger.info("job j1 job context: " + context(job));
		logger.info("job j1 job context: " + upcontext(job));
		//logger.info("job j1 eval @ j1/t3/result/y = " + get(job, "j1/t3/result/y"));
		assertEquals(get(job, "j1/t3/result/y"), 400.00);

	}

	@Test
	public void localJobber() throws Exception {

		Task t3 = task(
				"t3",
				sig("subtract", Subtractor.class),
				context("subtract", inVal("arg/x1", null), inVal("arg/x2", null),
						outVal("result/y", null)));

		Task t4 = task(
				"t4",
				sig("multiply", Multiplier.class),
				context("multiply", inVal("arg/x1", 10.0), inVal("arg/x2", 50.0),
						outVal("result/y", null)));

		Task t5 = task(
				"t5",
				sig("add", Adder.class),
				context("add", inVal("arg/x1", 20.0), inVal("arg/x2", 80.0),
						outVal("result/y", null)));

		// Service Composition j1(j2(t4(x1, x2), t5(x1, x2)), t3(x1, x2))
		Job job = job(
				"j1", sig("exert", ServiceJobber.class),
				job("j2", t4, t5), t3,
				pipe(outPoint(t4, "result/y"), inPoint(t3, "arg/x1")),
				pipe(outPoint(t5, "result/y"), inPoint(t3, "arg/x2")));

		Context context = upcontext(exert(job));
		logger.info("job context: " + context);
		assertEquals(value(context, "j1/t3/result/y"), 400.0);
	}

	@Test
	public void remoteServiceShell() throws Exception {

		Task t3 = task(
				"t3",
				sig("subtract", Subtractor.class),
				context("subtract", inVal("arg/x1", null), inVal("arg/x2", null),
						outVal("result/y", null)));

		Task t4 = task(
				"t4",
				sig("multiply", Multiplier.class),
				context("multiply", inVal("arg/x1", 10.0), inVal("arg/x2", 50.0),
						outVal("result/y", null)));

		Task t5 = task(
				"t5",
				sig("add", Adder.class),
				context("add", inVal("arg/x1", 20.0), inVal("arg/x2", 80.0),
						outVal("result/y", null)));

		// Service Composition j1(j2(t4(x1, x2), t5(x1, x2)), t3(x1, x2))
		Job job = job("j1", // sig("exert", ServiceJobber.class),
				job("j2", t4, t5), t3,
				pipe(outPoint(t4, "result/y"), inPoint(t3, "arg/x1")),
				pipe(outPoint(t5, "result/y"), inPoint(t3, "arg/x2")));

		Provider shell = (Provider) provider(sig(RemoteServiceShell.class));
		Context out = upcontext(exert(shell, job));
		logger.info("job context: " + out);
		assertEquals(value(out, "j1/t3/result/y"), 400.0);

	}

	@Test
	public void serviceShellRemote() throws Exception {

		Task t3 = task(
				"t3",
				sig("subtract", Subtractor.class),
				context("subtract", inVal("arg/x1", null), inVal("arg/x2", null),
						outVal("result/y", null)));

		Task t4 = task(
				"t4",
				sig("multiply", Multiplier.class),
				context("multiply", inVal("arg/x1", 10.0), inVal("arg/x2", 50.0),
						outVal("result/y")));

		Task t5 = task(
				"t5",
				sig("add", Adder.class),
				context("add", inVal("arg/x1", 20.0), inVal("arg/x2", 80.0),
						outVal("result/y", null)));

		// Service Composition j1(j2(t4(x1, x2), t5(x1, x2)), t3(x1, x2))
		Job job = job(
				"j1", sig("exert", Jobber.class, Shell.REMOTE),
				job("j2", t4, t5), t3,
				pipe(outPoint(t4, "result/y"), inPoint(t3, "arg/x1")),
				pipe(outPoint(t5, "result/y"), inPoint(t3, "arg/x2")));

		Context context = upcontext(exert(job));
		logger.info("job context: " + context);
		assertEquals(value(context, "j1/t3/result/y"), 400.0);

	}

	public static Context createContext() throws Exception {
		return context("add", inVal("arg/x1", 20.0), inVal("arg/x2", 80.0));
	}

	@Test
	public void contexterTest() throws Exception {

		Task cxtt = task("getAddContext", sig("getContext", Contexter.class, prvName("Add Contexter")),
				context("add", input("arg/x1"), input("arg/x2")));

		Context result = context(exert(cxtt));
//		logger.info("contexter context 1: " + result);

		assertEquals(value(result, "arg/x1"), 20.0);
		assertEquals(value(result, "arg/x2"), 80.0);

		cxtt = task("appendContext", sig("appendContext", Contexter.class, prvName("Add Contexter")),
				context("add", inVal("arg/x1", 200.0), inVal("arg/x2", 800.0)));

		result = context(exert(cxtt));
//		logger.info("contexter context 2: " + result);

		cxtt = task("getAddContext", sig("getContext", Contexter.class, prvName("Add Contexter")),
				context("add", input("arg/x1"), input("arg/x2")));

		result = context(exert(cxtt));
//		logger.info("contexter context 3: " + result);

		assertEquals(value(result, "arg/x1"), 200.0);
		assertEquals(value(result, "arg/x2"), 800.0);

		// reset the contexter
		cxtt = task("appendContext", sig("appendContext", Contexter.class, prvName("Add Contexter")),
				context("add", inVal("arg/x1", 20.0), inVal("arg/x2", 80.0)));

		result = context(exert(cxtt));
//		logger.info("contexter context 4: " + result);
		assertEquals(value(result, "arg/x1"), 20.0);
		assertEquals(value(result, "arg/x2"), 80.0);

	}

	public Job createProvisionedJob() throws Exception {

		Task f4 = task(
				"f4",
				sig("multiply", Multiplier.class,
					deploy(implementation(ServiceTasker.class.getName()),
						classpath("ex6-arithmetic-beans.jar"),
						codebase("ex6-arithmetic-dl.jar"),
						configuration("bin/examples/ex6/configs/multiplier-prv.config"),
						maintain(1),
						idle("3h"))),
				context("multiply", inVal("arg/x1", 10.0d),
						inVal("arg/x2", 50.0d), outVal("result/y1")));

		Task f5 = task(
				"f5",
				sig("add", Adder.class,
					deploy(classpath("arithmetic-beans.jar"),
						codebase("arithmetic-dl.jar"),
						configuration("bin/examples/ex6/configs/adder-prv.config"),
						idle(60*3))),
				context("add", inVal("arg/x3", 20.0d), inVal("arg/x4", 80.0d),
						outVal("result/y2")));

		Task f3 = task(
				"f3",
				sig("subtract", Subtractor.class,
					deploy(classpath("arithmetic-beans.jar"),
						codebase("arithmetic-dl.jar"),
						configuration("bin/examples/ex6/configs/subtractor-prv.config"))),
				context("subtract", inVal("arg/x5", null),
						inVal("arg/x6"), outVal("result/y3")));

		// job("f1", job("f2", f4, f5), f3,
		// job("f1", job("f2", f4, f5, strategy(Flow.PAR, Access.PULL)), f3,
		Job f1 = job("f1", job("f2", f4, f5), f3, strategy(Provision.NO),
				pipe(outPoint(f4, "result/y1"), inPoint(f3, "arg/x5")),
				pipe(outPoint(f5, "result/y2"), inPoint(f3, "arg/x6")));

		return f1;
	}

	@Test
	public void arithmeticJobNetExerter() throws Exception {

		// get the current eval of the exertlet
		Exerter exerter = task("eval", sig("getValue", Evaluation.class, prvName("Arithmetic Exerter")));
//		logger.info("j1/t3/result/y: " + eval(task, "j1/t3/result/y"));
		Context out = exert(exerter, context());
		assertEquals(value(out, "j1/t3/result/y"), 400.0);

		// update inputs contexts
		Context multiplyContext = context("multiply", inVal("arg/x1", 10.0), inVal("arg/x2", 70.0));
		Context addContext = context("add", inVal("arg/x1", 90.0), inVal("arg/x2", 110.0));
		Context invokeContext = context("invoke");
		link(invokeContext, "t4", multiplyContext);
		link(invokeContext, "t5", addContext);
		exerter = task("invoke", sig("invoke", Invocation.class, prvName("Arithmetic Exerter")), invokeContext);
		out = exert(exerter, invokeContext);
		logger.info("j1/t3/result/y: " + value(out, "j1/t3/result/y"));
		assertEquals(value(out, "j1/t3/result/y"), 500.0);

		// update contexts partially
		multiplyContext = context("multiply", inVal("arg/x1", 20.0));
		addContext = context("add", inVal("arg/x1", 80.0));
		invokeContext = context("invoke");
		link(invokeContext, "t4", multiplyContext);
		link(invokeContext, "t5", addContext);
		exerter = task("invoke", sig("invoke", Invocation.class, prvName("Arithmetic Exerter")), invokeContext);
		out = exert(exerter, invokeContext);
		logger.info("j1/t3/result/y: " + value(out, "j1/t3/result/y"));
		assertEquals(value(out, "j1/t3/result/y"), 1210.0);

		// reverse the state to the initial one
		multiplyContext = context("multiply", inVal("arg/x1", 10.0), inVal("arg/x2", 50.0));
		addContext = context("add", inVal("arg/x1", 80.0), inVal("arg/x2", 20.0));
		invokeContext = context("invoke");
		link(invokeContext, "t4", multiplyContext);
		link(invokeContext, "t5", addContext);
		exerter = task("invoke", sig("invoke", Invocation.class, prvName("Arithmetic Exerter")), invokeContext);
		out = exert(exerter, invokeContext);
		logger.info("j1/t3/result/y: " + value(out, "j1/t3/result/y"));
		assertEquals(value(out, "j1/t3/result/y"), 400.0);
	}

	@Test
	public void createModelWithTask() throws Exception {

		ProcModel vm = procModel(
				"Hello Arithmetic #2",
				// inputs
				ent("x1"), ent("x2"), proc("x3", 20.0), ent("x4"),
				// outputs
				proc("t4", invoker("x1 * x2", args("x1", "x2"))),
				proc("t5",
					task("t5",
						sig("add", Adder.class),
						cxt("add", inVal("arg/x3"), inVal("arg/x4"),
						result("result/y")))),
				proc("j1", invoker("t4 - t5", args("t4", "t5"))));

		vm = put(vm, proc("x1", 10.0), proc("x2", 50.0),
				proc("x4", 80.0));

		assertTrue(eval(proc(vm, "j1")).equals(400.0));
	}

}


text:
using System;
using System.IO;
using L4p.Common.Extensions;
using L4p.Common.Helpers;
using L4p.Common.Loggers;

namespace L4p.Common.ConfigurationFiles
{
    public interface IConfigFile<T>
        where T : class, new()
    {
        bool IsUpToDate();
        T Read();

        string Path { get; }
        string Name { get; }
    }

    public class ConfigFile<T> : IConfigFile<T>
        where T : class, new()
    {
        #region config

        public class Config
        {
            public TimeSpan MinimalCheckSpan { get; set; }

            public Config()
            {
                MinimalCheckSpan = 2.Seconds();
            }
        }

        #endregion

        #region members

        private readonly string _path;
        private readonly string _name;
        private readonly Config _config;
        private readonly ILogFile _log;

        private DateTime _loadedAt;
        private DateTime _checkedAt;
        private T _configuration;

        #endregion

        #region construction

        public static IConfigFile<T> New(string path, ILogFile log = null, Config config = null)
        {
            if (log == null)
                log = LogFile.New("bootstrap.log");

            return
                new ConfigFile<T>(path, log, config ?? new Config());
        }

        private ConfigFile(string path, ILogFile log, Config config)
        {
            _path = path;
            _name = Path.GetFileName(path);
            _config = config;
            _log = log;
            _loadedAt = DateTime.MinValue;
            _checkedAt = DateTime.MinValue;
            _configuration = new T();
        }

        #endregion

        #region private

        private T read_configuration(string path)
        {
            string json = Try.Catch.Wrap(
                () => File.ReadAllText(path),
                ex => ex.WrapWith<ConfigFileException>("Failed to read json from configuration file '{0}'", path));

            var parser = Json2Config<T>.New(path);

            var configuration = Try.Catch.Wrap(
                () => parser.ParseJson(path, json, _log),
                ex => ex.WrapWith<ConfigFileException>("Failed to parse json from configuration file '{0}'", path));

            _log.Info("Configuration file '{0}' is loaded (and parsed)", path);

            return configuration;
        }

        #endregion

        #region IConfigFile

        bool IConfigFile<T>.IsUpToDate()
        {
            var now = DateTime.UtcNow;

            var sinceLastCheck = now - _checkedAt;

            if (sinceLastCheck <= _config.MinimalCheckSpan)
                return true;

            var lastUpdatedAt = File.GetLastWriteTimeUtc(_path);
            _checkedAt = now;

            bool isUpToDate =
                lastUpdatedAt <= _loadedAt;

            return isUpToDate;
        }

        T IConfigFile<T>.Read()
        {
            var now = DateTime.UtcNow;

            var lastUpdatedAt = File.GetLastWriteTimeUtc(_path);
            _checkedAt = now;

            if (lastUpdatedAt > _loadedAt)
            {
                Try.Catch.Handle(
                    () => _configuration = read_configuration(_path),
                    ex => _log.Error(ex, "While loading configuration from '{0}'", _path));

                _loadedAt = now;
            }

            Validate.NotNull(_configuration);
            return _configuration;
        }

        string IConfigFile<T>.Path
        {
            get { return _path; }
        }

        string IConfigFile<T>.Name
        {
            get { return _name; }
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.reef.runtime.common;

import org.apache.reef.annotations.audience.ClientSide;
import org.apache.reef.annotations.audience.DriverSide;
import org.apache.reef.annotations.audience.Public;
import org.apache.reef.runtime.common.client.defaults.DefaultUserCredentials;
import org.apache.reef.tang.annotations.DefaultImplementation;

import java.io.IOException;
import java.security.PrivilegedExceptionAction;

/**
 * A holder object for REEF user credentials.
 * Implementations of this interface are used e.g. for Unmanaged AM applications on YARN.
 */
@Public
@ClientSide
@DriverSide
@DefaultImplementation(DefaultUserCredentials.class)
public interface UserCredentials {

  /**
   * Copy credentials from another existing user.
   * This method can be called only once per instance.
   * @param name name of the new user.
   * @param other Credentials of another user.
   * @throws IOException if unable to copy.
   */
  void set(final String name, final UserCredentials other) throws IOException;

  /**
   * Check if the user credentials had been set.
   * @return true if set() method had been called successfully before, false otherwise.
   */
  boolean isSet();

  /**
   * Execute the privileged action as a given user.
   * If user credentials are not set, execute the action outside the user context.
   * @param action an action to run.
   * @param <T> action return type.
   * @return result of an action.
   * @throws Exception whatever the action can throw.
   */
  <T> T doAs(final PrivilegedExceptionAction<T> action) throws Exception;
}


text:
//Compares the number of items in the list to the maxCount variable and enables or disables the add button
TheFarm.Umbraco.EmbeddedContent.CheckMaxCount = function (dtdid) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    if (EC.maxCount == 0) return true;

    valuexml = decodeURIComponent($("input[id$='hiddenXmlValue" + dtdid + "']").val());
    dojo.require("dojox.xml.parser");
    xmlDoc = dojox.xml.parser.parse(valuexml);

    if (xmlDoc.documentElement && xmlDoc.documentElement.hasChildNodes()) {
        count = xmlDoc.documentElement.childNodes.length;
    } else return true;

    return (count < EC.maxCount);
}

TheFarm.Umbraco.EmbeddedContent.AddBlurToFields = function (dtdid) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    schemaxml = decodeURIComponent($("input[id$='EChiddenXmlSchema" + dtdid + "']").val());
    if (window.DOMParser) {
        doc = schemaxml;
    } else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(schemaxml);
        doc = $(xmlDoc).children();
    }
    $(doc).children().each(function () {
        id = $(this).attr('propertyid');
        type = $(this).attr('type');
        required = $(this).attr('required');
        validation = $(this).attr('validation');
        EC.AddBlur(dtdid, id, type, required, validation);
    });
    return false;
}

TheFarm.Umbraco.EmbeddedContent.AddBlur = function (dtdid, fieldId, type, required, validation) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    if (type == 'True/false') {
        //do nothing
    } else if (type == 'Content picker' || type == 'Media picker') {
        //does not work!!
        //$("td:has(input[id$='field" + dtdid + "_" + fieldId + "_ContentIdValue']) a").blur(function () {
        //    EC.ValidateField(dtdid, fieldId, type, required, validation);
        //});
    } else if (type == 'Date picker') {
        //no blur action here
    } else if (type == 'Textbox multiple' || type == 'Simple editor') {
        $("textarea[id$='field" + dtdid + "_" + fieldId + "']").blur(function () {
            EC.ValidateField(dtdid, fieldId, type, required, validation);
        });
    } else {
        $("input[id$='field" + dtdid + "_" + fieldId + "']").blur(function () {
            EC.ValidateField(dtdid, fieldId, type, required, validation);
        });
    }
}

TheFarm.Umbraco.EmbeddedContent.ValidateFields = function (dtdid) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    valid = true;
    schemaxml = decodeURIComponent($("input[id$='EChiddenXmlSchema" + dtdid + "']").val());
    if (window.DOMParser) {
        doc = schemaxml;
    } else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(schemaxml);
        doc = $(xmlDoc).children();
    }
    $(doc).children().each(function () {
        id = $(this).attr('propertyid');
        type = $(this).attr('type');
        required = $(this).attr('required');
        validation = $(this).attr('validation');
        valid = valid & EC.ValidateField(dtdid, id, type, required, validation);
    });
    return valid;
}

TheFarm.Umbraco.EmbeddedContent.ValidateField = function (dtdid, fieldId, type, required, validation) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    if (type == 'True/false') {
        //won't be validated!
        return true;
    } else if (type == 'Content picker' || type == 'Media picker') {
        value = $("input[id$='field" + dtdid + "_" + fieldId + "_ContentIdValue']").val();
    } else if (type == 'Date picker') {
        value = $("td[id$='field" + dtdid + "_" + fieldId + "'] input").val();
    } else if (type == 'Textbox multiple' || type == 'Simple editor') {
        value = $("textarea[id$='field" + dtdid + "_" + fieldId + "']").val();
    } else {
        value = $("input[id$='field" + dtdid + "_" + fieldId + "']").val();
    }
    if (required == 'True' && value == '') {
        EC.MarkField(dtdid, fieldId, type);
        return false;
    }
    if (validation != '') {
        regex = new RegExp(validation);
        result = value.match(regex);
        if (!result || result == null || result == '') {
            EC.MarkField(dtdid, fieldId, type);
            return false;
        }
    }
    EC.UnmarkField(dtdid, fieldId, type);
    return true;
}

TheFarm.Umbraco.EmbeddedContent.MarkField = function (dtdid, fieldId, type) {
    if (type == 'Content picker' || type == 'Media picker') {
        $("td:has(input[id$='field" + dtdid + "_" + fieldId + "_ContentIdValue'])").prev().css('color', 'red').css('font-weight', 'bold');
    } else if (type == 'Date picker') {
        $("td[id$='field" + dtdid + "_" + fieldId + "']").prev().css('color', 'red').css('font-weight', 'bold');
    } else if (type == 'Textbox multiple' || type == 'Simple editor') {
        $("td:has(textarea[id$='field" + dtdid + "_" + fieldId + "'])").prev().css('color', 'red').css('font-weight', 'bold');
    } else {
        $("td:has(input[id$='field" + dtdid + "_" + fieldId + "'])").prev().css('color', 'red').css('font-weight', 'bold');
    }
}

TheFarm.Umbraco.EmbeddedContent.UnmarkField = function (dtdid, fieldId, type) {

    if (type == 'Content picker' || type == 'Media picker') {
        $("td:has(input[id$='field" + dtdid + "_" + fieldId + "_ContentIdValue'])").prev().css('color', 'black').css('font-weight', 'normal');
    } else if (type == 'Date picker') {
        $("td[id$='field" + dtdid + "_" + fieldId + "']").prev().css('color', 'black').css('font-weight', 'normal');
    } else if (type == 'Textbox multiple' || type == 'Simple editor') {
        $("td:has(textarea[id$='field" + dtdid + "_" + fieldId + "'])").prev().css('color', 'black').css('font-weight', 'normal');
    } else {
        $("td:has(input[id$='field" + dtdid + "_" + fieldId + "'])").prev().css('color', 'black').css('font-weight', 'normal');
    }
}

//used for changing the order after a successful dragsort
TheFarm.Umbraco.EmbeddedContent.WriteHiddenValueFromList = function (dtdid) {
    valuexml = decodeURIComponent($("input[id$='hiddenXmlValue" + dtdid + "']").val());
    dojo.require("dojox.xml.parser");
    xmlDoc = dojox.xml.parser.parse(valuexml);

    items = new Array();

    if (xmlDoc.documentElement && xmlDoc.documentElement.hasChildNodes()) {
        childNodes = xmlDoc.documentElement.childNodes;
        for (i = 0; i < childNodes.length; i++) {
            attributes = childNodes[i].attributes;
            oldId = 0;
            for (j = 0; j < attributes.length; j++) {
                if (attributes[j].name == 'id') {
                    oldId = attributes[j].value;
                }
            }
            items[items.length] = { id: oldId, properties: dojox.xml.parser.innerXML(childNodes[i]) };
        }
    }

    valuexml = '<data>';
    $('ul#sortList' + dtdid + ' li').each(function () {
        id = $(this).find('span').html();
        for (i = 0; i < items.length; i++) {
            if (items[i].id == id) {
                valuexml += items[i].properties;
            }
        }
    });
    valuexml += '</data>';
    $("input[id$='hiddenXmlValue" + dtdid + "']").val(encodeURIComponent(valuexml));
}

//removes an item from the value xml
TheFarm.Umbraco.EmbeddedContent.RemoveItem = function (elem) {
    //get dtdid
    ul = elem.parent().parent().parent();
    dtdid = ul.attr('id').replace(/.*sortList/i, '');
    EC = TheFarm.Umbraco.EmbeddedContent;
    //find out if an element was selected before; if so unselect and reselect if cancelled
    previousSelectedLI = null;
    $('ul#sortList' + dtdid + ' li').each(function () {
        if ($(this).hasClass('EChighlight')) {
            previousSelectedLI = $(this);
        }
    });
    EC.ResetLIs(dtdid);
    //if the addBox is open close it and re-open it when cancelled
    reOpenAddBox = false;
    if ($("div#addBox" + dtdid).css('display') != 'none') {
        $("div#addBox" + dtdid).hide();
        reOpenAddBox = true;
    }
    elem.parent().parent().removeClass('ECregular').addClass('EChighlight');
    ok = confirm('Are you sure you want to delete "' + elem.parent().html().replace(/<div (.){0,40}ECbigButton[^<]*<\/div>/gi, '').replace(/<div[^<]*<\/div>/gi, '').replace(/<a[^<]*<\/a>/gi, '') + '"?');
    if (ok) {
        //remove from xml value
        id = elem.parent().parent().find('span').html();
        valuexml = decodeURIComponent($("input[id$='hiddenXmlValue" + dtdid + "']").val());
        regex = new RegExp('<item id="' + id + '"([^<]|<[^\/]|<\/[^i]|<\/i[^t]|<\/it[^e]|<\/ite[^m]|<\/item[^>])*<\/item>');
        valuexml = valuexml.replace(regex, '');
        $("input[id$='hiddenXmlValue" + dtdid + "']").val(encodeURIComponent(valuexml));
        //make the graphical changes
        elem.parent().parent().remove();
        EC.ClearFields(dtdid);
        $("div#addBox" + dtdid).hide();
        $("a#addLink" + dtdid).show();
    } else {
        elem.parent().parent().removeClass('EChighlight').addClass('ECregular');
        if (reOpenAddBox) {
            $("div#addBox" + dtdid).show();
        };
        if (previousSelectedLI != null) {
            previousSelectedLI.addClass('EChighlight');
        }
    }
    return false;
}

//edits an item = opens the add box and fills in the values for that field
TheFarm.Umbraco.EmbeddedContent.EditItem = function (elem) {
    //get dtdid
    ul = elem.parent().parent().parent();
    dtdid = ul.attr('id').replace(/.*sortList/i, '');
    EC = TheFarm.Umbraco.EmbeddedContent;
    EC.ResetLIs(dtdid);
    elem.parent().parent().removeClass('ECregular').addClass('EChighlight');
    EC.ClearFields(dtdid);
    id = elem.parent().parent().find('span').html();
    $("input#hiddenEditId" + dtdid).val(id);
    valuexml = decodeURIComponent($("input[id$='hiddenXmlValue" + dtdid + "']").val());

    dojo.require("dojox.xml.parser");
    xmlDoc = dojox.xml.parser.parse(valuexml);
    if (xmlDoc.documentElement && xmlDoc.documentElement.hasChildNodes()) {
        childNodes = xmlDoc.documentElement.childNodes;
        for (i = 0; i < childNodes.length; i++) {
            childAttributes = childNodes[i].attributes;
            for (j = 0; j < childAttributes.length; j++) {
                if (childAttributes[j].name == 'id') {
                    oldId = childAttributes[j].value;
                }
            }
            if (oldId == id) {
                grandChildren = childNodes[i].childNodes;
                for (k = 0; k < grandChildren.length; k++) {
                    grandChildAttributes = grandChildren[k].attributes;
                    for (l = 0; l < grandChildAttributes.length; l++) {
                        if (grandChildAttributes[l].name == 'type') {
                            type = grandChildAttributes[l].value;
                        } else if (grandChildAttributes[l].name == 'propertyid') {
                            propertyid = grandChildAttributes[l].value;
                        }
                    }
                    if (type == 'Simple editor' || type == 'Textbox multiple' || type == 'Textstring') {
                        regex = new RegExp('<' + grandChildren[k].nodeName + '[^>]*>');
                        regex2 = new RegExp('<\/' + grandChildren[k].nodeName + '[^>]*>');
                        //value = grandChildren[k].xml.replace(regex, '').replace(regex2, '');
                        value = dojox.xml.parser.innerXML(grandChildren[k])
                            .replace(regex, '')
                            .replace(regex2, '')
                            .replace(/</gi, '<')
                            .replace(/>/gi, '>')
                            .replace(/&/gi, '&');
                        EC.FillField(dtdid, value, type, propertyid);
                    } else {
                        //EC.FillField(dtdid, grandChildren[k].text, type, propertyid);
                        EC.FillField(dtdid,  dojox.xml.parser.textContent(grandChildren[k]), type, propertyid);
                    }
                }
            }
        }
        //}
    }
    $("div#addBox" + dtdid).show();
    $("a#addLink" + dtdid).hide();
    $("a#addPropertyLink" + dtdid + " div.ECbigButton").css('background-position', '0px -160px');
    EC.SetFocusOnFirstElement(dtdid);
    return false;
}

TheFarm.Umbraco.EmbeddedContent.FillField = function (dtdid, value, type, propertyid) {
    if (type == 'True/false') {
        if (value == '1') {
            $("input[id$='field" + dtdid + "_" + propertyid + "']").attr('checked', 'checked');
        } else {
            $("input[id$='field" + dtdid + "_" + propertyid + "']").removeAttr('checked');
        }
    } else if (type == 'Content picker' || type == 'Media picker') {
        if (value != '') {
            $("input[id$='field" + dtdid + "_" + propertyid + "_ContentIdValue']").val(value);
            //get the name of the node
            $("span[id$='field" + dtdid + "_" + propertyid + "_btns']").show();

            $.ajax({
                type: 'POST',
                url: '/umbraco/rest/umbraconodename?id=' + value,
                success: function (data) {
                    name = $(data).text();
                    if (name != '' && name != 'no node found') {
                        $("span[id$='field" + dtdid + "_" + propertyid + "_title']").html(name);
                    }
                },
                error: function (msg) {
                    $.ajax({
                        type: 'POST',
                        url: '/umbraco/webservices/UmbracoNodeNameService.asmx/ReadUmbracoNodeName',
                        data: '{qid:"' + value + '"}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {
                            name = msg.d;
                            if (name != '' && name != 'no node found') {
                                $("span[id$='field" + dtdid + "_" + propertyid + "_title']").html(name);
                            }
                        }
                    });
                }
            });
        }
    } else if (type == 'Simple editor') {
        $("textarea[id$='field" + dtdid + "_" + propertyid + "']").val(value);
    } else if (type == 'Date picker') {
        $("td[id$='field" + dtdid + "_" + propertyid + "'] input").val(value);
    } else if (type == 'Textbox multiple') {
        $("textarea[id$='field" + dtdid + "_" + propertyid + "']").val(value);
    } else {
        $("input[id$='field" + dtdid + "_" + propertyid + "']").val(value);
    }
}

//Calculates the next avaiable Id to be used with a newly created property element
TheFarm.Umbraco.EmbeddedContent.CalculateNextAvailableId = function (dtdid) {
    currentMaxId = 0;
    $("ul#sortList" + dtdid + " li span").each(function () {
        thisNumber = parseInt($(this).html());
        if (thisNumber > currentMaxId) {
            currentMaxId = thisNumber;
        }
    });
    return (currentMaxId + 1);
}

TheFarm.Umbraco.EmbeddedContent.AddPropertyClicked = function (dtdid) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    if (!EC.ValidateFields(dtdid)) return false;

    editId = $("input#hiddenEditId" + dtdid).val();
    valuexml = decodeURIComponent($("input[id$='hiddenXmlValue" + dtdid + "']").val());
    schemaxml = decodeURIComponent($("input[id$='EChiddenXmlSchema" + dtdid + "']").val());
    schemaxml = schemaxml.replace(/id=""/, 'id="' + (editId != '' ? editId : EC.CalculateNextAvailableId(dtdid)) + '"');
    dojo.require("dojox.xml.parser");
    xmlDoc = dojox.xml.parser.parse(schemaxml);
    //xmlDocValue = dojox.xml.parser.parse(valuexml);

    //    if (window.DOMParser) {
    //        doc = schemaxml;
    //    } else // Internet Explorer" + Environment.NewLine +
    //    {
    //        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    //        xmlDoc.async = "false";
    //        xmlDoc.loadXML(schemaxml);
    //        doc = $(xmlDoc).children();
    //    }
    if (xmlDoc.documentElement && xmlDoc.documentElement.hasChildNodes()) {
        childNodes = xmlDoc.documentElement.childNodes;
        for (i = 0; i < childNodes.length; i++) {
            childAttributes = childNodes[i].attributes;
            value = '';
            for (j = 0; j < childAttributes.length; j++) {
                if (childAttributes[j].name == 'type') {
                    type = childAttributes[j].value;
                } else if (childAttributes[j].name == 'propertyid') {
                    id = childAttributes[j].value;
                }
            }
            if (type == 'True/false') {
                value = ($("input[id$='field" + dtdid + "_" + id + "']").is(':checked') ? '1' : '0');
            } else if (type == 'Content picker' || type == 'Media picker') {
                value = $("input[id$='field" + dtdid + "_" + id + "_ContentIdValue']").val();
            } else if (type == 'Date picker') {
                value = $("td[id$='field" + dtdid + "_" + id + "'] input").val();
            } else if (type == 'Textbox multiple' || type == 'Simple editor') {
                value = $("textarea[id$='field" + dtdid + "_" + id + "']").val();
            } else {
                value = $("input[id$='field" + dtdid + "_" + id + "']").val();
            }
            schemaxml = schemaxml.replace('|value' + id + '|', value.replace(/&/gi, '&').replace(/</gi, '<').replace(/>/gi, '>'));
        }
    }
    //    $(doc).children().each(function () {
    //        id = $(this).attr('propertyid');
    //        //check for different types
    //        value = '';
    //        type = $(this).attr('type');
    //        if (type == 'True/false') {
    //            value = ($("input[id$='field" + dtdid + "_" + id + "']").is(':checked') ? '1' : '0');
    //        } else if (type == 'Content picker' || type == 'Media picker') {
    //            value = $("input[id$='field" + dtdid + "_" + id + "_ContentIdValue']").val();
    //        } else if (type == 'Date picker') {
    //            value = $("td[id$='field" + dtdid + "_" + id + "'] input").val();
    //        } else if (type == 'Textbox multiple' || type == 'Simple editor') {
    //            value = $("textarea[id$='field" + dtdid + "_" + id + "']").val();
    //        } else {
    //            value = $("input[id$='field" + dtdid + "_" + id + "']").val();
    //        }
    //        schemaxml = schemaxml.replace('|value' + id + '|', value.replace(/&/gi, '&').replace(/</gi, '<').replace(/>/gi, '>'));
    //    });
    if (editId == '') {
        valuexml = valuexml.replace(/<\/data>/, schemaxml + '</data>');
    } else {
        regex = new RegExp('<item id="' + editId + '"([^<]|<[^\/]|<\/[^i]|<\/i[^t]|<\/it[^e]|<\/ite[^m]|<\/item[^>])*<\/item>');
        valuexml = valuexml.replace(regex, schemaxml);
    }
    $("input[id$='hiddenXmlValue" + dtdid + "']").val(encodeURIComponent(valuexml));
    EC.PopulateListFromHiddenValue(dtdid);
    EC.SetBigButtonBackground(false);
    EC.ClearFields(dtdid);
    $("div#addBox" + dtdid).hide();
    $("a#addLink" + dtdid).show();
    return false;
}

TheFarm.Umbraco.EmbeddedContent.InitializeDragSort = function(dtdid) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    $("ul#sortList" + dtdid).dragsort({
        dragEnd: function () { EC.WriteHiddenValueFromList(dtdid); },
        dragSelector: "div.ECdraghandle"
    });
}

TheFarm.Umbraco.EmbeddedContent.PopulateListFromHiddenValue = function(dtdid) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    $('ul#sortList' + dtdid).html('');
    //hiddenXmlValueId = 'EChiddenXmlValue' + dtdid;
    xml = decodeURIComponent($("input[id$='hiddenXmlValue" + dtdid + "']").val());
    if( window.DOMParser )
    {
        parser=new DOMParser();
        xmlDoc=parser.parseFromString(xml,"text/xml");
    }
    else // Internet Explorer
    {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xml);
    }
    $(xmlDoc).find('item').each(function(){
        li = EC.htmlLiStart +
            EC.htmlDragHandle +
            EC.htmlSpanStart +
            $(this).attr('id') +
            EC.htmlSpanEnd +
            EC.htmlTextDivStart;
        separator = '';
        $(this).children().each(function(){
            if ($(this).attr('showintitle') == 'True'){
                li += separator + $(this).text();  // + $(this) + ': '
                separator = ', ';
            }
        });
        li += EC.htmlEditButton +
            EC.htmlRemoveButton +
            EC.htmlTextDivEnd +
            EC.htmlLiEnd;
        $('ul#sortList' + dtdid).append(li);
    });
}

TheFarm.Umbraco.EmbeddedContent.ResetLIs = function(dtdid) {
    $('ul#sortList' + dtdid + ' li').each(function(){
        $(this).removeClass('EChighlight').removeClass('ECregular').addClass('ECregular');
    });
}

//Clears out the add box fields
TheFarm.Umbraco.EmbeddedContent.ClearFields = function (dtdid) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    $("input#hiddenEditId" + dtdid).val('');
    schemaxml = decodeURIComponent($("input[id$='EChiddenXmlSchema" + dtdid + "']").val());
    if (window.DOMParser) {
        $(schemaxml).children().each(function () {
            //check for different types
            EC.ClearField($(this).attr('propertyid'), $(this).attr('type'), dtdid);
            EC.UnmarkField(dtdid, $(this).attr('propertyid'), $(this).attr('type'));
        });
    }
    else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(schemaxml);
        xmlDoc.onreadystatechange = function () { if (xmlDoc.readyState != 4) return false; };
        if (xmlDoc.documentElement && xmlDoc.documentElement.hasChildNodes()) {
            childNodes = xmlDoc.documentElement.childNodes;
            for (i = 0; i < childNodes.length; i++) {
                attributes = childNodes[i].attributes;
                for (j = 0; j < attributes.length; j++) {
                    if (attributes[j].name == 'type') {
                        type = attributes[j].value;
                    } else if (attributes[j].name == 'propertyid') {
                        id = attributes[j].value;
                    }
                }
                EC.ClearField(id, type, dtdid);
                EC.UnmarkField(dtdid, id, type);
            }
        }
    }
}

TheFarm.Umbraco.EmbeddedContent.ClearField = function (id, type, dtdid) {
    if (type == 'True/false') {
        $("input[id$='field" + dtdid + "_" + id + "']").removeAttr('checked');
    } else if (type == 'Content picker' || type == 'Media picker') {
        $("input[id$='field" + dtdid + "_" + id + "_ContentIdValue']").val('');
        $("span[id$='field" + dtdid + "_" + id + "_btns']").hide();
        $("span[id$='field" + dtdid + "_" + id + "_title']").html('');
    } else if (type == 'Date picker') {
        $("td[id$='field" + dtdid + "_" + id + "'] input").val('');
    } else if (type == 'Textbox multiple' || type == 'Simple editor') {
        $("textarea[id$='field" + dtdid + "_" + id + "']").val('');
    } else {
        $("input[id$='field" + dtdid + "_" + id + "']").val('');
    }
}

TheFarm.Umbraco.EmbeddedContent.AddLinkClicked = function (dtdid, addLink) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    if (!EC.CheckMaxCount(dtdid)) return false;
    EC.ResetLIs(dtdid);
    $("input#hiddenEditId" + dtdid).val('');
    $("div#addBox" + dtdid).show();
    addLink.hide();
    $("a#addPropertyLink" + dtdid + " div.ECbigButton").css('background-position', '0px -80px');
    EC.ClearFields(dtdid);
    EC.SetFocusOnFirstElement(dtdid);
    return false;
}

TheFarm.Umbraco.EmbeddedContent.CloseLinkClicked = function (dtdid) {
    EC = TheFarm.Umbraco.EmbeddedContent;
    EC.ResetLIs(dtdid);
    EC.ClearFields(dtdid);
    $("div#addBox" + dtdid).hide();
    $("a#addLink" + dtdid).show();
    return false;
}

//Sets the focus on the first item when 'add' or 'edit' is clicked
TheFarm.Umbraco.EmbeddedContent.SetFocusOnFirstElement = function (dtdid) {
    schemaxml = decodeURIComponent($("input[id$='EChiddenXmlSchema" + dtdid + "']").val());
    if (window.DOMParser) {
        doc = schemaxml;
    } else // Internet Explorer" + Environment.NewLine +
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(schemaxml);
        doc = $(xmlDoc).children();
    }
    firstItem = $(doc).children(":first");
    if (firstItem) {
        id = firstItem.attr('propertyid');
        type = firstItem.attr('type');

        if (type == 'True/false') {
            $("input[id$='field" + dtdid + "_" + id + "']").focus();
        } else if (type == 'Content picker' || type == 'Media picker') {
            $("span[id$='field" + dtdid + "_" + id + "_btns']").next().focus();
        } else if (type == 'Simple editor') {
            $("textarea[id$='field" + dtdid + "_" + id + "']").focus().select();
        } else if (type == 'Date picker') {
            $("td[id$='field" + dtdid + "_" + id + "'] input").next().focus();
        } else if (type == 'Textbox multiple') {
            $("textarea[id$='field" + dtdid + "_" + id + "']").focus().select();
        } else {
            $("input[id$='field" + dtdid + "_" + id + "']").focus().select();
        }
    }
}


text:
Toolkit for building WebKit-based overlays for SteamVR.

Honestly, I'm awful at writing documentation so part of me is hoping someone else will come along and write one. SteamVR-WebKit-Test should tell you a lot about what you need to use this though.


text:
$currentWorkingDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
. $currentWorkingDir\env_asm.ps1

function updateVMImage(
   [String] $imageName,
   [String] $description,
   [String] $labelImgFamily,
   [String] $recommendedVMSize,
   [String] $subscriptionName)
{
   Try
   {
       # Prepare subscription and storage account
       Set-AzureSubscription -SubscriptionName $subscriptionName -CurrentStorageAccountName $storageAccount
       Select-AzureSubscription -Current -SubscriptionName $subscriptionName

       $publishedDate = Get-Date -Format MM/dd/yyyy
       gLogMsg "Update-AzureVMImage -ImageName $imageName -Label $labelImgFamily -RecommendedVMSize $recommendedVMSize -Description '$description' -PublishedDate $publishedDate" # -Eula $eula "
       Update-AzureVMImage -ImageName $imageName -Label $labelImgFamily `
                           -RecommendedVMSize $recommendedVMSize -Description $description `
                           -PublishedDate $publishedDate #-Eula $eula
   } Catch {
       gLogMsg "Upload Failed."
       gLogMsg $ERROR[0].Exception
   }
   return $False
}

gLogin

updateVMImage $vmImageName $imageDescription $vmLabelImageFamily $recommendedVMSize $subscriptionName


text:
![2ret-vim image][2ret-vim-img-1]

2ret-vim is a distribution of vim plugins and resources for Vim, Gvim and [MacVim].

The distribution is completely customisable using a `~/.vimrc.local`
and `~/.vimrc.bundles.local` Vim RC files.

# INSTALLATION (Linux, Mac OSX Installation)

The easiest way to install 2ret-vim is to use our [automatic installer](http://2ret.com/vim)
by simply copying and pasting the following line into a terminal.
This will install 2ret-vim and backup your existing vim configuration.

```bash
    curl http://2ret.com/vim -L -o - | sh
```

## Requirements:

* git (ex: ubuntu `apt-get install git-core`)
* vim 7.4+ _with lua support_
* curl

> __IMPORTANT:__
> To make all the plugins work, specifically [neocomplete](https://github.com/Shougo/neocomplete.vim),
> you need [vim with lua](https://github.com/Shougo/neocomplete.vim#requirements).

On Mac OSX, with homebrew, you would do something like this to reinstall your terminal vim with lua support:

```bash
$ brew update && brew uninstall --force vim && brew install vim --with-lua
```

## Updating to the latest version

The simpliest (and safest) way to update is to simply rerun the installer.
It will completely and non destructively upgrade to the latest version.

```bash
    curl http://2ret.com/vim -L -o - | sh
```

Alternatively you can manually perform the following steps.
If anything has changed with the structure of the configuration you will need to create the appropriate symlinks.

```bash
    cd $HOME/.2ret-vim/
    git pull
    vim +PluginInstall! +PluginClean +qall
```

# OPTIMIZED .vimrc CONFIG FILE

![2ret-vim vimrc image][2ret-vim-vimrc]

The .vimrc file is suited to programming. It is well organized and
folds in sections. Each section is labeled and each option is commented.

It fixes many of the inconveniences of vanilla vim including

 * A single config can be used across Windows, Mac and linux
 * Eliminates swap and backup files from littering directories, preferring to store in a central location.
 * Fixes common typos like :W, :Q, etc
 * Setup a solid set of settings for Formatting (change to meet your needs)
 * Setup the interface to take advantage of vim's features including
   * omnicomplete
   * line numbers
   * syntax highlighting
   * A better ruler & status line
   * & more
 * Configuring included plugins
 * Automatically remove trailing whitespaces when saving a file

It uses [Vundle] which has an excellent system built on the same principles as Pathogen,
but with an integrated plugin management system that is Git and Github aware.

## Some Basic Mappings

The `leader` key is mapped to `,`

* `<leader><leader>`            - switch between the currently open buffer and the previous one
* `<leader><space>`             - remove search highlighting
* `<leader>w`                   - open a new vertical split window and switch to it
* `<leader>z`                   - zoom In/Out current window
* `Y`                           - yank from cursor to end of line
* `arrows`                      - inactive, please use `h,j,k,l`

### Function Keys Mappings

* `F2`  - when you want to paste something in terminal, toggle to paste mode
* `F5`  - toggle the undotree panel
* `F6`  - open extradite for the current file
* `F8`  - toggle the tagbar panel
* `F12` - validate the current buffer as json

### Vim in the Terminal with [Tmux](https://tmux.github.io/)

    TODO: Tricks, gotchas (cut/paste, etc...)

## Customization

Create `~/.vimrc.local` and `~/.gvimrc.local` for any local
customizations.

For example, to override the default color schemes:

```bash
    echo colorscheme ir_black  >> ~/.vimrc.local
```

# PLUGINS

## Adding new plugins

Create `~/.vimrc.bundles.local` for any additional bundles.

To add a new bundle

```bash
    echo Bundle \'2ret-vim/vim-colors\' >> ~/.vimrc.bundles.local
```

Then to install or update bundles and remove obsolete ones:
```bash
vim +PluginInstall! +PluginClean +qall
```

Here are a few of the plugins:

## [Surround]

This plugin is a tool for dealing with pairs of "surroundings."  Examples
of surroundings include parentheses, quotes, and HTML tags.  They are
closely related to what Vim refers to as text-objects.  Provided
are mappings to allow for removing, changing, and adding surroundings.

Details follow on the exact semantics, but first, consider the following
examples.  An asterisk (*) is used to denote the cursor position.

      Old text                  Command     New text ~
      "Hello *world!"           ds"         Hello world!
      [123+4*56]/2              cs])        (123+456)/2
      "Look ma, I'm *HTML!"     cs"<q>      <q>Look ma, I'm HTML!</q>
      if *x>3 {                 ysW(        if ( x>3 ) {
      my $str = *whee!;         vlllls'     my $str = 'whee!';

For instance, if the cursor was inside `"foo bar"`, you could type
`cs"'` to convert the text to `'foo bar'`.

There's a lot more, check it out at `:help surround`

## [Vim-vinegar]

vinegar.vim enhances [netrw](http://vimcasts.org/episodes/the-file-explorer/), partially in an attempt to mitigate the need for more disruptive "project drawer" style plugins.

**QuickStart** Press `-` in any buffer to hop up to the directory listing and seek to the file you just came from.

## [Vim-commentary]

**QuickStart** `gcc` to comment or uncomment a text selection

Want to comment 3 lines? Try `3gcc`

## [Neocomplete]

Neocomplete is an autocomplete plugin.
It can complete simultaniously from the dictionary, buffer, omnicomplete.

**QuickStart** Just start typing, it will autocomplete where possible

**Customizations**:

 * Automatically present the autocomplete menu
 * Support tab and enter for autocomplete

## [Fugitive]

Fugitive adds pervasive git support to git directories in vim. For more
information, use `:help fugitive`

Use `:Gstatus` to view `git status` and type `-` on any file to stage or
unstage it. Type `p` on a file to enter `git add -p` and stage specific
hunks in the file.

Use `:Gdiff` on an open file to see what changes have been made to that
file

**QuickStart** `<leader>gs` to bring up git status

**Customizations**:

 * `<leader>gs` :Gstatus<CR>
 * `<leader>gd` :Gdiff<CR>
 * `<leader>gc` :Gcommit<CR>
 * `<leader>gb` :Gblame<CR>
 * `<leader>gl` :Glog<CR>
 * `<leader>gp` :Git push<CR>
 * :Git will pass anything along to git.

For more: [vimcast: Fugitive](http://vimcasts.org/episodes/fugitive-vim---a-complement-to-command-line-git/)

## [Vim-multiple-cursors]

A great plugin for quick refactoring!

![vim-multiple-cursors image][vim-multiple-cursors-img]

**QuickStart** `<CTRL-n>`

Out of the box, all you need to know is a single key `Ctrl-n`. Pressing the key in Normal mode highlights the current word under the cursor in Visual mode and places a virtual cursor at the end of it. Pressing it again finds the next ocurrence and places another virtual cursor at the end of the visual selection. If you select multiple lines in Visual mode, pressing the key puts a virtual cursor at every line and leaves you in Normal mode.

After you've marked all your locations with `Ctrl-n`, you can change the visual selection with normal Vim motion commands in Visual mode. You could go to Normal mode by pressing `v` and wield your motion commands there. Single key command to switch to Insert mode such as `c` or `s` from Visual mode or `i`, `a`, `I`, `A` in Normal mode should work without any issues.

At any time, you can press `<Esc>` to exit back to regular Vim.

## [Ack.vim]

Ack.vim uses ack to search inside the current directory for a pattern.
You can learn more about it with :help Ack

**QuickStart** `:Ack`

**Customization** `<leader>A` will `Ack` the word under your cursor.

## [Tagbar]

Plugin for browsing the tags of source code files.
It provides a sidebar that displays the ctags-generated tags of the current
file, ordered by their scope.

**QuickStart** `CTRL-]` while the cursor is on a keyword (such as a function name)
to jump to it's definition.

**Customizations**: 2ret-vim binds `<F8>` to toggle the tagbar panel

    Install dependency with exuberant ctags

    install http://ctags.sf.net
    ex: ubuntu `sudo apt-get install exuberant-ctags`
    ex: macos `brew install ctags && sudo mv /usr/bin/ctags /usr/bin/ctags.bak`

    Run ctags -R in project root to generate tags

## [ZoomWin]

Quickly make the current window zooms into a full screen and when done,
restore the previous set of windows.

**QuickStart** `<leader>z`

## [Ctrlp.vim]

Ctrlp provides an intuitive and fast mechanism to load files from the file system
(with regex and fuzzy find), from open buffers, and from recently used files.

**QuickStart** `<CTRL>-p`: will run the find file mode.

**Shortcuts**

* `1<CTRL>-p`: will run `:CtrlPBuffer`, the open buffers mode.
* `2<CTRL>-p`: will run `:CtrlPMRU`, the MRU files mode.

### [ctrlp-funky](https://github.com/tacahiroy/ctrlp-funky)

Very simple function navigator for ctrlp.vim.

**QuickStart** `<leader>-fu`: to navigate and jump to function definitions from the current file without ctags

## [Undotree]

If you undo changes and then make a new change, in most editors the changes you undid are gone forever, as their undo-history is a simple list.
Since version 7.0 vim uses an undo-tree instead. If you make a new change after undoing changes, a new branch is created in that tree.
Combined with persistent undo, this is nearly as flexible and safe as git ;-)

Undotree makes that feature more accessible by creating a visual representation of said undo-tree.

**QuickStart** `F5`

## [Gist]

Gist current file/selection

Requires setting GITHUB_TOKEN and GITHUB_USER Env's

**QuickStart** `:Gist`

## [Turbux]

**QuickStart** `<leader>r` run current file's specs

**Other Shortcuts**:

 * `<leader>R` run closest specs
 * `<leader>g` run all project's specs

# Intro to VIM

Here's some tips if you've never used VIM before:

## Tutorials

* Type `vimtutor` into a shell to go through a brief interactive
  tutorial inside VIM.
* Read the slides by Drew Neil at [VIM: Walking Without Crutches](http://walking-without-crutches.heroku.com/#1).
* Blog post by Yann Esposito: [Learn Vim Progressively](http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/)
* Blog post by Mislav Marohnić: [Vim: revisited](http://mislav.uniqpath.com/2011/12/vim-revisited/)
* Blog post by Michael Jakl: [Vim Introduction and Tutorial](http://blog.interlinked.org/tutorials/vim_tutorial.html)
* Blog post by Jon Beltran de Heredia: [Why, oh WHY, do those #?@! nutheads use vi?](http://www.viemu.com/a-why-vi-vim.html)

## Modes

* VIM has two (common) modes:
  * insert mode- stuff you type is added to the buffer
  * normal mode- keys you hit are interpreted as commands
* To enter insert mode, hit `i`
* To exit insert mode, hit `<ESC>`

## Useful commands

* Use `:q` to exit vim
* Certain commands are prefixed with a `<Leader>` key, which by default maps to `\`.
  2ret-vim uses `let mapleader = ","` to change this to `,` which is in a consistent and
  convenient location.

### Vim cheat sheet

[source cheatsheet](http://vimcheatsheet.com/)

![vim cheatsheet image][vim-cheatsheet]

### Keyboard cheat sheet

[source cheatsheet](http://walking-without-crutches.heroku.com/image/images/vi-vim-cheat-sheet.png)

![vim key mapping cheatsheet image][vim-key-mapping-img]

# CREDITS

Strongly inspired by [spf13-vim : Steve Francia's Vim Distribution](https://github.com/spf13/spf13-vim)

[2ret-vim]:https://github.com/benichu/2ret-vim
[MacVim]:http://code.google.com/p/macvim/
[spf13-vim]:https://github.com/spf13/spf13-vim

[Ack.vim]:https://github.com/mileszs/ack.vim
[Ctrlp.vim]:https://github.com/kien/ctrlp.vim.git
[Fugitive]:http://github.com/tpope/vim-fugitive
[Gist]:https://github.com/mattn/gist-vim
[Gundo]:https://github.com/sjl/gundo.vim
[Matchit]:"http://www.vim.org/scripts/script.php?script_id=39
[Neocomplete]:https://github.com/Shougo/neocomplete.vim
[Surround]:https://github.com/tpope/vim-surround
[Tabularize]:http://github.com/godlygeek/tabular
[Tagbar]:http://github.com/majutsushi/tagbar
[Undotree]:https://github.com/mbbill/undotree
[Vim-commentary]:http://github.com/tpope/vim-commentary
[Vim-vinegar]:http://github.com/tpope/vim-vinegar
[Vim-multiple-cursors]:https://github.com/terryma/vim-multiple-cursors
[Vundle]:http://github.com/gmarik/vundle
[ZoomWin]:https://github.com/vim-scripts/ZoomWin
[Turbux]:http://joshuadavey.com/2012/01/10/faster-tdd-feedback-with-tmux-tslime-vim-and-turbux

[2ret-vim-img-1]:http://storage.thouret.com.s3.amazonaws.com/monosnap/1._tmux_2016-05-14_09-16-41.png
[2ret-vim-vimrc]:http://storage.thouret.com.s3.amazonaws.com/monosnap/1._tmux_2016-05-14_09-14-24.png
[vim-cheatsheet]:http://i.imgur.com/PQQrd.png
[vim-key-mapping-img]:http://i.imgur.com/hP67T.png
[vim-multiple-cursors-img]:http://i.imgur.com/ajqUJM2.gif


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=4 sw=4 et tw=99:
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef jsion_frames_inl_h__
#define jsion_frames_inl_h__

#include "ion/IonFrames.h"
#include "ion/IonFrameIterator.h"
#include "ion/LIR.h"

namespace js {
namespace ion {

inline void
SafepointIndex::resolve()
{
    JS_ASSERT(!resolved);
    safepointOffset_ = safepoint_->offset();
    resolved = true;
}

static inline size_t
SizeOfFramePrefix(FrameType type)
{
    switch (type) {
      case IonFrame_Entry:
        return IonEntryFrameLayout::Size();
      case IonFrame_JS:
      case IonFrame_Bailed_JS:
        return IonJSFrameLayout::Size();
      case IonFrame_Rectifier:
        return IonRectifierFrameLayout::Size();
      case IonFrame_Bailed_Rectifier:
        return IonBailedRectifierFrameLayout::Size();
      case IonFrame_Exit:
        return IonExitFrameLayout::Size();
      case IonFrame_Osr:
        return IonOsrFrameLayout::Size();
      default:
        JS_NOT_REACHED("unknown frame type");
    }
    return 0;
}

inline IonCommonFrameLayout *
IonFrameIterator::current() const
{
    return (IonCommonFrameLayout *)current_;
}

inline uint8 *
IonFrameIterator::returnAddress() const
{
    IonCommonFrameLayout *current = (IonCommonFrameLayout *) current_;
    return current->returnAddress();
}

inline size_t
IonFrameIterator::prevFrameLocalSize() const
{
    IonCommonFrameLayout *current = (IonCommonFrameLayout *) current_;
    return current->prevFrameLocalSize();
}

inline FrameType
IonFrameIterator::prevType() const
{
    IonCommonFrameLayout *current = (IonCommonFrameLayout *) current_;
    return current->prevType();
}

size_t
IonFrameIterator::frameSize() const
{
    JS_ASSERT(type_ != IonFrame_Exit);
    return frameSize_;
}

// Returns the JSScript associated with the topmost Ion frame.
inline JSScript *
GetTopIonJSScript(JSContext *cx, const SafepointIndex **safepointIndexOut, void **returnAddrOut)
{
    IonFrameIterator iter(cx->runtime->ionTop);
    JS_ASSERT(iter.type() == IonFrame_Exit);
    ++iter;

    // If needed, grab the safepoint index.
    if (safepointIndexOut)
        *safepointIndexOut = iter.safepoint();

    JS_ASSERT(iter.returnAddressToFp() != NULL);
    if (returnAddrOut)
        *returnAddrOut = (void *) iter.returnAddressToFp();

    JS_ASSERT(iter.type() == IonFrame_JS);
    IonJSFrameLayout *frame = static_cast<IonJSFrameLayout*>(iter.current());
    switch (GetCalleeTokenTag(frame->calleeToken())) {
      case CalleeToken_Function: {
        JSFunction *fun = CalleeTokenToFunction(frame->calleeToken());
        return fun->script();
      }
      case CalleeToken_Script:
        return CalleeTokenToScript(frame->calleeToken());
      default:
        JS_NOT_REACHED("unexpected callee token kind");
        return NULL;
    }
}

} // namespace ion
} // namespace js

#endif // jsion_frames_inl_h__


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: ./core/src/java/org/apache/lucene/index/TermsHashPerField.java
//

#include "J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneIndexTermsHashPerField")
#ifdef RESTRICT_OrgApacheLuceneIndexTermsHashPerField
#define INCLUDE_ALL_OrgApacheLuceneIndexTermsHashPerField 0
#else
#define INCLUDE_ALL_OrgApacheLuceneIndexTermsHashPerField 1
#endif
#undef RESTRICT_OrgApacheLuceneIndexTermsHashPerField

#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif

#if !defined (OrgApacheLuceneIndexTermsHashPerField_) && (INCLUDE_ALL_OrgApacheLuceneIndexTermsHashPerField || defined(INCLUDE_OrgApacheLuceneIndexTermsHashPerField))
#define OrgApacheLuceneIndexTermsHashPerField_

#define RESTRICT_JavaLangComparable 1
#define INCLUDE_JavaLangComparable 1
#include "java/lang/Comparable.h"

@class IOSByteArray;
@class IOSIntArray;
@class OrgApacheLuceneIndexByteSliceReader;
@class OrgApacheLuceneIndexDocumentsWriterPerThread_DocState;
@class OrgApacheLuceneIndexFieldInfo;
@class OrgApacheLuceneIndexFieldInvertState;
@class OrgApacheLuceneIndexParallelPostingsArray;
@class OrgApacheLuceneIndexTermsHash;
@class OrgApacheLuceneUtilByteBlockPool;
@class OrgApacheLuceneUtilBytesRefHash;
@class OrgApacheLuceneUtilIntBlockPool;
@protocol OrgApacheLuceneAnalysisTokenattributesTermToBytesRefAttribute;
@protocol OrgApacheLuceneIndexIndexableField;

@interface OrgApacheLuceneIndexTermsHashPerField : NSObject < JavaLangComparable > {
 @public
  OrgApacheLuceneIndexTermsHash *termsHash_;
  OrgApacheLuceneIndexTermsHashPerField *nextPerField_;
  OrgApacheLuceneIndexDocumentsWriterPerThread_DocState *docState_;
  OrgApacheLuceneIndexFieldInvertState *fieldState_;
  id<OrgApacheLuceneAnalysisTokenattributesTermToBytesRefAttribute> termAtt_;
  OrgApacheLuceneUtilIntBlockPool *intPool_;
  OrgApacheLuceneUtilByteBlockPool *bytePool_;
  OrgApacheLuceneUtilByteBlockPool *termBytePool_;
  jint streamCount_;
  jint numPostingInt_;
  OrgApacheLuceneIndexFieldInfo *fieldInfo_;
  OrgApacheLuceneUtilBytesRefHash *bytesHash_;
  OrgApacheLuceneIndexParallelPostingsArray *postingsArray_;
  IOSIntArray *sortedTermIDs_;
  IOSIntArray *intUptos_;
  jint intUptoStart_;
}

#pragma mark Public

/*!
 @brief streamCount: how many streams this field stores per term.
 E.g. doc(+freq) is 1 stream, prox+offset is a second.
 */
- (instancetype __nonnull)initPackagePrivateWithInt:(jint)streamCount
           withOrgApacheLuceneIndexFieldInvertState:(OrgApacheLuceneIndexFieldInvertState *)fieldState
                  withOrgApacheLuceneIndexTermsHash:(OrgApacheLuceneIndexTermsHash *)termsHash
          withOrgApacheLuceneIndexTermsHashPerField:(OrgApacheLuceneIndexTermsHashPerField *)nextPerField
                  withOrgApacheLuceneIndexFieldInfo:(OrgApacheLuceneIndexFieldInfo *)fieldInfo;

- (void)addWithInt:(jint)textStart;

- (jint)compareToWithId:(OrgApacheLuceneIndexTermsHashPerField *)other;

- (void)initReaderWithOrgApacheLuceneIndexByteSliceReader:(OrgApacheLuceneIndexByteSliceReader *)reader
                                                  withInt:(jint)termID
                                                  withInt:(jint)stream OBJC_METHOD_FAMILY_NONE;

/*!
 @brief Collapse the hash table and sort in-place; also sets
  this.sortedTermIDs to the results
 */
- (IOSIntArray *)sortPostings;

- (void)writeBytesWithInt:(jint)stream
            withByteArray:(IOSByteArray *)b
                  withInt:(jint)offset
                  withInt:(jint)len;

#pragma mark Package-Private

/*!
 @brief Called once per inverted token.This is the primary
   entry point (for first TermsHash); postings use this
   API.
 */
- (void)add;

/*!
 @brief Called when a previously seen term is seen again.
 */
- (void)addTermWithInt:(jint)termID;

/*!
 @brief Creates a new postings array of the specified size.
 */
- (OrgApacheLuceneIndexParallelPostingsArray *)createPostingsArrayWithInt:(jint)size;

/*!
 @brief Finish adding all instances of this field to the
   current document.
 */
- (void)finish;

/*!
 @brief Called when the postings array is initialized or
   resized.
 */
- (void)newPostingsArray OBJC_METHOD_FAMILY_NONE;

/*!
 @brief Called when a term is seen for the first time.
 */
- (void)newTermWithInt:(jint)termID OBJC_METHOD_FAMILY_NONE;

- (void)reset;

/*!
 @brief Start adding a new field instance; first is true if
   this is the first time this field name was seen in the
   document.
 */
- (jboolean)startWithOrgApacheLuceneIndexIndexableField:(id<OrgApacheLuceneIndexIndexableField>)field
                                            withBoolean:(jboolean)first;

- (void)writeByteWithInt:(jint)stream
                withByte:(jbyte)b;

- (void)writeVIntWithInt:(jint)stream
                 withInt:(jint)i;

// Disallowed inherited constructors, do not use.

- (instancetype __nonnull)init NS_UNAVAILABLE;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneIndexTermsHashPerField)

J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, termsHash_, OrgApacheLuceneIndexTermsHash *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, nextPerField_, OrgApacheLuceneIndexTermsHashPerField *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, docState_, OrgApacheLuceneIndexDocumentsWriterPerThread_DocState *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, fieldState_, OrgApacheLuceneIndexFieldInvertState *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, termAtt_, id<OrgApacheLuceneAnalysisTokenattributesTermToBytesRefAttribute>)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, intPool_, OrgApacheLuceneUtilIntBlockPool *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, bytePool_, OrgApacheLuceneUtilByteBlockPool *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, termBytePool_, OrgApacheLuceneUtilByteBlockPool *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, fieldInfo_, OrgApacheLuceneIndexFieldInfo *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, bytesHash_, OrgApacheLuceneUtilBytesRefHash *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, postingsArray_, OrgApacheLuceneIndexParallelPostingsArray *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, sortedTermIDs_, IOSIntArray *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexTermsHashPerField, intUptos_, IOSIntArray *)

FOUNDATION_EXPORT void OrgApacheLuceneIndexTermsHashPerField_initPackagePrivateWithInt_withOrgApacheLuceneIndexFieldInvertState_withOrgApacheLuceneIndexTermsHash_withOrgApacheLuceneIndexTermsHashPerField_withOrgApacheLuceneIndexFieldInfo_(OrgApacheLuceneIndexTermsHashPerField *self, jint streamCount, OrgApacheLuceneIndexFieldInvertState *fieldState, OrgApacheLuceneIndexTermsHash *termsHash, OrgApacheLuceneIndexTermsHashPerField *nextPerField, OrgApacheLuceneIndexFieldInfo *fieldInfo);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneIndexTermsHashPerField)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneIndexTermsHashPerField")


text:
package org.assertj.android.api.view;

import android.support.annotation.IntDef;
import android.view.View;
import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.SOURCE;

@IntDef({
    View.TEXT_ALIGNMENT_INHERIT,
    View.TEXT_ALIGNMENT_GRAVITY,
    View.TEXT_ALIGNMENT_TEXT_START,
    View.TEXT_ALIGNMENT_TEXT_END,
    View.TEXT_ALIGNMENT_CENTER,
    View.TEXT_ALIGNMENT_VIEW_START,
    View.TEXT_ALIGNMENT_VIEW_END
})
@Retention(SOURCE)
@interface ViewTextAlignment {
}


text:
package com.rackspacecloud.client.service_registry.curator;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.curator.framework.listen.ListenerContainer;
import com.netflix.curator.x.discovery.ServiceCache;
import com.netflix.curator.x.discovery.ServiceInstance;
import com.netflix.curator.x.discovery.details.ServiceCacheListener;
import com.rackspacecloud.client.service_registry.MethodOptions;
import com.rackspacecloud.client.service_registry.objects.Event;
import com.rackspacecloud.client.service_registry.objects.EventType;
import com.rackspacecloud.client.service_registry.objects.ServicePayload;

import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;

public class RSRServiceCacheImpl<T> implements ServiceCache<T> {

    private final RSRServiceDiscoveryImpl<T> discovery;
    private final ListenerContainer<ServiceCacheListener> listenerContainer = new ListenerContainer<ServiceCacheListener>();
    private final ConcurrentMap<String, ServiceInstance<T>> instances = Maps.newConcurrentMap();
    private final String name;

    private volatile Thread eventPoller = null;
    private volatile boolean shouldStopPolling = false;

    public RSRServiceCacheImpl(RSRServiceDiscoveryImpl<T> discovery, String name) {
        this.discovery = discovery;
        this.name = name;
    }

    //
    // ServiceCache methods (includes method of InstanceProvider<T>)
    //

    public List<ServiceInstance<T>> getInstances() {
        return Collections.unmodifiableList(Lists.newArrayList(instances.values()));
    }

    public synchronized void start() throws Exception {
        if (eventPoller != null) return;
        shouldStopPolling = false;

        eventPoller = new Thread("Event poller for " + discovery.getClient()) {
            @Override
            public void run() {
                while (!shouldStopPolling) {
                    pollAndProcessEvents();
                }
                eventPoller = null;
                shouldStopPolling = false;
            }
        };

        // backfill existing services.
        List<String> names = new ArrayList<String>();
        if (this.name != null) {
            names.add(this.name);
        } else {
            for (String name : discovery.queryForNames()) {
                names.add(name);
            }
        }
        for (String name : names) {
            for (ServiceInstance<T> instance : discovery.queryForInstances(name)) {
                instances.put(instance.getId(), instance);
            }
        }

        // start the polling thread.
        eventPoller.start();
    }

    //
    // java.io.Closeable
    //

    public synchronized void close() throws IOException {
        // again, nothing to do here.
        shouldStopPolling = true;
    }

    //
    // com.netflix.curator.framework.listen.Listenable
    //

    public void addListener(ServiceCacheListener serviceCacheListener) {
        listenerContainer.addListener(serviceCacheListener);
    }

    public void addListener(ServiceCacheListener serviceCacheListener, Executor executor) {
        listenerContainer.addListener(serviceCacheListener, executor);
    }

    public void removeListener(ServiceCacheListener serviceCacheListener) {
        listenerContainer.removeListener(serviceCacheListener);
    }

    // helpers

    private boolean isPertinent(Event e) {
        return (e.getPayload() instanceof ServicePayload)
               && ((ServicePayload)e.getPayload()).getService().getTags().contains(discovery.getType());
    }

    private String processEvents(List<Event> events) {
        String lastId = null;
        for (Event e : events) {
            lastId = e.getId();
            if (!isPertinent(e)) {
                continue;
            }
            // ideally, the dispatch happens on a separate thread.
            try {
                // listeners should do work.
                listenerContainer.forEach(new Function<ServiceCacheListener, Void>() {
                    public Void apply(@Nullable ServiceCacheListener serviceCacheListener) {
                        if (serviceCacheListener == null) return null;
                        serviceCacheListener.cacheChanged();
                        return null;
                    }
                });

                // make sure the local collection is maintained.
                final ServicePayload ee = (ServicePayload)e.getPayload();
                if (name == null || (name.equals(ee.getService().getMetadata().get("name")))) {
                    try {
                        if (e.getType() == EventType.SERVICE_JOINED) {
                            instances.put(ee.getService().getId(), discovery.convert(ee.getService()));
                        } else if (e.getType() == EventType.SERVICE_REMOVED || e.getType() == EventType.SERVICE_TIMEOUT) {
                            instances.remove(ee.getService().getId());
                        }
                    } catch (Exception fromConverter) {
                        // todo: log it.
                    }
                }
            } catch (Throwable th) {
                // bad listener! todo: log only.
            }
        }
        return lastId;
    }

    // pull a page of events, process that page, pull the next page, etc.
    // todo: switch to iterator.
    private void pollAndProcessEvents() {
        MethodOptions options = new MethodOptions(100, null);
        List<Event> events = null;
        int count = 0;
        do {
            if (shouldStopPolling) break;
            count += 1;
            try {
                // get events from server, filter the ones we are interested in.
                events = Lists.newArrayList(discovery.getClient().getEventsClient().list(options));
                String lastEventId = processEvents(events);
                options = options.withMarker(lastEventId);
            } catch (Exception ex) {
                // todo: just log it.
                events = null;
            }
        } while (events != null && events.size() > 0);

        // if it only happened once, assume there are not many events happening.
        if (count == 1) {
            // todo: trace message.
            // todo: this should become configurable.
            try { Thread.sleep(1000); } catch (Exception ex) {}
        }
    }
}


text:
package org.openstack.atlas.common.ip.exception;

public class IPStringConversionException1 extends IPException {

    public IPStringConversionException1() {
        super();
    }

    public IPStringConversionException1(String msg) {
        super(msg);
    }

    public IPStringConversionException1(String msg, Throwable th) {
        super(msg,th);
    }

    public IPStringConversionException1(Throwable th) {
        super(th);
    }
}


text:
package griffon.javafx.support;

import griffon.annotations.core.Nonnull;
import griffon.core.GriffonApplication;
import griffon.core.artifact.GriffonView;
import griffon.core.mvc.MVCGroup;
import griffon.javafx.artifact.ContentProvider;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.util.Builder;
import javafx.util.BuilderFactory;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static griffon.util.StringUtils.isBlank;
import static griffon.util.StringUtils.requireNonBlank;
import static java.util.Objects.requireNonNull;

/**
 * @author Andres Almiray
 * @since 2.12.0
 */
public class GriffonBuilderFactory implements BuilderFactory {
    protected final GriffonApplication application;
    protected final MVCGroup mvcGroup;
    protected final BuilderFactory delegate;

    public GriffonBuilderFactory(@Nonnull GriffonApplication application, @Nonnull MVCGroup mvcGroup) {
        this(application, mvcGroup, application.getApplicationClassLoader().get());
    }

    public GriffonBuilderFactory(@Nonnull GriffonApplication application, @Nonnull MVCGroup mvcGroup, @Nonnull ClassLoader classLoader) {
        this.application = requireNonNull(application, "Argument 'application' must not be null");
        this.mvcGroup = requireNonNull(mvcGroup, "Argument 'mvcGroup' must not be null");
        this.delegate = new JavaFXBuilderFactory(requireNonNull(classLoader, "Argument 'classLoader' must not be null"));
    }

    @Override
    public Builder<?> getBuilder(Class<?> type) {
        if (type == MetaComponent.class) {
            return new MetaComponentBuilder(application, mvcGroup);
        }
        return delegate.getBuilder(type);
    }

    private static class MetaComponentBuilder extends MetaComponent implements Builder<Object> {
        private final GriffonApplication application;
        private final MVCGroup mvcGroup;

        public MetaComponentBuilder(@Nonnull GriffonApplication application, @Nonnull MVCGroup mvcGroup) {
            this.application = requireNonNull(application, "Argument 'application' must not be null");
            this.mvcGroup = requireNonNull(mvcGroup, "Argument 'mvcGroup' must not be null");
        }

        @Override
        public Object build() {
            String mvcType = requireNonBlank(getMvcType(), "Must define a value for 'mvcType'");
            String mvcId = getMcvId();
            if (isBlank(mvcId) || application.getMvcGroupManager().findGroup(mvcId) != null) {
                mvcId = mvcType + "-" + UUID.randomUUID().toString();
            }

            MVCGroup group = mvcGroup.createMVCGroup(mvcType, mvcId, toMap(getMvcArgs()));
            GriffonView view = group.getView();
            if (view instanceof ContentProvider) {
                return ((ContentProvider) view).getContent();
            }
            return group.getContext().get(group.getMvcId() + "-rootNode");
        }

        @Nonnull
        private Map<String, Object> toMap(@Nonnull List<MvcArg> mvcArgs) {
            Map<String, Object> args = new LinkedHashMap<>();
            mvcArgs.forEach(arg -> args.put(arg.getName(), arg.getValue()));
            return args;
        }
    }
}


text:
This is a class for validating file uploads. It was made
before frameworks became a thing in the PHP world...


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>Symfony PhpDoc project</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="css/template.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="img/favicon.ico">
<link rel="apple-touch-icon" href="img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="img/apple-touch-icon-114x114.png">

Symfony PhpDoc project

                                    API Documentation

Namespaces

 Acme

 AppBundle

 Blogger

 global

Packages

 Default

                                    Charts

 Class hierarchy diagram

                                    Reports

 Errors
                117

 Markers

 Deprecated elements
                0

Back to top

                            Javascript is disabled; several features are only available
                            if Javascript is enabled.

Filter type

<button class="btn critical">Critical</button><button class="btn error">Error</button><button class="btn notice">Notice</button>

Navigation

vendor/doctrine/orm/bin/doctrine

vendor/doctrine/dbal/bin/doctrine-dbal

vendor/doctrine/orm/bin/doctrine.php

vendor/sensiolabs/security-checker/security-checker

src/Blogger/BlogBundle/Controller/DefaultController.php

src/Blogger/BlogBundle/Controller/PageController.php

src/Blogger/BlogBundle/Entity/Enquiry.php

src/Blogger/BlogBundle/BloggerBlogBundle.php

src/Blogger/BlogBundle/DependencyInjection/BloggerBlogExtension.php

src/Blogger/BlogBundle/DependencyInjection/Configuration.php

src/Blogger/BlogBundle/Form/EnquiryType.php

src/Blogger/BlogBundle/Tests/Controller/DefaultControllerTest.php

src/AppBundle/Controller/DefaultController.php

src/AppBundle/AppBundle.php

src/AppBundle/Tests/Controller/DefaultControllerTest.php

src/Acme/DemoBundle/EventListener/ControllerListener.php

src/Acme/DemoBundle/Command/HelloWorldCommand.php

src/Acme/DemoBundle/Controller/SecuredController.php

src/Acme/DemoBundle/Controller/DemoController.php

src/Acme/DemoBundle/Controller/WelcomeController.php

src/Acme/DemoBundle/AcmeDemoBundle.php

src/Acme/DemoBundle/Twig/Extension/DemoExtension.php

src/Acme/DemoBundle/DependencyInjection/AcmeDemoExtension.php

src/Acme/DemoBundle/Form/ContactType.php

src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php

\

Compilation Errors

vendor/doctrine/orm/bin/doctrine1

Type
Line
Description

error
0
No summary was found for this file

vendor/doctrine/dbal/bin/doctrine-dbal1

Type
Line
Description

error
0
No summary was found for this file

vendor/doctrine/orm/bin/doctrine.php1

Type
Line
Description

error
0
No summary was found for this file

vendor/sensiolabs/security-checker/security-checker3

Type
Line
Description

error
0
No summary was found for this file

error
13
Argument $file is missing from the Docblock of includeIfExists

error
13
No summary for function ""

src/Blogger/BlogBundle/Controller/DefaultController.php4

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

error
9
Argument $name is missing from the Docblock of indexAction

error
9
No summary for method ""

src/Blogger/BlogBundle/Controller/PageController.php5

Type
Line
Description

error
0
No summary was found for this file

error
8
No summary for class ""

error
13
No summary for method ""

error
21
No summary for method ""

error
29
No summary for method ""

src/Blogger/BlogBundle/Entity/Enquiry.php18

Type
Line
Description

error
0
No summary was found for this file

error
4
No summary for class ""

error
6
No summary for property $name

error
8
No summary for property $email

error
10
No summary for property $subject

error
12
No summary for property $body

error
14
No summary for method ""

error
19
Argument $name is missing from the Docblock of setName

error
19
No summary for method ""

error
24
No summary for method ""

error
29
Argument $email is missing from the Docblock of setEmail

error
29
No summary for method ""

error
34
No summary for method ""

error
39
Argument $subject is missing from the Docblock of setSubject

error
39
No summary for method ""

error
44
No summary for method ""

error
49
Argument $body is missing from the Docblock of setBody

error
49
No summary for method ""

src/Blogger/BlogBundle/BloggerBlogBundle.php2

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

src/Blogger/BlogBundle/DependencyInjection/BloggerBlogExtension.php3

Type
Line
Description

error
0
No summary was found for this file

error
20
Argument $configs is missing from the Docblock of load

error
20
Argument $container is missing from the Docblock of load

src/Blogger/BlogBundle/DependencyInjection/Configuration.php1

Type
Line
Description

error
0
No summary was found for this file

src/Blogger/BlogBundle/Form/EnquiryType.php6

Type
Line
Description

error
0
No summary was found for this file

error
9
No summary for class ""

error
11
Argument $builder is missing from the Docblock of buildForm

error
11
Argument $options is missing from the Docblock of buildForm

error
11
No summary for method ""

error
19
No summary for method ""

src/Blogger/BlogBundle/Tests/Controller/DefaultControllerTest.php3

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

error
9
No summary for method ""

src/AppBundle/Controller/DefaultController.php3

Type
Line
Description

error
0
No summary was found for this file

error
8
No summary for class ""

error
13
No summary for method ""

src/AppBundle/AppBundle.php2

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

src/AppBundle/Tests/Controller/DefaultControllerTest.php3

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

error
9
No summary for method ""

src/Acme/DemoBundle/EventListener/ControllerListener.php7

Type
Line
Description

error
0
No summary was found for this file

error
9
No summary for class ""

error
11
No summary for property $extension

error
13
Argument $extension is missing from the Docblock of __construct

error
13
No summary for method ""

error
18
Argument $event is missing from the Docblock of onKernelController

error
18
No summary for method ""

src/Acme/DemoBundle/Command/HelloWorldCommand.php3

Type
Line
Description

error
0
No summary was found for this file

error
44
Argument $input is missing from the Docblock of execute

error
44
Argument $output is missing from the Docblock of execute

src/Acme/DemoBundle/Controller/SecuredController.php10

Type
Line
Description

error
0
No summary was found for this file

error
15
No summary for class ""

error
21
Argument $request is missing from the Docblock of loginAction

error
21
No summary for method ""

error
38
No summary for method ""

error
46
No summary for method ""

error
56
Argument $name is missing from the Docblock of helloAction

error
56
No summary for method ""

error
66
Argument $name is missing from the Docblock of helloadminAction

error
66
No summary for method ""

src/Acme/DemoBundle/Controller/DemoController.php7

Type
Line
Description

error
0
No summary was found for this file

error
14
No summary for class ""

error
20
No summary for method ""

error
29
Argument $name is missing from the Docblock of helloAction

error
29
No summary for method ""

error
38
Argument $request is missing from the Docblock of contactAction

error
38
No summary for method ""

src/Acme/DemoBundle/Controller/WelcomeController.php3

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

error
9
No summary for method ""

src/Acme/DemoBundle/AcmeDemoBundle.php2

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

src/Acme/DemoBundle/Twig/Extension/DemoExtension.php13

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

error
9
No summary for property $loader

error
10
No summary for property $controller

error
12
Argument $loader is missing from the Docblock of __construct

error
12
No summary for method ""

error
17
Argument $controller is missing from the Docblock of setController

error
17
No summary for method ""

error
32
Argument $template is missing from the Docblock of getCode

error
32
No summary for method ""

error
52
No summary for method ""

error
67
Argument $template is missing from the Docblock of getTemplateCode

error
67
No summary for method ""

src/Acme/DemoBundle/DependencyInjection/AcmeDemoExtension.php6

Type
Line
Description

error
0
No summary was found for this file

error
10
No summary for class ""

error
12
Argument $configs is missing from the Docblock of load

error
12
Argument $container is missing from the Docblock of load

error
12
No summary for method ""

error
18
No summary for method ""

src/Acme/DemoBundle/Form/ContactType.php6

Type
Line
Description

error
0
No summary was found for this file

error
8
No summary for class ""

error
10
Argument $builder is missing from the Docblock of buildForm

error
10
Argument $options is missing from the Docblock of buildForm

error
10
No summary for method ""

error
16
No summary for method ""

src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php4

Type
Line
Description

error
0
No summary was found for this file

error
7
No summary for class ""

error
9
No summary for method ""

error
18
No summary for method ""

            Template is built using Twitter Bootstrap 2 and icons provided by Glyphicons.

            Documentation is powered by phpDocumentor 2.8.1 and

            generated on 2015-01-24T20:28:49+02:00.


text:
require 'minitest_helper'

describe ::VPN::Config do
  it "has a version number" do
    _(::VPN::Config::VERSION).wont_be_nil
  end

  it "has a path to the default data file" do
    _(::VPN::Config::PROVIDERS_PATH).wont_be_nil
  end
end


text:
"""This package is deprecated. Please use `airflow.utils`."""

import warnings

warnings.warn("This module is deprecated. Please use `airflow.utils`.", DeprecationWarning, stacklevel=2)