text:
package lol4j.protocol.dto.stats;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * Created by Aaron Corley on 12/11/13.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class AggregatedStatDto {
    private int averageAssists;
    private int averageChampionsKilled;
    private int averageCombatPlayerScore;
    private int averageNodeCapture;
    private int averageNodeCaptureAssist;
    private int averageNodeNeutralize;
    private int averageNodeNeutralizeAssist;
    private int averageNumDeaths;
    private int averageObjectivePlayerScore;
    private int averageTeamObjective;
    private int averageTotalPlayerScore;
    private int botGamesPlayed;
    private int killingSpree;
    private int maxAssists;
    private int maxChampionsKilled;
    private int maxCombatPlayerScore;
    private int maxLargestCriticalStrike;
    private int maxLargestKillingSpree;
    private int maxNodeCapture;
    private int maxNodeCaptureAssist;
    private int maxNodeNeutralize;
    private int maxNodeNeutralizeAssist;
    private int maxNumDeaths;
    private int maxObjectivePlayerScore;
    private int maxTeamObjective;
    private int maxTimePlayed;
    private int maxTimeSpentLiving;
    private int maxTotalPlayerScore;
    private int mostChampionKillsPerSession;
    private int mostSpellsCast;
    private int normalGamesPlayed;
    private int rankedPremadeGamesPlayed;
    private int rankedSoloGamesPlayed;
    private int totalAssists;
    private int totalChampionKills;
    private int totalDamageDealt;
    private int totalDamageTaken;
    private int totalDeathsPerSession;
    private int totalDoubleKills;
    private int totalFirstBlood;
    private int totalGoldEarned;
    private int totalHeal;
    private int totalMagicDamageDealt;
    private int totalMinionKills;
    private int totalNeutralMinionsKilled;
    private int totalNodeCapture;
    private int totalNodeNeutralize;
    private int totalPentaKills;
    private int totalPhysicalDamageDealt;
    private int totalQuadraKills;
    private int totalSessionsLost;
    private int totalSessionsPlayed;
    private int totalSessionsWon;
    private int totalTripleKills;
    private int totalTurretsKilled;
    private int totalUnrealKills;

    public int getAverageAssists() {
        return averageAssists;
    }

    public void setAverageAssists(int averageAssists) {
        this.averageAssists = averageAssists;
    }

    public int getAverageChampionsKilled() {
        return averageChampionsKilled;
    }

    public void setAverageChampionsKilled(int averageChampionsKilled) {
        this.averageChampionsKilled = averageChampionsKilled;
    }

    public int getAverageCombatPlayerScore() {
        return averageCombatPlayerScore;
    }

    public void setAverageCombatPlayerScore(int averageCombatPlayerScore) {
        this.averageCombatPlayerScore = averageCombatPlayerScore;
    }

    public int getAverageNodeCapture() {
        return averageNodeCapture;
    }

    public void setAverageNodeCapture(int averageNodeCapture) {
        this.averageNodeCapture = averageNodeCapture;
    }

    public int getAverageNodeCaptureAssist() {
        return averageNodeCaptureAssist;
    }

    public void setAverageNodeCaptureAssist(int averageNodeCaptureAssist) {
        this.averageNodeCaptureAssist = averageNodeCaptureAssist;
    }

    public int getAverageNodeNeutralize() {
        return averageNodeNeutralize;
    }

    public void setAverageNodeNeutralize(int averageNodeNeutralize) {
        this.averageNodeNeutralize = averageNodeNeutralize;
    }

    public int getAverageNodeNeutralizeAssist() {
        return averageNodeNeutralizeAssist;
    }

    public void setAverageNodeNeutralizeAssist(int averageNodeNeutralizeAssist) {
        this.averageNodeNeutralizeAssist = averageNodeNeutralizeAssist;
    }

    public int getAverageNumDeaths() {
        return averageNumDeaths;
    }

    public void setAverageNumDeaths(int averageNumDeaths) {
        this.averageNumDeaths = averageNumDeaths;
    }

    public int getAverageObjectivePlayerScore() {
        return averageObjectivePlayerScore;
    }

    public void setAverageObjectivePlayerScore(int averageObjectivePlayerScore) {
        this.averageObjectivePlayerScore = averageObjectivePlayerScore;
    }

    public int getAverageTeamObjective() {
        return averageTeamObjective;
    }

    public void setAverageTeamObjective(int averageTeamObjective) {
        this.averageTeamObjective = averageTeamObjective;
    }

    public int getAverageTotalPlayerScore() {
        return averageTotalPlayerScore;
    }

    public void setAverageTotalPlayerScore(int averageTotalPlayerScore) {
        this.averageTotalPlayerScore = averageTotalPlayerScore;
    }

    public int getBotGamesPlayed() {
        return botGamesPlayed;
    }

    public void setBotGamesPlayed(int botGamesPlayed) {
        this.botGamesPlayed = botGamesPlayed;
    }

    public int getKillingSpree() {
        return killingSpree;
    }

    public void setKillingSpree(int killingSpree) {
        this.killingSpree = killingSpree;
    }

    public int getMaxAssists() {
        return maxAssists;
    }

    public void setMaxAssists(int maxAssists) {
        this.maxAssists = maxAssists;
    }

    public int getMaxChampionsKilled() {
        return maxChampionsKilled;
    }

    public void setMaxChampionsKilled(int maxChampionsKilled) {
        this.maxChampionsKilled = maxChampionsKilled;
    }

    public int getMaxCombatPlayerScore() {
        return maxCombatPlayerScore;
    }

    public void setMaxCombatPlayerScore(int maxCombatPlayerScore) {
        this.maxCombatPlayerScore = maxCombatPlayerScore;
    }

    public int getMaxLargestCriticalStrike() {
        return maxLargestCriticalStrike;
    }

    public void setMaxLargestCriticalStrike(int maxLargestCriticalStrike) {
        this.maxLargestCriticalStrike = maxLargestCriticalStrike;
    }

    public int getMaxLargestKillingSpree() {
        return maxLargestKillingSpree;
    }

    public void setMaxLargestKillingSpree(int maxLargestKillingSpree) {
        this.maxLargestKillingSpree = maxLargestKillingSpree;
    }

    public int getMaxNodeCapture() {
        return maxNodeCapture;
    }

    public void setMaxNodeCapture(int maxNodeCapture) {
        this.maxNodeCapture = maxNodeCapture;
    }

    public int getMaxNodeCaptureAssist() {
        return maxNodeCaptureAssist;
    }

    public void setMaxNodeCaptureAssist(int maxNodeCaptureAssist) {
        this.maxNodeCaptureAssist = maxNodeCaptureAssist;
    }

    public int getMaxNodeNeutralize() {
        return maxNodeNeutralize;
    }

    public void setMaxNodeNeutralize(int maxNodeNeutralize) {
        this.maxNodeNeutralize = maxNodeNeutralize;
    }

    public int getMaxNodeNeutralizeAssist() {
        return maxNodeNeutralizeAssist;
    }

    public void setMaxNodeNeutralizeAssist(int maxNodeNeutralizeAssist) {
        this.maxNodeNeutralizeAssist = maxNodeNeutralizeAssist;
    }

    public int getMaxNumDeaths() {
        return maxNumDeaths;
    }

    public void setMaxNumDeaths(int maxNumDeaths) {
        this.maxNumDeaths = maxNumDeaths;
    }

    public int getMaxObjectivePlayerScore() {
        return maxObjectivePlayerScore;
    }

    public void setMaxObjectivePlayerScore(int maxObjectivePlayerScore) {
        this.maxObjectivePlayerScore = maxObjectivePlayerScore;
    }

    public int getMaxTeamObjective() {
        return maxTeamObjective;
    }

    public void setMaxTeamObjective(int maxTeamObjective) {
        this.maxTeamObjective = maxTeamObjective;
    }

    public int getMaxTimePlayed() {
        return maxTimePlayed;
    }

    public void setMaxTimePlayed(int maxTimePlayed) {
        this.maxTimePlayed = maxTimePlayed;
    }

    public int getMaxTimeSpentLiving() {
        return maxTimeSpentLiving;
    }

    public void setMaxTimeSpentLiving(int maxTimeSpentLiving) {
        this.maxTimeSpentLiving = maxTimeSpentLiving;
    }

    public int getMaxTotalPlayerScore() {
        return maxTotalPlayerScore;
    }

    public void setMaxTotalPlayerScore(int maxTotalPlayerScore) {
        this.maxTotalPlayerScore = maxTotalPlayerScore;
    }

    public int getMostChampionKillsPerSession() {
        return mostChampionKillsPerSession;
    }

    public void setMostChampionKillsPerSession(int mostChampionKillsPerSession) {
        this.mostChampionKillsPerSession = mostChampionKillsPerSession;
    }

    public int getMostSpellsCast() {
        return mostSpellsCast;
    }

    public void setMostSpellsCast(int mostSpellsCast) {
        this.mostSpellsCast = mostSpellsCast;
    }

    public int getNormalGamesPlayed() {
        return normalGamesPlayed;
    }

    public void setNormalGamesPlayed(int normalGamesPlayed) {
        this.normalGamesPlayed = normalGamesPlayed;
    }

    public int getRankedPremadeGamesPlayed() {
        return rankedPremadeGamesPlayed;
    }

    public void setRankedPremadeGamesPlayed(int rankedPremadeGamesPlayed) {
        this.rankedPremadeGamesPlayed = rankedPremadeGamesPlayed;
    }

    public int getRankedSoloGamesPlayed() {
        return rankedSoloGamesPlayed;
    }

    public void setRankedSoloGamesPlayed(int rankedSoloGamesPlayed) {
        this.rankedSoloGamesPlayed = rankedSoloGamesPlayed;
    }

    public int getTotalAssists() {
        return totalAssists;
    }

    public void setTotalAssists(int totalAssists) {
        this.totalAssists = totalAssists;
    }

    public int getTotalChampionKills() {
        return totalChampionKills;
    }

    public void setTotalChampionKills(int totalChampionKills) {
        this.totalChampionKills = totalChampionKills;
    }

    public int getTotalDamageDealt() {
        return totalDamageDealt;
    }

    public void setTotalDamageDealt(int totalDamageDealt) {
        this.totalDamageDealt = totalDamageDealt;
    }

    public int getTotalDamageTaken() {
        return totalDamageTaken;
    }

    public void setTotalDamageTaken(int totalDamageTaken) {
        this.totalDamageTaken = totalDamageTaken;
    }

    public int getTotalDeathsPerSession() {
        return totalDeathsPerSession;
    }

    public void setTotalDeathsPerSession(int totalDeathsPerSession) {
        this.totalDeathsPerSession = totalDeathsPerSession;
    }

    public int getTotalDoubleKills() {
        return totalDoubleKills;
    }

    public void setTotalDoubleKills(int totalDoubleKills) {
        this.totalDoubleKills = totalDoubleKills;
    }

    public int getTotalFirstBlood() {
        return totalFirstBlood;
    }

    public void setTotalFirstBlood(int totalFirstBlood) {
        this.totalFirstBlood = totalFirstBlood;
    }

    public int getTotalGoldEarned() {
        return totalGoldEarned;
    }

    public void setTotalGoldEarned(int totalGoldEarned) {
        this.totalGoldEarned = totalGoldEarned;
    }

    public int getTotalHeal() {
        return totalHeal;
    }

    public void setTotalHeal(int totalHeal) {
        this.totalHeal = totalHeal;
    }

    public int getTotalMagicDamageDealt() {
        return totalMagicDamageDealt;
    }

    public void setTotalMagicDamageDealt(int totalMagicDamageDealt) {
        this.totalMagicDamageDealt = totalMagicDamageDealt;
    }

    public int getTotalMinionKills() {
        return totalMinionKills;
    }

    public void setTotalMinionKills(int totalMinionKills) {
        this.totalMinionKills = totalMinionKills;
    }

    public int getTotalNeutralMinionsKilled() {
        return totalNeutralMinionsKilled;
    }

    public void setTotalNeutralMinionsKilled(int totalNeutralMinionsKilled) {
        this.totalNeutralMinionsKilled = totalNeutralMinionsKilled;
    }

    public int getTotalNodeCapture() {
        return totalNodeCapture;
    }

    public void setTotalNodeCapture(int totalNodeCapture) {
        this.totalNodeCapture = totalNodeCapture;
    }

    public int getTotalNodeNeutralize() {
        return totalNodeNeutralize;
    }

    public void setTotalNodeNeutralize(int totalNodeNeutralize) {
        this.totalNodeNeutralize = totalNodeNeutralize;
    }

    public int getTotalPentaKills() {
        return totalPentaKills;
    }

    public void setTotalPentaKills(int totalPentaKills) {
        this.totalPentaKills = totalPentaKills;
    }

    public int getTotalPhysicalDamageDealt() {
        return totalPhysicalDamageDealt;
    }

    public void setTotalPhysicalDamageDealt(int totalPhysicalDamageDealt) {
        this.totalPhysicalDamageDealt = totalPhysicalDamageDealt;
    }

    public int getTotalQuadraKills() {
        return totalQuadraKills;
    }

    public void setTotalQuadraKills(int totalQuadraKills) {
        this.totalQuadraKills = totalQuadraKills;
    }

    public int getTotalSessionsLost() {
        return totalSessionsLost;
    }

    public void setTotalSessionsLost(int totalSessionsLost) {
        this.totalSessionsLost = totalSessionsLost;
    }

    public int getTotalSessionsPlayed() {
        return totalSessionsPlayed;
    }

    public void setTotalSessionsPlayed(int totalSessionsPlayed) {
        this.totalSessionsPlayed = totalSessionsPlayed;
    }

    public int getTotalSessionsWon() {
        return totalSessionsWon;
    }

    public void setTotalSessionsWon(int totalSessionsWon) {
        this.totalSessionsWon = totalSessionsWon;
    }

    public int getTotalTripleKills() {
        return totalTripleKills;
    }

    public void setTotalTripleKills(int totalTripleKills) {
        this.totalTripleKills = totalTripleKills;
    }

    public int getTotalTurretsKilled() {
        return totalTurretsKilled;
    }

    public void setTotalTurretsKilled(int totalTurretsKilled) {
        this.totalTurretsKilled = totalTurretsKilled;
    }

    public int getTotalUnrealKills() {
        return totalUnrealKills;
    }

    public void setTotalUnrealKills(int totalUnrealKills) {
        this.totalUnrealKills = totalUnrealKills;
    }
}


