text:
import mock
import mongomock

# DO NOT import KarmaPlugin directly -- it will import helga.db,
# and attempt to connect to MongoDB.
#from helga_karma.plugin import KarmaPlugin

class TestKarmaPlugin(object):

    def setup(self):
        from _pytest.monkeypatch import monkeypatch
        patch = monkeypatch()
        patch.setattr('pymongo.MongoClient', mongomock.MongoClient)

        from helga_karma import plugin
        self.plugin = plugin

    def test_give_handles_arrogance(self):
        ret = self.plugin.give('foo', ['foo'])
        assert ret == "Uhh, do you want a gold star, foo?"

    def test_give(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            from_user = mock.Mock()
            to_user = mock.Mock()
            db.get_for_nick.side_effect = [from_user, to_user]

            self.plugin.give('foo', ['bar'])

            from_user.give_karma_to.assert_called_with(to_user)

    def test_top(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            getitem = lambda s, k: getattr(s, k)
            users = [
                mock.Mock(nick='foo', get_value=lambda: 1, __getitem__=getitem),
                mock.Mock(nick='bar', get_value=lambda: 2, __getitem__=getitem),
                mock.Mock(nick='baz', get_value=lambda: 3, __getitem__=getitem),
            ]
            db.get_top.return_value = users
            ret = self.plugin.top()

            assert ret[0] == '#1: foo (1.0 karma)'
            assert ret[1] == '#2: bar (2.0 karma)'
            assert ret[2] == '#3: baz (3.0 karma)'

    def test_info_no_previous_karma(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            record = mock.Mock()
            record.get_value.return_value = None
            db.get_for_nick.return_value = record

            retval = self.plugin.info('me', 'foo')
            assert retval == "I'm not aware of foo having done anything helpful, me."

    def test_info_detailed(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            record = mock.Mock(nick='foo', given=1, received=2)
            record.__getitem__ = lambda s, k: getattr(s, k)
            record.get_value.return_value = 3
            record.get_coefficient.return_value = 4
            record.get_aliases.return_value = ['bar', 'baz']
            db.get_for_nick.return_value = record

            retval = self.plugin.info('me', 'foo', detailed=True)
            expected = ('foo has 3.0 karma. (thanked others 1 times, '
                        'received thanks 2 times, karma coefficient 4.0, '
                        'aliases: bar, baz)')
            assert retval == expected

    def test_info(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            record = mock.Mock()
            record.get_value.return_value = 1
            db.get_for_nick.return_value = record

            retval = self.plugin.info('me', 'foo')
            expected = 'foo has about 1 karma, me.'
            assert retval == expected

    def test_alias_nope_with_same_nick(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            db.get_for_nick.side_effect = [
                {'nick': 'foo'},
                {'nick': 'foo'},
            ]

            retval = self.plugin.alias('me', 'foo', 'foo')
            assert retval == "That doesn't make much sense now, does it, me."

    def test_alias_prefers_user_with_highest_value(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            user1 = mock.Mock(nick='foo', value=1)
            user2 = mock.Mock(nick='bar', value=5)

            getter = lambda s, k: getattr(s, k)
            user1.__getitem__ = getter
            user2.__getitem__ = getter

            db.get_for_nick.side_effect = [user1, user2]

            self.plugin.alias('me', 'foo', 'bar')
            user2.add_alias.assert_called_with(user1)

    def test_alias(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            user1 = mock.Mock(nick='foo', value=1)
            user2 = mock.Mock(nick='bar', value=1)

            getter = lambda s, k: getattr(s, k)
            user1.__getitem__ = getter
            user2.__getitem__ = getter

            db.get_for_nick.side_effect = [user1, user2]

            self.plugin.alias('me', 'foo', 'bar')
            user1.add_alias.assert_called_with(user2)

    def test_unalias_nope_with_same_nick(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            db.get_for_nick.side_effect = [
                {'nick': 'foo'},
                {'nick': 'foo'},
            ]

            retval = self.plugin.unalias('me', 'foo', 'foo')
            assert retval == "That doesn't make much sense now, does it, me."

    def test_unalias_no_records(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            db.get_for_nick.side_effect = [None, None]
            retval = self.plugin.unalias('me', 'foo', 'bar')
            assert retval == "Neither of the users you specified appear to exist, me."

    def test_unalias_non_linked_users(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            user1 = mock.Mock()
            user2 = mock.Mock()

            user2.get_aliases.return_value = ['bar']

            db.get_for_nick.side_effect = [user1, user2]

            retval = self.plugin.unalias('me', 'foo', 'bar')
            assert retval == "foo and bar are not linked."

    def test_unalias(self):
        with mock.patch.object(self.plugin, 'KarmaRecord') as db:
            user2 = mock.Mock()

            user2.get_aliases.return_value = ['bar']

            db.get_for_nick.side_effect = [None, user2]

            self.plugin.unalias(requested_by='me', nick1='bar', nick2='foo')

            user2.remove_alias.assert_called_with('bar')

    @mock.patch('helga_karma.plugin.settings')
    def test_message_not_overridden(self, settings):
        overridden_message = 'info_standard'
        not_overridden_message = 'linked'

        settings.KARMA_MESSAGE_OVERRIDES = {
            overridden_message: "Arbitrary Message"
        }
        from helga_karma.plugin import format_message, MESSAGES

        kwargs = {'main': 'foo', 'secondary': 'bar'}

        result = format_message(not_overridden_message, **kwargs)
        expected = MESSAGES[not_overridden_message].format(**kwargs)

        assert result == expected

    @mock.patch('helga_karma.plugin.settings')
    def test_message_karma_overridden(self, settings):
        overridden_message = 'info_standard'

        settings.KARMA_MESSAGE_OVERRIDES = {
            overridden_message: "Arbitrary Message"
        }
        from helga_karma.plugin import format_message

        result = format_message(overridden_message)
        expected = settings.KARMA_MESSAGE_OVERRIDES[overridden_message]
        assert result == expected

    def test_autokarma_match(self):
        matcher = self.plugin._autokarma_match

        assert ['helga'] == matcher('thanks, helga')
        assert ['helga'] == matcher('TYVM helga!')
        assert ['helga'] == matcher('ty helga. i needed that reminder')

        assert not matcher('i appreciate it helga')

class TestPlusPlusSupport(TestKarmaPlugin):

    def test_autokarma_match_nick_alone(self):
        matcher = self.plugin._autokarma_match
        assert ['helga++'] == matcher('helga++')

    def test_autokarma_match_nick_leading_whitespace(self):
        matcher = self.plugin._autokarma_match
        assert ['helga++'] == matcher(' helga++')

    def test_autokarma_match_leading_text_matches(self):
        matcher = self.plugin._autokarma_match
        assert ['helga++'] == matcher('you are doing great helga++')

    def test_autokarma_match_trailing_text_matches(self):
        matcher = self.plugin._autokarma_match
        assert ['helga++'] == matcher('you are doing great helga++ fantastic job there')

    def test_autokarma_match_trailing_comma_matches(self):
        matcher = self.plugin._autokarma_match
        assert ['helga++'] == matcher('helga++, way to go')

    def test_autokarma_no_match_trailing_garbage(self):
        matcher = self.plugin._autokarma_match
        assert matcher('helga++burrrr') == []

    def test_autokarma_no_match_cpp(self):
        matcher = self.plugin._autokarma_match
        assert matcher('I love programming in C++') == []

    def test_autokarma_multiple_matches(self):
        matcher = self.plugin._autokarma_match
        result = matcher('go team helga++ andrewschoen++ yuriw++')
        assert 'helga++' == result[0]
        assert 'andrewschoen++' == result[1]
        assert 'yuriw++' == result[2]

class TestInvalidWords(TestKarmaPlugin):
    # if py.test fixtures get used, they should be in place for these
    # tests to get all combinations of `thanks` that the plugin supports
    def test_default_for_does_not_match(self):
        matcher = self.plugin._autokarma_match
        assert matcher('thanks for helping out') is None

    def test_default_i_does_not_match(self):
        matcher = self.plugin._autokarma_match
        assert matcher('thanks I was able to fix it') is None


text:
<component name="ArtifactManager">
  <artifact type="exploded-war" name="Spring:war exploded">
    <output-path>$PROJECT_DIR$/Spring/target/aa</output-path>
    <root id="root">
      <element id="directory" name="WEB-INF">
        <element id="directory" name="classes">
          <element id="module-output" name="Spring" />
        </element>
        <element id="directory" name="lib">
          <element id="library" level="project" name="Maven: org.springframework:spring-core:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: commons-logging:commons-logging:1.1.3" />
          <element id="library" level="project" name="Maven: org.springframework:spring-web:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-beans:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-context:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-webmvc:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-expression:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-oxm:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-tx:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-jdbc:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-aop:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: aopalliance:aopalliance:1.0" />
          <element id="library" level="project" name="Maven: org.springframework:spring-context-support:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: org.mybatis:mybatis:3.2.6" />
          <element id="library" level="project" name="Maven: org.mybatis:mybatis-spring:1.2.2" />
          <element id="library" level="project" name="Maven: org.slf4j:slf4j-api:1.7.7" />
          <element id="library" level="project" name="Maven: org.slf4j:slf4j-log4j12:1.7.7" />
          <element id="library" level="project" name="Maven: javax.servlet:javax.servlet-api:3.0.1" />
          <element id="library" level="project" name="Maven: commons-io:commons-io:2.4" />
          <element id="library" level="project" name="Maven: org.springframework:spring-test:4.0.2.RELEASE" />
          <element id="library" level="project" name="Maven: log4j:log4j:1.2.17" />
          <element id="library" level="project" name="Maven: com.alibaba:fastjson:1.1.41" />
          <element id="library" level="project" name="Maven: com.google.guava:guava:11.0.2" />
          <element id="library" level="project" name="Maven: com.google.code.findbugs:jsr305:1.3.9" />
          <element id="library" level="project" name="Maven: joda-time:joda-time:2.2" />
          <element id="library" level="project" name="Maven: mysql:mysql-connector-java:5.1.26" />
          <element id="library" level="project" name="Maven: cglib:cglib:2.2" />
          <element id="library" level="project" name="Maven: asm:asm:3.1" />
          <element id="library" level="project" name="Maven: com.mchange:c3p0:0.9.5-pre6" />
          <element id="library" level="project" name="Maven: com.mchange:mchange-commons-java:0.2.6.3" />
          <element id="library" level="project" name="Maven: com.googlecode.xmemcached:xmemcached:1.3.1" />
          <element id="library" level="project" name="Maven: redis.clients:jedis:2.5.1" />
          <element id="library" level="project" name="Maven: org.apache.commons:commons-pool2:2.0" />
          <element id="library" level="project" name="Maven: org.apache.commons:commons-lang3:3.1" />
          <element id="library" level="project" name="Maven: org.opensymphony.quartz:quartz:1.6.1" />
          <element id="library" level="project" name="Maven: javax.mail:mail:1.4.3" />
          <element id="library" level="project" name="Maven: javax.activation:activation:1.1" />
          <element id="library" level="project" name="Maven: net.sf.json-lib:json-lib:jdk15:2.4" />
          <element id="library" level="project" name="Maven: commons-beanutils:commons-beanutils:1.8.0" />
          <element id="library" level="project" name="Maven: commons-collections:commons-collections:3.2.1" />
          <element id="library" level="project" name="Maven: commons-lang:commons-lang:2.5" />
          <element id="library" level="project" name="Maven: net.sf.ezmorph:ezmorph:1.0.6" />
          <element id="library" level="project" name="Maven: org.aspectj:aspectjtools:1.6.10" />
          <element id="library" level="project" name="Maven: org.aspectj:aspectjweaver:1.7.3" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.2.1" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.2.1" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-core:2.2.1" />
          <element id="library" level="project" name="Maven: org.codehaus.jackson:jackson-core-asl:1.9.10" />
          <element id="library" level="project" name="Maven: org.codehaus.jackson:jackson-jaxrs:1.9.10" />
          <element id="library" level="project" name="Maven: org.codehaus.jackson:jackson-mapper-asl:1.9.10" />
          <element id="library" level="project" name="Maven: com.typesafe:config:1.2.1" />
          <element id="library" level="project" name="Maven: org.apache.xmlbeans:xmlbeans:2.6.0" />
          <element id="library" level="project" name="Maven: stax:stax-api:1.0.1" />
          <element id="library" level="project" name="Maven: org.mybatis.generator:mybatis-generator-core:1.3.2" />
          <element id="library" level="project" name="Maven: jstl:jstl:1.2" />
          <element id="library" level="project" name="Maven: taglibs:standard:1.1.2" />
        </element>
      </element>
      <element id="directory" name="META-INF">
        <element id="file-copy" path="$PROJECT_DIR$/Spring/target/aa/META-INF/MANIFEST.MF" />
      </element>
      <element id="javaee-facet-resources" facet="Spring/web/Web" />
    </root>
  </artifact>
</component>

redpajama_set_name: RedPajamaGithub


text:
import djbdnslog, sys
from djbdnslog.scripts import check_args

def format_output(filename):
    for e in djbdnslog.parse_file(filename):
        print "%s  %-15s  %0d  %s  %14s  %-5s  %s" % e

def main(argv):
    # check command line args
    check_args(argv)
    format_output(argv[1])

if __name__ == '__main__':
    main(sys.argv)


text:
package controllers

import (
	"fmt"
	"strconv"

	"github.com/swfsql/estagio/models"
)

type EstagioController struct {
	AuthController
}

func (this *EstagioController) Get() {
	sess := this.StartSession()
	conta := sess.Get("conta").(models.Conta)

	estagio_id, _ := strconv.ParseUint(this.Ctx.Input.Param(":id"), 10, 64)
	fmt.Println("ENTROU NA PAGINA DO ESTAGIO")

	switch conta.Pessoa.Privilegio {
	case 2: // aluno
		aluno, _ := sess.Get("aluno").(models.Aluno)
		estagios, _ := sess.Get("estagios").([]*models.Estagio)

		estagioIndice := -1
		for i, e := range estagios {
			fmt.Println("Estagio id: ", e.Id)
			if estagio_id == e.Id {
				estagioIndice = i
				break
			}
		}
		if estagioIndice == -1 {
			this.Redirect("/", 302)
			return
		}
		estagio := estagios[estagioIndice]

		this.TplName = "estagio_aluno.html"
		this.Data["Aluno"] = aluno
		this.Data["Curso"] = aluno.Curso
		this.Data["Estagio"] = estagio
		break
	case 3, 4: // professor normal
		//professor, _ := sess.Get("professor").(models.Professor)
		estagios, _ := sess.Get("estagios").([]*models.Estagio)

		estagioIndice := -1

		for i, e := range estagios {
			if estagio_id == e.Id {
				estagioIndice = i
				break
			}
		}

		if estagioIndice == -1 {
			this.Redirect("/", 302)
			return
		}

		estagio := estagios[estagioIndice]

		this.TplName = "estagio_professor.html"
		//	this.Data["Professor"] = professor
		//	this.Data["Curso"] = professor.Curso
		this.Data["Estagio"] = estagio
		break

		/*	case 4: //professor coordenador
			break */

	case 5: // admin
		estagios, _ := models.GetEstagios()

		estagioIndice := -1

		for i, e := range estagios {
			if estagio_id == e.Id {
				estagioIndice = i
				break
			}
		}

		if estagioIndice == -1 {
			this.Redirect("/", 302)
			return
		}

		fmt.Println(estagioIndice)
		estagio := estagios[estagioIndice]

		this.TplName = "estagio_admin.html"
		this.Data["Estagio"] = estagio
		//this.Data[]
		break
	}

	this.Data["Usuario"] = conta.Pessoa
	fmt.Println(conta.Pessoa.Privilegio)
	fmt.Println(conta.Pessoa.Nome)

	fmt.Println(this.TplName)
	this.All()
	this.Render()
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\video\models\DirectorSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'name') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
//Input/output API.

#include <algorithm>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <ostream>

#include "api.h"
#include "api_basic.h"
#include "api_io.h"
#include "common.h"
#include "gc.h"
#include "scope.h"
#include "stringex.h"
#include "sysclass.h"
#include "sysclassbld__imp.h"
#include "value_core.h"

namespace ss = syn_script;
namespace gc = ss::gc;
namespace rt = ss::rt;

namespace syn_script {
	namespace rt {
		class StdOutTextOutputValue;
		class FileTextOutputValue;
	}
}

//
//TextOutputValue::API
//

class rt::TextOutputValue::API : public SysAPI<TextOutputValue> {
	void init() override {
		bld->add_method("print", &TextOutputValue::api_print);
		bld->add_method("println", &TextOutputValue::api_println_0);
		bld->add_method("println", &TextOutputValue::api_println_1);
		bld->add_method("close", &TextOutputValue::api_close);
	}
};

//
//TextOutputValue
//

std::size_t rt::TextOutputValue::get_sys_class_id() const {
	return API::get_class_id();
}

void rt::TextOutputValue::close(){}

void rt::TextOutputValue::api_print(const gc::Local<ExecContext>& context, const gc::Local<Value>& value) {
	std::ostream& out = get_out();
	rt::OperandType type = value->get_operand_type();
	if (rt::OperandType::INTEGER == type) {
		out << value->get_integer();
	} else if (rt::OperandType::STRING == type) {
		out << value->get_string();
	} else if (rt::OperandType::FLOAT == type) {
		out << value->get_float();
	} else if (rt::OperandType::BOOLEAN == type) {
		out << (value->get_boolean() ? "true" : "false");
	} else {
		out << value->to_string(context);
	}
	if (out.fail()) throw RuntimeError("Write error");
}

void rt::TextOutputValue::api_println_0(const gc::Local<ExecContext>& context) {
	std::ostream& out = get_out();
	out << std::endl;
	if (out.fail()) throw RuntimeError("Write error");
}

void rt::TextOutputValue::api_println_1(const gc::Local<ExecContext>& context, const gc::Local<Value>& value) {
	api_print(context, value);
	api_println_0(context);
}

void rt::TextOutputValue::api_close(const gc::Local<ExecContext>& context) {
	close();
}

//
//StdOutTextOutputValue : definition
//

class rt::StdOutTextOutputValue : public TextOutputValue {
	NONCOPYABLE(StdOutTextOutputValue);

public:
	StdOutTextOutputValue(){}

	std::ostream& get_out() override;
};

//
//StdOutTextOutputValue : implementation
//

std::ostream& rt::StdOutTextOutputValue::get_out() {
	return std::cout;
}

//
//FileTextOutputValue
//

void rt::FileTextOutputValue::initialize(const ss::StringLoc& path, bool append) {
	const std::string path_str = path->get_std_string();
	std::ios_base::openmode mode = append ? (std::ios_base::app | std::ios_base::ate)
		: static_cast<std::ios_base::openmode>(0);
	m_out.open(path_str, std::ios_base::out | mode);
	if (m_out.fail()) throw RuntimeError(std::string("Unable to open file: ") + path_str);
}

std::ostream& rt::FileTextOutputValue::get_out() {
	return m_out;
}

void rt::FileTextOutputValue::close() {
	m_out.close();
}

//
//BinaryInputValue::API
//

class rt::BinaryInputValue::API : public SysAPI<BinaryInputValue> {
	void init() override {
		bld->add_method("read_byte", &BinaryInputValue::api_read_byte);
		bld->add_method("read", &BinaryInputValue::api_read_1);
		bld->add_method("read", &BinaryInputValue::api_read_3);
		bld->add_method("close", &BinaryInputValue::api_close);
	}
};

//
//BinaryInputValue
//

std::size_t rt::BinaryInputValue::get_sys_class_id() const {
	return API::get_class_id();
}

int rt::BinaryInputValue::read(const gc::Local<ss::ByteArray>& buffer, std::size_t ofs, std::size_t len) {
	std::size_t array_len = buffer->length();
	if (len > array_len || ofs > array_len - len) throw RuntimeError("Index out of bounds");

	static_assert(sizeof(int) <= sizeof(std::size_t), "Wrong type size");
	std::size_t intmax = static_cast<std::size_t>(std::numeric_limits<int>::max());
	if (len > intmax) len = intmax;

	char* ptr = buffer->raw_array() + ofs;
	std::size_t initial_len = len;
	while (len--) {
		int k = read();
		if (k == -1) break;

		assert(k >= 0);
		unsigned char uc = k;
		*ptr++ = reinterpret_cast<char&>(uc);
	}

	std::size_t count = initial_len - len;
	return static_cast<int>(count);
}

int rt::BinaryInputValue::read(const gc::Local<ss::ByteArray>& buffer) {
	return read(buffer, 0, buffer->length());
}

void rt::BinaryInputValue::close(){}

ss::ScriptIntegerType rt::BinaryInputValue::api_read_byte(const gc::Local<ExecContext>& context) {
	return int_to_scriptint_ex(read());
}

ss::ScriptIntegerType rt::BinaryInputValue::api_read_3(
	const gc::Local<ExecContext>& context,
	const gc::Local<ss::ByteArray>& buffer,
	ss::ScriptIntegerType ofs,
	ss::ScriptIntegerType len)
{
	std::size_t sofs = scriptint_to_size_ex(ofs);
	std::size_t slen = scriptint_to_size_ex(len);
	return read(buffer, sofs, slen);
}

ss::ScriptIntegerType rt::BinaryInputValue::api_read_1(
	const gc::Local<ExecContext>& context,
	const gc::Local<ss::ByteArray>& buffer)
{
	return read(buffer);
}

void rt::BinaryInputValue::api_close(const gc::Local<ExecContext>& context) {
	close();
}

//
//BinaryOutputValue::API
//

class rt::BinaryOutputValue::API : public SysAPI<BinaryOutputValue> {
	void init() override {
		bld->add_method("write_byte", &BinaryOutputValue::api_write_byte);
		bld->add_method("write", &BinaryOutputValue::api_write_1);
		bld->add_method("write", &BinaryOutputValue::api_write_3);
		bld->add_method("close", &BinaryOutputValue::api_close);
	}
};

//
//BinaryOutputValue
//

std::size_t rt::BinaryOutputValue::get_sys_class_id() const {
	return API::get_class_id();
}

void rt::BinaryOutputValue::write(const gc::Local<ss::ByteArray>& buffer, std::size_t ofs, std::size_t len) {
	std::size_t array_len = buffer->length();
	if (len > array_len || ofs > array_len - len) throw RuntimeError("Index out of bounds");

	const char* ptr = buffer->raw_array() + ofs;
	while (len--) {
		char c = *ptr++;
		int k = reinterpret_cast<unsigned char&>(c);
		write(k);
	}
}

void rt::BinaryOutputValue::write(const gc::Local<ss::ByteArray>& buffer) {
	write(buffer, 0, buffer->length());
}

void rt::BinaryOutputValue::close(){}

void rt::BinaryOutputValue::api_write_byte(const gc::Local<ExecContext>& context, ss::ScriptIntegerType value) {
	int ivalue = scriptint_to_int_ex(value);
	write(ivalue);
}

void rt::BinaryOutputValue::api_write_3(
	const gc::Local<ExecContext>& context,
	const gc::Local<ss::ByteArray>& buffer,
	ss::ScriptIntegerType ofs,
	ss::ScriptIntegerType len)
{
	std::size_t sofs = scriptint_to_size_ex(ofs);
	std::size_t slen = scriptint_to_size_ex(len);
	write(buffer, sofs, slen);
}

void rt::BinaryOutputValue::api_write_1(const gc::Local<ExecContext>& context, const gc::Local<ss::ByteArray>& buffer) {
	write(buffer);
}

void rt::BinaryOutputValue::api_close(const gc::Local<ExecContext>& context) {
	close();
}

//
//FileBinaryInputValue
//

void rt::FileBinaryInputValue::initialize(const ss::StringLoc& path) {
	const std::string path_str = path->get_std_string();
	m_in.open(path_str, std::ios_base::out | std::ios_base::binary);
	if (m_in.fail()) throw RuntimeError(std::string("Unable to open file: ") + path_str);
}

int rt::FileBinaryInputValue::read() {
	char c;
	m_in.read(&c, 1);
	if (m_in.eof()) return -1;
	if (m_in.fail()) throw RuntimeError("Read error");

	return reinterpret_cast<unsigned char&>(c);
}

int rt::FileBinaryInputValue::read(const gc::Local<ss::ByteArray>& buffer, std::size_t ofs, std::size_t len) {
	std::size_t array_len = buffer->length();
	if (len > array_len || ofs > array_len - len) throw RuntimeError("Index out of bounds");

	const std::streamsize sizemax = std::numeric_limits<std::streamsize>::max();
	if (len > sizemax) len = static_cast<std::size_t>(sizemax);

	static_assert(sizeof(int) <= sizeof(std::size_t), "Wrong sizeof");
	const std::size_t intmax = static_cast<std::size_t>(std::numeric_limits<int>::max());
	if (len > intmax) len = static_cast<std::size_t>(intmax);

	char* ptr = buffer->raw_array() + ofs;
	m_in.read(ptr, len);

	if (m_in.eof()) {
		std::streamsize count = m_in.gcount();
		return count > 0 ? static_cast<int>(count) : -1;
	} else if (m_in.fail()) {
		throw RuntimeError("Read error");
	} else {
		return static_cast<int>(len);
	}
}

void rt::FileBinaryInputValue::close() {
	m_in.close();
}

//
//FileBinaryOutputValue
//

void rt::FileBinaryOutputValue::initialize(const ss::StringLoc& path, bool append) {
	const std::string path_str = path->get_std_string();
	std::ios_base::openmode mode = append ? (std::ios_base::app | std::ios_base::ate)
		: static_cast<std::ios_base::openmode>(0);
	m_out.open(path_str, std::ios_base::out | std::ios_base::binary | mode);
	if (m_out.fail()) throw RuntimeError(std::string("Unable to open file: ") + path_str);
}

void rt::FileBinaryOutputValue::write(int value) {
	assert(value >= 0);
	unsigned char uc = value;
	m_out.put(reinterpret_cast<char&>(uc));
	if (m_out.fail()) throw RuntimeError("Write error");
}

void rt::FileBinaryOutputValue::write(const gc::Local<ss::ByteArray>& buffer, std::size_t ofs, std::size_t len) {
	std::size_t array_len = buffer->length();
	if (len > array_len || ofs > array_len - len) throw RuntimeError("Index out of bounds");

	const char* ptr = buffer->raw_array() + ofs;
	m_out.write(ptr, len);

	if (m_out.fail()) throw RuntimeError("Write error");
}

void rt::FileBinaryOutputValue::close() {
	m_out.close();
}

//
//(Functions)
//

namespace {
	rt::SysNamespaceInitializer s_sys_namespace_initializer([](rt::SysClassBuilder<rt::SysNamespaceValue>& bld){
		bld.add_static_field("out", gc::create<rt::StdOutTextOutputValue>());
	});
}

void link__api_io(){}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new HH\ApiBundle\ApiBundle(),
            new HH\IceCreamBundle\IceCreamBundle(),
            new HH\SoccerMatchBundle\SoccerMatchBundle(),
            new HH\UserBundle\UserBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
body,
.stretched-layout .bgWrapper {
    background-color: #ffffff;
    background-position: top center;
    background-repeat: repeat;
    background-attachment: fixed
}

.wrapper-content {
    width:620px;
}

h1, h2, h3, h4, h5, h6, .special-font {
    font-family:'Quattrocento Sans' !important;
}

#nav > ul > li > a {
    font-family: 'Quattrocento Sans', Verdana, Geneva, sans-serif !important;
}

p,
li {
    font-family: 'Quattrocento Sans', Calibri, 'Lucida Sans Unicode', Helvetica, Arial, san-serif !important;
}

#topbar {
    text-align: right;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;
using Seringa.Engine.DataObjects;
using Seringa.Engine.Interfaces;
using System.IO;
using System.Xml;

namespace Seringa.Engine.Utils
{
    public static class XmlHelpers
    {
        public static bool CreateOrLoadMappingFile(string mappingFile,IInjectionStrategy injectionStrategy,
                                                    string dbmsName, ref string error,out XDocument doc)
        {
            bool outcome = true;
            XDocument document = null;

            if (!File.Exists(mappingFile))
            {
                var file = File.Create(mappingFile);
                file.Dispose();
            }
            else
            {
                try
                {
                    document = XDocument.Load(mappingFile);
                }
                catch(Exception ex)
                {
                    //TODO: do something
                }
            }

            try
            {
                if (document == null || (document != null && document.Element("map") == null))
                {
                    //create xml document from scratch
                    document = new XDocument(
                        new XElement("map",

                            new XElement("vulnerable-url", injectionStrategy.Url),
                            new XElement("injection-strategy",

                                    new XAttribute("name",injectionStrategy.GetType().Name),
                                    new XElement("columns",
                                        new List<XElement>()
                                        {
                                            new XElement("originalquery",injectionStrategy.NrColumnsInOriginalQuery),
                                            new XElement("resultinghtml",injectionStrategy.NumberOfResultsPerRequest),
                                            new XElement("indexes",
                                                ListHelpers.ListToCommaSeparatedValues(injectionStrategy.ColumnIndexes)),
                                        })),

                            new XElement("dbms",new XAttribute("name",dbmsName),
                                new XElement("users", "")
                                ),
                             new XElement("databases", "")
                        )
                    );

                    //save constructed document
                    document.Save(mappingFile);
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                outcome = false;
            }

            doc = document;
            return outcome;
        }

        public static string CreateProperMapToNodeFinderXpath(PayloadDetails payloadDetails,IInjectionStrategy strategy)
        {
            string result = string.Empty;

            result = payloadDetails.ParentNodeToMapTo;

            string[] replaceVars = payloadDetails.MapToParams.Split(',');

            for(int i=0;i<replaceVars.Count();i++)
            {
                result = result.Replace("{" + i + "}", PayloadHelpers.GetData(replaceVars[i], strategy));
            }

            return result;
        }

        public static string CreateProperMapToNodeCreatorXpath(PayloadDetails payloadDetails, string discoveredValue)
        {
            string result = string.Empty;
            result = payloadDetails.NodeToMapTo;
            if(!string.IsNullOrEmpty(payloadDetails.AttributeToMapTo))
                result += "[@"+payloadDetails.AttributeToMapTo+"='" + discoveredValue + "']";
            return result;
        }

        public static void ChangeMappingFileElementValue(string mappingFile, string elementXpath, string discoveredValue,
                                                            IInjectionStrategy injectionStrategy, string dbmsName)
        {
            string error = string.Empty;
            //XDocument document = XDocument.Load(mappingFile);
            XDocument document = null;
            if(!CreateOrLoadMappingFile(mappingFile, injectionStrategy, dbmsName, ref error,out document))
                return;//TODO: write message to UI
            bool save = true;

            var element = document.XPathSelectElement(elementXpath);

            if (element != null)
                element.Value = discoveredValue;
            else
            {
                element = document.XPathSelectElement(elementXpath.Substring(0, elementXpath.LastIndexOf("/")));
                if (element != null)
                {
                    int last = elementXpath.LastIndexOf("/");
                    element.Add(new XElement(elementXpath.Substring(last, elementXpath.Length - last),discoveredValue));
                }
                else
                    save = false;
            }
            if (save)
                document.Save(mappingFile);
        }

        public static void ChangeMappingFileAttributeValue(string mappingFile, string elementXpath,string attributeName, string discoveredValue,
                                                            IInjectionStrategy injectionStrategy, string dbmsName)
        {
            XDocument document = null;
            string error = string.Empty;
            if (!CreateOrLoadMappingFile(mappingFile, injectionStrategy, dbmsName, ref error, out document))
                return;//TODO: write message to UI
            bool save = true;

            var element = document.XPathSelectElement(elementXpath);

            if (element != null)
            {
                var attribute = element.Attribute(attributeName);
                if (attribute != null)
                    attribute.Value = discoveredValue;
                else
                    element.Add(new XAttribute(attributeName, discoveredValue));
            }
            else
            {
                element = document.XPathSelectElement(elementXpath.Substring(0,elementXpath.LastIndexOf("/")));
                if (element != null)
                {
                    int last = elementXpath.LastIndexOf("/");
                    element.Add(new XElement(elementXpath.Substring(last, elementXpath.Length - last), new XAttribute(attributeName, discoveredValue)));
                }
                else
                    save = false;
            }
            if(save)
                document.Save(mappingFile);
        }

        public static bool SaveToMappingFile(string mappingFile,PayloadDetails payloadDetails,string discoveredValue, IInjectionStrategy strategy,
                                                string dbmsName)
        {
            if (string.IsNullOrEmpty(payloadDetails.NodeToMapTo))
                return false;

            XDocument document = null;
            string error = string.Empty;
            if (!CreateOrLoadMappingFile(mappingFile, strategy, dbmsName, ref error, out document))
                return false;//TODO: write message to UI

            var element = document.XPathSelectElement(CreateProperMapToNodeFinderXpath(payloadDetails, strategy));

            if (element.XPathSelectElement(CreateProperMapToNodeCreatorXpath(payloadDetails,discoveredValue)) == null)
            {
                if(!string.IsNullOrEmpty(payloadDetails.AttributeToMapTo))
                    element.Add(
                        new XElement(payloadDetails.NodeToMapTo, new XAttribute(payloadDetails.AttributeToMapTo, discoveredValue))
                    );
                else
                    element.Add(new XElement(payloadDetails.NodeToMapTo, discoveredValue));

                //For simplicity, I just use the Save() method to overwrite the current .xml file
                document.Save(mappingFile);
                return true;
            }
            return false;
        }

        public static XElement GetXmlElementViaXpath(string docName, string xpath)
        {
            XElement result = null;
            XDocument doc = XDocument.Load(docName);
            result = GetXmlElementViaXpath(doc, xpath);
            return result;
        }

        public static XElement GetXmlElementViaXpath(XElement elem, string xpath)
        {
            XElement result = null;
            result = elem.XPathSelectElements(xpath).FirstOrDefault();
            return result;
        }

        public static XElement GetXmlElementViaXpath(XDocument doc, string xpath)
        {
            return GetXmlElementViaXpath(doc.Root, xpath);
        }

        public static T GetObjectFromXml<T>(string docName, string elementType, string elementUserFriendlyName)
        {
            var doc = XDocument.Load(docName);

            var elem = doc.Descendants(elementType)
                            .SingleOrDefault(e => e.Attribute("user-friendly-name").Value == elementUserFriendlyName);

            T createdObj = default(T);

            if(elem != null)
                createdObj = (T)Activator.CreateInstance(typeof(T), elem);

            return createdObj;
        }

        public static T GetObjectFromXml<T>(string docName, string elementType, int index)
        {
            var doc = XDocument.Load(docName);

            var elem = doc.Descendants(elementType).ElementAt(index);

            T createdObj = (T)Activator.CreateInstance(typeof(T), elem);

            return createdObj;
        }

        public static IList<T> GetObjectsFromXml<T>(string docName, string elementType,IList<dynamic> filters)
        {
            IList<T> results = new List<T>();
            var doc = XDocument.Load(docName);

            var query = doc.Descendants(elementType).AsQueryable();

            if(filters != null && filters.Count > 0)
                foreach (var filter in filters)
                {
                    if (filter != null && filter.AttributeName != null && filter.AttributeValue != null)
                    {
                        var dict = (IDictionary<string, object>)filter;

                        query = query.Where(e =>
                            e.Attribute(dict["AttributeName"].ToString()) != null &&
                            (e.Attribute(dict["AttributeName"].ToString()).Value == dict["AttributeValue"].ToString())).AsQueryable();
                    }
                }

            foreach (var elem in query.ToList())
            {
                results.Add((T)Activator.CreateInstance(typeof(T), elem));
            }

            return results;
        }

        public static IList<string> GetValuesFromDocByXpath(string docName,string xPath,string attributeName)
        {
            IList<string> results = new List<string>();

            var doc = XDocument.Load(docName);

            var attributes = doc.Root.XPathSelectElements(xPath).Attributes(attributeName);

            if(attributes.Count() > 0)
                results = attributes.Select(a => a.Value).ToList();

            return results;

        }

        public static IList<string> GetAllAttributeValuesFromDoc(string docName,string elementName,string attributeName)
        {
            IList<string> results = new List<string>();

            var doc = XDocument.Load(docName);

            results = doc.Descendants(elementName).Attributes(attributeName).Select(a => a.Value).Distinct().ToList();

            return results;
        }

        public static T GetElementValueViaXpath<T>(XElement elem, string xpath, T defaultValue)
        {
            T result = defaultValue;

            XElement element =  GetXmlElementViaXpath(elem,xpath);

            if (element != null)
            {
                string value = element.Value;
                result = (T)Convert.ChangeType(value, typeof(T));
            }
            return result;
        }

        public static T GetElementValue<T>(XElement element, T defaultValue)
        {
            T result = defaultValue;
            if (element != null)
            {
                string value = element.Value;
                result = (T)Convert.ChangeType(value, typeof(T));
            }
            return result;
        }

        public static T GetAttributeValueFromDoc<T>(string docName, string elemXpath, string attributeName, T defaultValue)
        {
            T result = defaultValue;
            XElement injectionStrategyElem = null;
            XAttribute injectionTypeNameAttr = null;

            if ((injectionStrategyElem = GetXmlElementViaXpath(docName, elemXpath)) != null)
                if ((injectionTypeNameAttr = injectionStrategyElem.Attribute(attributeName)) != null)
                    result = (T)Convert.ChangeType(injectionTypeNameAttr.Value, typeof(T));

            return result;
        }

        public static T GetElementValueFromDoc<T>(string docName, string elemXpath, T defaultValue)
        {
            T result = defaultValue;
            XElement injectionStrategyElem = null;

            if ((injectionStrategyElem = GetXmlElementViaXpath(docName, elemXpath)) != null)
                result = (T)Convert.ChangeType(injectionStrategyElem.Value, typeof(T));

            return result;
        }

        public static string GetAttributeValue(XElement element, string name)
        {
            if ((element == null) || (element.Attribute(name).Value == null))
                return String.Empty;
            return element.Attribute(name).Value;
        }

        public static T GetAttributeValue<T>(XElement element, string name, T defaultValue)
        {
            T result = defaultValue;
            if ((element != null) && element.Attribute(name)!=null && (element.Attribute(name).Value != null))
            {
                string value = element.Attribute(name).Value;
                result = (T)Convert.ChangeType(value, typeof(T));
            }
            return result;
        }

        public static string GetLastTagFromXpath(string xpath)
        {
            string result = string.Empty;

            int lastSlash = xpath.LastIndexOf("/")+1;
            int lastParanthesis = xpath.LastIndexOf("[");

            if (lastSlash > -1)
            {
                int length = ((lastParanthesis > -1)?lastParanthesis:xpath.Length) - lastSlash;

                result = xpath.Substring(lastSlash, length);
            }
            return result;
        }
    }
}


text:
package ogletest

import (
	"bytes"
	"flag"
	"fmt"
	"os"
	"path"
	"regexp"
	"runtime"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/scaleway/scaleway-cli/vendor/github.com/smartystreets/assertions/internal/reqtrace"
)

var fTestFilter = flag.String(
	"ogletest.run",
	"",
	"Regexp for matching tests to run.")

var fStopEarly = flag.Bool(
	"ogletest.stop_early",
	false,
	"If true, stop after the first failure.")

// runTestsOnce protects RunTests from executing multiple times.
var runTestsOnce sync.Once

func isAbortError(x interface{}) bool {
	_, ok := x.(abortError)
	return ok
}

// Run a single test function, returning a slice of failure records.
func runTestFunction(tf TestFunction) (failures []FailureRecord) {
	// Set up a clean slate for this test. Make sure to reset it after everything
	// below is finished, so we don't accidentally use it elsewhere.
	currentlyRunningTest = newTestInfo()
	defer func() {
		currentlyRunningTest = nil
	}()

	ti := currentlyRunningTest

	// Start a trace.
	var reportOutcome reqtrace.ReportFunc
	ti.Ctx, reportOutcome = reqtrace.Trace(ti.Ctx, tf.Name)

	// Run the SetUp function, if any, paying attention to whether it panics.
	setUpPanicked := false
	if tf.SetUp != nil {
		setUpPanicked = runWithProtection(func() { tf.SetUp(ti) })
	}

	// Run the test function itself, but only if the SetUp function didn't panic.
	// (This includes AssertThat errors.)
	if !setUpPanicked {
		runWithProtection(tf.Run)
	}

	// Run the TearDown function, if any.
	if tf.TearDown != nil {
		runWithProtection(tf.TearDown)
	}

	// Tell the mock controller for the tests to report any errors it's sitting
	// on.
	ti.MockController.Finish()

	// Report the outcome to reqtrace.
	if len(ti.failureRecords) == 0 {
		reportOutcome(nil)
	} else {
		reportOutcome(fmt.Errorf("%v failure records", len(ti.failureRecords)))
	}

	return ti.failureRecords
}

// Run everything registered with Register (including via the wrapper
// RegisterTestSuite).
//
// Failures are communicated to the supplied testing.T object. This is the
// bridge between ogletest and the testing package (and `go test`); you should
// ensure that it's called at least once by creating a test function compatible
// with `go test` and calling it there.
//
// For example:
//
//     import (
//       "github.com/smartystreets/assertions/internal/ogletest"
//       "testing"
//     )
//
//     func TestOgletest(t *testing.T) {
//       ogletest.RunTests(t)
//     }
//
func RunTests(t *testing.T) {
	runTestsOnce.Do(func() { runTestsInternal(t) })
}

// Signalling between RunTests and StopRunningTests.
var gStopRunning uint64

// Request that RunTests stop what it's doing. After the currently running test
// is finished, including tear-down, the program will exit with an error code.
func StopRunningTests() {
	atomic.StoreUint64(&gStopRunning, 1)
}

// runTestsInternal does the real work of RunTests, which simply wraps it in a
// sync.Once.
func runTestsInternal(t *testing.T) {
	// Process each registered suite.
	for _, suite := range registeredSuites {
		// Stop now if we've already seen a failure and we've been told to stop
		// early.
		if t.Failed() && *fStopEarly {
			break
		}

		// Print a banner.
		fmt.Printf("[----------] Running tests from %s\n", suite.Name)

		// Run the SetUp function, if any.
		if suite.SetUp != nil {
			suite.SetUp()
		}

		// Run each test function that the user has not told us to skip.
		stoppedEarly := false
		for _, tf := range filterTestFunctions(suite) {
			// Did the user request that we stop running tests? If so, skip the rest
			// of this suite (and exit after tearing it down).
			if atomic.LoadUint64(&gStopRunning) != 0 {
				stoppedEarly = true
				break
			}

			// Print a banner for the start of this test function.
			fmt.Printf("[ RUN      ] %s.%s\n", suite.Name, tf.Name)

			// Run the test function.
			startTime := time.Now()
			failures := runTestFunction(tf)
			runDuration := time.Since(startTime)

			// Print any failures, and mark the test as having failed if there are any.
			for _, record := range failures {
				t.Fail()
				fmt.Printf(
					"%s:%d:\n%s\n\n",
					record.FileName,
					record.LineNumber,
					record.Error)
			}

			// Print a banner for the end of the test.
			bannerMessage := "[       OK ]"
			if len(failures) != 0 {
				bannerMessage = "[  FAILED  ]"
			}

			// Print a summary of the time taken, if long enough.
			var timeMessage string
			if runDuration >= 25*time.Millisecond {
				timeMessage = fmt.Sprintf(" (%s)", runDuration.String())
			}

			fmt.Printf(
				"%s %s.%s%s\n",
				bannerMessage,
				suite.Name,
				tf.Name,
				timeMessage)

			// Stop running tests from this suite if we've been told to stop early
			// and this test failed.
			if t.Failed() && *fStopEarly {
				break
			}
		}

		// Run the suite's TearDown function, if any.
		if suite.TearDown != nil {
			suite.TearDown()
		}

		// Were we told to exit early?
		if stoppedEarly {
			fmt.Println("Exiting early due to user request.")
			os.Exit(1)
		}

		fmt.Printf("[----------] Finished with tests from %s\n", suite.Name)
	}
}

// Return true iff the supplied program counter appears to lie within panic().
func isPanic(pc uintptr) bool {
	f := runtime.FuncForPC(pc)
	if f == nil {
		return false
	}

	return f.Name() == "runtime.gopanic" || f.Name() == "runtime.sigpanic"
}

// Find the deepest stack frame containing something that appears to be a
// panic. Return the 'skip' value that a caller to this function would need
// to supply to runtime.Caller for that frame, or a negative number if not found.
func findPanic() int {
	localSkip := -1
	for i := 0; ; i++ {
		// Stop if we've passed the base of the stack.
		pc, _, _, ok := runtime.Caller(i)
		if !ok {
			break
		}

		// Is this a panic?
		if isPanic(pc) {
			localSkip = i
		}
	}

	return localSkip - 1
}

// Attempt to find the file base name and line number for the ultimate source
// of a panic, on the panicking stack. Return a human-readable sentinel if
// unsuccessful.
func findPanicFileLine() (string, int) {
	panicSkip := findPanic()
	if panicSkip < 0 {
		return "(unknown)", 0
	}

	// Find the trigger of the panic.
	_, file, line, ok := runtime.Caller(panicSkip + 1)
	if !ok {
		return "(unknown)", 0
	}

	return path.Base(file), line
}

// Run the supplied function, catching panics (including AssertThat errors) and
// reporting them to the currently-running test as appropriate. Return true iff
// the function panicked.
func runWithProtection(f func()) (panicked bool) {
	defer func() {
		// If the test didn't panic, we're done.
		r := recover()
		if r == nil {
			return
		}

		panicked = true

		// We modify the currently running test below.
		currentlyRunningTest.mu.Lock()
		defer currentlyRunningTest.mu.Unlock()

		// If the function panicked (and the panic was not due to an AssertThat
		// failure), add a failure for the panic.
		if !isAbortError(r) {
			var panicRecord FailureRecord
			panicRecord.FileName, panicRecord.LineNumber = findPanicFileLine()
			panicRecord.Error = fmt.Sprintf(
				"panic: %v\n\n%s", r, formatPanicStack())

			currentlyRunningTest.failureRecords = append(
				currentlyRunningTest.failureRecords,
				panicRecord)
		}
	}()

	f()
	return
}

func formatPanicStack() string {
	buf := new(bytes.Buffer)

	// Find the panic. If successful, we'll skip to below it. Otherwise, we'll
	// format everything.
	var initialSkip int
	if panicSkip := findPanic(); panicSkip >= 0 {
		initialSkip = panicSkip + 1
	}

	for i := initialSkip; ; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}

		// Choose a function name to display.
		funcName := "(unknown)"
		if f := runtime.FuncForPC(pc); f != nil {
			funcName = f.Name()
		}

		// Stop if we've gotten as far as the test runner code.
		if funcName == "github.com/smartystreets/assertions/internal/ogletest.runTestMethod" ||
			funcName == "github.com/smartystreets/assertions/internal/ogletest.runWithProtection" {
			break
		}

		// Add an entry for this frame.
		fmt.Fprintf(buf, "%s\n\t%s:%d\n", funcName, file, line)
	}

	return buf.String()
}

// Filter test functions according to the user-supplied filter flag.
func filterTestFunctions(suite TestSuite) (out []TestFunction) {
	re, err := regexp.Compile(*fTestFilter)
	if err != nil {
		panic("Invalid value for --ogletest.run: " + err.Error())
	}

	for _, tf := range suite.TestFunctions {
		fullName := fmt.Sprintf("%s.%s", suite.Name, tf.Name)
		if !re.MatchString(fullName) {
			continue
		}

		out = append(out, tf)
	}

	return
}


text:
'use strict';
var edge = require('edge');
var path = require('path');

var generateClr = edge.func({
  // assemblyFile: path.join(__dirname, 'ASTquery.dll'),
  assemblyFile: path.join(__dirname, '../../src.net/ASTquery/bin/Debug/ASTquery.exe'),
  typeName: 'ASTquery.Startup',
  methodName: 'Generate'
});

function generate(tree, alters, options) {
  var body;
  generateClr({ ast: JSON.stringify(tree), alters: JSON.stringify(alters) }, function (error, result) {
    if (error) throw error; //: console.log(result);
    body = (result ? result.replace(/\r\n/g, '\n') : null);
  });
  return body;
}

module.exports = {
  generate: generate,
};


text:
console.log('capetown.js loaded');
define(['jquery'], function($){

 	$(document).on('pagecreate', '#capetown', function(e){
 		console.log('#capetown.pagecreate');
 	});

 	$(document).on('pageshow', '#capetown', function(e){
 		console.log('#capetown.pageshow');
 	});

});


text:
Originally published: 2008-11-03 10:39:14
Last updated: 2013-09-07 10:24:17
Author: Romain Dartigues

The Python `mailbox.mbox` class require a real file to initialize, which was an issue in my case. These simple functions let you iter through a mailbox read from a read-only file descriptor (like `sys.stdin`).

This script use the generators which were introduced in Python-2.2. Let me know if you are interested a similar functionnality on older Python versions.


text:
@implementation SFScaleNode

- (instancetype)init
{
    SFInput *input = [[SFInput alloc] initWithName:@"input"];
    SFInput *scale = [[SFInput alloc] initWithName:@"scale"];
    SFOutput *output = [[SFOutput alloc] initWithName:@"output"];
    self = [super initWithInputs:@[input, scale] outputs:@[output]];
    if (self != nil) {
        _input = input;
        _scale = scale;
        _output = output;
    }
    return self;
}

- (BOOL)rendersConstantFrame
{
    SFNode *inputNode = _input.source.owner;
    SFNode *scaleNode = _scale.source.owner;
    if (inputNode == nil || scaleNode == nil) {
        return NO;
    }
    return ([inputNode rendersConstantFrame] &&
            [scaleNode rendersConstantFrame]);
}

- (BOOL)renderForPlayer:(SFPlaybackManager *)player
                  index:(UInt64)index
                  count:(NSInteger)count
                     to:(double *)buffer
{
    SFNode *iNode = _input.source.owner;
    if (iNode == nil) {
        return NO;
    }

    SFNode *sNode = _scale.source.owner;
    if (sNode == nil) {
        return NO;
    }

    BOOL inputIsConstant = [iNode rendersConstantFrame];
    BOOL scaleIsConstant = [sNode rendersConstantFrame];

    double sampleValue = 0.0;
    double scaleValue = 1.0;

    if (inputIsConstant) {
        if (![iNode renderForPlayer:player index:index count:1 to:&sampleValue]) {
            return NO;
        }
    }

    if (scaleIsConstant) {
        if (![sNode renderForPlayer:player index:index count:1 to:&scaleValue]) {
            return NO;
        }
    }

    if (inputIsConstant && scaleIsConstant) {
        double value = sampleValue * scaleValue;
        for (NSInteger i; i < count; i++) {
            buffer[i] = value;
        }
        return YES;
    }

    if (inputIsConstant) {
        SFBufferOperator *scaleBufferOperator = [player getSFBufferOperator];
        double *scaleBufferData = scaleBufferOperator.buffer.data;

        if (![sNode renderForPlayer:player index:index count:count to:scaleBufferData]) {
            return NO;
        }
        for (NSInteger i = 0; i < count; i++) {
            buffer[i] = sampleValue * scaleBufferData[i];
        }
        return YES;
    }

    if (scaleIsConstant) {
        SFBufferOperator *inputBufferOperator = [player getSFBufferOperator];
        double *inputBufferData = inputBufferOperator.buffer.data;

        if (![iNode renderForPlayer:player index:index count:count to:inputBufferData]) {
            return NO;
        }
        for (NSInteger i = 0; i < count; i++) {
            buffer[i] = scaleValue * inputBufferData[i];
        }
        return YES;
    }

    SFBufferOperator *inputBufferOperator = [player getSFBufferOperator];
    double *inputBufferData = inputBufferOperator.buffer.data;

    if (![iNode renderForPlayer:player index:index count:count to:inputBufferData]) {
        return NO;
    }

    SFBufferOperator *scaleBufferOperator = [player getSFBufferOperator];
    double *scaleBufferData = scaleBufferOperator.buffer.data;

    if (![sNode renderForPlayer:player index:index count:count to:scaleBufferData]) {
        return NO;
    }

    for (NSInteger i = 0; i < count; i++) {
        buffer[i] = inputBufferData[i] * scaleBufferData[i];
    }
    return YES;
}

@end


text:
import { NodeBuilder } from '../../core/NodeBuilder';
import { Node } from '../../core/Node';

export class PhongNode extends Node {
    constructor();

    color: Node;
    specular: Node;
    shininess: Node;
    nodeType: string;

    build(builder: NodeBuilder): string;
    copy(source: PhongNode): this;
}


text:
Introduction
============

View Binder is a page transition similar to what you see on Flipboard (the Android application),
and is highly inspired by hard work of Flipboard developers. There are still some flaws in this
implementation out of which some will be fixed while some won't. This project is kept on
example application level only.

License
=======

Application is licensed under Apache 2.0 license and is free for use in personal and commercial
projects. See LICENSE file for more detailed license information.


text:
<?php

namespace BambooLab\PiwikTracker\PiwikTrackerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('BambooLabPiwikTrackerBundle:Default:index.html.twig', array('name' => $name));
    }
}


text:
namespace WebApplication.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class AddGroup : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Groups",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Timestamp = c.DateTime(nullable: false),
                        ApplicationUser_Id = c.String(maxLength: 128),
                    })
                .PrimaryKey(t => t.ID)
                .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id)
                .Index(t => t.ApplicationUser_Id);

            CreateTable(
                "dbo.RoleInGroups",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Role = c.String(),
                        User_Id = c.String(maxLength: 128),
                        Group_ID = c.Int(),
                    })
                .PrimaryKey(t => t.ID)
                .ForeignKey("dbo.AspNetUsers", t => t.User_Id)
                .ForeignKey("dbo.Groups", t => t.Group_ID)
                .Index(t => t.User_Id)
                .Index(t => t.Group_ID);

            AddColumn("dbo.Curriculars", "ApplicationUser_Id", c => c.String(maxLength: 128));
            AddColumn("dbo.Items", "ApplicationUser_Id", c => c.String(maxLength: 128));
            CreateIndex("dbo.Curriculars", "ApplicationUser_Id");
            CreateIndex("dbo.Items", "ApplicationUser_Id");
            AddForeignKey("dbo.Items", "ApplicationUser_Id", "dbo.AspNetUsers", "Id");
            AddForeignKey("dbo.Curriculars", "ApplicationUser_Id", "dbo.AspNetUsers", "Id");
        }

        public override void Down()
        {
            DropForeignKey("dbo.Groups", "ApplicationUser_Id", "dbo.AspNetUsers");
            DropForeignKey("dbo.RoleInGroups", "Group_ID", "dbo.Groups");
            DropForeignKey("dbo.RoleInGroups", "User_Id", "dbo.AspNetUsers");
            DropForeignKey("dbo.Curriculars", "ApplicationUser_Id", "dbo.AspNetUsers");
            DropForeignKey("dbo.Items", "ApplicationUser_Id", "dbo.AspNetUsers");
            DropIndex("dbo.RoleInGroups", new[] { "Group_ID" });
            DropIndex("dbo.RoleInGroups", new[] { "User_Id" });
            DropIndex("dbo.Groups", new[] { "ApplicationUser_Id" });
            DropIndex("dbo.Items", new[] { "ApplicationUser_Id" });
            DropIndex("dbo.Curriculars", new[] { "ApplicationUser_Id" });
            DropColumn("dbo.Items", "ApplicationUser_Id");
            DropColumn("dbo.Curriculars", "ApplicationUser_Id");
            DropTable("dbo.RoleInGroups");
            DropTable("dbo.Groups");
        }
    }
}


