text:
package net.sf.webdav.methods;

import java.io.ByteArrayInputStream;

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

import net.sf.webdav.ITransaction;
import net.sf.webdav.IWebdavStore;
import net.sf.webdav.StoredObject;
import net.sf.webdav.WebdavStatus;
import net.sf.webdav.locking.ResourceLocks;
import net.sf.webdav.testutil.MockTest;

import org.jmock.Expectations;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.mock.web.DelegatingServletInputStream;

public class DoMoveTest extends MockTest {

    static IWebdavStore mockStore;
    static HttpServletRequest mockReq;
    static HttpServletResponse mockRes;
    static ITransaction mockTransaction;
    static byte[] resourceContent = new byte[] { '<', 'h', 'e', 'l', 'l', 'o',
            '/', '>' };
    static ByteArrayInputStream bais = new ByteArrayInputStream(resourceContent);
    static DelegatingServletInputStream dsis = new DelegatingServletInputStream(
            bais);

    static final String tmpFolder = "/tmp/tests";

    static final String sourceCollectionPath = tmpFolder + "/sourceFolder";
    static final String destCollectionPath = tmpFolder + "/destFolder";
    static final String sourceFilePath = sourceCollectionPath + "/sourceFile";
    static final String destFilePath = destCollectionPath + "/destFile";

    static final String overwritePath = destCollectionPath + "/sourceFolder";

    @BeforeClass
    public static void setUp() throws Exception {
        mockStore = _mockery.mock(IWebdavStore.class);
        mockReq = _mockery.mock(HttpServletRequest.class);
        mockRes = _mockery.mock(HttpServletResponse.class);
        mockTransaction = _mockery.mock(ITransaction.class);

    }

    @Test
    public void testMovingOfFileOrFolderIfReadOnlyIsTrue() throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockRes).sendError(WebdavStatus.SC_FORBIDDEN);
            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

    @Test
    public void testMovingOfaFileIfDestinationNotPresent() throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceFilePath));

                exactly(2).of(mockReq).getHeader("Destination");
                will(returnValue(destFilePath));

                one(mockReq).getServerName();
                will(returnValue("serverName"));

                one(mockReq).getContextPath();
                will(returnValue(""));

                one(mockReq).getPathInfo();
                will(returnValue(destFilePath));

                one(mockReq).getServletPath();
                will(returnValue("/servletPath"));

                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceFilePath));

                one(mockReq).getHeader("Overwrite");
                will(returnValue("F"));

                StoredObject sourceFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                StoredObject destFileSo = null;

                one(mockStore).getStoredObject(mockTransaction, destFilePath);
                will(returnValue(destFileSo));

                one(mockRes).setStatus(WebdavStatus.SC_CREATED);

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                one(mockStore).createResource(mockTransaction, destFilePath);

                one(mockStore).getResourceContent(mockTransaction,
                        sourceFilePath);
                will(returnValue(dsis));

                one(mockStore).setResourceContent(mockTransaction,
                        destFilePath, dsis, null, null);
                will(returnValue(8L));

                destFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction, destFilePath);
                will(returnValue(destFileSo));

                one(mockRes).setStatus(WebdavStatus.SC_NO_CONTENT);

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                one(mockStore).removeObject(mockTransaction, sourceFilePath);
            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, !readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, !readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, !readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

    @Test
    public void testMovingOfaFileIfDestinationIsPresentAndOverwriteFalse()
            throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceFilePath));

                exactly(2).of(mockReq).getHeader("Destination");
                will(returnValue(destFilePath));

                one(mockReq).getServerName();
                will(returnValue("server_name"));

                one(mockReq).getContextPath();
                will(returnValue(""));

                one(mockReq).getPathInfo();
                will(returnValue(destFilePath));

                one(mockReq).getServletPath();
                will(returnValue("servlet_path"));

                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceFilePath));

                one(mockReq).getHeader("Overwrite");
                will(returnValue("F"));

                StoredObject sourceFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                StoredObject destFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction, destFilePath);
                will(returnValue(destFileSo));

                one(mockRes).sendError(WebdavStatus.SC_PRECONDITION_FAILED);

            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, !readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, !readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, !readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

    @Test
    public void testMovingOfaFileIfDestinationIsPresentAndOverwriteTrue()
            throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceFilePath));

                exactly(2).of(mockReq).getHeader("Destination");
                will(returnValue(destFilePath));

                one(mockReq).getServerName();
                will(returnValue("server_name"));

                one(mockReq).getContextPath();
                will(returnValue(""));

                one(mockReq).getPathInfo();
                will(returnValue(destFilePath));

                one(mockReq).getServletPath();
                will(returnValue("servlet_path"));

                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceFilePath));

                one(mockReq).getHeader("Overwrite");
                will(returnValue("T"));

                StoredObject sourceFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                StoredObject destFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction, destFilePath);
                will(returnValue(destFileSo));

                one(mockRes).setStatus(WebdavStatus.SC_NO_CONTENT);

                one(mockStore).getStoredObject(mockTransaction, destFilePath);
                will(returnValue(destFileSo));

                one(mockStore).removeObject(mockTransaction, destFilePath);

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                one(mockStore).createResource(mockTransaction, destFilePath);

                one(mockStore).getResourceContent(mockTransaction,
                        sourceFilePath);
                will(returnValue(dsis));

                one(mockStore).setResourceContent(mockTransaction,
                        destFilePath, dsis, null, null);
                will(returnValue(8L));

                one(mockStore).getStoredObject(mockTransaction, destFilePath);
                will(returnValue(destFileSo));

                one(mockRes).setStatus(WebdavStatus.SC_NO_CONTENT);

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                one(mockStore).removeObject(mockTransaction, sourceFilePath);
            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, !readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, !readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, !readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

    @Test
    public void testMovingOfaFileIfSourceNotPresent() throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceFilePath));

                exactly(2).of(mockReq).getHeader("Destination");
                will(returnValue(destFilePath));

                one(mockReq).getServerName();
                will(returnValue("server_name"));

                one(mockReq).getContextPath();
                will(returnValue(""));

                one(mockReq).getPathInfo();
                will(returnValue(destFilePath));

                one(mockReq).getServletPath();
                will(returnValue("servlet_path"));

                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceFilePath));

                one(mockReq).getHeader("Overwrite");
                will(returnValue("F"));

                StoredObject sourceFileSo = null;

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                one(mockRes).sendError(WebdavStatus.SC_NOT_FOUND);
            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, !readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, !readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, !readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

    @Test
    public void testMovingIfSourcePathEqualsDestinationPath() throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(destFilePath));

                exactly(2).of(mockReq).getHeader("Destination");
                will(returnValue(destFilePath));

                one(mockReq).getServerName();
                will(returnValue("server_name"));

                one(mockReq).getContextPath();
                will(returnValue(""));

                one(mockReq).getPathInfo();
                will(returnValue(destFilePath));

                one(mockReq).getServletPath();
                will(returnValue("servlet_path"));

                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(destFilePath));

                one(mockRes).sendError(WebdavStatus.SC_FORBIDDEN);
            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, !readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, !readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, !readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

    @Test
    public void testMovingOfaCollectionIfDestinationIsNotPresent()
            throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceCollectionPath));

                exactly(2).of(mockReq).getHeader("Destination");
                will(returnValue(destCollectionPath));

                one(mockReq).getServerName();
                will(returnValue("server_name"));

                one(mockReq).getContextPath();
                will(returnValue(""));

                one(mockReq).getPathInfo();
                will(returnValue(destCollectionPath));

                one(mockReq).getServletPath();
                will(returnValue("servlet_path"));

                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceCollectionPath));

                one(mockReq).getHeader("Overwrite");
                will(returnValue("F"));

                StoredObject sourceCollectionSo = initFolderStoredObject();

                one(mockStore).getStoredObject(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceCollectionSo));

                StoredObject destCollectionSo = null;

                one(mockStore).getStoredObject(mockTransaction,
                        destCollectionPath);
                will(returnValue(destCollectionSo));

                one(mockRes).setStatus(WebdavStatus.SC_CREATED);

                one(mockStore).getStoredObject(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceCollectionSo));

                one(mockStore)
                        .createFolder(mockTransaction, destCollectionPath);

                one(mockReq).getHeader("Depth");
                will(returnValue(null));

                String[] sourceChildren = new String[] { "sourceFile" };

                one(mockStore).getChildrenNames(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceChildren));

                StoredObject sourceFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction,
                        sourceCollectionPath + "/sourceFile");
                will(returnValue(sourceFileSo));

                one(mockStore).createResource(mockTransaction,
                        destCollectionPath + "/sourceFile");

                one(mockStore).getResourceContent(mockTransaction,
                        sourceCollectionPath + "/sourceFile");
                will(returnValue(dsis));

                one(mockStore).setResourceContent(mockTransaction,
                        destCollectionPath + "/sourceFile", dsis, null, null);
                will(returnValue(8L));

                StoredObject movedSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction,
                        destCollectionPath + "/sourceFile");
                will(returnValue(movedSo));

                one(mockRes).setStatus(WebdavStatus.SC_NO_CONTENT);

                one(mockStore).getStoredObject(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceCollectionSo));

                sourceChildren = new String[] { "sourceFile" };

                one(mockStore).getChildrenNames(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceChildren));

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                one(mockStore).removeObject(mockTransaction, sourceFilePath);

                one(mockStore).removeObject(mockTransaction,
                        sourceCollectionPath);
            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, !readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, !readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, !readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

    @Test
    public void testMovingOfaCollectionIfDestinationIsPresentAndOverwriteFalse()
            throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceCollectionPath));

                exactly(2).of(mockReq).getHeader("Destination");
                will(returnValue(destCollectionPath));

                one(mockReq).getServerName();
                will(returnValue("server_name"));

                one(mockReq).getContextPath();
                will(returnValue(""));

                one(mockReq).getPathInfo();
                will(returnValue(destCollectionPath));

                one(mockReq).getServletPath();
                will(returnValue("servlet_path"));

                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceCollectionPath));

                one(mockReq).getHeader("Overwrite");
                will(returnValue("F"));

                StoredObject sourceCollectionSo = initFolderStoredObject();

                one(mockStore).getStoredObject(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceCollectionSo));

                StoredObject destCollectionSo = initFolderStoredObject();

                one(mockStore).getStoredObject(mockTransaction,
                        destCollectionPath);
                will(returnValue(destCollectionSo));

                one(mockRes).sendError(WebdavStatus.SC_PRECONDITION_FAILED);
            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, !readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, !readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, !readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

    @Test
    public void testMovingOfaCollectionIfDestinationIsPresentAndOverwriteTrue()
            throws Exception {

        _mockery.checking(new Expectations() {
            {
                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceCollectionPath));

                exactly(2).of(mockReq).getHeader("Destination");
                will(returnValue(overwritePath));

                one(mockReq).getServerName();
                will(returnValue("server_name"));

                one(mockReq).getContextPath();
                will(returnValue(""));

                one(mockReq).getPathInfo();
                will(returnValue(overwritePath));

                one(mockReq).getServletPath();
                will(returnValue("servlet_path"));

                one(mockReq).getAttribute("javax.servlet.include.request_uri");
                will(returnValue(null));

                one(mockReq).getPathInfo();
                will(returnValue(sourceCollectionPath));

                one(mockReq).getHeader("Overwrite");
                will(returnValue("T"));

                StoredObject sourceCollectionSo = initFolderStoredObject();

                one(mockStore).getStoredObject(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceCollectionSo));

                StoredObject destCollectionSo = initFolderStoredObject();

                one(mockStore).getStoredObject(mockTransaction, overwritePath);
                will(returnValue(destCollectionSo));

                one(mockRes).setStatus(WebdavStatus.SC_NO_CONTENT);

                one(mockStore).getStoredObject(mockTransaction, overwritePath);
                will(returnValue(destCollectionSo));

                one(mockStore).getChildrenNames(mockTransaction, overwritePath);
                will(returnValue(destChildren));

                StoredObject destFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction,
                        overwritePath + "/destFile");
                will(returnValue(destFileSo));

                one(mockStore).removeObject(mockTransaction,
                        overwritePath + "/destFile");

                one(mockStore).removeObject(mockTransaction, overwritePath);

                one(mockStore).getStoredObject(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceCollectionSo));

                one(mockStore).createFolder(mockTransaction, overwritePath);

                one(mockReq).getHeader("Depth");
                will(returnValue(null));

                one(mockStore).getChildrenNames(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceChildren));

                StoredObject sourceFileSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                one(mockStore).createResource(mockTransaction,
                        overwritePath + "/sourceFile");

                one(mockStore).getResourceContent(mockTransaction,
                        sourceFilePath);
                will(returnValue(dsis));

                one(mockStore).setResourceContent(mockTransaction,
                        overwritePath + "/sourceFile", dsis, null, null);

                StoredObject movedSo = initFileStoredObject(resourceContent);

                one(mockStore).getStoredObject(mockTransaction,
                        overwritePath + "/sourceFile");
                will(returnValue(movedSo));

                one(mockRes).setStatus(WebdavStatus.SC_NO_CONTENT);

                one(mockStore).getStoredObject(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceCollectionSo));

                sourceChildren = new String[] { "sourceFile" };

                one(mockStore).getChildrenNames(mockTransaction,
                        sourceCollectionPath);
                will(returnValue(sourceChildren));

                one(mockStore).getStoredObject(mockTransaction, sourceFilePath);
                will(returnValue(sourceFileSo));

                one(mockStore).removeObject(mockTransaction, sourceFilePath);

                one(mockStore).removeObject(mockTransaction,
                        sourceCollectionPath);
            }
        });

        ResourceLocks resLocks = new ResourceLocks();
        DoDelete doDelete = new DoDelete(mockStore, resLocks, !readOnly);
        DoCopy doCopy = new DoCopy(mockStore, resLocks, doDelete, !readOnly);

        DoMove doMove = new DoMove(resLocks, doDelete, doCopy, !readOnly);

        doMove.execute(mockTransaction, mockReq, mockRes);

        _mockery.assertIsSatisfied();
    }

}


