text:
package org.apache.flink.streaming.examples.statemachine;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.connector.kafka.source.reader.deserializer.KafkaRecordDeserializationSchema;
import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.examples.statemachine.dfa.State;
import org.apache.flink.streaming.examples.statemachine.event.Alert;
import org.apache.flink.streaming.examples.statemachine.event.Event;
import org.apache.flink.streaming.examples.statemachine.generator.EventsGeneratorSource;
import org.apache.flink.streaming.examples.statemachine.kafka.EventDeSerializer;
import org.apache.flink.util.Collector;

/**
 * Main class of the state machine example. This class implements the streaming application that
 * receives the stream of events and evaluates a state machine (per originating address) to validate
 * that the events follow the state machine's rules.
 */
public class StateMachineExample {

    /**
     * Main entry point for the program.
     *
     * @param args The command line arguments.
     */
    public static void main(String[] args) throws Exception {

        // ---- print some usage help ----

        System.out.println(
                "Usage with built-in data generator: StateMachineExample [--error-rate <probability-of-invalid-transition>] [--sleep <sleep-per-record-in-ms>]");
        System.out.println(
                "Usage with Kafka: StateMachineExample --kafka-topic <topic> [--brokers <brokers>]");
        System.out.println("Options for both the above setups: ");
        System.out.println("\t[--backend <hashmap|rocks>]");
        System.out.println("\t[--checkpoint-dir <filepath>]");
        System.out.println("\t[--incremental-checkpoints <true|false>]");
        System.out.println("\t[--output <filepath> OR null for stdout]");
        System.out.println();

        // ---- determine whether to use the built-in source, or read from Kafka ----

        final DataStream<Event> events;
        final ParameterTool params = ParameterTool.fromArgs(args);

        // create the environment to create streams and configure execution
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableCheckpointing(2000L);

        final String stateBackend = params.get("backend", "memory");
        if ("hashmap".equals(stateBackend)) {
            final String checkpointDir = params.get("checkpoint-dir");
            env.setStateBackend(new HashMapStateBackend());
            env.getCheckpointConfig().setCheckpointStorage(checkpointDir);
        } else if ("rocks".equals(stateBackend)) {
            final String checkpointDir = params.get("checkpoint-dir");
            boolean incrementalCheckpoints = params.getBoolean("incremental-checkpoints", false);
            env.setStateBackend(new EmbeddedRocksDBStateBackend(incrementalCheckpoints));
            env.getCheckpointConfig().setCheckpointStorage(checkpointDir);
        }

        if (params.has("kafka-topic")) {
            // set up the Kafka reader
            String kafkaTopic = params.get("kafka-topic");
            String brokers = params.get("brokers", "localhost:9092");

            System.out.printf("Reading from kafka topic %s @ %s\n", kafkaTopic, brokers);
            System.out.println();

            KafkaSource<Event> source =
                    KafkaSource.<Event>builder()
                            .setBootstrapServers(brokers)
                            .setGroupId("stateMachineExample")
                            .setTopics(kafkaTopic)
                            .setDeserializer(
                                    KafkaRecordDeserializationSchema.valueOnly(
                                            new EventDeSerializer()))
                            .setStartingOffsets(OffsetsInitializer.latest())
                            .build();
            events =
                    env.fromSource(
                            source, WatermarkStrategy.noWatermarks(), "StateMachineExampleSource");
        } else {
            double errorRate = params.getDouble("error-rate", 0.0);
            int sleep = params.getInt("sleep", 1);

            System.out.printf(
                    "Using standalone source with error rate %f and sleep delay %s millis\n",
                    errorRate, sleep);
            System.out.println();

            events = env.addSource(new EventsGeneratorSource(errorRate, sleep));
        }

        // ---- main program ----

        final String outputFile = params.get("output");

        // make parameters available in the web interface
        env.getConfig().setGlobalJobParameters(params);

        DataStream<Alert> alerts =
                events
                        // partition on the address to make sure equal addresses
                        // end up in the same state machine flatMap function
                        .keyBy(Event::sourceAddress)

                        // the function that evaluates the state machine over the sequence of events
                        .flatMap(new StateMachineMapper());

        // output the alerts to std-out
        if (outputFile == null) {
            alerts.print();
        } else {
            alerts.writeAsText(outputFile, FileSystem.WriteMode.OVERWRITE).setParallelism(1);
        }

        // trigger program execution
        env.execute("State machine job");
    }

    // ------------------------------------------------------------------------

    /**
     * The function that maintains the per-IP-address state machines and verifies that the events
     * are consistent with the current state of the state machine. If the event is not consistent
     * with the current state, the function produces an alert.
     */
    @SuppressWarnings("serial")
    static class StateMachineMapper extends RichFlatMapFunction<Event, Alert> {

        /** The state for the current key. */
        private ValueState<State> currentState;

        @Override
        public void open(Configuration conf) {
            // get access to the state object
            currentState =
                    getRuntimeContext().getState(new ValueStateDescriptor<>("state", State.class));
        }

        @Override
        public void flatMap(Event evt, Collector<Alert> out) throws Exception {
            // get the current state for the key (source address)
            // if no state exists, yet, the state must be the state machine's initial state
            State state = currentState.value();
            if (state == null) {
                state = State.Initial;
            }

            // ask the state machine what state we should go to based on the given event
            State nextState = state.transition(evt.type());

            if (nextState == State.InvalidTransition) {
                // the current event resulted in an invalid transition
                // raise an alert!
                out.collect(new Alert(evt.sourceAddress(), state, evt.type()));
            } else if (nextState.isTerminal()) {
                // we reached a terminal state, clean up the current state
                currentState.clear();
            } else {
                // remember the new state
                currentState.update(nextState);
            }
        }
    }
}


text:
package com.gentics.mesh.core.tag;

import static com.gentics.mesh.core.data.perm.InternalPermission.READ_PERM;
import static com.gentics.mesh.test.ClientHelper.call;
import static com.gentics.mesh.test.TestDataProvider.PROJECT_NAME;
import static com.gentics.mesh.test.TestSize.FULL;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
import java.util.stream.Collectors;

import org.junit.Test;

import com.gentics.mesh.context.BulkActionContext;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.data.branch.HibBranch;
import com.gentics.mesh.core.data.dao.NodeDao;
import com.gentics.mesh.core.data.dao.RoleDao;
import com.gentics.mesh.core.data.dao.TagDao;
import com.gentics.mesh.core.data.node.HibNode;
import com.gentics.mesh.core.data.tag.HibTag;
import com.gentics.mesh.core.data.tagfamily.HibTagFamily;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.core.rest.node.NodeListResponse;
import com.gentics.mesh.core.rest.node.NodeResponse;
import com.gentics.mesh.core.rest.tag.TagCreateRequest;
import com.gentics.mesh.core.rest.tag.TagListResponse;
import com.gentics.mesh.core.rest.tag.TagResponse;
import com.gentics.mesh.parameter.impl.PublishParametersImpl;
import com.gentics.mesh.parameter.impl.VersioningParametersImpl;
import com.gentics.mesh.test.MeshTestSetting;
import com.gentics.mesh.test.context.AbstractMeshTest;

@MeshTestSetting(testSize = FULL, startServer = true)
public class TagNodeEndpointTest extends AbstractMeshTest {

	@Test
	public void testReadNodesForTag() {
		try (Tx tx = tx()) {
			NodeListResponse nodeList = call(() -> client().findNodesForTag(PROJECT_NAME, tagFamily("colors").getUuid(), tag("red").getUuid(),
				new VersioningParametersImpl().draft()));
			NodeResponse concorde = new NodeResponse();
			concorde.setUuid(content("concorde").getUuid());
			assertThat(nodeList.getData()).as("Tagged nodes").isNotNull().usingElementComparatorOnFields("uuid").containsOnly(concorde);
		}
	}

	@Test
	public void testReadPublishedNodesForTag() {
		String colorsUuid = tx(() -> tagFamily("colors").getUuid());
		String redUuid = tx(() -> tag("red").getUuid());

		call(() -> client().takeNodeOffline(PROJECT_NAME, tx(() -> project().getBaseNode().getUuid()), new PublishParametersImpl().setRecursive(true)));
		NodeListResponse nodeList = call(() -> client().findNodesForTag(PROJECT_NAME, colorsUuid, redUuid,
			new VersioningParametersImpl().published()));
		assertThat(nodeList.getData()).as("Published tagged nodes").isNotNull().isEmpty();

		try (Tx tx = tx()) {
			NodeDao nodeDao = tx.nodeDao();

			// publish the node and its parent
			InternalActionContext ac = mockActionContext();
			BulkActionContext bac = createBulkContext();
			nodeDao.publish(nodeDao.getParentNode(content("concorde"), project().getLatestBranch().getUuid()), ac, bac);
			nodeDao.publish(content("concorde"), ac, bac);
		}

		nodeList = call(() -> client().findNodesForTag(PROJECT_NAME, colorsUuid, redUuid));
		NodeResponse concorde = new NodeResponse();
		concorde.setUuid(tx(() -> content("concorde").getUuid()));
		assertThat(nodeList.getData()).as("Tagged nodes").isNotNull().usingElementComparatorOnFields("uuid").containsOnly(concorde);
	}

	@Test
	public void testReadNodesForTagInBranch() {
		NodeResponse concorde = new NodeResponse();
		concorde.setUuid(db().tx(() -> content("concorde").getUuid()));

		// Create new branch
		HibBranch newBranch = tx(() -> createBranch("newbranch"));

		try (Tx tx = tx()) {
			HibBranch initialBranch = initialBranch();
			// Get for latest branch (must be empty)
			assertThat(call(() -> client().findNodesForTag(PROJECT_NAME, tagFamily("colors").getUuid(), tag("red").getUuid(),
				new VersioningParametersImpl().draft())).getData()).as("Nodes tagged in latest branch").isNotNull().isEmpty();

			// Get for new branch (must be empty)
			assertThat(call(() -> client().findNodesForTag(PROJECT_NAME, tagFamily("colors").getUuid(), tag("red").getUuid(),
				new VersioningParametersImpl().draft().setBranch(newBranch.getUuid()))).getData()).as("Nodes tagged in new branch").isNotNull()
					.isEmpty();

			// Get for initial branch
			assertThat(call(() -> client().findNodesForTag(PROJECT_NAME, tagFamily("colors").getUuid(), tag("red").getUuid(),
				new VersioningParametersImpl().draft().setBranch(initialBranch.getUuid()))).getData()).as("Nodes tagged in initial branch")
					.isNotNull().usingElementComparatorOnFields("uuid").containsOnly(concorde);
		}
	}

