text:
#include "Binary.h"
#include "Map.h"
#include "Types.h"
#include "Variable.h"
#include <istream>
namespace dynv {
namespace binary {
using ValueType = types::ValueType;
struct CountVisitor {
	CountVisitor(const std::unordered_map<types::ValueType, uint8_t> &typeMap):
		typeMap(typeMap) {
	}
	template<typename T>
	int operator()(const T &value) const {
		using namespace types::binary;
		auto i = typeMap.find(dynv::types::typeHandler<T>().type);
		return i != typeMap.end() ? 1 : 0;
	}
	int operator()(const Ref &value) const {
		return 0;
	}
	template<typename T>
	int operator()(const std::vector<T> &values) const {
		return 0;
	}
	const std::unordered_map<types::ValueType, uint8_t> &typeMap;
};
struct SerializeVisitor {
	SerializeVisitor(std::ostream &stream, const std::string &name, const std::unordered_map<types::ValueType, uint8_t> &typeMap):
		stream(stream),
		name(name),
		typeMap(typeMap) {
	}
	template<typename T>
	bool operator()(const T &value) const {
		using namespace types::binary;
		auto i = typeMap.find(dynv::types::typeHandler<T>().type);
		if (i == typeMap.end())
			return true;
		if (!write(stream, i->second))
			return false;
		if (!write(stream, name))
			return false;
		if (!write(stream, value))
			return false;
		return true;
	}
	bool operator()(const Ref &value) const {
		return true; // skip unsupported value type for binary serialization
	}
	template<typename T>
	bool operator()(const std::vector<T> &values) const {
		return true; // skip unsupported value type for binary serialization
	}
	std::ostream &stream;
	const std::string &name;
	const std::unordered_map<types::ValueType, uint8_t> &typeMap;
};
bool serialize(std::ostream &stream, const Map &map, const std::unordered_map<types::ValueType, uint8_t> &typeMap) {
	using namespace types::binary;
	uint32_t count = 0;
	auto countVisitor = [&typeMap, &count](const Variable &value) -> bool {
		count += std::visit(CountVisitor(typeMap), value.data());
		return true;
	};
	if (!map.visit(countVisitor))
		return false;
	if (!write(stream, count))
		return false;
	auto visitor = [&stream, &typeMap](const Variable &value) -> bool {
		if (!std::visit(SerializeVisitor(stream, value.name(), typeMap), value.data()))
			return false;
		return true;
	};
	if (!map.visit(visitor))
		return false;
	return true;
}
bool deserialize(std::istream &stream, Map &map, const std::unordered_map<uint8_t, ValueType> &typeMap) {
	using namespace types::binary;
	uint32_t count = read<uint32_t>(stream);
	if (!stream.good())
		return false;
	for (uint32_t i = 0; i < count; i++) {
		uint8_t handlerId = read<uint8_t>(stream);
		if (!stream.good())
			return false;
		std::string name = read<std::string>(stream);
		if (!stream.good())
			return false;
		auto type = typeMap.find(handlerId);
		if (type == typeMap.end()) {
			auto skip = read<uint32_t>(stream);
			if (!stream.good())
				return false;
			stream.seekg(skip, std::ios::cur);
			continue;
		}
		switch (type->second) {
		case ValueType::basicBool: {
			auto value = read<uint8_t>(stream);
			if (!stream.good())
				return false;
			map.set<bool>(name, value);
		} break;
		case ValueType::basicFloat: {
			auto value = read<float>(stream);
			if (!stream.good())
				return false;
			map.set(name, value);
		} break;
		case ValueType::basicInt32: {
			auto value = read<int32_t>(stream);
			if (!stream.good())
				return false;
			map.set(name, value);
		} break;
		case ValueType::string: {
			auto value = read<std::string>(stream);
			if (!stream.good())
				return false;
			map.set(name, value);
		} break;
		case ValueType::color: {
			auto value = read<Color>(stream);
			if (!stream.good())
				return false;
			map.set(name, value);
		} break;
		case ValueType::map:
		case ValueType::unknown:
			return false;
		}
	}
	return true;
}
}
}


text:
const _ = require('lodash');

module.exports = {
  directive: 'REST',
  handler: function ({command} = {}) {
    const arg = _.get(command, 'arg');
    const byteCount = parseInt(arg, 10);

    if (isNaN(byteCount) || byteCount < 0) return this.reply(501, 'Byte count must be 0 or greater');

    this.restByteCount = byteCount;
    return this.reply(350, `Restarting next transfer at ${byteCount}`);
  },
  syntax: '{{cmd}} <byte-count>',
  description: 'Restart transfer from the specified point. Resets after any STORE or RETRIEVE'
};

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.graph;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.aggregators.Aggregator;
import org.apache.flink.graph.spargel.GatherFunction;
import org.apache.flink.util.Preconditions;

import java.util.HashMap;
import java.util.Map;

/**
 * This is used as a base class for vertex-centric iteration or gather-sum-apply iteration
 * configuration.
 */
public abstract class IterationConfiguration {

    // the iteration name
    private String name;

    // the iteration parallelism
    private int parallelism = -1;

    // the iteration aggregators
    private Map<String, Aggregator<?>> aggregators = new HashMap<>();

    // flag that defines whether the solution set is kept in managed memory
    private boolean unmanagedSolutionSet = false;

    // flag that defines whether the number of vertices option is set
    private boolean optNumVertices = false;

    public IterationConfiguration() {}

    /**
     * Sets the name for the iteration. The name is displayed in logs and messages.
     *
     * @param name The name for the iteration.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Gets the name of the iteration.
     *
     * @param defaultName
     * @return The name of the iteration.
     */
    public String getName(String defaultName) {
        if (name != null) {
            return name;
        } else {
            return defaultName;
        }
    }

    /**
     * Sets the parallelism for the iteration.
     *
     * @param parallelism The parallelism.
     */
    public void setParallelism(int parallelism) {
        Preconditions.checkArgument(
                parallelism > 0 || parallelism == ExecutionConfig.PARALLELISM_DEFAULT,
                "The parallelism must be at least one, or ExecutionConfig.PARALLELISM_DEFAULT (use system default).");
        this.parallelism = parallelism;
    }

    /**
     * Gets the iteration's parallelism.
     *
     * @return The iterations parallelism, or -1, if not set.
     */
    public int getParallelism() {
        return parallelism;
    }

    /**
     * Defines whether the solution set is kept in managed memory (Flink's internal way of keeping
     * object in serialized form) or as a simple object map. By default, the solution set runs in
     * managed memory.
     *
     * @param unmanaged True, to keep the solution set in unmanaged memory, false otherwise.
     */
    public void setSolutionSetUnmanagedMemory(boolean unmanaged) {
        this.unmanagedSolutionSet = unmanaged;
    }

    /**
     * Gets whether the solution set is kept in managed memory (Flink's internal way of keeping
     * object in serialized form) or as a simple object map. By default, the solution set runs in
     * managed memory.
     *
     * @return True, if the solution set is in unmanaged memory, false otherwise.
     */
    public boolean isSolutionSetUnmanagedMemory() {
        return this.unmanagedSolutionSet;
    }

    /**
     * Gets whether the number of vertices option is set. By default, the number of vertices option
     * is not set.
     *
     * @return True, if the number of vertices option is set, false otherwise.
     */
    public boolean isOptNumVertices() {
        return optNumVertices;
    }

    /**
     * Sets the number of vertices option. By default, the number of vertices option is not set.
     *
     * @param optNumVertices True, to set this option, false otherwise.
     */
    public void setOptNumVertices(boolean optNumVertices) {
        this.optNumVertices = optNumVertices;
    }

