text:
package org.kaazing.gateway.client.impl.wseb;

import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.lib.action.CustomAction;
import org.junit.Assert;
import org.junit.Test;
import org.kaazing.gateway.client.impl.Expectations;
import org.kaazing.gateway.client.impl.http.HttpRequest;
import org.kaazing.gateway.client.impl.http.HttpRequestHandler;
import org.kaazing.gateway.client.impl.http.HttpRequestListener;
import org.kaazing.gateway.client.impl.http.HttpResponse;
import org.kaazing.gateway.client.impl.util.WSURI;
import org.kaazing.gateway.client.impl.ws.WebSocketCompositeChannel;
import org.kaazing.gateway.client.util.HttpURI;
import org.kaazing.gateway.client.util.WrappedByteBuffer;
import org.kaazing.net.ws.WebSocket;
import org.kaazing.net.ws.WebSocketFactory;
import org.kaazing.net.ws.impl.WebSocketImpl;

public class CreateHandlerTest {

    /*
     * pass through function call
     * but event should not pass through
     */
    @Test
    public void testProcessOpen() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);

        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire connectionOpen") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest channel = (HttpRequest)invocation.getParameter(0);
                        listener.requestOpened(channel);
                        return null;
                    }
                });
                //no event should pass through
                never(listener).createCompleted(with(any(CreateChannel.class)), with(any(HttpURI.class)), with(any(HttpURI.class)), with(any(String.class)));
            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();

        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

    @Test
    public void testProcessOpenWithProtocol() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);
        final String bumpProtocol = "x-kaazing-bump";
        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire connectionOpen") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest request = (HttpRequest)invocation.getParameter(0);
                        String protocol = request.getHeaders().get("X-WebSocket-Protocol");
                        Assert.assertNotNull("X-WebSocket-Protocol header should not be null", protocol);
                        Assert.assertEquals("X-WebSocket-Protocol header value should be x-kaazing-bump", protocol, bumpProtocol);
                        listener.requestOpened(request);
                        return null;
                    }
                });
                //no event should pass through
                never(listener).createCompleted(with(any(CreateChannel.class)), with(any(HttpURI.class)), with(any(HttpURI.class)), with(any(String.class)));
            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();
        channel.setProtocols(new String[]{bumpProtocol});

        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

    @Test
    public void testProcessOpenWithMultipleProtocols() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);
        String bumpProtocol = "x-kaazing-bump";
        String handshakeProtocol = "x-kaazing-handshake";
        final String[] protocols = new String[]{handshakeProtocol, bumpProtocol};
        final String expectedProtocolHeaderValue = handshakeProtocol + "," + bumpProtocol;
        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire connectionOpen") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest request = (HttpRequest)invocation.getParameter(0);
                        String protocols = request.getHeaders().get("X-WebSocket-Protocol");
                        Assert.assertNotNull("X-WebSocket-Protocol header should not be null", protocols);
                        Assert.assertEquals("X-WebSocket-Protocol header value should be 'x-kaazing-handshake,x-kaazing-bump'", protocols, expectedProtocolHeaderValue);
                        listener.requestOpened(request);
                        return null;
                    }
                });
                //no event should pass through
                never(listener).createCompleted(with(any(CreateChannel.class)), with(any(HttpURI.class)), with(any(HttpURI.class)), with(any(String.class)));
            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();
        channel.setProtocols(protocols);

        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

    /*
     * pass through function call
     * but event should not pass through
     */
    @Test
    public void testRequestReady() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);

        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire requestReady") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest channel = (HttpRequest)invocation.getParameter(0);
                        listener.requestReady(channel);
                        return null;
                    }
                });
                //no event should pass through
                never(listener).createCompleted(with(any(CreateChannel.class)), with(any(HttpURI.class)), with(any(HttpURI.class)), with(any(String.class)));
            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();

        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

        /*
     * pass through function call
     * but event should not pass through
     */
    @Test
    public void testRequestProgressed() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);

        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire requestProgressed") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest channel = (HttpRequest)invocation.getParameter(0);
                        listener.requestProgressed(channel, null);
                        return null;
                    }
                });
                //no event should pass through
                never(listener).createCompleted(with(any(CreateChannel.class)), with(any(HttpURI.class)), with(any(HttpURI.class)), with(any(String.class)));
            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();

        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

    /*
     * pass through function call
     * but event should not pass through
     */
    @Test
    public void testRequestAborted() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);

        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire requestAborted") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest channel = (HttpRequest)invocation.getParameter(0);
                        listener.requestAborted(channel);
                        return null;
                    }
                });
                //no event should pass through
                never(listener).createCompleted(with(any(CreateChannel.class)), with(any(HttpURI.class)), with(any(HttpURI.class)), with(any(String.class)));
            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();

        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

    /*
     * pass through function call
     * but event should not pass through
     */
    @Test
    public void testRequestClosed() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);

        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire requestClosed") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest channel = (HttpRequest)invocation.getParameter(0);
                        listener.requestClosed(channel);
                        return null;
                    }
                });
                //no event should pass through
                never(listener).createCompleted(with(any(CreateChannel.class)), with(any(HttpURI.class)), with(any(HttpURI.class)), with(any(String.class)));
            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();

        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

    /*
     * pass through function call
     * fire createCompleted
     */
    @Test
    public void testRequestLoaded() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);

        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire requestLoaded") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest channel = (HttpRequest)invocation.getParameter(0);
                        HttpResponse response = new HttpResponse();

                        String body = "http://localhost:8001/echo/;e/ub?.kv=10.05&.kz=uLsDpoYK6UyfchrIlU4p0paUdS2BssL9\n" +
"http://localhost:8001/echo/;e/db?.kv=10.05&.kz=uLsDpoYK6UyfchrIlU4p0paUdS2BssL9";
                        response.setBody(new WrappedByteBuffer(body.getBytes()));
                        response.setHeader("X-WebSocket-Extensions", "x-kaazing-http-revalidate; 56414C49");
                        listener.requestLoaded(channel, response);
                        return null;
                    }
                });
                //
                oneOf(listener).createCompleted(with(aNonNull(CreateChannel.class)), with(aNonNull(HttpURI.class)), with(aNonNull(HttpURI.class)), with(aNull(String.class)));

            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();
        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

    /*
     * pass through function call
     * fire createFailed event
     */
    @Test
    public void testErrorOccured() throws Exception {

        Mockery context = new Mockery();
        final HttpRequestHandler nextHandler = context.mock(HttpRequestHandler.class);
        final CreateHandlerListener listener = context.mock(CreateHandlerListener.class);

        context.checking(new Expectations() {

            {
                oneOf(nextHandler).setListener(with(aNonNull(HttpRequestListener.class)));
                will(saveParameter("listener", 0));
                oneOf(nextHandler).processOpen(with(aNonNull(HttpRequest.class)));
                will(new CustomAction("will fire errorOccurred") {

                    @Override
                    public Object invoke(Invocation invocation) {
                        HttpRequestListener listener = (HttpRequestListener)lookup("listener");
                        HttpRequest channel = (HttpRequest)invocation.getParameter(0);
                        listener.errorOccurred(channel, new IllegalArgumentException());
                        return null;
                    }
                });
                //fire createFailed
                oneOf(listener).createFailed(with(aNonNull(CreateChannel.class)), with(aNonNull(Exception.class)));
            }
        });

        HttpURI uri = new HttpURI("http://localhost:8001/echo");

        CreateChannel channel = getCreateChannel();

        CreateHandler handler = CreateHandlerImpl.FACTORY.createCreateHandler();
        handler.setNextHandler(nextHandler);
        handler.setListener(listener);

        handler.processOpen(channel, uri);
        context.assertIsSatisfied();
    }

    // Returns a CreateChannel whose hierarchy is all setup properly all the
    // up to the WebSocket.
    private CreateChannel getCreateChannel() throws Exception {
        CreateChannel channel = new CreateChannel();
        WSURI wsUri = new WSURI("ws://localhost:8001/echo");
        WebSocketFactory wsFactory = WebSocketFactory.createWebSocketFactory();
        WebSocket ws = wsFactory.createWebSocket(wsUri.getURI(), (String[])null);
        WebSocketCompositeChannel cc = ((WebSocketImpl)ws).getCompositeChannel();
        WebSocketEmulatedChannel ec = new WebSocketEmulatedChannel(wsUri);

        ec.setParent(cc);
        channel.setParent(ec);

        return channel;
    }

}


text:
package com.onboard.service.collaboration.impl.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import com.onboard.domain.model.Activity;
import com.onboard.domain.model.Story;
import com.onboard.service.activity.ActivityActionType;
import com.onboard.service.collaboration.activity.StoryActivityGenerator;
import com.onboard.service.web.SessionService;
import com.onboard.test.moduleutils.ModuleHelper;

@RunWith(MockitoJUnitRunner.class)
public class StoryActivityGeneratorTest {

    private final static Map<Integer, String> PR_MAP = new HashMap<Integer, String>() {
        private static final long serialVersionUID = 1L;
        {
            put(1, "非常紧急");
            put(2, "紧急");
            put(3, "重要");
            put(4, "普通");
            put(5, "可忽略");
        }
    };

    @InjectMocks
    StoryActivityGenerator testedStoryActivityGenerator;

    @Mock
    SessionService mockSessionService;

    @Before
    public void setupStoryActivityGeneratorTest() {
        Mockito.doReturn(ModuleHelper.getASampleUser()).when(mockSessionService).getCurrentUser();
    }

    public void runAsserts(Activity activity, Story story, String actionType, String subject) {
        assertEquals(story.getProjectId(), activity.getProjectId());
        assertEquals(story.getCompanyId(), activity.getCompanyId());
        assertEquals(story.getDescription(), activity.getTarget());
        assertEquals(story.getId(), activity.getAttachId());
        assertEquals(story.getType(), activity.getAttachType());
        assertEquals(subject, activity.getSubject());
        assertEquals(actionType, activity.getAction());
        assertEquals(ModuleHelper.userId, (int) activity.getCreatorId());
        assertEquals(ModuleHelper.userName, activity.getCreatorName());
        assertTrue(ModuleHelper.compareCreatedItemDateWithToday(activity.getCreated()));
    }

    /**
     * @author Steven
     * This test also includes tests for private method "generateActivityByActionType" and "enrichActivity"
     */
    @Test
    public void testGenerateCreateActivity() {
        Story story = ModuleHelper.getASampleStory();
        Activity activity = testedStoryActivityGenerator.generateCreateActivity(story);

        assertEquals(story.getProjectId(), activity.getProjectId());
        assertEquals(story.getCompanyId(), activity.getCompanyId());
        assertEquals(story.getDescription(), activity.getTarget());
        assertEquals(story.getDescription(), activity.getContent());
        assertEquals(story.getId(), activity.getAttachId());
        assertEquals(story.getType(), activity.getAttachType());
        assertEquals(StoryActivityGenerator.CREATE_STORY_SUBJECT, activity.getSubject());
        assertEquals(ActivityActionType.CREATE, activity.getAction());
        assertEquals(ModuleHelper.userId, (int) activity.getCreatorId());
        assertEquals(ModuleHelper.userName, activity.getCreatorName());
        assertTrue(ModuleHelper.compareCreatedItemDateWithToday(activity.getCreated()));
    }