	@Test
	public void testTagOrder() {
		try (Tx tx = tx()) {
			TagDao tagDao = tx.tagDao();
			RoleDao roleDao = tx.roleDao();
			HibTagFamily root = tagFamily("basic");
			HibTag tag1 = tagDao.create(root, "test1", project(), user());
			HibTag tag2 = tagDao.create(root, "test2", project(), user());
			HibTag tag3 = tagDao.create(root, "test3", project(), user());

			HibNode node = content();

			tagDao.addTag(node, tag1, latestBranch());
			tagDao.addTag(node, tag3, latestBranch());
			tagDao.addTag(node, tag2, latestBranch());

			roleDao.grantPermissions(role(), tag1, READ_PERM);
			roleDao.grantPermissions(role(), tag2, READ_PERM);
			roleDao.grantPermissions(role(), tag3, READ_PERM);
			tx.success();
		}

		String tagFamilyUuid = db().tx(() -> tagFamily("basic").getUuid());
		TagResponse tagResponse = call(() -> client().createTag(PROJECT_NAME, tagFamilyUuid, new TagCreateRequest().setName("test4")));

		String nodeUuid = contentUuid();
		TagListResponse list = call(() -> client().findTagsForNode(PROJECT_NAME, nodeUuid));

		List<String> names = list.getData().stream().map(entry -> entry.getName()).collect(Collectors.toList());
		assertThat(names).containsExactlyInAnyOrder("test1", "test3", "test2");

		call(() -> client().addTagToNode(PROJECT_NAME, nodeUuid, tagResponse.getUuid()));

		list = call(() -> client().findTagsForNode(PROJECT_NAME, nodeUuid));
		names = list.getData().stream().map(entry -> entry.getName()).collect(Collectors.toList());
		assertThat(names).containsExactlyInAnyOrder("test1", "test3", "test2", "test4");

	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.runtime.executiongraph;

import org.apache.flink.api.common.JobID;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.instance.SimpleSlot;
import org.apache.flink.runtime.jobmanager.slots.AllocatedSlot;
import org.apache.flink.runtime.jobmanager.slots.SlotOwner;
import org.apache.flink.runtime.jobmanager.slots.TaskManagerGateway;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;

import org.junit.Test;

import java.net.InetAddress;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import static org.mockito.Mockito.*;

/**
 * Tests for the utility methods in the class {@link ExecutionGraphUtils}.
 */
public class ExecutionGraphUtilsTest {

	@Test
	public void testReleaseSlots() {
		final JobID jid = new JobID();
		final SlotOwner owner = mock(SlotOwner.class);

		final SimpleSlot slot1 = new SimpleSlot(createAllocatedSlot(jid, 0), owner, 0);
		final SimpleSlot slot2 = new SimpleSlot(createAllocatedSlot(jid, 1), owner, 1);
		final SimpleSlot slot3 = new SimpleSlot(createAllocatedSlot(jid, 2), owner, 2);

		final CompletableFuture<SimpleSlot> incompleteFuture = new CompletableFuture<>();

		final CompletableFuture<SimpleSlot> completeFuture = new CompletableFuture<>();
		completeFuture.complete(slot2);

		final CompletableFuture<SimpleSlot> disposedSlotFuture = new CompletableFuture<>();
		slot3.releaseSlot();
		disposedSlotFuture.complete(slot3);

		// release all futures
		ExecutionGraphUtils.releaseSlotFuture(incompleteFuture);
		ExecutionGraphUtils.releaseSlotFuture(completeFuture);
		ExecutionGraphUtils.releaseSlotFuture(disposedSlotFuture);

		// only now complete the incomplete future
		incompleteFuture.complete(slot1);

		// verify that each slot was returned once to the owner
		verify(owner, times(1)).returnAllocatedSlot(eq(slot1));
		verify(owner, times(1)).returnAllocatedSlot(eq(slot2));
		verify(owner, times(1)).returnAllocatedSlot(eq(slot3));
	}

	@Test
	public void testReleaseSlotsWithNulls() {
		final JobID jid = new JobID();
		final SlotOwner owner = mock(SlotOwner.class);

		final Execution mockExecution = mock(Execution.class);

		final SimpleSlot slot1 = new SimpleSlot(createAllocatedSlot(jid, 0), owner, 0);
		final SimpleSlot slot2 = new SimpleSlot(createAllocatedSlot(jid, 1), owner, 1);
		final SimpleSlot slot3 = new SimpleSlot(createAllocatedSlot(jid, 2), owner, 2);
		final SimpleSlot slot4 = new SimpleSlot(createAllocatedSlot(jid, 3), owner, 3);
		final SimpleSlot slot5 = new SimpleSlot(createAllocatedSlot(jid, 4), owner, 4);

		ExecutionAndSlot[] slots1 = new ExecutionAndSlot[] {
				null,
				new ExecutionAndSlot(mockExecution, CompletableFuture.completedFuture(slot1)),
				null,
				new ExecutionAndSlot(mockExecution, CompletableFuture.completedFuture(slot2)),
				null
		};

		ExecutionAndSlot[] slots2 = new ExecutionAndSlot[] {
				new ExecutionAndSlot(mockExecution, CompletableFuture.completedFuture(slot3)),
				new ExecutionAndSlot(mockExecution, CompletableFuture.completedFuture(slot4)),
				new ExecutionAndSlot(mockExecution, CompletableFuture.completedFuture(slot5))
		};

		List<ExecutionAndSlot[]> resources = Arrays.asList(null, slots1, new ExecutionAndSlot[0], null, slots2);

		ExecutionGraphUtils.releaseAllSlotsSilently(resources);

		verify(owner, times(1)).returnAllocatedSlot(eq(slot1));
		verify(owner, times(1)).returnAllocatedSlot(eq(slot2));
		verify(owner, times(1)).returnAllocatedSlot(eq(slot3));
		verify(owner, times(1)).returnAllocatedSlot(eq(slot4));
		verify(owner, times(1)).returnAllocatedSlot(eq(slot5));
	}

	// ------------------------------------------------------------------------

	private static AllocatedSlot createAllocatedSlot(JobID jid, int num) {
		TaskManagerLocation loc = new TaskManagerLocation(
				ResourceID.generate(), InetAddress.getLoopbackAddress(), 10000 + num);

		return new AllocatedSlot(new AllocationID(), jid, loc, num,
				ResourceProfile.UNKNOWN, mock(TaskManagerGateway.class));
	}
}


text:
package com.dropbox.core;

import com.dropbox.core.json.JsonReadException;
import com.dropbox.core.json.JsonReader;
import com.dropbox.core.util.IOUtil;
import com.dropbox.core.util.LangUtil;
import com.dropbox.core.util.StringUtil;
import com.dropbox.core.v1.DbxEntry;
import org.testng.annotations.Test;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import java.io.IOException;
import java.io.InputStream;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class DbxEntryTest
{
    private static <T> T loadJsonResource(JsonReader<T> reader, String resourceName)
    {
        InputStream in = DbxEntryTest.class.getResourceAsStream(resourceName);
        if (in == null) throw new AssertionError("Couldn't get resource " + StringUtil.jq(resourceName) + ".");
        try {
            return reader.readFully(in);
        }
        catch (JsonReadException ex) {
            throw LangUtil.mkAssert("Test file had invalid JSON", ex);
        }
        catch (IOException ex) {
            throw LangUtil.mkAssert("IO error reading from resource?", ex);
        }
        finally {
            IOUtil.closeInput(in);
        }
    }

    @Test
    public void parseFile() throws Exception
    {
        DbxEntry.File f = loadJsonResource(DbxEntry.Reader, "/file.json").asFile();
        assertThat(f.path).isEqualTo("/Photos/Sample Album/Boston City Flow.jpg");
        assertThat(f.numBytes).isEqualTo(339773);
        assertThat(f.mightHaveThumbnail).isEqualTo(true);
        assertThat(f.rev).isEqualTo("400113f659");
        assertThat(f.humanSize).isEqualTo("331.8 KB");

        GregorianCalendar c = new GregorianCalendar(2013, GregorianCalendar.APRIL, 11, 17, 5, 17);
        c.setTimeZone(TimeZone.getTimeZone("UTC"));
        assertThat(f.lastModified).isEqualTo(c.getTime());
    }

    @Test
    public void parseFileWithPhotoInfo() throws Exception
    {
        DbxEntry.File f = loadJsonResource(DbxEntry.Reader, "/file-with-photo-info.json").asFile();
        assertWithMessage("Expected entry to have a photo info").that(f.photoInfo).isNotNull();
        assertWithMessage("Expected entry to have a time taken").that(f.photoInfo.timeTaken).isNotNull();
        assertWithMessage("Expected entry to have a location").that(f.photoInfo.location).isNotNull();
    }

    @Test
    public void parseFileWithVideoInfo() throws Exception
    {
        DbxEntry.File f = loadJsonResource(DbxEntry.Reader, "/file-with-video-info.json").asFile();
        assertWithMessage("Expected entry to have a video info").that(f.videoInfo).isNotNull();
        assertWithMessage("Expected entry to have a time taken").that(f.videoInfo.timeTaken).isNotNull();
        assertWithMessage("Expected entry to have a location").that(f.videoInfo.location).isNotNull();
        assertWithMessage("Expected to have a duration").that(f.videoInfo.duration).isEqualTo(Long.valueOf(666));
    }

    @Test
    public void parseFileWithVideoInfoNullFields() throws Exception
    {
        DbxEntry.File f = loadJsonResource(DbxEntry.Reader, "/file-with-video-info-null-fields.json").asFile();
        assertThat(f.videoInfo.duration).isNull();
        assertThat(f.videoInfo.location).isNull();
        assertThat(f.videoInfo.timeTaken).isNull();
    }

    @Test
    public void parseWithMediaInfoPending() throws Exception
    {
        DbxEntry.File f = loadJsonResource(DbxEntry.Reader, "/file-with-media-info-pending.json").asFile();
        assertThat(f.videoInfo == DbxEntry.File.VideoInfo.PENDING).isTrue();
        assertThat(f.photoInfo == DbxEntry.File.PhotoInfo.PENDING).isTrue();
    }
}


text:
__all__ = [
    'create_engine',
]

import re

import sqlalchemy

from g1.bases.assertions import ASSERT

DB_URL_PATTERN = re.compile(r'postgresql(\+.*)?://')

def create_engine(db_url):
    ASSERT(
        DB_URL_PATTERN.match(db_url), 'expect postgresql URL, not {!r}', db_url
    )
    return sqlalchemy.create_engine(db_url)


text:
/**
 * Module dependencies.
 */

var
  express = require('express'),
  http = require('http'),
  appInit = require('./app.init.js'),
  log = require('./services/logger'),
  app = express();

appInit.configureTemplateEngine(app);
appInit.configureMiddleware(app);
appInit.configureErrorHandler(app);

require('./routes')(app);

http.createServer(app).listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});


text:
package util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.ReflectionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Utility class to determine some useful catalina environment data.
 *
 * @author André Schmer
 *
 */
public class CatalinaUtil {

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

	private static String ip;

	private static String ipSuffix;

	private static String pid;

	private static Integer port;

	private static String instanceName;

	private static String catalinaHome;

	private static String osName;

	private static String hostName;

	private CatalinaUtil() {
		throw new IllegalStateException("Utility class, use in static manner.");
	}

	public static int port() {
		if (port == null) {
			port = detectCatalinaHttpPort();
		}
		return port;
	}

	public static String instanceName() {
		if (instanceName == null) {
			instanceName = detectInstance();
		}
		return instanceName;
	}

	public static String hostName() {
		if (hostName == null) {
			hostName = detectHostName();
		}
		return hostName;
	}

	public static String catalinaHome() {
		if (catalinaHome == null) {
			catalinaHome = System.getProperty("catalina.home", System.getProperty("user.dir"));
		}
		return catalinaHome;
	}

	public static String osName() {
		if (osName == null) {
			osName = detectOsName();
		}
		return osName;
	}

	private static String detectOsName() {
		return System.getProperty("os.name").toLowerCase();
	}

	public static String ip() {
		if (ip == null) {
			ip = detectIPAddress();
		}
		return ip;
	}

	public static String ipSuffix() {
		if (ipSuffix == null) {
			ipSuffix = detectIPAddressSuffix();
		}
		return ipSuffix;
	}

	public static String pid() {
		if (pid == null) {
			pid = detectPID();
		}
		return pid;
	}