    /**
     * Registers a new aggregator. Aggregators registered here are available during the execution of
     * the vertex updates via {@link GatherFunction#getIterationAggregator(String)} and {@link
     * GatherFunction#getPreviousIterationAggregate(String)}.
     *
     * @param name The name of the aggregator, used to retrieve it and its aggregates during
     *     execution.
     * @param aggregator The aggregator.
     */
    public void registerAggregator(String name, Aggregator<?> aggregator) {
        this.aggregators.put(name, aggregator);
    }

    /**
     * Gets the set of aggregators that are registered for this vertex-centric iteration.
     *
     * @return a Map of the registered aggregators, where the key is the aggregator name and the
     *     value is the Aggregator object
     */
    public Map<String, Aggregator<?>> getAggregators() {
        return this.aggregators;
    }
}


text:
//  -*- C++ -*-

/*
 * Copyright (C) 1990,91   Silicon Graphics, Inc.
 *
 _______________________________________________________________________
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 |
 |   $Revision: 1.1.1.1 $
 |
 |   Description:
 |	This file defines the SoGLLightIdElement class.
 |
 |   Author(s)		: Paul S. Strauss
 |
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 _______________________________________________________________________
 */

#ifndef  _SO_GL_LIGHT_ID_ELEMENT
#define  _SO_GL_LIGHT_ID_ELEMENT

#include <Inventor/elements/SoInt32Element.h>

//////////////////////////////////////////////////////////////////////////////
//
//  Class: SoGLLightIdElement
//
//  Element that stores the id of the current light. The first light
//  active in a scene has id 0, the next has 1, and so on. This
//  element can be used to determine how many lights are currently
//  active. The initial value of this element is -1 to indicate that
//  there are no lights active.
//
//  Note that even though the effects of this element accumulate (each
//  light source increments the id), it is derived from
//  SoInt32Element. This is because each call to increment()
//  effectively does a "get" of the current top instance, so caching
//  knows about the dependency of each instance on the previous one.
//
//////////////////////////////////////////////////////////////////////////////

SoEXTENDER class INVENTOR_API SoGLLightIdElement : public SoInt32Element {

    SO_ELEMENT_HEADER(SoGLLightIdElement);

  public:
    // Initializes element
    virtual void	init(SoState *state);

    // Increments the current light id. This should be called when a
    // light source becomes active. This returns the new id, or -1 if
    // the maximum number of GL light sources has been exceeded.
    // Otherwise, enables light source.
    static int		increment(SoState *state);

#ifndef IV_STRICT
    static int		increment(SoState *state, SoNode *)
	{ return increment(state); }
#endif

    // Returns current light id from the state
    static int		get(SoState *state)
	{ return (int)SoInt32Element::get(classStackIndex, state); }

    // Returns the default light id
    static int		getDefault()			{ return -1; }

    // Returns the maximum number of concurrent light sources
    // supported by GL implementation
    static int		getMaxGLSources();

    // Overrides push() method to copy values from next instance in the stack
    virtual void	push(SoState *state);

    // Override pop() method so side effects can occur in GL
    virtual void	pop(SoState *state, const SoElement *prevTopElement);

    // Prints element (for debugging)
    virtual void	print(FILE *fp) const;

  SoINTERNAL public:
    // Initializes the SoGLLightIdElement class
    static void		initClass();

  protected:
    virtual ~SoGLLightIdElement();

  private:
    static int		maxGLSources;	// Holds max number of GL sources
};

#endif /* _SO_GL_LIGHT_ID_ELEMENT */


text:
import time
from zmq.eventloop import ioloop

from core.connectors import CommandConnector

loop = ioloop.IOLoop().instance()

class MyCommandConnector(CommandConnector):

    def __init__(self, name, end_point):
        CommandConnector.__init__(self, name, end_point)
        self._stream.on_recv_stream(self._on_recv)

    def _on_recv(self, stream, msg):
        print('command executed: {0}'.format(msg[0]))

if __name__ == "__main__":
    server = 'tcp://127.0.0.1:5555'
    client = MyCommandConnector('MyCommandConnector', server)
    client.connect()

    data = 'hello word'

    client.send(data)

    loop.start()


text:
package com.swiftelan.rafter.servlet.boundary;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.json.JsonObject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

public class JspViewResponseBodyWriterTest {

    private JspViewMessageBodyWriter writer;
    private HttpServletRequest request;
    private HttpServletResponse response;
    private UriInfo uriInfo;
    private ResourceInfo resourceInfo;
    private Configuration configuration;
    private ServletContext servletContext;
    private RequestDispatcher dispatcher;

    @Before
    public void before() {
        writer = new JspViewMessageBodyWriter();
        request = Mockito.mock(HttpServletRequest.class);
        response = Mockito.mock(HttpServletResponse.class);
        uriInfo = Mockito.mock(UriInfo.class);
        resourceInfo = Mockito.mock(ResourceInfo.class);
        configuration = Mockito.mock(Configuration.class);
        writer.configuration = configuration;
        servletContext = Mockito.mock(ServletContext.class);

        Mockito.when(request.getServletContext()).thenReturn(servletContext);

        Map<String, ServletRegistration> registrations = new HashMap<>();
        ServletRegistration registration = Mockito.mock(ServletRegistration.class);
        Mockito.when(registration.getName()).thenReturn("jsp");
        Mockito.when(registration.getMappings()).thenReturn(Collections.singleton("*.jsp"));
        registrations.put("jsp", registration);
        Mockito.when(servletContext.getServletRegistrations()).then(i -> registrations);
        dispatcher = Mockito.mock(RequestDispatcher.class);
        Mockito.when(servletContext.getNamedDispatcher(registration.getName())).thenReturn(dispatcher);

        Mockito.when(uriInfo.getRequestUriBuilder()).then(i -> UriBuilder.fromPath(""));
    }

    @Test
    public void isWriteable() {
        Assert.assertTrue(writer.isWriteable(JspViewContext.class, null, null, null));
        Assert.assertFalse(writer.isWriteable(JsonObject.class, null, null, null));
    }

    @Test
    public void getSize() {
        Assert.assertEquals(-1, writer.getSize(null, null, null, null, null));
    }

    @Test(expected = InternalServerErrorException.class)
    public void noServlets() throws WebApplicationException, IOException {
        Mockito.when(servletContext.getServletRegistrations()).then(i -> Collections.emptyMap());
        JspViewContext context = new JspViewContext("test.jsp", request, response, uriInfo, resourceInfo, configuration,
                Collections.emptyMap());
        OutputStream entityStream = new ByteArrayOutputStream();
        MultivaluedMap<String, Object> httpHeaders = new MultivaluedHashMap<>();
        writer.writeTo(context, null, null, null, null, httpHeaders, entityStream);
    }

    @Test(expected = InternalServerErrorException.class)
    public void noJspServlet() throws WebApplicationException, IOException {
        ServletRegistration registration = Mockito.mock(ServletRegistration.class);
        Mockito.when(registration.getName()).thenReturn("html");
        Mockito.when(registration.getMappings()).thenReturn(Collections.singleton("*.html"));
        Mockito.when(servletContext.getServletRegistrations())
                .then(i -> Collections.singletonMap("html", registration));
        JspViewContext context = new JspViewContext("test.jsp", request, response, uriInfo, resourceInfo, configuration,
                Collections.emptyMap());
        OutputStream entityStream = new ByteArrayOutputStream();
        MultivaluedMap<String, Object> httpHeaders = new MultivaluedHashMap<>();
        writer.writeTo(context, null, null, null, null, httpHeaders, entityStream);
    }