text:
'use strict';

var React = require('react');

module.exports = React.createClass({
  handleClick: function(e) {
    chrome.tabs.create({ url: this.props.url, active: true });
  },
  render: function() {
    return(
      <button onClick={this.handleClick} className='mdl-button mdl-js-button mdl-button--primary'>
        {this.props.text}
      </button>
    );
  }
});

redpajama_set_name: RedPajamaGithub


text:
import uuid
import unittest
import json
import datetime
from six import ensure_binary
from six.moves.urllib.parse import urlencode
from six import BytesIO
from tornado.httpclient import HTTPRequest
from scrapydd.models import session_scope, Node, SpiderExecutionQueue, HistoricalJob, NodeKey
from scrapydd.poster.encode import multipart_encode
from scrapydd.main import make_app
from scrapydd.webhook import WebhookDaemon
from scrapydd.settting import SpiderSettingLoader
from scrapydd.schedule import SchedulerManager
from scrapydd.nodes import NodeManager
from scrapydd.config import Config
from scrapydd.security import generate_digest, generate_random_string
from scrapydd.stream import MultipartRequestBodyProducer
from tests.base import AppTest

class NodeTest(AppTest):
    def register_node(self):
        with session_scope() as session:
            session.query(Node).delete()

        response = self.fetch('/nodes', method="POST", body="")
        self.assertEqual(200, response.code)
        return json.loads(response.body)['id']

class NodeSecureTest(NodeTest):
    def setUp(self):
        super(NodeSecureTest, self).setUp()
        with session_scope() as session:
            node = self.node_manager.node_online(session, None, None, None)

            nodekey = NodeKey()
            nodekey.key = str(uuid.uuid4())
            nodekey.create_at = datetime.datetime.now()
            nodekey.secret_key = generate_random_string(32)
            session.add(nodekey)
            session.commit()
            self.node_key = nodekey
            self.node_id = node.id

    def get_app(self):
        config = Config()
        scheduler_manager = SchedulerManager(config=config)
        scheduler_manager.init()
        node_manager = NodeManager(scheduler_manager)
        node_manager.init()
        webhook_daemon = WebhookDaemon(config, SpiderSettingLoader(), scheduler_manager)
        webhook_daemon.init()
        self.node_manager = node_manager
        return make_app(scheduler_manager, node_manager, webhook_daemon, secret_key='123',
                        enable_node_registration=True)

    def register_node(self):
        node_key = self.node_manager.create_node_key()
        path = '/nodes/register'
        method = 'POST'
        query = ''
        body = ''
        headers = {'Authorization': '%s %s %s' % ('HMAC',
                                                  node_key.key,
                                                  generate_digest(node_key.secret_key, method, path, query, body))}
        response = self.fetch(path, method=method, body=body, headers=headers)
        self.assertEqual(200, response.code)
        self.node_key = node_key
        new_node_id = json.loads(response.body)['id']
        return new_node_id

    def fetch_secure(self, path, **kwargs):
        auth = kwargs.pop('auth', True)
        method = kwargs.pop('method', 'GET')
        headers = kwargs.pop('headers', {})
        body = kwargs.pop('body', None)
        if auth:
            body_binary = ensure_binary(body) if body else b''
            digest = generate_digest(self.node_key.secret_key, method, path, '', body_binary)
            key = ensure_binary(self.node_key.key)
            digest = ensure_binary(digest)
            headers['Authorization'] = b'%s %s %s' % (b'HMAC', key, digest)

        return super(NodeSecureTest, self).fetch(path, method=method, body=body, headers=headers, **kwargs)

class NodesHandlerTest(AppTest):
    def test_register(self):
        with session_scope() as session:
            session.query(Node).delete()

        response = self.fetch('/nodes', method="POST", body="")

        with session_scope() as session:
            new_node = session.query(Node).first()

        self.assertEqual(200, response.code)
        self.assertEqual('127.0.0.1', new_node.client_ip)
        self.assertEqual(datetime.date.today(), new_node.create_time.date())
        self.assertEqual(datetime.date.today(), new_node.last_heartbeat.date())
        self.assertEqual(True, new_node.isalive)
        self.assertEqual(None, new_node.tags)

    def test_register_realip(self):
        with session_scope() as session:
            session.query(Node).delete()

        headers = {'X-Real-IP': '1.2.3.4'}
        response = self.fetch('/nodes',
                              method="POST", headers=headers, body="")

        with session_scope() as session:
            new_node = session.query(Node).first()

        self.assertEqual(200, response.code)
        self.assertEqual('1.2.3.4', new_node.client_ip)
        self.assertEqual(datetime.date.today(), new_node.create_time.date())
        self.assertEqual(datetime.date.today(), new_node.last_heartbeat.date())
        self.assertEqual(True, new_node.isalive)
        self.assertEqual(None, new_node.tags)

class GetNextJobTest(NodeTest):
    def test_next_job(self):
        node_id = self.register_node()
        post_data = {'node_id': node_id}
        headers = {'X-Dd-Nodeid' : str(node_id)}
        body = urlencode(post_data)
        path = '/executing/next_task'
        response = self.fetch(path, method='POST', body=body, headers=headers)
        self.assertEqual(200, response.code)

@unittest.skip
class GetNextJobSecureTest(NodeTest):
    def test_next_job_wrong_app_key(self):
        node_id = self.register_node()
        post_data = {'node_id': node_id}
        body = urlencode(post_data)
        path = '/api/v1/jobs/next'
        request = HTTPRequest(url=self.get_url(path), method='POST', body=body, app_key='somethingwrong',
                                        app_secret=self.appsecret)
        response = self.fetch(request)
        self.assertEqual(403, response.code)

    def test_next_job_wrong_app_secret(self):
        node_id = self.register_node()
        post_data = {'node_id': node_id}
        body = urlencode(post_data)
        path = '/api/v1/jobs/next'
        request = HTTPRequest(url=self.get_url(path), method='POST', body=body, app_key=self.appkey,
                                        app_secret='somethingwrong')
        response = self.fetch(request)
        self.assertEqual(403, response.code)

