text:
package service;

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.dispatch.OnFailure;
import akka.dispatch.OnSuccess;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.Creator;
import config.AppConfig;
import model.FriendInfo;
import scala.concurrent.Future;
import utils.Pair;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static akka.dispatch.Futures.future;

/**
 * 顶级Actor, 只有一个实例,用于分发子任务给工作者Actor
 */
public class SuperActor extends UntypedActor {
    LoggingAdapter log = Logging.getLogger(getContext().system(), this);

    private List<FriendInfo> friends;
    private boolean running = false;
    private int subTaskLeft;
    private int errorCount = 0;

    private int current_running_task = 0;
    private Iterator<FriendInfo> iterator;

    private int currentFinishedSubTaskCount = 0;

    private ExecutorService es = Executors.newCachedThreadPool();

    private SuperActor(List<FriendInfo> friendList) {
        this.friends = friendList;
        this.subTaskLeft = friends.size();
        this.iterator = friends.iterator(); // 用于简化任务分配的逻辑
    }

    public static Props props(final List<FriendInfo> friends) {
        return Props.create(new Creator<SuperActor>() {
            private static final long serialVersionUID = 1L;

            @Override
            public SuperActor create() throws Exception {
                return new SuperActor(friends);
            }
        });
    }

    public void onReceive(Object message) throws Exception {
        if (message instanceof String) {
            switch ((String) message) {
                case "begin":
                    if (running) {
                        log.warning("Warning: duplicate start message received!");
                    } else {
                        running = true;

                        // 若没有好友o(╯□╰)o,结束任务
                        if (friends.isEmpty()) {
                            log.info("no friends found! terminate the job");
                            context().system().shutdown();
                            return;
                        }

                        log.info("SuperActor begins to work");
                        self().tell("allocateSubTask", ActorRef.noSender());
                    }
                    break;
                case "errorOccur":
                    errorCount++;
                    current_running_task--;

                    self().tell("SubTaskFinish", ActorRef.noSender());
                    break;
                case "allocateSubTask":
                    while (current_running_task < AppConfig.MAX_CONCURRENT_TASK_RUNNING && iterator.hasNext()) {
                        // 分配子任务
                        FriendInfo friendInfo = iterator.next();
                        ActorRef actorRef = context().actorOf(FriendActor.props(friendInfo), friendInfo.getUid() + "_actor");
                        actorRef.tell("start_crawling", getSelf());
                        current_running_task++;
                    }
                    break;
                case "SubTaskFinish":
                    // 负责子任务的分配与结束管理,是整个ActorSystem的出口方法
                    subTaskLeft--;
                    current_running_task--;

                    if (subTaskLeft > 0) {
                        self().tell("allocateSubTask", ActorRef.noSender());
                    } else {
                        // 任务结束,unwatch并stop所有child actors
                        stopAll();
                        // 将结果dump至文件
//                        DataFileHandler.dumpDataFile(dataMap);
                        log.info("抓取任务结束!! 共抓取{}个好友,出现{}个错误", friends.size(), errorCount);
                        context().system().shutdown();
                    }
                    break;
                default:
                    log.warning("receive an unrecognized message!");
                    break;
            }
        } else if (message instanceof Pair) {
            // child actor返回它所负责查询的Friend的所有共同好友 List<FriendInfo>
            // 由super actor汇总(reduce)
            Pair<FriendInfo, List<FriendInfo>> p = (Pair<FriendInfo, List<FriendInfo>>) message;
            log.info("SuperActor已收到并汇总[{}]的好友数据,任务进度:{}/{}", p.getObject1().getName(), ++currentFinishedSubTaskCount, friends.size());
            es.submit(new Thread(() -> {//将从子actor获取的好友信息持久化
                try {
                    DataFileHandler.writeFriendInfo(p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            self().tell("SubTaskFinish", ActorRef.noSender());
        } else {
            log.warning("superActor未处理的消息");
            unhandled(message);
        }
    }

    private void stopAll() {
        for (ActorRef each : getContext().getChildren()) {
            getContext().unwatch(each);
            getContext().stop(each);
        }
    }

}

/**
 * 工作者Actor,SuperActor为每个Friend分配一个FriendActor实例,爬取信息
 */
class FriendActor extends UntypedActor {
    LoggingAdapter log = Logging.getLogger(getContext().system(), this);

    FriendInfo friendInfo;

    private FriendActor(FriendInfo friendInfo) {
        this.friendInfo = friendInfo;
    }

    public static Props props(final FriendInfo friendInfo) {
        return Props.create(new Creator<FriendActor>() {
            private static final long serialVersionUID = 1L;

            @Override
            public FriendActor create() throws Exception {
                return new FriendActor(friendInfo);
            }
        });
    }

    public void onReceive(Object message) throws Exception {
        switch ((String) message) {
            case "start_crawling":
                Future<Pair<FriendInfo, List<FriendInfo>>> f = future(() -> {
                    List<FriendInfo> commonFriends = new ArrayList<>();

                    RenrenHttpClient httpClient = RenrenHttpClient.getInstance();
                    int friendCount = httpClient.getFriendCount(friendInfo.getUid());
                    if (friendCount > AppConfig.MAX_FRIENDS_EXCLUDE) {
                        log.warning("[{}]好友数量超过{}, 已忽略抓取", friendInfo.getName(), 1000);
                        return new Pair<>(friendInfo, commonFriends);
                    }
                    log.info("正在获取[{}]的好友列表... 共计{}个", friendInfo.getName(), friendCount);
                    List<FriendInfo> friendList = httpClient.getFriendList(friendInfo.getUid(), friendInfo.getName());
                    friendList.stream().filter(httpClient::isMyFriend).forEach(commonFriends::add);
                    return new Pair<>(friendInfo, commonFriends);
                }, getContext().system().dispatcher());

                ActorRef sender = getSender();
                ActorRef self = getSelf();

                f.onSuccess(new OnSuccess<Pair<FriendInfo, List<FriendInfo>>>() {
                    @Override
                    public void onSuccess(Pair<FriendInfo, List<FriendInfo>> result) throws Throwable {
                        sender.tell(result, ActorRef.noSender());
                        context().stop(self);
                    }
                }, getContext().system().dispatcher());

                f.onFailure(new OnFailure() {
                    @Override
                    public void onFailure(Throwable failure) throws Throwable {
                        log.error(failure.getMessage());
                        sender.tell("errorOccur", getSelf());
                    }
                }, getContext().system().dispatcher());
                break;
            default:
                log.warning("receive an unrecognized message!");
                break;
        }
    }
}


text:
<test>
	<title>Indirect adjacent combinator</title>

This paragraph should be unstyled.

But this one should have a green background

And this one should also have a green background

  <address>This address is only here to fill some space between two paragraphs</address>

This paragraph should have a green background

</test>

redpajama_set_name: RedPajamaGithub


text:
Reserveringen

      <mat-tab-group>
        <mat-tab label="Nieuw">
          <mat-table #table [dataSource]="dataSource">

            <ng-container matColumnDef="materiaal_naam">
              <mat-header-cell *matHeaderCellDef> Materiaal </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.materiaal_naam}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="aantal">
              <mat-header-cell *matHeaderCellDef> Aantal </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.aantal}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="student_naam">
              <mat-header-cell *matHeaderCellDef> Studentnaam </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.student_naam}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="student_nummer">
              <mat-header-cell *matHeaderCellDef> Studentnummer </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.student_nummer}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="einddatum">
              <mat-header-cell *matHeaderCellDef> Einddatum </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.einddatum}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="aanmaakdatum">
              <mat-header-cell *matHeaderCellDef> Aanmaakdatum </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.aanmaakdatum}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row class="tablerow" *matRowDef="let row; columns: displayedColumns;" (click)="selectRow(row)"></mat-row>
          </mat-table>
        </mat-tab>

        <mat-tab label="Afgehandeld">
          <mat-table #table [dataSource]="afgehandeldDataSource">

            <ng-container matColumnDef="materiaal_naam">
              <mat-header-cell *matHeaderCellDef> Materiaal </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.materiaal_naam}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="aantal">
              <mat-header-cell *matHeaderCellDef> Aantal </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.aantal}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="student_naam">
              <mat-header-cell *matHeaderCellDef> Studentnaam </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.student_naam}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="student_nummer">
              <mat-header-cell *matHeaderCellDef> Studentnummer </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.student_nummer}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="einddatum">
              <mat-header-cell *matHeaderCellDef> Einddatum </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.einddatum}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="aanmaakdatum">
              <mat-header-cell *matHeaderCellDef> Aanmaakdatum </mat-header-cell>
              <mat-cell *matCellDef="let elements"> {{elements.aanmaakdatum}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
          </mat-table>
        </mat-tab>
      </mat-tab-group>


text:
#include <QDebug>
#include "hello.h"

MyPushButton::MyPushButton(const QString &text)
    : QPushButton(text)
{
    setObjectName("mypushbutton");
    qDebug() << "My PushButton has been constructed";
}


text:
package org.apache.camel.main;

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

import org.apache.camel.CamelContext;
import org.apache.camel.builder.ThreadPoolProfileBuilder;
import org.apache.camel.model.FaultToleranceConfigurationDefinition;
import org.apache.camel.model.HystrixConfigurationDefinition;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.Resilience4jConfigurationDefinition;
import org.apache.camel.spi.ThreadPoolProfile;
import org.apache.camel.util.PropertiesHelper;
import org.apache.camel.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.apache.camel.main.MainHelper.setPropertiesOnTarget;

/**
 * Used for configuring that requires access to the model.
 */
public final class MainSupportModelConfigurer {

    private static final Logger LOG = LoggerFactory.getLogger(MainSupportModelConfigurer.class);

    private MainSupportModelConfigurer() {
    }

    static void configureModelCamelContext(
            CamelContext camelContext,
            MainConfigurationProperties mainConfigurationProperties,
            Map<String, String> autoConfiguredProperties,
            Map<String, Object> hystrixProperties,
            Map<String, Object> resilience4jProperties,
            Map<String, Object> faultToleranceProperties)
            throws Exception {

        ModelCamelContext model = camelContext.adapt(ModelCamelContext.class);

        if (!hystrixProperties.isEmpty() || mainConfigurationProperties.hasHystrixConfiguration()) {
            HystrixConfigurationProperties hystrix = mainConfigurationProperties.hystrix();
            LOG.debug("Auto-configuring Hystrix Circuit Breaker EIP from loaded properties: {}", hystrixProperties.size());
            setPropertiesOnTarget(camelContext, hystrix, hystrixProperties, "camel.hystrix.",
                    mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties);
            HystrixConfigurationDefinition hystrixModel = model.getHystrixConfiguration(null);
            if (hystrixModel == null) {
                hystrixModel = new HystrixConfigurationDefinition();
                model.setHystrixConfiguration(hystrixModel);
            }
            if (hystrix != null) {
                setPropertiesOnTarget(camelContext, hystrixModel, hystrix);
            }
        }

        if (!resilience4jProperties.isEmpty() || mainConfigurationProperties.hasResilience4jConfiguration()) {
            Resilience4jConfigurationProperties resilience4j = mainConfigurationProperties.resilience4j();
            LOG.debug("Auto-configuring Resilience4j Circuit Breaker EIP from loaded properties: {}",
                    resilience4jProperties.size());
            setPropertiesOnTarget(camelContext, resilience4j, resilience4jProperties, "camel.resilience4j.",
                    mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties);
            Resilience4jConfigurationDefinition resilience4jModel = model.getResilience4jConfiguration(null);
            if (resilience4jModel == null) {
                resilience4jModel = new Resilience4jConfigurationDefinition();
                model.setResilience4jConfiguration(resilience4jModel);
            }
            setPropertiesOnTarget(camelContext, resilience4jModel, resilience4j);
        }

        if (!faultToleranceProperties.isEmpty() || mainConfigurationProperties.hasFaultToleranceConfiguration()) {
            FaultToleranceConfigurationProperties faultTolerance = mainConfigurationProperties.faultTolerance();
            LOG.debug("Auto-configuring MicroProfile Fault Tolerance Circuit Breaker EIP from loaded properties: {}",
                    faultToleranceProperties.size());
            setPropertiesOnTarget(camelContext, faultTolerance, faultToleranceProperties, "camel.faulttolerance.",
                    mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties);
            FaultToleranceConfigurationDefinition faultToleranceModel = model.getFaultToleranceConfiguration(null);
            if (faultToleranceModel == null) {
                faultToleranceModel = new FaultToleranceConfigurationDefinition();
                model.setFaultToleranceConfiguration(faultToleranceModel);
            }
            setPropertiesOnTarget(camelContext, faultToleranceModel, faultTolerance);
        }
    }

    static void setThreadPoolProperties(
            CamelContext camelContext,
            MainConfigurationProperties mainConfigurationProperties,
            Map<String, Object> threadPoolProperties,
            boolean failIfNotSet, Map<String, String> autoConfiguredProperties)
            throws Exception {

        ThreadPoolConfigurationProperties tp = mainConfigurationProperties.threadPool();

        // extract all config to know their parent ids so we can set the values afterwards
        Map<String, Object> hcConfig = PropertiesHelper.extractProperties(threadPoolProperties, "config", false);
        Map<String, ThreadPoolProfileConfigurationProperties> tpConfigs = new HashMap<>();
        // build set of configuration objects
        for (Map.Entry<String, Object> entry : hcConfig.entrySet()) {
            String id = StringHelper.between(entry.getKey(), "[", "]");
            if (id != null) {
                ThreadPoolProfileConfigurationProperties tcp = tpConfigs.get(id);
                if (tcp == null) {
                    tcp = new ThreadPoolProfileConfigurationProperties();
                    tcp.setId(id);
                    tpConfigs.put(id, tcp);
                }
            }
        }
        if (tp.getConfig() != null) {
            tp.getConfig().putAll(tpConfigs);
        } else {
            tp.setConfig(tpConfigs);
        }

        setPropertiesOnTarget(camelContext, tp, threadPoolProperties, "camel.threadpool.",
                mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties);

        // okay we have all properties set so we should be able to create thread pool profiles and register them on camel
        final ThreadPoolProfile dp = new ThreadPoolProfileBuilder("default")
                .poolSize(tp.getPoolSize())
                .maxPoolSize(tp.getMaxPoolSize())
                .keepAliveTime(tp.getKeepAliveTime(), tp.getTimeUnit())
                .maxQueueSize(tp.getMaxQueueSize())
                .allowCoreThreadTimeOut(tp.getAllowCoreThreadTimeOut())
                .rejectedPolicy(tp.getRejectedPolicy()).build();

        for (ThreadPoolProfileConfigurationProperties config : tp.getConfig().values()) {
            ThreadPoolProfileBuilder builder = new ThreadPoolProfileBuilder(config.getId(), dp);
            final ThreadPoolProfile tpp = builder.poolSize(config.getPoolSize())
                    .maxPoolSize(config.getMaxPoolSize())
                    .keepAliveTime(config.getKeepAliveTime(), config.getTimeUnit())
                    .maxQueueSize(config.getMaxQueueSize())
                    .allowCoreThreadTimeOut(config.getAllowCoreThreadTimeOut())
                    .rejectedPolicy(config.getRejectedPolicy()).build();
            if (!tpp.isEmpty()) {
                camelContext.getExecutorServiceManager().registerThreadPoolProfile(tpp);
            }
        }

        if (!dp.isEmpty()) {
            dp.setDefaultProfile(true);
            camelContext.getExecutorServiceManager().setDefaultThreadPoolProfile(dp);
        }
    }

}


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="/static/bootstrap-3.3.4-dist/css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="/static/bootstrap-3.3.4-dist/css/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="/static/pets.css" />

Welcome to petwitter

About this site

This is a site to help you prepare for a PyCon 2015
          Security Tutorial called
          Getting Comfortable With Web Security.

Schedule

Lab material

Prepare for the tutorial in 2 steps

1. Bring a computer

If possible, bring a computer with Python installed, and with <tt>virtualenv</tt> installed.

If you don't know how to install <tt>virtualenv</tt>,
          please show up 15 minutes before the tutorial start
          time so we can help you.

2. Create an account on Slack

By the time you see this page, you should have already received
            an invitation to the
            petwitter Slack chat system.
            Join it!

If you haven't received one, that's OK. Send an email to:
            <tt>paulproteus@gmail.com</tt>.

Small group info (JUST FOR THE SUNDAY PRE-PYCON DEMO!)

Link to the code

the code!

Group #1

If you're in one, then here are your essential links:

Slack channel #h1

App instance

Your small-group lead is asheesh.

Group #2

If you're in two, then here are your essential links:

Slack channel

App instance

Your small-group lead is lettamercurial.

Group #3

If you're in three, then here are your essential links:

Slack channel

App instance

Your small-group lead is kyoki.

Pseudo-FAQ

Petwitter -- why the name?

For the fun of it, I figured we can use my petwitter.com
            domain name. This site has no relationship with
            with Twitter, Inc.


text:
NSString * const UserDidLoginNotification = @"UserDidLoginNotification";
NSString * const UserDidLogoutNotification = @"UserDidLogoutNotification";

@interface User()

@property (nonatomic, strong) NSDictionary *dictionary;

@end

@implementation User

-(id)initWithDictionary:(NSDictionary *)dictionary {

    self = [super init];

    if (self) {
        self.dictionary = dictionary;
        self.name = dictionary[@"name"];
        self.screenName = dictionary[@"screen_name"];
        self.profileImageUrl = dictionary[@"profile_image_url"];
        self.tagline = dictionary[@"description"];
    }

    return self;
}

+(void)logout {
    [User setCurrentUser:nil];
    [[TwitterClient sharedInstance].requestSerializer removeAccessToken];

    [[NSNotificationCenter defaultCenter] postNotificationName:UserDidLogoutNotification object:nil];
}

static User *_currentUser = nil;

NSString * const kCurrentUserKey = @"kCurrentUserKey";

+ (User *)currentUser {
    if (_currentUser == nil) {
        NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kCurrentUserKey];
        if (data != nil) {
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            _currentUser = [[User alloc] initWithDictionary:dictionary];
        }
    }

    return _currentUser;
}

