text:
from __future__ import unicode_literals

from django.db import models, migrations
import sortedm2m.fields
import sortedm2m.operations

class Migration(migrations.Migration):

    dependencies = [
        ('altersortedmanytomanyfield_tests', '0001_initial'),
    ]

    operations = [
        sortedm2m.operations.AlterSortedManyToManyField(
            model_name='m2mtosortedm2m',
            name='m2m',
            field=sortedm2m.fields.SortedManyToManyField(help_text=None, to='altersortedmanytomanyfield_tests.Target'),
            preserve_default=True,
        ),
        sortedm2m.operations.AlterSortedManyToManyField(
            model_name='sortedm2mtom2m',
            name='m2m',
            field=models.ManyToManyField(to='altersortedmanytomanyfield_tests.Target'),
            preserve_default=True,
        ),
    ]


text:
function fixWindowsPath(path) {
    return process.platform === 'win32' ? path.replace(/\\/g, '/') : path;
}

function fixWindowsPaths(paths){
    return paths.map(fixWindowsPath);
}

module.exports = { fixWindowsPath, fixWindowsPaths };

redpajama_set_name: RedPajamaGithub


text:
@interface TradePaymentOrderResp : NSObject

@property (strong, nonatomic) NSArray* list;

@end


text:
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int biggest = INT_MIN, second_biggest = INT_MIN;
        for (int& num : nums) {
            if (num > biggest) {
                second_biggest = biggest;
                biggest = num;
            } else if (num > second_biggest) {
                second_biggest = num;
            }
        }
        return (biggest - 1) * (second_biggest - 1);
    }
};


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Zombus.Infrastructure;
using NUnit.Framework;
using Shouldly;
using Zombus.Configuration;
using Zombus.Infrastructure.DependencyResolution;
using Zombus.IntegrationTests.Tests.AuditingInterceptorTests.MessageTypes;
using Zombus.Interceptors;
using Zombus.MessageContracts.ControlMessages;
using Zombus.Tests.Common;

namespace Zombus.IntegrationTests.Tests.AuditingInterceptorTests
{
    [TestFixture]
    [Timeout(_timeoutSeconds * 1000)]
    public class WhenSendingOneOfEachKindOfMessage : SpecificationForAsync<IBus>
    {
        private const int _timeoutSeconds = 5;

        private object[] _allAuditedMessages;

        protected override async Task<IBus> Given()
        {
            MethodCallCounter.Clear();

            var testFixtureType = GetType();
            var outboundAuditingInterceptorType = typeof (OutboundAuditingInterceptor);
            var auditEventType = typeof (AuditEvent);
            var typeProvider = new TestHarnessTypeProvider(new[] {testFixtureType.Assembly, outboundAuditingInterceptorType.Assembly},
                                                           new[] {testFixtureType.Namespace, outboundAuditingInterceptorType.Namespace, auditEventType.Namespace});
            var logger = TestHarnessLoggerFactory.Create();

            var dependencyResolver = new DependencyResolver(typeProvider);

            var bus = new BusBuilder().Configure()
                                      .WithNames("MyTestSuite", Environment.MachineName)
                                      .WithConnectionString(CommonResources.ServiceBusConnectionString)
                                      .WithTypesFrom(typeProvider)
                                      .WithDependencyResolver(dependencyResolver)
                                      .WithDefaultTimeout(TimeSpan.FromSeconds(10))
                                      .WithMaxDeliveryAttempts(1)
                                      .WithHeartbeatInterval(TimeSpan.MaxValue)
                                      .WithGlobalOutboundInterceptorTypes(typeof (OutboundAuditingInterceptor))
                                      .WithLogger(logger)
                                      .WithDebugOptions(
                                          dc =>
                                          dc.RemoveAllExistingNamespaceElementsOnStartup(
                                              "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                                      .Build();

            await bus.Start();

            return bus;
        }

        protected override async Task When()
        {
            await Task.WhenAll(
                Subject.SendAsync(new SomeCommand(42)),
                Subject.SendAtAsync(new SomeCommandSentViaDelay(), DateTimeOffset.UtcNow),
                Subject.PublishAsync(new SomeEvent())
                );

            await TimeSpan.FromSeconds(_timeoutSeconds).WaitUntil(() => MethodCallCounter.AllReceivedMessages.Count() >= 3);
            MethodCallCounter.Stop();

            _allAuditedMessages = MethodCallCounter.AllReceivedMessages
                                                   .OfType<AuditEvent>()
                                                   .Select(ae => ae.MessageBody)
                                                   .ToArray();
        }

        [Test]
        public async Task ThereShouldBeAnAuditRecordForSomeCommand()
        {
            _allAuditedMessages.OfType<SomeCommand>().Count().ShouldBe(1);
        }

        [Test]
        public async Task ThereShouldBeAnAuditRecordForSomeCommandSentViaDelay()
        {
            _allAuditedMessages.OfType<SomeCommandSentViaDelay>().Count().ShouldBe(1);
        }

        [Test]
        public async Task ThereShouldBeAnAuditRecordForSomeEvent()
        {
            _allAuditedMessages.OfType<SomeEvent>().Count().ShouldBe(1);
        }

        [Test]
        public async Task ThereShouldBeATotalOfThreeAuditRecords()
        {
            MethodCallCounter.AllReceivedMessages.OfType<AuditEvent>().Count().ShouldBe(3);
        }

        [Test]
        public async Task ThereShouldBeATotalOfThreeRecordedHandlerCalls()
        {
            MethodCallCounter.AllReceivedCalls.Count().ShouldBe(3);
        }
    }
}


text:
#ifndef AJAXREQUESTLISTENER_H
#define AJAXREQUESTLISTENER_H
#include <QNetworkAccessManager>
#include <QUrl>
namespace artemis
{

class AjaxRequestListener : public QNetworkAccessManager
{
    Q_OBJECT
public:
    explicit AjaxRequestListener(QObject* parent = 0);
    QNetworkReply* createRequest(Operation op, const QNetworkRequest& req, QIODevice* outgoingData = 0);

signals:
    void pageGet(QUrl url);
    void pagePost(QUrl url);
public slots:

};

}
#endif // AJAXREQUESTLISTENER_H


text:
#include <gtest/gtest.h>

#include <unordered_set>

#include <liballocgc/details/allocators/gc_pool_allocator.hpp>
#include <liballocgc/details/compacting/two_finger_compactor.hpp>
#include <liballocgc/details/allocators/gc_core_allocator.hpp>
#include <liballocgc/gc_type_meta.hpp>
#include <liballocgc/gc_common.hpp>

#include "utils.hpp"
#include "rand_util.h"
#include "test_forwarding.hpp"

using namespace allocgc;
using namespace allocgc::details;
using namespace allocgc::details::allocators;
using namespace allocgc::details::compacting;

namespace {
static const size_t OBJ_SIZE = 16;      // PAGE_SIZE / OBJECTS_PER_PAGE;
static const size_t ALLOC_SIZE = 64;

struct test_type
{
    byte data[OBJ_SIZE];
};

const gc_type_meta* type_meta = gc_type_meta_factory<test_type>::create();

typedef gc_pool_allocator allocator_t;

}

template <typename Compactor>
struct compactor_test : public ::testing::Test
{
    compactor_test()
        : rqst(OBJ_SIZE, 1, type_meta, &buf)
    {
        alloc.set_core_allocator(&core_alloc);
    }