    @Test
    public void noModels() throws WebApplicationException, IOException {
        JspViewContext context = new JspViewContext("test.jsp", request, response, uriInfo, resourceInfo, configuration,
                Collections.emptyMap());
        OutputStream entityStream = new ByteArrayOutputStream();
        MultivaluedMap<String, Object> httpHeaders = new MultivaluedHashMap<>();
        writer.writeTo(context, null, null, null, null, httpHeaders, entityStream);
    }

    @Test
    public void models() throws WebApplicationException, IOException {
        Map<String, Object> models = new HashMap<>();
        models.put("one", "1");
        models.put("two", Integer.valueOf(2));
        JspViewContext context = new JspViewContext("test.jsp", request, response, uriInfo, resourceInfo, configuration,
                models);
        OutputStream entityStream = new ByteArrayOutputStream();
        MultivaluedMap<String, Object> httpHeaders = new MultivaluedHashMap<>();

        final Map<String, Object> attributes = new HashMap<>();
        Mockito.doAnswer(i -> attributes.put(i.getArgument(0), i.getArgument(1))).when(request)
                .setAttribute(Mockito.anyString(), Mockito.any());
        writer.writeTo(context, null, null, null, null, httpHeaders, entityStream);
        Assert.assertEquals(models.get("one"), attributes.get("one"));
        Assert.assertEquals(models.get("two"), attributes.get("two"));
    }

    @Test(expected = InternalServerErrorException.class)
    public void servletException() throws WebApplicationException, IOException, ServletException {
        JspViewContext context = new JspViewContext("test.jsp", request, response, uriInfo, resourceInfo, configuration,
                Collections.emptyMap());
        OutputStream entityStream = new ByteArrayOutputStream();
        MultivaluedMap<String, Object> httpHeaders = new MultivaluedHashMap<>();
        Mockito.doThrow(new ServletException()).when(dispatcher).forward(Mockito.any(), Mockito.any());
        writer.writeTo(context, null, null, null, null, httpHeaders, entityStream);
    }
}


text:
package org.apache.jackrabbit.oak.plugins.segment;

import static org.apache.jackrabbit.oak.api.Type.LONG;
import static org.apache.jackrabbit.oak.api.Type.LONGS;
import static org.apache.jackrabbit.oak.api.Type.STRING;
import static org.apache.jackrabbit.oak.api.Type.STRINGS;
import static org.apache.jackrabbit.oak.plugins.segment.SegmentVersion.LATEST_VERSION;
import static org.apache.jackrabbit.oak.plugins.segment.SegmentVersion.V_10;
import static org.apache.jackrabbit.oak.plugins.segment.SegmentVersion.V_11;
import static org.apache.jackrabbit.oak.plugins.segment.compaction.CompactionStrategy.CleanupType.CLEAN_NONE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;

import javax.annotation.Nonnull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.plugins.segment.compaction.CompactionStrategy;
import org.apache.jackrabbit.oak.plugins.segment.file.FileStore;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStateDiff;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class SegmentVersionTest {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    private File getFileStoreFolder() {
        return folder.getRoot();
    }

    private File directory;

    @Test
    public void latestVersion() {
        assertEquals(V_11, LATEST_VERSION);
    }

    @Test
    public void compareOldRevision() throws Exception {
        FileStore fileStoreV10 = FileStore.builder(getFileStoreFolder()).withMaxFileSize(1).withSegmentVersion(V_10).build();
        try {
            NodeState content = addTestContent(fileStoreV10, "content").getChildNode("content");
            assertVersion(content, SegmentVersion.V_10);
            NodeBuilder builder = content.builder();
            builder.setChildNode("foo");
            content.compareAgainstBaseState(builder.getNodeState(), new NodeStateDiff() {
                @Override
                public boolean propertyAdded(PropertyState after) {
                    fail();
                    return false;
                }

                @Override
                public boolean propertyChanged(PropertyState before, PropertyState after) {
                    fail();
                    return false;
                }

                @Override
                public boolean propertyDeleted(PropertyState before) {
                    fail();
                    return false;
                }

                @Override
                public boolean childNodeAdded(String name, NodeState after) {
                    fail();
                    return false;
                }

                @Override
                public boolean childNodeChanged(String name, NodeState before, NodeState after) {
                    fail();
                    return false;
                }

                @Override
                public boolean childNodeDeleted(String name, NodeState before) {
                    assertEquals("foo", name);
                    return false;
                }
            });
        } finally {
            fileStoreV10.close();
        }
    }

    @Test
    public void readOldVersions() throws Exception {
        FileStore fileStoreV10 = FileStore.builder(getFileStoreFolder()).withMaxFileSize(1).withSegmentVersion(V_10).build();
        try {
            NodeState content = addTestContent(fileStoreV10, "content");
            assertVersion(content, SegmentVersion.V_10);
        } finally {
            fileStoreV10.close();
        }

        FileStore fileStoreV11 = FileStore.builder(getFileStoreFolder()).withMaxFileSize(1).build();
        try {
            verifyContent(fileStoreV11, "content");
        } finally {
            fileStoreV11.close();
        }
    }

    @Test
    public void mixedVersions() throws IOException, CommitFailedException {
        FileStore fileStoreV10 = FileStore.builder(getFileStoreFolder()).withMaxFileSize(1).withSegmentVersion(V_10).build();
        try {
            NodeState content10 = addTestContent(fileStoreV10, "content10");
            assertVersion(content10, SegmentVersion.V_10);
        } finally {
            fileStoreV10.close();
        }

        FileStore fileStoreV11 = FileStore.builder(getFileStoreFolder()).withMaxFileSize(1).build();
        try {
            NodeState content11 = addTestContent(fileStoreV11, "content11");
            assertVersion(content11, V_11);
            verifyContent(fileStoreV11, "content10");
            verifyContent(fileStoreV11, "content11");
        } finally {
            fileStoreV11.close();
        }
    }

    @Test
    public void migrate() throws IOException, CommitFailedException {
        FileStore fileStoreV10 = FileStore.builder(getFileStoreFolder()).withMaxFileSize(1).withSegmentVersion(V_10).build();
        try {
            addTestContent(fileStoreV10, "content10");
        } finally {
            fileStoreV10.close();
        }

        FileStore fileStoreV11 = FileStore.builder(getFileStoreFolder()).withMaxFileSize(1).build();
        try {
            fileStoreV11.setCompactionStrategy(new CompactionStrategy(false, false,
                    CLEAN_NONE, 0, (byte) 0) {
                @Override
                public boolean compacted(@Nonnull Callable<Boolean> setHead) throws Exception {
                    return setHead.call();
                }
            });
            checkAllVersions(fileStoreV11.getHead(), SegmentVersion.V_10);
            fileStoreV11.compact();
            checkAllVersions(fileStoreV11.getHead(), V_11);
        } finally {
            fileStoreV11.close();
        }
    }

    private static void checkAllVersions(SegmentNodeState head, SegmentVersion version) {
        assertVersion(head, version);
        for (ChildNodeEntry childNodeEntry : head.getChildNodeEntries()) {
            checkAllVersions((SegmentNodeState) childNodeEntry.getNodeState(), version);
        }
    }

    private static void assertVersion(NodeState node, SegmentVersion version) {
        assertTrue(node instanceof SegmentNodeState);
        assertEquals(version, ((SegmentNodeState) node).getSegment().getSegmentVersion());
    }

    @SuppressWarnings("deprecation")
    private static NodeState addTestContent(FileStore fs, String nodeName)
            throws CommitFailedException {
        NodeStore store = SegmentNodeStore.builder(fs).build();
        NodeBuilder builder = store.getRoot().builder();

        NodeBuilder content = builder.child(nodeName);
        content.setProperty("a", 1);
        content.setProperty("aM", ImmutableList.of(1L, 2L, 3L, 4L), LONGS);

        content.setProperty("b", "azerty");
        content.setProperty("bM",
                ImmutableList.of("a", "z", "e", "r", "t", "y"), STRINGS);

        // add blobs?

        return store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
    }

    private static void verifyContent(FileStore fs, String nodeName) {
        NodeStore store = SegmentNodeStore.builder(fs).build();
        SegmentNodeState content = (SegmentNodeState) store.getRoot()
                .getChildNode(nodeName);

        assertEquals(new Long(1), content.getProperty("a").getValue(LONG));
        assertEquals(ImmutableList.of(1L, 2L, 3L, 4L),
                Lists.newArrayList(content.getProperty("aM").getValue(LONGS)));

        assertEquals("azerty", content.getProperty("b").getValue(STRING));
        assertEquals("azerty", content.getString("b"));

        assertEquals(ImmutableList.of("a", "z", "e", "r", "t", "y"),
                Lists.newArrayList(content.getProperty("bM").getValue(STRINGS)));
        assertEquals(ImmutableList.of("a", "z", "e", "r", "t", "y"),
                Lists.newArrayList(content.getStrings("bM")));
    }
}