+ (void)setCurrentUser:(User *)currentUser {
    _currentUser = currentUser;

    if (_currentUser != nil) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:currentUser.dictionary options:0 error:NULL];

        [[NSUserDefaults standardUserDefaults] setObject:data forKey:kCurrentUserKey];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kCurrentUserKey];
    }

    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end


text:
from pydojo import *

# create game display
screen(1280, 720)

background('example_asset/backgrounds/forest2.png')

framerate(30)

# PYCO INIT
pyco = Actor('example_asset/characters/pyco1.png', 'idle')
print(pyco.costume, pyco.cosnumber)

pyco.loadfolder('example_asset/characters/pyco_walk')
print(pyco.costume, pyco.cosnumber)

pyco.goto(100, 600)
pyco.speed = 5
pyco.rotate('flip')
pyco.bullets = []
pyco.jumping = False
pyco.scale(0.9)

# BAT INIT
bat = Actor('example_asset/characters/bat1.png')
bat.load('example_asset/characters/bat2.png')
bat.rotate('flip')
bat.point(random.randint(0, 360))
bat.tag('enemy')
bat.scale(0.9)

# PY BULLET INIT
py = Actor('example_asset/characters/python.png')
py.scale(50, 50)
py.hide()
py.tag('bullet')
py.tag('test')
py.setpencolor(RED)

# PLATFORMS INIT
platforms = []
for i in range(6):
    a = Actor('example_asset/characters/platform.png', str(i))
    a.tag('support')
    a.scale(200, 50)
    platforms.append(a)
for p in platforms:
    p.gorand()
# print(platforms)

# TERRAIN INIT
terrain = Actor('example_asset/characters/terrain.png')
terrain.goto(CENTER.x, 700)
terrain.scale(1280, 50)
terrain.tag('support')
terrain.tag('prova')
terrain.untag('prova')

gravity = 10

print(pyco.costumes_by_number)

def pybullet_setup(bullet):
    bullet.tag('custom spawn setup behavior working')
    print(bullet.tags)

def pybullet_movement(bullet):
    bullet.setdirection(random.randint(int(bullet.direction - 10), int(bullet.direction + 10)))
    bullet.roll(5)
    if distance(pyco, bullet) > 2000:
        bullet.kill()

while True:

    # MOVEMENT
    if key(RIGHT):
        pyco.point(90)
        pyco.forward(pyco.speed)
        pyco.nextcostume(pause=7, costumes=[1, 4])
        # print pyco.cosnumber
    if keyup(RIGHT):
        pyco.setcostume('idle')
    if key(LEFT):
        pyco.point(-90)
        pyco.forward(pyco.speed)
        pyco.play('pyco_walk')
    if keyup(LEFT):
        pyco.setcostume('idle')

    # JUMP
    if keydown(UP):
        if pyco.collide('support'):
            pyco.jumping = True
            t = 0
    if pyco.jumping:
        if t < 15:
            pyco.y -= (2 * gravity)
            t = t + 1

    # SHOOT
    if keydown(SPACE):
        spawn(py,
              direction=pyco.direction,
              speed=10,
              position=pyco,
              setup_behavior=pybullet_setup,
              update_behavior=pybullet_movement)
        # bullet = clone(py)
        # print bullet.tags
        # bullet.rotate(False)
        # bullet.point(pyco.direction)
        # bullet.goto(pyco)
        # bullet.show()
        # # bullet.pendown()
        # print game_info.tagged_actors
        # bullet.untag('test')
        # print bullet.tags
        # print py.tags
        # pyco.bullets.append(bullet)

    if pyco.collide(bat):
        print('preso')
        pyco.hide(2)
    if keydown(P):
        pyco.show()
    if keydown(O):
        pyco.hide()

    # for b in pyco.bullets:
    #     b.forward(10)
    #     b.setdirection(random.randint(b.direction - 10, b.direction + 10))
    #     b.roll(5)
    #     if distance(pyco, b) > 2000:
    #         pyco.bullets.remove(b)

    if key(DOWN):
        pyco.point(180)
        pyco.forward(pyco.speed)

    if not pyco.collide('support'):
        # print('falling')
        pyco.y += gravity

    if pyco.y > 720:
        pyco.y = 500

    # BAT
    bat.nextcostume()
    bat.forward(10)
    bat.bounce()
    if bat.collide('bullet'):
        print('colpito')
        bat.hide(2)
        print(COLLISION.point)
        print(COLLISION.object)

    update()