text:
import type { FC } from "react";
import { useContext } from "react";
import { LayoutContext } from "./LayoutContext";
import { FlexibleColumn } from "./FlexibleColumn";
import { FlexibleDropZone } from "./FlexibleDropZone";
import { FlexibleTabsContainer } from "./FlexibleTabsContainer";
import style from "./FlexibleGridContainer.modules.scss";

/**
 * Arguments for the GridContainer component.
 */
export interface IFlexibleGridContainerProps {}

/**
 * Component responsible for mapping the layout to the actual components
 */
export const FlexibleGridContainer: FC<IFlexibleGridContainerProps> = () => {
    const context = useContext(LayoutContext);
    const { layout } = context;
    const columns =
        layout && layout.columns
            ? layout.columns.map((column: any, columnIdx: number) => {
                  return (
                      <FlexibleColumn key={column.id} width={column.width}>
                          {column.rows.map((row: any, rowIdx: number) => {
                              return (

                                      <FlexibleDropZone rowNumber={rowIdx} columnNumber={columnIdx}>
                                          <FlexibleTabsContainer tabs={row.tabs} selectedTab={row.selectedTab} rowIndex={rowIdx} columnIndex={columnIdx} />
                                      </FlexibleDropZone>

                              );
                          })}
                      </FlexibleColumn>
                  );
              })
            : [];
    return
{columns}
;
};