    gc_core_allocator core_alloc;
    gc_pool_allocator alloc;
    Compactor compactor;
    gc_buf buf;
    gc_alloc::request rqst;
};

typedef ::testing::Types<two_finger_compactor> test_compactor_types;
TYPED_TEST_CASE(compactor_test, test_compactor_types);

/**
 * In this test a small pool is compated by the two-finger-compact procedure and resulting forwarding is checked.
 * Pool layout illustrated below ( x - marked (occupied) cell, # - pinned cell).
 *
 *      *********************
 *      * 0 | 1 | 2 | 3 | 4 *
 *      *********************
 *      * x |   |   | # | x *
 *      *********************
 *
 * After compacting pool should look like:
 *
 *      *********************
 *      * 0 | 1 | 2 | 3 | 4 *
 *      *********************
 *      * x | x |   | # |   *
 *      *********************
 */
TYPED_TEST(compactor_test, test_compact_1)
{
    static const size_t OBJ_COUNT = 5;
    gc_alloc::response rsps[OBJ_COUNT];
    for (int i = 0; i < OBJ_COUNT; ++i) {
        rsps[i] = this->alloc.allocate(this->rqst, ALLOC_SIZE);
    }

    // mark & pin some objects
    commit(rsps[0]);
    set_mark(rsps[0], true);
    commit(rsps[3]);
    set_mark(rsps[3], true);
    set_pin(rsps[3], true);
    commit(rsps[4]);
    commit(rsps[4]);
    set_mark(rsps[4], true);

//    for (auto p: rng) {
//        std::cout << (void*) p.get() << " " << p.get_mark() << " " << p.get_pin() << std::endl;
//    }
//    std::cout << std::distance(rng.begin(), rng.end()) << std::endl;

    byte* exp_to = rsps[1].cell_start();
    byte* exp_from = rsps[4].cell_start();

    gc_collect_stat stat;
    test_forwarding frwd;
    auto rng = this->alloc.memory_range();
    this->compactor(rng, frwd, stat);

//    ASSERT_EQ(ALLOC_SIZE, stat.mem_freed);
    ASSERT_EQ(ALLOC_SIZE, stat.mem_moved);

    auto frwd_list = frwd.get_forwarding_list();
    ASSERT_EQ(1, frwd_list.size());
    void* from = frwd_list[0].from;
    void* to = frwd_list[0].to;

    ASSERT_EQ(exp_from, from);
    ASSERT_EQ(exp_to, to);

    ASSERT_TRUE(get_mark(rsps[0]));
    ASSERT_TRUE(get_mark(rsps[1]));
    ASSERT_TRUE(get_mark(rsps[3]));
    ASSERT_TRUE(get_pin(rsps[3]));

    ASSERT_EQ(gc_lifetime_tag::LIVE, get_lifetime_tag(rsps[0]));
    ASSERT_EQ(gc_lifetime_tag::LIVE, get_lifetime_tag(rsps[1]));
    ASSERT_EQ(gc_lifetime_tag::LIVE, get_lifetime_tag(rsps[3]));

    ASSERT_FALSE(get_mark(rsps[2]));
    ASSERT_FALSE(get_mark(rsps[4]));

    ASSERT_EQ(gc_lifetime_tag::FREE, get_lifetime_tag(rsps[2]));
    ASSERT_EQ(gc_lifetime_tag::FREE, get_lifetime_tag(rsps[4]));
}

TYPED_TEST(compactor_test, test_compact_2)
{
    const size_t LIVE_CNT = 5;
    const size_t ALLOC_CNT = 4 * LIVE_CNT;
    gc_alloc::response rsps[ALLOC_CNT];

    for (size_t i = 0; i < ALLOC_CNT; ++i) {
        rsps[i] = this->alloc.allocate(this->rqst, ALLOC_SIZE);
    }

    uniform_rand_generator<size_t> rand_gen(0, ALLOC_CNT - 1);
    auto rng = this->alloc.memory_range();
    for (size_t i = 0; i < LIVE_CNT; ++i) {
        size_t rand = rand_gen();
        gc_alloc::response* rsp = rsps + rand;
        while (get_mark(*rsp)) {
            rand = rand_gen();
            rsp = rsps + rand;
        }
        commit(*rsp);
        set_mark(*rsp, true);
    }

    gc_collect_stat stat;
    test_forwarding frwd;
    this->compactor(rng, frwd, stat);

    ASSERT_GE(ALLOC_SIZE * LIVE_CNT, stat.mem_moved);

    auto live_begin = rng.begin();
    auto live_end = std::next(live_begin, LIVE_CNT);
    auto dead_begin = live_end;
    auto dead_end = rng.end();
    size_t dead_cnt = std::distance(dead_begin, dead_end);
    for (auto it = live_begin; it != live_end; ++it) {
        ASSERT_TRUE(it->get_mark());
        ASSERT_TRUE(it->get_lifetime_tag() == gc_lifetime_tag::LIVE);
    }
    for (auto it = dead_begin; it != dead_end; ++it) {
        ASSERT_FALSE(it->get_mark());
        ASSERT_TRUE(it->get_lifetime_tag() == gc_lifetime_tag::FREE ||
                    it->get_lifetime_tag() == gc_lifetime_tag::GARBAGE);
    }
}

TYPED_TEST(compactor_test, test_compact_3)
{
    static const size_t OBJ_COUNT = 512;
    bernoulli_rand_generator mark_gen(0.3);
    bernoulli_rand_generator pin_gen(0.2);
    size_t exp_mark_cnt = 0;
    size_t exp_pin_cnt = 0;
    std::unordered_set<byte*> pinned;
    for (int i = 0; i < OBJ_COUNT; ++i) {
        gc_alloc::response rsp = this->alloc.allocate(this->rqst, ALLOC_SIZE);
        bool pin = pin_gen();
        bool mark = mark_gen() || pin;
        if (mark) {
            exp_mark_cnt++;
            commit(rsp);
            set_mark(rsp, true);
        }
        if (pin) {
            exp_pin_cnt++;
            set_pin(rsp, true);
            pinned.insert(rsp.cell_start());
        }
    }

    auto rng = this->alloc.memory_range();

    gc_collect_stat stat;
    test_forwarding frwd;
    this->compactor(rng, frwd, stat);

    EXPECT_GE(exp_mark_cnt * ALLOC_SIZE, stat.mem_moved);

    size_t pin_cnt = 0;
    size_t mark_cnt = 0;
    for (auto cell_ptr: rng) {
        if (cell_ptr.get_mark()) {
            mark_cnt++;
        }
        if (cell_ptr.get_pin()) {
            pin_cnt++;
            EXPECT_TRUE(pinned.count(cell_ptr.cell_start()));
        }
    }

    EXPECT_EQ(exp_pin_cnt, pin_cnt);
    EXPECT_EQ(exp_mark_cnt, mark_cnt);
}


text:
define(['angular'], function(angular) {
    'use strict';

    var factory = function($http, $q, $window, API_URL) {

        var selectedList;

        function getUsersLists(userId, access_token) {
            var deferred = $q.defer();

            if (!userId || !access_token) {
                deferred.reject("Missing parameters for this call");
            }

            $http({
                url: API_URL + 'lists/search',
                method: 'GET',
                params: {
                    userId: userId,
                    access_token: access_token
                }
            }).then(function(result) {
                if (result.data && result.data.response) {
                    deferred.resolve(result.data.response);
                } else {
                    deferred.reject(result.data.meta.errorDetail[0]);
                }

            }, function(error) {
                    deferred.reject(error);
                });

            return deferred.promise;
        }

        function getList(listId, access_token) {
            var deferred = $q.defer();

            if (!listId) {
                deferred.reject("Missing parameters for this call");
            }

            $http({
                url: API_URL + 'lists/' + listId,
                method: 'GET',
                params: {
                    access_token: access_token
                }
            }).then(function(result) {
                if (result.data && result.data.response) {
                    deferred.resolve(result.data.response);
                } else {
                    deferred.reject(result.data.meta.errorDetail[0]);
                }

            }, function(error) {
                    deferred.reject(error);
                });

            return deferred.promise;
        }

        function addList(name, userId, access_token) {
            var deferred = $q.defer();

            if (!name || !userId || !access_token) {
                deferred.reject("Missing parameters for this call");
            }

            $http.post(
                API_URL + 'lists/add',
                {
                    Name: name,
                    userId: userId,
                    access_token: access_token
                }
            ).then(function(result) {
                if (result.data && result.data.response) {
                    deferred.resolve(result.data.response);
                } else {
                    deferred.reject(result.data.meta.errorDetail[0]);
                }

            }, function(error) {
                    deferred.reject(error);
                });

            return deferred.promise;
        }

        function removeList(list, access_token) {
            var deferred = $q.defer();

            if (!list || !access_token) {
                deferred.reject("Missing parameters for this call");
            }

            $http({
                url: API_URL + 'lists/' + list._id,
                method: 'DELETE',
                params: {
                    access_token: access_token
                }
            }).then(function(result) {
                if (result.data && result.data.response) {
                    deferred.resolve(result.data.response);
                } else {
                    deferred.reject(result.data.meta.errorDetail[0]);
                }

            }, function(error) {
                    deferred.reject(error);
                });

            return deferred.promise;
        }

        function updateList(list, access_token) {
            var deferred = $q.defer();

            //TODO: Figure out errors here and having them hit the controller
            /*if (!list || !access_token) {
                deferred.reject("Missing parameters for this call");
            }*/

            // Replace any objects with strings
            angular.forEach(list.Plants, function(plant, key) {
                if (angular.isObject(plant)) {
                    list.Plants[key] = plant._id;
                }
            });

            $http.post(
                API_URL + 'lists/update',
                {
                    listId: list._id,
                    Name: list.Name,
                    Plants: list.Plants,
                    access_token: access_token
                }
            ).then(function(result) {
                if (result.data && result.data.response) {
                    deferred.resolve(result.data.response);
                } else {
                    deferred.reject(result.data.meta.errorDetail[0]);
                }

            }, function(error) {
                    deferred.reject(error);
                });

            return deferred.promise;
        }

        // Return all our public functions
        return {
            getUsersLists: getUsersLists,
            getList: getList,
            addList: addList,
            updateList: updateList,
            removeList: removeList,
            selectedList: selectedList
        };

    };

    factory.$inject = ['$http', '$q', '$window', 'API_URL'];
    return factory;
});


text:
from __future__ import division, print_function

from visual import cone, vector

from operator import add
from util import interpolate, avg

class BInducer:
    """
    A magnetic (B) field inducer.
    """