    /**
     * @author Steven
     * Test for updating priority
     */
    @Test
    public void testGenerateUpdateActivity_Test1() {
        Story origin = ModuleHelper.getASampleStory();
        Story update = ModuleHelper.getASampleStory();
        origin.setPriority(0);
        update.setPriority(1);

        Activity activity = testedStoryActivityGenerator.generateUpdateActivity(origin, update);

        runAsserts(activity, update, ActivityActionType.UPDATE, StoryActivityGenerator.UPDATE_STORY_SUBJECT);
        assertEquals(String.format(StoryActivityGenerator.UPDATE_STORY_PRIORITY_SUBJECT, PR_MAP.get(origin.getPriority()),
                PR_MAP.get(update.getPriority())), activity.getContent());
    }

    /**
     * @author Steven
     * Test for updating description
     */
    @Test
    public void testGenerateUpdateActivity_Test2() {
        Story origin = ModuleHelper.getASampleStory();
        Story update = ModuleHelper.getASampleStory();
        origin.setDescription("Description1");
        update.setDescription("Description2");

        Activity activity = testedStoryActivityGenerator.generateUpdateActivity(origin, update);

        runAsserts(activity, update, ActivityActionType.UPDATE, StoryActivityGenerator.UPDATE_STORY_SUBJECT);
        assertEquals(String.format(StoryActivityGenerator.UPDATE_STORY_TITLE_SUBJECT, origin.getDescription(),
                update.getDescription()), activity.getContent());
    }

    /**
     * @author Steven
     * Test for updating acceptanceLevel
     */
    @Test
    public void testGenerateUpdateActivity_Test3() {
        Story origin = ModuleHelper.getASampleStory();
        Story update = ModuleHelper.getASampleStory();
        origin.setAcceptanceLevel("AcceptanceLevel1");
        update.setAcceptanceLevel("AcceptanceLevel2");

        Activity activity = testedStoryActivityGenerator.generateUpdateActivity(origin, update);

        runAsserts(activity, update, ActivityActionType.UPDATE, StoryActivityGenerator.UPDATE_STORY_SUBJECT);
        assertEquals(String.format(StoryActivityGenerator.UPDATE_STORY_ACCEPTANCE_LEVEL_SUBJECT, origin.getAcceptanceLevel(),
                update.getAcceptanceLevel()), activity.getContent());
    }

    /**
     * @author Steven
     * Test for completing story
     */
    @Test
    public void testGenerateUpdateActivity_Test4() {
        Story origin = ModuleHelper.getASampleStory();
        Story update = ModuleHelper.getASampleStory();
        origin.setCompleted(false);
        update.setCompleted(true);

        Activity activity = testedStoryActivityGenerator.generateUpdateActivity(origin, update);

        runAsserts(activity, update, ActivityActionType.UPDATE, StoryActivityGenerator.UPDATE_STORY_COMPLETE_SUBJECT);
    }

    /**
     * @author Steven
     * Test for reopenning story
     */
    @Test
    public void testGenerateUpdateActivity_Test5() {
        Story origin = ModuleHelper.getASampleStory();
        Story update = ModuleHelper.getASampleStory();
        origin.setCompleted(true);
        update.setCompleted(false);

        Activity activity = testedStoryActivityGenerator.generateUpdateActivity(origin, update);

        runAsserts(activity, update, ActivityActionType.UPDATE, StoryActivityGenerator.UPDATE_STORY_REOPEN_SUBJECT);
    }

    /**
     * @author Steven
     * Test for deleting story
     */
    @Test
    public void testGenerateUpdateActivity_Test6() {
        Story origin = ModuleHelper.getASampleStory();
        Story update = ModuleHelper.getASampleStory();
        origin.setDeleted(false);
        update.setDeleted(true);

        Activity activity = testedStoryActivityGenerator.generateUpdateActivity(origin, update);

        runAsserts(activity, update, ActivityActionType.UPDATE, StoryActivityGenerator.UPDATE_STORY_SUBJECT);
        assertEquals(StoryActivityGenerator.DELETE_STORY_SUBJECT, activity.getContent());
    }

