text:
MooDb.View = new Class({
    Extends: MooDb,
    options: {
        src: null
    },
    initialize: function(options) {
        this.src = options.src;
        this.parent(options);
    }
});

redpajama_set_name: RedPajamaGithub


text:
#include <et/app/application.h>
#include <et/rendering/base/materiallibrary.h>

namespace et
{

struct MaterialReloaded : public ObjectLoader
{
	ET_DECLARE_POINTER(MaterialReloaded);

	void reloadObject(LoadableObject::Pointer object, ObjectsCache&) override
	{
		Material::Pointer mtl = object;
		mtl->invalidateInstances();
		mtl->loadFromJson(loadTextFile(mtl->origin()), getFilePath(mtl->origin()));
	}
};

const std::string defaultMaterials[DefaultMaterialCount] =
{
	std::string("engine_data/materials/textured2d.json"),
	std::string("engine_data/materials/textured.json"),
	std::string("engine_data/materials/microfacet.json"),
	std::string("engine_data/materials/environment.json"),
};

void MaterialLibrary::init(RenderInterface* ren)
{
	_renderer = ren;
	_cache.startMonitoring();

	loadDefaultMaterial(DefaultMaterial::Microfacet);
}

void MaterialLibrary::shutdown()
{
	for (Material::Pointer& mat : _defaultMaterials)
		mat.reset(nullptr);

	for (Material::Pointer& mtl : _loadedMaterials)
	{
		mtl->releaseInstances();
		_cache.discard(mtl);
	}

	_loadedMaterials.clear();
}

void MaterialLibrary::reloadMaterials()
{
	for (Material::Pointer mtl : _loadedMaterials)
	{
		mtl->invalidateInstances();
		mtl->loadFromJson(loadTextFile(mtl->origin()), getFilePath(mtl->origin()));
	}
}

Material::Pointer MaterialLibrary::loadDefaultMaterial(DefaultMaterial mtl)
{
	ET_ASSERT(mtl < DefaultMaterial::Count);

	uint32_t mtlIndex = static_cast<uint32_t>(mtl);
	if (_defaultMaterials[mtlIndex].invalid())
	{
		std::string fileName = application().resolveFileName(defaultMaterials[mtlIndex]);
		_defaultMaterials[mtlIndex] = loadMaterial(fileName);
	}
	return _defaultMaterials[mtlIndex];
}

Material::Pointer MaterialLibrary::loadMaterial(const std::string& fileName)
{
	Material::Pointer material = _cache.findAnyObject(fileName);

	if (material.invalid())
	{
		material = loadMaterialFromJson(loadTextFile(fileName), getFilePath(fileName));
		material->setOrigin(fileName);

		for (const auto& cfg : material->configurations())
		{
			for (const std::string& fn : cfg.second.usedFiles)
				material->addOrigin(fn);
		}

		_cache.manage(material, MaterialReloaded::Pointer::create());
	}

	return material;
}

Material::Pointer MaterialLibrary::loadMaterialFromJson(const std::string& json, const std::string& baseFolder)
{
	Material::Pointer result = Material::Pointer::create(_renderer);
	result->loadFromJson(json, baseFolder);
	_loadedMaterials.emplace_back(result);
	return result;
}

}


text:
import { Injectable } from '@angular/core';
import { Asset } from '../shared/asset';
import { ASSETS } from '../shared/mock-assets';

@Injectable()
export class AssetService {

  	/**
	 * Constructor.
	 */
    public constructor() {
		// nothing
    }

    /**
     * Returns a list of assets.
     *
     * @return {Promise<Asset[]>} list of assets.
     */
    public getAssets(): Promise<Asset[]> {
        return Promise.resolve(ASSETS);
    }

}


text:
package ca.uhn.fhir.context;

import static org.junit.Assert.*;

import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.Patient;
import org.junit.Test;

public class RuntimeResourceDefinitionDstu3Test {

	private FhirContext ourCtx = FhirContext.forDstu3();

	@Test
	public void testAsClass() {
		assertEquals(Bundle.class, ourCtx.getResourceDefinition("Bundle").getImplementingClass(Bundle.class));
	}

	@Test(expected=ConfigurationException.class)
	public void testAsClassWrong() {
		ourCtx.getResourceDefinition("Bundle").getImplementingClass(Patient.class);
	}

}


text:
require_relative 'formats/base'
require_relative 'formats/human'
require_relative 'formats/json'

module Mulder
  class Formatter

    VALID_FORMATS = {
      'human' => Formats::Human,
      'json'  => Formats::JSON
    }

    def initialize(instances, format)
      unless VALID_FORMATS.keys.include?(format)
        raise NotImplementedError.new("Formatting as #{format} has not been implemented!")
      end

      @instances = instances
      @format    = VALID_FORMATS[format]
    end

    def output
      @format.new(@instances).output
    end
  end

end


text:
package org.tolweb.tapestry.admin;

import org.apache.tapestry.IExternalPage;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.html.BasePage;
import org.tolweb.hibernate.MediaSurvey;
import org.tolweb.tapestry.injections.ImageInjectable;
import org.tolweb.tapestry.injections.MediaSurveyInjectable;
import org.tolweb.treegrow.main.NodeImage;

public abstract class ViewMediaSurveyDetail extends BasePage implements IExternalPage, MediaSurveyInjectable, ImageInjectable {

	public String getTitle() {
		String title = "Media Survey";
		title += (getDetail() != null) ? " #" + getDetail().getId() : "";
		return title;
	}

	public abstract MediaSurvey getDetail();
	public abstract void setDetail(MediaSurvey msurvey);

	public abstract NodeImage getImage();
	public abstract void setImage(NodeImage media);