text:
<?php

use Isimmons\Sgd\Console\RepoFetchCommand;
use Symfony\Component\Console\Tester\CommandTester;

class RepoFetchCommandTest extends TestCase {

    public function setUp()
    {
        $this->mock = Mockery::mock('Isimmons\Sgd\Git');
    }

    public function tearDown()
    {
        Mockery::close();
    }

    public function testAllArguments()
    {
        $this->mock->shouldReceive('fetch')
            ->once()
            ->with('repo', 'origin')
            ->andReturn(true);

        $command = new RepoFetchCommand($this->mock);

        $tester = new CommandTester($command);
        $tester->execute(['repo' => 'repo', 'remote' => 'origin']);

        $this->assertEquals('repo <<-- origin Success.', $tester->getDisplay());
    }

}

redpajama_set_name: RedPajamaGithub


text:
import { injectable } from "tsyringe";
import * as messages from "../../shared/messages";
import FollowSlaveUseCase from "../usecases/FollowSlaveUseCase";

@injectable()
export default class FollowSlaveController {
  constructor(private usecase: FollowSlaveUseCase) {}

  countTargets(m: messages.FollowRequestCountTargetsMessage): void {
    this.usecase.countTargets(m.viewSize, m.framePosition);
  }

  createHints(m: messages.FollowCreateHintsMessage): void {
    this.usecase.createHints(m.viewSize, m.framePosition, m.tags);
  }

  showHints(m: messages.FollowShowHintsMessage): void {
    this.usecase.showHints(m.prefix);
  }

  activate(m: messages.FollowActivateMessage): void {
    this.usecase.activate(m.tag, m.newTab, m.background);
  }

  clear(_m: messages.FollowRemoveHintsMessage) {
    this.usecase.clear();
  }
}


text:
package cn.binarywang.wx.miniapp.api.impl;

import java.io.File;

import org.testng.annotations.*;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.test.ApiTestModule;
import com.google.inject.Inject;

/**
 * @author Binary Wang
 */
@Test
@Guice(modules = ApiTestModule.class)
public class WxMaQrcodeServiceImplTest {
  @Inject
  private WxMaService wxService;

  @Test
  public void testCreateQrCode() throws Exception {
    final File qrCode = this.wxService.getQrcodeService().createQrcode("111", 122);
    System.out.println(qrCode);
  }

  @Test
  public void testCreateWxaCode() throws Exception {
    final File wxCode = this.wxService.getQrcodeService().createWxaCode("111", 122);
    System.out.println(wxCode);
  }

  @Test
  public void testCreateWxaCodeUnlimit() throws Exception {
    final File wxCode = this.wxService.getQrcodeService().createWxaCodeUnlimit("111", null);
    System.out.println(wxCode);
  }

}


text:
'use strict';

var mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI);
//const mongooseConnection = mongoose.c(process.env.MONGOHQ_URL);

var express = require('express');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var compression = require('compression');

app.use(compression({threshold: 0}));