    /**
     * @author Steven
     * Test for doing nothing
     */
    @Test
    public void testGenerateUpdateActivity_Test7() {
        Story origin = ModuleHelper.getASampleStory();
        Story update = ModuleHelper.getASampleStory();

        Activity activity = testedStoryActivityGenerator.generateUpdateActivity(origin, update);

        runAsserts(activity, update, ActivityActionType.UPDATE, StoryActivityGenerator.UPDATE_STORY_SUBJECT);
        assertEquals(StoryActivityGenerator.UPDATE_STORY_CONTENT_SUBJECT, activity.getContent());
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "lib.h"
#include "metadata.h"
#include "import-export.h"
#include "display.h"
#include "toolcontext.h"
#include "lvmcache.h"
#include "lv_alloc.h"
#include "pv_alloc.h"
#include "segtype.h"
#include "text_import.h"
#include "defaults.h"

typedef int (*section_fn) (struct format_instance * fid, struct dm_pool * mem,
			   struct volume_group * vg, const struct config_node * pvn,
			   const struct config_node * vgn,
			   struct dm_hash_table * pv_hash,
			   struct dm_hash_table * lv_hash,
			   unsigned *scan_done_once,
			   unsigned report_missing_devices);

#define _read_int32(root, path, result) \
	get_config_uint32(root, path, (uint32_t *) result)

#define _read_uint32(root, path, result) \
	get_config_uint32(root, path, result)

#define _read_int64(root, path, result) \
	get_config_uint64(root, path, result)

/*
 * Logs an attempt to read an invalid format file.
 */
static void _invalid_format(const char *str)
{
	log_error("Can't process text format file - %s.", str);
}

/*
 * Checks that the config file contains vg metadata, and that it
 * we recognise the version number,
 */
static int _vsn1_check_version(const struct config_tree *cft)
{
	const struct config_node *cn;
	const struct config_value *cv;

	/*
	 * Check the contents field.
	 */
	if (!(cn = find_config_node(cft->root, CONTENTS_FIELD))) {
		_invalid_format("missing contents field");
		return 0;
	}

	cv = cn->v;
	if (!cv || cv->type != CFG_STRING || strcmp(cv->v.str, CONTENTS_VALUE)) {
		_invalid_format("unrecognised contents field");
		return 0;
	}

	/*
	 * Check the version number.
	 */
	if (!(cn = find_config_node(cft->root, FORMAT_VERSION_FIELD))) {
		_invalid_format("missing version number");
		return 0;
	}

	cv = cn->v;
	if (!cv || cv->type != CFG_INT || cv->v.i != FORMAT_VERSION_VALUE) {
		_invalid_format("unrecognised version number");
		return 0;
	}

	return 1;
}

static int _is_converting(struct logical_volume *lv)
{
	struct lv_segment *seg;

	if (lv->status & MIRRORED) {
		seg = first_seg(lv);
		/* Can't use is_temporary_mirror() because the metadata for
		 * seg_lv may not be read in and flags may not be set yet. */
		if (seg_type(seg, 0) == AREA_LV &&
		    strstr(seg_lv(seg, 0)->name, MIRROR_SYNC_LAYER))
			return 1;
	}

	return 0;
}

static int _read_id(struct id *id, const struct config_node *cn, const char *path)
{
	const struct config_value *cv;

	if (!(cn = find_config_node(cn, path))) {
		log_error("Couldn't find uuid.");
		return 0;
	}

	cv = cn->v;
	if (!cv || !cv->v.str) {
		log_error("uuid must be a string.");
		return 0;
	}

	if (!id_read_format(id, cv->v.str)) {
		log_error("Invalid uuid.");
		return 0;
	}

	return 1;
}

static int _read_flag_config(const struct config_node *n, uint64_t *status, int type)
{
	const struct config_node *cn;
	*status = 0;

	if (!(cn = find_config_node(n, "status"))) {
		log_error("Could not find status flags.");
		return 0;
	}

	if (!(read_flags(status, type | STATUS_FLAG, cn->v))) {
		log_error("Could not read status flags.");
		return 0;
	}

	if ((cn = find_config_node(n, "flags"))) {
		if (!(read_flags(status, type, cn->v))) {
			log_error("Could not read flags.");
			return 0;
		}
	}

	return 1;
}

static int _read_pv(struct format_instance *fid, struct dm_pool *mem,
		    struct volume_group *vg, const struct config_node *pvn,
		    const struct config_node *vgn __attribute__((unused)),
		    struct dm_hash_table *pv_hash,
		    struct dm_hash_table *lv_hash __attribute__((unused)),
		    unsigned *scan_done_once,
		    unsigned report_missing_devices)
{
	struct physical_volume *pv;
	struct pv_list *pvl;
	const struct config_node *cn;
	uint64_t size;

	if (!(pvl = dm_pool_zalloc(mem, sizeof(*pvl))) ||
	    !(pvl->pv = dm_pool_zalloc(mem, sizeof(*pvl->pv))))
		return_0;

	pv = pvl->pv;

	/*
	 * Add the pv to the pv hash for quick lookup when we read
	 * the lv segments.
	 */
	if (!dm_hash_insert(pv_hash, pvn->key, pv))
		return_0;

	if (!(pvn = pvn->child)) {
		log_error("Empty pv section.");
		return 0;
	}

	if (!_read_id(&pv->id, pvn, "id")) {
		log_error("Couldn't read uuid for physical volume.");
		return 0;
	}

        pv->is_labelled = 1; /* All format_text PVs are labelled. */

	/*
	 * Convert the uuid into a device.
	 */
	if (!(pv->dev = device_from_pvid(fid->fmt->cmd, &pv->id, scan_done_once,
                                         &pv->label_sector))) {
		char buffer[64] __attribute__((aligned(8)));

		if (!id_write_format(&pv->id, buffer, sizeof(buffer)))
			buffer[0] = '\0';
		if (report_missing_devices)
			log_error_once("Couldn't find device with uuid %s.", buffer);
		else
			log_very_verbose("Couldn't find device with uuid %s.", buffer);
	}

	if (!(pv->vg_name = dm_pool_strdup(mem, vg->name)))
		return_0;

	memcpy(&pv->vgid, &vg->id, sizeof(vg->id));

	if (!_read_flag_config(pvn, &pv->status, PV_FLAGS)) {
		log_error("Couldn't read status flags for physical volume.");
		return 0;
	}

	if (!pv->dev)
		pv->status |= MISSING_PV;

	/* Late addition */
	_read_int64(pvn, "dev_size", &pv->size);

	if (!_read_int64(pvn, "pe_start", &pv->pe_start)) {
		log_error("Couldn't read extent size for physical volume.");
		return 0;
	}

	if (!_read_int32(pvn, "pe_count", &pv->pe_count)) {
		log_error("Couldn't find extent count (pe_count) for "
			  "physical volume.");
		return 0;
	}

	dm_list_init(&pv->tags);
	dm_list_init(&pv->segments);

	/* Optional tags */
	if ((cn = find_config_node(pvn, "tags")) &&
	    !(read_tags(mem, &pv->tags, cn->v))) {
		log_error("Couldn't read tags for physical volume %s in %s.",
			  pv_dev_name(pv), vg->name);
		return 0;
	}

	pv->pe_size = vg->extent_size;

	pv->pe_alloc_count = 0;
	pv->pe_align = 0;
	pv->fmt = fid->fmt;

	/* Fix up pv size if missing or impossibly large */
	if ((!pv->size || pv->size > (1ULL << 62)) && pv->dev) {
		if (!dev_get_size(pv->dev, &pv->size)) {
			log_error("%s: Couldn't get size.", pv_dev_name(pv));
			return 0;
		}
		log_verbose("Fixing up missing size (%s) "
			    "for PV %s", display_size(fid->fmt->cmd, pv->size),
			    pv_dev_name(pv));
		size = pv->pe_count * (uint64_t) vg->extent_size + pv->pe_start;
		if (size > pv->size)
			log_warn("WARNING: Physical Volume %s is too large "
				 "for underlying device", pv_dev_name(pv));
	}

	if (!alloc_pv_segment_whole_pv(mem, pv))
		return_0;

	vg->extent_count += pv->pe_count;
	vg->free_count += pv->pe_count;
	add_pvl_to_vgs(vg, pvl);

	return 1;
}

static void _insert_segment(struct logical_volume *lv, struct lv_segment *seg)
{
	struct lv_segment *comp;

	dm_list_iterate_items(comp, &lv->segments) {
		if (comp->le > seg->le) {
			dm_list_add(&comp->list, &seg->list);
			return;
		}
	}

	lv->le_count += seg->len;
	dm_list_add(&lv->segments, &seg->list);
}

static int _read_segment(struct dm_pool *mem, struct volume_group *vg,
			 struct logical_volume *lv, const struct config_node *sn,
			 struct dm_hash_table *pv_hash)
{
	uint32_t area_count = 0u;
	struct lv_segment *seg;
	const struct config_node *cn, *sn_child = sn->child;
	const struct config_value *cv;
	uint32_t start_extent, extent_count;
	struct segment_type *segtype;
	const char *segtype_str;

	if (!sn_child) {
		log_error("Empty segment section.");
		return 0;
	}

	if (!_read_int32(sn_child, "start_extent", &start_extent)) {
		log_error("Couldn't read 'start_extent' for segment '%s' "
			  "of logical volume %s.", sn->key, lv->name);
		return 0;
	}

	if (!_read_int32(sn_child, "extent_count", &extent_count)) {
		log_error("Couldn't read 'extent_count' for segment '%s' "
			  "of logical volume %s.", sn->key, lv->name);
		return 0;
	}

	segtype_str = "striped";

	if ((cn = find_config_node(sn_child, "type"))) {
		cv = cn->v;
		if (!cv || !cv->v.str) {
			log_error("Segment type must be a string.");
			return 0;
		}
		segtype_str = cv->v.str;
	}

	if (!(segtype = get_segtype_from_string(vg->cmd, segtype_str)))
		return_0;

	if (segtype->ops->text_import_area_count &&
	    !segtype->ops->text_import_area_count(sn_child, &area_count))
		return_0;

	if (!(seg = alloc_lv_segment(mem, segtype, lv, start_extent,
				     extent_count, 0, 0, NULL, area_count,
				     extent_count, 0, 0, 0, NULL))) {
		log_error("Segment allocation failed");
		return 0;
	}

	if (seg->segtype->ops->text_import &&
	    !seg->segtype->ops->text_import(seg, sn_child, pv_hash))
		return_0;

	/* Optional tags */
	if ((cn = find_config_node(sn_child, "tags")) &&
	    !(read_tags(mem, &seg->tags, cn->v))) {
		log_error("Couldn't read tags for a segment of %s/%s.",
			  vg->name, lv->name);
		return 0;
	}

	/*
	 * Insert into correct part of segment list.
	 */
	_insert_segment(lv, seg);

	if (seg_is_mirrored(seg))
		lv->status |= MIRRORED;

	if (seg_is_raid(seg))
		lv->status |= RAID;

	if (seg_is_virtual(seg))
		lv->status |= VIRTUAL;

	if (!seg_is_raid(seg) && _is_converting(lv))
		lv->status |= CONVERTING;

	return 1;
}

int text_import_areas(struct lv_segment *seg, const struct config_node *sn,
		      const struct config_node *cn, struct dm_hash_table *pv_hash,
		      uint64_t status)
{
	unsigned int s;
	const struct config_value *cv;
	struct logical_volume *lv1;
	struct physical_volume *pv;
	const char *seg_name = config_parent_name(sn);

	if (!seg->area_count) {
		log_error("Zero areas not allowed for segment %s", seg_name);
		return 0;
	}

	for (cv = cn->v, s = 0; cv && s < seg->area_count; s++, cv = cv->next) {

		/* first we read the pv */
		if (cv->type != CFG_STRING) {
			log_error("Bad volume name in areas array for segment %s.", seg_name);
			return 0;
		}

		if (!cv->next) {
			log_error("Missing offset in areas array for segment %s.", seg_name);
			return 0;
		}

		if (cv->next->type != CFG_INT) {
			log_error("Bad offset in areas array for segment %s.", seg_name);
			return 0;
		}

		/* FIXME Cope if LV not yet read in */
		if ((pv = dm_hash_lookup(pv_hash, cv->v.str))) {
			if (!set_lv_segment_area_pv(seg, s, pv, (uint32_t) cv->next->v.i))
				return_0;
		} else if ((lv1 = find_lv(seg->lv->vg, cv->v.str))) {
			if (!set_lv_segment_area_lv(seg, s, lv1,
						    (uint32_t) cv->next->v.i,
						    status))
				return_0;
		} else {
			log_error("Couldn't find volume '%s' "
				  "for segment '%s'.",
				  cv->v.str ? : "NULL", seg_name);
			return 0;
		}

		cv = cv->next;
	}

	/*
	 * Check we read the correct number of stripes.
	 */
	if (cv || (s < seg->area_count)) {
		log_error("Incorrect number of areas in area array "
			  "for segment '%s'.", seg_name);
		return 0;
	}

	return 1;
}

static int _read_segments(struct dm_pool *mem, struct volume_group *vg,
			  struct logical_volume *lv, const struct config_node *lvn,
			  struct dm_hash_table *pv_hash)
{
	const struct config_node *sn;
	int count = 0, seg_count;

	for (sn = lvn; sn; sn = sn->sib) {

		/*
		 * All sub-sections are assumed to be segments.
		 */
		if (!sn->v) {
			if (!_read_segment(mem, vg, lv, sn, pv_hash))
				return_0;

			count++;
		}
		/* FIXME Remove this restriction */
		if ((lv->status & SNAPSHOT) && count > 1) {
			log_error("Only one segment permitted for snapshot");
			return 0;
		}
	}

	if (!_read_int32(lvn, "segment_count", &seg_count)) {
		log_error("Couldn't read segment count for logical volume %s.",
			  lv->name);
		return 0;
	}

	if (seg_count != count) {
		log_error("segment_count and actual number of segments "
			  "disagree for logical volume %s.", lv->name);
		return 0;
	}

	/*
	 * Check there are no gaps or overlaps in the lv.
	 */
	if (!check_lv_segments(lv, 0))
		return_0;

	/*
	 * Merge segments in case someones been editing things by hand.
	 */
	if (!lv_merge_segments(lv))
		return_0;

	return 1;
}

static int _read_lvnames(struct format_instance *fid __attribute__((unused)),
			 struct dm_pool *mem,
			 struct volume_group *vg, const struct config_node *lvn,
			 const struct config_node *vgn __attribute__((unused)),
			 struct dm_hash_table *pv_hash __attribute__((unused)),
			 struct dm_hash_table *lv_hash,
			 unsigned *scan_done_once __attribute__((unused)),
			 unsigned report_missing_devices __attribute__((unused)))
{
	struct logical_volume *lv;
	const struct config_node *cn;

	if (!(lv = alloc_lv(mem)))
		return_0;

	if (!(lv->name = dm_pool_strdup(mem, lvn->key)))
		return_0;

	if (!(lvn = lvn->child)) {
		log_error("Empty logical volume section.");
		return 0;
	}

	if (!_read_flag_config(lvn, &lv->status, LV_FLAGS)) {
		log_error("Couldn't read status flags for logical volume %s.",
			  lv->name);
		return 0;
	}

	lv->alloc = ALLOC_INHERIT;
	if ((cn = find_config_node(lvn, "allocation_policy"))) {
		const struct config_value *cv = cn->v;
		if (!cv || !cv->v.str) {
			log_error("allocation_policy must be a string.");
			return 0;
		}

		lv->alloc = get_alloc_from_string(cv->v.str);
		if (lv->alloc == ALLOC_INVALID) {
			log_warn("WARNING: Ignoring unrecognised allocation policy %s for LV %s", cv->v.str, lv->name);
			lv->alloc = ALLOC_INHERIT;
		}
	}

	if (!_read_int32(lvn, "read_ahead", &lv->read_ahead))
		/* If not present, choice of auto or none is configurable */
		lv->read_ahead = vg->cmd->default_settings.read_ahead;
	else {
		switch (lv->read_ahead) {
		case 0:
			lv->read_ahead = DM_READ_AHEAD_AUTO;
			break;
		case (uint32_t) -1:
			lv->read_ahead = DM_READ_AHEAD_NONE;
			break;
		default:
			;
		}
	}

	/* Optional tags */
	if ((cn = find_config_node(lvn, "tags")) &&
	    !(read_tags(mem, &lv->tags, cn->v))) {
		log_error("Couldn't read tags for logical volume %s/%s.",
			  vg->name, lv->name);
		return 0;
	}

	if (!dm_hash_insert(lv_hash, lv->name, lv))
		return_0;

	return link_lv_to_vg(vg, lv);
}

static int _read_lvsegs(struct format_instance *fid __attribute__((unused)),
			struct dm_pool *mem,
			struct volume_group *vg, const struct config_node *lvn,
			const struct config_node *vgn __attribute__((unused)),
			struct dm_hash_table *pv_hash,
			struct dm_hash_table *lv_hash,
			unsigned *scan_done_once __attribute__((unused)),
			unsigned report_missing_devices __attribute__((unused)))
{
	struct logical_volume *lv;

	if (!(lv = dm_hash_lookup(lv_hash, lvn->key))) {
		log_error("Lost logical volume reference %s", lvn->key);
		return 0;
	}

	if (!(lvn = lvn->child)) {
		log_error("Empty logical volume section.");
		return 0;
	}

	/* FIXME: read full lvid */
	if (!_read_id(&lv->lvid.id[1], lvn, "id")) {
		log_error("Couldn't read uuid for logical volume %s.",
			  lv->name);
		return 0;
	}

	memcpy(&lv->lvid.id[0], &lv->vg->id, sizeof(lv->lvid.id[0]));

	if (!_read_segments(mem, vg, lv, lvn, pv_hash))
		return_0;

	lv->size = (uint64_t) lv->le_count * (uint64_t) vg->extent_size;

	lv->minor = -1;
	if ((lv->status & FIXED_MINOR) &&
	    !_read_int32(lvn, "minor", &lv->minor)) {
		log_error("Couldn't read minor number for logical "
			  "volume %s.", lv->name);
		return 0;
	}

	lv->major = -1;
	if ((lv->status & FIXED_MINOR) &&
	    !_read_int32(lvn, "major", &lv->major)) {
		log_error("Couldn't read major number for logical "
			  "volume %s.", lv->name);
	}

	return 1;
}

static int _read_sections(struct format_instance *fid,
			  const char *section, section_fn fn,
			  struct dm_pool *mem,
			  struct volume_group *vg, const struct config_node *vgn,
			  struct dm_hash_table *pv_hash,
			  struct dm_hash_table *lv_hash,
			  int optional,
			  unsigned *scan_done_once)
{
	const struct config_node *n;
	/* Only report missing devices when doing a scan */
	unsigned report_missing_devices = scan_done_once ? !*scan_done_once : 1;

	if (!(n = find_config_node(vgn, section))) {
		if (!optional) {
			log_error("Couldn't find section '%s'.", section);
			return 0;
		}

		return 1;
	}

	for (n = n->child; n; n = n->sib) {
		if (!fn(fid, mem, vg, n, vgn, pv_hash, lv_hash,
			scan_done_once, report_missing_devices))
			return_0;
	}

	return 1;
}

static struct volume_group *_read_vg(struct format_instance *fid,
				     const struct config_tree *cft,
				     unsigned use_cached_pvs)
{
	const struct config_node *vgn, *cn;
	struct volume_group *vg;
	struct dm_hash_table *pv_hash = NULL, *lv_hash = NULL;
	unsigned scan_done_once = use_cached_pvs;

	/* skip any top-level values */
	for (vgn = cft->root; (vgn && vgn->v); vgn = vgn->sib)
		;

	if (!vgn) {
		log_error("Couldn't find volume group in file.");
		return NULL;
	}

	if (!(vg = alloc_vg("read_vg", fid->fmt->cmd, vgn->key)))
		return_NULL;

	if (!(vg->system_id = dm_pool_zalloc(vg->vgmem, NAME_LEN + 1)))
		goto_bad;

	vgn = vgn->child;

	if ((cn = find_config_node(vgn, "system_id")) && cn->v) {
		if (!cn->v->v.str) {
			log_error("system_id must be a string");
			goto bad;
		}
		strncpy(vg->system_id, cn->v->v.str, NAME_LEN);
	}

	if (!_read_id(&vg->id, vgn, "id")) {
		log_error("Couldn't read uuid for volume group %s.", vg->name);
		goto bad;
	}

	if (!_read_int32(vgn, "seqno", &vg->seqno)) {
		log_error("Couldn't read 'seqno' for volume group %s.",
			  vg->name);
		goto bad;
	}

	if (!_read_flag_config(vgn, &vg->status, VG_FLAGS)) {
		log_error("Error reading flags of volume group %s.",
			  vg->name);
		goto bad;
	}

	if (!_read_int32(vgn, "extent_size", &vg->extent_size)) {
		log_error("Couldn't read extent size for volume group %s.",
			  vg->name);
		goto bad;
	}

	/*
	 * 'extent_count' and 'free_count' get filled in
	 * implicitly when reading in the pv's and lv's.
	 */

	if (!_read_int32(vgn, "max_lv", &vg->max_lv)) {
		log_error("Couldn't read 'max_lv' for volume group %s.",
			  vg->name);
		goto bad;
	}

	if (!_read_int32(vgn, "max_pv", &vg->max_pv)) {
		log_error("Couldn't read 'max_pv' for volume group %s.",
			  vg->name);
		goto bad;
	}

	if ((cn = find_config_node(vgn, "allocation_policy"))) {
		const struct config_value *cv = cn->v;
		if (!cv || !cv->v.str) {
			log_error("allocation_policy must be a string.");
			goto bad;
		}

		vg->alloc = get_alloc_from_string(cv->v.str);
		if (vg->alloc == ALLOC_INVALID) {
			log_warn("WARNING: Ignoring unrecognised allocation policy %s for VG %s", cv->v.str, vg->name);
			vg->alloc = ALLOC_NORMAL;
		}
	}

	if (!_read_uint32(vgn, "metadata_copies", &vg->mda_copies)) {
		vg->mda_copies = DEFAULT_VGMETADATACOPIES;
	}

	/*
	 * The pv hash memorises the pv section names -> pv
	 * structures.
	 */
	if (!(pv_hash = dm_hash_create(64))) {
		log_error("Couldn't create hash table.");
		goto bad;
	}

	if (!_read_sections(fid, "physical_volumes", _read_pv, vg->vgmem, vg,
			    vgn, pv_hash, lv_hash, 0, &scan_done_once)) {
		log_error("Couldn't find all physical volumes for volume "
			  "group %s.", vg->name);
		goto bad;
	}

	/* Optional tags */
	if ((cn = find_config_node(vgn, "tags")) &&
	    !(read_tags(vg->vgmem, &vg->tags, cn->v))) {
		log_error("Couldn't read tags for volume group %s.", vg->name);
		goto bad;
	}

	/*
	 * The lv hash memorises the lv section names -> lv
	 * structures.
	 */
	if (!(lv_hash = dm_hash_create(1024))) {
		log_error("Couldn't create hash table.");
		goto bad;
	}

	if (!_read_sections(fid, "logical_volumes", _read_lvnames, vg->vgmem,
			    vg, vgn, pv_hash, lv_hash, 1, NULL)) {
		log_error("Couldn't read all logical volume names for volume "
			  "group %s.", vg->name);
		goto bad;
	}

	if (!_read_sections(fid, "logical_volumes", _read_lvsegs, vg->vgmem,
			    vg, vgn, pv_hash, lv_hash, 1, NULL)) {
		log_error("Couldn't read all logical volumes for "
			  "volume group %s.", vg->name);
		goto bad;
	}

	if (!fixup_imported_mirrors(vg)) {
		log_error("Failed to fixup mirror pointers after import for "
			  "volume group %s.", vg->name);
		goto bad;
	}

	dm_hash_destroy(pv_hash);
	dm_hash_destroy(lv_hash);

	/* FIXME Determine format type from file contents */
	/* eg Set to instance of fmt1 here if reading a format1 backup? */
	vg_set_fid(vg, fid);

	/*
	 * Finished.
	 */
	return vg;

      bad:
	if (pv_hash)
		dm_hash_destroy(pv_hash);

	if (lv_hash)
		dm_hash_destroy(lv_hash);

	release_vg(vg);
	return NULL;
}

static void _read_desc(struct dm_pool *mem,
		       const struct config_tree *cft, time_t *when, char **desc)
{
	const char *d;
	unsigned int u = 0u;
	int old_suppress;

	old_suppress = log_suppress(1);
	d = find_config_str(cft->root, "description", "");
	log_suppress(old_suppress);
	*desc = dm_pool_strdup(mem, d);

	(void) get_config_uint32(cft->root, "creation_time", &u);
	*when = u;
}

static const char *_read_vgname(const struct format_type *fmt,
				const struct config_tree *cft, struct id *vgid,
				uint64_t *vgstatus, char **creation_host)
{
	const struct config_node *vgn;
	struct dm_pool *mem = fmt->cmd->mem;
	char *vgname;
	int old_suppress;

	old_suppress = log_suppress(2);
	*creation_host = dm_pool_strdup(mem,
					find_config_str(cft->root,
							"creation_host", ""));
	log_suppress(old_suppress);

	/* skip any top-level values */
	for (vgn = cft->root; (vgn && vgn->v); vgn = vgn->sib) ;

	if (!vgn) {
		log_error("Couldn't find volume group in file.");
		return 0;
	}

	if (!(vgname = dm_pool_strdup(mem, vgn->key)))
		return_0;

	vgn = vgn->child;

	if (!_read_id(vgid, vgn, "id")) {
		log_error("Couldn't read uuid for volume group %s.", vgname);
		return 0;
	}

	if (!_read_flag_config(vgn, vgstatus, VG_FLAGS)) {
		log_error("Couldn't find status flags for volume group %s.",
			  vgname);
		return 0;
	}

	return vgname;
}

static struct text_vg_version_ops _vsn1_ops = {
	.check_version = _vsn1_check_version,
	.read_vg = _read_vg,
	.read_desc = _read_desc,
	.read_vgname = _read_vgname,
};

struct text_vg_version_ops *text_vg_vsn1_init(void)
{
	return &_vsn1_ops;
}


text:
package org.openntf.domino.design.impl;

import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Instant;

import org.openntf.domino.Database;
import org.openntf.domino.Document;
import org.openntf.domino.utils.xml.XMLNode;

// TODO MetaData
public final class ScriptLibraryLS extends AbstractDesignFileResource implements org.openntf.domino.design.ScriptLibraryLS,
		HasMetadata {
	private static final long serialVersionUID = 1L;

	/**
	 * @param document
	 */
	protected ScriptLibraryLS(final Document document) {
		super(document);
	}

	@Override
	protected boolean enforceRawFormat() {
		//return false;

		// it is complex to transform a script library from the "<code event='...'>" tags to a .lss file
		// The LSS file contains "header" for each code event like this:
		// '++LotusScript Development Environment:2:5:(Options):0:74
		// '++LotusScript Development Environment:2:5:(Declarations):0:10
		// '++LotusScript Development Environment:2:5:(Forward):0:1

		return true; // so that's why we force RAW format
	}

	@SuppressWarnings("nls")
	protected ScriptLibraryLS(final Database database) {
		super(database);
		throw new UnsupportedOperationException("There is still something todo!");
		//		try {
		//			InputStream is = DesignView.class.getResourceAsStream("/org/openntf/domino/design/impl/dxl_lotusscriptlibrary.xml");
		//			loadDxl(is);
		//			is.close();
		//
		//			// Set some defaults
		//			Session session = getAncestorSession();
		//			String dataDirectory = session.getEnvironmentString("Directory", true);
		//			XMLDocument dxl = getDxl();
		//			dxl.selectSingleNode("/scriptlibrary/code/javaproject").setAttribute("codepath", dataDirectory);
		//
		//		} catch (IOException e) {
		//			DominoUtils.handleException(e);
		//		}
	}

	@Override
	public void writeOnDiskFile(final Path odpFile) throws IOException {
		// TODO Check for $Scriptlib_error => throw exception if item exists
		try(Writer pw = Files.newBufferedWriter(odpFile)) {
			for (XMLNode rawitemdata : getDxl().selectNodes("//item[@name='$ScriptLib']/text")) { //$NON-NLS-1$
				pw.write(rawitemdata.getText());
			}
		}
		Files.setLastModifiedTime(odpFile, FileTime.from(Instant.ofEpochMilli(getDocLastModified().getTime())));
	}

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
  ~ Copyright 2015 Open Networking Laboratory
  ~
  ~ 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.
  -->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="onos-app-fwd-1.3.0-SNAPSHOT">
    <repository>mvn:org.onosproject/onos-app-fwd/1.3.0-SNAPSHOT/xml/features</repository>
    <feature name="onos-app-fwd" version="1.3.0-SNAPSHOT"
             description="Reactive forwarding application using flow subsystem">
        <feature>onos-api</feature>
        <bundle>mvn:org.onosproject/onos-app-fwd/1.3.0-SNAPSHOT</bundle>
    </feature>
</features>


text:
// SampSharp
// Copyright 2015 Tim Potze
//
// 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.

using System;
using SampSharp.GameMode.Definitions;
using SampSharp.GameMode.World;

namespace SampSharp.GameMode.Events
{
    /// <summary>
    ///     Provides data for the <see cref="BaseMode.PlayerEnterExitModShop" /> or <see cref="GtaPlayer.EnterExitModShop" />
    ///     event.
    /// </summary>
    public class EnterModShopEventArgs : EventArgs
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="EnterModShopEventArgs" /> class.
        /// </summary>
        /// <param name="enterExit">The enter exit value.</param>
        /// <param name="interiorid">The interiorid.</param>
        public EnterModShopEventArgs(EnterExit enterExit, int interiorid)
        {
            EnterExit = enterExit;
            InteriorId = interiorid;
        }

        /// <summary>
        ///     Gets a value indicating whether the player is entering or exiting.
        /// </summary>
        public EnterExit EnterExit { get; private set; }

        /// <summary>
        ///     Gets the interior identifier of the mod shop.
        /// </summary>
        public int InteriorId { get; private set; }
    }
}


text:
package com.sphericalelephant.example.butterknife.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sphericalelephant.example.butterknife.R;

import java.util.List;

import butterknife.BindDrawable;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * This is an example illustrating the use of ButterKnife, a very simple dependency injection (view injection) framework for android.
 * ButterKnife can be found here (https://github.com/JakeWharton/butterknife)
 *

 * We are using AppCompatActivity to stay compatible with future releases of Android. Originally, AppCompatActivity
 * was used to provide Actionbar functionality (now known as the toolbar) to older Android systems, but starting from
 * 5.x.x it is also required to implement Material design features.
 */
public class MainActivity extends AppCompatActivity {
	/**
	 * We are binding the view instance to the view here, this is equivalent to calling
	 *

	 * testButton = (Button) findViewById(R.id.activity_mainactivity_b_test);
	 *

	 * after setContentView(...)
	 */
	@BindView(R.id.activity_mainactivity_b_test)
	Button testButton;

	/**
	 * Similar to the above binding, but is more fault tolerant: if the view cannot be found, no exception will be thrown
	 */
	@Nullable
	@BindView(R.id.activity_mainactivity_tv_mightnotbehere)
	TextView textView;

	@BindView(R.id.activity_mainactivity_iv_image)
	ImageView image;

	/**
	 * There are many more resource binding annotations, try @Bind<autocomplete>, here is a small sample
	 */
	@BindDrawable(R.drawable.activity_mainactivity_sellogo)
	Drawable sphericalElephantLogo;

	/**
	 * You can also use bind to bind views to lists and arrays
	 */
	@BindViews({R.id.activity_mainactivity_b_test, R.id.activity_mainactivity_iv_image, R.id.activity_mainactivity_tv_mightnotbehere})
	List<View> viewsToHideOrShow;

	/**
	 * As a point of reference, these two buttons are bound without using ButterKnife
	 */
	private Button hide, show;

	private Unbinder unbinder;

	private ButterKnife.Action hideAction = new ButterKnife.Action() {
		@Override
		public void apply(View view, int index) {
			view.setVisibility(View.INVISIBLE);
		}
	};

	private ButterKnife.Action showAction = new ButterKnife.Action() {
		@Override
		public void apply(View view, int index) {
			view.setVisibility(View.VISIBLE);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mainactivity);

		// binding button and setting onClick listener manually
		hide = (Button) findViewById(R.id.activity_mainactivity_b_hide);
		hide.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// pseudo lambda gets applied to all views in viewToHideOrShow
				ButterKnife.apply(viewsToHideOrShow, hideAction);
			}
		});

		// binding button and setting onClick listener manually
		show = (Button) findViewById(R.id.activity_mainactivity_b_show);
		show.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// pseudo lambda gets applied to all views in viewToHideOrShow
				ButterKnife.apply(viewsToHideOrShow, showAction);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		unbinder = ButterKnife.bind(this); // takes a view as second parameter to allow binding to arbitrary views (uses view as parent)
		image.setImageDrawable(sphericalElephantLogo);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unbinder.unbind(); // unbind! Actually: only required in fragments (onDestroyView)
	}