    def bfield_at(self, P):
        """Calculate the magnetic field vector at a point."""
        raise NotImplementedError

class EInducer:
    """
    An electric (E) field inducer.
    """

    def efield_at(self, P):
        """Calculate the electric field vector at a point."""
        raise NotImplementedError

class Field:
    """
    The abstract base class for all fields.

    All fields are callable objects; the return value is a vector denoting the
    field strength and direction at a point. Calculation of this vector must be
    implemented in every concrete subclass. It is typically the superposition
    of fields for every inducer in the field.

    Fields maintain a list of inducers called ducs.
    """

    def __init__(self, scene, ducs = [], color = (0, 1, 0)):
        self.scene = scene
        self.ducs = ducs
        self.color = color
        self.Ps = {}

    def add_inducer(self, duc):
        """Add an inducer to this field."""
        self.ducs += [duc]

    def draw_at(self, P, step):
        """Draw the field vector at the given point."""
        B = self[P]
        if self.avg_mag == 0:
            val = 0
        else:
            #get value in between smallest and largest
            val = 1-((B.mag-self.smallest_mag)\
                     /(self.largest_mag-self.smallest_mag))
        #set size of pointers, radius = step/rad
        rad = 15
        cone(pos = P, axis = B.norm(), radius=step/rad, length=step,
                display = self.scene, color = interpolate(self.color, val),
                opacity = val)

    def draw(self, origin, size, step, radius = -1):
        """
        Draw field vectors periodically within a region.

        Drawing begins at the origin and continues by the given step up to
        and including the size. Both the size and step may be vectors or
        scalars. Scalars are equivalent to vectors with equal dimensions.
        """

        # get the origin coordinates
        x0, y0, z0 = origin

        try:
            l, h, w = size
        except TypeError:
            l = w = h = size

        try:
            step_x, step_y, step_z = step
        except TypeError:
            step_x = step_y = step_z = step

        xs = range(int(x0), int(x0+l)+1, int(step_x))
        ys = range(int(y0), int(y0+h)+1, int(step_y))
        zs = range(int(z0), int(z0+w)+1, int(step_z))

        #getting values for color interpolation
        for x in xs:
            for y in ys:
                for z in zs:
                    self[vector(x, y, z)] = self(vector(x, y, z))
        self.avg_mag = avg(B.mag for B in self.Ps.values())
        self.largest_mag = max(B.mag for B in self.Ps.values())
        #smallest mag is estimate due to absolute smallest being zero, not useful
        self.smallest_mag = self.largest_mag- 2*(self.largest_mag - self.avg_mag)

        for x in xs:
            for y in ys:
                for z in zs:
                    if (radius == -1 or (x**2 + y**2 + z**2)**0.5 <= radius):
                        self.draw_at(vector(x, y, z), step)

    def __getitem__(self, P):
        if P in self.Ps:
            return self.Ps[P]
        else:
            B = self(P)
            self.Ps[P] = B
            return B

    def __setitem__(self, P, B):
        self.Ps[P] = B

    def __call__(self, P): raise NotImplementedError

class BField(Field):
    """
    A magnetic (B) field.
    """

    def __call__(self, P):
        dbs = [duc.bfield_at(P) for duc in self.ducs]
        return reduce(add, dbs, vector(0, 0, 0))

class EField(Field):
    """
    An electric (E) field.
    """

    def __call__(self, P):
        des = [duc.efield_at(P) for duc in self.ducs]
        return reduce(add, des, vector(0, 0, 0))


text:
'use strict';

import React from 'react';
import {connect} from 'react-redux';
import {changeLevel} from  '../../../store/actions';
import PropTypes from 'prop-types';

class CLSelectLevel extends React.Component {

    constructor(props) {
        super(props);
    }

    cutLevelName(levelName) {
        if (levelName === 'Undergraduate (1st and 2nd year)') {
            return 'Undergrad. (yrs 1-2)'
        } else if (levelName === 'Undergraduate (3rd and 4th year)') {
            return 'Undergrad. (yrs 3-4)'
        }
        else {
            return levelName
        }
    }

    render() {
        let levels;
        const {level, levelList, changeLevel} = this.props;
        const levelLength = levelList.length;
        levels = levelList.map(
            (item) => {
                return <li key={item.id}
                           className={`${(level === item.name ? 'active' : '')} cl-select-item`}
                           onClick={() => {
                               changeLevel(item.id)
                           }}>{this.cutLevelName(item.name)}

            });

        return (
            <div className={`level${levelLength} cl-select-wrap`}>

Academic level:

                    {levels}

        )
    }
}
CLSelectLevel.PropTypes = {
    level: PropTypes.string.isRequired,
    levelList: PropTypes.array.isRequired
};

//container to match redux state to component props and dispatch redux actions to callback props
const mapStateToProps = (reduxState, ownProps) => {
    const state = reduxState.calculatorSmall[ownProps.calcId];
    return {
        level: state.level.name,
        levelList: state.currentLevels,
    }
};

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        changeLevel: (id) => {
            dispatch(changeLevel(id, ownProps.calcId))
        },
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(CLSelectLevel);


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.sql.planner.optimizations;

import com.google.common.collect.ImmutableList;
import io.trino.metadata.AbstractMockMetadata;
import io.trino.sql.planner.PlanNodeIdAllocator;
import io.trino.sql.planner.iterative.rule.test.PlanBuilder;
import io.trino.sql.planner.plan.Assignments;
import io.trino.sql.planner.plan.JoinNode;
import io.trino.sql.planner.plan.PlanNode;
import io.trino.sql.planner.plan.PlanNodeId;
import io.trino.sql.planner.plan.ProjectNode;
import io.trino.sql.planner.plan.ValuesNode;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.trino.sql.planner.plan.JoinNode.Type.INNER;
import static io.trino.testing.assertions.Assert.assertEquals;

public class TestPlanNodeSearcher
{
    private static final PlanBuilder BUILDER = new PlanBuilder(new PlanNodeIdAllocator(), new AbstractMockMetadata() {});