	private static String detectIPAddress() {
		String ipAddress = null;
		try {
			if (InetAddress.getLocalHost().isAnyLocalAddress() || InetAddress.getLocalHost().isLoopbackAddress() || InetAddress.getLocalHost().isSiteLocalAddress()) {
				ipAddress = InetAddress.getLoopbackAddress().getHostAddress();
			} else {
				ipAddress = InetAddress.getLocalHost().getHostAddress();
			}
		} catch (final UnknownHostException e) {
			log.error("{}", e.getMessage());
		}
		return ipAddress;
	}

	private static String detectIPAddressSuffix() {
		final String ip = ip();
		if (ip != null) {
			return ip.substring(ip.lastIndexOf('.') + 1, ip.length());
		}
		return null;
	}

	private static String detectInstance() {
		final String catalinaHome = catalinaHome();
		String instanceName = null;
		if (catalinaHome.contains("workspace") || catalinaHome.contains("git")) {
			instanceName = "localhost";
		} else {
			instanceName = catalinaHome.substring(catalinaHome.lastIndexOf('/') + 1, catalinaHome.length());
		}
		return instanceName;
	}

	private static String detectPID() {
		if ("linux".equals(detectOsName())) {
			final byte[] bo = new byte[180];
			final String[] cmd = { "bash", "-c", "echo $PPID" };
			try {
				final Process p = Runtime.getRuntime().exec(cmd);
				final InputStream is = p.getInputStream();
				is.read(bo);
				final String pid = new String(bo);
				final StringBuilder sb = new StringBuilder();
				for (int i = 0; i < pid.length(); i++) {
					if ((pid.charAt(i) != (byte) 0x00) && pid.charAt(i) != (byte) 0x0A) {
						sb.append(pid.charAt(i));
						continue;
					}
					break;
				}
				is.close();
				return sb.toString().trim();
			} catch (final IOException e) {
				log.error("{}", e.getMessage());
			}
		}
		return "1";
	}

	private static int detectCatalinaHttpPort() {
		int localPort = -1;
		final MBeanServer pms = ManagementFactory.getPlatformMBeanServer();
		ObjectName protocolHandlerObjectNamePattern;
		try {
			protocolHandlerObjectNamePattern = new ObjectName("Catalina:type=ProtocolHandler,port=*");
			for (final ObjectInstance oi : pms.queryMBeans(protocolHandlerObjectNamePattern, null)) {
				try {
					if ("org.apache.coyote.http11.Http11Protocol".equals(pms.getAttribute(oi.getObjectName(), "modelerType"))) {
						localPort = (Integer) pms.getAttribute(oi.getObjectName(), "localPort");
					}
				} catch (final AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException e) {
					log.error("{}", e.getMessage());
				}
			}
		} catch (final MalformedObjectNameException e) {
			log.error("{}", e.getMessage());
		}

		return localPort;
	}

	public static boolean isPrivateAddress() {
		return InetAddress.getLoopbackAddress().getHostAddress().equals(ip);
	}

	public static boolean isOsName(final String fragment) {
		return (detectOsName() != null && detectOsName().contains(fragment));
	}

	private static String detectHostName() {
		try {
			return InetAddress.getLocalHost().getHostName();
		} catch (final UnknownHostException e) {
			log.error("{}", e.getMessage());
		}
		return null;
	}
}


text:
<?php

declare(strict_types=1);

namespace Todora\Todos\Domain\Service\AddUser;

interface PasswordHasherInterface
{
    public function hash(string $password): string;
}


text:
require 'spec_helper'
require 'active_support/core_ext/date'

module WithEthics
  describe Repo do
    describe "init" do
      before do
        @reporter = Reporter.instance
        @reporter.config
      end

      it "should instantiate" do
        expect{ Repo.new reporter: @reporter}.not_to raise_error
      end

      it "should accept 'git' as a type to find" do
        r = Repo.new type: 'git', reporter: @reporter
        expect(r.type).to eq('git')
      end

      # does it make sense that if a reporter is not provided, just don't report? Not really!
      it "should accept a reporter" do
        r = Repo.new reporter: @reporter
        expect(r.reporter).to be_kind_of Reporter
      end

      it "should accept root" do
        root = '/some/path'
        r = Repo.new root: root, reporter: @reporter
        expect(r.root).to eq(root)
      end
    end
  end

  describe "git" do
    before do
      @reporter = Reporter.instance
      @reporter.config
      @repo = Repo.new type: 'git', reporter: @reporter
    end

    it "should find git repo" do
       expect {
         expect(@repo.find).to eq(true)
      }.to output("\e[0;32;49m\tFound git repository\e[0m\n").to_stdout
      # suppress damned output!
    end

    it "should report finding git repo" do
      expect { @repo.find }.to output("\e[0;32;49m\tFound git repository\e[0m\n").to_stdout
    end

    it "should report simple git repo status" do
      gstat = double(Git::Status, changed: {}, added: {})
      git = double(Git::Base, status_hint: 'good', results: { summary: "Repository is in good condition." }, log: {}, status: gstat)
      allow(Git).to receive(:open).and_return(git)
      expect { @repo.status }.to output("\e[0;32;49m\tRepository is in good condition.\e[0m\n").to_stdout
    end
  end

  describe "subversion" do
    before do
      @reporter = Reporter.instance
      @reporter.config output_to: []
      @repo = Repo.new type: 'svn', reporter: @reporter
    end

    it "should not find locally" do
      expect(@repo.find).to eq(false)
    end

    it "should find when present" do
      # I know it's sort of a tautology but
      # how'm I going to test a subversion repository
      # from a git based project?
      path = "#{ Dir.pwd }/.svn"
      allow(File).to receive(:exists?).with(path).and_return(true)
      allow(File).to receive(:directory?).with(path).and_return(true)
      expect(@repo.find).to eq(true)
    end

    # SVN keeps a .svn directory in every directory throughout the repo
    # so just seeing it at the top level isn't good enough. You have to check
    # all the way down.
    it "confirms svn repo recursively"
  end

  describe "mercurial" do
    before do
      @reporter = Reporter.instance
      @reporter.config output_to: []
      @repo = Repo.new type: 'hg', reporter: @reporter
    end

    it "should find when present" do
      # I know it's sort of a tautology but
      # how'm I going to test a subversion repository
      # from a git based project?
      path = "#{ Dir.pwd }/.hg"
      allow(File).to receive(:exists?).with(path).and_return(true)
      allow(File).to receive(:directory?).with(path).and_return(true)
      expect(@repo.find).to eq(true)
    end
  end

  describe "unknown version control" do

    it "should find known type without spec" do
      %w(hg svn git).each do |t|
        path = "#{ Dir.pwd }/.#{ t }"
        val = (t == 'svn')
        allow(File).to receive(:exists?).with(path).and_return(val)
        allow(File).to receive(:directory?).with(path).and_return(val)

      end
      @reporter = Reporter.instance
      @reporter.config
      @repo = Repo.new type: nil, reporter: @reporter
      expect { @repo.find }.to output("\e[0;32;49m\tFound svn repository\e[0m\n").to_stdout
    end
  end

end


text:
function PCallError( ... )

	local arg = {...}

	local errored, retval = pcall( unpack( arg ) )

	if ( !errored ) then
		ErrorNoHalt( retval )
		return false, retval
	end

	return true, retval

end

ASS_LVL_SERVER_OWNER	= 0
ASS_LVL_SUPER_ADMIN		= 1
ASS_LVL_ADMIN			= 2
ASS_LVL_MOD				= 3
ASS_LVL_TEMPADMIN		= 10
ASS_LVL_PREMIUM			= 96
ASS_LVL_DIAMOND			= 97
ASS_LVL_GOLD			= 98
ASS_LVL_SILVER			= 99
ASS_LVL_BRONZE			= 100
ASS_LVL_GUEST			= 200
ASS_LVL_BANNED			= 255

ASS_VERSION = "Underscore Gaming"

LevelIcon		= {}
-- LevelIcon[0] = "icon16/lightning.png"
LevelIcon[0]	= "icon16/user_suit.png"
-- LevelIcon[1] = "icon16/star.png"
LevelIcon[1] 	= "icon16/user_gray.png"
LevelIcon[2]	= "icon16/shield.png"
LevelIcon[3]	= "icon16/asterisk_yellow.png"
LevelIcon[4]	= "icon16/award_star_gold_3.png"
LevelIcon[5]	= "icon16/user.png"
LevelIcon[255]	= "icon16/user_delete.png"

function ASS_Init_Shared()

	local PLAYER = FindMetaTable("Player")
	function PLAYER:IsOwner()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_SERVER_OWNER	end
	function PLAYER:IsSuperAdmin()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_SUPER_ADMIN	end
	function PLAYER:IsAdmin()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_ADMIN		end
	function PLAYER:IsTempAdmin()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_TEMPADMIN	end
	function PLAYER:IsPremium()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_PREMIUM	end
	function PLAYER:IsDiamond()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_DIAMOND	end
	function PLAYER:IsGold()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_GOLD	end
	function PLAYER:IsSilver()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_SILVER	end
	function PLAYER:IsBronze()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= ASS_LVL_BRONZE	end

	function PLAYER:IsGuest()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) >= ASS_LVL_GUEST && self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) < ASS_LVL_BANNED end
	function PLAYER:IsUnwanted()	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) >= ASS_LVL_BANNED end

	function PLAYER:GetLevel()		return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST)						end
	function PLAYER:HasLevel(n)		return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= n						end
	function PLAYER:IsBetterOrSame(PL2)	return self:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST) <= PL2:GetNetworkedInt("ASS_isAdmin", ASS_LVL_GUEST)	end
	function PLAYER:GetTAExpiry(n)		return self:GetNetworkedFloat("ASS_tempAdminExpiry")	end
	function PLAYER:AssId()	return self:SteamID()	end

-- --delete me
-- 	function PLAYER:Notify ( Text, truefalse )
-- 	if !self or !self:IsValid() then return false; end

-- 		if SERVER then

-- 		else
-- 			AddNotify(Text, NOTIFY_UNDO, 15, truefalse);
-- 		end
-- 	end

	PLAYER = nil

end

-- function AddNotify( str, type, length, hideSound )

-- 	Msg(str .. '\n');

-- end

function IncludeSharedFile( S )

	if (SERVER) then
		AddCSLuaFile(S)
	end

	include(S)

end

function LevelToString( LEVEL, TIME )

	if (LEVEL <= ASS_LVL_SERVER_OWNER) then								return "Owner";
	elseif (LEVEL <= ASS_LVL_SUPER_ADMIN) then							return "Super Admin";
	elseif (LEVEL <= ASS_LVL_ADMIN) then								return "Admin";
	elseif (LEVEL <= ASS_LVL_TEMPADMIN) then							if (TIME) then return "Admin for " .. TIME else return "Temp Admin" end
	elseif (LEVEL <= ASS_LVL_PREMIUM) then								return "Premium VIP";
	elseif (LEVEL <= ASS_LVL_DIAMOND) then								return "Diamond VIP";
	elseif (LEVEL <= ASS_LVL_GOLD) then									return "Gold VIP";
	elseif (LEVEL <= ALL_LVL_SILVER) then								return "Silver VIP";
	elseif (LEVEL <= ASS_LVL_BRONZE)then								return "Bronze VIP";
	elseif (LEVEL >= ASS_LVL_GUEST && LEVEL < ASS_LVL_BANNED) then		return "Guest"
	else
		//mofo must be banned
		return "Banned";
	end
end