	/**
	 * This annotation sets an onClick listener. You can provide a parameter here (instance of View) that will automatically casted
	 * to the type of the View in question.
	 */
	@OnClick(R.id.activity_mainactivity_b_test)
	public void testButtonClicked(Button testButton) {
		Toast.makeText(getApplicationContext(), R.string.activity_mainactivity_testpressed, Toast.LENGTH_SHORT).show();
	}
}


text:
var inspectorCommands = require("./InspectorBackendCommands");
var debuggerDomains = require("./debugger");
function getter(_this, property) {
    if (typeof property === "function") {
        return property.call(_this);
    }
    else {
        return property;
    }
}
var frameId = "NativeScriptMainFrameIdentifier";
var loaderId = "Loader Identifier";
var resources_datas = [];
var documentTypeByMimeType = {
    "text/xml": "Document",
    "text/plain": "Document",
    "text/html": "Document",
    "application/xml": "Document",
    "application/xhtml+xml": "Document",
    "text/css": "Stylesheet",
    "text/javascript": "Script",
    "text/ecmascript": "Script",
    "application/javascript": "Script",
    "application/ecmascript": "Script",
    "application/x-javascript": "Script",
    "application/json": "Script",
    "application/x-json": "Script",
    "text/x-javascript": "Script",
    "text/x-json": "Script",
    "text/typescript": "Script"
};
var Request = (function () {
    function Request(_networkDomainDebugger, _requestID) {
        this._networkDomainDebugger = _networkDomainDebugger;
        this._requestID = _requestID;
    }
    Object.defineProperty(Request.prototype, "mimeType", {
        get: function () {
            return this._mimeType;
        },
        set: function (value) {
            if (this._mimeType !== value) {
                this._mimeType = value;
                var resourceType = "Other";
                if (this._mimeType in documentTypeByMimeType) {
                    resourceType = documentTypeByMimeType[this._mimeType];
                }
                if (this._mimeType.indexOf("image/") !== -1) {
                    resourceType = "Image";
                }
                if (this._mimeType.indexOf("font/") !== -1) {
                    resourceType = "Font";
                }
                this._resourceType = resourceType;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "requestID", {
        get: function () {
            return this._requestID;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "hasTextContent", {
        get: function () {
            return ["Document", "Stylesheet", "Script", "XHR"].indexOf(this._resourceType) !== -1;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "data", {
        get: function () {
            return this._data;
        },
        set: function (value) {
            if (this._data !== value) {
                this._data = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "resourceType", {
        get: function () {
            return this._resourceType;
        },
        set: function (value) {
            if (this._resourceType !== value) {
                this._resourceType = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    Request.prototype.responseReceived = function (response) {
        if (this._networkDomainDebugger.enabled) {
            this._networkDomainDebugger.events.responseReceived(this.requestID, frameId, loaderId, __inspectorTimestamp(), this.resourceType, response);
        }
    };
    Request.prototype.loadingFinished = function () {
        if (this._networkDomainDebugger.enabled) {
            this._networkDomainDebugger.events.loadingFinished(this.requestID, __inspectorTimestamp());
        }
    };
    Request.prototype.requestWillBeSent = function (request) {
        if (this._networkDomainDebugger.enabled) {
            this._networkDomainDebugger.events.requestWillBeSent(this.requestID, frameId, loaderId, request.url, request, __inspectorTimestamp(), { type: 'Script' });
        }
    };
    return Request;
}());
exports.Request = Request;
var NetworkDomainDebugger = (function () {
    function NetworkDomainDebugger() {
        this.events = new inspectorCommands.NetworkDomain.NetworkFrontend();
    }
    Object.defineProperty(NetworkDomainDebugger.prototype, "enabled", {
        get: function () {
            return this._enabled;
        },
        enumerable: true,
        configurable: true
    });
    NetworkDomainDebugger.prototype.enable = function () {
        if (debuggerDomains.getNetwork()) {
            throw new Error("One NetworkDomainDebugger may be enabled at a time.");
        }
        else {
            debuggerDomains.setNetwork(this);
        }
        this._enabled = true;
    };
    NetworkDomainDebugger.prototype.disable = function () {
        if (debuggerDomains.getNetwork() === this) {
            debuggerDomains.setNetwork(null);
        }
        this._enabled = false;
    };
    NetworkDomainDebugger.prototype.setExtraHTTPHeaders = function (params) {
    };
    NetworkDomainDebugger.prototype.getResponseBody = function (params) {
        var resource_data = resources_datas[params.requestId];
        var body = resource_data.hasTextContent ? NSString.alloc().initWithDataEncoding(resource_data.data, 4).toString() :
            resource_data.data.base64EncodedStringWithOptions(0);
        if (resource_data) {
            return {
                body: body,
                base64Encoded: !resource_data.hasTextContent
            };
        }
    };
    NetworkDomainDebugger.prototype.canClearBrowserCache = function () {
        return {
            result: false
        };
    };
    NetworkDomainDebugger.prototype.clearBrowserCache = function () {
    };
    NetworkDomainDebugger.prototype.canClearBrowserCookies = function () {
        return {
            result: false
        };
    };
    NetworkDomainDebugger.prototype.clearBrowserCookies = function () {
    };
    NetworkDomainDebugger.prototype.setCacheDisabled = function (params) {
    };
    NetworkDomainDebugger.prototype.loadResource = function (params) {
        var appPath = getter(NSBundle, NSBundle.mainBundle).bundlePath;
        var pathUrl = params.url.replace("file://", appPath);
        var fileManager = getter(NSFileManager, NSFileManager.defaultManager);
        var data = fileManager.fileExistsAtPath(pathUrl) ? fileManager.contentsAtPath(pathUrl) : undefined;
        var content = data ? NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding) : "";
        return {
            content: content.toString(),
            mimeType: "application/octet-stream",
            status: 200
        };
    };
    NetworkDomainDebugger.prototype.create = function () {
        var id = (++NetworkDomainDebugger.idSequence).toString();
        var resourceData = new Request(this, id);
        resources_datas[id] = resourceData;
        return resourceData;
    };
    NetworkDomainDebugger.idSequence = 0;
    NetworkDomainDebugger = __decorate([
        inspectorCommands.DomainDispatcher("Network")
    ], NetworkDomainDebugger);
    return NetworkDomainDebugger;
}());
exports.NetworkDomainDebugger = NetworkDomainDebugger;
//# sourceMappingURL=webinspector.js.map


text:
package com.spotify.docker.client.messages;

import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;

import java.util.Date;
import java.util.List;

import javax.annotation.Nullable;

@AutoValue
@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE)
public abstract class ContainerState {

  @Nullable
  @JsonProperty("Status")
  public abstract String status();

  @JsonProperty("Running")
  public abstract Boolean running();

  @JsonProperty("Paused")
  public abstract Boolean paused();

  @Nullable
  @JsonProperty("Restarting")
  public abstract Boolean restarting();

  @JsonProperty("Pid")
  public abstract Integer pid();

  @JsonProperty("ExitCode")
  public abstract Integer exitCode();

  @JsonProperty("StartedAt")
  public abstract Date startedAt();

  @JsonProperty("FinishedAt")
  public abstract Date finishedAt();

  @Nullable
  @JsonProperty("Error")
  public abstract String error();

  @Nullable
  @JsonProperty("OOMKilled")
  public abstract Boolean oomKilled();

  @Nullable
  @JsonProperty("Health")
  public abstract Health health();

  @JsonCreator
  static ContainerState create(
      @JsonProperty("Status") final String status,
      @JsonProperty("Running") final Boolean running,
      @JsonProperty("Paused") final Boolean addr,
      @JsonProperty("Restarting") final Boolean restarting,
      @JsonProperty("Pid") final Integer pid,
      @JsonProperty("ExitCode") final Integer exitCode,
      @JsonProperty("StartedAt") final Date startedAt,
      @JsonProperty("FinishedAt") final Date finishedAt,
      @JsonProperty("Error") final String error,
      @JsonProperty("OOMKilled") final Boolean oomKilled,
      @JsonProperty("Health") final Health health) {
    return new AutoValue_ContainerState(status, running, addr, restarting, pid, exitCode,
        startedAt, finishedAt, error, oomKilled, health);
  }

  @AutoValue
  public abstract static class HealthLog {

    @JsonProperty("Start")
    public abstract Date start();

    @JsonProperty("End")
    public abstract Date end();

    @JsonProperty("ExitCode")
    public abstract Integer exitCode();

    @JsonProperty("Output")
    public abstract String output();

    @JsonCreator
    static HealthLog create(
        @JsonProperty("Start") final Date start,
        @JsonProperty("End") final Date end,
        @JsonProperty("ExitCode") final Integer exitCode,
        @JsonProperty("Output") final String output) {
      return new AutoValue_ContainerState_HealthLog(start, end, exitCode, output);
    }
  }

  @AutoValue
  public abstract static class Health {

    @JsonProperty("Status")
    public abstract String status();

    @JsonProperty("FailingStreak")
    public abstract Integer failingStreak();

    @JsonProperty("Log")
    public abstract ImmutableList<HealthLog> log();

    @JsonCreator
    static Health create(
        @JsonProperty("Status") final String status,
        @JsonProperty("FailingStreak") final Integer failingStreak,
        @JsonProperty("Log") final List<HealthLog> log) {
      final ImmutableList<HealthLog> logT =
          log == null ? ImmutableList.<HealthLog>of() : ImmutableList.copyOf(log);
      return new AutoValue_ContainerState_Health(status, failingStreak, logT);
    }
  }
}


text:
/* ../../../../var/folders/74/5b1jhx655yg17x4s7m5bxsvr0000gn/T/tmp-11047-7Oi7DdmDGDHB/OBIS/src/ui/styles/app.css */
@media screen and (min-width:352px) {
  #obis-root {
    margin: 1em;
  }
}
#obis-root {
  z-index: 1000;
  position: fixed;
  top: 3em;
  right: 0px;
  width: 24em;
  margin: 0;
  padding: 0;
  font-size: 16px;
  font-family: sans-serif;
  text-align: center;
}
#obis-root * {
  color: #f5f5ee;
  font-family: sans-serif;
}
#obis-root .dialog {
  padding: 1.5em;
  background: #1a1a1a;
  box-shadow: #222 0.5em 0.5em 2em;
  border-radius: 1.3em;
  width: 20em;
}
#obis-root .dialog.hidden {
  display: none;
}
#obis-root .dialog .toggle-button {
  float: right;
  font-size: 1em;
  margin-left: 0.5em;
  width: 3em;
  height: 3em;
  border-radius: 1.5em;
}
#obis-root .dialog .toggle-button.closed {
  transform: rotate(-180deg);
}
#obis-root .dialog h1 {
  margin: 0 0 0.8em 0;
  padding: 0;
  font-size: 1.5em;
  font-weight: 400;
  letter-spacing: -0.5;
  text-align: left;
}
#obis-root .dialog h2 {
  font-size: 0.75em;
  font-weight: 100;
  text-align: left;
}
#obis-root .dialog progress {
  width: 100%;
}
#obis-root .dialog button {
  padding: 0.75em 0.7em;
  font-style: normal;
  font-weight: bold;
  font-size: 0.8em;
  border: none;
  border-radius: 0.5em;
  text-align: center;
  background: rgba(72, 72, 72, 0.6);
  color: #fff;
}
#obis-root .dialog button:disabled {
  color: #888;
}
#obis-root .dialog .accounts {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: auto;
  column-gap: 0.5em;
}
#obis-root .dialog .accounts .account {
  border: none;
  border-radius: 0.75em;
  min-height: 6em;
  padding: 0.5em;
  margin: 0.5em 0;
  background: #484848;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-content: flex-end;
}
#obis-root .dialog .accounts .account .statements-loaded {
  font-size: 0.575em;
  font-weight: 600;
  text-align: right;
}
#obis-root .dialog .accounts .account .years-loaded {
  font-size: 0.7em;
  font-weight: 600;
  text-align: right;
  color: #aaa;
  flex: 2;
}
#obis-root .dialog .accounts .account .account-name {
  font-size: 0.9em;
  font-weight: 800;
  text-align: left;
  margin-bottom: auto;
}
#obis-root .dialog .actions {
  display: grid;
  margin-top: 0.5em;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto 1fr;
  grid-template-areas: "slider fetch" "view download";
  column-gap: 0.5em;
  row-gap: 0.5em;
}
#obis-root .dialog .actions .fetch-slider {
  grid-area: slider;
}
#obis-root .dialog .actions .fetch-everything {
  grid-area: fetch;
}
#obis-root .vertical-animation-container {
  max-height: 0em;
  overflow: hidden;
  transition-property: max-height opacity;
  transition-duration: 0ms;
}
#obis-root .vertical-animation-container.opening {
  overflow: hidden;
  transition-duration: 250ms;
  opacity: 1;
}
#obis-root .vertical-animation-container.closing {
  overflow: hidden;
  opacity: 0;
  max-height: 0em !important;
  transition-duration: 250ms;
}
#obis-root .vertical-animation-container.opened {
  overflow: inherit;
  opacity: 1;
}
#obis-root .vertical-animation-container.closed {
  overflow: hidden;
  max-height: 0em !important;
  opacity: 0;
}