    @Test
    public void testFindAll()
    {
        int size = 10;
        ProjectNode root = BUILDER.project(Assignments.of(), BUILDER.values());
        for (int i = 1; i < size; i++) {
            root = BUILDER.project(Assignments.of(), root);
        }

        List<PlanNodeId> rootToBottomIds = new ArrayList<>();
        PlanNode node = root;
        while (node instanceof ProjectNode) {
            rootToBottomIds.add(node.getId());
            node = ((ProjectNode) node).getSource();
        }

        List<PlanNodeId> findAllResult = PlanNodeSearcher.searchFrom(root)
                .where(ProjectNode.class::isInstance)
                .findAll()
                .stream()
                .map(PlanNode::getId)
                .collect(toImmutableList());

        assertEquals(rootToBottomIds, findAllResult);
    }

    @Test
    public void testFindAllMultipleSources()
    {
        List<JoinNode> joins = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            joins.add(BUILDER.join(INNER, BUILDER.values(), BUILDER.values()));
        }
        JoinNode leftSource = BUILDER.join(INNER, joins.get(0), joins.get(1));
        JoinNode rightSource = BUILDER.join(INNER, joins.get(2), joins.get(3));
        JoinNode root = BUILDER.join(INNER, leftSource, rightSource);

        ImmutableList.Builder<PlanNodeId> idsInPreOrder = ImmutableList.builder();
        joinNodePreorder(root, idsInPreOrder);

        List<PlanNodeId> findAllResult = PlanNodeSearcher.searchFrom(root)
                .where(JoinNode.class::isInstance)
                .findAll()
                .stream()
                .map(PlanNode::getId)
                .collect(toImmutableList());

        assertEquals(idsInPreOrder.build(), findAllResult);
    }

    /**
     * This method adds PlanNodeIds of JoinNodes to the builder in pre-order.
     * The plan tree must contain only JoinNodes and ValuesNodes.
     */
    private static void joinNodePreorder(PlanNode root, ImmutableList.Builder<PlanNodeId> builder)
    {
        if (root instanceof ValuesNode) {
            return;
        }

        if (root instanceof JoinNode) {
            builder.add(root.getId());
            JoinNode join = (JoinNode) root;
            joinNodePreorder(join.getLeft(), builder);
            joinNodePreorder(join.getRight(), builder);
            return;
        }

        throw new IllegalArgumentException("unsupported node type: " + root.getClass().getSimpleName());
    }
}


text:
package com.fly.xwx.tobattle.api;

/**
 * Created by Administrator on 2016/8/11 0011.
 */
public interface ApiService {
    //例子
    //    @GET("UserDriver/getList")
//    Observable<ApiBean<ArrayList<UserDriverBean>>> loadDrivers(@Query("token") String token);
}


text:
package org.saburto.seq.gen;

public class GeneratorCommandLine {

	private static final int INPUT_FILE = 0;
	private static final int OUTPUT_FILE = 1;
	private static final String USAGE = "usage: java -jar generator.jar [inputFile] [outputFile]";
	private static final String SUCCESS_MESSAGE = "GENERATION SUCCESSFUL";