class ExecuteCompleteHandlerTest(NodeTest):
    def test_job_complete(self):
        project_name = 'test_project'
        spider_name = 'success_spider'

        node_id = self.register_node()

        # schedule a job
        with session_scope() as session:
            session.query(SpiderExecutionQueue).delete()
            session.commit()
        run_spider_post_data =  {'project': project_name, 'spider': spider_name}
        res = self.fetch('/schedule.json', method='POST', body=urlencode(run_spider_post_data))
        self.assertEqual(200, res.code)

        # fetch a job
        next_job_post_data = {'node_id': node_id}
        headers = {'X-Dd-Nodeid': str(node_id)}
        res = self.fetch('/executing/next_task', method='POST', body=urlencode(next_job_post_data),
                         headers=headers)
        self.assertEqual(200, res.code)
        task_id = json.loads(res.body)['data']['task']['task_id']

        # job start
        post_data = {'pid' : '1'}
        headers = {'X-Dd-Nodeid': str(node_id)}
        res = self.fetch('/jobs/%s/start' % task_id, method='POST', headers=headers, body=urlencode(post_data))
        self.assertEqual(200, res.code)

        # complete this job
        post_data = {'task_id': task_id,
                     'status': 'success'}
        post_data['log'] = BytesIO(b'some logs')
        post_data['items'] = BytesIO(b'{"a" : "some items"}')
        datagen, headers = multipart_encode(post_data)
        headers['X-Dd-Nodeid'] = str(node_id)
        #
        res = self.fetch('/executing/complete', method='POST', headers=headers,
                         body_producer=MultipartRequestBodyProducer(datagen))
        self.assertEqual(200, res.code)

        with session_scope() as session:
            complete_job = session.query(HistoricalJob).filter_by(id=task_id).first()
            self.assertIsNotNone(complete_job)
            self.assertEqual(2, complete_job.status)

class ExecuteCompleteHandlerSecureTest(NodeSecureTest):
    def test_job_complete(self):
        project_name = 'test_project'
        spider_name = 'success_spider'

        node_id = self.register_node()

        # schedule a job
        with session_scope() as session:
            session.query(SpiderExecutionQueue).delete()
            session.commit()
        run_spider_post_data =  {'project': project_name, 'spider': spider_name}
        res = self.fetch('/schedule.json', method='POST', body=urlencode(run_spider_post_data))
        self.assertEqual(200, res.code)

        # fetch a job
        next_job_post_data = {'node_id': node_id}
        headers = {'X-Dd-Nodeid': str(node_id)}
        res = self.fetch_secure('/executing/next_task', method='POST', body=urlencode(next_job_post_data),
                         headers=headers)
        self.assertEqual(200, res.code)
        task_id = json.loads(res.body)['data']['task']['task_id']

        # job start
        post_data = {'pid' : '1'}
        headers = {'X-Dd-Nodeid': str(node_id)}
        res = self.fetch_secure('/jobs/%s/start' % task_id, method='POST', headers=headers, body=urlencode(post_data))
        self.assertEqual(200, res.code)

        # complete this job
        post_data = {'task_id': task_id,
                     'status': 'success'}
        post_data['log'] = BytesIO(b'some logs')
        post_data['items'] = BytesIO(b'{"a" : "some items"}')
        datagen, headers = multipart_encode(post_data)
        headers['X-Dd-Nodeid'] = str(node_id)
        res = self.fetch_secure('/executing/complete', method='POST', headers=headers,
                                body_producer=MultipartRequestBodyProducer(datagen))
        self.assertEqual(200, res.code)

        with session_scope() as session:
            complete_job = session.query(HistoricalJob).filter_by(id=task_id).first()
            self.assertIsNotNone(complete_job)
            self.assertEqual(2, complete_job.status)

class NodeHeartbeatHandler(NodeTest):
    def test_heartbeat(self):
        node_id = self.register_node()
        headers = {'X-Dd-Nodeid': str(node_id)}
        res = self.fetch('/nodes/%d/heartbeat' % node_id, method='POST', body=b'', headers=headers)
        self.assertEqual(200, res.code)

class NodesHandlerSecureTest(NodeSecureTest):
    def test_post_new_node_with_key(self):
        node_key = self.node_manager.create_node_key()
        headers = {'Authorization': '%s %s %s' % ('HMAC',
                                                  node_key.key,
                                                  generate_digest(node_key.secret_key, 'POST', '/nodes', '', ''))}
        response = self.fetch('/nodes', method="POST", body="", headers=headers)
        self.assertEqual(403, response.code)

    def test_post_exist_node_with_key(self):
        self.node_key = self.node_manager.create_node_key()
        res = self.fetch_secure('/nodes/register', method='POST', body='')
        self.assertEqual(200, res.code)
        node_id = json.loads(res.body)['id']

        headers = {'Authorization': '%s %s %s' % ('HMAC',
                                                  self.node_key.key,
                                                  generate_digest(self.node_key.secret_key, 'POST', '/nodes', '', ''))}
        response = self.fetch('/nodes', method="POST", body="", headers=headers)
        self.assertEqual(200, response.code)
        new_node_id = json.loads(response.body)['id']
        self.assertTrue(new_node_id > 0)

    def test_post_without_auth(self):
        response = self.fetch('/nodes', method="POST", body="")
        self.assertEqual(403, response.code)

    def test_post_real_ip(self):
        self.node_key = self.node_manager.create_node_key()
        res = self.fetch_secure('/nodes/register', method='POST', body='')
        self.assertEqual(200, res.code)
        node_id = json.loads(res.body)['id']

        headers = {'Authorization': '%s %s %s' % ('HMAC',
                                                  self.node_key.key,
                                                  generate_digest(self.node_key.secret_key, 'POST', '/nodes', '', ''))}
        headers['X-Real-IP'] = '1.2.3.4'
        response = self.fetch('/nodes', method="POST", body="", headers=headers)
        self.assertEqual(200, response.code)
        new_node_id = json.loads(response.body)['id']
        self.assertTrue(new_node_id > 0)
        with session_scope() as session:
            active_node = session.query(Node).get(new_node_id)
            self.assertEqual(active_node.client_ip, '1.2.3.4')

class RegisterNodeHandlerSecureTest(NodeSecureTest):
    def test_post(self):
        node_key = self.node_manager.create_node_key()
        headers = {'Authorization': '%s %s %s' % ('HMAC',
                                                  node_key.key,
                                                  generate_digest(node_key.secret_key, 'POST', '/nodes/register', '', ''))}
        response = self.fetch('/nodes/register', method="POST", body="",
                              headers=headers)
        self.assertEqual(200, response.code)
        new_node_id = json.loads(response.body)['id']
        self.assertTrue(new_node_id > 0)
        with session_scope() as session:
            node = session.query(Node).get(new_node_id)
            self.assertEqual(node.node_key_id, node_key.id)

            updated_node_key = session.query(NodeKey).get(node_key.id)
            self.assertEqual(updated_node_key.used_node_id, new_node_id)

    def test_post_get_real_ip(self):
        node_key = self.node_manager.create_node_key()
        headers = {'Authorization': '%s %s %s' % ('HMAC',
                                                  node_key.key,
                                                  generate_digest(node_key.secret_key, 'POST', '/nodes/register', '',
                                                                  ''))}
        headers['x-real-ip'] = '1.2.3.4'
        response = self.fetch('/nodes/register', method="POST", body="",
                              headers=headers)
        self.assertEqual(200, response.code)
        new_node_id = json.loads(response.body)['id']
        self.assertTrue(new_node_id > 0)
        with session_scope() as session:
            node = session.query(Node).get(new_node_id)
            self.assertEqual(node.node_key_id, node_key.id)
            self.assertEqual(node.client_ip, '1.2.3.4')

            updated_node_key = session.query(NodeKey).get(node_key.id)
            self.assertEqual(updated_node_key.used_node_id, new_node_id)

class JobEggHandlerTest(NodeSecureTest):
    def test_get(self):
        project_name = 'test_project'
        spider_name = 'success_spider'

        node_id = self.register_node()

        # schedule a job
        with session_scope() as session:
            session.query(SpiderExecutionQueue).delete()
            session.commit()
        run_spider_post_data = {'project': project_name,
                                'spider': spider_name}
        res = self.fetch('/schedule.json', method='POST',
                         body=urlencode(run_spider_post_data))
        self.assertEqual(200, res.code)

        # fetch a job
        next_job_post_data = {'node_id': node_id}
        headers = {'X-Dd-Nodeid': str(node_id)}
        res = self.fetch_secure('/executing/next_task', method='POST',
                                body=urlencode(next_job_post_data),
                                headers=headers)
        self.assertEqual(200, res.code)
        task_id = json.loads(res.body)['data']['task']['task_id']
        res = self.fetch_secure(f'/jobs/{task_id}/egg', method='GET',
                                headers=headers)
        self.assertEqual(200, res.code)

class CreateNodeSessionHandlerTest(NodeTest):
    def test_post(self):
        res = self.fetch('/v1/nodeSessions', method='POST', body='')
        self.assertEqual(200, res.code)
        res_data = json.loads(res.body)
        self.assertIsNotNone(res_data['id'])
        self.assertIsNotNone(res_data['node_id'])

    def test_post_body_tags(self):
        post_data = {
        }
        body = urlencode(post_data, doseq=True)
        res = self.fetch('/v1/nodeSessions', method='POST', body=body)
        self.assertEqual(200, res.code)
        res_data = json.loads(res.body)
        node_id = res_data['node_id']
        session_id = res_data['id']

        self.assertTrue(node_id > 0)
        self.assertTrue(session_id > 0)

        #headers = {'X-Dd-Nodeid': str(node_id)}
        #res = self.fetch('/v1/nodes/%s' % node_id, headers=headers)
        res = self.fetch('/v1/nodes/%s' % node_id)
        self.assertEqual(200, res.code)
        res_data = json.loads(res.body)