	public void activateExternalPage(Object[] args, IRequestCycle cycle) {
        Long id = (Long) args[0];
        setDetail(getMediaSurveyDAO().getMediaSurveyWithId(id));
        setImage(getImageDAO().getImageWithId(getDetail().getMediaId().intValue()));
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

Options and Preferences

    OPTIONS
    CURRENT STATUS

    Text color

    <input type=text" id="fgst" value="" disabled=true />

    Page background color (WARNING: WILL REMOVE IMAGES)

    <input type=text" id="bgst" value="" disabled=true />

    Text background color (WARNING: SLOW BUT WILL RETAIN IMAGES)

    <input type=text" id="bg2st" value="" disabled=true />

    Font Size

    <input type=text" id="fntsizst" value="" disabled=true />

      Disable/Enable Images
	  <input type=text" id="loadimgst" value="" disabled=true />

    Toggle Optimize(enabling will disable images and extra formatting to boost speed)

Fonts

reset to Default


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See W3C License http://www.w3.org/Consortium/Legal/ for more details.
--><!DOCTYPE test SYSTEM "dom1.dtd">

<test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-1" name="hc_attrhaschildnodes">
<metadata>
<title>hc_attrhaschildnodes</title>
<creator>Curt Arnold</creator>
<description>
Checks that Node.hasChildNodes() is true for an attribute with content.
</description>

<date qualifier="created">2004-01-01</date>
<!--  Attr interface  -->
<subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-637646024"/>
<!--  Node.hasChildNodes   -->
<subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-810594187"/>
</metadata>

<var name="doc" type="Document"/>
<var name="acronymList" type="NodeList"/>
<var name="testNode" type="Node"/>
<var name="attributes" type="NamedNodeMap"/>
<var name="titleAttr" type="Attr"/>
<var name="hasChildNodes" type="boolean"/>

<load var="doc" href="hc_staff" willBeModified="true"/>
<getElementsByTagName interface="Document" obj="doc" var="acronymList" tagname='"acronym"'/>
<item interface="NodeList" obj="acronymList" var="testNode" index="3"/>
<attributes obj="testNode" var="attributes"/>
<getNamedItem obj="attributes" var="titleAttr" name='"title"'/>
<hasChildNodes var="hasChildNodes" obj="titleAttr"/>
<assertTrue actual="hasChildNodes" id="hasChildrenIsTrue"/>
</test>


text:
package com.pongsor.ide;

//import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class IDE extends Frame{

	TextArea ta;

	public IDE(){
		super("compiler");

		setLayout(new BorderLayout());

		Button comBut;

		add("Center", ta = new TextArea());
		add("South", comBut = new Button("Compile it"));

		comBut.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				try{

					compile();
				}catch(Exception e){
					e.printStackTrace();
				}

			}
		});

	}

	public void compile() throws Exception{
		Process proc;

		proc= Runtime.getRuntime().exec("cmd /c javac.exe -classpath c:\\pongsor Test.java");

		System.out.println("proc is null?"+(proc==null));

		InputStream in = proc.getInputStream();
		InputStream errin = proc.getErrorStream();

		final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		final BufferedReader reader2 = new BufferedReader(new InputStreamReader(errin));

		Thread pourer1= new Thread(){
			public void run(){
				String line;
				try{
					while((line = reader.readLine())!=null){
						System.out.println(">"+line);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		};

		Thread pourer2= new Thread(){
			public void run(){
				try{
					String line;

					while((line = reader.readLine())!=null){
						System.out.println(">"+line);
					}
				}catch(Exception e){
					e.printStackTrace();
				}			}
		};

		pourer1.start();
		pourer2.start();

		in.close();
		errin.close();
	}

	public static void main(String args[]){
		IDE ide = new IDE();

		ide.setVisible(true);
	}
}


text:
@extends('layouts/newtimeline')

@section('content')

New Timeline multipurpose timeline sample

THEME COLORS

												Default

												Blue Hoki

												Blue Steel

												Orange

												Yellow Crusta

												Green Haze

												Red Sunglo

						/var/www/html
												Red Intense

												Purple Plum

												Purple Studio

LAYOUT

										 Theme Style
										<select class="theme-setting theme-setting-style form-control input-sm input-small input-inline tooltips" data-original-title="Change theme style" data-container="body" data-placement="left">
											<option value="boxed" selected="selected">Square corners</option>
											<option value="rounded">Rounded corners</option>
										</select>

										 Layout
										<select class="theme-setting theme-setting-layout form-control input-sm input-small input-inline tooltips" data-original-title="Change layout type" data-container="body" data-placement="left">
											<option value="boxed" selected="selected">Boxed</option>
											<option value="fluid">Fluid</option>
										</select>

										 Top Menu Style
										<select class="theme-setting theme-setting-top-menu-style form-control input-sm input-small input-inline tooltips" data-original-title="Change top menu dropdowns style" data-container="body" data-placement="left">
											<option value="dark" selected="selected">Dark</option>
											<option value="light">Light</option>
										</select>

										 Top Menu Mode
										<select class="theme-setting theme-setting-top-menu-mode form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) top menu" data-container="body" data-placement="left">
											<option value="fixed">Fixed</option>
											<option value="not-fixed" selected="selected">Not Fixed</option>
										</select>

										 Mega Menu Style
										<select class="theme-setting theme-setting-mega-menu-style form-control input-sm input-small input-inline tooltips" data-original-title="Change mega menu dropdowns style" data-container="body" data-placement="left">
											<option value="dark" selected="selected">Dark</option>
											<option value="light">Light</option>
										</select>

										 Mega Menu Mode
										<select class="theme-setting theme-setting-mega-menu-mode form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) mega menu" data-container="body" data-placement="left">
											<option value="fixed" selected="selected">Fixed</option>
											<option value="not-fixed">Not Fixed</option>
										</select>

							<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Modal title

							 Widget settings form goes here

							<button type="button" class="btn blue">Save changes</button>
							<button type="button" class="btn default" data-dismiss="modal">Close</button>

			@include('newtimeline/elements/breadcrumb')

										Andres Iniesta
										Replied at 7:45 PM

											<button class="btn btn-circle green-haze btn-sm dropdown-toggle" type="button" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
											Actions
											</button>

													Action

													Another action

													Something else here

													Separated link

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

										Vanessa Bond
										Posted new post at 5:10 PM

										Caulie dandelion maize lentil collard greens radish arugula sweet pepper water spinach kombu courgette lettuce. Celery coriander bitterleaf epazote radicchio shallot winter purslane collard greens spring onion squash lentil. Artichoke salad bamboo shoot black-eyed pea brussels sprout garlic kohlrabi. coriander bitterleaf epazote radicchio shallot winter purslane collard.

										 Coriander bitterleaf epazote radicchio shallot winter purslane collard. Caulie dandelion maize lentil collard greens radish arugula sweet pepper water spinach kombu courgette lettuce. Celery coriander bitterleaf epazote radicchio shallot winter purslane collard greens spring onion squash lentil. Artichoke salad bamboo shoot black-eyed pea brussels sprout garlic kohlrabi.

										 Caulie dandelion maize lentil collard greens radish arugula sweet pepper water spinach kombu courgette lettuce. Celery coriander bitterleaf epazote radicchio shallot winter purslane collard greens spring onion squash lentil. Artichoke salad bamboo shoot black-eyed pea brussels sprout garlic kohlrabi radicchio shallot winter purslane collard greens spring onion squash lentil.

										 Coriander bitterleaf epazote radicchio shallot winter purslane collard. Caulie dandelion maize lentil collard greens radish arugula sweet pepper water spinach kombu courgette lettuce. Celery coriander bitterleaf epazote radicchio shallot winter purslane collard greens spring onion squash lentil. Artichoke salad bamboo shoot black-eyed pea brussels sprout garlic kohlrabi.

										Carles Puyol
										Added office location at 2:50 PM

											<button class="btn btn-circle btn-default btn-sm dropdown-toggle" type="button" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
											Actions
											</button>

													Action

													Another action

													Something else here

													Separated link

										You have new follower
										at 11:00 PM

											<button class="btn btn-circle grey-salsa btn-sm dropdown-toggle" type="button" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
											Actions
											</button>

													Action

													Another action

													Something else here

													Separated link

									You have new follower Ivan Rakitic

										Andres Iniesta
										Replied at 7:45 PM

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

										Vanessa Bond
										Posted new post at 5:10 PM

										Caulie dandelion maize lentil collard greens radish arugula sweet pepper water spinach kombu courgette lettuce. Celery coriander bitterleaf epazote radicchio shallot winter purslane collard greens spring onion squash lentil. Artichoke salad bamboo shoot black-eyed pea brussels sprout garlic kohlrabi. coriander bitterleaf epazote radicchio shallot winter purslane collard.

										 Coriander bitterleaf epazote radicchio shallot winter purslane collard. Caulie dandelion maize lentil collard greens radish arugula sweet pepper water spinach kombu courgette lettuce. Celery coriander bitterleaf epazote radicchio shallot winter purslane collard greens spring onion squash lentil. Artichoke salad bamboo shoot black-eyed pea brussels sprout garlic kohlrabi.

										 Caulie dandelion maize lentil collard greens radish arugula sweet pepper water spinach kombu courgette lettuce. Celery coriander bitterleaf epazote radicchio shallot winter purslane collard greens spring onion squash lentil. Artichoke salad bamboo shoot black-eyed pea brussels sprout garlic kohlrabi radicchio shallot winter purslane collard greens spring onion squash lentil.

										 Coriander bitterleaf epazote radicchio shallot winter purslane collard. Caulie dandelion maize lentil collard greens radish arugula sweet pepper water spinach kombu courgette lettuce. Celery coriander bitterleaf epazote radicchio shallot winter purslane collard greens spring onion squash lentil. Artichoke salad bamboo shoot black-eyed pea brussels sprout garlic kohlrabi.

										Server Report
										Yesterday at 11:00 PM

											<button class="btn btn-circle green-haze btn-sm dropdown-toggle" type="button" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
											Actions
											</button>

													Action

													Another action

													Something else here

													Separated link

									Lorem ipsum dolore sit amet Ispect

@endsection


text:
package org.andengine.input.touch.detector;

import org.andengine.input.touch.TouchEvent;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 16:12:29 - 16.08.2010
 */
public class SurfaceScrollDetector extends ScrollDetector {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	// ===========================================================
	// Constructors
	// ===========================================================

	public SurfaceScrollDetector(final float pTriggerScrollMinimumDistance, final IScrollDetectorListener pScrollDetectorListener) {
		super(pTriggerScrollMinimumDistance, pScrollDetectorListener);
	}

	public SurfaceScrollDetector(final IScrollDetectorListener pScrollDetectorListener) {
		super(pScrollDetectorListener);
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	protected float getX(final TouchEvent pTouchEvent) {
		return pTouchEvent.getMotionEvent().getX();
	}

	@Override
	protected float getY(final TouchEvent pTouchEvent) {
		return pTouchEvent.getMotionEvent().getY();
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
namespace Utilities {
    QSqlDatabase getDatabaseConnection();
    std::string stringToLower(std::string original);
    bool validYearCheck(std::string year);

    //Class to be able to sort integers in table widget.
    //Slightly ajusted code from: http://stackoverflow.com/questions/20706819/qt-qtablewidget-adding-integers-to-table
    class TableItemSC : public QTableWidgetItem
    {
    public:
        TableItemSC(const QString & text)
            :
                QTableWidgetItem(text)
        {}

        TableItemSC(int num)
            :
                QTableWidgetItem(QString::number(num))
        {}

        bool operator< (const QTableWidgetItem &other) const
        {
            if (other.column() == 0) {
                // Compare cell data as integers id column.
                return text().toInt() < other.text().toInt();
            }
            return other.text() < text();
        }
    };

    //For connection tables.
    class TableItemConnect : public QTableWidgetItem
    {
    public:
        TableItemConnect(const QString & text)
            :
                QTableWidgetItem(text)
        {}

        TableItemConnect(int num)
            :
                QTableWidgetItem(QString::number(num))
        {}

        bool operator< (const QTableWidgetItem &other) const
        {
            if (other.column() == 0 || other.column() == 2) {
                // Compare cell data as integers for id columns.
                return text().toInt() < other.text().toInt();
            }
            return other.text() < text();
        }
    };
}

#endif // UTILITIES_H


text:
package main

import (
	"io"

	"github.com/mattn/go-colorable"
)

func getColorWriter() io.Writer {
	return colorable.NewColorableStdout()
}


text:
using System.Numerics;
using LottieUWP.Animation.Content;
using LottieUWP.Model.Animatable;
using LottieUWP.Model.Layer;

namespace LottieUWP.Model.Content
{
    public class PolystarShape : IContentModel
    {
        public enum Type
        {
            Star = 1,
            Polygon = 2
        }

        private readonly Type _type;

        public PolystarShape(string name, Type type, AnimatableFloatValue points, IAnimatableValue<Vector2?, Vector2?> position, AnimatableFloatValue rotation, AnimatableFloatValue innerRadius, AnimatableFloatValue outerRadius, AnimatableFloatValue innerRoundedness, AnimatableFloatValue outerRoundedness, bool hidden)
        {
            Name = name;
            _type = type;
            Points = points;
            Position = position;
            Rotation = rotation;
            InnerRadius = innerRadius;
            OuterRadius = outerRadius;
            InnerRoundedness = innerRoundedness;
            OuterRoundedness = outerRoundedness;
            IsHidden = hidden;
        }

        internal string Name { get; }

        internal new Type GetType()
        {
            return _type;
        }

        internal AnimatableFloatValue Points { get; }

        internal IAnimatableValue<Vector2?, Vector2?> Position { get; }

        internal AnimatableFloatValue Rotation { get; }

        internal AnimatableFloatValue InnerRadius { get; }

        internal AnimatableFloatValue OuterRadius { get; }

        internal AnimatableFloatValue InnerRoundedness { get; }

        internal AnimatableFloatValue OuterRoundedness { get; }

        internal bool IsHidden { get; }

        public IContent ToContent(ILottieDrawable drawable, BaseLayer layer)
        {
            return new PolystarContent(drawable, layer, this);
        }
    }
}


text:
package board;

import game.Player;
import pieces.*;

/**
 *
 * @author Robbert
 */
public class PlayerBoard {

	private Player player;
	private PlayerBoard leftNeighbour, rightNeighbour;
	private PlayerField[][] playerfields;

	public PlayerBoard(Player player) {
		this.player = player;

		playerfields = new PlayerField[8][4];
		for (int i = 0; i < 8; i++) {
			for (int j = 0; j < 4; j++) {
				playerfields[i][j] = new PlayerField(i, j, player.getId());
			}
		}
		for(int i = 0; i<8; i++) {
			playerfields[i][1].setPiece(new Pawn(player));
		}
		playerfields[0][0].setPiece(new Rook(player));
		playerfields[7][0].setPiece(new Rook(player));
		playerfields[1][0].setPiece(new Knight(player));
		playerfields[6][0].setPiece(new Knight(player));
		playerfields[2][0].setPiece(new Bishop(player));
		playerfields[5][0].setPiece(new Bishop(player));
		playerfields[3][0].setPiece(new Queen(player));
		playerfields[4][0].setPiece(new King(player));

	}

	public void setLeftNeighbour(PlayerBoard neighbour) {
		this.leftNeighbour = neighbour;
	}

	public void setRightNeighbour(PlayerBoard neighbour) {
		this.rightNeighbour = neighbour;
	}

	public PlayerField getFieldAt(Coordinate c) {
		return getPlayerFieldAt(c.getX(), c.getY());
	}

	public Player getPlayer() {
		return player;
	}

	/**
	 * @pre 0 <= x <= 8, 0 <= y <= 8
	 * @param x coordinate based on 8x8 board, indexed from 0 to 7
	 * @param y coordinate based on 8x8 board, indexed from 0 to 7
	 * @return field at this coordinate, may be on this player board or on either of its neighbours
	 */
	public PlayerField getPlayerFieldAt(int x, int y) {
		if (y >= 0 && y <= 3) {
			return this.playerfields[x][y];
		} else {
			if (x >= 0 && x <= 3) {
				return this.leftNeighbour.getPlayerFieldAt(7 - x, 7 - y);
			} else {
				return this.rightNeighbour.getPlayerFieldAt(7 - x, 7 - y);
			}
		}
	}

	public PlayerBoard getRightNeighbour() {
		return rightNeighbour;
	}

	public PlayerBoard getLeftNeighbour() {
		return leftNeighbour;
	}
}


text:
"""
This module defines two signals, one that initiates a purge request directly,
and another that queues the request. The queueing signal is conditionally
defined and depends on the successful import of PurgeRequestTask, which depends
on django-celery being installed.

When sending these signals from other apps, you can pass in a variety of things
as the sender for convenience. Sender can be a single URL string, a list of
URL strings, an individual Django object, or a QuerySet. If passing in an
object or QuerySet, then get_absolute_url() must be defined on every object.

Example:
>>> obj = MyObject.objects.get(pk=3)
>>> obj.get_absolute_url()
u'http://www.example.com/blahblah.html'
>>> purge_request.send(obj)

Or:
>>> queue_purge_request.send(obj)
"""
from __future__ import absolute_import

from django.dispatch import Signal

from .purge import PurgeRequest

try:
    from .tasks import PurgeRequestTask
except:
    tasks_available = False
else:
    tasks_available = True

purge_request = Signal()

def purge_request_handler(sender, **kwargs):
    pr = PurgeRequest()
    pr.add(sender.get_absolute_url())
    result = pr.purge()
    return result

purge_request.connect(purge_request_handler)

if tasks_available:
    queue_purge_request = Signal()

    def queue_purge_request_handler(sender, **kwargs):
        result = PurgeRequestTask.delay(sender)

    queue_purge_request.connect(queue_purge_request_handler)


text:
<?php

namespace Hybrid;

Factory::import('textile/classTextile', 'vendor');

use \Textile;

/**
 * Hybrid
 *
 * A set of class that extends the functionality of FuelPHP without
 * affecting the standard workflow when the application doesn't actually
 * utilize Hybrid feature.
 *
 * @package     Fuel
 * @subpackage  Hybrid
 * @category    Parser_Textile
 * @author      Ignacio Muñoz Fernandez <nmunozfernandez@gmail.com>
 */

class Parser_Textile extends Parser_Driver
{
	private $parser;

	/**
	 * Construct a new instance
	 *
	 * @access  public
	 * @return  void
	 */
	public function __construct()
	{
		$this->parser = new Textile();
	}

	/**
	 * Parse textile formatted text to HTML
	 *
	 * @access  public
	 * @param   string   $text
	 * @return  string
	 */
	public function parse($text = '')
	{
		if (empty($text) or ! strval($text))
		{
			$text = '';
		}

		return $this->parser->TextileThis($text);
	}

}


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using LogShark.Shared.LogReading.Containers;
using Newtonsoft.Json;

namespace LogShark.Shared.LogReading.Readers
{
    public class NativeJsonLogsReader : ILogReader
    {
        private readonly string _filePath;
        private readonly IProcessingNotificationsCollector _processingNotificationsCollector;
        private readonly JsonSerializerSettings _serializerSettings;
        private readonly Stream _stream;

        private static readonly Regex NumberDecimalSeparatorRepairRegex = new Regex(@"(""[^""]+""\s*:\s*\d+),(\d+)", RegexOptions.Compiled);

        public NativeJsonLogsReader(Stream stream, string filePath, IProcessingNotificationsCollector processingNotificationsCollector)
        {
            _filePath = filePath;
            _processingNotificationsCollector = processingNotificationsCollector; ;
            _stream = stream;

            _serializerSettings = new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
            };
        }

        public IEnumerable<ReadLogLineResult> ReadLines()
        {
            return new SimpleLinePerLineReader(_stream)
                .ReadLines()
                .Select(TurnStringIntoNativeJsonLogBaseEvent);
        }

        private ReadLogLineResult TurnStringIntoNativeJsonLogBaseEvent(ReadLogLineResult originalEvent)
        {
            if (!(originalEvent.LineContent is string lineString))
            {
                _processingNotificationsCollector.ReportError("Can't interpret line as string", _filePath, originalEvent.LineNumber, nameof(NativeJsonLogsReader));
                return new ReadLogLineResult(originalEvent.LineNumber, null);
            }

            try
            {
                try
                {
                    var deserializedObject = JsonConvert.DeserializeObject<NativeJsonLogsBaseEvent>(lineString, _serializerSettings);
                    return new ReadLogLineResult(originalEvent.LineNumber, deserializedObject);
                }
                catch (JsonReaderException ex) when (ex.Message.StartsWith(@"Invalid JavaScript property identifier character:"))
                {
                    // Check for and repair properties using an incorrect ',' character as a number decimal separator in unquoted properties
                    var repairedLineString = NumberDecimalSeparatorRepairRegex.Replace(lineString, "$1.$2");
                    var deserializedObject = JsonConvert.DeserializeObject<NativeJsonLogsBaseEvent>(repairedLineString, _serializerSettings);
                    _processingNotificationsCollector.ReportWarning("Invalid Json found and repaired", _filePath, originalEvent.LineNumber, nameof(NativeJsonLogsReader));
                    return new ReadLogLineResult(originalEvent.LineNumber, deserializedObject);
                }
            }
            catch (JsonException ex)
            {
                _processingNotificationsCollector.ReportError(ex.Message, _filePath, originalEvent.LineNumber, nameof(NativeJsonLogsReader));
                return new ReadLogLineResult(originalEvent.LineNumber, null);
            }
        }
    }
}


text:
package com.dmonsters.blocks;

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

import javax.annotation.Nullable;

import com.dmonsters.main.MainMod;
import com.dmonsters.main.ModBlocks;
import com.dmonsters.main.ModItems;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class MeshFence extends Block {

    public static final PropertyBool NORTH = PropertyBool.create("north");
    public static final PropertyBool EAST = PropertyBool.create("east");
    public static final PropertyBool SOUTH = PropertyBool.create("south");
    public static final PropertyBool WEST = PropertyBool.create("west");

	public MeshFence() {
		super(Material.rock);
        setUnlocalizedName(MainMod.MODID + ".meshFence");
        setRegistryName("meshFence");
        GameRegistry.registerBlock(this);
        setCreativeTab(MainMod.MOD_CREATIVETAB);
        this.setHardness(5);
        this.setResistance(5);
        this.setDefaultState(this.blockState.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)));
	}

    @SideOnly(Side.CLIENT)
    public void initModel() {
        ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory"));
    }

    public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
    {
    	if (!worldIn.isRemote) {
        	BlockPos neighborPos;
        	Block neighborBlock;
        	Boolean distReason = false;
        	//north
        	neighborPos = new BlockPos(pos.getX(), pos.getY(), pos.getZ() - 1);
        	if (worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFence ||
        			worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole) {
        		if (checkIfCanBuildInDirection(0, 0, -1, 8, pos, worldIn)) {
        			return this.getDefaultState();
        		} else {
        			distReason = true;
        		}
        	}
        	//east
        	neighborPos = new BlockPos(pos.getX() + 1, pos.getY(), pos.getZ());
        	if (worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFence ||
        			worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole) {
        		if (checkIfCanBuildInDirection(1, 0, 0, 8, pos, worldIn)) {
        			return this.getDefaultState();
        		} else {
        			distReason = true;
        		}
        	}
        	//west
        	neighborPos = new BlockPos(pos.getX() - 1, pos.getY(), pos.getZ());
        	if (worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFence ||
        			worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole) {
        		if (checkIfCanBuildInDirection(-1, 0, 0, 8, pos, worldIn)) {
        			return this.getDefaultState();
        		} else {
        			distReason = true;
        		}
        	}
        	//south
        	neighborPos = new BlockPos(pos.getX(), pos.getY(), pos.getZ() + 1);
        	if (worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFence ||
        			worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole) {
        		if (checkIfCanBuildInDirection(0, 0, 1, 8, pos, worldIn)) {
        			return this.getDefaultState();
        		} else {
        			distReason = true;
        		}
        	}
        	return Blocks.air.getDefaultState();
    	}
    	return Blocks.air.getDefaultState();
    }

    @Override
    public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) {
    	BlockPos neighborPos;
    	Block neigbourBlock;
    	//north
		if (checkIfCanBuildInDirection(0, 0, -1, 8, pos, worldIn)) {
			return;
		}
		//east
		if (checkIfCanBuildInDirection(1, 0, 0, 8, pos, worldIn)) {
			return;
		}
		//west
		if (checkIfCanBuildInDirection(-1, 0, 0, 8, pos, worldIn)) {
			return;
		}
		//south
		if (checkIfCanBuildInDirection(0, 0, 1, 8, pos, worldIn)) {
			return;
		}
		worldIn.destroyBlock(pos, true);
    }

    public void addCollisionBoxesToList(World worldIn, BlockPos pos, IBlockState state, AxisAlignedBB mask, List<AxisAlignedBB> list, Entity collidingEntity)
    {
        boolean flag = this.checkIfCanBuildInDirection(0, 0, -1, 8, pos, worldIn);
        boolean flag1 = this.checkIfCanBuildInDirection(0, 0, 1, 8, pos, worldIn);
        boolean flag2 = this.checkIfCanBuildInDirection(-1, 0, 0, 8, pos, worldIn);
        boolean flag3 = this.checkIfCanBuildInDirection(1, 0, 0, 8, pos, worldIn);
        float f = 0.375F;
        float f1 = 0.625F;
        float f2 = 0.375F;
        float f3 = 0.625F;

        if (flag)
        {
            f2 = 0.0F;
        }

        if (flag1)
        {
            f3 = 1.0F;
        }

        if (flag || flag1)
        {
            this.setBlockBounds(f, 0.0F, f2, f1, 1.5F, f3);
            super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
        }

        f2 = 0.375F;
        f3 = 0.625F;

        if (flag2)
        {
            f = 0.0F;
        }

        if (flag3)
        {
            f1 = 1.0F;
        }

        if (flag2 || flag3 || !flag && !flag1)
        {
            this.setBlockBounds(f, 0.0F, f2, f1, 1.5F, f3);
            super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
        }

        if (flag)
        {
            f2 = 0.0F;
        }

        if (flag1)
        {
            f3 = 1.0F;
        }

        this.setBlockBounds(f, 0.0F, f2, f1, 1.0F, f3);
    }

    public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos)
    {
        boolean flag = this.checkIfCanBuildInDirection(0, 0, -1, 8, pos, worldIn);
        boolean flag1 = this.checkIfCanBuildInDirection(0, 0, 1, 8, pos, worldIn);
        boolean flag2 = this.checkIfCanBuildInDirection(-1, 0, 0, 8, pos, worldIn);
        boolean flag3 = this.checkIfCanBuildInDirection(1, 0, 0, 8, pos, worldIn);
        float f = 0.375F;
        float f1 = 0.625F;
        float f2 = 0.375F;
        float f3 = 0.625F;

        if (flag)
        {
            f2 = 0.0F;
        }

        if (flag1)
        {
            f3 = 1.0F;
        }

        if (flag2)
        {
            f = 0.0F;
        }

        if (flag3)
        {
            f1 = 1.0F;
        }

        this.setBlockBounds(f, 0.0F, f2, f1, 1.0F, f3);
    }

    @Override
    public boolean isOpaqueCube()
    {
        return false;
    }

    @Override
    public boolean isFullCube()
    {
        return false;
    }

    @Override
    public boolean isPassable(IBlockAccess worldIn, BlockPos pos)
    {
        return false;
    }

    @SideOnly(Side.CLIENT)
    public EnumWorldBlockLayer getBlockLayer()
    {
        return EnumWorldBlockLayer.CUTOUT;
    }

    public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
    {
    	BlockPos neighborPos;
    	Block neighborBlock;
    	boolean north, east, west, south = false;
    	//north
    	neighborPos = new BlockPos(pos.getX(), pos.getY(), pos.getZ() - 1);
    	north = worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFence ||
    			worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole ? true : false;
    	//east
    	neighborPos = new BlockPos(pos.getX() + 1, pos.getY(), pos.getZ());
    	east = worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFence ||
    			worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole ? true : false;
    	//west
    	neighborPos = new BlockPos(pos.getX() - 1, pos.getY(), pos.getZ());
    	west = worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFence ||
    			worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole ? true : false;
    	//south
    	neighborPos = new BlockPos(pos.getX(), pos.getY(), pos.getZ() + 1);
    	south = worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFence ||
    			worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole ? true : false;

    	return state.withProperty(NORTH, north).withProperty(EAST, east).withProperty(WEST, west).withProperty(SOUTH, south);
    }

    private boolean checkIfCanBuildInDirection(int x, int y, int z, int dist, BlockPos pos, IBlockAccess worldIn) {
    	BlockPos neighborPos = pos;
    	for (int i = 0; i < dist; i++) {
    		neighborPos = new BlockPos(neighborPos.getX() + x, neighborPos.getY() + y, neighborPos.getZ() + z);
        	if (worldIn.getBlockState(neighborPos).getBlock() == ModBlocks.meshFencePole) {
        		return true;
        	} else if (worldIn.getBlockState(neighborPos).getBlock() != ModBlocks.meshFence) {
        		return false;
        	}
    	}
    	return false;
    }

    protected BlockState createBlockState()
    {
        return new BlockState(this, new IProperty[] {NORTH, EAST, WEST, SOUTH});
    }

    public int getMetaFromState(IBlockState state)
    {
        return 0;
    }
}