text:
/* ************************************************************************* */
/* elina_tcons0.h: tree expressions constraints and arrays */
/* ************************************************************************* */

#ifndef _ELINA_TCONS0_H_
#define _ELINA_TCONS0_H_

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include "elina_coeff.h"
#include "elina_texpr0.h"
#include "elina_lincons0.h"

#ifdef __cplusplus
extern "C" {
#endif

/* Datatypes */
/* ====================================================================== */

/* Represents the constraint "expr constyp 0" */
typedef struct elina_tcons0_t {
  elina_texpr0_t* texpr0;  /* expression */
  elina_constyp_t constyp; /* type of constraint */
  elina_scalar_t* scalar;  /* maybe NULL.
			   For EQMOD constraint, indicates the
			   modulo */
} elina_tcons0_t;

/* Array of constraints */
typedef struct elina_tcons0_array_t {
  elina_tcons0_t* p;
  size_t size;
} elina_tcons0_array_t;

/* ********************************************************************** */
/* I. elina_tcons0_t */
/* ********************************************************************** */

/* ====================================================================== */
/* I.1 Memory management and printing */
/* ====================================================================== */

static inline
elina_tcons0_t elina_tcons0_make(elina_constyp_t constyp,
			   elina_texpr0_t* texpr,
			   elina_scalar_t* scalar);
  /* Create a constraint of given type with the given expression.
     The expression and the coefficient are not duplicated, just pointed to */

elina_tcons0_t elina_tcons0_make_unsat(void);
  /* Create the constraint -1>=0 */

static inline
elina_tcons0_t elina_tcons0_from_lincons0(elina_lincons0_t* cons);
  /* From linear constraint to comb-like tree expression constraint  */

static inline
elina_tcons0_t elina_tcons0_copy(elina_tcons0_t* cons);
  /* Duplication */

static inline
void elina_tcons0_clear(elina_tcons0_t* cons);
  /* Free the linear expression of the constraint and set pointer to NULL */

void elina_tcons0_fprint(FILE* stream,
		      elina_tcons0_t* cons, char** name_of_dim);
  /* Printing a linear constraint */

/* ====================================================================== */
/* I.2 Tests */
/* ====================================================================== */

static inline
bool elina_tcons0_is_interval_cst(elina_tcons0_t* a);
  /* no-variable, only constant leaves */

static inline
bool elina_tcons0_is_interval_linear(elina_tcons0_t* a);
  /* linear with possibly interval coefficients, no rounding */

static inline
bool elina_tcons0_is_interval_polynomial(elina_tcons0_t* a);
  /* polynomial with possibly interval coefficients, no rounding  */

static inline
bool elina_tcons0_is_interval_polyfrac(elina_tcons0_t* a);
  /* polynomial fraction with possibly interval coefficients, no rounding */

static inline
bool elina_tcons0_is_scalar(elina_tcons0_t* a);
  /* all coefficients are scalar (non-interval) */

/* ====================================================================== */
/* I.3 Change of dimensions and permutations */
/* ====================================================================== */

static inline
void elina_tcons0_add_dimensions_with(elina_tcons0_t* cons,
				   elina_dimchange_t* dimchange);
static inline
elina_tcons0_t elina_tcons0_add_dimensions(elina_tcons0_t* cons,
				     elina_dimchange_t* dimchange);

static inline
void elina_tcons0_remove_dimensions_with(elina_tcons0_t* cons,
				      elina_dimchange_t* dimchange);
static inline
elina_tcons0_t elina_tcons0_remove_dimensions(elina_tcons0_t* cons,
					elina_dimchange_t* dimchange);

static inline
void elina_tcons0_permute_dimensions_with(elina_tcons0_t* cons,
				       elina_dimperm_t* perm);
static inline
elina_tcons0_t elina_tcons0_permute_dimensions(elina_tcons0_t* cons,
					 elina_dimperm_t* perm);

/* ********************************************************************** */
/* II. Array of linear constraints */
/* ********************************************************************** */

elina_tcons0_array_t elina_tcons0_array_make(size_t size);
  /* Allocate an array of size constraints.
     The constraints are initialized with NULL pointers, */

void elina_tcons0_array_resize(elina_tcons0_array_t* array, size_t size);
  /* Resize an array of size constraints.
     New constraints are initialized with NULL pointers,
     Removed constraints with non-NULL pointers are deallocated */

void elina_tcons0_array_clear(elina_tcons0_array_t* array);
  /* Clear the constraints of the array, and then the array itself */

void elina_tcons0_array_fprint(FILE* stream,
			      elina_tcons0_array_t* elina_tcons0_array,
			      char** name_of_dim);
  /* Printing */

bool elina_tcons0_array_is_interval_linear(elina_tcons0_array_t* array);
  /* Are all the expressions involved interval linear ? */

/* ====================================================================== */
/* II.1 Change of dimensions and permutations */
/* ====================================================================== */

void elina_tcons0_array_add_dimensions_with(elina_tcons0_array_t* array,
					 elina_dimchange_t* dimchange);
elina_tcons0_array_t elina_tcons0_array_add_dimensions(elina_tcons0_array_t* array,
						 elina_dimchange_t* dimchange);

void elina_tcons0_array_remove_dimensions_with(elina_tcons0_array_t* array,
					    elina_dimchange_t* dimchange);
elina_tcons0_array_t elina_tcons0_array_remove_dimensions(elina_tcons0_array_t* array,
						    elina_dimchange_t* dimchange);

void elina_tcons0_array_permute_dimensions_with(elina_tcons0_array_t* array,
					     elina_dimperm_t* perm);
elina_tcons0_array_t elina_tcons0_array_permute_dimensions(elina_tcons0_array_t* array,
						     elina_dimperm_t* perm);

/* ********************************************************************** */
/* III. Inline functions definitions */
/* ********************************************************************** */

static inline elina_tcons0_t elina_tcons0_make(elina_constyp_t constyp, elina_texpr0_t* texpr, elina_scalar_t* scalar)
{
  elina_tcons0_t cons;
  cons.constyp = constyp;
  cons.texpr0 = texpr;
  cons.scalar = scalar;
  return cons;
}
static inline elina_tcons0_t elina_tcons0_from_lincons0(elina_lincons0_t* cons)
{
  elina_tcons0_t res;
  res.texpr0 = elina_texpr0_from_linexpr0(cons->linexpr0);
  res.constyp = cons->constyp;
  res.scalar = cons->scalar ? elina_scalar_alloc_set(cons->scalar) : NULL;
  return res;
}
static inline elina_tcons0_t elina_tcons0_copy(elina_tcons0_t* cons)
{
  return elina_tcons0_make(cons->constyp,
			elina_texpr0_copy(cons->texpr0),
			cons->scalar ? elina_scalar_alloc_set(cons->scalar) : NULL);
}
static inline void elina_tcons0_clear(elina_tcons0_t* tcons)
{
  if (tcons->texpr0){
    elina_texpr0_free(tcons->texpr0);
  }
  tcons->texpr0 = NULL;
  if (tcons->scalar){
    elina_scalar_free(tcons->scalar);
  }
  tcons->scalar = NULL;
}

static inline
bool elina_tcons0_is_interval_cst(elina_tcons0_t* a)
{ return elina_texpr0_is_interval_cst(a->texpr0); }
static inline
bool elina_tcons0_is_interval_linear(elina_tcons0_t* a)
{ return elina_texpr0_is_interval_linear(a->texpr0); }
static inline
bool elina_tcons0_is_interval_polynomial(elina_tcons0_t* a)
{ return elina_texpr0_is_interval_polynomial(a->texpr0); }
static inline
bool elina_tcons0_is_interval_polyfrac(elina_tcons0_t* a)
{ return elina_texpr0_is_interval_polyfrac(a->texpr0); }
static inline
bool elina_tcons0_is_scalar(elina_tcons0_t* a)
{ return elina_texpr0_is_scalar(a->texpr0); }

static inline
void elina_tcons0_add_dimensions_with(elina_tcons0_t* cons,
				   elina_dimchange_t* dimchange)
{ elina_texpr0_add_dimensions_with(cons->texpr0,dimchange); }
static inline
elina_tcons0_t elina_tcons0_add_dimensions(elina_tcons0_t* cons,
				     elina_dimchange_t* dimchange)
{
  return elina_tcons0_make(cons->constyp,
			elina_texpr0_add_dimensions(cons->texpr0,dimchange),
			cons->scalar ? elina_scalar_alloc_set(cons->scalar) : NULL);
}
static inline
void elina_tcons0_remove_dimensions_with(elina_tcons0_t* cons,
				      elina_dimchange_t* dimchange)
{ elina_texpr0_remove_dimensions_with(cons->texpr0,dimchange); }
static inline
elina_tcons0_t elina_tcons0_remove_dimensions(elina_tcons0_t* cons,
					elina_dimchange_t* dimchange)
{
  return elina_tcons0_make(cons->constyp,
			elina_texpr0_remove_dimensions(cons->texpr0,dimchange),
			cons->scalar ? elina_scalar_alloc_set(cons->scalar) : NULL);
}
static inline
void elina_tcons0_permute_dimensions_with(elina_tcons0_t* cons,
				       elina_dimperm_t* perm)
{ elina_texpr0_permute_dimensions_with(cons->texpr0,perm); }
static inline
elina_tcons0_t elina_tcons0_permute_dimensions(elina_tcons0_t* cons,
					 elina_dimperm_t* perm)
{
  return elina_tcons0_make(cons->constyp,
			elina_texpr0_permute_dimensions(cons->texpr0,perm),
			cons->scalar ? elina_scalar_alloc_set(cons->scalar) : NULL);
}

#ifdef __cplusplus
}
#endif