function ASS_FormatText( TEXT )

	if (CLIENT) then
		TEXT = string.Replace(TEXT, "%assmod%", ASS_VERSION )

		TEXT = string.Replace(TEXT, "%cl_time%", os.date("%H:%M:%S") )
		TEXT = string.Replace(TEXT, "%cl_date%",  os.date("%d/%b/%Y") )
		TEXT = string.Replace(TEXT, "%cl_timedate%", os.date("%H:%M:%S") .. " " ..  os.date("%d/%b/%Y") )

		TEXT = string.Replace(TEXT, "%sv_time%", GetGlobalString("ServerTime") )
		TEXT = string.Replace(TEXT, "%sv_date%", GetGlobalString("ServerDate") )
		TEXT = string.Replace(TEXT, "%sv_timedate%", GetGlobalString("ServerTime") .. " " .. GetGlobalString("ServerDate") )

		TEXT = string.Replace(TEXT, "%hostname%", GetGlobalString( "ServerName" ) )
		TEXT = string.gsub(TEXT, "%%%&([%w_]+)%%", GetConVarString)
	end
	if (SERVER) then

		TEXT = string.Replace(TEXT, "%map%", game.GetMap() )
		TEXT = string.Replace(TEXT, "%gamemode%", gmod.GetGamemode().Name )

		TEXT = string.gsub(TEXT, "%%@([%w_]+)%%", GetConVarString)

	end

	TEXT = ASS_RunPluginFunction("FormatText", TEXT, TEXT)

	return TEXT

end

IncludeSharedFile("ass_plugins.lua")
IncludeSharedFile("ass_debug.lua")
IncludeSharedFile("ass_config.lua")


text:
package main.java.meterstanden.domain;

import java.io.IOException;
import java.util.List;

import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import com.google.gson.Gson;

import main.java.meterstanden.hibernate.HibernateUtil;

/**
 * Servlet implementation class JaaroverzichtDomain
 */
@WebServlet(
		description = "Get the yearly overview",
		urlPatterns = {
				"/Jaaroverzicht",
				"/JAAROVERZICHT",
				"/jaaroverzicht"
		}
	)

public class JaaroverzichtDomain extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(JaaroverzichtDomain.class);

    /**
     * @see HttpServlet#HttpServlet()
     */
    public JaaroverzichtDomain() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		log.debug("Getting the jaarverbruik.");
		Session session = HibernateUtil.getSessionFactory().openSession();
		StringBuilder hql = new StringBuilder();
		hql.append("from Jaarverbruik");
		Query q = session.createQuery(hql.toString());
		List<?> rl = q.getResultList();

		Gson gson = new Gson();
		response.getWriter().append(gson.toJson(rl));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}


text:
package org.apache.phoenix.pherf.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.apache.commons.lang3.StringUtils;
import org.apache.phoenix.pherf.exception.PherfException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;

/**
 * list resources available from the classpath @ *
 */
public class ResourceList {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResourceList.class);
    private final String rootResourceDir;
    // Lists the directories to ignore meant for testing something else
    // when getting the resources from classpath
    private List<String> dirsToIgnore = Lists.newArrayList("sql_files");

    public ResourceList(String rootResourceDir) {
        this.rootResourceDir = rootResourceDir;
    }

    public Collection<Path> getResourceList(final String pattern) throws Exception {
        // Include files from config directory
        Collection<Path> paths = getResourcesPaths(Pattern.compile(pattern));

        return paths;
    }

    /**
     * for all elements of java.class.path get a Collection of resources Pattern
     * pattern = Pattern.compile(".*"); gets all resources
     *
     * @param pattern the pattern to match
     * @return the resources in the order they are found
     */
    private Collection<Path> getResourcesPaths(
            final Pattern pattern) throws Exception {

        final String classPath = System.getProperty("java.class.path", ".");
        final String[] classPathElements = classPath.split(":");
        Set<String> strResources = new HashSet<>();
        Collection<Path> paths = new ArrayList<>();

        // TODO Make getResourcesPaths() return the URLs directly instead of converting them
        // Get resources as strings.
        for (final String element : classPathElements) {
            strResources.addAll(getResources(element, pattern));
        }

        // Convert resources to URL
        for (String resource : strResources) {
            URL url = null;
            URI uri = null;
            Path path = null;

            String rName = rootResourceDir + resource;

            LOGGER.debug("Trying with the root append.");
            url = ResourceList.class.getResource(rName);
            if (url == null) {
                LOGGER.debug("Failed! Must be using a jar. Trying without the root append.");
                url = ResourceList.class.getResource(resource);

                if (url == null) {
                    throw new PherfException("Could not load resources: " + rName);
                }
                final String[] splits = url.toString().split("!");
                uri = URI.create(splits[0]);
                path = (splits.length < 2) ? Paths.get(uri) : Paths.get(splits[1]);
            } else {
                path = Paths.get(url.toURI());
            }
            LOGGER.debug("Found the correct resource: " + path.toString());
            paths.add(path);
        }

        Collections.sort((List<Path>)paths);
        return paths;
    }

    private Collection<String> getResources(
            final String element,
            final Pattern pattern) {
        final List<String> retVal = new ArrayList<>();
        if (StringUtils.isBlank(element)) {
            return retVal;
        }
        final File file = new File(element);
        if (file.isDirectory()) {
            retVal.addAll(getResourcesFromDirectory(file, pattern));
        } else {
            retVal.addAll(getResourcesFromJarFile(file, pattern));
        }
        return retVal;
    }

    // Visible for testing
    Collection<String> getResourcesFromJarFile(
            final File file,
            final Pattern pattern) {
        final List<String> retVal = new ArrayList<>();
        ZipFile zf;
        try {
            zf = new ZipFile(file);
        } catch (FileNotFoundException|NoSuchFileException e) {
            // Gracefully handle a jar listed on the classpath that doesn't actually exist.
            return Collections.emptyList();
        } catch (final ZipException e) {
            throw new Error(e);
        } catch (final IOException e) {
            throw new Error(e);
        }
        final Enumeration e = zf.entries();
        while (e.hasMoreElements()) {
            final ZipEntry ze = (ZipEntry) e.nextElement();
            final String fileName = ze.getName();
            final boolean accept = pattern.matcher(fileName).matches();
            LOGGER.trace("fileName:" + fileName);
            LOGGER.trace("File:" + file.toString());
            LOGGER.trace("Match:" + accept);
            if (accept) {
                LOGGER.trace("Adding File from Jar: " + fileName);
                retVal.add("/" + fileName);
            }
        }
        try {
            zf.close();
        } catch (final IOException e1) {
            throw new Error(e1);
        }
        return retVal;
    }

    private Collection<String> getResourcesFromDirectory(
            final File directory,
            final Pattern pattern) {
        final ArrayList<String> retval = new ArrayList<String>();
        final File[] fileList = directory.listFiles();
        for (final File file : fileList) {
            if (isIgnoredDir(file.getAbsolutePath())) continue;
            if (file.isDirectory()) {
                retval.addAll(getResourcesFromDirectory(file, pattern));
            } else {
                final String fileName = file.getName();
                final boolean accept = pattern.matcher(file.toString()).matches();
                if (accept) {
                    LOGGER.debug("Adding File from directory: " + fileName);
                    retval.add("/" + fileName);
                }
            }
        }
        return retval;
    }

    private boolean isIgnoredDir(String path) {
        for (String dir : dirsToIgnore) {
            if (path.contains(dir)) return true;
        }
        return false;
    }
}


text:
package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"go/build"
	"io"
	"log"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"time"

	"compress/gzip"
	"io/ioutil"

	"github.com/qrtz/livedev/env"
	"github.com/qrtz/livedev/logger"
	"github.com/qrtz/livedev/watcher"
)

var (
	errTimeout            = errors.New("Timeout:Gaving up")
	errInvalidFilePattern = errors.New("Invalid file pattern")
)

type processState uint32

const (
	created processState = iota
	running
	stopping
	exited
)

type resource struct {
	Ignore *regexp.Regexp
	Paths  map[string]struct{}
}

func newResource(paths []string, ignore string) (*resource, error) {

	rs := &resource{Paths: make(map[string]struct{})}

	if len(paths) > 0 {
		for _, s := range paths {
			if p := strings.TrimSpace(s); len(p) > 0 {
				rs.Paths[filepath.Clean(p)] = struct{}{}
			}
		}

		if s := strings.TrimSpace(ignore); len(s) > 0 {
			pattern, err := regexp.Compile(s)
			if err != nil {
				return nil, err
			}
			rs.Ignore = pattern
		}
	}

	return rs, nil
}

// Watch adds Resource files and directories to the given watcher
func (r resource) Walk(walkFunc func(string) error) {
	for f := range r.Paths {
		if info, err := os.Lstat(f); err == nil {
			if info.IsDir() {
				filepath.Walk(f, func(path string, info os.FileInfo, err error) error {
					if err == nil && info.IsDir() {
						if r.Ignore != nil && r.Ignore.MatchString(path) {
							return filepath.SkipDir
						}
						return walkFunc(path)

					}
					return nil
				})
			} else {
				walkFunc(f)
			}
		}
	}
}

// MathcPath tests whehere the given string matches any of the resource files
func (r resource) MatchPath(p string) bool {
	for f := range r.Paths {
		if strings.HasPrefix(p, f) {
			return r.Ignore == nil || !r.Ignore.MatchString(p)
		}
	}
	return false
}

type updateListeners struct {
	mu        sync.Mutex
	listeners map[chan struct{}]struct{}
}

func newUpdateListeners() *updateListeners {
	return &updateListeners{
		listeners: make(map[chan struct{}]struct{}),
	}
}

func (u *updateListeners) register() <-chan struct{} {
	u.mu.Lock()
	defer u.mu.Unlock()

	ch := make(chan struct{})
	u.listeners[ch] = struct{}{}
	return ch
}

func (u *updateListeners) remove(ch chan struct{}) {
	u.mu.Lock()
	defer u.mu.Unlock()

	delete(u.listeners, ch)
	close(ch)
}

func (u *updateListeners) notify() {
	u.mu.Lock()
	defer u.mu.Unlock()
	for ch := range u.listeners {
		select {
		case ch <- struct{}{}:
		default:
			go u.remove(ch)
		}
	}
}

// Server represents an http server
type Server struct {
	addr           string
	bin            string
	builder        []string
	closed         chan struct{}
	context        build.Context
	dep            map[string]struct{}
	host           string
	port           int
	resources      *resource
	assets         *resource
	startup        []string
	target         string
	targetDir      string
	stdout         *logger.LogWriter
	stderr         *logger.BufferedLogWriter
	startupTimeout time.Duration
	watcher        *watcher.Watcher
	watcherEvents  chan watcher.Event
	pending        sync.WaitGroup

	updateListeners *updateListeners

	busy    chan bool
	ready   chan error
	stopped chan bool
	started chan bool
	exit    chan bool
	done    chan error

	mu    sync.Mutex
	error error

	once sync.Once

	cmd          *exec.Cmd
	processState uint32
	conf         serverConfig
	proxyPort    int
}

func (srv *Server) setProcessState(state processState) {
	atomic.StoreUint32(&srv.processState, uint32(state))
}

func (srv *Server) getProcessState() processState {
	return processState(atomic.LoadUint32(&srv.processState))
}

func (srv *Server) setError(err error) {
	srv.mu.Lock()
	srv.error = err
	srv.mu.Unlock()
}

func (srv *Server) getError() error {
	srv.mu.Lock()
	defer srv.mu.Unlock()
	return srv.error
}

func (srv *Server) watch(path string) error {
	return srv.watcher.Add(path, srv.watcherEvents)
}

func (srv *Server) unwatch(path string) error {
	return srv.watcher.Remove(path, srv.watcherEvents)
}

func (srv *Server) unwatchAll() error {
	srv.resources.Walk(srv.unwatch)
	srv.assets.Walk(srv.unwatch)
	for p := range srv.dep {
		srv.unwatch(p)
	}
	return nil
}