text:
"""deployment scripts for researchcompendia
with credit to scipy-2014 and researchcompendia fabric.py

fab <deploy|provision>[:<git ref>]

provision: provisions a box to run the site. is not idempotent. do not rerun.
deploy: deploys a update to the site. if no git ref is provided, deploys HEAD.
git ref: a git branch, hash, tag

provision: provisions a new box.

example usages:

deploy new version of the site with an updated virtualenv.
$ fab provision:1.1.1

WARNINGS

This does not set up elasticsearch or the cron jobs for indexing and running
the link checker.

deploy has never been properly tested

provision is no longer properly tested, Carl wanted an vagrant example
and I don't have time to finish this today. It's a start for him to pick
up, unless I get to it first.

"""
import string, random
from os.path import join, dirname, abspath
from fabric.api import run, task, env, cd, sudo, local
from fabric.contrib.files import sed, append
from fabtools import require, supervisor, postgres, files
from fabtools.files import upload_template
import fabtools

from fabtools.vagrant import vagrant

FAB_HOME = dirname(abspath(__file__))
TEMPLATE_DIR = join(FAB_HOME, 'templates')

# shourt name - user, group, db name, supervised_process...
SITE_NAME = "rt1"
# public facing name (connonical?  fqdn?)
SERVER_NAME='richard.test1.nextdayvideo.com'