#endif


text:
package at.alladin.rmbt.controlServer.filter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Status;
import org.restlet.routing.Filter;

public class ResultStatusFilter extends Filter {

	@Override
	protected void afterHandle(Request request, Response response) {
		System.out.println("STATUS FILTER");
		try {
			final JSONObject json = new JSONObject(response.getEntityAsText());
			final JSONArray errorArray = json.optJSONArray("error");
			if (errorArray != null && errorArray.length() > 0) {
				response.setStatus(Status.SERVER_ERROR_INTERNAL);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.setStatus(Status.SERVER_ERROR_INTERNAL);
		}
		super.afterHandle(request, response);
	}
}


text:
package de.xneo.hetznerstatusfilter;

import com.google.common.collect.ImmutableSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.util.Collections;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = HetznerStatusFilterApplication.class)
@WebAppConfiguration
public class HetznerStatusFilterApplicationTests {

    @Autowired
    private FeedFilterController filterController;

    @Test
    public void contextLoads() {
    }

    @Test
    public void testEmptyFilter() throws Exception {
        filterController.filterFeed(Language.de, Collections.emptySet(), System.out);
    }

    @Test
    public void testFilterVhost() throws Exception {
        filterController.filterFeed(Language.de, Collections.singleton("vhost"), System.out);
    }