text:
#pragma once

//[Headers]     -- You can add your own extra header files here --
#include "JuceHeader.h"
//[/Headers]

//==============================================================================
/**
                                                                    //[Comments]
    An auto-generated component, created by the Projucer.

    Describe your class and how it works here!
                                                                    //[/Comments]
*/
class AudioInput  : public juce::ChangeListener,
                    public ompu::plug::base::AppComponent<>
{
public:
    //==============================================================================
    AudioInput (App& app_);
    ~AudioInput();

    //==============================================================================
    //[UserMethods]     -- You can add your own custom methods in this section.
    //[/UserMethods]

    void paint (Graphics& g) override;
    void resized() override;

private:
    //[UserVariables]   -- You can add your own custom variables in this section.
    //[/UserVariables]

    //==============================================================================
    ScopedPointer<Label> host_device_;
    ScopedPointer<Label> label2;
    ScopedPointer<Viewport> in_ch_;
    ScopedPointer<Label> label;

    //==============================================================================
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioInput)
};

//[EndFile] You can add extra defines here...
//[/EndFile]


text:
/* ShowOff JS Logic */

var ShowOff = {};

var preso_started = false
var slidenum = 0
var slideTotal = 0
var slides
var currentSlide
var totalslides = 0
var slidesLoaded = false
var incrSteps = 0
var incrElem
var incrCurr = 0
var incrCode = false
var debugMode = false
var gotoSlidenum = 0
var lastMessageGuid = 0
var query
var slideStartTime = new Date().getTime()