	public static void main(String[] args) {

		if(!argsAreValid(args)){
			System.err.println(USAGE);
			return;
		}

		try {
			GeneratorEA gen = new GeneratorEA(args[INPUT_FILE], args[OUTPUT_FILE]);
			gen.execute();
			System.out.println(SUCCESS_MESSAGE);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static boolean argsAreValid(String[] args) {
		return args.length >= 2 && argsHaveContents(args);
	}

	private static boolean argsHaveContents(String[] args) {
		return argHasValue(args, 0) && argHasValue(args, 1);
	}

	private static boolean argHasValue(String[] args, int i) {
		return args[i] != null && !args[i].isEmpty();
	}

}


text:
package VMOMI::VmfsDatastoreExtendSpec;
use parent 'VMOMI::VmfsDatastoreSpec';

use strict;
use warnings;

our @class_ancestors = (
    'VmfsDatastoreSpec',
    'DynamicData',
);

our @class_members = (
    ['partition', 'HostDiskPartitionSpec', 0, ],
    ['extent', 'HostScsiDiskPartition', 1, ],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
package com.cadasta.murad.backend.processor.record;

import com.cadasta.murad.models.records.Location;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by m-murad on 08/09/17.
 */

public class LocationResponseProcessor implements Callback<Location> {
    @Override
    public void onResponse(Call<Location> call, Response<Location> response) {

    }

    @Override
    public void onFailure(Call<Location> call, Throwable t) {

    }
}


text:
/**
 * Archives.tsx
 */

import * as React from "react";
import Link from "gatsby-link";
import Header from "../components/Header";
import Archives from "../components/Archives";
import PageHeader from "../components/PageHeader";
import Layout from "../components/layout";

type Props = {
  location: {
    pathname: string;
  };
};

const ArchivePage = (props: Props) => {
  const { location } = props;
  return (
    <Layout location={location}>

        <PageHeader
          title="Event Archives"
          subtitle={`To the best of our ability, we document our meetings and communications. If you missed a workshop or speaker, look here to catch up.`}
        />

        <Archives />

    </Layout>
  );
};

export default ArchivePage;


text:
Mockup Converter
================

So you have your [Bootstrap mockups](https://v4-alpha.getbootstrap.com/) in hand and now you want to make an awesome application based on [reactstrap]() components. But now you realize you are going to need to hand translate the class names in your mockups into props on your components.

```html
<button class="btn btn-large">OK!</button>
```

Needs to become:

```jsx
import { Button, } from 'reactstrap';

render() {
  return (
    <Button size="lg">OK!</Button>
  );
}
```

What a hassle! So let's fix that with `mockup-converter`. Simply install it:

```
$ npm install mockup-converter -g
```

And either run it on your file:

```
$ mockup-converter mymockup.html
```

Or run it through STDIN to `mockup-converter`:

```
$ cat mymockup.html | mockup-converter
```

Which means you can do cool things like running it through the [FilterText](https://github.com/yhirose/vscode-filtertext) extension in VSCode.

![Demo](images/demo.gif)

# What does this handle?

Most of the bootstrap classes are mapped. A few big things, like Media and Carousel aren't in there. But what's in there will get you far down the road really quickly.

# Classname passthrough

Any class name it doesn't recognize will be passed through, so:

```html
<div class="my-custom-class">Hey now!</div>
```

Becomes:

```jsx
<div className="my-custom-class">Hey now!</div>
```

And

```html
<button class="btn btn-large foo">OK!</button>
```

Becomes:

```jsx
<Button size="lg" className="foo">OK!</Button>
```

# Style handling

Styles are also broken into their react versions automagically:

```html
<div style="margin-top: 50px;padding: 5px; line-height: 2em;">
```

Becomes:

```jsx
<div style={{marginTop: 50, padding: 5, lineHeight: '2em'}}>
```

Yeah... It does that too. So honestly, it's cool to use this even if you aren't using Bootstrap or reactstrap.


text:
<?php

namespace Grido\DataSources;

use Grido\Exception;

/**
 * Dibi Fluent data source.
 *
 * @package     Grido
 * @subpackage  DataSources
 * @author      Petr Bugyík
 *
 * @property-read \Dibi\Fluent $fluent
 * @property-read int $limit
 * @property-read int $offset
 * @property-read int $count
 * @property-read array $data
 */
class DibiFluent implements IDataSource
{
    use \Nette\SmartObject;

    /** @var \Dibi\Fluent */
    protected $fluent;

    /** @var int */
    protected $limit;

    /** @var int */
    protected $offset;

    /**
     * @param \Dibi\Fluent $fluent
     */
    public function __construct(\Dibi\Fluent $fluent)
    {
        $this->fluent = $fluent;
    }

    /**
     * @return \Dibi\Fluent
     */
    public function getFluent()
    {
        return $this->fluent;
    }

    /**
     * @return int
     */
    public function getLimit()
    {
        return $this->limit;
    }

    /**
     * @return int
     */
    public function getOffset()
    {
        return $this->offset;
    }

    /**
     * @param \Grido\Components\Filters\Condition $condition
     * @param \Dibi\Fluent $fluent
     */
    protected function makeWhere(\Grido\Components\Filters\Condition $condition, \Dibi\Fluent $fluent = NULL)
    {
        $fluent = $fluent === NULL
            ? $this->fluent
            : $fluent;

        if ($condition->callback) {
            call_user_func_array($condition->callback, [$condition->value, $fluent]);
        } else {
            call_user_func_array([$fluent, 'where'], $condition->__toArray('[', ']'));
        }
    }

    /********************************** inline editation helpers ************************************/

    /**
     * Default callback used when an editable column has customRender.
     * @param mixed $id
     * @param string $idCol
     * @return \DibiRow
     */
    public function getRow($id, $idCol)
    {
        $fluent = clone $this->fluent;
        return $fluent
            ->where("%n = %s", $idCol, $id)
            ->fetch();
    }

    /*********************************** interface IDataSource ************************************/

    /**
     * @return int
     */
    public function getCount()
    {
        $fluent = clone $this->fluent;
        return $fluent->count();
    }

    /**
     * @return array
     */
    public function getData()
    {
        return $this->fluent->fetchAll($this->offset, $this->limit);
    }

    /**
     * @param array $conditions
     */
    public function filter(array $conditions)
    {
        foreach ($conditions as $condition) {
            $this->makeWhere($condition);
        }
    }

    /**
     * @param int $offset
     * @param int $limit
     */
    public function limit($offset, $limit)
    {
        $this->offset = $offset;
        $this->limit = $limit;
    }

    /**
     * @param array $sorting
     */
    public function sort(array $sorting)
    {
        foreach ($sorting as $column => $sort) {
            $this->fluent->orderBy("%n", $column, $sort);
        }
    }

    /**
     * @param mixed $column
     * @param array $conditions
     * @param int $limit
     * @return array
     * @throws Exception
     */
    public function suggest($column, array $conditions, $limit)
    {
        $fluent = clone $this->fluent;
        if (is_string($column)) {
            $fluent->removeClause('SELECT')->select("DISTINCT %n", $column)->orderBy("%n", $column, 'ASC');
        }

        foreach ($conditions as $condition) {
            $this->makeWhere($condition, $fluent);
        }

        $items = [];
        $data = $fluent->fetchAll(0, $limit);
        foreach ($data as $row) {
            if (is_string($column)) {
                $value = (string) $row[$column];
            } elseif (is_callable($column)) {
                $value = (string) $column($row);
            } else {
                $type = gettype($column);
                throw new Exception("Column of suggestion must be string or callback, $type given.");
            }

            $items[$value] = \Latte\Runtime\Filters::escapeHtml($value);
        }

        is_callable($column) && sort($items);
        return array_values($items);
    }
}


text:
<doctype html>

    <title>Icarus - Post-Login</title>

One moment please...


text:
package es.bsc.mobile.types.messages.comm;

import es.bsc.comm.Connection;
import es.bsc.comm.Node;
import es.bsc.mobile.node.P2PNode;
import es.bsc.mobile.types.messages.Message;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class StartP2P extends Message {

    private static final long serialVersionUID = 1L;

    private Node contactNode;
    private boolean responsible;

    public StartP2P() {

    }

    public StartP2P(boolean takeResponsibilities, Node newNode) {
        contactNode = newNode;
        responsible = takeResponsibilities;
    }

    public String getID() {
        return id;
    }

    public Node getContactNode() {
        return contactNode;
    }

    public boolean isResponsible() {
        return responsible;
    }

    @Override
    public void handleMessage(Connection c, P2PNode handler) {
        completeSource(contactNode, c);
        c.finishConnection();
        handler.startP2P(responsible, contactNode);
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(contactNode);
        out.writeBoolean(responsible);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        contactNode = (Node) in.readObject();
        responsible = in.readBoolean();
    }

}


text:
package org.jetbrains.plugins.scala.lang.psi.types.nonvalue

import org.jetbrains.plugins.scala.lang.psi.types._
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.{ScParameter, ScTypeParam}
import result.TypingContext
import com.intellij.psi.PsiTypeParameter
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiManager
import collection.immutable.{HashSet, HashMap}

/**
 * @author ilyas
 */

/**
 * This is internal type, no expression can have such type.
 */
trait NonValueType extends ScType {
  def isValue = false
}

/**
 * Generalized parameter. It's not psi element. So can be used in any place.
 * Some difference
 */
case class Parameter(name: String, deprecatedName: Option[String], paramType: ScType, expectedType: ScType,
                     isDefault: Boolean, isRepeated: Boolean,
                     isByName: Boolean, index: Int = -1, paramInCode: Option[ScParameter] = None) {
  def this(name: String, deprecatedName: Option[String], paramType: ScType, isDefault: Boolean, isRepeated: Boolean,
           isByName: Boolean, index: Int) {
    this(name, deprecatedName, paramType, paramType, isDefault, isRepeated, isByName, index)
  }

  def this(param: ScParameter) {
    this(param.name, param.deprecatedName, param.getType(TypingContext.empty).getOrAny, param.getType(TypingContext.empty).getOrAny,
      param.isDefaultParam, param.isRepeatedParameter, param.isCallByNameParameter, param.index, Some(param))
  }
}
case class TypeParameter(name: String, typeParams: Seq[TypeParameter], lowerType: ScType, upperType: ScType,
                         ptp: PsiTypeParameter) {
  def this(ptp: PsiTypeParameter) {
    this(ptp match {
      case tp: ScTypeParam => tp.name
      case _ => ptp.getName
    }, ptp match {
      case tp: ScTypeParam => tp.typeParameters.map(new TypeParameter(_))
      case _ => Seq.empty
    }, ptp match {
      case tp: ScTypeParam => tp.lowerBound.getOrNothing
      case _ => Nothing //todo: lower type?
    }, ptp match {
      case tp: ScTypeParam => tp.upperBound.getOrAny
      case _ => Any //todo: upper type?
    }, ptp)
  }

  def update(fun: ScType => ScType): TypeParameter = {
    new TypeParameter(name, typeParams.map(_.update(fun)), fun(lowerType), fun(upperType), ptp)
  }
}

case class ScMethodType(returnType: ScType, params: Seq[Parameter], isImplicit: Boolean)
                       (val project: Project, val scope: GlobalSearchScope) extends NonValueType {

  def visitType(visitor: ScalaTypeVisitor) {
    visitor.visitMethodType(this)
  }

  def inferValueType: ValueType = {
    ScFunctionType(returnType.inferValueType, params.map(p => {
      val inferredParamType = p.paramType.inferValueType
      if (!p.isRepeated) inferredParamType
      else {
        val seqClass = ScalaPsiManager.instance(project).getCachedClass(scope, "scala.collection.Seq")
        if (seqClass == null) inferredParamType
        else ScParameterizedType(ScDesignatorType(seqClass), Seq(inferredParamType))
      }
    }))(project, scope)
  }

  override def removeAbstracts = new ScMethodType(returnType.removeAbstracts,
    params.map(p => p.copy(paramType = p.paramType.removeAbstracts)), isImplicit)(project, scope)

  override def recursiveUpdate(update: ScType => (Boolean, ScType), visited: HashSet[ScType]): ScType = {
    if (visited.contains(this)) {
      return update(this) match {
        case (true, res) => res
        case _ => this
      }
    }
    val newVisited = visited + this
    update(this) match {
      case (true, res) => res
      case _ =>
        new ScMethodType(returnType.recursiveUpdate(update, newVisited),
          params.map(p => p.copy(paramType = p.paramType.recursiveUpdate(update, newVisited))), isImplicit)(project, scope)
    }
  }

  override def recursiveVarianceUpdateModifiable[T](data: T, update: (ScType, Int, T) => (Boolean, ScType, T),
                                           variance: Int = 1): ScType = {
    update(this, variance, data) match {
      case (true, res, _) => res
      case (_, _, newData) =>
        new ScMethodType(returnType.recursiveVarianceUpdateModifiable(newData, update, variance),
          params.map(p => p.copy(paramType = p.paramType.recursiveVarianceUpdateModifiable(newData, update, -variance))),
          isImplicit)(project, scope)
    }
  }

  override def equivInner(r: ScType, uSubst: ScUndefinedSubstitutor, falseUndef: Boolean): (Boolean, ScUndefinedSubstitutor) = {
    var undefinedSubst = uSubst
    r match {
      case m: ScMethodType =>
        if (m.params.length != params.length) return (false, undefinedSubst)
        var t = Equivalence.equivInner(m.returnType, returnType,undefinedSubst, falseUndef)
        if (!t._1) return (false, undefinedSubst)
        undefinedSubst = t._2
        var i = 0
        while (i < params.length) {
          //todo: Seq[Type] instead of Type*
          if (params(i).isRepeated != m.params(i).isRepeated) return (false, undefinedSubst)
          t = Equivalence.equivInner(params(i).paramType, m.params(i).paramType, undefinedSubst, falseUndef)
          if (!t._1) return (false, undefinedSubst)
          undefinedSubst = t._2
          i = i + 1
        }
        (true, undefinedSubst)
      case _ => (false, undefinedSubst)
    }
  }
}

case class ScTypePolymorphicType(internalType: ScType, typeParameters: Seq[TypeParameter]) extends NonValueType {
  if (internalType.isInstanceOf[ScTypePolymorphicType]) {
    throw new IllegalArgumentException("Polymorphic type can't have wrong internal type")
  }

  def polymorphicTypeSubstitutor: ScSubstitutor = polymorphicTypeSubstitutor(inferValueType = false)

  def polymorphicTypeSubstitutor(inferValueType: Boolean): ScSubstitutor =
    new ScSubstitutor(new HashMap[(String, String), ScType] ++ typeParameters.map(tp => {
      var contraVariant = 0
      var coOrInVariant = 0
      internalType.recursiveVarianceUpdate {
        case (typez: ScType, i: Int) =>
          val pair = typez match {
            case tp: ScTypeParameterType => (tp.name, ScalaPsiUtil.getPsiElementId(tp.param))
            case ScUndefinedType(tp) => (tp.name, ScalaPsiUtil.getPsiElementId(tp.param))
            case ScAbstractType(tp, _, _) => (tp.name, ScalaPsiUtil.getPsiElementId(tp.param))
            case _ => null
          }
          if (pair != null) {
            if ((tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)) == pair) {
              if (i == -1) contraVariant += 1
              else coOrInVariant += 1
            }
          }
          (false, typez)
      }
      if (coOrInVariant == 0 && contraVariant != 0)
        ((tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)), tp.upperType.inferValueType)
      else
        ((tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)), tp.lowerType.inferValueType)
    }), Map.empty, None)

  def polymorphicTypeSubstitutorMissedEmptyParams: ScSubstitutor =
    new ScSubstitutor(new HashMap[(String, String), ScType] ++ typeParameters.flatMap(tp => {
      var contraVariant = 0
      var coOrInVariant = 0
      internalType.recursiveVarianceUpdate {
        case (typez: ScType, i: Int) =>
          val pair = typez match {
            case tp: ScTypeParameterType => (tp.name, ScalaPsiUtil.getPsiElementId(tp.param))
            case ScUndefinedType(tp) => (tp.name, ScalaPsiUtil.getPsiElementId(tp.param))
            case ScAbstractType(tp, _, _) => (tp.name, ScalaPsiUtil.getPsiElementId(tp.param))
            case _ => null
          }
          if (pair != null) {
            if ((tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)) == pair) {
              if (i == -1) contraVariant += 1
              else coOrInVariant += 1
            }
          }
          (false, typez)
      }
      if (coOrInVariant == 0 && contraVariant != 0)
        Seq(((tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)), tp.upperType))
      else if (coOrInVariant != 0)
        Seq(((tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)), tp.lowerType))
      else Seq.empty
    }),  Map.empty, None)