    @Test
    public void testFilterEverything() throws Exception {
        ImmutableSet<String> terms = ImmutableSet.of("vhost", "sql");
        filterController.filterFeed(Language.de, terms, System.out);
    }
}


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.LanguageServices.Implementation.F1Help

Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Help
    <ExportLanguageService(GetType(IHelpContextService), LanguageNames.VisualBasic), [Shared]>
    Partial Friend Class VisualBasicHelpContextService
        Inherits AbstractHelpContextService

        <ImportingConstructor>
        <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
        Public Sub New()
        End Sub

        Public Overrides ReadOnly Property Language As String
            Get
                Return "VB"
            End Get
        End Property

        Public Overrides ReadOnly Property Product As String
            Get
                Return "VB"
            End Get
        End Property

        Public Overrides Async Function GetHelpTermAsync(document As Document, span As TextSpan, cancellationToken As CancellationToken) As Task(Of String)
            Dim tree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False)
            Dim token = tree.GetRoot(cancellationToken).FindToken(span.Start, findInsideTrivia:=True)

            If TokenIsHelpKeyword(token) Then
                Return "vb." + token.Text
            End If

            If token.Span.IntersectsWith(span) OrElse token.GetAncestor(Of XmlElementSyntax)() IsNot Nothing Then
                Dim visitor = New Visitor(token.Span, Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False), document.Project.Solution.Workspace.Kind <> WorkspaceKind.MetadataAsSource, Me, cancellationToken)
                visitor.Visit(token.Parent)
                Return visitor.result
            End If

            Dim trivia = tree.GetRoot(cancellationToken).FindTrivia(span.Start, findInsideTrivia:=True)

            Dim text = If(trivia.ToFullString(), String.Empty).Replace(" ", "").TrimStart("'"c)
            If text.StartsWith("TODO:", StringComparison.CurrentCultureIgnoreCase) Then
                Return HelpKeywords.TaskListUserComments
            End If

            If trivia.IsKind(SyntaxKind.CommentTrivia) Then
                Return "vb.Rem"
            End If

            Return String.Empty
        End Function

        Private Shared Function TokenIsHelpKeyword(token As SyntaxToken) As Boolean
            Return token.IsKind(SyntaxKind.SharedKeyword, SyntaxKind.WideningKeyword, SyntaxKind.CTypeKeyword, SyntaxKind.NarrowingKeyword,
                                SyntaxKind.OperatorKeyword, SyntaxKind.AddHandlerKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.AnsiKeyword,
                                SyntaxKind.AutoKeyword, SyntaxKind.UnicodeKeyword, SyntaxKind.HandlesKeyword, SyntaxKind.NotKeyword)
        End Function

        Private Shared Function FormatNamespaceOrTypeSymbol(symbol As INamespaceOrTypeSymbol) As String
            If symbol.IsAnonymousType() Then
                Return HelpKeywords.AnonymousType
            End If

            Dim displayString = symbol.ToDisplayString(TypeFormat)
            If symbol.GetTypeArguments().Any() Then
                Return $"{displayString}`{symbol.GetTypeArguments().Length}"
            End If

            Return displayString
        End Function

        Public Overloads Overrides Function FormatSymbol(symbol As ISymbol) As String
            Return FormatSymbol(symbol, isContainingType:=False)
        End Function

        Private Overloads Function FormatSymbol(symbol As ISymbol, isContainingType As Boolean) As String
            Dim symbolType = symbol.GetSymbolType()

            If TypeOf symbolType Is IArrayTypeSymbol Then
                symbolType = DirectCast(symbolType, IArrayTypeSymbol).ElementType
            End If

            If (symbolType IsNot Nothing AndAlso symbolType.IsAnonymousType) OrElse symbol.IsAnonymousType() OrElse symbol.IsAnonymousTypeProperty() Then
                Return HelpKeywords.AnonymousType
            End If

            If symbol.MatchesKind(SymbolKind.Alias, SymbolKind.Local, SymbolKind.Parameter, SymbolKind.RangeVariable) Then
                Return FormatNamespaceOrTypeSymbol(symbol.GetSymbolType())
            End If

            If Not isContainingType AndAlso TypeOf symbol Is INamedTypeSymbol Then
                Dim type = DirectCast(symbol, INamedTypeSymbol)
                If type.SpecialType <> SpecialType.None Then
                    Return "vb." + type.ToDisplayString(SpecialTypeFormat)
                End If
            End If

            If TypeOf symbol Is ITypeSymbol OrElse TypeOf symbol Is INamespaceSymbol Then
                Return FormatNamespaceOrTypeSymbol(DirectCast(symbol, INamespaceOrTypeSymbol))
            End If

            Dim containingType = FormatSymbol(symbol.ContainingType, isContainingType:=True)
            Dim name = symbol.ToDisplayString(NameFormat)

            If symbol.IsConstructor() Then
                Return $"{containingType}.New"
            End If

            Dim arity = symbol.GetArity()
            If arity > 0 Then
                Return $"{containingType}.{name}``{arity}"
            End If

            Return $"{containingType}.{name}"
        End Function
    End Class