var loadSlidesBool
var loadSlidesPrefix

var keycode_dictionary,
    keycode_shifted_keys;

var mode = { track: true, follow: true };

$(document).on('click', 'code.execute', executeCode);

function setupPreso(load_slides, prefix) {
	if (preso_started)
	{
		alert("already started")
		return
	}
	preso_started = true

	// save our query string as an object for later use
	query = $.parseQuery();

	// Load slides fetches images
	loadSlidesBool = load_slides
	loadSlidesPrefix = prefix || '/'
	loadSlides(loadSlidesBool, loadSlidesPrefix)

  loadKeyDictionaries();

	doDebugStuff()

	// bind event handlers
	toggleKeybinding('on');

	$('#preso').addSwipeEvents().
		bind('tap', swipeLeft).         // next
		bind('swipeleft', swipeLeft).   // next
		bind('swiperight', swipeRight); // prev

  // give us the ability to disable tracking via url parameter
  if(query.track == 'false') mode.track = false;

  // make sure that the next view doesn't bugger things on the first load
  if(query.next == 'true') {
    $('#preso').addClass('zoomed');
    mode.next = true;
    zoom();
  }

  // Make sure the slides always look right.
  // Better would be dynamic calculations, but this is enough for now.
  $(window).resize(function(){location.reload();});

  $("#feedbackWrapper").hover(
    function() {
      $('#feedbackSidebar').show();
      toggleKeybinding();
    },
    function() {
      $('#feedbackSidebar').hide();
      toggleKeybinding();
    }
  );

  $("#paceSlower").click(function() { sendPace('slower'); });
  $("#paceFaster").click(function() { sendPace('faster'); });
  $("#askQuestion").click(function() { askQuestion( $("textarea#question").val()) });
  $("#sendFeedback").click(function() {
    sendFeedback($( "input:radio[name=rating]:checked" ).val(), $("textarea#feedback").val())
  });
  $("#editSlide").click(function() { editSlide(); });

  // Open up our control socket
  if(mode.track) {
    connectControlChannel();
  }
/*
  ws           = new WebSocket('ws://' + location.host + '/control');
  ws.onopen    = function()  { connected();          };
  ws.onclose   = function()  { disconnected();       }
  ws.onmessage = function(m) { parseMessage(m.data); };
*/
}