text:
package com.hjhrq1991.car.Event;

import android.text.TextUtils;

import com.hjhrq1991.car.Model.BasicModel;
import com.hjhrq1991.car.Model.NowWeatherModel;
import com.hjhrq1991.car.Model.SuggestionModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

/**
 * @author hjhrq1991 created at 1/28/16 11 13.
 * @Package com.hjhrq1991.car.Event
 * @Description:
 */
public class WeatherEvent {

    private String errorCode;
    private boolean isSuccess;

    private BasicModel basic;

    private NowWeatherModel now;

    private SuggestionModel suggestion;

    public WeatherEvent() {
    }

    public WeatherEvent(String json) {
        if (!TextUtils.isEmpty(json)) {
            try {
                JSONObject jsonObject = new JSONObject(json);

                Iterator<String> keys = jsonObject.keys();
                String key = keys.next();
                JSONArray jsonArray = jsonObject.optJSONArray(key);
                if (jsonArray != null && jsonArray.length() > 0) {
                    JSONObject mJson = jsonArray.optJSONObject(0);
                    this.errorCode = mJson.optString("status");
                    if (errorCode.equals("ok")) {
                        this.isSuccess = true;
                        this.basic = new BasicModel(mJson.optJSONObject("basic"));
                        this.now = new NowWeatherModel(mJson.optJSONObject("now"));
                        this.suggestion = new SuggestionModel(mJson.optJSONObject("suggestion"));
                    } else {
                        this.isSuccess = false;
                    }
                }

            } catch (JSONException e) {
                this.isSuccess = false;
            }
        } else {
            this.isSuccess = false;
        }
    }

    public String getErrorCode() {
        return errorCode;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public BasicModel getBasic() {
        return basic;
    }

    public NowWeatherModel getNow() {
        return now;
    }

    public SuggestionModel getSuggestion() {
        return suggestion;
    }
}


text:
<?php

namespace source\modules\menu\models;

use Yii;
use source\core\base\BaseActiveRecord;
use source\libs\Constants;
use source\LuLu;
use yii\helpers\Url;
use rmrevin\yii\fontawesome\FA;

/**
 * This is the model class for table "lulu_menu".
 *
 * @property integer $id
 * @property integer $parent_id
 * @property string $category_id
 * @property string $name
 * @property string $icon
 * @property string $url
 * @property string $target
 * @property string $description
 * @property string $thumb
 * @property integer $status
 * @property integer $sort_num
 *
 * @property Menu[] $subItem
 * @property Menu[] $subMenu
 */
class Menu extends BaseActiveRecord
{
    const CachePrefix = 'menu_';

    public function init() {
        $this->target = Constants::SELF;
        $this->status = Constants::BLANK;

        parent::init();
    }

    public static function find(){
        return new MenuActiveQuery(get_called_class());
    }

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%menu}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['parent_id', 'category_id', 'name', 'url'], 'required'],
            [['parent_id', 'status', 'sort_num'], 'integer'],
            [['name', 'target', 'category_id'], 'string', 'max' => 64],
            [['url', 'description', 'thumb'], 'string', 'max' => 512],
            [['icon'], 'string', 'max' => 256],
        ];
    }

    public function attributeLabels() {
        return [
            'id'            => Yii::t('app', 'Id'),
            'parent_id'     => Yii::t('app', 'Parent'),
            'category_id'   => Yii::t('app', 'Category'),
            'name'          => Yii::t('app', 'Name'),
            'icon'          => Yii::t('app', 'Icon'),
            'url'           => Yii::t('app', 'Url'),
            'target'        => Yii::t('app', 'Target'),
            'description'   => Yii::t('app', 'Description'),
            'thumb'         => Yii::t('app', 'Thumb'),
            'status'        => Yii::t('app', 'Status'),
            'sort_num'      => Yii::t('app', 'Sort Num'),
        ];
    }

    public function getSubItem(){
        return $this->hasMany(static::className(), ['parent_id'=>'id']);
    }

    public function getSubMenu(){
        return $this->subItem;
    }

    protected $defaultIcon = '<i class="fa fa-circle-o"></i>';
    public function afterFind() {
        $re = parent::afterFind();
        if(empty($this->icon)){
            $this->icon = $this->defaultIcon;
        }
        return $re;
    }

}


text:
package com.horowitz.seaport.ocr;

import java.awt.image.BufferedImage;
import java.io.IOException;

import Catalano.Imaging.FastBitmap;
import Catalano.Imaging.Filters.Invert;
import Catalano.Imaging.Filters.Threshold;

import com.horowitz.commons.DateUtils;
import com.horowitz.commons.ImageComparator;
import com.horowitz.ocr.OCRB;
import com.horowitz.ocr.OCRe;

public class OCRMarketBonus {

  private static final String INPUT_PATH = "ocr/ocrb";
  private final static String OUTPUT_PATH = "ocrb";
  private final static String OCR_PREFIX = "b";

  private OCRB ocrb;

  public OCRMarketBonus(ImageComparator comparator) throws IOException {
    super();
    ocrb = new OCRB(OUTPUT_PATH + "/" + OCR_PREFIX, comparator);
  }

  public String scanImage(BufferedImage image) {
    FastBitmap fb = new FastBitmap(image);
    if (fb.isRGB())
      fb.toGrayscale();
    Invert invert = new Invert();
    invert.applyInPlace(fb);
    Threshold t = new Threshold(150);
    t.applyInPlace(fb);
    //fb.saveAsBMP(OCR_PREFIX + "_" + DateUtils.formatDateForFile(System.currentTimeMillis()) + ".bmp");
    return ocrb.scanImage(fb.toBufferedImage());
  }

  // ////////////////////////////

  public static void main(String[] args) {
    OCRe ocr = new OCRe();
    ocr.setNegative(true);
    Threshold t = new Threshold(150);
    ocr.setThreshold(t);
    if (args.length < 3)
      ocr.learn(INPUT_PATH, OCR_PREFIX, "images/" + OUTPUT_PATH, false);
    else {
      ocr.learn(args[0], args[1], args[2], false);
    }
  }

}


text:
import unittest
import os
from link import Link, Wrapper
from link.utils import load_json_file
from link.tests import *

DIR = os.path.dirname(__file__)
TEST_CONFIG = 'test_link.test_config'
TEST_CONFIG2 = 'test_link2.test_config'
BAD_CONFIG = 'bad_config.test_config'
NO_CONFIG = 'no_config.test_config'

#load in all the configs that we want
lnk = Link.instance()
config1 = load_tst_config(TEST_CONFIG)
config1_path = tst_config_path(TEST_CONFIG)
config2 = load_tst_config(TEST_CONFIG2)
config2_path = tst_config_path(TEST_CONFIG2)
bad_config_path = tst_config_path(BAD_CONFIG)
#this does not exist
no_config_path = tst_config_path(NO_CONFIG)

FAKE_WRAPPER_PATH1 = tst_file_path('fake_wrappers')
FAKE_WRAPPER_PATH2 = tst_file_path('fake_wrappers.fake_wrap2')
FAKE_WRAPPER_PACKAGE1 = 'fake_wrappers'
FAKE_WRAPPER_PACKAGE2 = 'fake_wrappers.fake_wrap2'

class TestLink(unittest.TestCase):

    def setUp(self):
        #reset the config every time to config1
        lnk.fresh(config_file=config1_path)

    def test_config(self):
        self.assertEquals(lnk.config(), config1)

    def test_instance(self):
        self.assertNotEquals(lnk, Link(config1_path))
        #check to make sure this is a singleton
        self.assertEquals(lnk,
                          Link.instance())

    def test_config_lookup(self):
        lookup = lnk.config('apis.test_api')
        self.assertEquals(lookup, config1['apis']['test_api'])
        self.assertRaises(KeyError, lnk.config, 'this.is.not.a.key')

    def test_fresh(self):
        lookup_conf1 = lnk.config('apis.test_api')
        #now change what config we are pointing to
        lnk.fresh(config_file = config2_path)
        lookup_conf2 = lnk.config('apis.test_api')
        self.assertNotEquals(lookup_conf1, lookup_conf2)
        self.assertEquals(lookup_conf1, config1['apis']['test_api'])
        self.assertEquals(lookup_conf2, config2['apis']['test_api'])

    def test_bad_config(self):
        #we want to make sure it won't bomb out on the fresh but
        #throws exception when you actually do something where it calls the
        #config
        lnk.fresh(config_file = bad_config_path)
        self.assertRaises(ValueError, lnk.config)

    def test_no_config(self):
        #we want to make sure that it will load without a config but will throw
        #an appropriate error when you try to use the config
        lnk.fresh(config_file = no_config_path)
        self.assertRaises(Exception, lnk.config)

    def test_default_wrapper(self):
        wrap_name = 'apis.test_api'
        api = lnk(wrap_name)
        config = api.config()
        self.assertEquals(api.wrap_name, wrap_name)
        self.assertEquals(config['user'], lnk.config('apis.test_api.user'))
        self.assertEquals(config['password'], lnk.config('apis.test_api.password'))

    def test_wrapper_not_configured(self):
        self.assertRaises(Exception, lnk, 'this.is.not.a.key')

    def test_wrapper_kwargs_override(self):
        wrap_name = 'apis.test_api'
        user_override = 'this is the overridden user'
        api = lnk(wrap_name, user=user_override)
        config = api.config()
        self.assertEquals(api.wrap_name, wrap_name)
        self.assertEquals(config['user'], user_override)
        self.assertEquals(config['password'], lnk.config('apis.test_api.password'))

    def test_load_wrapper_directories(self):
        lnk.fresh()
        self.assertEquals(lnk.wrappers, {})
        lnk.load_wrapper_directories([FAKE_WRAPPER_PATH1])
        self.assertTrue(lnk.wrappers.has_key('FakeWrapper'))
        self.assertFalse(lnk.wrappers.has_key('FakeWrapper2'))
        lnk.load_wrapper_directories([FAKE_WRAPPER_PATH2])
        self.assertTrue(lnk.wrappers.has_key('FakeWrapper2'))

    def test_load_wrapper_packages(self):
        lnk.fresh()
        self.assertEquals(lnk.wrappers, {})
        lnk.load_wrapper_packages([FAKE_WRAPPER_PACKAGE1])
        self.assertTrue(lnk.wrappers.has_key('FakeWrapper'))
        self.assertFalse(lnk.wrappers.has_key('FakeWrapper2'))
        lnk.load_wrapper_packages([FAKE_WRAPPER_PACKAGE2])
        self.assertTrue(lnk.wrappers.has_key('FakeWrapper2'))