app.use(favicon(__dirname + '/client/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());

var passport = require('passport');
//http://code.tutsplus.com/tutorials/authenticating-nodejs-applications-with-passport--cms-21619

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
app.use(session({
    secret: 'mySecretKey',
    maxAge: new Date(Date.now() + 3600000),
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

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

app.set('views', __dirname + '/server/ui/views');
app.set('view engine', 'ejs');

app.use(passport.initialize());
app.use(passport.session());

// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());

app.use('/api', require('./server/api'));
// Initialize Passport
var initPassport = require('./server/passport/init');
initPassport(passport);

var routes = require('./server/ui/routes')(passport);
app.use('/', routes);

app.use(function (req, res) {
    res.send(404);
});

/*jshint unused:false */
app.use(function (err, req, res, next) {
    res.send(500, {
        err: err.stack
    });
});
/*jshint unused:true */
module.exports = app;


text:
package org.apache.jmeter.examples.testbeans.example3;

import java.beans.PropertyDescriptor;

import org.apache.jmeter.testbeans.BeanInfoSupport;
import org.apache.jmeter.testbeans.gui.TypeEditor;

public class Example3BeanInfo extends BeanInfoSupport {

    private PropertyDescriptor getprop(String name) {
        return property(name);
    }

    private PropertyDescriptor getprop(String name, Object deflt) {
        PropertyDescriptor p = property(name);
        p.setValue(DEFAULT, deflt);
        p.setValue(NOT_UNDEFINED, Boolean.TRUE);
        return p;
    }

    public Example3BeanInfo() {
        super(Example3.class);
        getprop("mybool");
        getprop("myBoolean1");
        getprop("myBoolean2", "True");
        getprop("myInt", "77");
        getprop("myInteger1");
        getprop("myInteger2", Integer.valueOf(123));
        getprop("mylong", "99");
        getprop("myLong1");
        getprop("myLong2", Long.valueOf(456));
        getprop("myString1");
        getprop("myString2","abcd");
        property("myFile2", TypeEditor.FileEditor);
    }
}


text:
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE USER test WITH PASSWORD 'test';
    CREATE DATABASE test;
    GRANT ALL PRIVILEGES ON DATABASE test TO test;
EOSQL


text:
<?php

/**
 * Backwards copatible CsvBulkLoader
 * Almost api equivelant to CSVBulkLoader
 */
class CsvBetterBulkLoader extends BetterBulkLoader{

	public $delimiter = ',';
	public $enclosure = '"';
	public $hasHeaderRow = true;

	protected function processAll($filepath, $preview = false) {
		//configre a CsvBulkLoaderSource
		$source = new CsvBulkLoaderSource();
		$source->setFilePath($filepath);
		$source->setHasHeader($this->hasHeaderRow);
		$source->setFieldDelimiter($this->delimiter);
		$source->setFieldEnclosure($this->enclosure);
		$this->setSource($source);

		return parent::processAll($filepath, $preview);
	}

	public function hasHeaderRow() {
		return ($this->hasHeaderRow || isset($this->columnMap));
	}

}


text:
from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.http import QueryDict
from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.conf.urls.static import static, settings
import json

# Modal
from registrar.models import Course
from registrar.models import Teacher
from registrar.models import Assignment
from registrar.models import AssignmentSubmission
from registrar.models import EssayQuestion
from registrar.models import EssaySubmission
from registrar.models import MultipleChoiceQuestion
from registrar.models import MultipleChoiceSubmission
from registrar.models import ResponseQuestion
from registrar.models import ResponseSubmission
from registrar.models import TrueFalseQuestion
from registrar.models import TrueFalseSubmission

# View
from teacher.views import assignment

# Contants
TEST_USER_EMAIL = "ledo@gah.com"
TEST_USER_USERNAME = "Ledo"
TEST_USER_PASSWORD = "ContinentalUnion"
TEST_USER_EMAIL2 = "whalesquid@hideauze.com"
TEST_USER_USERNAME2 = "whalesquid"
TEST_USER_PASSWORD2 = "Evolvers"

# Notes:
# https://docs.djangoproject.com/en/1.7/topics/testing/tools/#assertions

# Create your tests here.
class AssignmentTestCase(TestCase):
    def tearDown(self):
        courses = Course.objects.all()
        for course in courses:
            course.delete()
        User.objects.all().delete()

    def setUp(self):
        # Create our Trudy user.
        User.objects.create_user(
            email=TEST_USER_EMAIL2,
            username=TEST_USER_USERNAME2,
            password=TEST_USER_PASSWORD2
        )
        user = User.objects.get(email=TEST_USER_EMAIL2)
        teacher = Teacher.objects.create(user=user)

        # Create our Student.
        User.objects.create_user(
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        ).save()
        user = User.objects.get(email=TEST_USER_EMAIL)
        teacher = Teacher.objects.create(user=user)

        # Create a test course.
        Course.objects.create(
            id=1,
            title="Comics Book Course",
            sub_title="The definitive course on comics!",
            category="",
            teacher=teacher,
        ).save()

        course = Course.objects.get(id=1)
        Assignment.objects.create(
            assignment_id=1,
            assignment_num=1,
            title="Hideauze",
            description="Anime related assignment.",
            worth=25,
            course=course,
        )

    def get_logged_in_client(self):
        client = Client()
        client.login(
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        return client

    def get_logged_in_trudy_client(self):
        client = Client()
        client.login(
            username=TEST_USER_USERNAME2,
            password=TEST_USER_PASSWORD2
        )
        return client

    def test_url_resolves_to_assignments_page_view(self):
        found = resolve('/teacher/course/1/assignments')
        self.assertEqual(found.func, assignment.assignments_page)

    def test_assignments_page_with_no_submissions(self):
        try:
            Assignment.objects.get(assignment_id=1).delete()
        except Assignment.DoesNotExist:
            pass
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignments')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'Comics Book Course',response.content)
        self.assertIn(b'ajax_assignment_modal',response.content)

    def test_url_resolves_to_assignment_table_view(self):
        found = resolve('/teacher/course/1/assignments_table')
        self.assertEqual(found.func, assignment.assignments_table)

    def test_assignments_table_returns_with_no_submissions(self):
        try:
            Assignment.objects.get(assignment_id=1).delete()
        except Assignment.DoesNotExist:
            pass
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignments_table')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'ajax_assignment(0);',response.content)

    def test_url_resolves_to_delete_assignment(self):
        found = resolve('/teacher/course/1/delete_assignment')
        self.assertEqual(found.func, assignment.delete_assignment)

    def test_delete_assignment_with_no_submissions(self):
        try:
            Assignment.objects.get(assignment_id=1).delete()
        except Assignment.DoesNotExist:
            pass
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/delete_assignment',{
            'assignment_id': 1,
        }, **kwargs)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(array['status'], 'failed')
        self.assertEqual(array['message'], 'record not found')

    def test_delete_assignment_with_submissions_and_correct_user(self):
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/delete_assignment',{
            'assignment_id': 1,
        }, **kwargs)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(array['status'], 'success')
        self.assertEqual(array['message'], 'assignment was deleted')

    def test_delete_assignment_with_submissions_and_incorrect_user(self):
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_trudy_client()
        response = client.post('/teacher/course/1/delete_assignment',{
            'assignment_id': 1,
        }, **kwargs)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(array['status'], 'failed')
        self.assertEqual(array['message'], 'unauthorized deletion')

    def test_url_resolves_to_save_assignment(self):
        found = resolve('/teacher/course/1/save_assignment')
        self.assertEqual(found.func, assignment.save_assignment)

    def test_save_assignment_with_insert(self):
        try:
            Assignment.objects.get(assignment_id=1).delete()
        except Assignment.DoesNotExist:
            pass
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/save_assignment',{
            'assignment_id': 0,
            'assignment_num': 1,
            'title': 'Test',
            'description': 'Test',
            'start_date': '2020-01-01',
            'due_date': '2020-01-01',
            'worth': 25,
        }, **kwargs)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(array['message'], 'saved')
        self.assertEqual(array['status'], 'success')

    def test_save_assignment_with_update(self):
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/save_assignment',{
            'assignment_id': 1,
            'assignment_num': 1,
            'title': 'Test',
            'description': 'Test',
            'start_date': '2020-01-01',
            'due_date': '2020-01-01',
            'worth': 25,
        }, **kwargs)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(array['message'], 'saved')
        self.assertEqual(array['status'], 'success')

    def test_url_resolves_to_assignment_page_view(self):
        found = resolve('/teacher/course/1/assignment/1')
        self.assertEqual(found.func, assignment.assignment_page)

    def test_assignment_page(self):
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'ajax_question_modal',response.content)

    def test_save_question_with_insert_essay_question(self):
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/save_question',{
            'question_id': 0,
            'question_type': settings.ESSAY_QUESTION_TYPE,
            'question_num': 1,
            'title': 'H+',
            'description': 'What does it mean to be a human being?',
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was saved')
        self.assertEqual(array['status'], 'success')

    def test_save_question_with_update_essay_question(self):
        # Insert
        EssayQuestion.objects.create(
            question_id=1,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Evolvers",
            description="Write an essay about the Evolvers.",
        )

        # Update
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/save_question',{
            'question_id': 1,
            'question_type': settings.ESSAY_QUESTION_TYPE,
            'question_num': 1,
            'title': 'H+',
            'description': 'What does it mean to be a human being?',
            'marks': 1,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was saved')
        self.assertEqual(array['status'], 'success')

    def test_save_question_with_insert_multiple_choice_question(self):
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/save_question',{
            'question_id': 0,
            'question_type': settings.MULTIPLECHOICE_QUESTION_TYPE,
            'question_num': 1,
            'title': 'Sun',
            'description': 'Why did humanity leave Earth?',
            'a': 'Global Cooling',
            'b': 'Abnormal Solar Hibernation',
            'c': 'Global Warming',
            'd': 'World Peace',
            'a_is_correct': True,
            'b_is_correct': True,
            'marks': 1,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was saved')
        self.assertEqual(array['status'], 'success')

    def test_save_question_with_update_multiple_choice_question(self):
        # Insert
        MultipleChoiceQuestion.objects.create(
            question_id=2,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Hideauze",
            description="Who where the Hideauze?",
            a="Former Humans",
            a_is_correct=True,
            b="Aliens",
            b_is_correct=False,
            c="Magical or Supernatural Creatures",
            c_is_correct=False,
            d="Transhumanists",
            d_is_correct=True,
            e="Heavenly Creatures",
            e_is_correct=True,
        )

        # Update
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/save_question',{
            'question_id': 2,
            'question_type': settings.MULTIPLECHOICE_QUESTION_TYPE,
            'question_num': 1,
            'title': 'Sun',
            'description': 'Why did humanity leave Earth?',
            'a': 'Global Cooling',
            'b': 'Abnormal Solar Hibernation',
            'c': 'Global Warming',
            'd': 'World Peace',
            'a_is_correct': True,
            'b_is_correct': True,
            'marks': 1,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was saved')
        self.assertEqual(array['status'], 'success')

    def test_save_question_with_insert_true_false_question(self):
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/save_question',{
            'question_id': 0,
            'question_type': settings.TRUEFALSE_QUESTION_TYPE,
            'question_num': 3,
            'title': 'Hideauze',
            'description': 'Where the Hideauze once humans?',
            'true_choice':'Yes, former humans',
            'false_choice':'No, aliens',
            'answer': True,
            'marks': 1,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was saved')
        self.assertEqual(array['status'], 'success')

    def test_save_question_with_update_true_false_question(self):
        # Insert
        TrueFalseQuestion.objects.create(
            question_id=3,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Hideauze",
            description="Where the Hideauze human?",
            true_choice="Yes, former humans",
            false_choice="No, aliens",
            answer=True,
        )

        # Update
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/save_question',{
            'question_id': 3,
            'question_type': settings.TRUEFALSE_QUESTION_TYPE,
            'question_num': 3,
            'title': 'Hideauze',
            'description': 'Where the Hideauze once humans?',
            'true_choice':'Yes, former humans',
            'false_choice':'No, aliens',
            'answer': True,
            'marks': 1,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was saved')
        self.assertEqual(array['status'], 'success')

    def test_save_question_with_insert_response_question(self):
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/save_question',{
            'question_id': 0,
            'question_type': settings.RESPONSE_QUESTION_TYPE,
            'question_num': 4,
            'title': 'Ice Age',
            'description': 'Why did humanity migrate off-world?',
            'answer': 'Because of solar hibernation causing Global Cooling on Earth.',
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was saved')
        self.assertEqual(array['status'], 'success')

    def test_save_question_with_update_response_question(self):
        # Insert
        ResponseQuestion.objects.create(
            question_id=4,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Ice Age",
            description="Why did humanity migrate off-world?",
            answer="Because of solar hibernation causing Global Cooling on Earth.",
        )

        # Update
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/save_question',{
            'question_id': 4,
            'question_type': settings.RESPONSE_QUESTION_TYPE,
            'question_num': 4,
            'title': 'Mecha',
            'description': 'What was the name of Ledos mech?',
            'answer': 'Chambers',
            'marks': 1,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was saved')
        self.assertEqual(array['status'], 'success')

    def test_delete_question_with_essay_question(self):
        EssayQuestion.objects.create(
            question_id=1,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Evolvers",
            description="Write an essay about the Evolvers.",
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/delete_question',{
            'question_id': 1,
            'question_type': settings.ESSAY_QUESTION_TYPE,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was deleted')
        self.assertEqual(array['status'], 'success')

    def test_delete_question_with_multiple_choice_question(self):
        MultipleChoiceQuestion.objects.create(
            question_id=2,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Hideauze",
            description="Who where the Hideauze?",
            a="Former Humans",
            a_is_correct=True,
            b="Aliens",
            b_is_correct=False,
            c="Magical or Supernatural Creatures",
            c_is_correct=False,
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/delete_question',{
            'question_id': 2,
            'question_type': settings.MULTIPLECHOICE_QUESTION_TYPE,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was deleted')
        self.assertEqual(array['status'], 'success')

    def test_delete_question_with_true_false_question(self):
        TrueFalseQuestion.objects.create(
            question_id=3,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Hideauze",
            description="Where the Hideauze human?",
            true_choice="Yes, former humans",
            false_choice="No, aliens",
            answer=True,
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/delete_question',{
            'question_id': 3,
            'question_type': settings.TRUEFALSE_QUESTION_TYPE,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was deleted')
        self.assertEqual(array['status'], 'success')

    def test_delete_question_with_response_question(self):
        ResponseQuestion.objects.create(
            question_id=4,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Ice Age",
            description="Why did humanity migrate off-world?",
            answer="Because of solar hibernation causing Global Cooling on Earth.",
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/delete_question',{
            'question_id': 4,
            'question_type': settings.RESPONSE_QUESTION_TYPE,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'question was deleted')
        self.assertEqual(array['status'], 'success')

    def test_url_resolves_to_questions_table_view(self):
        found = resolve('/teacher/course/1/assignment/1/questions_table')
        self.assertEqual(found.func, assignment.questions_table)

    def test_questions_table_returns_without_questions(self):
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/questions_table')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'ajax_question(0,0);',response.content)

    def test_questions_table_returns_with_questions(self):
        ResponseQuestion.objects.create(
            question_id=4,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Ice Age",
            description="Why did humanity migrate off-world?",
            answer="Because of solar hibernation causing Global Cooling on Earth.",
        )
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/questions_table')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'Response',response.content)

    def test_question_type_modal(self):
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/question_type_modal',**kwargs)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'question_modal',response.content)

    def test_question_essay_modal(self):
        EssayQuestion.objects.create(
            question_id=1,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Evolvers",
            description="Write an essay about the Evolvers.",
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/question_essay_modal',{
            'question_id': 1,
        },**kwargs)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'question_modal',response.content)

    def test_question_multiple_choice_modal(self):
        MultipleChoiceQuestion.objects.create(
            question_id=2,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Hideauze",
            description="Who where the Hideauze?",
            a="Former Humans",
            a_is_correct=True,
            b="Aliens",
            b_is_correct=False,
            c="Magical or Supernatural Creatures",
            c_is_correct=False,
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/question_multiple_choice_modal',{
            'question_id':2,
        },**kwargs)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'question_modal',response.content)

    def test_question_true_false_modal(self):
        TrueFalseQuestion.objects.create(
                question_id=3,
                assignment=Assignment.objects.get(assignment_id=1),
            title="Hideauze",
            description="Where the Hideauze human?",
            true_choice="Yes, former humans",
            false_choice="No, aliens",
            answer=True,
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/question_true_false_modal',{
            'question_id':3,
        },**kwargs)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'question_modal',response.content)

    def test_question_response_modal(self):
        ResponseQuestion.objects.create(
            question_id=4,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Ice Age",
            description="Why did humanity migrate off-world?",
            answer="Because of solar hibernation causing Global Cooling on Earth.",
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_client()
        response = client.post('/teacher/course/1/assignment/1/question_response_modal',{
            'question_id':4,
        },**kwargs)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'question_modal',response.content)

    def test_delete_question_with_incorrect_user(self):
        ResponseQuestion.objects.create(
            question_id=4,
            assignment=Assignment.objects.get(assignment_id=1),
            title="Ice Age",
            description="Why did humanity migrate off-world?",
            answer="Because of solar hibernation causing Global Cooling on Earth.",
        )
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}
        client = self.get_logged_in_trudy_client()
        response = client.post('/teacher/course/1/assignment/1/delete_question',{
            'question_id': 4,
            'question_type': settings.RESPONSE_QUESTION_TYPE,
        }, **kwargs)
        self.assertEqual(response.status_code, 200)
        json_string = response.content.decode(encoding='UTF-8')
        array = json.loads(json_string)
        self.assertEqual(array['message'], 'unauthorized deletion')
        self.assertEqual(array['status'], 'failed')