func (srv *Server) startWatcher() {
	var mu sync.Mutex
	var timer *time.Timer
	for {
		select {
		case event := <-srv.watcherEvents:
			mu.Lock()
			if timer != nil {
				timer.Stop()
				timer = nil
			}

			timer = time.AfterFunc(1*time.Second, func() {
				srv.sync(event.Name)
			})
			mu.Unlock()
		}
	}
}

func (srv *Server) runOnce() {
	srv.once.Do(func() {
		srv.busy <- true
		defer func() {
			srv.started <- true
			go srv.loop()
			<-srv.busy
		}()

		go srv.startWatcher()
		err := srv.build()
		srv.setError(err)

		if err == nil {
			err = srv.start()
			if err != nil {
				srv.setError(fmt.Errorf("%v\nError:%s\n", err, srv.stderr.ReadAll()))
			}
		}
		srv.resources.Walk(srv.watch)
		srv.assets.Walk(srv.watch)
	})
}

func newServer(context build.Context, conf serverConfig, proxyPort int, w *watcher.Watcher) (*Server, error) {
	var err error
	srv := new(Server)
	srv.conf = conf
	srv.proxyPort = proxyPort

	srv.resources, err = newResource(conf.Resources.Paths, conf.Resources.Ignore)

	if err != nil {
		return nil, err
	}

	srv.assets, err = newResource(conf.Assets.Paths, conf.Assets.Ignore)

	if err != nil {
		return nil, err
	}

	srv.startupTimeout = conf.StartupTimeout

	srv.target = strings.TrimSpace(conf.Target)
	srv.targetDir = filepath.Dir(conf.Target)
	srv.bin = strings.TrimSpace(conf.Bin)
	srv.builder = conf.Builder

	if !hasPrefix(srv.target, filepath.SplitList(context.GOPATH)) {
		// Target is not in the $GOPATH
		// Try to guess the import root(workspace) from the path
		roots := importRoots(srv.target)

		if len(roots) > 0 {
			context.GOPATH = strings.Join(append(roots, context.GOPATH), string(filepath.ListSeparator))
		}
	}

	srv.context = context

	if len(srv.builder) == 0 {
		gobin := "go"

		if len(context.GOROOT) > 0 && fileExists(context.GOROOT) {
			gobin = filepath.Join(context.GOROOT, "bin", gobin)
		}

		srv.builder = append(srv.builder, gobin, "build", "-o", srv.bin)
	}

	srv.watcher = w
	srv.watcherEvents = make(chan watcher.Event, 1)
	srv.ready = make(chan error, 1)
	srv.busy = make(chan bool, 1)
	srv.stopped = make(chan bool, 1)
	srv.started = make(chan bool, 1)
	srv.done = make(chan error, 1)
	srv.exit = make(chan bool, 1)
	srv.updateListeners = newUpdateListeners()
	srv.port = conf.Port
	srv.startup = conf.Startup
	srv.host = conf.Host
	srv.stdout = logger.NewLogWriter(os.Stdout, srv.host+"> ", log.LstdFlags)
	srv.stderr = new(logger.BufferedLogWriter)
	return srv, nil
}

func (srv *Server) testConnection(target *url.URL, timeout time.Duration) <-chan error {
	t := time.After(timeout)
	done := make(chan error, 1)
	client := &http.Client{}
	go func() {
		for {
			select {
			case err := <-srv.done:
				done <- err
				srv.done <- err
			case <-t:
				done <- errTimeout
				return
			default:
				response, err := client.Head(target.String())
				if err == nil {
					response.Body.Close()
					done <- nil
					return
				}

				if t, ok := err.(*url.Error); ok && t.Err == io.EOF {
					// The server started successfully but the handler paniced
					done <- nil
					return
				}

				if srv.getProcessState() != running {
					done <- nil
					return
				}

				time.Sleep(100 * time.Millisecond)
			}
		}
	}()

	return done
}

func (srv *Server) stopAndNotify() error {
	srv.busy <- true
	defer func() {
		srv.updateListeners.notify()
		srv.started <- <-srv.busy
	}()

	err := srv.stop()
	srv.setError(err)
	return err
}

func (srv *Server) stop() error {
	log.Printf("Stopping...%s:%v", srv.host, srv.port)
	select {
	case srv.stopped <- true:
		<-time.After(10 * time.Millisecond)
		srv.pending.Wait()
		return srv.stopProcess()
	default:
	}
	return nil
}

func (srv *Server) shutdown() error {
	srv.busy <- true
	log.Println("shuting down: ", srv.host)
	defer func() {
		<-srv.busy
	}()

	select {
	case srv.exit <- true:
		srv.unwatchAll()
		return srv.stop()
	default:
		return nil
	}
}

func (srv *Server) sync(filename string) error {
	srv.busy <- true
	notifyUpdate := true

	defer func() {
		if notifyUpdate {
			go srv.updateListeners.notify()
		}
		srv.started <- <-srv.busy
	}()

	_, rebuild := srv.dep[filename]

	restart := rebuild || srv.resources.MatchPath(filename)

	if !restart && !srv.assets.MatchPath(filename) {
		return nil
	}

	if restart {
		err := srv.stop()
		srv.setError(err)
		if err != nil {
			return err
		}
	}

	if rebuild {
		err := srv.build()
		srv.setError(err)

		if err != nil {
			return err
		}
	}

	if restart {
		// Let start handle the notification
		notifyUpdate = false
		err := srv.start()
		if err != nil {
			err = fmt.Errorf("%v\nError:%s\n", err, srv.stderr.ReadAll())
		}
		srv.setError(err)
	}

	return nil
}

func (srv *Server) start() error {
	log.Printf("Starting...%s", srv.host)
	defer srv.updateListeners.notify()

	if len(srv.addr) == 0 {
		srv.addr = net.JoinHostPort(srv.host, strconv.Itoa(srv.port))
	}

	log.Println(srv.addr)

	if _, err := net.ResolveTCPAddr("tcp", srv.addr); err != nil {
		return err
	}

	srv.stderr.Reset()

	err := srv.startProcess()
	if err == nil {
		select {
		case err = <-srv.done:
		default:
		}
	}

	log.Println(srv.host, "...Startup completed")
	return err
}

func (srv *Server) loop() {
	<-srv.started
	err := srv.getError()
	for {
		select {
		case s := <-srv.stopped:
			srv.stopped <- s
			select {
			case <-srv.ready:
			default:
			}
			<-srv.started
			<-srv.stopped
			err = srv.getError()
		case <-srv.exit:
			select {
			case <-srv.ready:
			default:
			}
			return
		case srv.ready <- err:
		}
	}
}

func (srv *Server) stopProcess() (err error) {
	log.Println("Stopping process", srv.host)
	select {
	case err = <-srv.done:
		log.Println("Process already stopped")
	default:
		if srv.getProcessState() == running {
			srv.setProcessState(stopping)
			srv.cmd.Process.Signal(syscall.SIGTERM)
			select {
			case err = <-srv.done:
			case <-time.After(srv.startupTimeout):
				srv.cmd.Process.Signal(syscall.SIGKILL)
				// TODO : We may need to set a timeout here
				err = <-srv.done
			}
		}
	}
	return err
}

func (srv *Server) restart() error {
	srv.busy <- true
	defer func() {
		srv.started <- <-srv.busy
	}()

	err := srv.stop()
	srv.setError(err)
	if err != nil {
		return err
	}

	err = srv.start()
	if err != nil {
		err = fmt.Errorf("%v\nError:%s\n", err, srv.stderr.ReadAll())
	}
	srv.setError(err)
	return err
}

func (srv *Server) startProcess() error {
	log.Println("Starting Process: ", srv.addr)
	srv.setProcessState(created)
	ev := env.New(os.Environ())
	for key, value := range srv.conf.Env {
		ev.Set(key, value)
	}

	cmd := exec.Command(srv.bin, srv.startup...)
	cmd.Env = ev.Data()
	cmd.Stderr = srv.stderr
	cmd.Stdout = srv.stdout

	err := cmd.Start()
	if err == nil {
		srv.setProcessState(running)
		srv.cmd = cmd

		go func() {
			status := cmd.Wait()

			log.Println(srv.host, "->", status)
			srv.done <- nil
			oldState := srv.getProcessState()
			srv.setProcessState(exited)

			select {
			case srv.busy <- true:
				if oldState == running {
					// The process crashed or was killed externally
					// Restart it
					// TODO: limit the number of consecutive restart
					if srv.stderr.Len() == 0 || strings.Contains(status.Error(), "terminated") {
						go srv.restart()
					} else {
						go srv.stopAndNotify()
					}
				}
				<-srv.busy
			default:
			}
		}()

		err = <-srv.testConnection(&url.URL{
			Host:   srv.addr,
			Scheme: "http",
			Path:   "/",
		}, srv.startupTimeout*time.Second)
	}
	return err

}

func (srv *Server) build() error {
	log.Printf("Building...%s", srv.host)

	// List of file to pass to "go build"
	var buildFiles []string

	dep, err := computeDep(&srv.context, srv.target)
	if err != nil {
		return err
	}

	for f := range srv.dep {
		srv.unwatch(f)
	}

	// Reset the dependency list.
	srv.dep = make(map[string]struct{})
	for _, f := range dep {
		srv.dep[f] = struct{}{}
		if err := srv.watch(f); err != nil {
			return err
		}

		if filepath.Dir(f) == srv.targetDir {
			buildFiles = append(buildFiles, filepath.Base(f))
		}
	}

	env := env.New(os.Environ())
	env.Set("GOPATH", srv.context.GOPATH)

	command, args := srv.builder[0], srv.builder[1:]

	args = append(args, buildFiles...)

	cmd := exec.Command(command, args...)
	cmd.Env = env.Data()
	cmd.Dir = srv.conf.WorkingDir

	if out, err := cmd.CombinedOutput(); err != nil {
		if len(out) > 0 {
			r := bufio.NewReader(bytes.NewReader(out))
			var lines []string
		done:
			for {
				line, err := r.ReadString('\n')
				switch {
				case err != nil:
					break done
				case !strings.HasPrefix(line, "#"):
					lines = append(lines, line)
				}
			}
			return errors.New(strings.Join(lines, ""))
		}

		return err
	}

	return nil
}

func (srv *Server) onUpdate() <-chan struct{} {
	return srv.updateListeners.register()
}

func (srv *Server) handleLivedevSocket(w http.ResponseWriter, r *http.Request) error {
	client, buf, err := w.(http.Hijacker).Hijack()

	if err == nil {
		// For now, no need for a full websocket protocol implementation
		// We need just enough to maintain the connection
		// Communicate changes to the caller by just closing the conntection
		go func() {
			code := http.StatusSwitchingProtocols
			fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
			buf.WriteString("Upgrade: websocket\r\n")
			buf.WriteString("Connection: Upgrade\r\n")
			fmt.Fprintf(buf, "Sec-WebSocket-Accept: %s\r\n", generateWebsocketAcceptKey(r.Header.Get("Sec-Websocket-Key")))
			fmt.Fprintf(buf, "Sec-WebSocket-Protocol: %s\r\n", liveReloadProtocol)
			buf.WriteString("\r\n")
			buf.Flush()
			done := make(chan bool, 1)
			update := srv.onUpdate()

			go func() {
				// We do not expect any message from the client
				// Any data indicates a connection closed or a misbehaving client
				client.Read(make([]byte, 8))
				done <- true
			}()

			select {
			case <-update:
			case <-done:
			}
			client.Close()
		}()
	}
	return err
}