class NodeSessionInstanceHeartbeatHandlerTest(NodeTest):
    def session_login(self):
        post_data = {
            'tags': ''
        }
        res = self.fetch('/v1/nodeSessions', method='POST',
                         body=urlencode(post_data))
        self.assertEqual(200, res.code)
        res_data = json.loads(res.body)
        self.node_id = res_data['node_id']
        self.session_id = res_data['id']

    def test_post(self):
        post_data = {}
        self.session_login()
        headers = {'X-Dd-Nodeid': str(self.node_id)}
        res = self.fetch('/v1/nodeSessions/%s:heartbeat' % self.session_id,
                         method='POST', body=urlencode(post_data),
                         headers=headers,
                         allow_nonstandard_methods=True)
        self.assertEqual(200, res.code)
        res_data = json.loads(res.body)
        self.assertEqual(res_data['kill_job_ids'], [])
        self.assertEqual(res_data['new_job_available'], False)

    def test_post_running_jobs(self):
        job_ids = ['1', '2']
        post_data = {
            'running_job_ids': job_ids
        }
        self.session_login()
        res = self.fetch('/v1/nodeSessions/%s:heartbeat' % self.session_id,
                         method='POST', body=urlencode(post_data, doseq=True),
                         allow_nonstandard_methods=True)
        self.assertEqual(200, res.code)
        res_data = json.loads(res.body)
        self.assertEqual(res_data['kill_job_ids'], job_ids)
        self.assertEqual(res_data['new_job_available'], False)

class NodeCollectionHandlerTest(NodeTest):
    def test_post(self):
        new_key = self._app.settings.get('node_manager').create_node_key()

        # pass parameters other than body by query parameter
        # according to api design guide
        # https://cloud.google.com/apis/design/standard_methods#create
        res = self.fetch('/v1/nodes' + '?node_key=' + new_key.key,
                         method='POST',
                         body='')
        self.assertEqual(200, res.code)

        res_data = json.loads(res.body)

        self.assertIsNotNone(res_data['name'])
        self.assertIsNotNone(res_data['id'])
        self.assertIsNotNone(res_data['display_name'])
        self.assertIsNotNone(res_data['tags'])
        self.assertEqual(len(res_data['tags']), 0)
        self.assertIsNotNone(res_data['is_online'])
        self.assertIsNotNone(res_data['client_ip'])

    def test_post_full(self):
        new_key = self._app.settings.get('node_manager').create_node_key()
        post_data = {
            'tags': ['a', 'bb', 'ccc']
        }

        res = self.fetch('/v1/nodes' + '?node_key=' + new_key.key,
                         method='POST',
                         body=urlencode(post_data, doseq=True))
        self.assertEqual(200, res.code)

        res_data = json.loads(res.body)

        self.assertIsNotNone(res_data['name'])
        self.assertIsNotNone(res_data['id'])
        self.assertIsNotNone(res_data['display_name'])
        self.assertIsNotNone(res_data['tags'])
        self.assertEqual(len(res_data['tags']), 3)
        self.assertEqual(res_data['tags'], ['a', 'bb', 'ccc'])
        self.assertIsNotNone(res_data['is_online'])
        self.assertIsNotNone(res_data['client_ip'])

    def test_post_json(self):
        new_key = self._app.settings.get('node_manager').create_node_key()
        post_data = {}

        res = self.fetch('/v1/nodes' + '?node_key=' + new_key.key,
                         method='POST',
                         body=json.dumps(post_data),
                         headers={'Content-Type': 'application/json'})
        self.assertEqual(200, res.code)

        res_data = json.loads(res.body)

        self.assertIsNotNone(res_data['name'])
        self.assertIsNotNone(res_data['id'])
        self.assertIsNotNone(res_data['display_name'])
        self.assertIsNotNone(res_data['tags'])
        self.assertEqual(len(res_data['tags']), 0)
        self.assertIsNotNone(res_data['is_online'])
        self.assertIsNotNone(res_data['client_ip'])

    def test_post_json_full(self):
        new_key = self._app.settings.get('node_manager').create_node_key()
        post_data = {
            'tags': ['a', 'bb', 'ccc']
        }

        res = self.fetch('/v1/nodes' + '?node_key=' + new_key.key,
                         method='POST',
                         body=json.dumps(post_data),
                         headers={'Content-Type': 'application/json'})
        self.assertEqual(200, res.code)

        res_data = json.loads(res.body)

        self.assertIsNotNone(res_data['name'])
        self.assertIsNotNone(res_data['id'])
        self.assertIsNotNone(res_data['display_name'])
        self.assertIsNotNone(res_data['tags'])
        self.assertEqual(len(res_data['tags']), 3)
        self.assertEqual(res_data['tags'], ['a', 'bb', 'ccc'])
        self.assertIsNotNone(res_data['is_online'])
        self.assertIsNotNone(res_data['client_ip'])

    def test_post_no_node_key(self):
        new_key = self._app.settings.get('node_manager').create_node_key()
        post_data = {
            'tags': ['a', 'bb', 'ccc']
        }

        res = self.fetch('/v1/nodes',
                         method='POST',
                         body=json.dumps(post_data),
                         headers={'Content-Type': 'application/json'})
        # no NodeKey provided, should return 400
        self.assertEqual(400, res.code)

    def test_post_invalid_node_key(self):
        new_key = self._app.settings.get('node_manager').create_node_key()
        post_data = {
            'tags': ['a', 'bb', 'ccc']
        }

        # invalid node_key
        res = self.fetch('/v1/nodes?node_key=1',
                         method='POST',
                         body=json.dumps(post_data),
                         headers={'Content-Type': 'application/json'})
        # invalid NodeKey provided, should return 400
        self.assertEqual(400, res.code)

class NodeInstanceHandlerTest(NodeTest):
    def test_get(self):
        new_key = self._app.settings.get('node_manager').create_node_key()

        res = self.fetch('/v1/nodes' + '?node_key=' + new_key.key,
                         method='POST',
                         body='')
        self.assertEqual(200, res.code)

        res_data = json.loads(res.body)

        node_id = res_data['id']

        res = self.fetch('/v1/nodes/%s' % node_id)
        self.assertEqual(200, res.code)
        res_data = json.loads(res.body)
        self.assertIsNotNone(res_data['name'])
        self.assertIsNotNone(res_data['id'])
        self.assertIsNotNone(res_data['display_name'])
        self.assertIsNotNone(res_data['tags'])
        self.assertEqual(len(res_data['tags']), 0)
        self.assertIsNotNone(res_data['is_online'])
        self.assertIsNotNone(res_data['client_ip'])

class ObtainNodeSessionJobHandlerTest(NodeTest):
    def test_post(self):
        with session_scope() as session:
            user = self.get_user()
            project_manager = self.project_manager
            scheduler_manager = self.scheduler_manager
            node_manager = self._app.settings.get('node_manager')
            project_name = 'ObtainNodeSessionJobHandlerTest'
            exist_project = project_manager.get_project_by_name(
                session, user, project_name)
            if exist_project:
                project_manager.delete_project(user.id, exist_project.id)
                session.expunge(exist_project)

            project = project_manager.create_project(session,
                                                          user,
                                                          project_name)
            node_session = node_manager.create_node_session(session)
            spider = project_manager.create_spider(session, project, 'test')
            new_job = scheduler_manager.add_spider_task(session, spider)

            res = self.fetch('/v1/nodeSessions/%s/jobs:obtain' % node_session.id,
                             method='POST', body='')
            self.assertEqual(200, res.code)
            res_data = json.loads(res.body)
            self.assertIsNotNone(res_data['name'])

            # obtain one more
            # this time, there is no job available, should return 404
            res = self.fetch(
                '/v1/nodeSessions/%s/jobs:obtain' % node_session.id,
                method='POST', body='')
            self.assertEqual(404, res.code)

            project_manager.delete_project(user.id, project.id)

class CompleteNodeSessionJobHandlerTest(NodeTest):
    def test_post(self):
        with session_scope() as session:
            user = self.get_user()
            project_manager = self.project_manager
            scheduler_manager = self.scheduler_manager
            node_manager = self._app.settings.get('node_manager')
            project_name = 'CompoleteNodeSessionJobHandlerTest'
            exist_project = project_manager.get_project_by_name(
                session, user, project_name)
            if exist_project:
                project_manager.delete_project(user.id, exist_project.id)
                session.expunge(exist_project)

            project = project_manager.create_project(session,
                                                          user,
                                                          project_name)
            node_session = node_manager.create_node_session(session)
            spider = project_manager.create_spider(session, project, 'test')
            new_job = scheduler_manager.add_spider_task(session, spider)

            res = self.fetch('/v1/nodeSessions/%s/jobs:obtain' % node_session.id,
                             method='POST', body='')
            self.assertEqual(200, res.code)
            res_data = json.loads(res.body)
            self.assertIsNotNone(res_data['name'])
            job_id = res_data['id']

            complete_data = {'status': 'success'}
            complete_res = self.fetch('/v1/nodeSessions/%s/jobs/%s:complete' %
                                      (node_session.id, job_id),
                                      method='POST',
                                      body=urlencode(complete_data))
            self.assertEqual(200, complete_res.code)

            project_manager.delete_project(user.id, project.id)


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.Caching;
using Umbraco.Core.Persistence.Factories;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Services;
using NullCacheProvider = Umbraco.Core.Persistence.Caching.NullCacheProvider;

namespace Umbraco.Core.Persistence.Repositories
{
    /// <summary>
    /// Represents a repository for doing CRUD operations for <see cref="DataTypeDefinition"/>
    /// </summary>
    internal class DataTypeDefinitionRepository : PetaPocoRepositoryBase<int, IDataTypeDefinition>, IDataTypeDefinitionRepository
    {
        private readonly CacheHelper _cacheHelper;
        private readonly IContentTypeRepository _contentTypeRepository;
        private readonly DataTypePreValueRepository _preValRepository;

        public DataTypeDefinitionRepository(IDatabaseUnitOfWork work, CacheHelper cacheHelper,
            IContentTypeRepository contentTypeRepository)
			: base(work)
        {
            _cacheHelper = cacheHelper;
            _contentTypeRepository = contentTypeRepository;
            _preValRepository = new DataTypePreValueRepository(work, NullCacheProvider.Current);
        }

        public DataTypeDefinitionRepository(IDatabaseUnitOfWork work, IRepositoryCacheProvider cache, CacheHelper cacheHelper,
            IContentTypeRepository contentTypeRepository)
            : base(work, cache)
        {
            _cacheHelper = cacheHelper;
            _contentTypeRepository = contentTypeRepository;
            _preValRepository = new DataTypePreValueRepository(work, NullCacheProvider.Current);
        }

        private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();

        #region Overrides of RepositoryBase<int,DataTypeDefinition>