class TestLazyFunctions(unittest.TestCase):

    def setUp(self):
        #reset the config every time to config1
        lnk.fresh(config_file=config1_path)

    def test_function_lookup(self):
        func = lnk.lazy_functions.test_function
        self.assertTrue(func.commander.has_command("__default__"))
        self.assertTrue(func.commander.has_command("function"))
        self.assertFalse(func.commander.has_command("aeuoaeaosuoesth"))

class MockCallableWrapper(Wrapper):

    def __init__(self):
        super(MockCallableWrapper, self).__init__()

    @property
    def command(self):
        return 'echo'

class MockNonCallableWrapper(Wrapper):

    def __init__(self):
        super(MockNonCallableWrapper, self).__init__()

class TestWrapper(unittest.TestCase):

    def setUp(self):
        lnk.fresh(config_file=config1_path)
        self.wrapper = lnk.test_wrapper

    def test_call(self):
        ran = MockCallableWrapper()('echo')
        self.assertTrue(ran!=None)

    def test_call_default(self):
        ran = MockCallableWrapper()()
        self.assertTrue(ran!=None)
        self.assertRaises(NotImplementedError, MockNonCallableWrapper())

if __name__ == '__main__':
    import nose
    nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],
                   exit=False)


text:
from django.core.files.base import ContentFile
import requests

class DownloadError(Exception):
    """Error downloading a paper."""

def guess_extension_from_headers(h):
    """
    Given headers from an ArXiV e-print response, try and guess what the file
    extension should be.

    Based on: https://arxiv.org/help/mimetypes
    """
    if h.get("content-type") == "application/pdf":
        return ".pdf"
    if (
        h.get("content-encoding") == "x-gzip"
        and h.get("content-type") == "application/postscript"
    ):
        return ".ps.gz"
    if (
        h.get("content-encoding") == "x-gzip"
        and h.get("content-type") == "application/x-eprint-tar"
    ):
        return ".tar.gz"
    if (
        h.get("content-encoding") == "x-gzip"
        and h.get("content-type") == "application/x-eprint"
    ):
        return ".tex.gz"
    if (
        h.get("content-encoding") == "x-gzip"
        and h.get("content-type") == "application/x-dvi"
    ):
        return ".dvi.gz"
    return None

def arxiv_id_to_source_url(arxiv_id):
    # This URL is normally a tarball, but sometimes something else.
    # ArXiV provides a /src/ URL which always serves up a tarball,
    # but if we used this, we'd have to untar the file to figure out
    # whether it's renderable or not. By using the /e-print/ endpoint
    # we can figure out straight away whether we should bother rendering
    # it or not.
    # https://arxiv.org/help/mimetypes has more info
    return "https://arxiv.org/e-print/" + arxiv_id

def arxiv_id_to_source_file(arxiv_id):
    """
    Convert an arXiv ID into the filename the source file should be stored as,
    without extension.

    This is the inverse of `convert_source_file_to_arxiv_id()` in
    `arxiv_vanity/scraper/bulk_sources.py`.
    """
    return arxiv_id.replace("/", "")

def download_source_file(arxiv_id):
    """
    Download the LaTeX source of this paper and returns as ContentFile.
    """
    source_url = arxiv_id_to_source_url(arxiv_id)
    headers = {"User-Agent": "arXivVanity (https://www.arxiv-vanity.com)"}
    res = requests.get(source_url, headers=headers)
    res.raise_for_status()
    extension = guess_extension_from_headers(res.headers)
    if not extension:
        raise DownloadError(
            "Could not determine file extension from "
            "headers: Content-Type: {}; "
            "Content-Encoding: {}".format(
                res.headers.get("content-type"), res.headers.get("content-encoding")
            )
        )
    file = ContentFile(res.content)
    file.name = arxiv_id_to_source_file(arxiv_id) + extension
    return file


text:
<template>
  <require from="./good-auto-complete.css"></require>
  <require from="./good-scroll-into-view-if"></require>

    <input class="gac-input"
        class.bind="additionalClassInput"
        ref="_suggestionsElementLogic.inputElement"
        placeholder.bind="placeholder"
        autocomplete="off"
        value.bind="_value"
        blur.trigger="resetSuggestions()"
        keydown.delegate="keyPressed($event)"></input>

            <template replaceable part="suggestion-item-template">

${item.value}

            </template>

</template>


text:
@interface RgHomeViewController : RogueBaseViewContorller

@end


text:
var express = require("express");
var app = express ();

app.use(express.static(__dirname + '/dist'));

var port = Number(process.env.PORT || 3000);
app.listen(port, function() {
  console.log("Listening on" + port);
});


text:
module.exports = function () {
  return false // we've been rescued!
}


text:
package org.diirt.service.exec;

import java.util.HashMap;
import java.util.Map;
import org.diirt.vtype.VString;
import org.diirt.vtype.ValueFactory;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

/**
 *
 * @author carcassi
 */
public class GenericExecServiceTest {

    @Test
    public void runCommand1() {
        GenericExecService services = new GenericExecService();
        Map<String, Object> params = new HashMap<>();
        params.put("command", ValueFactory.newVString("echo This is a test!", ValueFactory.alarmNone(), ValueFactory.timeNow()));
        Map<String, Object> result = services.getServiceMethods().get("run").syncExecute(params);
        VString output = (VString) result.get("output");
        assertThat(output.getValue(), equalTo("This is a test!\n"));
    }

}


text:
#include <stdint.h>
#include <string.h>

#include <grpc/compression.h>
#include <grpc/grpc.h>
#include <grpc/slice.h>
#include <grpc/slice_buffer.h>

#include "src/core/lib/compression/message_compress.h"

bool squelch = true;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size < 1) return 0;

  // Instead of rolling something complicated to convert a uint8_t to the enum,
  // just bail out if it isn't trivially convertible.
  if (data[0] >= GRPC_COMPRESS_ALGORITHMS_COUNT) return 0;
  const auto compression_algorithm =
      static_cast<grpc_compression_algorithm>(data[0]);

  grpc_init();
  grpc_slice_buffer input_buffer;
  grpc_slice_buffer_init(&input_buffer);
  grpc_slice_buffer_add(&input_buffer,
                        grpc_slice_from_copied_buffer(
                            reinterpret_cast<const char*>(data + 1), size - 1));
  grpc_slice_buffer output_buffer;
  grpc_slice_buffer_init(&output_buffer);

  grpc_msg_decompress(compression_algorithm, &input_buffer, &output_buffer);

  grpc_slice_buffer_destroy(&input_buffer);
  grpc_slice_buffer_destroy(&output_buffer);
  grpc_shutdown();
  return 0;
}


text:
package integration

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"path/filepath"
	"testing"
	"time"

	"go.uber.org/zap"

	"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
	"github.com/coreos/etcd/integration"
	"github.com/coreos/etcd/lease"
	"github.com/coreos/etcd/mvcc"
	"github.com/coreos/etcd/mvcc/backend"
	"github.com/coreos/etcd/pkg/testutil"
)

func TestMaintenanceHashKV(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	for i := 0; i < 3; i++ {
		if _, err := clus.RandClient().Put(context.Background(), "foo", "bar"); err != nil {
			t.Fatal(err)
		}
	}

	var hv uint32
	for i := 0; i < 3; i++ {
		cli := clus.Client(i)
		// ensure writes are replicated
		if _, err := cli.Get(context.TODO(), "foo"); err != nil {
			t.Fatal(err)
		}
		hresp, err := cli.HashKV(context.Background(), clus.Members[i].GRPCAddr(), 0)
		if err != nil {
			t.Fatal(err)
		}
		if hv == 0 {
			hv = hresp.Hash
			continue
		}
		if hv != hresp.Hash {
			t.Fatalf("#%d: hash expected %d, got %d", i, hv, hresp.Hash)
		}
	}
}

func TestMaintenanceMoveLeader(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	oldLeadIdx := clus.WaitLeader(t)
	targetIdx := (oldLeadIdx + 1) % 3
	target := uint64(clus.Members[targetIdx].ID())

	cli := clus.Client(targetIdx)
	_, err := cli.MoveLeader(context.Background(), target)
	if err != rpctypes.ErrNotLeader {
		t.Fatalf("error expected %v, got %v", rpctypes.ErrNotLeader, err)
	}

	cli = clus.Client(oldLeadIdx)
	_, err = cli.MoveLeader(context.Background(), target)
	if err != nil {
		t.Fatal(err)
	}

	leadIdx := clus.WaitLeader(t)
	lead := uint64(clus.Members[leadIdx].ID())
	if target != lead {
		t.Fatalf("new leader expected %d, got %d", target, lead)
	}
}

// TestMaintenanceSnapshotError ensures that context cancel/timeout
// before snapshot reading returns corresponding context errors.
func TestMaintenanceSnapshotError(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	// reading snapshot with canceled context should error out
	ctx, cancel := context.WithCancel(context.Background())
	rc1, err := clus.RandClient().Snapshot(ctx)
	if err != nil {
		t.Fatal(err)
	}
	defer rc1.Close()

	cancel()
	_, err = io.Copy(ioutil.Discard, rc1)
	if err != context.Canceled {
		t.Errorf("expected %v, got %v", context.Canceled, err)
	}

	// reading snapshot with deadline exceeded should error out
	ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	rc2, err := clus.RandClient().Snapshot(ctx)
	if err != nil {
		t.Fatal(err)
	}
	defer rc2.Close()

	time.Sleep(2 * time.Second)

	_, err = io.Copy(ioutil.Discard, rc2)
	if err != nil && err != context.DeadlineExceeded {
		t.Errorf("expected %v, got %v", context.DeadlineExceeded, err)
	}
}