text:
var crypto;
var token;

module.exports.generateToken = function () {

	try {
		crypto = require('crypto')
		var secret = require('../config/config').secret

		var timeNow = new Date().getTime()
		var hash = crypto.createHmac('sha256', secret)
									.update(timeNow + '')
									.digest('base64')
		token = {msg_mac : hash, time_created : timeNow}
	} catch(err) {
		console.log('crypto support is disabled')
	}

	return token
}


text:
@implementation ADTestAppAcquireLayoutBuilder

- (id)init
{
    if (!(self = [super init]))
        return nil;

    _screenRect = UIScreen.mainScreen.bounds;
    _contentView = [[UIView alloc] initWithFrame:_screenRect];
    _contentView.translatesAutoresizingMaskIntoConstraints = NO;

    _views = [NSMutableDictionary new];
    _keys = [NSMutableArray new];

    return self;
}

- (void)addControl:(UIControl *)control
             title:(NSString *)title
{
    UIView* view = [[UIView alloc] init];
    UILabel* label = [[UILabel alloc] init];
    label.textColor = UIColor.blackColor;
    label.text = title;
    label.font = [UIFont systemFontOfSize:12.0];
    label.translatesAutoresizingMaskIntoConstraints = NO;
    label.textAlignment = NSTextAlignmentRight;

    [view addSubview:label];

    control.translatesAutoresizingMaskIntoConstraints = NO;
    [view addSubview:control];

    NSDictionary* views = @{ @"label" : label, @"control" : control };
    NSArray* verticalConstraints1 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label]|" options:0 metrics:NULL views:views];
    NSArray* verticalConstraints2 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[control(29)]|" options:0 metrics:NULL views:views];
    NSArray* horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label(60)]-[control]|" options:NSLayoutFormatAlignAllCenterY metrics:NULL views:views];

    [view addConstraints:verticalConstraints1];
    [view addConstraints:verticalConstraints2];
    [view addConstraints:horizontalConstraints];

    [self addView:view key:title];
}

- (void)addViewInternal:(UIView*)view key:(NSString *)key
{
    view.translatesAutoresizingMaskIntoConstraints = NO;
    [_contentView addSubview:view];
    [_views setObject:view forKey:key];
    [_keys addObject:key];
}

- (void)addView:(UIView*)view key:(NSString *)key
{
    [self addViewInternal:view key:key];

    NSString* horizontalConstraint = [NSString stringWithFormat:@"H:|-6-[%@]-6-|", key];
    NSArray* horizontalConstraints2 = [NSLayoutConstraint constraintsWithVisualFormat:horizontalConstraint options:0 metrics:NULL views:_views];
    [_contentView addConstraints:horizontalConstraints2];
}

- (void)addCenteredView:(UIView *)view key:(NSString *)key
{
    [self addViewInternal:view key:key];

    NSLayoutConstraint* centerConstraint =
    [NSLayoutConstraint constraintWithItem:view
                                 attribute:NSLayoutAttributeCenterX
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:_contentView
                                 attribute:NSLayoutAttributeCenterX
                                multiplier:1.0
                                  constant:0.0];
    [_contentView addConstraint:centerConstraint];
}

- (UIView*)contentView
{
    if (_keys.count == 0)
    {
        return _contentView;
    }

    NSMutableString* verticalConstraint = [NSMutableString new];
    [verticalConstraint appendString:@"V:|"];

    for (int i = 0; i < _keys.count - 1; i++)
    {
        NSString* key = _keys[i];
        [verticalConstraint appendFormat:@"[%@]-", key];
    }

    NSString* lastKey = _keys.lastObject;
    [verticalConstraint appendFormat:@"[%@(>=200)]-36-|", lastKey];

    NSArray* verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:verticalConstraint options:0 metrics:NULL views:_views];
    [_contentView addConstraints:verticalConstraints];

    return _contentView;
}