        protected override IDataTypeDefinition PerformGet(int id)
        {
            return GetAll(new[] {id}).FirstOrDefault();
        }

        protected override IEnumerable<IDataTypeDefinition> PerformGetAll(params int[] ids)
        {
            var factory = new DataTypeDefinitionFactory(NodeObjectTypeId);
            var dataTypeSql = GetBaseQuery(false);

            if (ids.Any())
            {
                dataTypeSql.Where("umbracoNode.id in (@ids)", new { ids = ids });
            }
            else
            {
                dataTypeSql.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
            }

            var dtos = Database.Fetch<DataTypeDto, NodeDto>(dataTypeSql);
            return dtos.Select(factory.BuildEntity).ToArray();
        }

        protected override IEnumerable<IDataTypeDefinition> PerformGetByQuery(IQuery<IDataTypeDefinition> query)
        {
            var factory = new DataTypeDefinitionFactory(NodeObjectTypeId);

            var sqlClause = GetBaseQuery(false);
            var translator = new SqlTranslator<IDataTypeDefinition>(sqlClause, query);
            var sql = translator.Translate();

            var dtos = Database.Fetch<DataTypeDto, NodeDto>(sql);

            return dtos.Select(factory.BuildEntity).ToArray();
        }

        /// <summary>
        /// Override the delete method so that we can ensure that all related content type's are updated as part of the overall transaction
        /// </summary>
        /// <param name="entity"></param>
        public override void Delete(IDataTypeDefinition entity)
        {
            //Find ContentTypes using this IDataTypeDefinition on a PropertyType
            var query = Query<PropertyType>.Builder.Where(x => x.DataTypeDefinitionId == entity.Id);

            //TODO: Don't we need to be concerned about media and member types here too ?
            var contentTypes = _contentTypeRepository.GetByQuery(query);

            //Loop through the list of results and remove the PropertyTypes that references the DataTypeDefinition that is being deleted
            foreach (var contentType in contentTypes)
            {
                if (contentType == null) continue;

                foreach (var group in contentType.PropertyGroups)
                {
                    var types = @group.PropertyTypes.Where(x => x.DataTypeDefinitionId == entity.Id).ToList();
                    foreach (var propertyType in types)
                    {
                        @group.PropertyTypes.Remove(propertyType);
                    }
                }

                _contentTypeRepository.AddOrUpdate(contentType);
            }

            //call the base method to queue the deletion of this data type
            base.Delete(entity);
        }

        #endregion

        #region Overrides of PetaPocoRepositoryBase<int,DataTypeDefinition>

        protected override Sql GetBaseQuery(bool isCount)
        {
            var sql = new Sql();
            sql.Select(isCount ? "COUNT(*)" : "*")
               .From<DataTypeDto>()
               .InnerJoin<NodeDto>()
               .On<DataTypeDto, NodeDto>(left => left.DataTypeId, right => right.NodeId)
               .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
            return sql;
        }

        protected override string GetBaseWhereClause()
        {
            return "umbracoNode.id = @Id";
        }

        protected override IEnumerable<string> GetDeleteClauses()
        {
            return new List<string>();
        }

        protected override Guid NodeObjectTypeId
        {
            get { return new Guid(Constants.ObjectTypes.DataType); }
        }

        #endregion

        #region Unit of Work Implementation

        protected override void PersistNewItem(IDataTypeDefinition entity)
        {
            ((DataTypeDefinition)entity).AddingEntity();

            //Cannot add a duplicate data type
            var exists = Database.ExecuteScalar<int>(@"SELECT COUNT(*) FROM cmsDataType
INNER JOIN umbracoNode ON cmsDataType.nodeId = umbracoNode.id
WHERE umbracoNode." + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedColumnName("text") + "= @name", new {name = entity.Name});
            if (exists > 0)
            {
                throw new DuplicateNameException("A data type with the name " + entity.Name + " already exists");
            }

            var factory = new DataTypeDefinitionFactory(NodeObjectTypeId);
            var dto = factory.BuildDto(entity);

            //Logic for setting Path, Level and SortOrder
            var parent = Database.First<NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
            int level = parent.Level + 1;
            int sortOrder =
                Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoNode WHERE parentID = @ParentId AND nodeObjectType = @NodeObjectType",
                                                      new { ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId });

            //Create the (base) node data - umbracoNode
            var nodeDto = dto.NodeDto;
            nodeDto.Path = parent.Path;
            nodeDto.Level = short.Parse(level.ToString(CultureInfo.InvariantCulture));
            nodeDto.SortOrder = sortOrder;
            var o = Database.IsNew(nodeDto) ? Convert.ToInt32(Database.Insert(nodeDto)) : Database.Update(nodeDto);

            //Update with new correct path
            nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
            Database.Update(nodeDto);

            //Update entity with correct values
            entity.Id = nodeDto.NodeId; //Set Id on entity to ensure an Id is set
            entity.Path = nodeDto.Path;
            entity.SortOrder = sortOrder;
            entity.Level = level;

            dto.DataTypeId = nodeDto.NodeId;
            Database.Insert(dto);

            entity.ResetDirtyProperties();
        }

        protected override void PersistUpdatedItem(IDataTypeDefinition entity)
        {

            //Cannot change to a duplicate alias
            var exists = Database.ExecuteScalar<int>(@"SELECT COUNT(*) FROM cmsDataType
INNER JOIN umbracoNode ON cmsDataType.nodeId = umbracoNode.id
WHERE umbracoNode." + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedColumnName("text") + @"= @name
AND umbracoNode.id <> @id",
                    new { id = entity.Id, name = entity.Name });
            if (exists > 0)
            {
                throw new DuplicateNameException("A data type with the name " + entity.Name + " already exists");
            }

            //Updates Modified date and Version Guid
            ((DataTypeDefinition)entity).UpdatingEntity();

            //Look up parent to get and set the correct Path if ParentId has changed
            if (entity.IsPropertyDirty("ParentId"))
            {
                var parent = Database.First<NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
                entity.Path = string.Concat(parent.Path, ",", entity.Id);
                entity.Level = parent.Level + 1;
                var maxSortOrder =
                    Database.ExecuteScalar<int>(
                        "SELECT coalesce(max(sortOrder),0) FROM umbracoNode WHERE parentid = @ParentId AND nodeObjectType = @NodeObjectType",
                        new { ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId });
                entity.SortOrder = maxSortOrder + 1;
            }

            var factory = new DataTypeDefinitionFactory(NodeObjectTypeId);
            //Look up DataTypeDefinition entry to get Primary for updating the DTO
            var dataTypeDto = Database.SingleOrDefault<DataTypeDto>("WHERE nodeId = @Id", new { Id = entity.Id });
            factory.SetPrimaryKey(dataTypeDto.PrimaryKey);
            var dto = factory.BuildDto(entity);

            //Updates the (base) node data - umbracoNode
            var nodeDto = dto.NodeDto;
            Database.Update(nodeDto);
            Database.Update(dto);

            entity.ResetDirtyProperties();
        }

        protected override void PersistDeletedItem(IDataTypeDefinition entity)
        {
            //Remove Notifications
            Database.Delete<User2NodeNotifyDto>("WHERE nodeId = @Id", new { Id = entity.Id });

            //Remove Permissions
            Database.Delete<User2NodePermissionDto>("WHERE nodeId = @Id", new { Id = entity.Id });

            //Remove associated tags
            Database.Delete<TagRelationshipDto>("WHERE nodeId = @Id", new { Id = entity.Id });

            //PropertyTypes containing the DataType being deleted
            var propertyTypeDtos = Database.Fetch<PropertyTypeDto>("WHERE dataTypeId = @Id", new { Id = entity.Id });
            //Go through the PropertyTypes and delete referenced PropertyData before deleting the PropertyType
            foreach (var dto in propertyTypeDtos)
            {
                Database.Delete<PropertyDataDto>("WHERE propertytypeid = @Id", new { Id = dto.Id });
                Database.Delete<PropertyTypeDto>("WHERE id = @Id", new { Id = dto.Id });
            }

            //Delete the pre-values
            Database.Delete<DataTypePreValueDto>("WHERE datatypeNodeId = @Id", new {Id = entity.Id});

            //Delete Content specific data
            Database.Delete<DataTypeDto>("WHERE nodeId = @Id", new { Id = entity.Id });

            //Delete (base) node data
            Database.Delete<NodeDto>("WHERE uniqueID = @Id", new { Id = entity.Key });
        }

        #endregion

        public PreValueCollection GetPreValuesCollectionByDataTypeId(int dataTypeId)
        {
            using (var l = new UpgradeableReadLock(_locker))
            {
                var cached = _cacheHelper.RuntimeCache.GetCacheItemsByKeySearch<PreValueCollection>(GetPrefixedCacheKey(dataTypeId));
                if (cached != null && cached.Any())
                {
                    //return from the cache, ensure it's a cloned result
                    return (PreValueCollection)cached.First().DeepClone();
                }

                l.UpgradeToWriteLock();

                return GetAndCachePreValueCollection(dataTypeId);
            }
        }

        public string GetPreValueAsString(int preValueId)
        {
            using (var l = new UpgradeableReadLock(_locker))
            {
                //We need to see if we can find the cached PreValueCollection based on the cache key above

                var regex = CacheKeys.DataTypePreValuesCacheKey + @"[\d]+-[,\d]*" + preValueId + @"[,\d$]*";

                var cached = _cacheHelper.RuntimeCache.GetCacheItemsByKeyExpression<PreValueCollection>(regex);
                if (cached != null && cached.Any())
                {
                    //return from the cache
                    var collection = cached.First();
                    var preVal = collection.FormatAsDictionary().Single(x => x.Value.Id == preValueId);
                    return preVal.Value.Value;
                }

                l.UpgradeToWriteLock();

                //go and find the data type id for the pre val id passed in

                var dto = Database.FirstOrDefault<DataTypePreValueDto>("WHERE id = @preValueId", new { preValueId = preValueId });
                if (dto == null)
                {
                    return string.Empty;
                }
                // go cache the collection
                var preVals = GetAndCachePreValueCollection(dto.DataTypeNodeId);

                //return the single value for this id
                var pv = preVals.FormatAsDictionary().Single(x => x.Value.Id == preValueId);
                return pv.Value.Value;
            }
        }