// TestMaintenanceSnapshotErrorInflight ensures that inflight context cancel/timeout
// fails snapshot reading with corresponding context errors.
func TestMaintenanceSnapshotErrorInflight(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	// take about 1-second to read snapshot
	clus.Members[0].Stop(t)
	dpath := filepath.Join(clus.Members[0].DataDir, "member", "snap", "db")
	b := backend.NewDefaultBackend(dpath)
	s := mvcc.NewStore(zap.NewExample(), b, &lease.FakeLessor{}, nil)
	rev := 100000
	for i := 2; i <= rev; i++ {
		s.Put([]byte(fmt.Sprintf("%10d", i)), bytes.Repeat([]byte("a"), 1024), lease.NoLease)
	}
	s.Close()
	b.Close()
	clus.Members[0].Restart(t)

	// reading snapshot with canceled context should error out
	ctx, cancel := context.WithCancel(context.Background())
	rc1, err := clus.RandClient().Snapshot(ctx)
	if err != nil {
		t.Fatal(err)
	}
	defer rc1.Close()

	donec := make(chan struct{})
	go func() {
		time.Sleep(300 * time.Millisecond)
		cancel()
		close(donec)
	}()
	_, err = io.Copy(ioutil.Discard, rc1)
	if err != nil && err != context.Canceled {
		t.Errorf("expected %v, got %v", context.Canceled, err)
	}
	<-donec

	// reading snapshot with deadline exceeded should error out
	ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	rc2, err := clus.RandClient().Snapshot(ctx)
	if err != nil {
		t.Fatal(err)
	}
	defer rc2.Close()

	// 300ms left and expect timeout while snapshot reading is in progress
	time.Sleep(700 * time.Millisecond)
	_, err = io.Copy(ioutil.Discard, rc2)
	if err != nil && err != context.DeadlineExceeded {
		t.Errorf("expected %v, got %v", context.DeadlineExceeded, err)
	}
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @author Nicolas Ferrero
 *
 * TablePanel is the basis of both {@link Ext.tree.Panel TreePanel} and {@link Ext.grid.Panel GridPanel}.
 *
 * TablePanel aggregates:
 *
 *  - a Selection Model
 *  - a View
 *  - a Store
 *  - Scrollers
 *  - Ext.grid.header.Container
 */
Ext.define('Ext.panel.Table', {
    extend: 'Ext.panel.Panel',

    alias: 'widget.tablepanel',

    uses: [
        'Ext.selection.RowModel',
        'Ext.selection.CellModel',
        'Ext.selection.CheckboxModel',
        'Ext.grid.plugin.BufferedRenderer',
        'Ext.grid.header.Container',
        'Ext.grid.locking.Lockable'
    ],

    extraBaseCls: Ext.baseCSSPrefix + 'grid',
    extraBodyCls: Ext.baseCSSPrefix + 'grid-body',

    layout: 'fit',
    /**
     * @property {Boolean} hasView
     * True to indicate that a view has been injected into the panel.
     */
    hasView: false,

    // each panel should dictate what viewType and selType to use
    /**
     * @cfg {String} viewType
     * An xtype of view to use. This is automatically set to 'gridview' by {@link Ext.grid.Panel Grid}
     * and to 'treeview' by {@link Ext.tree.Panel Tree}.
     * @protected
     */
    viewType: null,

    /**
     * @cfg {Object} viewConfig
     * A config object that will be applied to the grid's UI view. Any of the config options available for
     * {@link Ext.view.Table} can be specified here. This option is ignored if {@link #view} is specified.
     */

    /**
     * @cfg {Ext.view.Table} view
     * The {@link Ext.view.Table} used by the grid. Use {@link #viewConfig} to just supply some config options to
     * view (instead of creating an entire View instance).
     */

    /**
     * @cfg {String} selType
     * An xtype of selection model to use. Defaults to 'rowmodel'. This is used to create selection model if just
     * a config object or nothing at all given in {@link #selModel} config.
     */
    selType: 'rowmodel',

    /**
     * @cfg {Ext.selection.Model/Object} selModel
     * A {@link Ext.selection.Model selection model} instance or config object.  In latter case the {@link #selType}
     * config option determines to which type of selection model this config is applied.
     */

    /**
     * @cfg {Boolean} [multiSelect=false]
     * True to enable 'MULTI' selection mode on selection model.
     * @deprecated 4.1.1 Use {@link Ext.selection.Model#mode} 'MULTI' instead.
     */

    /**
     * @cfg {Boolean} [simpleSelect=false]
     * True to enable 'SIMPLE' selection mode on selection model.
     * @deprecated 4.1.1 Use {@link Ext.selection.Model#mode} 'SIMPLE' instead.
     */

    /**
     * @cfg {Ext.data.Store} store (required)
     * The {@link Ext.data.Store Store} the grid should use as its data source.
     */

    /**
     * @cfg {String/Boolean} scroll
     * Scrollers configuration. Valid values are 'both', 'horizontal' or 'vertical'.
     * True implies 'both'. False implies 'none'.
     */
    scroll: true,

    /**
     * @cfg {Ext.grid.column.Column[]/Object} columns
     * An array of {@link Ext.grid.column.Column column} definition objects which define all columns that appear in this
     * grid. Each column definition provides the header text for the column, and a definition of where the data for that
     * column comes from.
     *
     * This can also be a configuration object for a {Ext.grid.header.Container HeaderContainer} which may override
     * certain default configurations if necessary. For example, the special layout may be overridden to use a simpler
     * layout, or one can set default values shared by all columns:
     *
     *     columns: {
     *         items: [
     *             {
     *                 text: "Column A"
     *                 dataIndex: "field_A"
     *             },{
     *                 text: "Column B",
     *                 dataIndex: "field_B"
     *             },
     *             ...
     *         ],
     *         defaults: {
     *             flex: 1
     *         }
     *     }
     */

    /**
     * @cfg {Boolean} forceFit
     * True to force the columns to fit into the available width. Headers are first sized according to configuration,
     * whether that be a specific width, or flex. Then they are all proportionally changed in width so that the entire
     * content width is used. For more accurate control, it is more optimal to specify a flex setting on the columns
     * that are to be stretched & explicit widths on columns that are not.
     */

    /**
     * @cfg {Ext.grid.feature.Feature[]/Object[]/Ext.enums.Feature[]} features
     * An array of grid Features to be added to this grid. Can also be just a single feature instead of array.
     *
     * Features config behaves much like {@link #plugins}.
     * A feature can be added by either directly referencing the instance:
     *
     *     features: [Ext.create('Ext.grid.feature.GroupingSummary', {groupHeaderTpl: 'Subject: {name}'})],
     *
     * By using config object with ftype:
     *
     *     features: [{ftype: 'groupingsummary', groupHeaderTpl: 'Subject: {name}'}],
     *
     * Or with just a ftype:
     *
     *     features: ['grouping', 'groupingsummary'],
     *
     * See {@link Ext.enums.Feature} for list of all ftypes.
     */

    /**
     * @cfg {Boolean} [hideHeaders=false]
     * True to hide column headers.
     */

    /**
     * @cfg {Boolean} deferRowRender
     * Defaults to true to enable deferred row rendering.
     *
     * This allows the View to execute a refresh quickly, with the expensive update of the row structure deferred so
     * that layouts with GridPanels appear, and lay out more quickly.
     */

    /**
     * @cfg {Object} verticalScroller
     * A config object to be used when configuring the {@link Ext.grid.plugin.BufferedRenderer scroll monitor} to control
     * refreshing of data in an "infinite grid".
     *
     * Configurations of this object allow fine tuning of data caching which can improve performance and usability
     * of the infinite grid.
     */

    deferRowRender: true,

    /**
     * @cfg {Boolean} sortableColumns
     * False to disable column sorting via clicking the header and via the Sorting menu items.
     */
    sortableColumns: true,

    /**
     * @cfg {Boolean} [enableLocking=false]
     * Configure as `true` to enable locking support for this grid. Alternatively, locking will also be automatically
     * enabled if any of the columns in the {@link #columns columns} configuration contain a {@link Ext.grid.column.Column#locked locked} config option.
     *
     * A locking grid is processed in a special way. The configuration options are cloned and *two* grids are created to be the locked (left) side
     * and the normal (right) side. This Panel becomes merely a {@link Ext.container.Container container} which arranges both in an {@link Ext.layout.container.HBox HBox} layout.
     *
     * {@link #plugins Plugins} may be targeted at either locked, or unlocked grid, or, both, in which case the plugin is cloned and used on both sides.
     *
     * Plugins may also be targeted at the containing locking Panel.
     *
     * This is configured by specifying a `lockableScope` property in your plugin which may have the following values:
     *
     *  * `"both"` (the default) - The plugin is added to both grids
     *  * `"top"` - The plugin is added to the containing Panel
     *  * `"locked"` - The plugin is added to the locked (left) grid
     *  * `"normal"` - The plugin is added to the normal (right) grid
     *
     * If `both` is specified, then each copy of the plugin gains a property `lockingPartner` which references its sibling on the other side so that they
     * can synchronize operations is necessary.
     *
     * {@link #features Features} may also be configured with `lockableScope` and may target the locked grid, the normal grid or both grids. Features
     * also get a `lockingPartner` reference injected.
     */
    enableLocking: false,

    // private property used to determine where to go down to find views
    // this is here to support locking.
    scrollerOwner: true,

    /**
     * @cfg {Boolean} [enableColumnMove=true]
     * False to disable column dragging within this grid.
     */
    enableColumnMove: true,

    /**
     * @cfg {Boolean} [sealedColumns=false]
     * True to constrain column dragging so that a column cannot be dragged in or out of it's
     * current group. Only relevant while {@link #enableColumnMove} is enabled.
     */
    sealedColumns: false,

    /**
     * @cfg {Boolean} [enableColumnResize=true]
     * False to disable column resizing within this grid.
     */
    enableColumnResize: true,

    /**
     * @cfg {Boolean} [enableColumnHide=true]
     * False to disable column hiding within this grid.
     */

    /**
     * @cfg {Boolean} columnLines Adds column line styling
     */

    /**
     * @cfg {Boolean} [rowLines=true] Adds row line styling
     */
    rowLines: true,

    /**
     * @cfg {Boolean} [disableSelection=false]
     * True to disable selection model.
     */

    /**
     * @cfg {String} emptyText Default text (html tags are accepted) to display in the Panel body when the Store
     * is empty. When specified, and the Store is empty, the text will be rendered inside a DIV with the CSS class "x-grid-empty".
     */

    /**
     * @cfg {Boolean} [allowDeselect=false]
     * True to allow deselecting a record. This config is forwarded to {@link Ext.selection.Model#allowDeselect}.
     */

    /**
     * @property {Boolean} optimizedColumnMove
     * If you are writing a grid plugin or a {Ext.grid.feature.Feature Feature} which creates a column-based structure which
     * needs a view refresh when columns are moved, then set this property in the grid.
     *
     * An example is the built in {@link Ext.grid.feature.AbstractSummary Summary} Feature. This creates summary rows, and the
     * summary columns must be in the same order as the data columns. This plugin sets the `optimizedColumnMove` to `false.
     */

    colLinesCls: Ext.baseCSSPrefix + 'grid-with-col-lines',
    rowLinesCls: Ext.baseCSSPrefix + 'grid-with-row-lines',
    hiddenHeaderCtCls: Ext.baseCSSPrefix + 'grid-header-ct-hidden',
    hiddenHeaderCls: Ext.baseCSSPrefix + 'grid-header-hidden',
    resizeMarkerCls: Ext.baseCSSPrefix + 'grid-resize-marker',
    emptyCls: Ext.baseCSSPrefix + 'grid-empty',

    initComponent: function() {
        //<debug>
        if (!this.viewType) {
            Ext.Error.raise("You must specify a viewType config.");
        }
        if (this.headers) {
            Ext.Error.raise("The headers config is not supported. Please specify columns instead.");
        }
        //</debug>

        var me          = this,
            headerCtCfg = me.columns || me.colModel,
            view,
            i, len,
            // Look up the configured Store. If none configured, use the fieldless, empty Store defined in Ext.data.Store.
            store       = me.store = Ext.data.StoreManager.lookup(me.store || 'ext-empty-store');

        if (me.columnLines) {
            me.addCls(me.colLinesCls);
        }

        if (me.rowLines) {
            me.addCls(me.rowLinesCls);
        }

        //<debug>
        if (!headerCtCfg) {
            Ext.Error.raise("A column configuration must be specified");
        }
        //</debug>

        // The columns/colModel config may be either a fully instantiated HeaderContainer, or an array of Column definitions, or a config object of a HeaderContainer
        // Either way, we extract a columns property referencing an array of Column definitions.
        if (headerCtCfg instanceof Ext.grid.header.Container) {
            me.headerCt = headerCtCfg;
            me.headerCt.isRootHeader = true;
            me.columns = me.headerCt.items.items;
        } else {
            if (Ext.isArray(headerCtCfg)) {
                headerCtCfg = {
                    items: headerCtCfg
                };
            }
            Ext.apply(headerCtCfg, {
                forceFit: me.forceFit,
                sortable: me.sortableColumns,
                enableColumnMove: me.enableColumnMove,
                enableColumnResize: me.enableColumnResize,
                sealed: me.sealedColumns,
                isRootHeader: true
            });

            if (Ext.isDefined(me.enableColumnHide)) {
                headerCtCfg.enableColumnHide = me.enableColumnHide;
            }

            me.columns = headerCtCfg.items;

            // If any of the Column objects contain a locked property, and are not processed, this is a lockable TablePanel, a
            // special view will be injected by the Ext.grid.locking.Lockable mixin, so no processing of .
            if (me.enableLocking || me.hasLockedColumns(me.columns)) {
                me.self.mixin('lockable', Ext.grid.locking.Lockable);
                me.injectLockable();
            }
        }

        me.scrollTask = new Ext.util.DelayedTask(me.syncHorizontalScroll, me);

        me.addEvents(
            // documented on GridPanel
            'reconfigure',
            /**
             * @event viewready
             * Fires when the grid view is available (use this for selecting a default row).
             * @param {Ext.panel.Table} this
             */
            'viewready'
        );

        me.bodyCls = me.bodyCls || '';
        me.bodyCls += (' ' + me.extraBodyCls);

        me.cls = me.cls || '';
        me.cls += (' ' + me.extraBaseCls);

        // autoScroll is not a valid configuration
        delete me.autoScroll;

        // If this TablePanel is lockable (Either configured lockable, or any of the defined columns has a 'locked' property)
        // than a special lockable view containing 2 side-by-side grids will have been injected so we do not need to set up any UI.
        if (!me.hasView) {

            // If we were not configured with a ready-made headerCt (either by direct config with a headerCt property, or by passing
            // a HeaderContainer instance as the 'columns' property, then go ahead and create one from the config object created above.
            if (!me.headerCt) {
                me.headerCt = new Ext.grid.header.Container(headerCtCfg);
            }

            // Extract the array of Column objects
            me.columns = me.headerCt.items.items;

            // If the Store is paging blocks of the dataset in, then it can only be sorted remotely.
            if (store.buffered && !store.remoteSort) {
                for (i = 0, len = me.columns.length; i < len; i++) {
                    me.columns[i].sortable = false;
                }
            }

            if (me.hideHeaders) {
                me.headerCt.height = 0;
                // don't se the hidden property, we still need these to layout
                me.headerCt.hiddenHeaders = true;
                me.headerCt.addCls(me.hiddenHeaderCtCls);
                me.addCls(me.hiddenHeaderCls);
                // IE Quirks Mode fix
                // If hidden configuration option was used, several layout calculations will be bypassed.
                if (Ext.isIEQuirks) {
                    me.headerCt.style = {
                        display: 'none'
                    };
                }
            }

            me.relayHeaderCtEvents(me.headerCt);
            me.features = me.features || [];
            if (!Ext.isArray(me.features)) {
                me.features = [me.features];
            }
            me.dockedItems = [].concat(me.dockedItems || []);
            me.dockedItems.unshift(me.headerCt);
            me.viewConfig = me.viewConfig || {};

            // AbstractDataView will look up a Store configured as an object
            // getView converts viewConfig into a View instance
            view = me.getView();

            me.items = [view];
            me.hasView = true;

            // Add a listener to synchronize the horizontal scroll position of the headers
            // with the table view's element... Unless we are not showing headers!
            if (!me.hideHeaders) {
                view.on({
                    scroll: {
                        fn: me.onHorizontalScroll,
                        element: 'el',
                        scope: me
                    }
                });
            }

            // Attach this Panel to the Store
            me.bindStore(store, true);

            me.mon(view, {
                viewready: me.onViewReady,
                refresh: me.onRestoreHorzScroll,
                scope: me
            });
        }

        // Relay events from the View whether it be a LockingView, or a regular GridView
        me.relayEvents(me.view, [
            /**
             * @event beforeitemmousedown
             * @inheritdoc Ext.view.View#beforeitemmousedown
             */
            'beforeitemmousedown',
            /**
             * @event beforeitemmouseup
             * @inheritdoc Ext.view.View#beforeitemmouseup
             */
            'beforeitemmouseup',
            /**
             * @event beforeitemmouseenter
             * @inheritdoc Ext.view.View#beforeitemmouseenter
             */
            'beforeitemmouseenter',
            /**
             * @event beforeitemmouseleave
             * @inheritdoc Ext.view.View#beforeitemmouseleave
             */
            'beforeitemmouseleave',
            /**
             * @event beforeitemclick
             * @inheritdoc Ext.view.View#beforeitemclick
             */
            'beforeitemclick',
            /**
             * @event beforeitemdblclick
             * @inheritdoc Ext.view.View#beforeitemdblclick
             */
            'beforeitemdblclick',
            /**
             * @event beforeitemcontextmenu
             * @inheritdoc Ext.view.View#beforeitemcontextmenu
             */
            'beforeitemcontextmenu',
            /**
             * @event itemmousedown
             * @inheritdoc Ext.view.View#itemmousedown
             */
            'itemmousedown',
            /**
             * @event itemmouseup
             * @inheritdoc Ext.view.View#itemmouseup
             */
            'itemmouseup',
            /**
             * @event itemmouseenter
             * @inheritdoc Ext.view.View#itemmouseenter
             */
            'itemmouseenter',
            /**
             * @event itemmouseleave
             * @inheritdoc Ext.view.View#itemmouseleave
             */
            'itemmouseleave',
            /**
             * @event itemclick
             * @inheritdoc Ext.view.View#itemclick
             */
            'itemclick',
            /**
             * @event itemdblclick
             * @inheritdoc Ext.view.View#itemdblclick
             */
            'itemdblclick',
            /**
             * @event itemcontextmenu
             * @inheritdoc Ext.view.View#itemcontextmenu
             */
            'itemcontextmenu',
            /**
             * @event beforecellclick
             * @inheritdoc Ext.view.Table#beforecellclick
             */
            'beforecellclick',
            /**
             * @event cellclick
             * @inheritdoc Ext.view.Table#cellclick
             */
            'cellclick',
            /**
             * @event beforecelldblclick
             * @inheritdoc Ext.view.Table#beforecelldblclick
             */
            'beforecelldblclick',
            /**
             * @event celldblclick
             * @inheritdoc Ext.view.Table#celldblclick
             */
            'celldblclick',
            /**
             * @event beforecellcontextmenu
             * @inheritdoc Ext.view.Table#beforecellcontextmenu
             */
            'beforecellcontextmenu',
            /**
             * @event cellcontextmenu
             * @inheritdoc Ext.view.Table#cellcontextmenu
             */
            'cellcontextmenu',
            /**
             * @event beforecellmousedown
             * @inheritdoc Ext.view.Table#beforecellmousedown
             */
            'beforecellmousedown',
            /**
             * @event cellmousedown
             * @inheritdoc Ext.view.Table#cellmousedown
             */
            'cellmousedown',
            /**
             * @event beforecellmouseup
             * @inheritdoc Ext.view.Table#beforecellmouseup
             */
            'beforecellmouseup',
            /**
             * @event cellmouseup
             * @inheritdoc Ext.view.Table#cellmouseup
             */
            'cellmouseup',
            /**
             * @event beforecellkeydown
             * @inheritdoc Ext.view.Table#beforecellkeydown
             */
            'beforecellkeydown',
            /**
             * @event cellkeydown
             * @inheritdoc Ext.view.Table#cellkeydown
             */
            'cellkeydown',
            /**
             * @event beforecontainermousedown
             * @inheritdoc Ext.view.View#beforecontainermousedown
             */
            'beforecontainermousedown',
            /**
             * @event beforecontainermouseup
             * @inheritdoc Ext.view.View#beforecontainermouseup
             */
            'beforecontainermouseup',
            /**
             * @event beforecontainermouseover
             * @inheritdoc Ext.view.View#beforecontainermouseover
             */
            'beforecontainermouseover',
            /**
             * @event beforecontainermouseout
             * @inheritdoc Ext.view.View#beforecontainermouseout
             */
            'beforecontainermouseout',
            /**
             * @event beforecontainerclick
             * @inheritdoc Ext.view.View#beforecontainerclick
             */
            'beforecontainerclick',
            /**
             * @event beforecontainerdblclick
             * @inheritdoc Ext.view.View#beforecontainerdblclick
             */
            'beforecontainerdblclick',
            /**
             * @event beforecontainercontextmenu
             * @inheritdoc Ext.view.View#beforecontainercontextmenu
             */
            'beforecontainercontextmenu',
            /**
             * @event containermouseup
             * @inheritdoc Ext.view.View#containermouseup
             */
            'containermouseup',
            /**
             * @event containermouseover
             * @inheritdoc Ext.view.View#containermouseover
             */
            'containermouseover',
            /**
             * @event containermouseout
             * @inheritdoc Ext.view.View#containermouseout
             */
            'containermouseout',
            /**
             * @event containerclick
             * @inheritdoc Ext.view.View#containerclick
             */
            'containerclick',
            /**
             * @event containerdblclick
             * @inheritdoc Ext.view.View#containerdblclick
             */
            'containerdblclick',
            /**
             * @event containercontextmenu
             * @inheritdoc Ext.view.View#containercontextmenu
             */
            'containercontextmenu',
            /**
             * @event selectionchange
             * @inheritdoc Ext.selection.Model#selectionchange
             */
            'selectionchange',
            /**
             * @event beforeselect
             * @inheritdoc Ext.selection.RowModel#beforeselect
             */
            'beforeselect',
            /**
             * @event select
             * @inheritdoc Ext.selection.RowModel#select
             */
            'select',
            /**
             * @event beforedeselect
             * @inheritdoc Ext.selection.RowModel#beforedeselect
             */
            'beforedeselect',
            /**
             * @event deselect
             * @inheritdoc Ext.selection.RowModel#deselect
             */
            'deselect'
        ]);

        me.callParent(arguments);
        me.addStateEvents(['columnresize', 'columnmove', 'columnhide', 'columnshow', 'sortchange', 'filterchange']);

        // If lockable, the headerCt is just a collection of Columns, not a Container
        if (!me.lockable && me.headerCt) {
            me.headerCt.on('afterlayout', me.onRestoreHorzScroll, me);
        }
    },

    // Private. Determine if there are any columns with a locked configuration option
    hasLockedColumns: function(columns) {
        var i,
            len = columns.length,
            column;

        for (i = 0; i < len; i++) {
            column = columns[i];
            if (!column.processed && column.locked) {
                return true;
            }
        }
    },

    relayHeaderCtEvents: function (headerCt) {
        this.relayEvents(headerCt, [
            /**
             * @event columnresize
             * @inheritdoc Ext.grid.header.Container#columnresize
             */
            'columnresize',
            /**
             * @event columnmove
             * @inheritdoc Ext.grid.header.Container#columnmove
             */
            'columnmove',
            /**
             * @event columnhide
             * @inheritdoc Ext.grid.header.Container#columnhide
             */
            'columnhide',
            /**
             * @event columnshow
             * @inheritdoc Ext.grid.header.Container#columnshow
             */
            'columnshow',
            /**
             * @event columnschanged
             * @inheritdoc Ext.grid.header.Container#columnschanged
             */
            'columnschanged',
            /**
             * @event sortchange
             * @inheritdoc Ext.grid.header.Container#sortchange
             */
            'sortchange',
            /**
             * @event headerclick
             * @inheritdoc Ext.grid.header.Container#headerclick
             */
            'headerclick',
            /**
             * @event headercontextmenu
             * @inheritdoc Ext.grid.header.Container#headercontextmenu
             */
            'headercontextmenu',
            /**
             * @event headertriggerclick
             * @inheritdoc Ext.grid.header.Container#headertriggerclick
             */
            'headertriggerclick'
        ]);
    },

    getState: function(){
        var me = this,
            state = me.callParent(),
            storeState = me.store.getState();

        state = me.addPropertyToState(state, 'columns', me.headerCt.getColumnsState());

        if (storeState) {
            state.storeState = storeState;
        }
        return state;
    },

    applyState: function(state) {
        var me = this,
            sorter = state.sort,
            storeState = state.storeState,
            store = me.store,
            columns = state.columns;

        delete state.columns;

        // Ensure superclass has applied *its* state.
        // AbstractComponent saves dimensions (and anchor/flex) plus collapsed state.
        me.callParent(arguments);

        if (columns) {
            me.headerCt.applyColumnsState(columns);
        }

        // Old stored sort state. Deprecated and will die out.
        if (sorter) {
            if (store.remoteSort) {
                // Pass false to prevent a sort from occurring
                store.sort({
                    property: sorter.property,
                    direction: sorter.direction,
                    root: sorter.root
                }, null, false);
            } else {
                store.sort(sorter.property, sorter.direction);
            }
        }
        // New storeState which encapsulates groupers, sorters and filters
        else if (storeState) {
            store.applyState(storeState);
        }
    },

    /**
     * Returns the store associated with this Panel.
     * @return {Ext.data.Store} The store
     */
    getStore: function(){
        return this.store;
    },

    /**
     * Gets the view for this panel.
     * @return {Ext.view.Table}
     */
    getView: function() {
        var me = this,
            sm;

        if (!me.view) {
            sm = me.getSelectionModel();

            // TableView injects the view reference into this grid so that we have a reference as early as possible
            Ext.widget(Ext.apply({

                // Features need a reference to the grid, so configure a reference into the View
                grid: me,
                deferInitialRefresh: me.deferRowRender !== false,
                trackOver: me.trackMouseOver !== false,
                scroll: me.scroll,
                xtype: me.viewType,
                store: me.store,
                headerCt: me.headerCt,
                selModel: sm,
                features: me.features,
                panel: me,
                emptyText: me.emptyText || ''
            }, me.viewConfig));

            // Normalize the application of the markup wrapping the emptyText config.
            // `emptyText` can now be defined on the grid as well as on its viewConfig, and this led to the emptyText not
            // having the wrapping markup when it was defined in the viewConfig. It should be backwards compatible.
            // Note that in the unlikely event that emptyText is defined on both the grid config and the viewConfig that the viewConfig wins.
            if (me.view.emptyText) {
                me.view.emptyText = '<div class="' + me.emptyCls + '">' + me.view.emptyText + '</div>';
            }

            // TableView's custom component layout, Ext.view.TableLayout requires a reference to the headerCt because it depends on the headerCt doing its work.
            me.view.getComponentLayout().headerCt = me.headerCt;

            me.mon(me.view, {
                uievent: me.processEvent,
                scope: me
            });
            sm.view = me.view;
            me.headerCt.view = me.view;
        }
        return me.view;
    },

    /**
     * @private
     * autoScroll is never valid for all classes which extend TablePanel.
     */
    setAutoScroll: Ext.emptyFn,

    /**
     * @private
     * Processes UI events from the view. Propagates them to whatever internal Components need to process them.
     * @param {String} type Event type, eg 'click'
     * @param {Ext.view.Table} view TableView Component
     * @param {HTMLElement} cell Cell HtmlElement the event took place within
     * @param {Number} recordIndex Index of the associated Store Model (-1 if none)
     * @param {Number} cellIndex Cell index within the row
     * @param {Ext.EventObject} e Original event
     */
    processEvent: function(type, view, cell, recordIndex, cellIndex, e) {
        var me = this,
            header;

        if (cellIndex !== -1) {
            header = me.headerCt.getGridColumns()[cellIndex];
            return header.processEvent.apply(header, arguments);
        }
    },

    /**
     * This method is obsolete in 4.1. The closest equivalent in
     * 4.1 is {@link #doLayout}, but it is also possible that no
     * layout is needed.
     * @deprecated 4.1
     */
    determineScrollbars: function () {
        //<debug>
        Ext.log.warn('Obsolete');
        //</debug>
    },

    /**
     * This method is obsolete in 4.1. The closest equivalent in 4.1 is
     * {@link Ext.AbstractComponent#updateLayout}, but it is also possible that no layout
     * is needed.
     * @deprecated 4.1
     */
    invalidateScroller: function () {
        //<debug>
        Ext.log.warn('Obsolete');
        //</debug>
    },

    scrollByDeltaY: function(yDelta, animate) {
        this.getView().scrollBy(0, yDelta, animate);
    },

    scrollByDeltaX: function(xDelta, animate) {
        this.getView().scrollBy(xDelta, 0, animate);
    },

    afterCollapse: function() {
        var me = this;
        me.saveScrollPos();
        me.saveScrollPos();
        me.callParent(arguments);
    },

    afterExpand: function() {
        var me = this;
        me.callParent(arguments);
        me.restoreScrollPos();
        me.restoreScrollPos();
    },

    saveScrollPos: Ext.emptyFn,

    restoreScrollPos: Ext.emptyFn,

    onHeaderResize: function(){
        this.delayScroll();
    },

    // Update the view when a header moves
    onHeaderMove: function(headerCt, header, colsToMove, fromIdx, toIdx) {
        var me = this;

        // If there are Features or Plugins which create DOM which must match column order, they set the optimizedColumnMove flag to false.
        // In this case we must refresh the view on column move.
        if (me.optimizedColumnMove === false) {
            me.view.refresh();
        }

        // Simplest case for default DOM structure is just to swap the columns round in the view.
        else {
            me.view.moveColumn(fromIdx, toIdx, colsToMove);
        }
        me.delayScroll();
    },

    // Section onHeaderHide is invoked after view.
    onHeaderHide: function(headerCt, header) {
        this.delayScroll();
    },

    onHeaderShow: function(headerCt, header) {
        this.delayScroll();
    },

    delayScroll: function(){
        var target = this.getScrollTarget().el;
        if (target) {
            this.scrollTask.delay(10, null, null, [target.dom.scrollLeft]);
        }
    },

    /**
     * @private
     * Fires the TablePanel's viewready event when the view declares that its internal DOM is ready
     */
    onViewReady: function() {
         this.fireEvent('viewready', this);
    },

    /**
     * @private
     * Tracks when things happen to the view and preserves the horizontal scroll position.
     */
    onRestoreHorzScroll: function() {
        var left = this.scrollLeftPos;
        if (left) {
            // We need to restore the body scroll position here
            this.syncHorizontalScroll(left, true);
        }
    },

    getScrollerOwner: function() {
        var rootCmp = this;
        if (!this.scrollerOwner) {
            rootCmp = this.up('[scrollerOwner]');
        }
        return rootCmp;
    },

    /**
     * Gets left hand side marker for header resizing.
     * @private
     */
    getLhsMarker: function() {
        var me = this;
        return me.lhsMarker || (me.lhsMarker = Ext.DomHelper.append(me.el, {
            cls: me.resizeMarkerCls
        }, true));
    },

    /**
     * Gets right hand side marker for header resizing.
     * @private
     */
    getRhsMarker: function() {
        var me = this;

        return me.rhsMarker || (me.rhsMarker = Ext.DomHelper.append(me.el, {
            cls: me.resizeMarkerCls
        }, true));
    },

    /**
     * Returns the selection model being used and creates it via the configuration if it has not been created already.
     * @return {Ext.selection.Model} selModel
     */
    getSelectionModel: function(){
        var me = this,
            selModel = me.selModel,
            applyMode, mode, type;

        if (!selModel) {
            selModel = {};
            // no config, set our own mode
            applyMode = true;
        }

        if (!selModel.events) {
            // only config provided, set our mode if one doesn't exist on the config
            type = selModel.selType || me.selType;
            applyMode = !selModel.mode;
            selModel = me.selModel = Ext.create('selection.' + type, selModel);
        }

        if (me.simpleSelect) {
            mode = 'SIMPLE';
        } else if (me.multiSelect) {
            mode = 'MULTI';
        }

        Ext.applyIf(selModel, {
            allowDeselect: me.allowDeselect
        });

        if (mode && applyMode) {
            selModel.setSelectionMode(mode);
        }

        if (!selModel.hasRelaySetup) {
            me.relayEvents(selModel, [
                'selectionchange', 'beforeselect', 'beforedeselect', 'select', 'deselect'
            ]);
            selModel.hasRelaySetup = true;
        }

        // lock the selection model if user
        // has disabled selection
        if (me.disableSelection) {
            selModel.locked = true;
        }
        return selModel;
    },

    getScrollTarget: function(){
        var owner = this.getScrollerOwner(),
            items = owner.query('tableview');

        return items[1] || items[0];
    },

    onHorizontalScroll: function(event, target) {
        this.syncHorizontalScroll(target.scrollLeft);
    },

    syncHorizontalScroll: function(left, setBody) {
        var me = this,
            scrollTarget;

        setBody = setBody === true;
        // Only set the horizontal scroll if we've changed position,
        // so that we don't set this on vertical scrolls
        if (me.rendered && (setBody || left !== me.scrollLeftPos)) {
            // Only set the body position if we're reacting to a refresh, otherwise
            // we just need to set the header.
            if (setBody) {
                scrollTarget = me.getScrollTarget();
                scrollTarget.el.dom.scrollLeft = left;
            }
            me.headerCt.el.dom.scrollLeft = left;
            me.scrollLeftPos = left;
        }
    },

    // template method meant to be overriden
    onStoreLoad: Ext.emptyFn,

    getEditorParent: function() {
        return this.body;
    },

    bindStore: function(store, initial) {
        var me = this,
            view = me.getView(),
            bufferedStore = store && store.buffered,
            bufferedRenderer;

        // Bind to store immediately because subsequent processing looks for grid's store property
        me.store = store;

        if (view.store !== store) {
            if (initial) {
                // The initially created View will already be bound to the configured Store
                view.bindStore(store, false, 'dataSource');
            } else {
                // Otherwise, we're coming from a reconfigure, so we need to set the actual
                // store property on the view. It will set the data source
                view.bindStore(store, false);
            }
        }

        me.mon(store, {
            load: me.onStoreLoad,
            scope: me
        });
        me.storeRelayers = me.relayEvents(store, [
            /**
             * @event filterchange
             * @inheritdoc Ext.data.Store#filterchange
             */
            'filterchange'
        ]);

        // If the Store is buffered, create a BufferedRenderer to monitor the View's scroll progress
        // and scroll rows on/off when it detects we are nearing an edge.
        bufferedRenderer = me.findPlugin('bufferedrenderer');
        if (bufferedRenderer) {
            me.verticalScroller = bufferedRenderer;
            // If we're in a reconfigure rebind the BufferedRenderer
            if (bufferedRenderer.store) {
                bufferedRenderer.bindStore(store);
            }
        } else if (bufferedStore) {
            me.verticalScroller = bufferedRenderer = me.addPlugin(Ext.apply({
                ptype: 'bufferedrenderer'
            }, me.initialConfig.verticalScroller));
        }

        // If buffered rendering is being used, scroll position must be preserved across refreshes
        if (bufferedRenderer) {
            me.invalidateScrollerOnRefresh = false;
        }

        if (me.invalidateScrollerOnRefresh !== undefined) {
            view.preserveScrollOnRefresh = !me.invalidateScrollerOnRefresh;
        }
    },

    unbindStore: function() {
        var me = this,
            store = me.store;

        if (store) {
            me.store = null;
            me.mun(store, {
                load: me.onStoreLoad,
                scope: me
            });
            Ext.destroy(me.storeRelayers);
        }
    },

    // documented on GridPanel
    reconfigure: function(store, columns) {
        var me = this,
            view = me.getView(),
            originalDeferinitialRefresh,
            oldStore = me.store,
            headerCt = me.headerCt,
            oldColumns = headerCt ? headerCt.items.getRange() : me.columns;

        // Make copy in case the beforereconfigure listener mutates it.
        if (columns) {
            columns = Ext.Array.slice(columns);

            // Trigger generation of new XTemplate if the column set is different
            delete view.tpl;
        }

        me.fireEvent('beforereconfigure', me, store, columns, oldStore, oldColumns);
        if (me.lockable) {
            me.reconfigureLockable(store, columns);
        } else {
            Ext.suspendLayouts();
            if (columns) {
                // new columns, delete scroll pos
                delete me.scrollLeftPos;
                headerCt.removeAll();
                headerCt.add(columns);
            }
            if (store && store !== oldStore) {
                // Only unbind the store if a new one was passed
                if (me.store) {
                    me.unbindStore();
                }
                store = Ext.StoreManager.lookup(store);

                // On reconfigure, view refresh must be inline.
                originalDeferinitialRefresh = view.deferInitialRefresh;
                view.deferInitialRefresh = false;
                me.bindStore(store);
                view.deferInitialRefresh = originalDeferinitialRefresh;
            } else {
                me.getView().refresh();
            }
            headerCt.setSortState();
            Ext.resumeLayouts(true);
        }
        me.fireEvent('reconfigure', me, store, columns, oldStore, oldColumns);
    },

    beforeDestroy: function(){
        var task = this.scrollTask;
        if (task) {
            task.cancel();
            this.scrollTask = null;
        }
        this.callParent();
    },

    onDestroy: function(){
        if (this.lockable) {
            this.destroyLockable();
        }
        this.callParent();

    }
});


text:
import {Session} from "../shell/Session";
import {SplitDirection} from "../Enums";
import * as _ from "lodash";

export type PaneTree = Pane | PaneList;

export class Pane {
    readonly session: Session;
    readonly size = 1;

    constructor(session: Session) {
        this.session = session;
    }
}

export abstract class PaneList {
    readonly children: PaneTree[];

    constructor(children: PaneTree[]) {
        this.children = children;
    }

    /**
     * Add a new pane after the existing one.
     */
    add(newPane: Pane, existingPane: Pane, direction: SplitDirection) {
        const list = this.findListWithDirectChild(existingPane);

        if (!list) {
            throw `Couldn't find a list containing the pane.`;
        }

        const insertIndex = list.children.indexOf(existingPane);

        if (direction === SplitDirection.Horizontal) {
            list.insertBelow(insertIndex, newPane);
        } else {
            list.insertNextTo(insertIndex, newPane);
        }
    }

    remove(pane: Pane) {
        const list = this.findListWithDirectChild(pane);

        if (!list) {
            throw `Couldn't find a list containing the pane.`;
        }

        list.children.splice(list.children.indexOf(pane), 1);
    }

    get size(): number {
        return _.sum(this.children.map(child => child.size));
    }

    forEach(callback: (pane: Pane, index: number) => void, counter = 0): void {
        for (const child of this.children) {
            if (child instanceof Pane) {
                callback(child, counter);
                ++counter;
            } else {
                child.forEach((pane) => {
                    callback(pane, counter);
                    ++counter;
                });
            }
        }
    }

    previous(pane: Pane): Pane {
        let paneIndex = 0;

        this.forEach((current, index) => {
            if (pane === current) {
                paneIndex = index;
            }
        });

        let previous = pane;

        this.forEach((current, index) => {
            if (index === paneIndex - 1) {
                previous = current;
            }
        });

        return previous;
    }

    next(pane: Pane): Pane {
        let paneIndex = 0;

        this.forEach((current, index) => {
            if (pane === current) {
                paneIndex = index;
            }
        });

        let next = pane;

        this.forEach((current, index) => {
            if (index === paneIndex + 1) {
                next = current;
            }
        });

        return next;
    }

    protected abstract insertBelow(position: number, pane: Pane): void;
    protected abstract insertNextTo(position: number, pane: Pane): void;

    private findListWithDirectChild(tree: PaneTree): PaneList | undefined {
        const childContaining = this.children.find(child => child === tree);

        if (childContaining) {
            return this;
        }

        for (const child of this.children) {
            if (child instanceof PaneList) {
                const childListContaining = child.findListWithDirectChild(tree);
                if (childListContaining) {
                    return childListContaining;
                }
            }
        }
    }
}

export class ColumnList extends PaneList {
    protected insertBelow(position: number, pane: Pane) {
        this.children.splice(position, 1, new RowList([this.children[position], pane]));
    }

    protected insertNextTo(position: number, pane: Pane) {
        this.children.splice(position + 1, 0, pane);
    }
}

export class RowList extends PaneList {
    protected insertBelow(position: number, pane: Pane) {
        this.children.splice(position + 1, 0, pane);
    }

    protected insertNextTo(position: number, pane: Pane) {
        this.children.splice(position, 1, new ColumnList([this.children[position], pane]));
    }
}


text:
package com.github.daytron.daytronmoney.exception;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Test class for CurrencyDidNotMatchException
 * @author Ryan Gilera
 */
public class CurrencyDidNotMatchExceptionTest {

    public CurrencyDidNotMatchExceptionTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test(expected=CurrencyDidNotMatchException.class)
    public void testExceptionWithoutMessage() {
        throw new CurrencyDidNotMatchException();
    }

    @Test(expected=CurrencyDidNotMatchException.class)
    public void testExceptionWithMessage() {
        throw new CurrencyDidNotMatchException("Invalid");
    }
}


text:
import sublime
import sublime_plugin

if int(sublime.version()) < 3000:
    from sublime_haskell_common import attach_sandbox, get_cabal_project_dir_and_name_of_view, get_setting
else:
    from SublimeHaskell.sublime_haskell_common import attach_sandbox, get_cabal_project_dir_and_name_of_view, get_setting

class SublimeHaskellAutobuild(sublime_plugin.EventListener):
    def on_post_save(self, view):
        auto_build_enabled = get_setting('enable_auto_build')
        auto_check_enabled = get_setting('enable_auto_check')
        auto_lint_enabled = get_setting('enable_auto_lint')
        cabal_project_dir, cabal_project_name = get_cabal_project_dir_and_name_of_view(view)

        # auto build enabled and file within a cabal project
        if auto_build_enabled and cabal_project_dir is not None:
            view.window().run_command('sublime_haskell_build_auto')
            if get_setting('enable_ghc_mod') and auto_lint_enabled:
                view.window().run_command('sublime_haskell_ghc_mod_lint')
        # try to ghc-mod check
        elif get_setting('enable_ghc_mod'):
            if auto_check_enabled and auto_lint_enabled:
                view.window().run_command('sublime_haskell_ghc_mod_check_and_lint')
            elif auto_check_enabled:
                view.window().run_command('sublime_haskell_ghc_mod_check')
            elif auto_lint_enabled:
                view.window().run_command('sublime_haskell_ghc_mod_lint')

def current_cabal_build():
    """Current cabal build command"""
    args = ['stack', 'build']
    return attach_sandbox(args)


text:
package com.amazonaws.services.imagebuilder.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ImageStatus {

    PENDING("PENDING"),
    CREATING("CREATING"),
    BUILDING("BUILDING"),
    TESTING("TESTING"),
    DISTRIBUTING("DISTRIBUTING"),
    INTEGRATING("INTEGRATING"),
    AVAILABLE("AVAILABLE"),
    CANCELLED("CANCELLED"),
    FAILED("FAILED"),
    DEPRECATED("DEPRECATED"),
    DELETED("DELETED");

    private String value;

    private ImageStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ImageStatus corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ImageStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ImageStatus enumEntry : ImageStatus.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}