  def abstractTypeSubstitutor: ScSubstitutor = {
    def hasRecursiveTypeParameters(typez: ScType): Boolean = {
      var hasRecursiveTypeParameters = false
      typez.recursiveUpdate {
        case tpt: ScTypeParameterType =>
          typeParameters.find(tp => (tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)) == (tpt.name, tpt.getId)) match {
            case None => (true, tpt)
            case _ =>
              hasRecursiveTypeParameters = true
              (true, tpt)
          }
        case tp: ScType => (hasRecursiveTypeParameters, tp)
      }
      hasRecursiveTypeParameters
    }
    new ScSubstitutor(new HashMap[(String, String), ScType] ++ typeParameters.map(tp => {
      val lowerType: ScType = if (hasRecursiveTypeParameters(tp.lowerType)) Nothing else tp.lowerType
      val upperType: ScType = if (hasRecursiveTypeParameters(tp.upperType)) Any else tp.upperType
      ((tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)),
              new ScAbstractType(new ScTypeParameterType(tp.ptp, ScSubstitutor.empty), lowerType, upperType))
    }), Map.empty, None)
  }

  def typeParameterTypeSubstitutor: ScSubstitutor =
    new ScSubstitutor(new HashMap[(String, String), ScType] ++ typeParameters.map(tp => ((tp.name, ScalaPsiUtil.getPsiElementId(tp.ptp)),
            new ScTypeParameterType(tp.ptp, ScSubstitutor.empty))), Map.empty, None)

  def inferValueType: ValueType = {
    polymorphicTypeSubstitutor(inferValueType = true).subst(internalType.inferValueType).asInstanceOf[ValueType]
  }

  override def removeAbstracts = ScTypePolymorphicType(internalType.removeAbstracts, typeParameters.map(tp => {
    TypeParameter(tp.name, tp.typeParams /* todo: ? */, tp.lowerType.removeAbstracts, tp.upperType.removeAbstracts, tp.ptp)
  }))

  override def recursiveUpdate(update: ScType => (Boolean, ScType), visited: HashSet[ScType]): ScType = {
    if (visited.contains(this)) {
      return update(this) match {
        case (true, res) => res
        case _ => this
      }
    }
    val newVisited = visited + this
    update(this) match {
      case (true, res) => res
      case _ =>
        ScTypePolymorphicType(internalType.recursiveUpdate(update, newVisited), typeParameters.map(tp => {
          TypeParameter(tp.name, tp.typeParams /* todo: ? */, tp.lowerType.recursiveUpdate(update, newVisited),
            tp.upperType.recursiveUpdate(update, newVisited), tp.ptp)
        }))
    }
  }

  override def recursiveVarianceUpdateModifiable[T](data: T, update: (ScType, Int, T) => (Boolean, ScType, T),
                                           variance: Int = 1): ScType = {
    update(this, variance, data) match {
      case (true, res, _) => res
      case (_, _, newData) =>
        ScTypePolymorphicType(internalType.recursiveVarianceUpdateModifiable(newData, update, variance), typeParameters.map(tp => {
          TypeParameter(tp.name, tp.typeParams /* todo: ? */, tp.lowerType.recursiveVarianceUpdateModifiable(newData, update, -variance),
            tp.upperType.recursiveVarianceUpdateModifiable(newData, update, variance), tp.ptp)
        }))
    }
  }

  override def equivInner(r: ScType, uSubst: ScUndefinedSubstitutor,
                          falseUndef: Boolean): (Boolean, ScUndefinedSubstitutor) = {
    var undefinedSubst = uSubst
    r match {
      case p: ScTypePolymorphicType => {
        if (typeParameters.length != p.typeParameters.length) return (false, undefinedSubst)
        var i = 0
        while (i < typeParameters.length) {
          var t = Equivalence.equivInner(typeParameters(i).lowerType,
            p.typeParameters(i).lowerType, undefinedSubst, falseUndef)
          if (!t._1) return (false,undefinedSubst)
          undefinedSubst = t._2
          t = Equivalence.equivInner(typeParameters(i).upperType,
            p.typeParameters(i).upperType, undefinedSubst, falseUndef)
          if (!t._1) return (false, undefinedSubst)
          undefinedSubst = t._2
          i = i + 1
        }
        val subst = new ScSubstitutor(new collection.immutable.HashMap[(String, String), ScType] ++
                typeParameters.zip(p.typeParameters).map({
          tuple => ((tuple._1.name, ScalaPsiUtil.getPsiElementId(tuple._1.ptp)), new ScTypeParameterType(tuple._2.name,
            tuple._2.ptp match {
              case p: ScTypeParam => p.typeParameters.toList.map{new ScTypeParameterType(_, ScSubstitutor.empty)}
              case _ => Nil
            }, tuple._2.lowerType, tuple._2.upperType, tuple._2.ptp))
        }), Map.empty, None)
        Equivalence.equivInner(subst.subst(internalType), p.internalType, undefinedSubst, falseUndef)
      }
      case _ => (false, undefinedSubst)
    }
  }

  def visitType(visitor: ScalaTypeVisitor) {}
}