function loadSlides(load_slides, prefix) {
	//load slides offscreen, wait for images and then initialize
	if (load_slides) {
		$("#slides").load(loadSlidesPrefix + "slides", false, function(){
			$("#slides img").batchImageLoad({
			loadingCompleteCallback: initializePresentation(prefix)
		})
		})
	} else {
	$("#slides img").batchImageLoad({
		loadingCompleteCallback: initializePresentation(prefix)
	})
	}
}

function loadKeyDictionaries () {
  $.getJSON('/js/keyDictionary.json', function(data) {
    keycode_dictionary = data['keycodeDictionary'];
    keycode_shifted_keys = data['shiftedKeyDictionary'];
  });
}

function initializePresentation(prefix) {
	// unhide for height to work in static mode
        $("#slides").show();

	//copy into presentation area
	$("#preso").empty()
	$('#slides > .slide').appendTo($("#preso"))

	//populate vars
	slides = $('#preso > .slide')
	slideTotal = slides.size()

	//setup manual jquery cycle
	$('#preso').cycle({
		timeout: 0
	})

	setupMenu()

	if (slidesLoaded) {
		showSlide()
	} else {
		showFirstSlide();
		slidesLoaded = true
	}
	setupSlideParamsCheck();

  $('pre.highlight code').each(function(i, block) {
    try {
      hljs.highlightBlock(block);
    } catch(e) {
      console.log('Syntax highlighting failed on ' + $(this).closest('div.slide').attr('id'));
      console.log('Syntax highlighting failed for ' + $(this).attr('class'));
      console.log(e);
    }
  });

  $(".content form").submit(function(e) {
    e.preventDefault();
    submitForm($(this));
  });

  // suspend hotkey handling
  $(".content form :input").focus( function() {
    toggleKeybinding();
  });
  $(".content form :input").blur( function() {
    toggleKeybinding();
  });

  $(".content form :input").change(function(e) {
    enableForm($(this));
  });

  $(".content form div.tools input.display").click(function(e) {
    try {
      // If we're a presenter, try to bust open the slave display
      slaveWindow.renderForm($(this).closest('form').attr('id'));
    }
    catch (e) {
      console.log(e);
      renderForm($(this).closest('form'));
    }
  });

	$("#preso").trigger("showoff:loaded");
}