        public void AddOrUpdatePreValues(int dataTypeId, IDictionary<string, PreValue> values)
        {
            var dtd = Get(dataTypeId);
            if (dtd == null)
            {
                throw new InvalidOperationException("No data type found with id " + dataTypeId);
            }
            AddOrUpdatePreValues(dtd, values);
        }

        public void AddOrUpdatePreValues(IDataTypeDefinition dataType, IDictionary<string, PreValue> values)
        {
            var currentVals = new DataTypePreValueDto[]{};
            if (dataType.HasIdentity)
            {
                //first just get all pre-values for this data type so we can compare them to see if we need to insert or update or replace
                var sql = new Sql().Select("*")
                                   .From<DataTypePreValueDto>()
                                   .Where<DataTypePreValueDto>(dto => dto.DataTypeNodeId == dataType.Id)
                                   .OrderBy<DataTypePreValueDto>(dto => dto.SortOrder);
                currentVals = Database.Fetch<DataTypePreValueDto>(sql).ToArray();
            }

            //already existing, need to be updated
            var valueIds = values.Where(x => x.Value.Id > 0).Select(x => x.Value.Id).ToArray();
            var existingByIds = currentVals.Where(x => valueIds.Contains(x.Id)).ToArray();

            //These ones need to be removed from the db, they no longer exist in the new values
            var deleteById = currentVals.Where(x => valueIds.Contains(x.Id) == false);

            foreach (var d in deleteById)
            {
                _preValRepository.Delete(new PreValueEntity
                {
                    Alias = d.Alias,
                    Id = d.Id,
                    Value = d.Value,
                    DataType = dataType,
                    SortOrder = d.SortOrder
                });
            }

            var sortOrder = 1;

            foreach (var pre in values)
            {
                var existing = existingByIds.FirstOrDefault(valueDto => valueDto.Id == pre.Value.Id);
                if (existing != null)
                {
                    existing.Value = pre.Value.Value;
                    existing.SortOrder = sortOrder;
                    _preValRepository.AddOrUpdate(new PreValueEntity
                    {
                        //setting an id will update it
                        Id = existing.Id,
                        Alias = existing.Alias,
                        SortOrder = existing.SortOrder,
                        Value = existing.Value,
                        DataType = dataType,
                    });
                }
                else
                {
                    _preValRepository.AddOrUpdate(new PreValueEntity
                    {
                        Alias = pre.Key,
                        SortOrder = sortOrder,
                        Value = pre.Value.Value,
                        DataType = dataType,
                    });
                }

                sortOrder++;
            }

        }

        private string GetPrefixedCacheKey(int dataTypeId)
        {
            return CacheKeys.DataTypePreValuesCacheKey + dataTypeId + "-";
        }

        private PreValueCollection GetAndCachePreValueCollection(int dataTypeId)
        {
            //go get the data
            var dtos = Database.Fetch<DataTypePreValueDto>("WHERE datatypeNodeId = @Id", new { Id = dataTypeId });
            var list = dtos.Select(x => new Tuple<PreValue, string, int>(new PreValue(x.Id, x.Value, x.SortOrder), x.Alias, x.SortOrder)).ToList();
            var collection = PreValueConverter.ConvertToPreValuesCollection(list);

            //now create the cache key, this needs to include all pre-value ids so that we can use this cached item in the GetPreValuesAsString method
            //the key will be: "UmbracoPreValDATATYPEID-CSVOFPREVALIDS

            var key = GetPrefixedCacheKey(dataTypeId)
                      + string.Join(",", collection.FormatAsDictionary().Select(x => x.Value.Id).ToArray());

            //store into cache
            _cacheHelper.RuntimeCache.InsertCacheItem(key, () => collection,
                //30 mins
                new TimeSpan(0, 0, 30),
                //sliding is true
                true);

            return collection;
        }

        /// <summary>
        /// Private class to handle pre-value crud based on units of work with transactions
        /// </summary>
        private class PreValueEntity : Entity, IAggregateRoot
        {
            public string Value { get; set; }
            public string Alias { get; set; }
            public IDataTypeDefinition DataType { get; set; }
            public int SortOrder { get; set; }
        }

        /// <summary>
        /// Private class to handle pre-value crud based on standard principles and units of work with transactions
        /// </summary>
        private class DataTypePreValueRepository : PetaPocoRepositoryBase<int, PreValueEntity>
        {
            public DataTypePreValueRepository(IDatabaseUnitOfWork work, IRepositoryCacheProvider cache) : base(work, cache)
            {
            }

            #region Not implemented (don't need to for the purposes of this repo)
            protected override PreValueEntity PerformGet(int id)
            {
                throw new NotImplementedException();
            }

            protected override IEnumerable<PreValueEntity> PerformGetAll(params int[] ids)
            {
                throw new NotImplementedException();
            }

            protected override IEnumerable<PreValueEntity> PerformGetByQuery(IQuery<PreValueEntity> query)
            {
                throw new NotImplementedException();
            }

            protected override Sql GetBaseQuery(bool isCount)
            {
                throw new NotImplementedException();
            }

            protected override string GetBaseWhereClause()
            {
                throw new NotImplementedException();
            }

            protected override IEnumerable<string> GetDeleteClauses()
            {
                return new List<string>();
            }

            protected override Guid NodeObjectTypeId
            {
                get { throw new NotImplementedException(); }
            }
            #endregion

            protected override void PersistDeletedItem(PreValueEntity entity)
            {
                Database.Execute(
                    "DELETE FROM cmsDataTypePreValues WHERE id=@Id",
                    new { Id = entity.Id });
            }

            protected override void PersistNewItem(PreValueEntity entity)
            {
                if (entity.DataType.HasIdentity == false)
                {
                    throw new InvalidOperationException("Cannot insert a pre value for a data type that has no identity");
                }

                //Cannot add a duplicate alias
                var exists = Database.ExecuteScalar<int>(@"SELECT COUNT(*) FROM cmsDataTypePreValues
WHERE alias = @alias
AND datatypeNodeId = @dtdid",
                        new { alias = entity.Alias, dtdid = entity.DataType.Id });
                if (exists > 0)
                {
                    throw new DuplicateNameException("A pre value with the alias " + entity.Alias + " already exists for this data type");
                }

                var dto = new DataTypePreValueDto
                {
                    DataTypeNodeId = entity.DataType.Id,
                    Value = entity.Value,
                    SortOrder = entity.SortOrder,
                    Alias = entity.Alias
                };
                Database.Insert(dto);
            }

            protected override void PersistUpdatedItem(PreValueEntity entity)
            {
                if (entity.DataType.HasIdentity == false)
                {
                    throw new InvalidOperationException("Cannot update a pre value for a data type that has no identity");
                }

                //Cannot change to a duplicate alias
                var exists = Database.ExecuteScalar<int>(@"SELECT COUNT(*) FROM cmsDataTypePreValues
WHERE alias = @alias
AND datatypeNodeId = @dtdid
AND id <> @id",
                        new { id = entity.Id, alias = entity.Alias, dtdid = entity.DataType.Id });
                if (exists > 0)
                {
                    throw new DuplicateNameException("A pre value with the alias " + entity.Alias + " already exists for this data type");
                }

                var dto = new DataTypePreValueDto
                {
                    DataTypeNodeId = entity.DataType.Id,
                    Id = entity.Id,
                    Value = entity.Value,
                    SortOrder = entity.SortOrder,
                    Alias = entity.Alias
                };
                Database.Update(dto);
            }
        }

        internal static class PreValueConverter
        {
            /// <summary>
            /// Converts the tuple to a pre-value collection
            /// </summary>
            /// <param name="list"></param>
            /// <returns></returns>
            internal static PreValueCollection ConvertToPreValuesCollection(IEnumerable<Tuple<PreValue, string, int>> list)
            {
                //now we need to determine if they are dictionary based, otherwise they have to be array based
                var dictionary = new Dictionary<string, PreValue>();

                //need to check all of the keys, if there's only one and it is empty then it's an array
                var keys = list.Select(x => x.Item2).Distinct().ToArray();
                if (keys.Length == 1 && keys[0].IsNullOrWhiteSpace())
                {
                    return new PreValueCollection(list.OrderBy(x => x.Item3).Select(x => x.Item1));
                }

                foreach (var item in list
                    .OrderBy(x => x.Item3) //we'll order them first so we maintain the order index in the dictionary
                    .GroupBy(x => x.Item2)) //group by alias
                {
                    if (item.Count() > 1)
                    {
                        //if there's more than 1 item per key, then it cannot be a dictionary, just return the array
                        return new PreValueCollection(list.OrderBy(x => x.Item3).Select(x => x.Item1));
                    }

                    dictionary.Add(item.Key, item.First().Item1);
                }

                return new PreValueCollection(dictionary);
            }
        }

    }

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_edit"
        android:orderInCategory="100"
        android:title="编辑"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_save"
        android:orderInCategory="100"
        android:title="保存"
        app:showAsAction="always" />
</menu>


text:
import { hash } from 'rsvp';
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  can: service(),

  model() {
    let repository = this.modelFor('repositories/show');
    let doi = this.store.createRecord('doi', { repository, mode: 'upload', state: 'draft' });

    return hash({
      repository,
      doi,
    });
  },

  // afterModel(model) {
  //   if (this.get('can').cannot('create doi', model)) {
  //     return this.transitionTo('index');
  //   }
  // }
});


text:
class fuego:public Enemygo
{
    public:
        fuego(Personaje * personaje);
        void logica();
        void reset();
        virtual ~fuego();
    protected:
    private:
};

#endif // FUEGO_H


text:
export type GreetingChartData = { label: string; value: number }[];

export type GreetingId = string | number;

export type NewGreeting = {
  greeting: string;
  name: string;
};

export interface Greeting extends NewGreeting {
  id: GreetingId;
}

export type Greetings = Greeting[];
export type GreetingFilter = string | null;

export const MODE_MASTER = "MODE_MASTER";
export const MODE_DETAIL = "MODE_DETAIL";
export type Mode = typeof MODE_DETAIL | typeof MODE_MASTER;

export type GreetingState = Greetings;
export type FilterState = GreetingFilter;
export type ModeState = Mode;