@end


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.ComponentModel.Composition.Hosting
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.CSharp.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.Navigation
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Navigation
Imports Microsoft.CodeAnalysis.Notification
Imports Microsoft.CodeAnalysis.Text
Imports Roslyn.Utilities

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition
    Public Class GoToDefinitionCancellationTests

        <Fact, Trait(Traits.Feature, Traits.Features.GoToDefinition)>
        Public Sub TestCancellation()
            ' Run without cancelling.
            Dim updates As Integer = Me.Cancel(Integer.MaxValue, False)
            Assert.InRange(updates, 0, Integer.MaxValue)
            Dim i As Integer = 0
            While i < updates
                Dim n As Integer = Me.Cancel(i, True)
                Assert.Equal(n, i + 1)
                i = i + 1
            End While
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.GoToDefinition)>
        Public Sub TestInLinkedFiles()
            Dim definition =
<Workspace>
    <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
        <Document FilePath="C.cs">
class C
{
    void M()
    {
        M1$$(5);
    }
#if Proj1
    void M1(int x) { }
#endif
#if Proj2
    void M1(int x) { }
#endif
}
        </Document>
    </Project>
    <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
        <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
    </Project>
</Workspace>

            Using workspace = TestWorkspaceFactory.CreateWorkspace(
                    definition,
                    exportProvider:=MinimalTestExportProvider.CreateExportProvider(GoToDefinitionTests.Catalog.WithPart(GetType(CSharpGoToDefinitionService))))

                Dim baseDocument = workspace.Documents.First(Function(d) Not d.IsLinkFile)
                Dim linkDocument = workspace.Documents.First(Function(d) d.IsLinkFile)
                Dim view = baseDocument.GetTextView()

                Dim mockDocumentNavigationService =
                    DirectCast(workspace.Services.GetService(Of IDocumentNavigationService)(), MockDocumentNavigationService)

                Dim commandHandler = New GoToDefinitionCommandHandler(New TestWaitIndicator(New TestWaitContext(100)))
                commandHandler.TryExecuteCommand(view.TextSnapshot, baseDocument.CursorPosition.Value)
                Assert.True(mockDocumentNavigationService._triedNavigationToSpan)
                Assert.Equal(New TextSpan(78, 2), mockDocumentNavigationService._span)

                workspace.SetDocumentContext(linkDocument.Id)

                commandHandler.TryExecuteCommand(view.TextSnapshot, baseDocument.CursorPosition.Value)
                Assert.True(mockDocumentNavigationService._triedNavigationToSpan)
                Assert.Equal(New TextSpan(121, 2), mockDocumentNavigationService._span)
            End Using
        End Sub

        Private Function Cancel(updatesBeforeCancel As Integer, expectedCancel As Boolean) As Integer
            Dim definition =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
            class [|C|] { $$C c; }"
        </Document>
    </Project>
</Workspace>

            Using workspace = TestWorkspaceFactory.CreateWorkspace(definition, exportProvider:=GoToDefinitionTests.ExportProvider)
                Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
                Dim cursorPosition = cursorDocument.CursorPosition.Value

                Dim mockDocumentNavigationService = DirectCast(workspace.Services.GetService(Of IDocumentNavigationService)(), MockDocumentNavigationService)

                Dim navigatedTo = False
                Dim presenter = New MockNavigableItemsPresenter(Sub(i) navigatedTo = True)
                Dim presenters = {New Lazy(Of INavigableItemsPresenter)(Function() presenter)}

                Dim cursorBuffer = cursorDocument.TextBuffer
                Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)

                Dim goToDefService = New CSharpGoToDefinitionService(presenters)

                Dim waitContext = New TestWaitContext(updatesBeforeCancel)
                Dim waitIndicator = New TestWaitIndicator(waitContext)
                Dim commandHandler = New GoToDefinitionCommandHandler(waitIndicator)

                commandHandler.TryExecuteCommand(document, cursorPosition, goToDefService)

                Assert.Equal(navigatedTo OrElse mockDocumentNavigationService._triedNavigationToSpan, Not expectedCancel)

                Return waitContext.Updates
            End Using
        End Function
    End Class
End Namespace


text:
package de.chrlembeck.codegen.gui.datamodel;

import java.util.Enumeration;

import javax.swing.tree.TreeNode;

import org.jdesktop.swingx.treetable.TreeTableNode;

import de.chrlembeck.util.collections.ArrayEnumeration;

public class ModelTreeTableNode implements TreeTableNode {

    private ModelTreeNodeUtil helper;

    private TreeTableNode[] children;

    private String name;

    private TreeTableNode parent;

    private Class<?> type;

    private Object userObject;

    public ModelTreeTableNode(final ModelTreeTableNode parent, final String name, final Class<?> type,
            final Object userObject) {
        this.parent = parent;
        this.helper = parent == null ? null : parent.helper;
        this.name = name;
        this.type = type;
        this.userObject = userObject;
    }

    public void setHelper(final ModelTreeNodeUtil helper) {
        this.helper = helper;
    }

    @Override
    public Enumeration<? extends TreeTableNode> children() {
        lazyInit();
        return new ArrayEnumeration<>(children);
    }

    @Override
    public boolean getAllowsChildren() {
        return helper.allowsChildren(userObject);
    }

    @Override
    public TreeTableNode getChildAt(final int childIndex) {
        lazyInit();
        return children[childIndex];
    }

    @Override
    public int getChildCount() {
        lazyInit();
        return children.length;
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public int getIndex(final TreeNode node) {
        lazyInit();
        for (int i = 0; i < children.length; i++) {
            if (children[i] == node) {
                return i;
            }
        }
        return -1;
    }

    public String getName() {
        return name;
    }

    @Override
    public TreeTableNode getParent() {
        return parent;
    }

    public Class<?> getType() {
        return type;
    }

    @Override
    public Object getUserObject() {
        return userObject;
    }

    @Override
    public Object getValueAt(final int column) {
        switch (column) {
            case 0:
                return name;
            case 1:
                return helper.getVisibleTypeName(type, userObject == null ? null : userObject.getClass());
            case 2:
                return helper.toVisibleString(userObject);
            default:
                return null;
        }
    }

    @Override
    public boolean isEditable(final int column) {
        return false;
    }

    @Override
    public boolean isLeaf() {
        lazyInit();
        return children.length == 0;
    }

    private void lazyInit() {
        if (children == null) {
            children = helper.getChildren(this);
        }
    }

    @Override
    public void setUserObject(final Object userObject) {
        this.userObject = userObject;
    }

    @Override
    public void setValueAt(final Object aValue, final int column) {
    }
}


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

import java.util.List;

import com.google.common.base.Splitter;
import com.google.common.io.BaseEncoding;

import org.apache.shiro.authc.AuthenticationToken;

import static java.util.Objects.requireNonNull;

/**
 * Parser for the unsanitized input data from the client WWW-Authenticate header. See RFC 4559.
 */
class AuthorizeHeaderToken implements AuthenticationToken {
  private final byte[] authorizeHeaderValue;

  private static final Splitter SPLITTER = Splitter.on(" ");
  private static final BaseEncoding BASE64 = BaseEncoding.base64();

  AuthorizeHeaderToken(String authorizeHeaderValue) throws IllegalArgumentException {
    requireNonNull(authorizeHeaderValue);
    List<String> parts = SPLITTER.splitToList(authorizeHeaderValue);
    if (parts.size() != 2 || !ShiroKerberosAuthenticationFilter.NEGOTIATE.equals(parts.get(0))) {
      throw new IllegalArgumentException("Malformed Authorize header: " + authorizeHeaderValue);
    }

    this.authorizeHeaderValue = BASE64.decode(parts.get(1));
  }

  @Override
  public Object getPrincipal() {
    // We don't know the principal that we're attempting to authenticate as until we've actually
    // succeeded - this data is encapsulated in the credentials we pass to GssManager.
    return null;
  }

  /**
   * Required by the API, but in-package consumers should use the type-safe
   * {@link #getAuthorizeHeaderValue} method instead.
   */
  @Override
  public Object getCredentials() {
    return getAuthorizeHeaderValue();
  }

  /**
   * The decoded value of the {@code Authorize} header.
   */
  byte[] getAuthorizeHeaderValue() {
    return authorizeHeaderValue;
  }
}


text:
package org.quartz.impl.jdbcjobstore;

import java.sql.Connection;

/**
 * An interface for providing thread/resource locking in order to protect
 * resources from being altered by multiple threads at the same time.
 *
 * @author jhouse
 */
public interface Semaphore {

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Interface.
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    /**
     * Grants a lock on the identified resource to the calling thread (blocking
     * until it is available).
     *
     * @param conn Database connection used to establish lock.  Can be null if
     * {@link #requiresConnection()} returns false.
     *
     * @return true if the lock was obtained.
     */
    boolean obtainLock(Connection conn, String lockName) throws LockException;

    /**
     * Release the lock on the identified resource if it is held by the calling
     * thread.

     * @param conn Database connection used to establish lock.  Can be null if
     * {@link #requiresConnection()} returns false.
     */
    void releaseLock(Connection conn, String lockName) throws LockException;

    /**
     * Determine whether the calling thread owns a lock on the identified
     * resource.

     * @param conn Database connection used to establish lock.  Can be null if
     * {@link #requiresConnection()} returns false.
     */
    boolean isLockOwner(Connection conn, String lockName) throws LockException;

    /**
     * Whether this Semaphore implementation requires a database connection for
     * its lock management operations.
     *
     * @see #isLockOwner(Connection, String)
     * @see #obtainLock(Connection, String)
     * @see #releaseLock(Connection, String)
     */
    boolean requiresConnection();
}


text:
import flatMap from "lodash/flatMap";
import uniqBy from "lodash/uniqBy";
import { Field, ObjectType } from "type-graphql";
import { Conference } from "./Conference";
import { Image } from "./Image";
import Keyword from "./keywords";
import { Location } from "./Location";
import { resolveSessions } from "./Schedule";
import { Session, SessionType } from "./Session";
import { Social } from "./Social";

export enum ContactType {
  PRESS = "PRESS",
  SPEAKER = "SPEAKER",
  TALK = "TALK",
  LIGHTNING_TALK = "LIGHTNING_TALK",
  KEYNOTE = "KEYNOTE",
  WORKSHOP = "WORKSHOP",
  WORKSHOP_HOST = "WORKSHOP_HOST",
  ORGANIZER = "ORGANIZER",
  SPONSOR = "SPONSOR",
  GOLD_SPONSOR = "GOLD_SPONSOR",
  SILVER_SPONSOR = "SILVER_SPONSOR",
  BRONZE_SPONSOR = "BRONZE_SPONSOR",
  PLATFORM_SPONSOR = "PLATFORM_SPONSOR",
  PARTNER = "PARTNER",
  ATTENDEE = "ATTENDEE",
}

@ObjectType()
export class Contact {
  // Needed for badges
  @Field((_) => String)
  public firstName?: string;