/* This looks like the zoom() function for the presenter preview, but it uses a different algorithm */
function zoom()
{
  if(window.innerWidth <= 480) {
    $(".zoomed").css("zoom", 0.32);
  }
  else {
    var hSlide = parseFloat($("#preso").height());
    var wSlide = parseFloat($("#preso").width());
    var hBody  = parseFloat($("html").height());
    var wBody  = parseFloat($("html").width());

    newZoom = Math.min(hBody/hSlide, wBody/wSlide) - 0.04;

    $(".zoomed").css("zoom", newZoom);
    $(".zoomed").css("-ms-zoom", newZoom);
    $(".zoomed").css("-webkit-zoom", newZoom);
    $(".zoomed").css("-moz-transform", "scale("+newZoom+")");
    $(".zoomed").css("-moz-transform-origin", "left top");
  }
}

function setupMenu() {
	$('#navmenu').hide();

	var currSlide = 0
	var menu = new ListMenu()

	slides.each(function(s, elem) {
		content = $(elem).find(".content")
		shortTxt = $(content).text().substr(0, 20)
		path = $(content).attr('ref').split('/')
		currSlide += 1
		menu.addItem(path, shortTxt, currSlide)
	})

	$('#navigation').html(menu.getList())
	$('#navmenu').menu({
		content: $('#navigation').html(),
		flyOut: true
	});
}

function checkSlideParameter() {
	if (slideParam = currentSlideFromParams()) {
		slidenum = slideParam;
	}
}

function currentSlideFromName(name) {
  var count = 0;
  if(name.length > 0 ) {
  	slides.each(function(s, slide) {
  	  if (name == $(slide).find(".content").attr("ref") ) {
  	    found = count;
  	    return false;
  	  }
  	  count++;
  	});
	}
	return count;
}