text:
package meetup.akka.simple

import akka.actor.Props
import meetup.akka.{AkkaConfig, TestCaseRunner}

class SimpleActorTest extends TestCaseRunner("simple-actor", Props[Receptionist], AkkaConfig.FullLogConfig) {

}


text:
If you're experiencing slow processing for your feed, try the following:

- Turn off `devMode`. Craft's built-in logging when devMode is switched on will greatly slow down the import process, and causes a high degree of memory overhead.
- Similarly, when importing, make sure to disable the debug toolbar under your user account preferences. It can cause high memory overhead and other resource related issues.
- Consider turning on the `compareContent` [configuration setting](get-started/configuration.md#configuration-options) to prevent unnecessary content overwriting.
- Consider selecting the Add Entries option for duplication handling, depending on your requirements.
- Consider turning off the Backup option for the feed. This will depend on your specific circumstances.
- Opt for a JSON feed - there is significantly less processing overhead as opposed to XML.

You may also need to adjust the `memory_limit` and `max_execution_time` values in your php.ini file if you run into memory issues.

### Unexpected Results

If you're experiencing unexpected results when running an import, try to isolate the issue by selectively mapping fields until you have a bare-minimum import.

For example, if you're mapping 20+ fields for an Entry import, but it isn't working, try to map just the Title field, and work your way through mapping additional fields until things stop working as expected.

### Logging

Feed Me create a log event for just about everything it does, notably errors, but other useful information. If you're experiencing issues or unexpected results with a Feed, consult the Logs tab first.

![The Logs tab](./screenshots/feedme-logs.png)

### Debugging

There is a special controller action to assist with debugging your feed, should you encounter issues, or errors during an import. The easiest way to get to this is clicking on the small 'bug' icon on the feeds index page (image below). The icon is placed in the Actions column on the far right, but only visible when [devMode](https://craftcms.com/docs/config-settings#devMode) is turned on.

![Feedme Overview](./screenshots/feedme-overview.png)

The output from this page will be in raw format, providing you with as much information as possible about your feed settings, field-mappings and data. If there are code exceptions, they'll appear on this page.


text:
<title>
Team Node Requirements Inspection Testing
</title>

Team Node Requirements Inspection Testing

 Week 7 Inspection by Matt Bleifer

    Component
    Inspector
    Date
    Status
    Remarks

    2.2
    MEB
    25feb15
    FIX
    Random "s" in bottom header area

    2.2 P1
    MEB
    25feb15
    DONE


text:
<?php

require_once( __DIR__ . '/BattleNetAPI/api.php' );
require_once( __DIR__ . '/BattleNetAPI/api-endpoint.php' );
require_once( __DIR__ . '/BattleNetAPI/api-endpoint-factory.php' );
require_once( __DIR__ . '/BattleNetAPI/api-exception.php' );
require_once( __DIR__ . '/BattleNetAPI/api-request.php' );


text:
DESCRIPTION
===========

This cookbook installs sudo and configures the /etc/sudoers file.

REQUIREMENTS
============

Requires that the platform has a package named sudo and the sudoers file is /etc/sudoers.

ATTRIBUTES
==========

The following attributes are set to blank arrays:

    node['authorization']['sudo']['groups']
    node['authorization']['sudo']['users']

They are passed into the sudoers template which iterates over the values to add sudo permission to the specified users and groups.

If you prefer to use passwordless sudo just set the following attribute to true:

    node['authorization']['sudo']['passwordless']

This attribute controls whether or not to include the /etc/sudoers.d
directory, it default to false. If you set it to true, the default
recipe will create the directory /etc/sudoers.d and put the
placeholder file README there

    node['authorization']['sudo']['include_sudoers_d']

USAGE
=====

You can create sudoer entries in two ways,

- populating the node['authorization']['sudo']  properties
- using the sudo lwrp

To use this cookbook, set the attributes above on the node via a role or the node object itself. In a role.rb:

    "authorization" => {
      "sudo" => {
        "groups" => ["admin", "wheel", "sysadmin"],
        "users" => ["jerry", "greg"],
        "passwordless" => true
      }
    }

In JSON (role.json or on the node object):

    "authorization": {
      "sudo": {
        "groups": [
          "admin",
          "wheel",
          "sysadmin"
        ],
        "users": [
          "jerry",
          "greg"
        ],
        "passwordless": true
      }
    }

Note that the template for the sudoers file has the group "sysadmin" with ALL:ALL permission, though the group by default does not exist.

sudo LWRP
=========

**Note** Sudo version 1.7.2 or newer is required to use the sudo LWRP
  as it relies on the "#includedir" directive introduced in version
  1.7.2. The recipe does not enforce installing the version. To use
  this LWRP, set `node['authorization']['sudo']['include_sudoers_d']`
  to `true`.

This is a fairly complex LWRP for managing sudoers fragment files in
/etc/sudoers.d. It has two modes, "natural" mode which mimics the
sudoers file interface and "template" mode where you supply a regular
erb template and hash of variables. For "template" mode, the sudo lwrp
simply ensures that resulting sudo fragment passes validation and has
the proper filesystem permissions.

In either mode, the sudo lwrp will render a sudoers fragment in
/etc/sudoers.d/

In the case that the sudoers fragment does not pass validation, this
lwrp will fail the chef-client run before the fragment can be copied
to /etc/sudoers.d. This prevents the corruption of your sudoers configuration.

Example of the default mode, "natural" mode

    sudo "tomcat" do
      user "%tomcat" # or a username
      runas "app_user" # or "app_user : tomcat"
      commands ["/etc/init.d/tomcat restart"] # array of commands, will be .join(",")
      host "ALL"
      nopasswd false # true prepends the runas_spec with NOPASSWD
    end

Example of template mode

    sudo "tomcat"
      # this template must exist in the calling cookbook
      template "restart_tomcat.erb"
      variables( :cmds => [ "/etc/init.d/tomcat restart" ] )
    end

In either case, the following file would be generated in /etc/sudoers.d/tomcat

     # this file was generated by chef
     %tomcat ALL=(app_user) /etc/init.d/tomcat restart

Description of all attributes

* :name -- name of the file to be created in /etc/sudoers.d/ ,
  defaults to the name you use for the resource. An exception will be
  thrown if th
* :user -- user to provide sudo privileges to
* :group -- same as user except "%" is prepended to the name in
case it is not already
* :commands -- an array of commands that the user/group can execute using
sudo, must use the full path for each command, otherwise the resulting
fragment will fail validation
* :nopasswd -- whether or not a password must be supplied when
invoking sudo
* :template -- a template file in the current cookbook (not the sudo
cookbook), currently must be an erb template
* :variables -- variables to use with the template

If you use the template attribute, all other attributes will be
ignored except for the variables attribute.

LICENSE AND AUTHOR
==================

Author:: Bryan W. Berry <bryan.berry@gmail.com>
Author:: Adam Jacob <adam@opscode.com>
Author:: Seth Chisamore <schisamo@opscode.com>

Copyright 2009-2011, Opscode, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:keepScreenOn="true"
    tools:context="com.sousoum.droneswear.MainActivity"
    android:background="@color/primary_light">

    <Button
        android:id="@+id/emergencyBt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/emergency"
        android:enabled="true"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_marginBottom="20dp"
        android:textColor="@color/text_on_button"
        android:background="@color/primary"
        android:layout_centerHorizontal="true"
        android:layout_above="@+id/acceleroSwitch"
        android:visibility="gone"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_above="@+id/emergencyBt">
        <TextView
            android:id="@+id/connection_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:textSize="18sp"
            android:text="@string/device_connected"
            android:textColor="@color/secondary_text"/>

        <TextView
            android:id="@+id/wifi_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:layout_marginTop="40dp"
            android:textSize="18sp"
            android:textColor="@color/secondary_text"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/piloting_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:layout_marginTop="40dp"
            android:textSize="18sp"
            android:text="@string/no_piloting"
            android:textColor="@color/secondary_text"
            android:visibility="gone"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/timeout_helper"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/acceleroSwitch"
        android:orientation="vertical"
        android:visibility="gone">

        <TextView
            android:id="@+id/timeout_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/timeout_explanation"
            android:gravity="center"
            android:textSize="19sp"
            android:textColor="@color/secondary_text"
            android:textStyle="bold"
            android:layout_marginTop="@dimen/instruction_vertical_margin" />

        <LinearLayout
            android:id="@+id/timeout_helper_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="@dimen/instruction_vertical_margin"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="@dimen/instruction_number_width_height"
                android:layout_height="@dimen/instruction_number_width_height"
                android:text="1"
                android:textColor="@color/secondary_text"
                android:layout_marginStart="@dimen/instruction_number_margin_left"
                android:gravity="center"
                android:background="@drawable/instruction_bg" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="@dimen/instruction_number_width_height"
                android:gravity="center_vertical"
                android:layout_marginStart="@dimen/instruction_margin"
                android:text="@string/timeout_instruction_1"
                android:textColor="@color/secondary_text" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/timeout_helper_2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="@dimen/instruction_vertical_margin"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="@dimen/instruction_number_width_height"
                android:layout_height="@dimen/instruction_number_width_height"
                android:text="2"
                android:textColor="@color/secondary_text"
                android:layout_marginStart="@dimen/instruction_number_margin_left"
                android:gravity="center"
                android:background="@drawable/instruction_bg" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="@dimen/instruction_number_width_height"
                android:gravity="center_vertical"
                android:layout_marginStart="@dimen/instruction_margin"
                android:text="@string/timeout_instruction_2"
                android:textColor="@color/secondary_text" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/timeout_helper_3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="@dimen/instruction_vertical_margin"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="@dimen/instruction_number_width_height"
                android:layout_height="@dimen/instruction_number_width_height"
                android:text="3"
                android:textColor="@color/secondary_text"
                android:layout_marginStart="@dimen/instruction_number_margin_left"
                android:gravity="center"
                android:background="@drawable/instruction_bg" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="@dimen/instruction_number_width_height"
                android:gravity="center_vertical"
                android:layout_marginStart="@dimen/instruction_margin"
                android:text="@string/timeout_instruction_3"
                android:textColor="@color/secondary_text" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/timeout_helper_4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="@dimen/instruction_vertical_margin"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="@dimen/instruction_number_width_height"
                android:layout_height="@dimen/instruction_number_width_height"
                android:text="4"
                android:textColor="@color/secondary_text"
                android:layout_marginStart="@dimen/instruction_number_margin_left"
                android:gravity="center"
                android:background="@drawable/instruction_bg" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="@dimen/instruction_number_width_height"
                android:gravity="center_vertical"
                android:layout_marginStart="@dimen/instruction_margin"
                android:text="@string/timeout_instruction_4"
                android:textColor="@color/secondary_text" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/timeout_helper_5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="@dimen/instruction_vertical_margin"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="@dimen/instruction_number_width_height"
                android:layout_height="@dimen/instruction_number_width_height"
                android:text="5"
                android:textColor="@color/secondary_text"
                android:layout_marginStart="@dimen/instruction_number_margin_left"
                android:gravity="center"
                android:background="@drawable/instruction_bg" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="@dimen/instruction_number_width_height"
                android:gravity="center_vertical"
                android:layout_marginStart="@dimen/instruction_margin"
                android:text="@string/timeout_instruction_5"
                android:textColor="@color/secondary_text" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/timeout_helper_6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="@dimen/instruction_vertical_margin"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="@dimen/instruction_number_width_height"
                android:layout_height="@dimen/instruction_number_width_height"
                android:text="6"
                android:textColor="@color/secondary_text"
                android:layout_marginStart="@dimen/instruction_number_margin_left"
                android:gravity="center"
                android:background="@drawable/instruction_bg" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="@dimen/instruction_number_width_height"
                android:gravity="center_vertical"
                android:layout_marginStart="@dimen/instruction_margin"
                android:text="@string/timeout_instruction_6"
                android:textColor="@color/secondary_text" />
        </LinearLayout>
    </LinearLayout>

    <Switch
        android:id="@+id/acceleroSwitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="@string/pilot_from_wear"
        android:textStyle="bold"
        android:textSize="18sp"
        android:textColor="@color/secondary_text"
        android:buttonTint="@color/primary"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>


text:
package de.dfki.cps.specific.sysml

import java.io.File

import specific.sysml.parser.{IndentScanner, SysMLLexer, SysMLParsers}

import scala.io.Source
import spray.json._
import spray.json.DefaultJsonProtocol._

import scala.collection.mutable

/**
  * This case class is an immediate Representationform of a connection between Blocks. It recieves a syntactically
  * correct connection. The function semanticaly analyses the connections and remove reverse connections
  * canEqual is overwritten in such way, that a BlockConnection is equivalent if from from and l_start are swaped with to and l_end
  *
  * @param from    Represents from in a Connection
  * @param to      Represents to in a Connection
  * @param l_start Represents the Map Label Start in a Connection
  * @param l_end   Represents the Map Label End in a Connection
  */
case class BlockConnection(from: String, to: String, l_start: String, l_end: String, mul_start: Option[Multiplicity], mul_end: Option[Multiplicity]) { // contravariant type bounds
  def isOpposite(that: BlockConnection) = that match {
    case BlockConnection(from, to, l_start, l_end, _, _) =>
      this.from == to && this.to == from && this.l_end == l_start && this.l_start == l_end
  }
}

object BlockConnection {
  /**
    * Serializer for BlockConnection to JsValue
    */
  implicit val blockConnectionJsonFormat = new JsonFormat[BlockConnection] {
    def read(js: JsValue) = ???

    def write(connection: BlockConnection): JsValue = {
      JsObject(
        "from" -> JsString(connection.from),
        "to" -> JsString(connection.to),
        "labels" -> Map(
          "start" -> (connection.l_start + connection.mul_start.fold("")(_.toString)),
          "end" -> (connection.l_end + connection.mul_end.fold("")(_.toString))
        ).toJson
      )
    }
  }

}

object DiagramParser extends App {
  var useOCL = false
  val usedConnections: Map[String, String] = Map()

  /**
    * Converts a NamedElement from the SysML parser to json
    * Uses the following Syntax Modell:
    *
    * Positional = Filepositinal | TypeAnnotation | TimeEvent
    * FilePostional = Element
    * Element =  Comment | Mapping | Satifsfy | Trace | Project | BlockCompartment | TransistionTarget | Trigger |
    * BlockCompatement = UnsupportedCompartment | PropertiesCompartment |  ValuesCompartment | OperationsCompartment
    * BehaviorCompartment | ConstraintsCompartment | ReferencesCompartment | PortsCompartment |
    * DiagramKind = ActivityDiagram | BlockDefinitionDiagram | InternalBlockDiagram | InternalBlockDiagram | ParametricDiagram | RequirementDiagram |
    * SequenceDiagram | StateMachineDiagram |  UseCaseDiagram
    * NameSpace = Diagram | Package
    * NamedElement = Realization | BlockMember | State | Requirement | State
    * BlockMember = Property | Reference | Operation | Parameter | Port | StateMachine
    * Classifier = Block
    * ConstraintType = Inv | Pre | Post | Body | Init | Derive | Query
    * Blockmember = UnprocessedConstraint
    * FlowDirection = In | Out | InOut
    * State = PseudoState
    * PseudoState = Choice
    * TransistionTarget = InlineTargetState | UnresolvedTargetStateName
    * ShortConstraint = Subsets
    *
    * @param element Takes a Diagram from the Parser
    * @return the json representation
    */

  def convert(element: NamedElement): JsValue = element match {
    case Diagram(DiagramKind.BlockDefinitionDiagram, m, n, name, members) =>
      Map(
        "title" -> Array("Block Definition Diagram", s"[$m]", n.mkString("::"), name).toJson,
        "blocks" -> members.collect {
          case Block(name, compartments, comments) =>
            name -> Map(
              "stereotype" -> "block".toJson,
              "compartments" -> compartments.collect { // Hier die Ausnahmen, welche separat geparsed werdenn
                case comp if (!((comp.compartmentName == "references") || (comp.compartmentName == "operations") || (comp.compartmentName == "constraints")))
                => comp.compartmentName -> comp.content.map(convert).toJson
                case comp if (comp.compartmentName == "constraints" && useOCL) => comp.compartmentName -> comp.content.map(_.toString).toJson
                case comp if (comp.compartmentName == "operations") => comp.compartmentName -> comp.content.map(_.toString).toJson
              }.toMap.toJson
            ).toJson
        }.toMap.toJson,
        "connectors" -> {
          val refs = members.collect { case b: Block => b }.flatMap { from =>
            from.compartments.collect { case r: ReferencesCompartment => r }.flatMap(r => r.references.map((from, _)))
          }
          filterConnections(parseNodes(refs, members)).toJson
        }
      ).toJson
    case default => default.toString.toJson
  }

  /**
    * (refs: Seq[Reference], members: Seq[NamedElement], from: Block) -> Seq[BlockConnection] -> Option[Set[BlockConnection]
    *
    * Parse the Parameters to a Sequence of Block Connections. Syntax Correct, Semantic Not
    *
    * @param refs
    * @param members
    * @return
    */
  def parseNodes(refs: Seq[(Block,Reference)], members: Seq[NamedElement]): Seq[BlockConnection] =
    refs.map{ case (from,to) => {
      val c = {
        to.typeAnnotation.name.parts.mkString("::")
      }
      val opposite = to.oppositeName.flatMap(n => members.collect { case b: Block if b.rawName == c => b }
        .flatMap(_.members.collect { case r: Reference if r.name == n => r }).headOption) // her dopllet?

      BlockConnection(from.rawName, c, to.oppositeName.getOrElse(from.rawName.toLowerCase), to.name, opposite.flatMap(_.typeAnnotation.multiplicity), to.typeAnnotation.multiplicity)
  }}

  /**
    * Takes an Sequence of BlockConnections with correct Syntax and return it Semantically correct
    * The Sequence of connections is a  Bigraph, which should be returned as a Graph.
    * In case of an Error None is returned.
    *
    * Fixes the Semantic
    *
    * @param connection Seq[BlockConnection]
    * @return Option[Set[BlockConnection]]
    **/
  def filterConnections(connection: Seq[BlockConnection]): Seq[BlockConnection] = {
    val buf = mutable.Buffer.empty[BlockConnection]
    for (c <- connection) {
      buf.indexWhere(c.isOpposite) match {
        case -1 => buf.append(c)
        case n =>
          val o = buf.remove(n)
          val r = BlockConnection(c.from, c.to, c.l_start, c.l_end, c.mul_start orElse o.mul_end, c.mul_end orElse o.mul_start)
          buf.append(r)
      }
    }
    connection.toSet
    buf.toSeq
  }

  /**
    * Take a .sysml file and return its json representation
    * Use SysMLParsers, if successful convert to json
    *
    * @param source Specify where a .sysml file is saved
    * @return returns the prettyprinted json representation
    */
  def fileToJsonString(source: File) = {
    // Read from File and run SysML Lexer
    val textSource = Source.fromFile(source)
    val tokens = IndentScanner(new SysMLLexer.Scanner(textSource.mkString))

    SysMLParsers.phrase(SysMLParsers.diagram)(tokens) match {
      case SysMLParsers.Success(b: Diagram, _) =>
        convert(b).prettyPrint // IR
      case err@SysMLParsers.NoSuccess(msg, i) =>
        s"parse error [${source.getName}:${i.pos.line}:${i.pos.column}]: $msg" +
          i.pos.longString
    }
  }

  useOCL = true
  println("diagram = " + fileToJsonString(new File("example.sysml")))
}


text:
package probes

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"

	"github.com/lebauce/dockerclient"
	"github.com/vishvananda/netns"

	"github.com/redhat-cip/skydive/config"
	"github.com/redhat-cip/skydive/logging"
	"github.com/redhat-cip/skydive/topology/graph"
)

const (
	StoppedState  = iota
	RunningState  = iota
	StoppingState = iota
)

type ContainerInfo struct {
	Pid  int
	Node *graph.Node
}

type DockerProbe struct {
	sync.RWMutex
	NetNSProbe
	url          string
	client       *dockerclient.DockerClient
	state        int64
	connected    atomic.Value
	quit         chan bool
	wg           sync.WaitGroup
	hostNs       netns.NsHandle
	containerMap map[string]ContainerInfo
}

func (probe *DockerProbe) containerNamespace(pid int) string {
	return fmt.Sprintf("/proc/%d/ns/net", pid)
}

func (probe *DockerProbe) registerContainer(id string) {
	probe.Lock()
	defer probe.Unlock()

	if _, ok := probe.containerMap[id]; ok {
		return
	}
	info, err := probe.client.InspectContainer(id)
	if err != nil {
		logging.GetLogger().Errorf("Failed to inspect Docker container %s: %s", id, err.Error())
		return
	}

	nsHandle, err := netns.GetFromPid(info.State.Pid)
	if err != nil {
		return
	}

	namespace := probe.containerNamespace(info.State.Pid)
	logging.GetLogger().Debugf("Register docker container %s and PID %d", info.Id, info.State.Pid)

	var n *graph.Node
	if probe.hostNs.Equal(nsHandle) {
		// The container is in net=host mode
		n = probe.Root
	} else {
		n = probe.Register(namespace, graph.Metadata{"Name": info.Name[1:], "Manager": "docker"})

	}

	probe.Graph.Lock()
	metadata := graph.Metadata{
		"Type":                 "container",
		"Name":                 info.Name[1:],
		"Docker.ContainerID":   info.Id,
		"Docker.ContainerName": info.Name,
		"Docker.ContainerPID":  info.State.Pid,
	}
	containerNode := probe.Graph.NewNode(graph.GenID(), metadata)
	probe.Graph.Link(n, containerNode, graph.Metadata{"RelationType": "membership"})
	probe.Graph.Unlock()

	probe.containerMap[info.Id] = ContainerInfo{
		Pid:  info.State.Pid,
		Node: containerNode,
	}
}

func (probe *DockerProbe) unregisterContainer(id string) {
	probe.Lock()
	defer probe.Unlock()

	infos, ok := probe.containerMap[id]
	if !ok {
		return
	}
	namespace := probe.containerNamespace(infos.Pid)
	logging.GetLogger().Debugf("Stop listening for namespace %s with PID %d", namespace, infos.Pid)
	probe.Unregister(namespace)

	probe.Graph.Lock()
	probe.Graph.DelNode(infos.Node)
	probe.Graph.Unlock()

	delete(probe.containerMap, id)
}

func (probe *DockerProbe) handleDockerEvent(event *dockerclient.Event) {
	if event.Status == "start" {
		probe.registerContainer(event.ID)
	} else if event.Status == "die" {
		probe.unregisterContainer(event.ID)
	}
}

func (probe *DockerProbe) connect() error {
	var err error

	if probe.hostNs, err = netns.Get(); err != nil {
		return err
	}

	logging.GetLogger().Debugf("Connecting to Docker daemon: %s", probe.url)
	probe.client, err = dockerclient.NewDockerClient(probe.url, nil)
	if err != nil {
		logging.GetLogger().Errorf("Failed to connect to Docker daemon: %s", err.Error())
		return err
	}

	eventsOptions := &dockerclient.MonitorEventsOptions{
		Filters: &dockerclient.MonitorEventsFilters{
			Events: []string{"start", "die"},
		},
	}

	eventErrChan, err := probe.client.MonitorEvents(eventsOptions, nil)
	if err != nil {
		logging.GetLogger().Errorf("Unable to monitor Docker events: %s", err.Error())
		return err
	}

	probe.wg.Add(2)
	probe.quit = make(chan bool)

	probe.connected.Store(true)
	defer probe.connected.Store(false)

	go func() {
		defer probe.wg.Done()

		containers, err := probe.client.ListContainers(false, false, "")
		if err != nil {
			logging.GetLogger().Errorf("Failed to list containers: %s", err.Error())
			return
		}

		for _, c := range containers {
			if atomic.LoadInt64(&probe.state) != RunningState {
				break
			}
			probe.registerContainer(c.Id)
		}
	}()

	defer probe.wg.Done()

	for {
		select {
		case <-probe.quit:
			return nil
		case e := <-eventErrChan:
			if e.Error != nil {
				logging.GetLogger().Errorf("Got error while waiting for Docker event: %s", e.Error.Error())
				return e.Error
			}
			probe.handleDockerEvent(&e.Event)
		}
	}
}

func (probe *DockerProbe) Start() {
	if !atomic.CompareAndSwapInt64(&probe.state, StoppedState, RunningState) {
		return
	}

	go func() {
		for {
			state := atomic.LoadInt64(&probe.state)
			if state == StoppingState || state == StoppedState {
				break
			}

			if probe.connect() != nil {
				time.Sleep(1 * time.Second)
			}
		}
	}()
}

func (probe *DockerProbe) Stop() {
	if !atomic.CompareAndSwapInt64(&probe.state, RunningState, StoppingState) {
		return
	}

	if probe.connected.Load() == true {
		close(probe.quit)
		probe.wg.Wait()
	}

	atomic.StoreInt64(&probe.state, StoppedState)
}

func NewDockerProbe(g *graph.Graph, n *graph.Node, dockerURL string) (probe *DockerProbe) {
	probe = &DockerProbe{
		NetNSProbe:   *NewNetNSProbe(g, n),
		url:          dockerURL,
		containerMap: make(map[string]ContainerInfo),
		state:        StoppedState,
	}
	return
}

func NewDockerProbeFromConfig(g *graph.Graph, n *graph.Node) *DockerProbe {
	dockerURL := config.GetConfig().GetString("docker.url")
	return NewDockerProbe(g, n, dockerURL)
}


text:
package ixa.kaflib;

import ixa.kaflib.KAFDocument.AnnotationType;
import ixa.kaflib.KAFDocument.Utils;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

/** Dependencies represent dependency relations among terms. */
public class Dep extends Annotation implements SentenceLevelAnnotation {

    /** Source term of the dependency (required) */
    private Term from;

    /** Target term of the dependency (required) */
    private Term to;

    /** Relational function of the dependency (required) */
    private String rfunc;

    /** Declension case (optional) */
    private String depcase;

    Dep(Term from, Term to, String rfunc) {
	this.from = from;
	this.to = to;
	this.rfunc = rfunc;
    }

    Dep(Dep dep, HashMap<String, Term> terms) {
	this.from = terms.get(dep.from.getId());
	if (this.from == null) {
	    throw new IllegalStateException("Couldn't find the term when loading dep (" + dep.getFrom().getId()+", "+dep.getTo().getId()+")");
	}
	this.to = terms.get(dep.to.getId());
	if (this.to == null) {
	    throw new IllegalStateException("Couldn't find the term when loading dep (" + dep.getFrom().getId()+", "+dep.getTo().getId()+")");
	}
	this.rfunc = dep.rfunc;
	this.depcase = dep.depcase;
    }

    public Term getFrom() {
	return this.from;
    }

    public void setFrom(Term term) {
	this.from = term;
    }

    public Term getTo() {
	return to;
    }

    public void setTo(Term term) {
	this.to = term;
    }

    public String getRfunc() {
	return rfunc;
    }

     public void setRfunc(String rfunc) {
	 this.rfunc = rfunc;
    }

    public boolean hasCase() {
	return depcase != null;
    }

    public String getCase() {
	return depcase;
    }

    public void setCase(String depcase) {
	this.depcase = depcase;
    }

    public String getStr() {
	return rfunc + "(" + this.getFrom().getStr() + ", " + this.getTo().getStr() + ")";
    }

    Map<AnnotationType, List<Annotation>> getReferencedAnnotations() {
	Map<AnnotationType, List<Annotation>> referenced = new HashMap<AnnotationType, List<Annotation>>();
	List<Annotation> terms = new ArrayList<Annotation>();
	terms.add(this.getFrom());
	terms.add(this.getTo());
	referenced.put(AnnotationType.TERM, terms);
	return referenced;
    }

    /*
    @Override
    public boolean equals(Object o) {
	if (this == o) return true;
	if (!(o instanceof Dep)) return false;
	Dep ann = (Dep) o;
	return Utils.areEquals(this.from, ann.from) &&
		Utils.areEquals(this.to, ann.to) &&
		Utils.areEquals(this.rfunc, ann.rfunc) &&
		Utils.areEquals(this.depcase, ann.depcase);
    }
    */

    @Override
    public Integer getSent() {
	return this.from.getSent();
    }

    @Override
    public Integer getPara() {
	return this.from.getPara();
    }

}


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from citeproc.py2compat import *

import os

from warnings import warn

from lxml import etree

from . import SCHEMA_PATH, LOCALES_PATH, STYLES_PATH
from .model import CitationStylesElement
from .formatter import html

class CitationStylesXML(object):
    def __init__(self, f, validate=True):
        lookup = etree.ElementNamespaceClassLookup()
        namespace = lookup.get_namespace('http://purl.org/net/xbiblio/csl')
        namespace[None] = CitationStylesElement
        namespace.update(dict([(cls.__name__.replace('_', '-').lower(), cls)
                               for cls in CitationStylesElement.__subclasses__()]))

        self.parser = etree.XMLParser(remove_comments=True, encoding='UTF-8',
                                      no_network=True)
        self.parser.set_element_class_lookup(lookup)
        self.xml = etree.parse(f, self.parser)#, base_url=".")
        if validate:
            self.schema = etree.RelaxNG(etree.parse(SCHEMA_PATH))
            if not self.schema.validate(self.xml):
                err = self.schema.error_log
                #raise Exception("XML file didn't pass schema validation:\n%s" % err)
                warn("XML file didn't pass schema validation:\n%s" % err)
                # TODO: proper error reporting
        self.root = self.xml.getroot()

class CitationStylesLocale(CitationStylesXML):
    def __init__(self, locale, validate=True):
        locale_path = os.path.join(LOCALES_PATH, 'locales-{}.xml'.format(locale))
        try:
            super(CitationStylesLocale, self).__init__(locale_path,
                                                       validate=validate)
        except IOError:
            raise ValueError("'{}' is not a known locale".format(locale))

class CitationStylesStyle(CitationStylesXML):
    def __init__(self, style, locale=None, validate=True):
        try:
            if not os.path.exists(style):
                style = os.path.join(STYLES_PATH, '{}.csl'.format(style))
        except TypeError:
            pass
        try:
            super(CitationStylesStyle, self).__init__(
                style, validate=validate)
        except IOError:
            raise ValueError("'{}' is not a known style".format(style))
        if locale is None:
            locale = self.root.get('default-locale', 'en-US')
        self.root.set_locale_list(locale, validate=validate)

    def has_bibliography(self):
        return self.root.bibliography is not None

    def render_citation(self, citation, cites, callback=None):
        return self.root.citation.render(citation, cites, callback)

    def sort_bibliography(self, citation_items):
        return self.root.bibliography.sort(citation_items)

    def render_bibliography(self, citation_items):
        return self.root.bibliography.render(citation_items)

class CitationStylesBibliography(object):
    def __init__(self, style, source, formatter=html):
        self.style = style
        self.source = source
        self.formatter = self.style.root.formatter = formatter
        self.keys = []
        self.items = []
        self._cites = []

    def register(self, citation, callback=None):
        citation.bibliography = self
        for item in citation.cites:
            if item.key in self.source:
                if item.key not in self.keys:
                    self.keys.append(item.key)
                    self.items.append(item)
            elif callback is not None:
                callback(item)

    def sort(self):
        self.items = self.style.sort_bibliography(self.items)
        self.keys = [item.key for item in self.items]

    def cite(self, citation, callback):
        return self.style.render_citation(citation, self._cites, callback)

    def bibliography(self):
        return self.style.render_bibliography(self.items)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Stevens, Bulletin of the Bernice P. Bishop Museum, Honolulu, Hawaii 19: 59 (1925)

#### Original name
Phaeosaccardinula morindae J.M. Mend.

### Remarks
null


text:
package exec

import (
	"context"
	"fmt"
	"time"

	"github.com/apache/beam/sdks/go/pkg/beam/core/graph/mtime"
	"github.com/apache/beam/sdks/go/pkg/beam/core/graph/window"
	"github.com/apache/beam/sdks/go/pkg/beam/core/typex"
)

// WindowInto places each element in one or more windows.
type WindowInto struct {
	UID UnitID
	Fn  *window.Fn
	Out Node
}

func (w *WindowInto) ID() UnitID {
	return w.UID
}

func (w *WindowInto) Up(ctx context.Context) error {
	return nil
}

func (w *WindowInto) StartBundle(ctx context.Context, id string, data DataManager) error {
	return w.Out.StartBundle(ctx, id, data)
}

func (w *WindowInto) ProcessElement(ctx context.Context, elm FullValue, values ...ReStream) error {
	windowed := FullValue{
		Windows:   assignWindows(w.Fn, elm.Timestamp),
		Timestamp: elm.Timestamp,
		Elm:       elm.Elm,
		Elm2:      elm.Elm2,
	}
	return w.Out.ProcessElement(ctx, windowed, values...)
}

func assignWindows(wfn *window.Fn, ts typex.EventTime) []typex.Window {
	switch wfn.Kind {
	case window.GlobalWindows:
		return window.SingleGlobalWindow

	case window.FixedWindows:
		start := ts - (ts.Add(wfn.Size) % mtime.FromDuration(wfn.Size))
		end := mtime.Min(start.Add(wfn.Size), mtime.EndOfGlobalWindowTime.Add(time.Millisecond))
		return []typex.Window{window.IntervalWindow{Start: start, End: end}}

	case window.SlidingWindows:
		var ret []typex.Window

		period := mtime.FromDuration(wfn.Period)
		lastStart := ts - (ts.Add(wfn.Size) % period)
		for start := lastStart; start > ts.Subtract(wfn.Size); start -= period {
			ret = append(ret, window.IntervalWindow{Start: start, End: start.Add(wfn.Size)})
		}
		return ret

	default:
		panic(fmt.Sprintf("Unexpected window fn: %v", wfn))
	}
}

func (w *WindowInto) FinishBundle(ctx context.Context) error {
	return w.Out.FinishBundle(ctx)
}

func (w *WindowInto) Down(ctx context.Context) error {
	return nil
}

func (w *WindowInto) String() string {
	return fmt.Sprintf("WindowInto[%v]. Out:%v", w.Fn, w.Out.ID())
}


text:
(function ($) {
  'use strict';

  if (patternfly !== undefined) {
    $.pfPaletteColors = patternfly.pfPaletteColors;
  }
}(jQuery));


text:
@extends('layouts.master')
@include('home.slider')
@section('title')
    Home
@stop

@section('meta_description')
    This is a description
@stop

@section('content')
	@yield('slider')

Student Management Administration

        Welcome to SMA - Student Management Administration.

        Please use "admin" as username and "password" as password for demo login.

@stop

@section('scripts')

@stop


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cwainner.chris.recipecentral.ui.RecipeListFragment">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/recipesHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Recipes"
            android:textAlignment="center"
            android:textSize="20sp"
            android:textColor="@color/colorHeader"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"/>

    </LinearLayout>

</FrameLayout>


text:
package com.ace.budgetexpensetracker.utility;

import com.ace.budgetexpensetracker.database.ACEBudgetExpenseTrackerDBHelper.Account;
import com.ace.budgetexpensetracker.views.AccountLinearLayout;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.CursorAdapter;

public class AccountListAdapter extends CursorAdapter{
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)
	OnClickListener onclick;
	OnLongClickListener onLongClick;
	boolean mDrawEditButton;

    public AccountListAdapter(Context context, Cursor c, OnClickListener onclick, OnLongClickListener onLongClick) {
        super(context, c, CursorAdapter.NO_SELECTION);
        this.onclick = onclick;
        this.onLongClick = onLongClick;
        mDrawEditButton = false;
    }

    public void bindView(View view, Context context, Cursor cursor) {
    	AccountLinearLayout layout = (AccountLinearLayout) view;
    	layout.setAccountID(cursor.getLong((cursor.getColumnIndexOrThrow(Account._ID))));
    	layout.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(Account.COLUMN_NAME_TITLE)));
    	layout.setAccountBalance(cursor.getFloat(cursor.getColumnIndexOrThrow(Account.COLUMN_NAME_BALANCE)));
    	layout.setOnClickListener(onclick);
    	layout.setOnLongClickListener(onLongClick);
    	layout.setDrawEditIcon(mDrawEditButton);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
    	AccountLinearLayout view = new AccountLinearLayout(context);
        return view;
    }

    public void setDrawEditButton(boolean drawEditButton){
    	mDrawEditButton = drawEditButton;
    }

}