text:
Proposed changes in this pull-request:

-
-
-

---

*Please make sure that you read the guidelines and test your code before submission, or else your request might be rejected*


text:
layout: post
title: "Implementing REST Webservice Using Spring and JBoss's RESTEasy"
published: ture
---

Here is a quick intro on how to implement a RESTFul webservice in five minutes using Spring and RESTEasy integration and Jackson to handle processing of the deserialized JSON objects.
RESTEasy is JBOSS provided implementation of JAX-RS specification.

Configurations
==============

(1) First and foremost, modify your pom.xml to add the required dependencies (The actual versions may vary depending on what's the lastest):

    <dependencies>
       <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-jaxrs</artifactId>
          <version>1.9.2</version>
       <dependency>

       <dependency>
          <groupId>org.jboss.resteasy</groupId>
          <artifactId>resteasy-spring</artifactId>
          <version>2.3.4.Final</version>
       </dependency>

       <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>3.2.8.RELEASE</version>
       </dependency>

       <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-beans</artifactId>
         <version>3.2.8.RELEASE</version>
    </dependencies>

(2) Specify the jaxrs provider, and add the RESTEasy bootstrap listener to your web.xml:

    <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <context-param>
       <param-name>resteasy.providers</param-name>
       <param-value>org.codehaus.jackson.jaxrs.JacksonJsonProvider</param-value>
    </context-param>

    <listener>
 	<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasoyBootStrap</listener-class>
    </listener>

    <listener>
	<listener-class>org.jboss.resteasy.plugins.spring.SpringContextLoaderListener</listener-class>
    </listener>

(3) Finally, add the resteasy specific servlet mapping to your web.xml

    <serverlet>
	 <servlet-name>my-service-servlet</servlet-name>
         <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
    </servlet>

    <servelet-mapping>
       <servlet-name>my-service-servlet</servlet-name>
       <url-pattern>/*</url-pattern>
    </servlet-mapping>

Sample Code
===========

Below are sample Java code that shows how to define a REST service endpoint and write a simple Authorization REST Service. Make sure to enable component scan and set annotation-config to "true" in your applicationContext.xml so that the resource and service are recognized by Spring at startup:

    import javax.ws.rs.*;
    import javax.ws.core.MediaType;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.RequestBody;

    @Component
    @Path("/authorize")
    @Produces(MediaType.APPLICATION_JSON)

    public class AuthorizeResource {

      @Autowired
      private AuthorizationService authorizationService;

      @POST
      @Path("/roles")
      public UMResponse getUserRoles(@RequestBody UMRequest umRequest) throws Exception {
         return authorizationService.getUserRoles(umRequest.getFullDn());
      }
    }

    public class UMResponse {

      protected String fullDn;
      @JsonProperty("roles")
      private List<String> userRoles;

      public List<String> getUserRoles() {
         return userRoles;
      }

      public void setUserRoles(List<String> roles) {
         this.userRoles = roles;
      }

    }

Customization
=============

In some cases, you may wish to customize how a JSON object should be serialized.
The example below creates a custom Jackson JSON provider that serializes date objects into "yyyy-mm-dd'Z'" date format and skips serialization of null values. To utilize this, specify this class in the context-param in your web.xml.

    import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.map.annotate.JsonSerialize;
    import javax.ws.rs.core.MultivaluedMap;
    import javax.ws.rs.ext.Provider;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Type;
    import java.text.SimpleDateFormat;

    @Provider
    public class customJacksonProvider extends JacksonJsonProvider {
       public void writeTo(Object value,
                      Class<?> type,
                      Type genericType,
                      Annotation[] annotations,
                      javax.ws.rs.core.MediaType mediaType,
                      MultivaluedMap<String, Object> httpHeaders,
                      OutputStream entityStream) throws IOException{
          final String DATE_FORMAT = "yyyy-mm-dd'Z'";

          ObjectMapper mapper = locateMapper(type, mediaType);
          mapper.setSerializationInclusion(JsonSerialzie.Inclusion.NON_NULL);
          mapper.setDateFormat(new SimpleDateFormat(DATE_FORMAT));
          super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
       }
    }


text:
/*
 * Define new class Student which is derived from Human and has new field – grade
 */

namespace StudentsAndWorkers
{
    using System;

    public class Student : Human
    {
        private int grade;

        public Student(string firstName, string lastName, int grade) : base(firstName, lastName)
        {
            this.Grade = grade;
        }

        public int Grade
        {
            get
            {
                return this.grade;
            }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException("Grade must be possitive");
                }

                this.grade = value;
            }
        }

        public override string ToString()
        {
            return string.Format("{0} {1}, grade: {2}", this.FirstName, this.LastName, this.grade);
        }
    }
}


text:
  <mat-form-field class="textInput">
    <mat-select i18n-placeholder="services.form.label.type"
               [placeholder]="messages.services_form_label_type"
               [(ngModel)]="type"
               (change)="changeType()">
      <mat-option *ngFor="let opt of types; let i = index" [value]="opt">
        {{ display[i] }}
      </mat-option>
    </mat-select>
  </mat-form-field>


text:
<?php

namespace Michalmanko\Holiday\Provider;

use ArrayObject;

/**
 * Hamburg (state of Germany) Holidays Provider.
 *
 * @author ottowayne <mr.ottowayne@gmail.com>
 */
class GermanyHH extends Germany
{
    /**
     * {@inheritdoc}
     */
    protected function prepareHolidays($year)
    {
        /** @var ArrayObject $data */
        $data = new ArrayObject(parent::prepareHolidays($year));

        return $data;
    }
}