function currentSlideFromParams() {
	var result;
	if (result = window.location.hash.match(/#([0-9]+)/)) {
		return result[result.length - 1] - 1;
	}
	else {
	  var hash = window.location.hash
	  return currentSlideFromName(hash.substr(1, hash.length))
  }
}

function setupSlideParamsCheck() {
	var check = function() {
		var currentSlide = currentSlideFromParams();
		if (!isNaN(currentSlide) && slidenum != currentSlide) {
			slidenum = currentSlide;
			showSlide();
		}
		setTimeout(check, 100);
	}
	setTimeout(check, 100);
}

function gotoSlide(slideNum, updatepv) {
  var newslide = parseInt(slideNum);
  if (slidenum != newslide && !isNaN(newslide)) {
    slidenum = newslide;
    showSlide(false, updatepv);
  }
}

function showFirstSlide() {
	slidenum = 0
	checkSlideParameter();
	showSlide()
}

function showSlide(back_step, updatepv) {
  // allows the master presenter view to disable the update callback
  updatepv = (typeof(updatepv) === 'undefined') ? true : updatepv;

	if(slidenum < 0) {
		slidenum = 0
		return
	}

	if(slidenum > (slideTotal - 1)) {
		slidenum = slideTotal - 1
		return
	}

	currentSlide = slides.eq(slidenum)

	var transition = currentSlide.attr('data-transition')
	var fullPage = currentSlide.find(".content").is('.full-page');

	if (back_step || fullPage) {
		transition = 'none'
	}

	$('#preso').cycle(slidenum, transition)

	if (fullPage) {
		$('#preso').css({'width' : '100%', 'overflow' : 'visible'});
		currentSlide.css({'width' : '100%', 'text-align' : 'center', 'overflow' : 'visible'});
	} else {
		$('#preso').css({'width' : '', 'overflow' : ''});
	}

	percent = getSlidePercent()
	$("#slideInfo").text((slidenum + 1) + '/' + slideTotal + '	- ' + percent + '%')

	if(!back_step) {
		// determine if there are incremental bullets to show
		// unless we are moving backward
		determineIncremental()
	} else {
		incrCurr = 0
		incrSteps = 0
	}
	location.hash = slidenum + 1;

	removeResults();

  var currentContent = $(currentSlide).find(".content")
	currentContent.trigger("showoff:show");

	var ret = setCurrentNotes();

	var fileName = currentSlide.children().first().attr('ref');
  $('#slideFilename').text(fileName);

  if (query.next) {
    $(currentSlide).find('li').removeClass('hidden');
  }

  // Update presenter view, if we spawned one
	if (updatepv && 'presenterView' in window && ! mode.next) {
    var pv = window.presenterView;
		pv.slidenum = slidenum;
    pv.incrCurr = incrCurr
    pv.incrSteps = incrSteps
		pv.showSlide(true);
		pv.postSlide();

		pv.update();

	}

  // Update presenter view nav for current slide
  $( ".menu > ul > li > ul > li" ).each(function() {
    if ($(this).text().split(". ")[0] == slidenum+1) {
      $(".menu > ul > li > ul ").hide();  //Collapse nav
      $(".menu > ul > li > ul > li").removeClass('highlighted');
      $(this).addClass('highlighted'); //Highlight current menu item
      $(this).parent().show();         //Show nav block containing current slide

      if( ! mobile() ) {
        $(this).get(0).scrollIntoView(); //Scroll so current item is at the top of the view
      }
    }
  });

	return ret;
}

function getSlideProgress()
{
	return (slidenum + 1) + '/' + slideTotal
}

function getCurrentNotes()
{
    var notes = currentSlide.find("div.notes");
    return notes;
}

function getCurrentNotesText()
{
    var notes = getCurrentNotes();
    return notes.text();
}

function setCurrentNotes()
{
    var notes = getCurrentNotesText();
    $('#notesInfo').text(notes);
    return notes;
}

function getSlidePercent()
{
	return Math.ceil(((slidenum + 1) / slideTotal) * 100)
}

function determineIncremental()
{
	incrCurr = 0
	incrCode = false
	incrElem = currentSlide.find(".incremental > ul > li")
	incrSteps = incrElem.size()
	if(incrSteps == 0) {
		// also look for commandline
		incrElem = currentSlide.find(".incremental > pre > code > code")
		incrSteps = incrElem.size()
		incrCode = true
	}
	incrElem.each(function(s, elem) {
		$(elem).addClass('incremental hidden');
	})
}

function showIncremental(incr)
{
		elem = incrElem.eq(incrCurr);
		if (incrCode && elem.hasClass('command')) {
			incrElem.eq(incrCurr).removeClass('hidden').jTypeWriter({duration:1.0});
		} else {
			incrElem.eq(incrCurr).removeClass('hidden');
		}
}

// form handling
function submitForm(form) {
  if(validateForm(form)) {
    var dataString = form.serialize();
    var formAction = form.attr("action");

    $.post(formAction, dataString, function( data ) {
      var submit = form.find("input[type=submit]")
      submit.attr("disabled", "disabled");
      submit.removeClass("dirty");
    });
  }
}

function validateForm(form) {
  var success = true;

  form.children('div.form.element.required').each(function() {
    var count  = $(this).find(':input:checked').length;
    var value  = $.trim($(this).children('input:text, textarea, select').first().val());

    // if we have no checked inputs or content, then flag it
    if(count || (value && value)) {
      $(this).closest('div.form.element').removeClass('warning');
    }
    else {
      $(this).closest('div.form.element').addClass('warning');
      success = false;
    }

  });

  return success;
}

function enableForm(element) {
  var submit = element.closest('form').find(':submit')
  submit.removeAttr("disabled");
  submit.addClass("dirty")
}

function renderFormWatcher(element) {
  var form = element.attr('title');
  var action = $('.content form#'+form).attr('action');

  element.empty();
  element.attr('action', action); // yes, we're putting an action on a div. Sue me.
  $('.content form#'+form+' div.form.element').each(function() {
    $(this).clone().appendTo(element);
  });

  renderForm(element);
  // short pause to let the form be rebuilt. Prevents screen flashing.
  setTimeout(function() { element.show(); }, 100);
  return setInterval(function() { renderForm(element); }, 3000);
}

function renderForm(form) {
  if(typeof(form) == 'string') {
    form = $('form#'+form);
  }
  var action = form.attr("action");
  $.getJSON(action, function( data ) {
    //console.log(data);
    form.children('div.form.element').each(function() {
      var key = $(this).attr('data-name');
      var sum = 0;

      $(this).find('ul > li > *').each(function() {
        $(this).parent().parent().before(this);
      });
      $(this).children('ul').each(function() {
        $(this).remove();
      });

      // replace all input widgets with spans for the bar chart
      var max   = 5;
      var style = 0;
      $(this).children(':input').each(function() {
        switch( $(this).attr('type') ) {
          case 'text':
          case 'button':
          case 'submit':
          case 'textarea':
            // we don't render these
            $(this).parent().remove();
            break;

          case 'radio':
          case 'checkbox':
            // Just render these directly and migrate the label to inside the span
            var value = $(this).attr('value');
            var label = $(this).next('label');
            var text  = label.text();

            if(text.match(/^-+$/)) {
              $(this).remove();
            }
            else{
              $(this).replaceWith('
'+text+'
');
            }
            label.remove();
            break;

          default:
            // select doesn't have a type attribute... yay html
            // poke inside to get options, then render each as a span and replace the select
            parent = $(this).parent();

            $(this).children('option').each(function() {
              var value = $(this).val();
              var text  = $(this).text();

              if(! text.match(/^-+$/)) {
                parent.append('
'+text+'
');

                // loop style counter
                style++; style %= max;
              }
            });
            $(this).remove();
            break;
        }

        // loop style counter
        style++; style %= max;
      });

      // only start counting and sizing bars if we actually have usable data
      if(data) {
        // double loop so we can handle re-renderings of the form
        $(this).find('.item').each(function() {
          var name = $(this).attr('data-value');

          if(key in data) {
            var count = data[key][name];
            if(count) { sum += count; }
          }
        });

        $(this).find('.item').each(function() {
          var name     = $(this).attr('data-value');
          var oldCount = $(this).attr('data-count');
          var oldSum   = $(this).attr('data-sum');

          if(key in data) {
            var count = data[key][name] || 0;
          }
          else {
            var count = 0;
          }

          if(count != oldCount || sum != oldSum) {
            var percent = (sum) ? ((count/sum)*100)+'%' : '0%';

            $(this).attr('data-count', count);
            $(this).attr('data-sum', sum);
            $(this).animate({width: percent});
          }
        });
      }

      $(this).addClass('rendered');
    });

  });
}

function connectControlChannel() {
  ws           = new WebSocket('ws://' + location.host + '/control');
  ws.onopen    = function()  { connected();          };
  ws.onclose   = function()  { disconnected();       }
  ws.onmessage = function(m) { parseMessage(m.data); };
}

// This exists as an intermediary simply so the presenter view can override it
function reconnectControlChannel() {
  connectControlChannel();
}

function connected() {
  console.log('Control socket opened');
  $("#feedbackSidebar button").attr("disabled", false);
  $("img#disconnected").hide();

  try {
    // If we are a presenter, then remind the server where we are
    update();
    register();
  }
  catch (e) {}
}

function disconnected() {
  console.log('Control socket closed');
  $("#feedbackSidebar button").attr("disabled", true);
  $("img#disconnected").show();

  setTimeout(function() { reconnectControlChannel() } , 5000);
}

function parseMessage(data) {
  var command = JSON.parse(data);

  if ("id" in command) {
    var guid = command['id'];
    if (lastMessageGuid != guid) {
      lastMessageGuid = guid;
    }
    else {
      return;
    }
  }

  if ("current" in command) { follow(command["current"]); }

  // Presenter messages only, so catch errors if method doesn't exist
  try {
    if ("pace"     in command) { paceFeedback(command["pace"]);     }
    if ("question" in command) {  askQuestion(command["question"]); }
  }
  catch(e) {
    console.log("Not a presenter!");
  }
}

function sendPace(pace) {
  ws.send(JSON.stringify({ message: 'pace', pace: pace}));
  feedbackActivity();
}

function askQuestion(question) {
  ws.send(JSON.stringify({ message: 'question', question: question}));
  feedbackActivity();
}

function sendFeedback(rating, feedback) {
  var slide  = $("#slideFilename").text();
  ws.send(JSON.stringify({ message: 'feedback', rating: rating, feedback: feedback, slide: slide}));
  $("input:radio[name=rating]:checked").attr('checked', false);
  feedbackActivity();
}

function feedbackActivity() {
  $("img#feedbackActivity").show();
  setTimeout(function() { $("img#feedbackActivity").hide() }, 1000);
}

function track() {
  if (mode.track) {
    var slideName    = $("#slideFilename").text();
    var slideEndTime = new Date().getTime();
    var elapsedTime  = slideEndTime - slideStartTime;

    // reset the timer
    slideStartTime = slideEndTime;

    if (elapsedTime > 1000) {
      elapsedTime /= 1000;
      ws.send(JSON.stringify({ message: 'track', slide: slideName, time: elapsedTime}));
    }
  }
}

// Open a new tab with an online code editor, if so configured
function editSlide() {
  var slide = $("span#slideFilename").text().replace(/\/\d+$/, '');
  var link  = editUrl + slide + ".md";
  window.open(link);
}

function follow(slide) {
  if (mode.follow) {
    console.log("New slide: " + slide);
    gotoSlide(slide);
  }
}

function getPosition() {
  // get the current position from the server
  ws.send(JSON.stringify({ message: 'position' }));
}

function prevStep(updatepv)
{
	var event = jQuery.Event("showoff:prev");
	$(currentSlide).find(".content").trigger(event);
	if (event.isDefaultPrevented()) {
			return;
	}

  track();

	slidenum--
	return showSlide(true, updatepv) // We show the slide fully loaded
}

function nextStep(updatepv)
{
	var event = jQuery.Event("showoff:next");
	$(currentSlide).find(".content").trigger(event);
	if (event.isDefaultPrevented()) {
			return;
	}

	track();

	if (incrCurr >= incrSteps) {
		slidenum++
		return showSlide(false, updatepv)
	} else {
		showIncremental(incrCurr);
		var incrEvent = jQuery.Event("showoff:incr");
		incrEvent.slidenum = slidenum;
		incrEvent.incr = incrCurr;
		$(currentSlide).find(".content").trigger(incrEvent);
		incrCurr++;
	}
}

function doDebugStuff()
{
	if (debugMode) {
	  $('#debugInfo').show();
		$('#slideFilename').show();
	} else {
	  $('#debugInfo').hide();
		$('#slideFilename').hide();
	}
}

function blankScreen()
{
  try {
    slaveWindow.blankScreen();
  }
  catch (e) {
    if ($('#screenblanker').length) { // if #screenblanker exists
        $('#screenblanker').slideUp('normal', function() {
            $('#screenblanker').remove();
        });
    } else {
        $('body').prepend('

');
        $('#screenblanker').slideDown();
    }
  }
}

var notesMode = false
function toggleNotes()
{
  notesMode = !notesMode
	if (notesMode) {
		$('#notesInfo').show()
		debug('notes mode on')
	} else {
		$('#notesInfo').hide()
	}
}

function toggleFollow()
{
  mode.follow = ! mode.follow;

  if(mode.follow) {
    $("#followMode").show().text('Follow Mode:');
    getPosition();
  } else {
    $("#followMode").hide();
  }
}

function debug(data)
{
	$('#debugInfo').text(data)
}

function toggleKeybinding (setting) {
  if (document.onkeydown === null || setting === 'on') {
    if (typeof presenterKeyDown === 'function') {
      document.onkeydown = presenterKeyDown;
    } else {
      document.onkeydown = keyDown;
    }
  } else {
    document.onkeydown = null;
  }
}

function keyDown(event){
  var key = event.keyCode;

  debug('keyDown: ' + key);
  // avoid overriding browser commands
  if (event.ctrlKey || event.altKey || event.metaKey) {
    return true;
  }

  switch(getAction(event)) {
    case 'DEBUG':     toggleDebug();    break;
    case 'PREV':      prevStep();       break;
    case 'NEXT':      nextStep();       break;
    case 'RELOAD':    reloadSlides();   break;
    case 'CONTENTS':  toggleContents(); break;
    case 'HELP':      toggleHelp();     break;
    case 'BLANK':     blankScreen();    break;
    case 'FOOTER':    toggleFooter();   break;
    case 'FOLLOW':    toggleFollow();   break;
    case 'NOTES':     toggleNotes();    break;
    case 'CLEAR':     removeResults();  break;
    case 'PAUSE':     togglePause();    break;
    case 'PRESHOW':   togglePreShow();  break;
    case 'EXECUTE':
      debug('executeCode');
      executeVisibleCodeBlock();
      break;
    default:
      switch (key) {
        case 48: // 0
        case 49: // 1
        case 50: // 2
        case 51: // 3
        case 52: // 4
        case 53: // 5
        case 54: // 6
        case 55: // 7
        case 56: // 8
        case 57: // 9
          // concatenate numbers from previous keypress events
          gotoSlidenum = gotoSlidenum * 10 + (key - 48);
          break;
        case 13: // enter/return
          // check for a combination of numbers from previous keypress events
          if (gotoSlidenum > 0) {
            debug('go to ' + gotoSlidenum);
            slidenum = gotoSlidenum - 1;
            showSlide(true);
            gotoSlidenum = 0;
          }
          break;
        default:
          break;
      }
      break;
    }
  return true;
}

function getAction (event) {
  return keymap[getKeyName(event)];
}

function getKeyName (event) {
  var keyName = keycode_dictionary[event.keyCode];
  if (event.shiftKey && keyName !== undefined) {
    // Check for non-alpha characters first, because no idea what toUpperCase will do to those
    if (keycode_shifted_keys[keyName] !== undefined) {
      keyName = keycode_shifted_keys[keyName];
    } else {
      keyName = keyName.toUpperCase();
    }
  }
  return keyName;
}

function toggleDebug () {
  debugMode = !debugMode;
  doDebugStuff();
}

function reloadSlides () {
  if (confirm('Are you sure you want to reload the slides?')) {
    loadSlides(loadSlidesBool, loadSlidesPrefix);
    showSlide();
  }
}

function toggleFooter() {
	$('#footer').toggle()
}

function toggleHelp () {
  $('#help').toggle();
}

function toggleContents () {
  $('#navmenu').toggle().trigger('click');
}

function swipeLeft() {
  nextStep();
}

function swipeRight() {
  prevStep();
}

function ListMenu(s)
{
	this.slide = s
	this.typeName = 'ListMenu'
	this.itemLength = 0;
	this.items = new Array();
	this.addItem = function (key, text, slide) {
		if (key.length > 1) {
			thisKey = key.shift()
			if (!this.items[thisKey]) {
				this.items[thisKey] = new ListMenu(slide)
			}
			this.items[thisKey].addItem(key, text, slide)
		} else {
			thisKey = key.shift()
			this.items[thisKey] = new ListMenuItem(text, slide)
		}
	}
	this.getList = function() {
		var newMenu = $("
")
		for(var i in this.items) {
			var item = this.items[i]
			var domItem = $("
")
			if (item.typeName == 'ListMenu') {
				choice = $("" + i + "")
				domItem.append(choice)
				domItem.append(item.getList())
			}
			if (item.typeName == 'ListMenuItem') {
				choice = $("" + item.slide + '. ' + item.textName + "")
				domItem.append(choice)
			}
			newMenu.append(domItem)
		}
		return newMenu
	}
}

function ListMenuItem(t, s)
{
	this.typeName = "ListMenuItem"
	this.slide = s
	this.textName = t
}

var removeResults = function() {
	$('.results').remove();

	// if we're a presenter, mirror this on the display window
  try { slaveWindow.removeResults() } catch (e) {};
};

var print = function(text) {
	removeResults();
	var _results = $('
').addClass('results').html('
'+$.print(text, {max_string:500})+'
');
	$('body').append(_results);
	_results.click(removeResults);

	// if we're a presenter, mirror this on the display window
  try { slaveWindow.print(text) } catch (e) {};
};

// Execute the first visible executable code block
function executeVisibleCodeBlock()
{
  var code = $('code.execute:visible')
  if (code.length > 0) {
    // make the code block available as $(this) object
    executeCode.call(code[0]);
  }
}

// determine which code handler to call and execute code sample
function executeCode() {
  var codeDiv = $(this);

  try {
    var lang = codeDiv.attr("class").match(/\blanguage-(\w+)/)[1];
    switch(lang) {
      case 'javascript':
      case 'coffeescript':
        executeLocalCode(lang, codeDiv);
        break;
      default:
        executeRemoteCode(lang, codeDiv)
        break;
    }
  }
  catch(e) {
    debug('No code block to execute: ' + codeDiv.attr('class'));
  };
}

// any code that can be run directly in the browser
function executeLocalCode(lang, codeDiv) {
  var result = null;
  var codeDiv = $(this);

  setExecutionSignal(true, codeDiv);
  setTimeout(function() { setExecutionSignal(false, codeDiv);}, 1000 );

  try {
    switch(lang) {
      case 'javascript':
        result = eval(codeDiv.text());
        break;
      case 'coffeescript':
        result = eval(CoffeeScript.compile(codeDiv.text(), {bare: true}));
        break;
      default:
        result = 'No local exec handler for ' + lang;
    }
  }
  catch(e) {
    result = e.message;
  };
  if (result != null) print(result);
}

// request the server to execute a code block by path and index
function executeRemoteCode(lang, codeDiv) {
  var slide = codeDiv.closest('div.content');
  var index = slide.find('code.execute').index(codeDiv);
  var path  = slide.attr('ref');

  setExecutionSignal(true, codeDiv);
  $.get('/execute/'+lang, {path: path, index: index}, function(result) {
    if (result != null) print(result);
    setExecutionSignal(false, codeDiv);
  });
}

// Provide visual indication that a block of code is running
function setExecutionSignal(status, codeDiv) {
  if (status === true) {
    codeDiv.addClass("executing");
  }
  else {
    codeDiv.removeClass("executing");
  }

  // if we're a presenter, mirror this on the display window
  try {
    var id    = codeDiv.closest('div.slide').attr('id');
    var index = $('div.slide#'+id+' code.execute').index(codeDiv);
    var code  = slaveWindow.$('div.slide#'+id+' code.execute').eq(index)

    if (status === true) {
      code.addClass("executing");
    }
    else {
      code.removeClass("executing");
    }
  } catch (e) {};
}

/********************
 PreShow Code
 ********************/

var preshow_stop         = null;
var preshow_secondsPer   = 8;

var preshow_current      = 0;
var preshow_images       = null;
var preshow_imagesTotal  = 0;
var preshow_des          = null;

function togglePreShow() {
  // The slave window updates this flag, which seems backwards except that the
  // slave determines when to finish preshow.
  if(preshow_stop) {
    try {
      slaveWindow.stopPreShow();
    }
    catch (e) {
      stopPreShow();
    }

  } else {
    var seconds = parseFloat(prompt("Minutes from now to start") * 60);

    try {
      slaveWindow.setupPreShow(seconds);
    }
    catch (e) {
      setupPreShow(seconds);
    }
  }
}

function setupPreShow(seconds) {
  preshow_stop = secondsFromNow(seconds);
  try { presenterView.preshow_stop = preshow_stop } catch (e) {}

  // footer styling looks icky. Hide it for now.
  $('#footer').hide();

  $.getJSON("preshow_files", false, function(data) {
    $('#preso').after("

");
    $.each(data, function(i, n) {
      if(n == "preshow.json") {
        // has a descriptions file
        $.getJSON("/file/_preshow/preshow.json", false, function(data) {
          preshow_des = data;
        })
      } else {
        $('#preshow').append('');
      }
    })
    preshow_images      = $('#preshow > img');
    preshow_imagesTotal = preshow_images.size();

    startPreShow();
  });
}

function startPreShow() {
  nextPreShowImage();

  var nextImage = secondsFromNow(preshow_secondsPer);
  var interval  = setInterval(function() {
    var now = new Date();

    if (now > preshow_stop) {
      clearInterval(interval);
      stopPreShow();
    } else {
      if (now > nextImage) {
        nextImage = secondsFromNow(preshow_secondsPer);
        nextPreShowImage();
      }
      var secondsLeft = Math.floor((preshow_stop.getTime() - now.getTime()) / 1000);
      addPreShowTips(secondsLeft);
    }
  }, 1000)
}

function addPreShowTips(secondsLeft) {
	$('#preshow_timer').text('Resuming in: ' + secondsToTime(secondsLeft));
	var des = preshow_des && preshow_des[tmpImg.attr("ref")];
	if(des) {
		$('#tips').show();
		$('#tips').text(des);
	} else {
		$('#tips').hide();
	}
}

function secondsFromNow(seconds) {
  var now = new Date();
  now.setTime(now.getTime() + seconds * 1000);
  return now;
}

function secondsToTime(sec) {
	var min = Math.floor(sec / 60);
	sec = sec - (min * 60);
	if(sec < 10) {
		sec = "0" + sec;
	}
	return min + ":" + sec;
}

function stopPreShow() {
  try { presenterView.preshow_stop = null } catch (e) {}
	preshow_stop = null;

	$('#preshow').remove();
	$('#tips').remove();
	$('#preshow_timer').remove();

	loadSlides(loadSlidesBool, loadSlidesPrefix);
}

function nextPreShowImage() {
	preshow_current += 1;
	if((preshow_current + 1) > preshow_imagesTotal) {
		preshow_current = 0;
	}

	$("#preso").empty();
	tmpImg = preshow_images.eq(preshow_current).clone();
	$(tmpImg).attr('width', '1020');
	$("#preso").html(tmpImg);
}

/********************
 End PreShow Code
 ********************/

function togglePause() {
  try {
    slaveWindow.togglePause();
  }
  catch (e) {
    $("#pauseScreen").toggle();
  }
}

/********************
 Stats page
 ********************/

function setupStats()
{
  $("#stats div#all div.detail").hide();
  $("#stats div#all div.row").click(function() {
      $(this).find("div.detail").slideToggle("fast");
  });
}

/* Is this a mobile device? */
function mobile() {
/*
  return ( navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
            || navigator.userAgent.match(/Windows Phone/i)
  );
*/

  return ( $(window).width() <= 480 )
}


text:
package IO::All::Pipe;
use strict;
use warnings;
use IO::All -base;
use IO::File;

const type => 'pipe';

sub pipe {
    my $self = shift;
    bless $self, __PACKAGE__;
    $self->name(shift) if @_;
    return $self->_init;
}

sub assert_open {
    my $self = shift;
    return if $self->is_open;
    $self->mode(shift) unless $self->mode;
    $self->open;
}

sub open {
    my $self = shift;
    $self->is_open(1);
    require IO::Handle;
    $self->io_handle(IO::Handle->new)
      unless defined $self->io_handle;
    my $command = $self->name;
    $command =~ s/(^\||\|$)//;
    my $mode = shift || $self->mode || '<';
    my $pipe_mode =
      $mode eq '>' ? '|-' :
      $mode eq '<' ? '-|' :
      $self->throw("Invalid usage mode '$mode' for pipe");
    CORE::open($self->io_handle, $pipe_mode, $command);
    $self->set_binmode;
}

my %mode_msg = (
    '>' => 'output',
    '<' => 'input',
    '>>' => 'append',
);
sub open_msg {
    my $self = shift;
    my $name = defined $self->name
      ? " '" . $self->name . "'"
      : '';
    my $direction = defined $mode_msg{$self->mode}
      ? ' for ' . $mode_msg{$self->mode}
      : '';
    return qq{Can't open pipe$name$direction:\n$!};
}

=head1 NAME

IO::All::Pipe - Pipe Support for IO::All

=head1 SYNOPSIS

See L<IO::All>.

=head1 DESCRIPTION

=head1 AUTHOR

Ingy döt Net <ingy@cpan.org>

=head1 COPYRIGHT

Copyright (c) 2006. Ingy döt Net. All rights reserved.

Copyright (c) 2004. Brian Ingerson. All rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

See http://www.perl.com/perl/misc/Artistic.html

=cut

1;