  // Needed for badges
  @Field((_) => String)
  public lastName?: string;

  // Combine with first/lastName somehow? Problematic for companies.
  @Field((_) => String)
  public name!: string;

  @Field((_) => String)
  public about!: string;

  @Field((_) => String, { nullable: true })
  public aboutShort?: string;

  // TODO: This might become a Contact reference eventually
  @Field((_) => String, { nullable: true })
  public company?: string;

  @Field((_) => Image)
  public image!: Image;

  @Field((_) => [ContactType])
  public type!: ContactType[];

  @Field((_) => Social)
  public social!: Social;

  @Field((_) => [String], { nullable: true })
  public keywords?: Keyword[];

  @Field((_) => Location)
  public location!: Location;

  @Field((_) => [Session], { nullable: true })
  public talks?: Session[];

  @Field((_) => [Session], { nullable: true })
  public workshops?: Session[];

  @Field((_) => Boolean, { nullable: true })
  public noPhotography?: boolean;
}

// TODO: Maybe this should become a static method of Conference
export function getSessionSpeakers(
  conference: Conference,
  sessions?: Session[]
): Contact[] {
  const talks = resolveSessions(conference.schedules, [
    SessionType.LIGHTNING_TALK,
    SessionType.TALK,
    SessionType.KEYNOTE,
  ]);
  const workshops = resolveSessions(conference.schedules, [
    SessionType.WORKSHOP,
  ]);
  const speakers = uniqBy(
    flatMap(sessions, (session) =>
      (session.people || []).concat(
        session.sessions
          ? flatMap(session.sessions, (session) => session.people || [])
          : []
      )
    ),
    "name"
  );

  return speakers.map((speaker) => ({
    ...speaker,
    talks: talks
      ? talks.filter(
          ({ people }) =>
            people && people.find((person) => person.name === speaker.name)
        )
      : [],
    workshops: workshops
      ? workshops.filter(
          ({ people }) =>
            people && people.find((person) => person.name === speaker.name)
        )
      : [],
  }));
}


text:
package org.apache.camel.component.mail;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.jvnet.mock_javamail.Mailbox;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * Unit test for a special corner case with fetchSize=0
 */
public class MailFetchSizeZeroTest extends CamelTestSupport {

    @Override
    public void setUp() throws Exception {
        prepareMailbox();
        super.setUp();
    }

    @Test
    public void testFetchSize() throws Exception {
        Mailbox mailbox = Mailbox.get("bill@localhost");
        assertEquals(5, mailbox.size());

        MockEndpoint mock = getMockEndpoint("mock:result");
        // no messages expected as we have a fetch size of zero
        mock.expectedMessageCount(0);
        // should be done within 2 seconds as no delay when started
        mock.setResultWaitTime(2000L);
        mock.assertIsSatisfied();

        assertEquals(5, mailbox.size());
    }

    private void prepareMailbox() throws Exception {
        // connect to mailbox
        Mailbox.clearAll();
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        Store store = sender.getSession().getStore("pop3");
        store.connect("localhost", 25, "bill", "secret");
        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        folder.expunge();

        // inserts 5 new messages
        Message[] messages = new Message[5];
        for (int i = 0; i < 5; i++) {
            messages[i] = new MimeMessage(sender.getSession());
            messages[i].setText("Message " + i);
        }
        folder.appendMessages(messages);
        folder.close(true);
    }

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("pop3://bill@localhost?password=secret&fetchSize=0&consumer.delay=1000").to("mock:result");
            }
        };
    }

}


text:
<!DOCTYPE html>

<meta charset=utf-8 />
<title></title>

  <link href='http://api.tiles.mapbox.com/mapbox.js/v1.6.1/mapbox.css' rel='stylesheet' />

<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-fullscreen/v0.0.2/leaflet.fullscreen.css' rel='stylesheet' />

INCENDIOS EN VALPARAÍSO 1998-2010

                Para navegar activa las capas y para mayor información haz click sobre los puntos.

Estos puntos indican los incendios registrados por CONAF entre los años 1998 al 2010 en la ciudad de Valparaíso, además de información específica sobre cada uno de ellos.

El tamaño del punto señala la magnitud del incendio en relación al área afectada.


text:
using System;
using System.Net;

namespace m.Http.Backend
{
    class RequestException : Exception
    {
        public readonly HttpStatusCode HttpStatusCode;

        public RequestException(string msg, HttpStatusCode statusCode) :base(msg)
        {
            HttpStatusCode = statusCode;
        }