text:
<bill session="110" type="hc" number="438" updated="2009-01-08T16:22:49-05:00">
	<status><introduced date="1222488000" datetime="2008-09-27"/></status>

	<introduced date="1222488000" datetime="2008-09-27"/>
	<titles>
		<title type="official" as="introduced">Expressing the sense of Congress with regard to providing humanitarian assistance to countries of the Caribbean devastated by Hurricanes Gustav and Ike and Tropical Storms Fay and Hanna.</title>
	</titles>
	<sponsor id="400237"/>
	<cosponsors>
		<cosponsor id="400661" joined="2008-09-27"/>
		<cosponsor id="400073" joined="2008-09-27"/>
		<cosponsor id="400199" joined="2008-09-27"/>
		<cosponsor id="400080" joined="2008-09-27"/>
		<cosponsor id="412221" joined="2008-09-27"/>
		<cosponsor id="400333" joined="2008-09-27"/>
		<cosponsor id="400295" joined="2008-09-27"/>
		<cosponsor id="400170" joined="2008-09-27"/>
		<cosponsor id="400424" joined="2008-09-27"/>
		<cosponsor id="400423" joined="2008-09-27"/>
		<cosponsor id="400409" joined="2008-09-27"/>
		<cosponsor id="400130" joined="2008-09-27"/>
		<cosponsor id="400030" joined="2008-09-27"/>
		<cosponsor id="400312" joined="2008-10-02"/>
		<cosponsor id="400048" joined="2008-09-27"/>
		<cosponsor id="412199" joined="2008-09-27"/>
		<cosponsor id="412263" joined="2008-09-27"/>
		<cosponsor id="400270" joined="2008-09-27"/>
		<cosponsor id="400422" joined="2008-09-27"/>
		<cosponsor id="400350" joined="2008-09-27"/>
		<cosponsor id="400201" joined="2008-09-27"/>
		<cosponsor id="400204" joined="2008-09-27"/>
		<cosponsor id="400090" joined="2008-09-27"/>
		<cosponsor id="400240" joined="2008-09-27"/>
		<cosponsor id="400363" joined="2008-09-27"/>
	</cosponsors>
	<actions>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to the House Committee on Foreign Affairs.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	9/27/2008--Introduced.
Commends the governments of the Caribbean countries and the Caribbean-American community for their efforts to assist the people of the region after the devastation caused by Hurricanes Gustav and Ike and Tropical Storms Fay and Hanna. Supports the Administration's efforts to assist in coordinating international humanitarian assistance to help the people of the Caribbean region and to provide relief to affected communities, particularly in the Dominican Republic, Haiti, Jamaica, the Bahamas, Cuba, and Turks and Caicos.

</bill>


text:
package net.npg.abattle.common.utils;

/**
 * (not a correct visitor pattern!)
 *
 * @author cymric
 *
 */
public abstract class FieldVisitor {

	public void visit(final int x, final int y) {
		// nothing to do
	}

	public void visitRowEnd(final int y) {
		// nothing to do
	}

	public void visitRowStart(final int y) {
		// nothing to do
	}
}


text:
#include <aws/imagebuilder/model/ListImagePipelinesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::imagebuilder::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

ListImagePipelinesResult::ListImagePipelinesResult()
{
}

ListImagePipelinesResult::ListImagePipelinesResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ListImagePipelinesResult& ListImagePipelinesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("requestId"))
  {
    m_requestId = jsonValue.GetString("requestId");

  }

  if(jsonValue.ValueExists("imagePipelineList"))
  {
    Array<JsonView> imagePipelineListJsonList = jsonValue.GetArray("imagePipelineList");
    for(unsigned imagePipelineListIndex = 0; imagePipelineListIndex < imagePipelineListJsonList.GetLength(); ++imagePipelineListIndex)
    {
      m_imagePipelineList.push_back(imagePipelineListJsonList[imagePipelineListIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("nextToken"))
  {
    m_nextToken = jsonValue.GetString("nextToken");

  }

  return *this;
}


text:
package nablarch.core.dataformat.convertor;

import nablarch.core.dataformat.convertor.datatype.Bytes;
import nablarch.core.dataformat.convertor.datatype.SingleByteCharacterString;
import nablarch.core.dataformat.convertor.logicbased.CustomType;
import nablarch.core.repository.SystemRepository;
import nablarch.core.repository.di.ComponentDefinitionLoader;
import nablarch.core.repository.di.DiContainer;
import nablarch.core.repository.di.config.xml.XmlComponentDefinitionLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Map;
import java.util.Map.Entry;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertSame;

/**
 * FixedLengthConvertorのテスト。
 *
 * 観点:
 * デフォルト設定での動作は別のテストで確認しているので、ここではリポジトリから設定できることのテストを行う。
 *
 * @author Masato Inoue
 */
public class FixedLengthConvertorSettingTest {

    @Before
    public void setUp() throws Exception {
        SystemRepository.clear();
    }

    @After
    public void tearDown() throws Exception {
        SystemRepository.clear();
    }

    /**
     * コンバータをリポジトリから設定するテスト
     */
    @Test
    public void testRepository() throws Exception {
        // テスト用のリポジトリ構築
        ComponentDefinitionLoader loader = new XmlComponentDefinitionLoader(
                "nablarch/core/dataformat/convertor/ConvertorSetting.xml");
        DiContainer container = new DiContainer(loader);
        SystemRepository.load(container);

        FixedLengthConvertorSetting setting = FixedLengthConvertorSetting.getInstance();
        Map<String, Class<?>> resultTable = setting.getConvertorFactory().getConvertorTable();
        assertSame(SingleByteCharacterString.class, resultTable.get("Test"));
        assertSame(Bytes.class, resultTable.get("Hoge"));
    }

    /**
     * 後方互換用の空文字列を{@code null}にするフラグが
     * デフォルトで{@code true}になってること。
     */
    @Test
    public void testDefaultConvertEmptyToNull() throws Exception {
        FixedLengthConvertorSetting setting = FixedLengthConvertorSetting.getInstance();

        assertThat(setting.isConvertEmptyToNull(), is(true));
    }

    /**
     * 後方互換用の空文字列を{@code null}にするフラグが
     * 設定を記述することで{@code false}になること。
     */
    @Test
    public void testSetConvertEmptyToNull() throws Exception {
        XmlComponentDefinitionLoader loader = new XmlComponentDefinitionLoader("nablarch/core/dataformat/convertor/ConvertorSettingCompatible.xml");
        DiContainer container = new DiContainer(loader);
        SystemRepository.load(container);

        FixedLengthConvertorSetting setting = FixedLengthConvertorSetting.getInstance();
        assertThat(setting.isConvertEmptyToNull(), is(false));
    }

    /**
     * コンバータファクトリをリポジトリから設定するテスト
     */
    @Test
    public void testCustomConvertorFactory() throws Exception {
        ComponentDefinitionLoader loader = new XmlComponentDefinitionLoader(
                "nablarch/core/dataformat/convertor/LogicBasedSetting.xml");
        DiContainer container = new DiContainer(loader);
        SystemRepository.load(container);

        FixedLengthConvertorSetting setting = FixedLengthConvertorSetting.getInstance();
        Map<String, Class<?>> resultTable = setting.getConvertorFactory().getConvertorTable();
        assertSame("データタイプが追加されていること", CustomType.class, resultTable.get("custom"));

        Map<String, Class<?>> defaultTable = new FixedLengthConvertorFactory().getDefaultConvertorTable();
        assertThat("デフォルトから1つだけ追加されていること", resultTable.size(), is(defaultTable.size() + 1));
        for (Entry<String, Class<?>> entry : defaultTable.entrySet()) {
            assertSame("デフォルトと同一のデータタイプが設定されていること", entry.getValue(), resultTable.get(entry.getKey()));
        }
    }
}