try:
    from secrets import admins
except:
    # you will need to run ./manage.py createsuperuser
    admins = []

SITE_CLONE_NAME = SITE_NAME

SITE_DIR = join('/', 'srv', SITE_NAME)
SITE_SETTINGS = {
    'site_name': SITE_NAME,
    'repo_dir': join(SITE_DIR, SITE_NAME),
    'setup_args': '.[postgresql]',
    'django_site_url': 'http://{0}'.format(SERVER_NAME),
    'repo': 'https://github.com/willkg/richard.git',
    'user': SITE_NAME,
    'group': SITE_NAME,
    'virtualenv': 'venv',
    'supervised_process': SITE_NAME,
    'settings_module': '{0}.richard.settings'.format(SITE_NAME) ,
    'wsgi_module': '{0}.richard.wsgi'.format(SITE_NAME),
    'server_name': SERVER_NAME,
    'nginx_site': SITE_NAME,
    'gunicorn_port':'8001',
    'admins':admins
}

env.disable_known_hosts = True

env.hosts = ['root@'+SERVER_NAME]
# env.hosts = [SERVER_NAME+':2222']
#env.hosts = ['127.0.0.1:2222']
#env.hosts = ['root@test.pyohio.nextdayvideo.com']

@task
def uname():
    """call uname to check that we can do a simple command
    """
    run('uname -a')

@task
def deploy(version_tag=None):
    """deploys a updated version of the site

    version_tag: a git tag, defaults to HEAD
    """
    supervised_process = SITE_SETTINGS['supervised_process']

    #dust()
    stop(supervised_process)
    update(commit=version_tag)
    setup()
    collectstatic()
    start(supervised_process)
    #undust()

@task
def stop(process_name):
    """stops supervisor process
    """
    supervisor.stop_process(process_name)

@task
def start(process_name):
    """starts supervisor process
    """
    supervisor.start_process(process_name)

@task
def update(commit='origin/master'):
    repo_dir = SITE_SETTINGS['repo_dir']
    with cd(repo_dir):
        su('git fetch')
        su('git checkout %s' % commit)

@task
def migrate(app):
    """ run south migration on specified app
    """
    with cd(SITE_SETTINGS['repo_dir']):
        vsu('./manage.py migrate %s' % app)

@task
def provision(commit='origin/master'):
    """Run only once to provision a new host.
    This is not idempotent. Only run once!
    """
    install_packages()
    install_python_packages()
    lockdown_nginx()
    # lockdown_ssh() # locks you out if you don't have keys setup
    setup_database()
    setup_site_user()
    setup_site_root()
    provision_django()
    provision_django_settings()
    syncdb()
    create_superuser()
    collectstatic()
    setup_nginx_site()
    setup_supervisor()

    print("")
    print('handy debugging stuff:')
    print('127.0.0.1    localhost {server_name}'.format(
        **SITE_SETTINGS))
    print('curl http://{server_name}:8081'.format(
        **SITE_SETTINGS))
        # not the gunicorn_port. this is the port mapped to 80 by vagrant
    print('curl --head http://{server_name}:8081'.format(
        **SITE_SETTINGS))
    print("sudo supervisorctl restart {0}".format(SITE_NAME))
    print('cat {0}/logs/gunicorn.log'.format(SITE_DIR))

    activate = join(
            SITE_DIR, SITE_SETTINGS['virtualenv'], 'bin', 'activate')
    print('cd {repo_dir}'.format(**SITE_SETTINGS))
    print( 'sudo su {user} -c "source {activate} && ./manage.py shell"'.format(activate=activate, **SITE_SETTINGS))

def setup_nginx_site():
    nginx_site = SITE_NAME
    static_dir = SITE_SETTINGS['repo_dir']
    upload_template('nginx_site.conf',
        '/etc/nginx/sites-available/%s' % nginx_site,
        context={
            'server_name': SITE_SETTINGS['server_name'],
            'gunicorn_port': SITE_SETTINGS['gunicorn_port'],
            'path_to_static': join(static_dir, 'static'),
            'site_dir': SITE_DIR,
            'static_parent': '%s/' % static_dir,
        },
        use_jinja=True, use_sudo=True, template_dir=TEMPLATE_DIR)
    require.nginx.enabled(nginx_site)

def setup_supervisor():
    supervised_process = SITE_SETTINGS['supervised_process']
    bindir = join(SITE_DIR, 'bin')
    logdir = join(SITE_DIR, 'logs')
    upload_template('supervised_site.conf',
        '/etc/supervisor/conf.d/%s.conf' % supervised_process,
        context={
            'supervised_process': supervised_process,
            'command': join(bindir, 'gunicorn.sh'),
            'user': SITE_SETTINGS['user'],
            'group': SITE_SETTINGS['group'],
            'logfile': join(logdir, 'gunicorn.log'),
            'site_dir': bindir,
        },
        use_jinja=True, use_sudo=True, template_dir=TEMPLATE_DIR)
    supervisor.update_config()

def lockdown_nginx():
    # don't share nginx version in header and error pages
    sed('/etc/nginx/nginx.conf', '# server_tokens off;', 'server_tokens off;', use_sudo=True)
    sudo('service nginx restart')

def lockdown_ssh():
    sed('/etc/ssh/sshd_config', '^#PasswordAuthentication yes', 'PasswordAuthentication no', use_sudo=True)
    append('/etc/ssh/sshd_config', ['UseDNS no', 'PermitRootLogin no', 'DebianBanner no', 'TcpKeepAlive yes'], use_sudo=True)
    sudo('service ssh restart')

def clone_site():
    with cd(SITE_DIR):
        su('git clone -q %s %s' % (SITE_SETTINGS['repo'], SITE_CLONE_NAME))
    with cd(join(SITE_DIR, SITE_CLONE_NAME)):
        su('touch __init__.py') # janky way to treat the SITE_CLONE_NAME like a module name

def provision_django():
    with cd(SITE_DIR):
        su('virtualenv {0}'.format(SITE_SETTINGS['virtualenv']))
    clone_site()
    setup()

@task
def provision_django_settings():
    settings_local = join(SITE_DIR, SITE_SETTINGS['repo_dir'],
            'richard', 'settings_local.py')

    secret_key = ''.join(random.choice(string.ascii_letters +
                string.digits + '~@#%^&*-_') for x in range(64))

    upload_template('settings_local.py',
        settings_local,
        context={
            'site_name': SITE_NAME,
            'db_name': SITE_NAME,
            'secret_key': secret_key,
            'admins': SITE_SETTINGS['admins'],
            'server_name': SITE_SETTINGS['server_name'],
        },
        use_jinja=True, use_sudo=True, template_dir=TEMPLATE_DIR)

    sudo('chown {user}:{group} {file}'.format(
        file=settings_local, **SITE_SETTINGS ))

def syncdb():
    with cd(SITE_SETTINGS['repo_dir']):
        vsu('./manage.py syncdb --noinput --migrate')

@task
def create_superuser():
    """ create admin user.
    richard uses Persona, which is tied to email.
    """
    with cd(SITE_SETTINGS['repo_dir']):
        for user,email in SITE_SETTINGS['admins']:
            vsu('./manage.py createsuperuser --noinput --username {user} --email {email}'.format(user=user,email=email))

@task
def setup(virtualenv='venv'):

    with cd(SITE_SETTINGS['repo_dir']):
        # TODO: figure out how to escape .[postgresql], I keep getting: invalid command name
        #vsu("python setup.py '%s'" % SITE_SETTINGS['setup_args'], virtualenv=virtualenv)
        vsu("python setup.py install", virtualenv=virtualenv)
        vsu("pip install gunicorn", virtualenv=virtualenv)
        vsu("pip install psycopg2", virtualenv=virtualenv)

def setup_database():
    user = SITE_SETTINGS['user']
    require.postgres.server()
    # TODO: fabtools.require.postgres.user did not allow a user with no pw prompt? see if there is a better way
    if not postgres.user_exists(user):
        su('createuser -S -D -R -w %s' % user, 'postgres')
    if not postgres.database_exists(user):
        require.postgres.database(user, user, encoding='UTF8', locale='en_US.UTF-8')
    # TODO: change default port
    # port = 5432
    # /etc/postgresql/9.1/main/postgresql.conf

def setup_site_user():
    user = SITE_SETTINGS['user']
    if not fabtools.user.exists(user):
        sudo('useradd -s/bin/bash -d/home/%s -m %s' % (user, user))