        public RequestException(string msg, Exception innerException, HttpStatusCode statusCode) : base(msg, innerException)
        {
            HttpStatusCode = statusCode;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
Copyright (C) 2015 brayanarias.com ing.brayanarias@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.brayanarias.alarmproject">

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.android.alarm.permission.SET_ALARM" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activity.MainActivity"
            android:label="@string/title_activity_main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.AddAlarmActivity"
            android:label="@string/title_activity_add_alarm"></activity>
        <activity
            android:name=".activity.AlarmScreenActivity"
            android:excludeFromRecents="true"
            android:label="@string/title_activity_alarm_screen"
            android:screenOrientation="portrait"></activity>

        <service
            android:name=".service.AlarmService"
            android:enabled="true" />
        <service
            android:name=".service.NotificationService"
            android:enabled="true" />

        <receiver android:name=".receiver.AlarmReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity
            android:name=".activity.SetAlarmActivity"
            android:excludeFromRecents="true"
            android:permission="com.android.alarm.permission.SET_ALARM"
            android:theme="@android:style/Theme.NoDisplay">
            <intent-filter>
                <action android:name="android.intent.action.SET_ALARM" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package com.fasterxml.jackson.datatype.jsr310;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectReader;
import org.junit.Test;

import java.io.IOException;
import java.time.OffsetTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

public class TestOffsetTimeDeserialization extends ModuleTestBase
{
    private final ObjectReader READER = newMapper().readerFor(OffsetTime.class);

    @Test
    public void testDeserializationAsString01() throws Exception
    {
        expectSuccess(OffsetTime.of(12, 0, 0, 0, ZoneOffset.UTC), "'12:00Z'");
    }

    @Test
    public void testBadDeserializationAsString01() throws Throwable
    {
        expectFailure("'notanoffsettime'");
    }

    private void expectFailure(String json) throws Throwable {
        try {
            read(json);
            fail("expected DateTimeParseException");
        } catch (JsonProcessingException e) {
            if (e.getCause() == null) {
                throw e;
            }
            if (!(e.getCause() instanceof DateTimeParseException)) {
                throw e.getCause();
            }
        } catch (IOException e) {
            throw e;
        }
    }

    private void expectSuccess(Object exp, String json) throws IOException {
        final OffsetTime value = read(json);
        notNull(value);
        expect(exp, value);
    }

    private OffsetTime read(final String json) throws IOException {
        return READER.readValue(aposToQuotes(json));
    }

    private static void notNull(Object value) {
        assertNotNull("The value should not be null.", value);
    }

    private static void expect(Object exp, Object value) {
        assertEquals("The value is not correct.", exp,  value);
    }
}


text:
Predicts the outcome of NFL games with regression models

By [Michael Greenberg](twitter.com/migreenberg), <migreenberg7@gmail.com>.

### Dependencies
* [NFLGame](https://github.com/BurntSushi/nflgame)
* [Scikit-learn](http://scikit-learn.org/stable/)
* [Numpy](http://www.numpy.org/)

### Running

Test statistical prediction quality:
```python
python -m scripts.prediction_quality
```

Test regression model quality:
```python
python -m scripts.learning_quality
```

Test suite quality:
```python
python -m scripts.suite_quality
```


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Database extends CI_Controller {

  public function index() {
  }
}


text:
FROM themattrix/tox-base

LABEL maintainer="Peter Bittner <peter@painless.software>"

RUN apt-get update \
 && apt-get install -y --no-install-recommends \
        ca-certificates \
        git \
        libmysqlclient-dev \
        libpq-dev \
        ssh \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN apt-get update \
 && apt-get install -y --no-install-recommends \
        php7.0-cli \
        php7.0-mbstring \
        composer \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Release 4.0: db_env_set_XXX</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Berkeley DB Programmer's Reference Guide" />
    <link rel="up" href="upgrade_4_0_toc.html" title="Chapter 37. Upgrading Berkeley DB 3.3 applications to Berkeley DB 4.0" />
    <link rel="prev" href="upgrade_4_0_txn.html" title="Release 4.0: txn_XXX" />
    <link rel="next" href="upgrade_4_0_rpc.html" title="Release 4.0: DB_ENV->set_server" />

          Release 4.0: db_env_set_XXX

          Prev
          Chapter 37. Upgrading Berkeley DB 3.3 applications to Berkeley DB 4.0
           Next

Release 4.0: db_env_set_XXX

The db_env_set_region_init function was removed in the 4.0 release and
replaced with the DB_REGION_INIT flag to the
DB_ENV->set_flags() method.  This is an interface change: historically,
the db_env_set_region_init function operated on the entire Berkeley DB
library, not a single environment.  The new method only operates on
a single DB_ENV class handle (and any handles created in the scope of
that handle).  Applications calling the db_env_set_region_init function
should update their calls: calls to the historic routine with an
argument of 1 (0) are equivalent to calling DB_ENV->set_flags() with
the DB_REGION_INIT flag and an argument of 1 (0).

The db_env_set_tas_spins function was removed in the 4.0 release and
replaced with the DB_ENV->set_tas_spins method.  This is an
interface change: historically, the db_env_set_tas_spins function
operated on the entire Berkeley DB library, not a single environment.  The new
method only operates on a single DB_ENV class handle (and any handles
created in the scope of that handle).  Applications calling the
db_env_set_tas_spins function should update their calls: calls to the
historic routine are equivalent to calling DB_ENV->set_tas_spins
with the same argument.  In addition, for consistent behavior, all
DB_ENV class handles opened by the application should make the same
configuration call, or the value will need to be entered into the
environment's DB_CONFIG configuration file.

Also, three of the standard Berkeley DB debugging interfaces changed in the
4.0 release.  It is quite unlikely that Berkeley DB applications use these
interfaces.

The DB_ENV->set_mutexlocks method was removed in the 4.0 release
and replaced with the DB_NO_LOCKING flag to the
DB_ENV->set_flags() method.  Applications calling the
DB_ENV->set_mutexlocks method should update their calls: calls
to the historic routine with an argument of 1 (0) are equivalent to
calling DB_NO_LOCKING flag and
an argument of 1 (0).

The db_env_set_pageyield function was removed in the 4.0 release and
replaced with the  DB_YIELDCPU  flag to the
DB_ENV->set_flags() method.  This is an interface change: historically,
the db_env_set_pageyield function operated on the entire Berkeley DB library,
not a single environment.  The new method only operates on a single
DB_ENV class handle (and any handles created in the scope of that
handle).  Applications calling the db_env_set_pageyield function should
update their calls: calls to the historic routine with an argument of 1
(0) are equivalent to calling DB_ENV->set_flags() with the
DB_YIELDCPU flag and an argument of 1 (0).  In addition, all
DB_ENV class handles opened by the application will need to make the
same call, or the DB_YIELDCPU flag will need to be entered into
the environment's DB_CONFIG configuration file.

The db_env_set_panicstate function was removed in the 4.0 release,
replaced with the DB_PANIC_ENVIRONMENT
flags to the DB_ENV->set_flags() method.  (The
DB_PANIC_ENVIRONMENT flag will cause an environment to panic,
affecting all threads of control using that environment.  The
DB_ENV->set_flags() handle to
ignore the current panic state of the environment.)   This is an
interface change: historically the db_env_set_panicstate function
operated on the entire Berkeley DB library, not a single environment.
Applications calling the db_env_set_panicstate function should update
their calls, replacing the historic call with a call to
DB_ENV->set_flags() and the appropriate flag, depending on their
usage of the historic interface.

          Prev

            Up

           Next

          Release 4.0: txn_XXX

            Home

           Release 4.0: DB_ENV->set_server


text:
namespace Cake.Core.Diagnostics
{
    /// <summary>
    /// A log that discards messages written to it.
    /// </summary>
    public sealed class NullLog : ICakeLog
    {
        /// <summary>
        /// Writes the text representation of the specified array of objects to the
        /// log using the specified verbosity, log level and format information.
        /// </summary>
        /// <param name="verbosity">The verbosity.</param>
        /// <param name="level">The log level.</param>
        /// <param name="format">A composite format string.</param>
        /// <param name="args">An array of objects to write using format.</param>
        public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args)
        {
        }
    }
}


text:
./bin/package.js
git add -u
npm version $1
git push --follow-tags origin master


text:
import React, { Component } from "react";
import { connect } from 'react-redux'
import { addTodo } from './../../redux/actions/actionTypes'

class SideBar extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (

Side Bar Component

    );
  }
}

export default SideBar


text:
/**
 *
Title: AddNewAction Class>
 *
Description:	This Class is used to maintain FormBean for AddNew operation

 * Copyright:    Copyright (c) year
 * Company: Washington University, School of Medicine, St. Louis.
 * @author Krunal Thakkar
 * @version 1.00
 * Created on Apr 12, 2006
 */

package edu.wustl.common.action;

import java.util.Stack;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import edu.wustl.common.actionForm.AbstractActionForm;
import edu.wustl.common.beans.AddNewSessionDataBean;
import edu.wustl.common.util.global.Constants;
import edu.wustl.common.util.logger.Logger;

/**
 * This Class is used to maintain FormBean for AddNew operation.
 * @author Krunal Thakkar
 */
public class AddNewAction extends Action
{
    /**
     * Overrides the execute method of Action class.
     * Maintains FormBean for AddNew operation.
     * */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            Logger.out.debug("-----------------------------AddNewAction-----------------------------");
            //Populating ADDNewSessionDataBean to store FormBean into Session and Path to redirect
	        AddNewSessionDataBean addNewSessionDataBean=new AddNewSessionDataBean();

	        //Storing FormBean into AddNewSessionDataBean
	        addNewSessionDataBean.setAbstractActionForm((AbstractActionForm)form);
	        Logger.out.debug("ActionForm in AddNewAction----"+form);

	        //Getting ForwardTo attribute from Request
	        String forwardTo=(String)request.getParameter(Constants.FORWARD_TO);

	        Logger.out.debug("forwardTo stored in AddNewSessionDataBean------>"+forwardTo);

	        //Storing forwardTo of InitializeAction into AddNewSessionDataBean
	        addNewSessionDataBean.setForwardTo(forwardTo);

	        Logger.out.debug("AddNewAction:::Forward To ------------"+addNewSessionDataBean.getForwardTo());

	        //Getting AddNewFor attribute from Request
	        String addNewFor =(String)request.getParameter(Constants.ADD_NEW_FOR);

	        //Storing addNewFor of InitializeAction into AddNewSessionDataBean
	        addNewSessionDataBean.setAddNewFor(addNewFor);

	        //Retrieving current Session
	        HttpSession session = request.getSession();

	        //Storing Stack of FormBean into Session
	        Stack formBeanStack=(Stack)session.getAttribute(Constants.FORM_BEAN_STACK);

	        if(formBeanStack ==null)
	        {
	            Logger.out.debug("Creating FormBeanStack in AddNewAction.......................");
	            formBeanStack=new Stack();
	        }

	        formBeanStack.push(addNewSessionDataBean);

	        session.setAttribute(Constants.FORM_BEAN_STACK, formBeanStack);

	        //Storing required Attributes into Request
	        request.setAttribute(Constants.SUBMITTED_FOR , "AddNew");

	        Logger.out.debug("ForwardTo attribute----------------"+request.getParameter(Constants.ADD_NEW_FORWARD_TO));

	        //Forwarding to ADD_NEW_FORWARD_TO Action
	    	return mapping.findForward((String)request.getParameter(Constants.ADD_NEW_FORWARD_TO));
        }
        catch(Exception e)
        {
            Logger.out.info("Exception: " + e.getMessage(), e);

            return mapping.findForward(Constants.SUCCESS);
        }
    }
}


text:
* Create a [Sonatype OSSRH JIRA account](https://issues.sonatype.org/secure/Signup!default.jspa).
* Create a ticket to request access to the `com.squareup.leakcanary` project. Here's an example: [OSSRH-54959](https://issues.sonatype.org/browse/OSSRH-54959).
* Then ask someone with deployer role from the LeakCanary team to confirm access.

### Set up your signing key

```bash
# Create a new key
gpg --gen-key
# List local keys. Key id is last 8 characters
gpg -K
cd ~/.gnupg
# Export key locally
gpg --export-secret-keys -o secring.gpg
# Upload key to Ubuntu servers
gpg --send-keys --keyserver keyserver.ubuntu.com <KEY ID>
# Confirm the key can now be found
gpg --recv-keys --keyserver keyserver.ubuntu.com <KEY ID>
```

### Set up your home gradle.properties

Add this to your `~/.gradle/gradle.properties`:

```
signing.keyId=<KEY ID>
signing.password=<KEY PASSWORD>
signing.secretKeyRingFile=/Users/YOUR_USERNAME_/.gnupg/secring.gpg
SONATYPE_NEXUS_USERNAME=<SONATYPE_USERNAME>
SONATYPE_NEXUS_PASSWORD=<SONATYPE_PASSWORD>
```

### Set up the Google Analytics docs key

Add this to your `~/.bashrc`:

```bash
export LEAKCANARY_GOOGLE_ANALYTICS_KEY="UA-142834539-1"
```

### Set up GitHub CLI

Install GitHub CLI

```bash
brew install gh
```

Install jq, a CLI Json processor

```bash
brew install jq
```

Set up aliases for milestone management:

```bash
gh alias set listOpenMilestones "api graphql -F owner=':owner' -F name=':repo' -f query='
    query ListOpenMilestones(\$name: String\!, \$owner: String\!) {
        repository(owner: \$owner, name: \$name) {
            milestones(first: 100, states: OPEN) {
                nodes {
                    title
                    number
                    description
                    dueOn
                    url
                    state
                    closed
                    closedAt
                    updatedAt
                }
            }
        }
    }
'"

gh alias set --shell createMilestone "gh api --method POST repos/:owner/:repo/milestones --input - | jq '{ html_url: .html_url, state: .state, created_at: .created_at }'"

gh alias set --shell closeMilestone "echo '{\"state\": \"closed\"}' | gh api --method PATCH repos/:owner/:repo/milestones/\$1 --input - | jq '{ html_url: .html_url, state: .state, closed_at: .closed_at }'"
```

### Install the doc generation dependencies

```bash
pip3 install mkdocs-material mkdocs-markdownextradata-plugin
```

## Releasing

* Create a local release branch from `main`
```bash
git checkout main && \
git pull && \
git checkout -b release_{{ leak_canary.next_release }}
```

* Update `VERSION_NAME` in `gradle.properties` (remove `-SNAPSHOT`)
```gradle
sed -i '' 's/VERSION_NAME={{ leak_canary.next_release }}-SNAPSHOT/VERSION_NAME={{ leak_canary.next_release }}/' gradle.properties
```

* Update the current version and next version in `mkdocs.yml`
```bash
sed -i '' 's/{{ leak_canary.next_release }}/NEXT/' mkdocs.yml
sed -i '' 's/{{ leak_canary.release }}/{{ leak_canary.next_release }}/' mkdocs.yml
```

* Create the release
```bash
git commit -am "Prepare {{ leak_canary.next_release }} release" && \
./gradlew clean && \
./gradlew build && \
git tag v{{ leak_canary.next_release }} && \
git push origin v{{ leak_canary.next_release }} && \
./gradlew publish --no-daemon --no-parallel && \
./gradlew closeAndReleaseRepository && \
./gradlew shark-cli:distZip
```

Note: if anything goes wrong, you can manually drop the release at https://s01.oss.sonatype.org/

* Merge back to main
```bash
git checkout main && \
git pull && \
git merge --no-ff release_{{ leak_canary.next_release }}
```
* Update `VERSION_NAME` in `gradle.properties` (increase version and add `-SNAPSHOT`)
```gradle
sed -i '' 's/VERSION_NAME={{ leak_canary.next_release }}/VERSION_NAME=NEXT-SNAPSHOT/' gradle.properties
```

* Generate the Dokka docs
```bash
rm -rf docs/api && \
./gradlew leakcanary-android-core:dokkaGfm leakcanary-android-instrumentation:dokkaGfm leakcanary-android-process:dokkaGfm leakcanary-object-watcher-android-core:dokkaGfm leakcanary-object-watcher:dokkaGfm shark-android:dokkaGfm shark-graph:dokkaGfm shark-hprof:dokkaGfm shark-log:dokkaGfm shark:dokkaGfm plumber-android:dokkaGfm leakcanary-android-release:dokkaGfm
```

* Update the changelog ([commit list](https://github.com/square/leakcanary/compare/v{{ leak_canary.release }}...main))
```
mate docs/changelog.md
```

* Deploy the docs locally then [open the changelog](http://127.0.0.1:8000/leakcanary/changelog/) and check everything looks good
```bash
mkdocs serve
```

* Finish up the release

```bash
git commit -am "Prepare for next development iteration" && \
git push && \
gh listOpenMilestones | jq '.data.repository.milestones.nodes[0].number' | xargs gh closeMilestone && \
echo '{
  "title": "REPLACE_WITH_NEXT_VERSION_NUMBER",
  "state": "open",
  "description": ""
}' | gh createMilestone && \
mkdocs gh-deploy
gh release create v{{ leak_canary.next_release }} ./shark-cli/build/distributions/shark-cli-{{ leak_canary.next_release }}.zip --title v{{ leak_canary.next_release }} --notes 'See [Change Log](https://square.github.io/leakcanary/changelog)'
```

* Open the [v{{ leak_canary.next_release }} release](https://github.com/square/leakcanary/releases/tag/v{{ leak_canary.next_release }}) to confirm everything looks good.

* Upload shark-cli to [brew](https://brew.sh/):
```bash
brew bump-formula-pr --url https://github.com/square/leakcanary/releases/download/v{{ leak_canary.next_release }}/shark-cli-{{ leak_canary.next_release }}.zip leakcanary-shark
```

* Wait for the release to be available [on Maven Central](https://repo1.maven.org/maven2/com/squareup/leakcanary/leakcanary-android/).
* Tell your friends, update all of your apps, and tweet the new release. As a nice extra touch, mention external contributions.


text:
<!-- metadata -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.title }}</title>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/css/custom.css" rel="stylesheet">

<link rel="icon" href="/favicon.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

{% assign author = site.owner %}


text:
var server = require("./server.js")
  , router = require("./router.js")
  , requestHandlers = require('./request-handlers.js');

var handle = {};
handle["/"] = requestHandlers.start
handle["/start"] = requestHandlers.start
handle["/upload"] = requestHandlers.upload
handle["/show"] = requestHandlers.show

server.start(router.route, handle);


text:
[![Hex.pm](https://img.shields.io/hexpm/l/plug.svg)](https://github.com/grzesuav/gjpf-core/blob/master/LICENSE-2.0.txt)
[![Build Status](https://travis-ci.org/grzesuav/gjpf-core.svg?branch=master)](https://travis-ci.org/grzesuav/gjpf-core)
[![Coverage Status](https://coveralls.io/repos/grzesuav/gjpf-core/badge.svg?branch=master)](https://coveralls.io/r/grzesuav/gjpf-core)
[![HuBoard badge](http://img.shields.io/badge/Hu-Board-7965cc.svg)](https://huboard.com/grzesuav/gjpf-core)
[![Join the chat at https://gitter.im/grzesuav/gjpf-core](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/grzesuav/gjpf-core?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[![codecov.io](https://codecov.io/github/grzesuav/gjpf-core/coverage.svg?branch=master)](https://codecov.io/github/grzesuav/gjpf-core?branch=master)
[![Codacy Badge](https://api.codacy.com/project/badge/grade/4aefa07697fe442c9bc9a2bb39e109ea)](https://www.codacy.com/app/grzesuav/gjpf-core)

This is fork of Java Path Finder project (which is one-to-one mirrored [here](https://github.com/grzesuav/jpf-core)).

Main reasons/motivation:
* desire to contribute in some OS project
* experiment with new language features/libraries
* maybe contribute some changes to original JPF.

Currently:
* setup of Travis CI build was configured
* develop branch was created
* coverity-scan branch was created and coverity static analysis scan was attached (see branch coverity-scan to see results)
* coveralls.io was configured, coverage result are reported on badge
* gradle is almost done, need to finalize work
* documentation was modified, so now its fully navigable from github, click [here](doc/index.md)
* merged latest Peter changes from babelfish repo (up to 25. commit, from 22 april 15)
* **(in progress)** preparing example maven/distribution repo on bintray as POC for gradle build

#Gradle project layout
It was difficult to balance between old layout, which is required by program way of work (directory layout, files location etc.).
Main change is project modularization, which reflects present of multiple source directories in ant structure. I have temporarily removed
some IDE-related directories (netbeans and eclipse) to keep basic layout simpler, need to consider in which form restore them.
## Build
In project Gradle wrapper in version 3.1 is used. You do not need to install it by yourself, Gradle will be install via wrapper.
To check which tasks are accessible type './gradlew tasks' in root project directory (where 'build.gradle' and 'setting.gradle' are placed).
To build project type `./gradlew build` or `./gradlew clean build`, it will:
* clean (in case when this target was called)
* compile each module, examples and tests
* make jars necessary to properly run tests
* test project with coverage (reports are located in build/reports)
* make distribution packages (tar and zip) placed in build/

Distribution packages are identical as ant-make dist package.

## Repository artifact
This is main goal of gradle-switch. After typing `gradle install` each of submodule will be deployed in local maven repository and accessible from it.
In other words, if you have some maven/gradle/other project managed by any dependency management system, you can refer to this modules by:
* `GroupId:artifactId:version` (actual format depends on build system)

Group id is :
* `gov.nas.jpf.jpf-core`

artifacts id's are :
* `annotations`
* `classes`
* `main`
* `peers`

Current version is set to _`0.1`_.
So, if you want to use annotations module, here is maven example:
```
    <dependency>
        <groupId>gov.nasa.jpf.jpf-core</groupId>
        <artifactId>annotations</artifactId>
        <version>0.1</version>
    </dependency>
```
In future probably release artifacts will be deployed on public maven repo (or something similar), so in order to write extension/software depending
on jpf, there will be no reason to download and build jpf manually (well, except that run it, of course).

## Importing to eclipse

**Prerequisites**
 * Gradle eclipse plugin : http://marketplace.eclipse.org/content/gradle-integration-eclipse-44
 * EGit : http://eclipse.org/egit/

At first, you need a local copy of this repo, which can be obtained :
* from command line : `git clone https://github.com/grzesuav/gjpf-core.git`
* import using eclipse wizard

*Importing using eclipse import wizard*:
* select `File -> Import -> Git -> Project from Git` and click next
* select `Create from uri` and click next
* paste into `URI`: `https://github.com/grzesuav/gjpf-core.git` and click next
* select at least `develop` branch and click next
* select desired location and click next
* wait until repository will be cloned and don't import any project, quit wizard

*Importing Gradle project to eclipse using `Gradle import wizard`* :
* select `File -> Import -> Gradle -> Gradle Project` and click next
* point to location where repository was cloned (also include `gjpf-core` directory) and click `Build Model`
* select all project visible in tree and click finish (leave all options as is)
* wait until project will be imported (could take a while)
* unfortunately, default eclipse output folder (for compiled classes and other resources) is $PROJECT_DIR/bin, which conflicts with jpf project layout. To change it, for every project (*besides root* `gjpf-core`) do the following : Right click on project name, select `Properties -> Java Build Path`, go into `Source` tab, and on the bottom there is `Default output folder`. Change it to $PROJECT_DIR/build.
* for root project `gjpf-core` eclipse project layout must be changed to fit jpf structure. To do it, right click on project name, select `Properties -> Java Build Path`, go into `Source` tab, and on the bottom there is `Default output folder`. As `Default output folder` set `build/default`. Next select checkbox  `Allow output folders for source folders` and for source folders above change `Output folder` (expand each source folder to see this) to `build/examples` and `build/tests`respectively.
* problem regarding non-existing test dependency (`RunJPF.jar`) will be resolved by building this jar, to do this, right click on project `gjpf-core` and select `Gradle -> Tasks Quick Launcher` and type `test`. It will build all required jars ad run tests.

## To be done
* discuss with jpf developers project layout/get some feedback
* put info about importing project to eclipse (and ask what IDEs developers are using)


text:
<!DOCTYPE html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<link rel="stylesheet" href="../../resources/empty.css" integrity="sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU= sha512-z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg==">
<script>
test(function() { assert_true(true); }, "Should not crash on empty response.");
</script>