End Namespace


text:
require 'exogenesis/support/passenger'

# Manages Homebrew - the premier package manager for Mac OS
class Homebrew < Passenger
  INSTALL_SCRIPT = 'https://raw.github.com/mxcl/homebrew/go'
  TEARDOWN_SCRIPT = 'https://gist.github.com/mxcl/1173223/raw/a833ba44e7be8428d877e58640720ff43c59dbad/uninstall_homebrew.sh'

  register_as :homebrew
  needs :brews
  with_emoji :beer

  def up
    install_homebrew
    install_missing_brews
    update_existing_brews
  end

  def clean
    execute 'Clean Up', 'brew cleanup'
  end

  def down
    execute 'Teardown', "\\curl -L #{TEARDOWN_SCRIPT} | bash -s"
  end

  private

  def install_homebrew
    if command_exists? 'brew'
      skip_task 'Install Homebrew'
    else
      execute_interactive 'Install Homebrew', "ruby -e \"$(curl -fsSL #{INSTALL_SCRIPT})\""
    end
  end

  def install_missing_brews
    each_brew_to_install do |brew, options|
      install_package brew, options
    end
  end

  def update_existing_brews
    execute 'Updating Homebrew', 'brew update'

    if outdated_brews.length == 0
      skip_task 'Upgrade Brews'
    else
      info 'Outdated Brews', outdated_brews.join(', ')
      execute 'Upgrade Brews', 'brew upgrade'
    end
  end

  def each_brew_to_install
    brews.each do |brew|
      if brew.class == String
        name = brew
        options = []
      else
        name = brew.keys.first
        options = brew[name]
      end

      yield name, options unless installed_brews.include? name
    end
  end

  def installed_brews
    @installed_brews ||= silent_execute('brew ls').split(/\s/)
  end

  def outdated_brews
    @outdated_brews ||= silent_execute('brew outdated').split(/\s/)
  end

  def install_package(name, options)
    execute "Installing #{name}", "brew install #{name} #{options.join}"
  end
end


text:
package com.intive.patronage.toz.organization;

import com.intive.patronage.toz.base.repository.IdentifiableRepository;
import com.intive.patronage.toz.organization.model.db.OrganizationInfo;

interface OrganizationInfoRepository extends IdentifiableRepository<OrganizationInfo> {
}


text:
package it.reply.orchestrator.exception;

import org.springframework.core.NestedRuntimeException;

public class OrchestratorException extends NestedRuntimeException {

  private static final long serialVersionUID = 1L;

  public OrchestratorException(String message) {
    super(message);
  }

  public OrchestratorException(String message, Throwable cause) {
    super(message, cause);
  }

}


text:
import services from "./services";
import Routes from "./routes";
import { registerComponents } from "../common/module-utils";

import ChangeSetView from "./pages/view/change-set-view";

import ChangeSetOverview from "./components/overview/change-set-overview";
import ChangeSetPanel from "./components/panel/change-set-panel";
import ChangeSetSection from "./components/section/change-set-section";

export default () => {

    const module = angular.module("waltz.change.set", []);

    services(module);

    module.config(Routes);

    registerComponents(module, [
        ChangeSetView,
        ChangeSetOverview,
        ChangeSetPanel,
        ChangeSetSection
    ]);

    return module.name;
};


text:
package ro.isdc.wro.http.handler;

import static org.apache.commons.lang3.Validate.isTrue;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import ro.isdc.wro.WroRuntimeException;
import ro.isdc.wro.cache.CacheKey;
import ro.isdc.wro.model.group.Inject;
import ro.isdc.wro.model.resource.ResourceType;
import ro.isdc.wro.model.resource.support.change.ResourceWatcher;

/**
 * Triggers resource watcher check. This handler is not meant to be invoked publicly. It has a protection mechanism,
 * which allows only server-side handling.
 *
 * @author Alex Objelean
 * @created 9 Jan 2014
 * @since 1.7.3
 */
public class ResourceWatcherRequestHandler
    extends RequestHandlerSupport {
  private static final Logger LOG = LoggerFactory.getLogger(ResourceWatcherRequestHandler.class);
  /**
   * @VisibleForTesting
   */
  static final String PARAM_GROUP_NAME = "group";
  /**
   * @VisibleForTesting
   */
  static final String PARAM_RESOURCE_TYPE = "resourceType";
  /**
   * @VisibleForTesting
   */
  static final String PARAM_AUTH_KEY = "auth";
  static final String PATH_HANDLER = "resourceWatcher";
  /**
   * The alias of this {@link RequestHandler} used for configuration.
   */
  public static final String ALIAS = "resourceWatcher";
  @Inject
  private ResourceWatcher resourceWatcher;
  /**
   * A random string used to authorize request. This key is updated after each successful handle operation to avoid
   * hijacking.
   */
  private static String authorizationKey;

  public ResourceWatcherRequestHandler() {
    updateAuthorizationKey();
  }

  @Override
  public void handle(final HttpServletRequest request, final HttpServletResponse response)
      throws IOException {
    resourceWatcher.check(retrieveCacheKey(request));
    updateAuthorizationKey();
  }

  private CacheKey retrieveCacheKey(final HttpServletRequest request) {
    CacheKey cacheKey = null;
    final String resourceTypeAsString = request.getParameter(PARAM_RESOURCE_TYPE);
    final String groupName = request.getParameter(PARAM_GROUP_NAME);
    try {
      final ResourceType resourceType = ResourceType.get(resourceTypeAsString);
      isTrue(groupName != null);
      if (groupName != null) {
        LOG.debug("groupName={}, resourceType={}", groupName, resourceType);
        cacheKey = new CacheKey(groupName, resourceType);
      }
    } catch (final IllegalArgumentException e) {
      LOG.debug("groupName={}, resourceType={}", groupName, resourceTypeAsString);
      throw WroRuntimeException.wrap(e, "Cannot retrieve cacheKey from the request");
    }
    return cacheKey;
  }

  @Override
  public boolean accept(final HttpServletRequest request) {
    // Authorize only server-side included request (performed by {@link DispatcherStreamLocator}). Any public access to
    // this request handler is forbidden.
    final boolean isHandlerRequest = isHandlerRequest(request);
    return isHandlerRequest && isAuthorized(request);
  }

  private boolean isAuthorized(final HttpServletRequest request) {
    final String actualKey = request.getParameter(PARAM_AUTH_KEY);
    final boolean isAuthorized = authorizationKey.equals(actualKey);
    if (!isAuthorized) {
      LOG.debug("Unauthorized request. actualKey={}, expected={}", actualKey, authorizationKey);
    }
    return isAuthorized;
  }

  /**
   * Checks if the provided url is a resource proxy request.
   *
   * @param url
   *          to check.
   * @return true if the provided url is a proxy resource.
   */
  private boolean isHandlerRequest(final HttpServletRequest request) {
    String apiHandlerValue = request.getParameter(PATH_API);
    return PATH_HANDLER.equals(apiHandlerValue) && retrieveCacheKey(request) != null;
  }

  /**
   * Updates the authorizationKey with an unique value.
   */
  private void updateAuthorizationKey() {
    authorizationKey = generateRandomKey();
  }

  /**
   * @VisibleForTesting
   * @return a random key used for authorization.
   */
  String generateRandomKey() {
    return UUID.randomUUID().toString();
  }

  /**
   * Computes the servlet context relative url to call this handler using a server-side invocation. Hides the details
   * about creating a valid url and providing the authorization key required to invoke this handler.
   */
  public static String createHandlerRequestPath(final CacheKey cacheKey, final HttpServletRequest request) {
    final String handlerQueryPath = getRequestHandlerPath(cacheKey.getGroupName(), cacheKey.getType());
    final String location = request.getServletPath() + handlerQueryPath;
    return location;
  }

  private static String getRequestHandlerPath() {
    return String.format("?%s=%s", PATH_API, PATH_HANDLER);
  }

  private static String getRequestHandlerPath(final String groupName, final ResourceType resourceType) {
    return String.format("%s&%s=%s&%s=%s&%s=%s", getRequestHandlerPath(), PARAM_GROUP_NAME, groupName,
        PARAM_RESOURCE_TYPE, resourceType.name(), PARAM_AUTH_KEY, authorizationKey);
  }
}