def setup_site_root():
    bindir = join(SITE_DIR, 'bin')
    user = SITE_SETTINGS['user']
    sudo('mkdir -p %s' % SITE_DIR)
    sudo('chown %s:%s %s' % (user, user, SITE_DIR))

    with cd(SITE_DIR):
        su('mkdir -p logs bin {0}'.format(SITE_SETTINGS['virtualenv']))

    with cd(bindir):
        setup_gunicorn_script()
        sudo('chown -R %s:%s %s' % (user, user, SITE_DIR))
        su('chmod +x gunicorn.sh')

def setup_gunicorn_script():
    bindir = join(SITE_DIR, 'bin')
    python_path = SITE_SETTINGS['repo_dir']

    upload_template('gunicorn.sh',
        join(bindir, 'gunicorn.sh'),
        context={
            'settings_module': SITE_SETTINGS['settings_module'],
            'path_to_virtualenv': join(SITE_DIR, SITE_SETTINGS['virtualenv']),
            'user': SITE_SETTINGS['user'],
            'group': SITE_SETTINGS['group'],
            'site_dir': SITE_DIR,
            'wsgi_module': SITE_SETTINGS['wsgi_module'],
            'gunicorn_port': SITE_SETTINGS['gunicorn_port'],
            'python_path': python_path,
        },
        use_jinja=True, use_sudo=True, template_dir=TEMPLATE_DIR)

def install_packages():
    require.deb.uptodate_index(max_age={'hour': 1})
    require.deb.packages([
        'python-software-properties',
        'python-dev',
        'build-essential',
        'libxml2',
        'libxslt-dev',
        'git',
        'nginx-extras',
        'libxslt1-dev',
        'supervisor',
        'postgresql',
        'postgresql-server-dev-9.1',
        # useful but not strictly required
        'tig',
        'vim',
        'curl',
        'tmux',
        'htop',
        'ack-grep',
    ])

def install_python_packages():
    sudo('wget --quiet https://raw.github.com/pypa/pip/master/contrib/get-pip.py')
    sudo('python get-pip.py')
    # install global python packages
    require.python.packages([
        'virtualenvwrapper',
        'setproctitle',
        'wheel',
    ], use_sudo=True)

def su(cmd, user=None):
    if user is None:
        user = SITE_SETTINGS['user']
    sudo("su %s -c '%s'" % (user, cmd))

def vsu(cmd, virtualenv='venv', user=None):
    if user is None:
        user = SITE_SETTINGS['user']
    activate = join(SITE_DIR, virtualenv, 'bin', 'activate')
    sudo("su {0} -c 'source {1}; {2}'".format(user, activate, cmd))

def collectstatic():
    with cd(SITE_SETTINGS['repo_dir']):
        vsu('./manage.py collectstatic --noinput')

def randomstring(n):
    return ''.join(random.choice(string.ascii_letters + string.digits + '~@#%^&*-_') for x in range(n))


text:
void NTP1TxIn::setPrevout(const NTP1OutPoint& value) { prevout = value; }

NTP1OutPoint NTP1TxIn::getPrevout() const { return prevout; }

void NTP1TxIn::setSequence(const uint64_t& value) { nSequence = value; }

NTP1TxIn::NTP1TxIn() { nSequence = std::numeric_limits<unsigned int>::max(); }

void NTP1TxIn::setNull()
{
    prevout.setNull();
    scriptSigHex.clear();
    nSequence = 0;
    tokens.clear();
}

void NTP1TxIn::importJsonData(const json_spirit::Value& parsedData)
{
    try {
        std::string txid_str = NTP1Tools::GetStrField(parsedData.get_obj(), "txid");
        uint256     txid;
        txid.SetHex(txid_str);
        nSequence                 = NTP1Tools::GetUint64Field(parsedData.get_obj(), "sequence");
        unsigned int        index = NTP1Tools::GetUint64Field(parsedData.get_obj(), "vout");
        json_spirit::Object scriptSigJsonObj =
            NTP1Tools::GetObjectField(parsedData.get_obj(), "scriptSig");
        prevout      = NTP1OutPoint(txid, index);
        scriptSigHex = NTP1Tools::GetStrField(scriptSigJsonObj, "hex");
        json_spirit::Array tokens_list;
        if (!json_spirit::find_value(parsedData.get_obj(), "tokens").is_null()) {
            tokens_list = NTP1Tools::GetArrayField(parsedData.get_obj(), "tokens");
        }
        tokens.clear();
        tokens.resize(tokens_list.size());
        for (unsigned long i = 0; i < tokens_list.size(); i++) {
            tokens[i].importJsonData(tokens_list[i]);
        }
    } catch (std::exception& ex) {
        NLog.write(b_sev::err, "{}", ex.what());
        throw;
    }
}

json_spirit::Value NTP1TxIn::exportDatabaseJsonData() const
{
    json_spirit::Object root;

    root.push_back(json_spirit::Pair("prevout", prevout.exportDatabaseJsonData()));
    root.push_back(json_spirit::Pair("scriptSig", scriptSigHex));
    root.push_back(json_spirit::Pair("sequence", nSequence));
    json_spirit::Array tokensArray;

    for (long i = 0; i < static_cast<long>(tokens.size()); i++) {
        tokensArray.push_back(tokens[i].exportDatabaseJsonData());
    }
    root.push_back(json_spirit::Pair("tokens", json_spirit::Value(tokensArray)));

    return json_spirit::Value(root);
}

void NTP1TxIn::importDatabaseJsonData(const json_spirit::Value& data)
{
    setNull();

    prevout.importDatabaseJsonData(NTP1Tools::GetObjectField(data.get_obj(), "prevout"));
    scriptSigHex                   = NTP1Tools::GetStrField(data.get_obj(), "scriptSig");
    nSequence                      = NTP1Tools::GetUint64Field(data.get_obj(), "sequence");
    json_spirit::Array tokens_list = NTP1Tools::GetArrayField(data.get_obj(), "tokens");
    tokens.clear();
    tokens.resize(tokens_list.size());
    for (unsigned long i = 0; i < tokens_list.size(); i++) {
        tokens[i].importDatabaseJsonData(tokens_list[i]);
    }
}
void NTP1TxIn::importJsonData(const std::string& data)
{
    try {
        json_spirit::Value parsedData;
        json_spirit::read_or_throw(data, parsedData);
        importJsonData(parsedData);
    } catch (std::exception& ex) {
        NLog.write(b_sev::err, "{}", ex.what());
        throw;
    }
}

NTP1OutPoint NTP1TxIn::getOutPoint() const { return prevout; }

std::string NTP1TxIn::getScriptSigHex() const { return scriptSigHex; }

void NTP1TxIn::setScriptSigHex(const std::string& s) { scriptSigHex = s; }

uint64_t NTP1TxIn::getSequence() const { return nSequence; }

const NTP1TokenTxData& NTP1TxIn::getToken(unsigned long index) const { return tokens[index]; }

unsigned long NTP1TxIn::getNumOfTokens() const { return tokens.size(); }

void NTP1TxIn::__addToken(const NTP1TokenTxData& token) { tokens.push_back(token); }


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:gravity="center_vertical"
    android:orientation="vertical">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
                <TextView
                    android:id="@+id/title_text_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:textStyle="bold" >
                </TextView>
                <TextView
                    android:id="@+id/date_text_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:textStyle="bold" >
                </TextView>
        </LinearLayout>

        <TextView
            android:id="@+id/description_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="12sp" >
        </TextView>

</LinearLayout>


text:
<html>
<head>
</head>
<body>
<form id="upload-form" action="upload.php" method="post" enctype="multipart/form-data" >

  <input type="file" id="upload" name="upload" /> <br />

  <input type="submit" value="Upload" />

</form>
</body>
</html>


text:
> JSON Web Token Authentication for Laravel