/** The overall application state */
export type AppState = {
  greetings: GreetingState;
  filter: FilterState;
  mode: ModeState;
};


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Agric. Gaz. N. S. W. , Sydney 7(3): 154 (1896)

#### Original name
Tilletia inolens McAlpine, 1896

### Remarks
null


text:
{-# LANGUAGE TemplateHaskell, TypeOperators #-}
-- | For more information: http://www.ietf.org/rfc/rfc2109.txt
module Network.Protocol.Cookie {- todo: test please -}
(

-- * Cookie datatype.
  Cookie (Cookie)
, empty
, cookie
, setCookie

-- * Accessing cookies.
, name
, value
, comment
, commentURL
, discard
, domain
, maxAge
, expires
, path
, port
, secure
, version

-- * Collection of cookies.
, Cookies
, unCookies
, cookies
, setCookies

, pickCookie
, fromList
, toList
)
where

import Prelude hiding ((.), id)
import Control.Category
import Control.Monad (join)
import Data.Record.Label
import Data.Maybe
import Data.Char
import Safe
import Data.List
import Network.Protocol.Uri.Query
import qualified Data.Map as M

-- | The `Cookie` data type containg one key/value pair with all the
-- (potentially optional) meta-data.

data Cookie =
  Cookie
    { _name       :: String
    , _value      :: String
    , _comment    :: Maybe String
    , _commentURL :: Maybe String
    , _discard    :: Bool
    , _domain     :: Maybe String
    , _maxAge     :: Maybe Int
    , _expires    :: Maybe String
    , _path       :: Maybe String
    , _port       :: [Int]
    , _secure     :: Bool
    , _version    :: Int
    } deriving Eq

$(mkLabelsNoTypes [''Cookie])

-- | Access name/key of a cookie.

name :: Cookie :-> String

-- | Access value of a cookie.

value :: Cookie :-> String

-- | Access comment of a cookie.

comment :: Cookie :-> Maybe String

-- | Access comment-URL of a cookie.

commentURL :: Cookie :-> Maybe String

-- | Access discard flag of a cookie.

discard :: Cookie :-> Bool

-- | Access domain of a cookie.

domain :: Cookie :-> Maybe String

-- | Access max-age of a cookie.

maxAge :: Cookie :-> Maybe Int

-- | Access expiration of a cookie.

expires :: Cookie :-> Maybe String

-- | Access path of a cookie.

path :: Cookie :-> Maybe String

-- | Access port of a cookie.

port :: Cookie :-> [Int]

-- | Access secure flag of a cookie.

secure :: Cookie :-> Bool

-- | Access version of a cookie.

version :: Cookie :-> Int

-- | Create an empty cookie.

empty :: Cookie
empty = Cookie "" "" Nothing Nothing False Nothing Nothing Nothing Nothing [] False 0

-- Cookie show instance.

instance Show Cookie where
  showsPrec _ = showsSetCookie

-- Show a semicolon separated list of attribute/value pairs. Only meta pairs
-- with significant values will be pretty printed.

showsSetCookie :: Cookie -> ShowS
showsSetCookie c =
    pair (getL name c) (getL value c)
  . opt  "comment"    (getL comment c)
  . opt  "commentURL" (getL commentURL c)
  . bool "discard"    (getL discard c)
  . opt  "domain"     (getL domain c)
  . opt  "maxAge"     (fmap show (getL maxAge c))
  . opt  "expires"    (getL expires c)
  . opt  "path"       (getL path c)
  . lst  "port"       (map show (getL port c))
  . bool "secure"     (getL secure c)
  . opt  "version"    (optval (getL version c))
  where
    attr a       = showString a
    val v        = showString ("=" ++ v)
    end          = showString "; "
    single a     = attr a . end
    pair a v     = attr a . val v . end
    opt a        = maybe id (pair a)
    lst _ []     = id
    lst a xs     = pair a (intercalate "," xs)
    bool _ False = id
    bool a True  = single a
    optval 0     = Nothing
    optval i     = Just (show i)

showCookie :: Cookie -> String
showCookie c = _name c ++ "=" ++ _value c

parseSetCookie :: String -> Cookie
parseSetCookie s =
  let p = fw (keyValues ";" "=") s
  in Cookie
    { _name       = (fromMaybe "" .        fmap fst . headMay)              p
    , _value      = (fromMaybe "" . join . fmap snd . headMay)              p
    , _comment    = (                           join . lookup "comment")    p
    , _commentURL = (                           join . lookup "commentURL") p
    , _discard    = (maybe False (const True) . join . lookup "discard")    p
    , _domain     = (                           join . lookup "commentURL") p
    , _maxAge     = (join . fmap readMay .      join . lookup "commentURL") p
    , _expires    = (                           join . lookup "expires")    p
    , _path       = (                           join . lookup "path")       p
    , _port       = (maybe [] (readDef [-1]) .  join . lookup "port")       p
    , _secure     = (maybe False (const True) . join . lookup "secure")     p
    , _version    = (maybe 1 (readDef 1) .      join . lookup "version")    p
    }

parseCookie :: String -> Cookie
parseCookie s =
  let p = fw (values "=") s
  in empty
       { _name  = atDef "" p 0
       , _value = atDef "" p 1
       }

-- | Cookie parser and pretty printer as a lens. To be used in combination with
-- the /Set-Cookie/ header field.

setCookie :: String :<->: Cookie
setCookie = parseSetCookie :<->: show

-- | Cookie parser and pretty printer as a lens. To be used in combination with
-- the /Cookie/ header field.

cookie :: String :<->: Cookie
cookie = parseCookie :<->: showCookie

-- | A collection of multiple cookies. These can all be set in one single HTTP
-- /Set-Cookie/ header field.

data Cookies = Cookies { _unCookies :: M.Map String Cookie }
  deriving Eq

$(mkLabelsNoTypes [''Cookies])

-- | Access raw cookie mapping from collection.

unCookies :: Cookies :-> M.Map String Cookie

instance Show Cookies where
  showsPrec _ = showsSetCookies

showsSetCookies :: Cookies -> ShowS
showsSetCookies =
      is (showString ", ")
    . map (shows . snd)
    . M.toList
    . getL unCookies
  where
  is _ []     = id
  is s (x:xs) = foldl (\a b -> a.s.b) x xs

-- | Cookies parser and pretty printer as a lens.

setCookies :: String :<->: Cookies
setCookies = (fromList :<->: toList) . (map parseSetCookie :<->: map show) . values ","

-- | Label for printing and parsing collections of cookies.

cookies :: String :<->: Cookies
cookies = (fromList :<->: toList) . (map parseCookie :<->: map showCookie) . values ";"

-- | Case-insensitive way of getting a cookie out of a collection by name.

pickCookie :: String -> Cookies :-> Maybe Cookie
pickCookie n = lookupL (map toLower n) . unCookies
  where lookupL k = lens (M.lookup k) (flip M.alter k . const)

-- | Convert a list to a cookies collection.

fromList :: [Cookie] -> Cookies
fromList = Cookies . M.fromList . map (\a -> (map toLower (getL name a), a))

-- | Get the cookies as a list.

toList :: Cookies -> [Cookie]
toList = map snd . M.toList . getL unCookies


text:
#ifndef DALI_INTERNAL_SCENE_GRAPH_FRAME_CALLBACK_PROCESSOR_H
#define DALI_INTERNAL_SCENE_GRAPH_FRAME_CALLBACK_PROCESSOR_H

// EXTERNAL INCLUDES
#include <memory>

// INTERNAL INCLUDES
#include <dali/internal/common/buffer-index.h>
#include <dali/internal/common/owner-pointer.h>
#include <dali/internal/update/manager/scene-graph-frame-callback.h>
#include <dali/internal/update/manager/update-proxy-impl.h>
#include <dali/public-api/common/vector-wrapper.h>

namespace Dali
{
class FrameCallbackInterface;

namespace Internal
{
namespace SceneGraph
{
class Node;
class TransformManager;
class UpdateManager;

/**
 * This class processes all the registered frame-callbacks.
 */
class FrameCallbackProcessor
{
public:
  /**
   * Construct a new FrameCallbackProcessor.
   * @param[in]  updateManager     A reference to the UpdateManager
   * @param[in]  transformManager  A reference to the TransformManager
   */
  FrameCallbackProcessor(UpdateManager& updateManager, TransformManager& transformManager);

  /**
   * Non-virtual Destructor.
   */
  ~FrameCallbackProcessor();

  // Movable but not copyable

  FrameCallbackProcessor(const FrameCallbackProcessor&) = delete;            ///< Deleted copy constructor.
  FrameCallbackProcessor(FrameCallbackProcessor&&)      = default;           ///< Default move constructor.
  FrameCallbackProcessor& operator=(const FrameCallbackProcessor&) = delete; ///< Deleted copy assignment operator.
  FrameCallbackProcessor& operator=(FrameCallbackProcessor&&) = delete;      ///< Deleted move assignment operator.

  /**
   * Adds an implementation of the FrameCallbackInterface.
   * @param[in]  frameCallback  An OwnerPointer to the SceneGraph FrameCallback object
   * @param[in]  rootNode       A pointer to the root node to apply the FrameCallback to
   */
  void AddFrameCallback(OwnerPointer<FrameCallback>& frameCallback, const Node* rootNode);

  /**
   * Removes the specified implementation of FrameCallbackInterface.
   * @param[in]  frameCallback  A pointer to the implementation of the FrameCallbackInterface to remove.
   */
  void RemoveFrameCallback(FrameCallbackInterface* frameCallback);

  /**
   * Called on Update by the UpdateManager.
   * @param[in]  bufferIndex     The bufferIndex to use
   * @param[in]  elapsedSeconds  Time elapsed time since the last frame (in seconds)
   */
  void Update(BufferIndex bufferIndex, float elapsedSeconds);

  /**
   * Called by the UpdateManager when the node hierarchy changes.
   */
  void NodeHierarchyChanged()
  {
    mNodeHierarchyChanged = true;
  }

private:
  std::vector<OwnerPointer<FrameCallback> > mFrameCallbacks; ///< A container of all the frame-callbacks & accompanying update-proxies.

  UpdateManager& mUpdateManager;

  TransformManager& mTransformManager;

  bool mNodeHierarchyChanged; ///< Set to true if the node hierarchy changes
};

} // namespace SceneGraph

} // namespace Internal

} // namespace Dali

#endif // DALI_INTERNAL_SCENE_GRAPH_FRAME_CALLBACK_PROCESSOR_H


text:
import { combineEpics } from 'redux-observable';
import 'rxjs/add/operator/map';

import { Store } from '../index';
import { ActionCreators, Action } from './reducer';
import { convertValueWithBaseRateToTargetRate } from './utils';
import * as CurrencyConverterSelectors from './selectors';
import * as CurrencyRatesSelectors from '../currency-rates/selectors';

// Epics - handling side effects of actions
const changeCurrencyEpic = (action$: any, store: Store) =>
  action$.ofType(
    ActionCreators.ChangeBaseCurrency.type,
    ActionCreators.ChangeTargetCurrency.type,
  ).map((action: typeof ActionCreators.ChangeBaseCurrency) => ({
    type: ActionCreators.UpdateCurrencyConverterState.type,
    payload: {
      targetValue: convertValueWithBaseRateToTargetRate(
        CurrencyConverterSelectors.getBaseValue(store.getState()),
        CurrencyRatesSelectors.getBaseCurrencyRate(store.getState()),
        CurrencyRatesSelectors.getTargetCurrencyRate(store.getState()),
      ),
    },
  } as Action));

const changeBaseValueEpic = (action$: any, store: Store) =>
  action$.ofType(ActionCreators.ChangeBaseValue.type)
    .map((action: typeof ActionCreators.ChangeBaseValue) => ({
      type: ActionCreators.UpdateCurrencyConverterState.type,
      payload: {
        targetValue: convertValueWithBaseRateToTargetRate(
          action.payload,
          CurrencyRatesSelectors.getBaseCurrencyRate(store.getState()),
          CurrencyRatesSelectors.getTargetCurrencyRate(store.getState()),
        ),
      },
    } as Action));

const changeTargetValueEpic = (action$: any, store: Store) =>
  action$.ofType(ActionCreators.ChangeTargetValue.type)
    .map((action: typeof ActionCreators.ChangeTargetValue) => ({
      type: ActionCreators.UpdateCurrencyConverterState.type,
      payload: {
        baseValue: convertValueWithBaseRateToTargetRate(
          action.payload,
          CurrencyRatesSelectors.getTargetCurrencyRate(store.getState()),
          CurrencyRatesSelectors.getBaseCurrencyRate(store.getState()),
        ),
      },
    } as Action));

export const epics = combineEpics(
  changeCurrencyEpic, changeBaseValueEpic, changeTargetValueEpic,
);


text:
/**********************************************************************
 * This a dirt simple boot loader, whose sole job is to boot
 * an ELF kernel image from the first IDE hard disk.
 *
 * DISK LAYOUT
 *  * This program(boot.S and main.c) is the bootloader.  It should
 *    be stored in the first sector of the disk.
 *
 *  * The 2nd sector onward holds the kernel image.
 *
 *  * The kernel image must be in ELF format.
 *
 * BOOT UP STEPS
 *  * when the CPU boots it loads the BIOS into memory and executes it
 *
 *  * the BIOS intializes devices, sets of the interrupt routines, and
 *    reads the first sector of the boot device(e.g., hard-drive)
 *    into memory and jumps to it.
 *
 *  * Assuming this boot loader is stored in the first sector of the
 *    hard-drive, this code takes over...
 *
 *  * control starts in bootloader.S -- which sets up protected mode,
 *    and a stack so C code then run, then calls bootmain()
 *
 *  * bootmain() in this file takes over, reads in the kernel and jumps to it.
 **********************************************************************/

void
bootmain(void)
{
	//This is where the fun begins!!
	//To be continued...
	int i;
	while (1)
	{/* do nothing */

	}
}


text:
import React from 'react';
import {
  StyleProp,
  StyleSheet,
  View,
  ViewProps,
  ViewStyle,
} from 'react-native';
import {
  ChildrenWithProps,
  Overwrite,
  LiteralUnion,
} from '../../devsupport';
import {
  styled,
  StyledComponentProps,
  StyleType,
} from '../../theme';
import {
  TabElement,
  TabProps,
} from './tab.component';
import { TabIndicator } from '../shared/tabIndicator.component';

type TabBarStyledProps = Overwrite<StyledComponentProps, {
  appearance?: LiteralUnion<'default'>;
}>;

export interface TabBarProps extends ViewProps, TabBarStyledProps {
  children?: ChildrenWithProps<TabProps>;
  selectedIndex?: number;
  onSelect?: (index: number) => void;
  indicatorStyle?: StyleProp<ViewStyle>;
}

export type TabBarElement = React.ReactElement<TabBarProps>;

/**
 * A bar with tabs styled by Eva.
 * TabBar should contain Tab components to provide a useful navigation component.
 *
 * @extends React.Component
 *
 * @property {ReactElement<TabProps> | ReactElement<TabProps>[]} children - Tabs to be rendered within the bar.
 *
 * @property {number} selectedIndex - Index of currently selected tab.
 *
 * @property {(number) => void} onSelect - Called when tab is pressed.
 *
 * @property {StyleProp<ViewStyle>} indicatorStyle - Style of the indicator component.
 *
 * @property {ViewProps} ...ViewProps - Any props applied to View component.
 *
 * @overview-example TabBarSimpleUsage
 * In basic examples, tabs are wrapped within `TabBar`.
 *
 * @overview-example Using with React Navigation
 * TabBar can also be [configured with React Navigation](guides/configure-navigation)
 * to provide a navigational component.
 * ```
 * import React from 'react';
 * import { NavigationContainer } from '@react-navigation/native';
 * import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
 * import { TabBar, Tab, Layout, Text } from '@ui-kitten/components';
 *
 * const { Navigator, Screen } = createMaterialTopTabNavigator();
 *
 * const UsersScreen = () => (
 *   <Layout style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
 *     <Text category='h1'>USERS</Text>
 *   </Layout>
 * );
 *
 * const OrdersScreen = () => (
 *   <Layout style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
 *     <Text category='h1'>ORDERS</Text>
 *   </Layout>
 * );
 *
 * const TopTabBar = ({ navigation, state }) => (
 *   <TabBar
 *     selectedIndex={state.index}
 *     onSelect={index => navigation.navigate(state.routeNames[index])}>
 *     <Tab title='USERS'/>
 *     <Tab title='ORDERS'/>
 *   </TabBar>
 * );
 *
 * const TabNavigator = () => (
 *   <Navigator tabBar={props => <TopTabBar {...props} />}>
 *     <Screen name='Users' component={UsersScreen}/>
 *     <Screen name='Orders' component={OrdersScreen}/>
 *   </Navigator>
 * );
 *
 * export const AppNavigator = () => (
 *   <NavigationContainer>
 *     <TabNavigator/>
 *   </NavigationContainer>
 * );
 * ```
 *
 * @overview-example TabBarAccessories
 * Tabs also may contain [icons](guides/icon-packages), to provide a better user interfaces.
 *
 * @overview-example TabStyling
 * Tab and it's inner views can be styled by passing them as function components.
 * ```
 * import { Tab, Text } from '@ui-kitten/components';
 *
 * <Tab
 *   title={evaProps => <Text {...evaProps}>USERS</Text>}
 * />
 * ```
 *
 * @overview-example TabTheming
 * In most cases this is redundant, if [custom theme is configured](guides/branding).
 */
@styled('TabBar')
export class TabBar extends React.Component<TabBarProps> {

  static defaultProps: Partial<TabBarProps> = {
    selectedIndex: 0,
  };

  private tabIndicatorRef = React.createRef<TabIndicator>();

  public scrollToIndex(params: { index: number; animated?: boolean }): void {
    this.tabIndicatorRef.current?.scrollToIndex(params);
  }

  public scrollToOffset(params: { offset: number; animated?: boolean }): void {
    this.tabIndicatorRef.current?.scrollToOffset(params);
  }

  private onTabSelect = (index: number): void => {
    this.props.onSelect?.(index);
  };

  private getComponentStyle = (source: StyleType): StyleType => {
    const {
      indicatorHeight,
      indicatorBorderRadius,
      indicatorBackgroundColor,
      ...containerParameters
    } = source;

    return {
      container: containerParameters,
      item: {},
      indicator: {
        height: indicatorHeight,
        borderRadius: indicatorBorderRadius,
        backgroundColor: indicatorBackgroundColor,
      },
    };
  };

  private isTabSelected = (index: number): boolean => {
    return index === this.props.selectedIndex;
  };

  private renderTabElement = (element: TabElement, index: number): TabElement => {
    return React.cloneElement(element, {
      key: index,
      style: [styles.item, element.props.style],
      selected: this.isTabSelected(index),
      onSelect: () => this.onTabSelect(index),
    });
  };

  private renderTabElements = (source: ChildrenWithProps<TabProps>): TabElement[] => {
    return React.Children.map(source, this.renderTabElement);
  };

  public render(): React.ReactElement<ViewProps> {
    const { eva, style, testID, indicatorStyle, selectedIndex, children, ...viewProps } = this.props;
    const evaStyle = this.getComponentStyle(eva.style);
    const tabElements: TabElement[] = this.renderTabElements(children);

    return (
      <View testID={testID}>
        <View
          {...viewProps}
          style={[evaStyle.container, styles.container, style]}
        >
          {tabElements}
        </View>
        <TabIndicator
          ref={this.tabIndicatorRef}
          style={[evaStyle.indicator, indicatorStyle]}
          selectedPosition={selectedIndex}
          positions={tabElements.length}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
  },
  item: {
    flex: 1,
  },
});


text:
<?php
	use Lidiun\Layout;

	Class Home
	{
		public function __construct() {

		}
	}


text:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="addB115.xsd"
>

	<foo a="fooasdfsdfs" />

</root>


text:
module HerePlaces
  class Category < HerePlaces::Base
    def places(payload)
      call_api(path, payload)
    end

    private

    def path
      @_path ||= HerePlaces::API_PREFIX + '/' + 'categories' + '/' + 'places'
    end
  end
end


text:
package com.ekocaman;

import com.ekocaman.service.CalculatorService;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.ekocaman")
public class SpringAnnotationConfig {
}