func (srv *Server) serveWebSocket(w http.ResponseWriter, r *http.Request) error {
	client, buf, err := w.(http.Hijacker).Hijack()

	if err != nil {
		return err
	}

	// We have taken over the connection from this point on. Do not return any error to the caller
	requestURL := *r.URL
	requestURL.Host = srv.addr

	conn, err := net.Dial(client.LocalAddr().Network(), requestURL.Host)

	if err != nil {
		writeWebSocketError(buf, err, http.StatusInternalServerError)
		client.Close()
		return nil
	}

	if err = r.Write(conn); err != nil {
		writeWebSocketError(buf, err, http.StatusInternalServerError)
		conn.Close()
		client.Close()
		return nil
	}

	go func() {
		done := make(chan bool, 1)
		copy := func(dst io.Writer, src io.Reader) {
			io.Copy(dst, src)
			done <- true
		}

		go copy(bufio.NewWriter(conn), buf)
		go copy(buf, bufio.NewReader(conn))

		<-done
		conn.Close()
		client.Close()
	}()

	return nil
}

func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
	srv.runOnce()
	isWS := r.Header.Get("Upgrade") == "websocket"
	isLiveReload := isWS && r.Header.Get("Sec-WebSocket-Protocol") == liveReloadProtocol

	err := <-srv.ready

	if isLiveReload {
		return srv.handleLivedevSocket(w, r)
	}

	if err != nil {
		return err
	}

	srv.pending.Add(1)
	defer srv.pending.Done()

	if isWS {
		return srv.serveWebSocket(w, r)
	}

	req := new(http.Request)
	*req = *r
	req.Host = srv.addr
	req.URL.Host = srv.addr
	req.Proto = "HTTP/1.1"
	req.Close = false
	req.ProtoMajor = 1
	req.ProtoMinor = 1
	transport := http.DefaultTransport

	if len(req.URL.Scheme) == 0 {
		req.URL.Scheme = "http"
	}

	if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
		req.Header.Set("X-Forwarded-For", ip)
	}

	response, err := transport.RoundTrip(req)

	if err != nil {
		return fmt.Errorf("%s\n%s\n", err.Error(), srv.stderr.ReadAll())
	}

	defer response.Body.Close()

	wh := w.Header()

	for key, v := range response.Header {
		for _, value := range v {
			wh.Add(key, value)
		}
	}

	body := response.Body.(io.Reader)

	if strings.HasPrefix(response.Header.Get("Content-Type"), "text/html") {
		var contentLen int
		gzipped := "gzip" == response.Header.Get("Content-Encoding")
		if gzipped {
			body, err = gzip.NewReader(body)
			if err != nil {
				return err
			}
		}
		body, contentLen, err = appendLiveScript(body, srv.proxyPort)

		if err != nil {
			return err
		}
		if gzipped {
			gw := gzip.NewWriter(w)
			defer gw.Close()
			w = responseWriter{gw, w}
		}

		wh.Set("Content-Length", strconv.Itoa(contentLen))
	}

	w.WriteHeader(response.StatusCode)
	if _, err := io.Copy(w, body); err != nil {
		return fmt.Errorf("%s\n%s\n", err.Error(), srv.stderr.ReadAll())
	}

	return nil
}

func appendLiveScript(reader io.Reader, port int) (io.Reader, int, error) {

	data, err := ioutil.ReadAll(reader)

	if err == nil {
		data = appendHTML(data, []byte(fmt.Sprintf(liveReloadHTML, port)))
	}

	if err != nil {
		return nil, 0, err
	}

	return bytes.NewReader(data), len(data), nil

}

type responseWriter struct {
	io.Writer
	http.ResponseWriter
}

func (w responseWriter) Write(b []byte) (int, error) {
	return w.Writer.Write(b)
}


text:
namespace Moip.Net.V2.Model
{
    /// <summary>
    /// Tarifas do pagamento
    /// </summary>
    public class Taxa
    {
        public FeeType Type { get; set; }
        public int Amount { get; set; }
    }
}


text:
/**
 */
package bpsim;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.util.FeatureMap;

/**
 *
 * A representation of the model object 'Enum Parameter Type'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link bpsim.EnumParameterType#getGroup Group}

 *
{@link bpsim.EnumParameterType#getParameterValueGroup Parameter Value Group}

 *
{@link bpsim.EnumParameterType#getParameterValue Parameter Value}

 *

 *

 *
 * @see bpsim.BpsimPackage#getEnumParameterType()
 * @model extendedMetaData="name='EnumParameter_._type' kind='elementOnly'"
 * @generated
 */
public interface EnumParameterType extends ParameterValue {
	/**
	 * Returns the value of the 'Group' attribute list.
	 * The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}.
	 *
	 *
	 *
	 * Even if here we reference a list of Parameter Values, only Constant Parameters are valid here. There is just no real way of expressing it in xsd.
	 *
	 * @return the value of the 'Group' attribute list.
	 * @see bpsim.BpsimPackage#getEnumParameterType_Group()
	 * @model unique="false" dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="true"
	 *        extendedMetaData="kind='group' name='group:3'"
	 * @generated
	 */
	FeatureMap getGroup();

	/**
	 * Returns the value of the 'Parameter Value Group' attribute list.
	 * The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}.
	 *
	 *

	 * If the meaning of the 'Parameter Value Group' attribute list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Parameter Value Group' attribute list.
	 * @see bpsim.BpsimPackage#getEnumParameterType_ParameterValueGroup()
	 * @model unique="false" dataType="org.eclipse.emf.ecore.EFeatureMapEntry" required="true" many="true" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='group' name='ParameterValue:group' namespace='##targetNamespace' group='#group:3'"
	 * @generated
	 */
	FeatureMap getParameterValueGroup();

	/**
	 * Returns the value of the 'Parameter Value' containment reference list.
	 * The list contents are of type {@link bpsim.ParameterValue}.
	 *
	 *

	 * If the meaning of the 'Parameter Value' containment reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Parameter Value' containment reference list.
	 * @see bpsim.BpsimPackage#getEnumParameterType_ParameterValue()
	 * @model containment="true" required="true" transient="true" volatile="true" derived="true"
	 *        extendedMetaData="kind='element' name='ParameterValue' namespace='##targetNamespace' group='ParameterValue:group'"
	 * @generated
	 */
	EList<ParameterValue> getParameterValue();

} // EnumParameterType


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBitcoin.Protocol
{
	[Payload("blocktxn")]
	public class BlockTxnPayload : Payload
	{

		uint256 _BlockId;
		public uint256 BlockId
		{
			get
			{
				return _BlockId;
			}
			set
			{
				_BlockId = value;
			}
		}

		private List<Transaction> _Transactions = new List<Transaction>();
		public List<Transaction> Transactions
		{
			get
			{
				return _Transactions;
			}
		}

		public override void ReadWriteCore(BitcoinStream stream)
		{
			stream.ReadWrite(ref _BlockId);
			stream.ReadWrite(ref _Transactions);
		}
	}
}


text:
package com.amazonaws.services.qldb.model.transform;