[![Build Status](http://img.shields.io/travis/tymondesigns/jwt-auth/master.svg?style=flat-square)](https://travis-ci.org/tymondesigns/jwt-auth)
[![Scrutinizer Code Quality](http://img.shields.io/scrutinizer/g/tymondesigns/jwt-auth.svg?style=flat-square)](https://scrutinizer-ci.com/g/tymondesigns/jwt-auth/)
[![SensioLabs Insight](https://img.shields.io/sensiolabs/i/ba600082-7869-4ea8-b877-0bf6a86d4988.svg?style=flat-square)](https://insight.sensiolabs.com/projects/ba600082-7869-4ea8-b877-0bf6a86d4988)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/tymondesigns/jwt-auth/develop.svg?style=flat-square)](https://scrutinizer-ci.com/g/tymondesigns/jwt-auth/code-structure)
[![StyleCI](https://styleci.io/repos/23680678/shield?style=flat-square)](https://styleci.io/repos/23680678)
[![HHVM](https://img.shields.io/hhvm/tymon/jwt-auth.svg?style=flat-square)](http://hhvm.h4cc.de/package/tymon/jwt-auth)
[![Latest Version](http://img.shields.io/packagist/v/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth)
[![Latest Dev Version](https://img.shields.io/packagist/vpre/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth#dev-develop)
[![Monthly Downloads](https://img.shields.io/packagist/dm/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth)

See the [WIKI](https://github.com/tymondesigns/jwt-auth/wiki) for documentation

## License

The MIT License (MIT)

Copyright (c) 2014 Sean Tymon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

[![Gratipay](https://img.shields.io/gratipay/tymondesigns.svg?style=flat-square)](https://gratipay.com/~tymondesigns)


text:
package com.baidu.bjf.remoting.protobuf.enumeration;

import java.io.IOException;

import org.junit.Assert;
import org.junit.Test;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.baidu.bjf.remoting.protobuf.enumeration.EnumClass.EnumClassInternal;

/**
 * Test class for enum type
 *
 * @author xiemalin
 * @since 1.4.0
 */
public class EnumClassTest {

    @Test
    public void testEnum() throws IOException {

        Codec<EnumPOJOClass> codec = ProtobufProxy.create(EnumPOJOClass.class);
        EnumPOJOClass ec = new EnumPOJOClass();
        ec.enumAttr = EnumAttrPOJO.INT;

        byte[] bytes = codec.encode(ec);

        EnumPOJOClass decode = codec.decode(bytes);
        Assert.assertEquals(EnumAttrPOJO.INT, decode.enumAttr);

        byte[] byteArray = EnumClassInternal.newBuilder().setStatus(
                com.baidu.bjf.remoting.protobuf.enumeration.EnumClass.EnumAttr.INT).build().toByteArray();
        Assert.assertArrayEquals(bytes, byteArray);

        EnumClassInternal enumClass = com.baidu.bjf.remoting.protobuf.enumeration.EnumClass.EnumClassInternal.parseFrom(bytes);

        Assert.assertEquals(com.baidu.bjf.remoting.protobuf.enumeration.EnumClass.EnumAttr.INT, enumClass.getStatus());
    }

    @Test
    public void testEnum2() throws IOException {

        Codec<EnumPOJOClass2> codec = ProtobufProxy.create(EnumPOJOClass2.class);
        EnumPOJOClass2 ec = new EnumPOJOClass2();
        ec.setEnumAttr(EnumAttrPOJO.INT);

        byte[] bytes = codec.encode(ec);
        EnumPOJOClass2 decode = codec.decode(bytes);
        Assert.assertEquals(EnumAttrPOJO.INT, decode.getEnumAttr());

        byte[] byteArray = EnumClassInternal.newBuilder().setStatus(
                com.baidu.bjf.remoting.protobuf.enumeration.EnumClass.EnumAttr.INT).build().toByteArray();
        Assert.assertArrayEquals(bytes, byteArray);
        EnumClassInternal enumClass = com.baidu.bjf.remoting.protobuf.enumeration.EnumClass.EnumClassInternal.parseFrom(bytes);

        Assert.assertEquals(com.baidu.bjf.remoting.protobuf.enumeration.EnumClass.EnumAttr.INT, enumClass.getStatus());
    }
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
    switch (arguments.length) {
        case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
        case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
        case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
    }
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var annotations_1 = require('angular2/src/core/annotations/annotations');
var decorators_1 = require('angular2/src/core/annotations/decorators');
var core_1 = require('angular2/core');
var collection_1 = require('angular2/src/facade/collection');
var lang_1 = require('angular2/src/facade/lang');
var dom_adapter_1 = require('angular2/src/dom/dom_adapter');
var router_1 = require('./router');
var location_1 = require('./location');
/**
 * The RouterLink directive lets you link to specific parts of your app.
 *
 *
 * Consider the following route configuration:

 * ```
 * @RouteConfig({
 *   path: '/user', component: UserCmp, as: 'user'
 * });
 * class MyComp {}
 * ```
 *
 * When linking to a route, you can write:
 *
 * ```
 * <a router-link="user">link to user component</a>
 * ```
 *
 * @exportedAs angular2/router
 */
var RouterLink = (function () {
    function RouterLink(elementRef, _router, _location) {
        this._router = _router;
        this._location = _location;
        this._domEl = elementRef.domElement;
        this._params = collection_1.StringMapWrapper.create();
    }
    Object.defineProperty(RouterLink.prototype, "route", {
        set: function (changes) { this._route = changes; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(RouterLink.prototype, "params", {
        set: function (changes) { this._params = changes; },
        enumerable: true,
        configurable: true
    });
    RouterLink.prototype.onClick = function () {
        this._router.navigate(this._navigationHref);
        return false;
    };
    RouterLink.prototype.onAllChangesDone = function () {
        if (lang_1.isPresent(this._route) && lang_1.isPresent(this._params)) {
            this._navigationHref = this._router.generate(this._route, this._params);
            this._visibleHref = this._location.normalizeAbsolutely(this._navigationHref);
            // Keeping the link on the element to support contextual menu `copy link`
            // and other in-browser affordances.
            dom_adapter_1.DOM.setAttribute(this._domEl, 'href', this._visibleHref);
        }
    };
    RouterLink = __decorate([
        decorators_1.Directive({
            selector: '[router-link]',
            properties: ['route: routerLink', 'params: routerParams'],
            lifecycle: [annotations_1.onAllChangesDone],
            host: { '(^click)': 'onClick()' }
        }),
        __metadata('design:paramtypes', [core_1.ElementRef, router_1.Router, location_1.Location])
    ], RouterLink);
    return RouterLink;
})();
exports.RouterLink = RouterLink;
exports.__esModule = true;
//# sourceMappingURL=router_link.js.map


text:
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;

namespace MSBuildCustomTasks.Common
{

    /// <summary>
    /// Ini file operation
    /// </summary>
    public class IniFileOperation : IIniFileOperation
    {
        [DllImport("kernel32", SetLastError = true)]
        private static extern int WritePrivateProfileString(string section, string key,string val,string filePath);
        [DllImport("kernel32", SetLastError = true)]
        private static extern int GetPrivateProfileString(string section, string key,string def, StringBuilder retVal, int size,string filePath);

        public string Read(string path, string section, string key)
        {
            var value = new StringBuilder(255);
            GetPrivateProfileString(section, key, "", value, 255, path);
            var errorCode = Marshal.GetLastWin32Error();
            if(errorCode != 0)
            {
                throw new Win32Exception(errorCode, string.Format("Failed to read '\"{0}\"[{1}]{2}'", path, section, key));
            }
            return value.ToString();
        }

        public void Write(string path, string section, string key, string value)
        {
            WritePrivateProfileString(section,key,value,path);
            var errorCode = Marshal.GetLastWin32Error();
            if(errorCode != 0)
            {
                throw new Win32Exception(errorCode, string.Format("Failed to write '\"{0}\"[{1}]{2}={3}'", path, section, key, value));
            }
        }
    }
}


text:
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

    <title>PHPXRef 0.7.1 : Unnamed Project : Function Reference: realpath()</title>
    <link rel="stylesheet" href="../sample.css" type="text/css">
    <link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">

    <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">

            [ Index ]

PHP Cross Reference of Unnamed Project

[ Show Explorer ]
[ Hide Navbar ]

[Top level directory]

title

Body

[close]

Function and Method Cross Reference

realpath()

This function is provided by PHP directly.

You can lookup the documentation for it here:
  [php.net] [us2.php.net] [uk.php.net] [au.php.net] [de.php.net]

Referenced 21 times:

/application/config/autoload.php  ->  line 41

/tests/run.php  ->  line 16

/application/helpers/MY_file_helper.php  ->  line 30

/application/config/config.php  ->  line 5

/application/config/config.php  ->  line 6

/bonfire/codeigniter/libraries/Upload.php  ->  line 708

/bonfire/codeigniter/libraries/Upload.php  ->  line 710

/bonfire/codeigniter/libraries/Image_lib.php  ->  line 176

/bonfire/codeigniter/libraries/Image_lib.php  ->  line 178

/bonfire/codeigniter/libraries/Image_lib.php  ->  line 218

/bonfire/codeigniter/libraries/Image_lib.php  ->  line 220

/bonfire/codeigniter/libraries/Image_lib.php  ->  line 321

/bonfire/codeigniter/helpers/file_helper.php  ->  line 186

/bonfire/codeigniter/helpers/file_helper.php  ->  line 238

/bonfire/helpers/application_helper.php  ->  line 667

/public/index.php  ->  line 192

/public/index.php  ->  line 194

/tests/simpletest/test/eclipse_test.php  ->  line 17

/bonfire/codeigniter/helpers/path_helper.php  ->  line 49

/bonfire/codeigniter/helpers/path_helper.php  ->  line 51

/bonfire/modules/translate/helpers/languages_helper.php  ->  line 94

Generated: Thu Oct 23 19:15:14 2014
	Cross-referenced by PHPXref 0.7.1


text:
package com.yunkuent.sdk.data;

import com.gokuai.base.ReturnResult;

public class YunkuException extends Exception {

    private ReturnResult result;

    public YunkuException(String message) {
        super(message);
    }

    public YunkuException(Throwable cause) {
        super(cause);
    }

    public YunkuException(String message, ReturnResult result) {
        super(message);
        this.result = result;
    }

    public ReturnResult getReturnResult() {
        return this.result;
    }
}


text:
package amberdb.version;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import amberdb.graph.AmberEdge;

public class TEdgeDiff extends TElementDiff {

    Map<String, Object[]> edgeAttributes = new HashMap<>();

    public TEdgeDiff(Long txn1, Long txn2, TEdge e1, TEdge e2) {
        super(txn1, txn2, e1, e2);

        // edge specific attributes
        switch (transition) {
        case NEW:
            edgeAttributes.put("label", new Object[] {e2.getLabel() });
            edgeAttributes.put("inVertexId", new Object[] { e2.inId });
            edgeAttributes.put("outVertexId", new Object[] { e2.outId });
            edgeAttributes.put(AmberEdge.SORT_ORDER_PROPERTY_NAME, new Object[] { e2.order });
            break;

        case DELETED:
            edgeAttributes.put("label", new Object[] { e1.getLabel() });
            edgeAttributes.put("inVertexId", new Object[] { e1.inId });
            edgeAttributes.put("outVertexId", new Object[] { e1.outId });
            edgeAttributes.put(AmberEdge.SORT_ORDER_PROPERTY_NAME, new Object[] { e1.order });
            break;

        case MODIFIED:
            edgeAttributes.put("label", (e1.getLabel().equals(e2.getLabel())) ? new Object[] { e1.getLabel() } : new Object[] { e1.getLabel(), e2.getLabel() });
            edgeAttributes.put("inVertexId", (e1.inId.equals(e2.inId)) ? new Object[] { e1.inId } : new Object[] { e1.inId, e2.inId });
            edgeAttributes.put("outVertexId", (e1.outId.equals(e2.outId)) ? new Object[] { e1.outId } : new Object[] { e1.outId, e2.outId });
            edgeAttributes.put(AmberEdge.SORT_ORDER_PROPERTY_NAME, (e1.order.equals(e2.order)) ? new Object[] { e1.order } : new Object[] { e1.order, e2.order });
            break;

        case UNCHANGED:
            TEdge e = null;
            if (e1 != null) e = e1;
            if (e2 != null) e = e2;
            if (e != null) {
                edgeAttributes.put("label", new Object[] { e.getLabel() });
                edgeAttributes.put("inVertexId", new Object[] { e.inId });
                edgeAttributes.put("outVertexId", new Object[] { e.outId });
                edgeAttributes.put(AmberEdge.SORT_ORDER_PROPERTY_NAME, new Object[] { e.order });
            } else {
                edgeAttributes.put("label", new Object[] { null });
                edgeAttributes.put("inVertexId", new Object[] { null });
                edgeAttributes.put("outVertexId", new Object[] { null });
                edgeAttributes.put(AmberEdge.SORT_ORDER_PROPERTY_NAME, new Object[] { null });
            }
            break;
        }
    }

    @Override
    public Object getProperty(String propertyName) throws TDiffException {
        switch (propertyName) {
        case "label" :
        case "inVertexId" :
        case "outVertexId" :
        case AmberEdge.SORT_ORDER_PROPERTY_NAME :
            return edgeAttributes.get(propertyName);
        }
        return super.getProperty(propertyName);
    }

    public Map<String, Object[]> getDiffMap() {
        Map<String, Object[]> diffMap = super.getDiffMap();
        for (String key : edgeAttributes.keySet()){
        	Object[] values = edgeAttributes.get(key);
            switch (transition) {
            case NEW:
                diffMap.put(key, new Object[] {null, values[0]});
                break;
            case DELETED:
                diffMap.put(key, new Object[] {values[0], null});
                break;
            case MODIFIED:
                if (values.length == 2){
                    diffMap.put(key, values);
                }else if(values.length == 1){
                    diffMap.put(key, new Object[] {values[0], values[0]});
                }
                break;
            case UNCHANGED:
                diffMap.put(key, new Object[] {values[0], values[0]});
                break;
            }
        }
        return diffMap;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(super.toString() + "\n");
        for (String propName : edgeAttributes.keySet()) {
            sb.append(propName + ": ");
            Object[] objArr = (Object[]) getProperty(propName);
            sb.append((objArr[0] != null) ? objArr[0].toString() : "<null>");
            if (objArr.length > 1) {
                sb.append(" -> ");
                sb.append((objArr[1] != null) ? objArr[1].toString() : "<null>");
            }
            sb.append('\n');
        }
        sb.setLength(sb.length() - 1);
        return sb.toString();
    }
}


text:
package client

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"strings"
	"testing"

	"github.com/docker/docker-credential-helpers/credentials"
)

const (
	validServerAddress   = "https://index.docker.io/v1"
	validUsername        = "linus"
	validServerAddress2  = "https://example.com:5002"
	invalidServerAddress = "https://foobar.example.com"
	missingCredsAddress  = "https://missing.docker.io/v1"
)

var errProgramExited = fmt.Errorf("exited 1")

// mockProgram simulates interactions between the docker client and a remote
// credentials helper.
// Unit tests inject this mocked command into the remote to control execution.
type mockProgram struct {
	arg   string
	input io.Reader
}

// Output returns responses from the remote credentials helper.
// It mocks those responses based in the input in the mock.
func (m *mockProgram) Output() ([]byte, error) {
	in, err := ioutil.ReadAll(m.input)
	if err != nil {
		return nil, err
	}
	inS := string(in)

	switch m.arg {
	case "erase":
		switch inS {
		case validServerAddress:
			return nil, nil
		default:
			return []byte("program failed"), errProgramExited
		}
	case "get":
		switch inS {
		case validServerAddress:
			return []byte(`{"Username": "foo", "Secret": "bar"}`), nil
		case validServerAddress2:
			return []byte(`{"Username": "<token>", "Secret": "abcd1234"}`), nil
		case missingCredsAddress:
			return []byte(credentials.NewErrCredentialsNotFound().Error()), errProgramExited
		case invalidServerAddress:
			return []byte("program failed"), errProgramExited
		case "":
			return []byte(credentials.NewErrCredentialsMissingServerURL().Error()), errProgramExited
		}
	case "store":
		var c credentials.Credentials
		err := json.NewDecoder(strings.NewReader(inS)).Decode(&c)
		if err != nil {
			return []byte("error storing credentials"), errProgramExited
		}
		switch c.ServerURL {
		case validServerAddress:
			return nil, nil
		case validServerAddress2:
			return nil, nil
		default:
			return []byte("error storing credentials"), errProgramExited
		}
	case "list":
		return []byte(fmt.Sprintf(`{"%s": "%s"}`, validServerAddress, validUsername)), nil

	}

	return []byte(fmt.Sprintf("unknown argument %q with %q", m.arg, inS)), errProgramExited
}

// Input sets the input to send to a remote credentials helper.
func (m *mockProgram) Input(in io.Reader) {
	m.input = in
}

func mockProgramFn(args ...string) Program {
	return &mockProgram{
		arg: args[0],
	}
}

func ExampleStore() {
	p := NewShellProgramFunc("docker-credential-secretservice")

	c := &credentials.Credentials{
		ServerURL: "https://example.com",
		Username:  "calavera",
		Secret:    "my super secret token",
	}

	if err := Store(p, c); err != nil {
		fmt.Println(err)
	}
}

func TestStore(t *testing.T) {
	valid := []credentials.Credentials{
		{validServerAddress, "foo", "bar"},
		{validServerAddress2, "<token>", "abcd1234"},
	}

	for _, v := range valid {
		if err := Store(mockProgramFn, &v); err != nil {
			t.Fatal(err)
		}
	}

	invalid := []credentials.Credentials{
		{invalidServerAddress, "foo", "bar"},
	}

	for _, v := range invalid {
		if err := Store(mockProgramFn, &v); err == nil {
			t.Fatalf("Expected error for server %s, got nil", v.ServerURL)
		}
	}
}

func ExampleGet() {
	p := NewShellProgramFunc("docker-credential-secretservice")

	creds, err := Get(p, "https://example.com")
	if err != nil {
		fmt.Println(err)
	}

	fmt.Printf("Got credentials for user `%s` in `%s`\n", creds.Username, creds.ServerURL)
}

func TestGet(t *testing.T) {
	valid := []credentials.Credentials{
		{validServerAddress, "foo", "bar"},
		{validServerAddress2, "<token>", "abcd1234"},
	}

	for _, v := range valid {
		c, err := Get(mockProgramFn, v.ServerURL)
		if err != nil {
			t.Fatal(err)
		}

		if c.Username != v.Username {
			t.Fatalf("expected username `%s`, got %s", v.Username, c.Username)
		}
		if c.Secret != v.Secret {
			t.Fatalf("expected secret `%s`, got %s", v.Secret, c.Secret)
		}
	}

	missingServerURLErr := credentials.NewErrCredentialsMissingServerURL()

	invalid := []struct {
		serverURL string
		err       string
	}{
		{missingCredsAddress, credentials.NewErrCredentialsNotFound().Error()},
		{invalidServerAddress, "error getting credentials - err: exited 1, out: `program failed`"},
		{"", fmt.Sprintf("error getting credentials - err: %s, out: `%s`",
			missingServerURLErr.Error(), missingServerURLErr.Error())},
	}

	for _, v := range invalid {
		_, err := Get(mockProgramFn, v.serverURL)
		if err == nil {
			t.Fatalf("Expected error for server %s, got nil", v.serverURL)
		}
		if err.Error() != v.err {
			t.Fatalf("Expected error `%s`, got `%v`", v.err, err)
		}
	}
}

func ExampleErase() {
	p := NewShellProgramFunc("docker-credential-secretservice")

	if err := Erase(p, "https://example.com"); err != nil {
		fmt.Println(err)
	}
}

func TestErase(t *testing.T) {
	if err := Erase(mockProgramFn, validServerAddress); err != nil {
		t.Fatal(err)
	}

	if err := Erase(mockProgramFn, invalidServerAddress); err == nil {
		t.Fatalf("Expected error for server %s, got nil", invalidServerAddress)
	}
}

func TestList(t *testing.T) {
	auths, err := List(mockProgramFn)
	if err != nil {
		t.Fatal(err)
	}

	if username, exists := auths[validServerAddress]; !exists || username != validUsername {
		t.Fatalf("auths[%s] returned %s, %t; expected %s, %t", validServerAddress, username, exists, validUsername, true)
	}
}


text:
import { PublicKeyReference } from '@proton/crypto';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Api, Recipient } from '@proton/shared/lib/interfaces';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';

import { DecryptMessageResult } from '../../helpers/message/messageDecrypt';
import { Preparation } from '../../helpers/transforms/transforms';
import {
    MessageErrors,
    MessageImages,
    MessageRemoteImage,
    MessageState,
    MessageVerification,
} from '../messages/messagesTypes';

export interface EOInitResult {
    token: string | undefined;
    decryptedToken: string | undefined;
    password: string | undefined;
}

export interface EOInitParams {
    get: (key: string) => any;
}

export interface EOMessageParams {
    api: Api;
    token: string;
    id: string;
    password: string;
    set: (key: string, data: any) => void;
}

export interface EOTokenParams {
    api: Api;
    id: string;
    set: (key: string, data: any) => void;
}

export interface EOMessageReply {
    Attachments: Attachment[];
    Body: any;
    DecryptedBody?: any;
    Time: number;
}

export interface EOLoadEmbeddedParams {
    attachments: Attachment[];
    api: Api;
    messageVerification?: MessageVerification;
    password: string;
    id: string;
    decryptedToken: string;
}

export type EOLoadEmbeddedResults = { attachment: Attachment; blob: string }[];

export interface EOLoadRemoteParams {
    imagesToLoad: MessageRemoteImage[];
    api: Api;
}

export interface EOLoadRemoteResults {
    image: MessageRemoteImage;
    blob?: Blob;
    tracker?: string;
    error?: unknown;
}

export interface EODocumentInitializeParams {
    dataChanges: Partial<Message>;
    initialized?: boolean;
    preparation?: Preparation;
    decryption?: DecryptMessageResult;
    errors?: MessageErrors;
    messageImages?: MessageImages;
}

export type EOMessage = {
    Attachments: Attachment[];
    Body: any;
    ToList: Recipient[];
    CCList: Recipient[];
    ExpirationTime: number;
    Subject: string;
    Sender: Recipient;
    Recipient: string;
    Time: number;
    NumAttachments: number;
    Replies: EOMessageReply[];
    SenderName: string;
    SenderAddress: string;
    MIMEType: MIME_TYPES;
    PublicKey?: PublicKeyReference[];
};

export type EOState = {
    message: EOMessage;
    encryptedToken: string;
    decryptedToken: string;
    isStoreInitialized: boolean;
    password: string;
    messageState: MessageState;
};


text:
package gov.sandia.cognition.learning.algorithm.clustering.cluster;

import gov.sandia.cognition.annotation.CodeReview;
import gov.sandia.cognition.statistics.distribution.MultivariateGaussian;
import gov.sandia.cognition.math.matrix.Vector;
import java.util.Collection;

/**
 * The {@code GaussianCluster} class implements a cluster of {@code Vector}
 * objects that has a {@code MultivariateGaussian} object representing the
 * cluster.
 *
 * @author Justin Basilico
 * @since 1.0
 */
@CodeReview(
    reviewer="Kevin R. Dixon",
    date="2008-07-22",
    changesNeeded=false,
    comments="Code generally looks fine."
)
public class GaussianCluster
    extends DefaultCluster<Vector>
{
    /** The Gaussian distribution that the cluster represents. */
    private MultivariateGaussian.PDF gaussian;

    /**
     * Creates a new instance of GaussianCluster.
     */
    public GaussianCluster()
    {
        this(null);
    }

    /**
     * Creates a new instance of GaussianCluster.
     *
     * @param  gaussian The MultivariateGaussian representing the data.
     */
    public GaussianCluster(
        final MultivariateGaussian.PDF gaussian)
    {
        super();

        this.setGaussian(gaussian);
    }

    /**
     * Creates a new instance of GaussianCluster.
     *
     * @param  members The members of the cluster.
     * @param  gaussian The MultivariateGaussian representing the data.
     */
    public GaussianCluster(
        final Collection<? extends Vector> members,
        final MultivariateGaussian.PDF gaussian)
    {
        super(members);

        this.setGaussian(gaussian);
    }

    /**
     * Creates a new instance of GaussianCluster.
     *
     * @param  index The index of the cluster.
     * @param  members The members of the cluster.
     * @param  gaussian The MultivariateGaussian representing the data.
     */
    public GaussianCluster(
        final int index,
        final Collection<? extends Vector> members,
        final MultivariateGaussian.PDF gaussian)
    {
        super(index, members);

        this.setGaussian(gaussian);
    }

    /**
     * Gets the Gaussian that represents the cluster.
     *
     * @return The Gaussian representing the cluster.
     */
    public MultivariateGaussian.PDF getGaussian()
    {
        return this.gaussian;
    }

    /**
     * Sets the Gaussian representing the cluster.
     *
     * @param  gaussian The new Gaussian to represent the cluster.
     */
    public void setGaussian(
        final MultivariateGaussian.PDF gaussian)
    {
        this.gaussian = gaussian;
    }
}


text:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

from django.conf.urls import patterns, url

from apps.survey.routes import (survey, survey_from_event,
                                flag_survey, survey_detail,
                                confirm_survey, release_blockface)

# These URLs have the prefix 'survey/'
urlpatterns = patterns(
    '',
    url(r'^$', survey, name='survey'),

    url(r'^confirm/(?P<survey_id>\d+)/$',
        confirm_survey, name='confirm_survey'),

    url(r'^detail/(?P<survey_id>\d+)/$', survey_detail, name='survey_detail'),

    url(r'^(?P<group_slug>[\w-]+)/event/(?P<event_slug>[\w-]+)/$',
        survey_from_event, name='survey_from_event'),

    url(r'^flag/(?P<survey_id>\d+)/$', flag_survey, name='flag_survey'),

    url(r'^release_blockface/(?P<survey_id>\d+)/$',
        release_blockface, name='release_blockface'),
)


text:
package de.galan.snake.bootstrap;

/**
 * Simple lifecycle of an application
 *
 * @author galan
 */
public interface Application {

	default void initialize() {
		// can be overriden when required
	}

	public void start();

	default String getName() {
		return "default";
	}

	default void shutdown() {
		// can be overriden when required
	}

}


text:
using System;
using FluentAssertions;
using NUnit.Framework;

namespace HealthNet.SystemCheckerBaseFixtures
{
  class When_checking_an_unhealthy_system
  {
    private SystemCheckResult result;
    private TestSystemSystemChecker testSystemSystemChecker;

    [SetUp]
    public void SetUp()
    {
      testSystemSystemChecker = new TestSystemSystemChecker();
      result = testSystemSystemChecker.CheckSystem();
    }

    [Test]
    public void System_name_is_derived_from_the_checker_class_name()
    {
      result.SystemName.Should().Be("Test System");
    }

    [Test]
    public void Error_results_in_a_critical_health_state()
    {
      result.Health.Should().Be(HealthState.Critical);
    }

    [Test]
    public void Error_message_returned_in_result_message()
    {
      result.Message.Should().Be("Fail");
    }

    [Test]
    public void Defaults_to_vital_system()
    {
      result.IsVital.Should().BeTrue();
    }

    [Test]
    public void Defaults_to_non_intrusive_checker()
    {
      testSystemSystemChecker.IsIntrusive.Should().BeFalse();
    }

    class TestSystemSystemChecker : SystemCheckerBase
    {
      protected override void PerformCheck()
      {
        throw new Exception("Fail");
      }
    }
  }
}


text:
namespace skald{

struct compA{
	compA(unsigned long _id):id{_id}{}
	unsigned long id;
};

struct compB{
	compB(unsigned long _id,int _first):id{_id},first{_first}{}
	unsigned long id;
	int first;
};

struct compC{
	compC(unsigned long _id,int _first,int _second):id{_id},first{_first},
													second{_second}{}
	unsigned long id;
	int first;
	int second;
};

typedef World<uint8_t,compA,compB,compC> testWorld;
typedef typename testWorld::SystemPtr sysPtr;

class TestSystem1 : public testWorld::SystemBase{
public:
	TestSystem1(int p,int t):System(p,t),testVal(0){}
	~TestSystem1(){}
	int testVal;
	const int id()const override{return 1;}
	void init(testWorld*) override{}
	void destroy(testWorld*) override{}
	void update(const double d) override{
		testVal++;
	}
};

class TestSystem2 : public testWorld::SystemBase{
public:
	TestSystem2(int p,int t):System(p,t),testVal(0){}
	~TestSystem2(){}
	int testVal;
	const int id()const override{return 2;}
	void init(testWorld*) override{}
	void destroy(testWorld*) override{}
	void update(const double d) override{
		testVal--;
	}
};

class TestSystem3 : public testWorld::SystemBase{
public:
	TestSystem3(int p,int t):System(p,t),testVal(0),parent(nullptr){}
	~TestSystem3(){}
	int testVal;
	const int id()const override{return 3;}
	void init(testWorld* p) override{
		parent = p;
	}
	void destroy(testWorld*) override{
		parent = nullptr;
	}
	void update(const double d) override{
		testVal += static_cast<int>(d);
	}

	testWorld * parent;
};

}//namespace
#endif


text:
<!DOCTYPE html>

    <title>Services</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="themes/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
    <link href="themes/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
    <link href="themes/jquery.mobile.icons.min.css" rel="stylesheet" />

    Home

Services

Prayer Services

Five Daily Prayers

Friday/Jumuah Khutbah and Payer

Ramadan Activities including Iftar and Taraweeh Services

EID UL-Fitr and EID UL-Adha Prayers

Educational Services

Summer/Sunday School

Quran Learning Classes for Kids

Hifz School

Weekly Educational Lectures/Halaqas

Seminars/Conferences

Full Time HIFZ School

DARUL QURAN FULL TIME HIFZ SCHOOL

By the blessing of ALLAH,EPIC opened the new Darul Quran Hifz School on Sep 4,2012. This school is running under the supervision of Hafiz Sajjad Gul and is a full time program (6-7 hrs per day) dedicated
                to helping students master the memorization and recitation of the Quran.The students must meet the selection criteria before admission. Homeschooling and the study of non-Quranic subjects should be arranged
                separately by parents.

Social Services

Free Medical Clinic (Every Saturday by Appointment)

Financial Assistance to the Needy

Sadaqa and Zakat Distribution

Medical Clinic

The EPIC Medical Clinic provides basic primary medical care in internal medicine, family practice, general pediatrics and adolescent medicine.

NOTE: THIS SERVICES IS ONLY RESERVED FOR PEOPLE WHO DO NOT HAVE ANY KIND OF HEALTH INSURANCE AND  WHO CANNOT AFFORT TO SEE A DOCTOR.

Medical Clinic is held every Saturday of the Month from 10:30 AM to 12:30 PM

Note: There is NO CLINIC on the 5th Saturday.

For Appointments:

            Call (972) 836-6401

EPIC MEDICAL CLINIC DOCTORS TEAM:

Dr. Saniya Naheed, Dr. Nabila Zaidi, Dr. M.Raziuddin, Dr. Tariq Vora, Dr.Nayyar Syed

Outreach Activities

Mosque Open Houses

Islam 101 classes for people from other faiths

New Muslim Outreach

Islamic Funerals

EPIC partners with RAHMA FUNERAL HOME to provide funeral services. Rahma is approved/licensed by the State of Texas and has been operated by a  licensed Funeral Director since August 11,2004.

Rahma Funeral Home

			Toll Free (877) 526-2924
            Call (972) 386 0383
            www.IFSNT.com
            Direction


text:
Compiled example
----------------
![Example](spherical-coordinates.png)


text:
package com.strongjoshua.console;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.reflect.ClassReflection;

public class ConsoleContext {
	private Table root;
	private Label label, copy;
	private InputListener stageListener;

	ConsoleContext (Class<? extends Table> tableClass, Class<? extends Label> labelClass, Skin skin, String background) {
		try {
			root = ClassReflection.newInstance(tableClass);
		} catch (Exception e) {
			throw new RuntimeException("Table class does not support empty constructor.");
		}
		try {
			copy = (Label) ClassReflection.getConstructor(labelClass, CharSequence.class, Skin.class)
					.newInstance("Copy", skin);
		} catch (Exception e) {
			try {
				copy = (Label) ClassReflection.getConstructor(labelClass, CharSequence.class)
						.newInstance("Copy");
			} catch (Exception e2) {
				throw new RuntimeException(
					"Label class does not support either (<CharSequence>, <Skin>) or (<CharSequence>) constructors.");
			}
		}
		copy.addListener(new ClickListener() {
			@Override public void clicked (InputEvent event, float x, float y) {
				if (event.getPointer() != 0)
					return;
				if (label == null)
					throw new RuntimeException("Trying to copy a null label (this should never happen).");
				Gdx.app.getClipboard().setContents(label.getText().toString().trim());
				ConsoleContext.this.remove();
			}
		});
		copy.addListener(new HoverListener(copy));

		root.add(copy);
		root.pad(5);
		root.setBackground(skin.getDrawable(background));
		root.setSize(root.getPrefWidth(), root.getPrefHeight());

		stageListener = new InputListener() {
			@Override public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
				if (ConsoleContext.this.root.hit(x, y, false) == null)
					remove();
				return true;
			}
		};
	}

	void setLabel (Label l) {
		label = l;
	}

	protected void setStage (Stage stage) {
		if (stage != null) {
			stage.addListener(stageListener);
			stage.addActor(root);
		}
	}

	protected boolean remove () {
		if (root.getStage() != null)
			root.getStage().removeListener(stageListener);
		return root.remove();
	}

	protected void setPosition (float x, float y) {
		root.setPosition(x, y);
	}

	private class HoverListener extends InputListener {
		private Label label;

		HoverListener (Label l) {
			this.label = l;
		}

		@Override public void enter (InputEvent event, float x, float y, int pointer, Actor fromActor) {
			label.setColor(Color.CYAN);
		}

		@Override public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) {
			label.setColor(Color.WHITE);
		}
	}
}


text:
/*
 * This source code is provided to illustrate the usage of a given feature
 * or technique and has been deliberately simplified. Additional steps
 * required for a production-quality application, such as security checks,
 * input validation and proper error handling, might not be present in
 * this sample code.
 */

import java.io.*;
import java.nio.*;
import java.nio.charset.*;

/**
 * An object used for sending Content to the requestor.
 *
 * @author Mark Reinhold
 * @author Brad R. Wetmore
 */
class Reply implements Sendable {

    /**
     * A helper class which define the HTTP response codes
     */
    static class Code {

        private int number;
        private String reason;
        private Code(int i, String r) { number = i; reason = r; }
        public String toString() { return number + " " + reason; }

        static Code OK = new Code(200, "OK");
        static Code BAD_REQUEST = new Code(400, "Bad Request");
        static Code NOT_FOUND = new Code(404, "Not Found");
        static Code METHOD_NOT_ALLOWED = new Code(405, "Method Not Allowed");

    }

    private Code code;
    private Content content;
    private boolean headersOnly;

    Reply(Code rc, Content c) {
        this(rc, c, null);
    }

    Reply(Code rc, Content c, Request.Action head) {
        code = rc;
        content = c;
        headersOnly = (head == Request.Action.HEAD);
    }

    private static String CRLF = "\r\n";
    private static Charset ascii = Charset.forName("US-ASCII");

    private ByteBuffer hbb = null;

    private ByteBuffer headers() {
        CharBuffer cb = CharBuffer.allocate(1024);
        for (;;) {
            try {
                cb.put("HTTP/1.0 ").put(code.toString()).put(CRLF);
                cb.put("Server: niossl/0.1").put(CRLF);
                cb.put("Content-type: ").put(content.type()).put(CRLF);
                cb.put("Content-length: ")
                    .put(Long.toString(content.length())).put(CRLF);
                cb.put(CRLF);
                break;
            } catch (BufferOverflowException x) {
                assert(cb.capacity() < (1 << 16));
                cb = CharBuffer.allocate(cb.capacity() * 2);
                continue;
            }
        }
        cb.flip();
        return ascii.encode(cb);
    }

    public void prepare() throws IOException {
        content.prepare();
        hbb = headers();
    }

    public boolean send(ChannelIO cio) throws IOException {

        if (hbb == null)
            throw new IllegalStateException();

        if (hbb.hasRemaining()) {
            if (cio.write(hbb) <= 0)
                return true;
        }

        if (!headersOnly) {
            if (content.send(cio))
                return true;
        }

        if (!cio.dataFlush())
            return true;

        return false;
    }

    public void release() throws IOException {
        content.release();
    }
}