import java.util.Map;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.qldb.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * StreamJournalToKinesisRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class StreamJournalToKinesisRequestMarshaller {

    private static final MarshallingInfo<String> LEDGERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<String> ROLEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("RoleArn").build();
    private static final MarshallingInfo<Map> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Tags").build();
    private static final MarshallingInfo<java.util.Date> INCLUSIVESTARTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InclusiveStartTime").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<java.util.Date> EXCLUSIVEENDTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ExclusiveEndTime").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<StructuredPojo> KINESISCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("KinesisConfiguration").build();
    private static final MarshallingInfo<String> STREAMNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StreamName").build();

    private static final StreamJournalToKinesisRequestMarshaller instance = new StreamJournalToKinesisRequestMarshaller();

    public static StreamJournalToKinesisRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(StreamJournalToKinesisRequest streamJournalToKinesisRequest, ProtocolMarshaller protocolMarshaller) {

        if (streamJournalToKinesisRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(streamJournalToKinesisRequest.getLedgerName(), LEDGERNAME_BINDING);
            protocolMarshaller.marshall(streamJournalToKinesisRequest.getRoleArn(), ROLEARN_BINDING);
            protocolMarshaller.marshall(streamJournalToKinesisRequest.getTags(), TAGS_BINDING);
            protocolMarshaller.marshall(streamJournalToKinesisRequest.getInclusiveStartTime(), INCLUSIVESTARTTIME_BINDING);
            protocolMarshaller.marshall(streamJournalToKinesisRequest.getExclusiveEndTime(), EXCLUSIVEENDTIME_BINDING);
            protocolMarshaller.marshall(streamJournalToKinesisRequest.getKinesisConfiguration(), KINESISCONFIGURATION_BINDING);
            protocolMarshaller.marshall(streamJournalToKinesisRequest.getStreamName(), STREAMNAME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
"""
* add version and updated_at to provider_details
* set active to not nullable (any existing null is set to false)
* create provider_details_history table, mimicking provider_details

Revision ID: 0062_provider_details_history
Revises: 0061_add_client_reference
Create Date: 2016-12-14 13:00:24.226990

"""

# revision identifiers, used by Alembic.
revision = "0062_provider_details_history"
down_revision = "0061_add_client_reference"

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

def upgrade():
    op.get_bind()
    op.add_column("provider_details", sa.Column("updated_at", sa.DateTime()))

    op.execute("UPDATE provider_details SET active = false WHERE active is null")
    op.alter_column("provider_details", "active", nullable=False)

    op.add_column("provider_details", sa.Column("version", sa.Integer(), nullable=True))
    op.execute("UPDATE provider_details SET version = 1")
    op.alter_column("provider_details", "version", nullable=False)

    op.create_table(
        "provider_details_history",
        sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("display_name", sa.String(), nullable=False),
        sa.Column("identifier", sa.String(), nullable=False),
        sa.Column("priority", sa.Integer(), nullable=False),
        sa.Column(
            "notification_type",
            postgresql.ENUM("email", "sms", "letter", name="notification_type", create_type=False),
            nullable=False,
        ),
        sa.Column("active", sa.Boolean(), nullable=False),
        sa.Column("version", sa.Integer(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.PrimaryKeyConstraint("id", "version"),
    )
    op.execute(
        "INSERT INTO provider_details_history"
        + " (id, display_name, identifier, priority, notification_type, active, version)"
        + " SELECT id, display_name, identifier, priority, notification_type, active, version FROM provider_details"
    )

def downgrade():
    op.drop_table("provider_details_history")

    op.alter_column("provider_details", "active", existing_type=sa.BOOLEAN(), nullable=True)
    op.drop_column("provider_details", "version")
    op.drop_column("provider_details", "updated_at")


text:
`mercury_uuid` is a [Mercury](http:/www.mercurylang.org) library providing
universally unique identifiers (UUIDs).

## License

`mercury_uuid` is licensed under a simple 2-clause BSD style license.  See the
file [COPYING](COPYING) for details.

## Author

Julien Fischer <juliensf@gmail.com>


text:
import { createElement, render } from 'rax';
import * as DriverDOM from 'driver-dom';

import { document } from 'global';
import dedent from 'ts-dedent';

const rootElement = document ? document.getElementById('root') : null;

export default function renderMain({
  storyFn,
  kind,
  name,
  showMain,
  showError,
}: {
  storyFn: Function;
  kind: string;
  name: string;
  showMain: () => any;
  showError: (input: { title: string; description: string }) => void;
}) {
  const Element = storyFn;

  if (!Element) {
    showError({
      title: `Expecting a Rax element from the story: "${name}" of "${kind}".`,
      description: dedent`
        Did you forget to return the Rax element from the story?
        Use "() => (<MyComp/>)" or "() => { return <MyComp/>; }" when defining the story.
      `,
    });
    return;
  }

  showMain();

  // There is something miscellaneous here, for now, more precisely on L23,
  // as we are using the storyFn directly and not calling it, so `Element` is a
  // function but according to `createElement` types, there is no signature
  // taking a function as input.
  // @ts-expect-error
  render(createElement(Element), rootElement, {
    driver: DriverDOM,
  });
}


text:
module Decimals

    import Core: ===
    import Base: string, float, ==, +, -, *, /, .*, ./, is

    export Decimal,
           decimal,
           string,
           float,
           number,
           norm,
           round,
           isequal,
           is,
           isint,
           inv,
           +,
           -,
           *,
           /,
           ==

    DIGITS = 20

    # Numerical value: (-1)^s * c * 10^q
    immutable Decimal
        s::Integer  # sign can be 0 (+) or 1 (-)
        c::BigInt   # coefficient (significand)
        q::Integer  # exponent
    end

    Decinum = Union{Decimal, Number}

    # Convert between Decimal objects, numbers, and strings
    include("decimal.jl")

    # Decimal normalization
    include("norm.jl")

    # Addition, subtraction, negation, multiplication
    include("arithmetic.jl")

    # Equality
    include("equals.jl")

    # Rounding
    include("round.jl")

end


text:
Add-Type -Path "$($PSScriptRoot)\EPPlus.dll"

. $PSScriptRoot\Charting.ps1
. $PSScriptRoot\ConvertFromExcelData.ps1
. $PSScriptRoot\ConvertFromExcelToSQLInsert.ps1
. $PSScriptRoot\ConvertToExcelXlsx.ps1
. $PSScriptRoot\Copy-ExcelWorkSheet.ps1
. $PSScriptRoot\Export-Excel.ps1
. $PSScriptRoot\Export-ExcelSheet.ps1
. $PSScriptRoot\Get-ExcelColumnName.ps1
. $PSScriptRoot\Get-ExcelSheetInfo.ps1
. $PSScriptRoot\Get-ExcelWorkbookInfo.ps1
. $PSScriptRoot\Get-HtmlTable.ps1
. $PSScriptRoot\Get-Range.ps1
. $PSScriptRoot\Get-XYRange.ps1
. $PSScriptRoot\Import-Html.ps1
. $PSScriptRoot\Import-ExcelTable.ps1
. $PSScriptRoot\InferData.ps1
. $PSScriptRoot\Invoke-Sum.ps1
. $PSScriptRoot\New-ConditionalFormattingIconSet.ps1
. $PSScriptRoot\New-ConditionalText.ps1
. $PSScriptRoot\New-ExcelChart.ps1
. $PSScriptRoot\New-PSItem.ps1
. $PSScriptRoot\Pivot.ps1
. $PSScriptRoot\Set-CellStyle.ps1
. $PSScriptRoot\TrackingUtils.ps1
. $PSScriptRoot\Update-FirstObjectProperties.ps1

if ($PSVersionTable.PSVersion.Major -ge 5) {
    . $PSScriptRoot\Plot.ps1

    Function New-Plot {

        [PSPlot]::new()
    }

}
else {
    Write-Warning 'PowerShell 5 is required for plot.ps1'
    Write-Warning 'PowerShell Excel is ready, except for that functionality'
}

Function Import-Excel {
     <#
    .SYNOPSIS
        Create custom objects from the rows in an Excel worksheet.

    .DESCRIPTION
        The Import-Excel cmdlet creates custom objects from the rows in an Excel worksheet. Each row represents one object. All of this is possible without installing Microsoft Excel and by using the .NET library 'EPPLus.dll'.

        By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blanc property name, only columns with column headers will be imported.

        If the default behavior is not desired and you want to import the complete worksheet 'as is', the parameter '-NoHeader' can be used. In case you want to provide your own property names, you can use the parameter '-HeaderName'.

    .PARAMETER Path
        Specifies the path to the Excel file.

    .PARAMETER WorksheetName
        Specifies the name of the worksheet in the Excel workbook to import. By default, if no name is provided, the first worksheet will be imported.

    .PARAMETER DataOnly
        Import only rows and columns that contain data, empty rows and empty columns are not imported.

    .PARAMETER HeaderName
        Specifies custom property names to use, instead of the values defined in the column headers of the TopRow.

        In case you provide less header names than there is data in the worksheet, then only the data with a corresponding header name will be imported and the data without header name will be disregarded.

        In case you provide more header names than there is data in the worksheet, then all data will be imported and all objects will have all the property names you defined in the header names. As such, the last properties will be blanc as there is no data for them.

    .PARAMETER NoHeader
        Automatically generate property names (P1, P2, P3, ..) instead of the ones defined in the column headers of the TopRow.

        This switch is best used when you want to import the complete worksheet 'as is' and are not concerned with the property names.

    .PARAMETER StartRow
        The row from where we start to import data, all rows above the StartRow are disregarded. By default this is the first row.

        When the parameters '-NoHeader' and '-HeaderName' are not provided, this row will contain the column headers that will be used as property names. When one of both parameters are provided, the property names are automatically created and this row will be treated as a regular row containing data.

    .PARAMETER Password
        Accepts a string that will be used to open a password protected Excel file.

    .EXAMPLE
        Import data from an Excel worksheet. One object is created for each row. The property names of the objects consist of the column names defined in the first row. In case a column doesn't have a column header (usually in row 1 when '-StartRow' is not used), then the unnamed columns will be skipped and the data in those columns will not be imported.

        ----------------------------------------------
        | File: Movies.xlsx     -      Sheet: Actors |
        ----------------------------------------------
        |           A           B            C       |
        |1     First Name                 Address    |
        |2     Chuck         Norris       California |
        |3     Jean-Claude   Vandamme     Brussels   |
        ----------------------------------------------

        PS C:\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors

        First Name: Chuck
        Address   : California

        First Name: Jean-Claude
        Address   : Brussels

        Notice that column 'B' is not imported because there's no value in cell 'B1' that can be used as property name for the objects.

    .EXAMPLE
        Import the complete Excel worksheet 'as is' by using the '-NoHeader' switch. One object is created for each row. The property names of the objects will be automatically generated (P1, P2, P3, ..).

        ----------------------------------------------
        | File: Movies.xlsx     -      Sheet: Actors |
        ----------------------------------------------
        |           A           B            C       |
        |1     First Name                 Address    |
        |2     Chuck         Norris       California |
        |3     Jean-Claude   Vandamme     Brussels   |
        ----------------------------------------------

        PS C:\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -NoHeader

        P1: First Name
        P2:
        P3: Address

        P1: Chuck
        P2: Norris
        P3: California

        P1: Jean-Claude
        P2: Vandamme
        P3: Brussels

        Notice that the column header (row 1) is imported as an object too.

     .EXAMPLE
        Import data from an Excel worksheet. One object is created for each row. The property names of the objects consist of the names defined in the parameter '-HeaderName'. The properties are named starting from the most left column (A) to the right. In case no value is present in one of the columns, that property will have an empty value.

        ----------------------------------------------------------
        | File: Movies.xlsx            -           Sheet: Movies |
        ----------------------------------------------------------
        |           A            B            C          D       |
        |1     The Bodyguard   1992           9                  |
        |2     The Matrix      1999           8                  |
        |3                                                       |
        |4     Skyfall         2012           9                  |
        ----------------------------------------------------------

        PS C:\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Movies -HeaderName 'Movie name', 'Year', 'Rating', 'Genre'

        Movie name: The Bodyguard
        Year      : 1992
        Rating    : 9
        Genre     :

        Movie name: The Matrix
        Year      : 1999
        Rating    : 8
        Genre     :

        Movie name:
        Year      :
        Rating    :
        Genre     :

        Movie name: Skyfall
        Year      : 2012
        Rating    : 9
        Genre     :

        Notice that empty rows are imported and that data for the property 'Genre' is not present in the worksheet. As such, the 'Genre' property will be blanc for all objects.

     .EXAMPLE
        Import data from an Excel worksheet. One object is created for each row. The property names of the objects are automatically generated by using the switch '-NoHeader' (P1, P@, P#, ..). The switch '-DataOnly' will speed up the import because empty rows and empty columns are not imported.

        ----------------------------------------------------------
        | File: Movies.xlsx            -           Sheet: Movies |
        ----------------------------------------------------------
        |           A            B            C          D       |
        |1     The Bodyguard   1992           9                  |
        |2     The Matrix      1999           8                  |
        |3                                                       |
        |4     Skyfall         2012           9                  |
        ----------------------------------------------------------

        PS C:\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Movies -NoHeader -DataOnly

        P1: The Bodyguard
        P2: 1992
        P3: 9

        P1: The Matrix
        P2: 1999
        P3: 8

        P1: Skyfall
        P2: 2012
        P3: 9

        Notice that empty rows and empty columns are not imported.

 .EXAMPLE
        Import data from an Excel worksheet. One object is created for each row. The property names are provided with the '-HeaderName' parameter. The import will start from row 2 and empty columns and rows are not imported.

        ----------------------------------------------------------
        | File: Movies.xlsx            -           Sheet: Actors |
        ----------------------------------------------------------
        |           A           B           C            D       |
        |1     Chuck                     Norris       California |
        |2                                                       |
        |3     Jean-Claude               Vandamme     Brussels   |
        ----------------------------------------------------------

        PS C:\> Import-Excel -Path 'C:\Movies.xlsx' -WorkSheetname Actors -DataOnly -HeaderName 'FirstName', 'SecondName', 'City' -StartRow 2

        FirstName : Jean-Claude
        SecondName: Vandamme
        City      : Brussels

        Notice that only 1 object is imported with only 3 properties. Column B and row 2 are empty and have been disregarded by using the switch '-DataOnly'. The property names have been named with the values provided with the parameter '-HeaderName'. Row number 1 with 'Chuck Norris' has not been imported, because we started the import from row 2 with the parameter '-StartRow 2'.

    .LINK
        https://github.com/dfinke/ImportExcel

    .NOTES
    #>

    [CmdLetBinding(DefaultParameterSetName)]
    Param (
        [Alias('FullName')]
        [Parameter(ValueFromPipelineByPropertyName, ValueFromPipeline, Position=0, Mandatory)]
        [ValidateScript({(Test-Path -Path $_ -PathType Leaf) -and ($_ -match '.xls$|.xlsx$')})]
        [String]$Path,
        [Alias('Sheet')]
        [Parameter(Position=1)]
        [ValidateNotNullOrEmpty()]
        [String]$WorksheetName,
        [Parameter(ParameterSetName='B', Mandatory)]
        [String[]]$HeaderName,
        [Parameter(ParameterSetName='C', Mandatory)]
        [Switch]$NoHeader,
        [Alias('HeaderRow','TopRow')]
        [ValidateRange(1, 9999)]
        [Int]$StartRow,
        [Switch]$DataOnly,
        [ValidateNotNullOrEmpty()]
        [String]$Password
    )

    Begin {
        Function Add-Property {
            <#
            .SYNOPSIS
                Add the property name and value to the hashtable that will create a new object for each row.
            #>

            Param (
                [Parameter(Mandatory)]
                [String]$Name,
                $Value
            )

            Try {
                $NewRow.$Name = $Value
                Write-Verbose "Import cell '$($Worksheet.Cells[$R, $P.Column].Address)' with property name '$Name' and value '$Value'"
            }
            Catch {
                throw "Failed adding the property name '$Name' with value '$Value': $_"
            }
        }

        Function Get-PropertyNames {
            <#
            .SYNOPSIS
                Create objects containing the column number and the column name for each of the different header types.
            #>

            Param (
                [Parameter(Mandatory)]
                [Int[]]$Columns,
                [Parameter(Mandatory)]
                [Int]$StartRow
            )

            Try {
                if ($NoHeader) {
                    $i = 0
                    foreach ($C in $Columns) {
                        $i++
                        $C | Select-Object @{N='Column'; E={$_}}, @{N='Value'; E={'P' + $i}}
                    }
                }
                elseif ($HeaderName) {
                    $i = 0
                    foreach ($H in $HeaderName) {
                        $H | Select-Object @{N='Column'; E={$Columns[$i]}}, @{N='Value'; E={$H}}
                        $i++
                    }
                }
                else {
                    if ($StartRow -eq 0) {
                        throw 'The top row can never be equal to 0 when we need to retrieve headers from the worksheet.'
                    }

                    foreach ($C in $Columns) {
                        $Worksheet.Cells[$StartRow,$C] | where {$_.Value} | Select-Object @{N='Column'; E={$C}}, Value
                    }
                }
            }
            Catch {
                throw "Failed creating property names: $_"
            }
        }
    }

    Process {
        Try {
            #region Open file
            $Path = (Resolve-Path $Path).ProviderPath
            Write-Verbose "Import Excel workbook '$Path' with worksheet '$Worksheetname'"

            $Stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path, 'Open', 'Read', 'ReadWrite'

            if ($Password) {
                $Excel = New-Object -TypeName OfficeOpenXml.ExcelPackage

	            Try {
		            $Excel.Load($Stream,$Password)
	            }
	            Catch {
		            throw "Password '$Password' is not correct."
	            }
            }
            else {
                $Excel = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Stream
            }
            #endregion

            #region Select worksheet
            if ($WorksheetName) {
                if (-not ($Worksheet = $Excel.Workbook.Worksheets[$WorkSheetName])) {
                    throw "Worksheet '$WorksheetName' not found, the workbook only contains the worksheets '$($Excel.Workbook.Worksheets)'. If you only wish to select the first worksheet, please remove the '-WorksheetName' parameter."
                }
            }
            else {
                $Worksheet = $Excel.Workbook.Worksheets | Select-Object -First 1
            }
            #endregion

            #region Set the top row
            if (((-not ($NoHeader -or $HeaderName)) -and ($StartRow -eq 0))) {
                $StartRow = 1
            }
            #endregion

            if (-not ($AllCells = $Worksheet.Cells | where {($_.Start.Row -ge $StartRow)})) {
                Write-Warning "Worksheet '$WorksheetName' in workbook '$Path' is empty after StartRow '$StartRow'"
            }
            else {
                #region Get rows and columns
                if ($DataOnly) {
                    $CellsWithValues = $AllCells | where {$_.Value}

                    $Columns = $CellsWithValues.Start.Column | Sort-Object -Unique
                    $Rows = $CellsWithValues.Start.Row | Sort-Object -Unique
                }
                else {
                    $LastColumn = $AllCells.Start.Column | Sort-Object -Unique | Select-Object -Last 1
                    $Columns = 1..$LastColumn

                    $LastRow = $AllCells.Start.Row | Sort-Object -Unique | Select-Object -Last 1
                    $Rows = $StartRow..$LastRow | where {($_ -ge $StartRow) -and ($_ -gt 0)}
                }
                #endregion

                #region Create property names
                if ((-not $Columns) -or (-not ($PropertyNames = Get-PropertyNames -Columns $Columns -StartRow $StartRow))) {
                    throw "No column headers found on top row '$StartRow'. If column headers in the worksheet are not a requirement then please use the '-NoHeader' or '-HeaderName' parameter."
                }

                if ($Duplicates = $PropertyNames | Group-Object Value | where Count -GE 2) {
                    throw "Duplicate column headers found on row '$StartRow' in columns '$($Duplicates.Group.Column)'. Column headers must be unique, if this is not a requirement please use the '-NoHeader' or '-HeaderName' parameter."
                }
                #endregion

                #region Filter out rows with data in columns that don't have a column header
                if ($DataOnly -and (-not $NoHeader)) {
                    $Rows = $CellsWithValues.Start | where {$PropertyNames.Column -contains $_.Column} |
                        Sort-Object Row -Unique | Select-Object -ExpandProperty Row
                }
                #endregion

                #region Filter out the top row when it contains column headers
                if (-not ($NoHeader -or $HeaderName)) {
                    $Rows = $Rows | where {$_ -gt $StartRow}
                }
                #endregion

                if (-not $Rows) {
                    Write-Warning "Worksheet '$WorksheetName' in workbook '$Path' contains no data in the rows after top row '$StartRow'"
                }
                else {
                    #region Create one object per row
                    foreach ($R in $Rows) {
                        Write-Verbose "Import row '$R'"
                        $NewRow = [Ordered]@{}

                        foreach ($P in $PropertyNames) {
                            Add-Property -Name $P.Value -Value $Worksheet.Cells[$R, $P.Column].Value
                        }

                        [PSCustomObject]$NewRow
                    }
                    #endregion
                }
            }
        }
        Catch {
            throw "Failed importing the Excel workbook '$Path' with worksheet '$Worksheetname': $_"
        }
        Finally {
            $Stream.Close()
            $Stream.Dispose()
            $Excel.Dispose()
            $Excel = $null
        }
    }
}

function Add-WorkSheet {
    param(
        #TODO Use parametersets to allow a workbook to be passed instead of a package
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [OfficeOpenXml.ExcelPackage] $ExcelPackage,
        [Parameter(Mandatory=$true)]
        [string] $WorkSheetname,
        [Switch] $NoClobber
    )

    $ws = $ExcelPackage.Workbook.Worksheets[$WorkSheetname]

    if(!$ws) {
        Write-Verbose "Add worksheet '$WorkSheetname'"
        $ws=$ExcelPackage.Workbook.Worksheets.Add($WorkSheetname)
    }

    return $ws
}

function ConvertFrom-ExcelSheet {
    <#
        .Synopsis
        Reads an Excel file an converts the data to a delimited text file

        .Example
        ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data
        Reads each sheet in TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt

        .Example
        ConvertFrom-ExcelSheet .\TestSheets.xlsx .\data sheet?0
        Reads and outputs sheets like Sheet10 and Sheet20 form TestSheets.xlsx and outputs it to the data directory as the sheet name with the extension .txt
    #>

    [CmdletBinding()]
    param
    (
        [Alias("FullName")]
        [Parameter(Mandatory = $true)]
        [String]
        $Path,
        [String]
        $OutputPath = '.\',
        [String]
        $SheetName="*",
        [ValidateSet('ASCII', 'BigEndianUniCode','Default','OEM','UniCode','UTF32','UTF7','UTF8')]
        [string]
        $Encoding = 'UTF8',
        [ValidateSet('.txt', '.log','.csv')]
        [string]
        $Extension = '.csv',
        [ValidateSet(';', ',')]
        [string]
        $Delimiter = ';'
    )

    $Path = (Resolve-Path $Path).Path
    $stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path,"Open","Read","ReadWrite"
    $xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $stream
    $workbook = $xl.Workbook

    $targetSheets = $workbook.Worksheets | Where {$_.Name -like $SheetName}

    $params = @{} + $PSBoundParameters
    $params.Remove("OutputPath")
    $params.Remove("SheetName")
    $params.Remove('Extension')
    $params.NoTypeInformation = $true

    Foreach ($sheet in $targetSheets)
    {
        Write-Verbose "Exporting sheet: $($sheet.Name)"

        $params.Path = "$OutputPath\$($Sheet.Name)$Extension"

        Import-Excel $Path -Sheet $($sheet.Name) | Export-Csv @params
    }

    $stream.Close()
    $stream.Dispose()
    $xl.Dispose()
}

function Export-MultipleExcelSheets {
    param(
        [Parameter(Mandatory=$true)]
        $Path,
        [Parameter(Mandatory=$true)]
        [hashtable]$InfoMap,
        [string]$Password,
        [Switch]$Show,
        [Switch]$AutoSize
    )

    $parameters = @{}+$PSBoundParameters
    $parameters.Remove("InfoMap")
    $parameters.Remove("Show")

    $parameters.Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)

    foreach ($entry in $InfoMap.GetEnumerator()) {
        Write-Progress -Activity "Exporting" -Status "$($entry.Key)"
        $parameters.WorkSheetname=$entry.Key

        & $entry.Value | Export-Excel @parameters
    }

    if($Show) {Invoke-Item $Path}
}


text:
"""
    pure_python
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging

log = logging.getLogger(__name__)

def updateLightsByCoord(dim, x, y, z):
    for i in range(len(x)):
        updateLights(dim, x[i], y[i], z[i])

def updateLightsInSelection(dim, selection):
    for x, y, z in selection.positions:
        updateLights(dim, x, y, z)

def neighbors(x, y, z):
    yield x-1, y, z
    yield x+1, y, z
    yield x, y-1, z
    yield x, y+1, z
    yield x, y, z-1
    yield x, y, z+1

def updateLights(dim, x, y, z):
    # import pdb; pdb.set_trace()
    previousLight = dim.getBlockLight(x, y, z)
    light = dim.getBlock(x, y, z).brightness
    dim.setBlockLight(x, y, z, light)

    drawLight(dim, x, y, z)

    if previousLight < light:
        spreadLight(dim, x, y, z)

    if previousLight > light:
        fadeLight(dim, x, y, z, previousLight)

def getOpacity(dim, x, y, z):
    return max(1, dim.getBlock(x, y, z).opacity)

def drawLight(dim, x, y, z):
    opacity = getOpacity(dim, x, y, z)

    for nx, ny, nz in neighbors(x, y, z):
        adjacentLight = dim.getBlockLight(nx, ny, nz)
        if adjacentLight - opacity > dim.getBlockLight(x, y, z):
            dim.setBlockLight(x, y, z, adjacentLight - opacity)

def spreadLight(dim, x, y, z):
    light = dim.getBlockLight(x, y, z)
    if light <= 0:
        return

    for nx, ny, nz in neighbors(x, y, z):

        # xxx cast to int because one of these is a numpy.uint8 and
        # light - opacity rolls over to a large number.
        adjacentLight = int(dim.getBlockLight(nx, ny, nz))
        adjacentOpacity = getOpacity(dim, nx, ny, nz)
        newLight = light - adjacentOpacity
        # If the adjacent cell already has the "correct" light value, stop.
        if newLight > adjacentLight:
            dim.setBlockLight(nx, ny, nz, newLight)
            spreadLight(dim, nx, ny, nz)

def fadeLight(dim, x, y, z, previousLight):
    fadedCells = findFadedCells(dim, x, y, z, previousLight)
    for x, y, z in fadedCells:
        dim.setBlockLight(x, y, z, dim.getBlock(x, y, z).brightness)
        # dim.setBlock(x, y, z, "glass")
    for x, y, z in fadedCells:
        drawLight(dim, x, y, z)
    for x, y, z in fadedCells:
        spreadLight(dim, x, y, z)

def relCoords(ox, oy, oz, coords):
    for x, y, z, l in coords:
        yield x - ox, y - oy, z - oz

def findFadedCells(dim, ox, oy, oz, oPreviousLight):
    foundCells = set()
    toScan = [(ox, oy, oz, oPreviousLight)]

    while len(toScan):
        x, y, z, previousLight = toScan.pop(0)
        for nx, ny, nz in neighbors(x, y, z):

            adjacentLight = int(dim.getBlockLight(nx, ny, nz))
            adjacentOpacity = getOpacity(dim, nx, ny, nz)
            if previousLight - adjacentOpacity <= 0:
                continue
            if previousLight - adjacentOpacity == adjacentLight:
                if (nx, ny, nz) not in foundCells:
                    toScan.append((nx, ny, nz, adjacentLight))
                    foundCells.add((nx, ny, nz))

    return foundCells