text:
/**
 * @author Nikolay A. Kuznetsov
 */
package org.teavm.classlib.java.util.regex;

/**
 * Node accepting substrings in unicode case insensitive manner.
 *
 * @author Nikolay A. Kuznetsov
 */
class TUCISequenceSet extends TLeafSet {

    private String string = null;

    TUCISequenceSet(StringBuffer substring) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < substring.length(); i++) {
            res.append(Character.toLowerCase(Character.toUpperCase(substring.charAt(i))));
        }
        this.string = res.toString();
        this.charCount = res.length();
    }

    @Override
    public int accepts(int strIndex, CharSequence testString) {
        for (int i = 0; i < string.length(); i++) {
            if (string.charAt(i) != Character.toLowerCase(Character.toUpperCase(testString.charAt(strIndex + i)))) {
                return -1;
            }
        }

        return string.length();

    }

    @Override
    public String getName() {
        return "UCI sequence: " + string; //$NON-NLS-1$
    }
}


text:
package com.globallogic.codingdojo.ui.adapters;

import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.globallogic.codingdojo.domain.model.Item;
import com.globallogic.codingdojo.R;
import com.squareup.picasso.Picasso;

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

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by david.sinner on 29/03/2016.
 */
public class RssAdapter extends RecyclerView.Adapter<RssAdapter.RSSHolder> {
    private final List<Item> mList = new ArrayList<>();
    private OnItemClickListener onItemClickListener;

    @Override
    public RSSHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rss, parent, false);
        return new RSSHolder(v);
    }

    @Override
    public void onBindViewHolder(RSSHolder holder, int position) {
        Item item = mList.get(position);
        holder.load(item);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public void setList(List<Item> items) {
        mList.clear();
        mList.addAll(items);
        this.notifyDataSetChanged();
    }

    public void clearList() {
        mList.clear();
        this.notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClickListener(Item item);
    }

    public class RSSHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        @Bind(R.id.item_rss_title)
        public TextView vTitle;
        @Bind(R.id.item_rss_description)
        public TextView vDescription;
        @Bind(R.id.item_rss_pub_date)
        public TextView vPubDate;
        @Bind(R.id.item_rss_image)
        public ImageView vImage;
        @Bind(R.id.item_rss_author)
        public TextView vAuthor;
        private Item mItem;

        public RSSHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (onItemClickListener != null)
                onItemClickListener.onItemClickListener(mItem);
        }

        public void load(Item item) {
            this.mItem = item;

            vTitle.setText(item.title);
            vDescription.setText(Html.fromHtml(item.getDescription()));
            vPubDate.setText(item.getPubDate());
            if (item.content != null && !TextUtils.isEmpty(item.content.url)) {
                Picasso.with(vTitle.getContext())
                        .load(item.content.url)
                        .into(vImage);
                vImage.setContentDescription(item.content.title);
                vImage.setVisibility(View.VISIBLE);
            } else {
                vImage.setVisibility(View.GONE);
            }
            vAuthor.setText(vAuthor.getResources().getString(R.string.created_by, item.getCreator()));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
function createStyleElement(className: string) {
  const style = document.createElement('style');
  style.className = className;
  style.type = 'text/css';
  return style;
}

// The original, non-typescript code referenced `style.styleSheet`.
// I can't find what sort of element would have a styleSheet property,
// so have created this type to satisfy TS without changing behavior.
type MysteryStyleElement = {
  styleSheet: {
    cssText: string;
  };
};

export default function injectCustomCss(css: string) {
  const className = 'CssEditor-css';
  const head = document.head || document.getElementsByTagName('head')[0];
  const style: HTMLStyleElement =
    document.querySelector(`.${className}`) || createStyleElement(className);

  if ('styleSheet' in style) {
    (style as HTMLStyleElement & MysteryStyleElement).styleSheet.cssText = css;
  } else {
    style.innerHTML = css;
  }

  /**
   * Ensures that the style applied is always the last.
   *
   * from: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
   * The Node.appendChild() method adds a node to the end of the list of children
   * of a specified parent node. If the given child is a reference to an existing
   * node in the document, appendChild() moves it from its current position to the
   * new position (there is no requirement to remove the node from its parent node
   * before appending it to some other node).
   */

  head.appendChild(style);

  return function removeCustomCSS() {
    style.remove();
  };
}


text:
Ti=Oral and Written Presentations

1.sec=Pleadings, formal requests (motions), and legal argument ordinarily should be presented initially in writing, but the parties should have the right to present oral argument on important substantive and procedural issues.

2.sec=The final hearing must be held before the judges who are to give judgment.

3.sec=The court should specify the procedure for presentation of testimony. Ordinarily, testimony of parties and witnesses should be received orally, and reports of experts in writing; but the court may, upon consultation with the parties, require that initial testimony of witnesses be in writing, which should be supplied to the parties in advance of the hearing.

4.sec=Oral testimony may be limited to supplemental questioning following written presentation of a witness's principal testimony or of an expert's report.

=[G/Z/ol/s4]

Comment:

P-19A Traditionally, all legal systems received witness testimony in oral form. However, in modern practice, the tendency is to replace the main testimony of a witness by a written statement. Principle 19 allows flexibility in this regard. It contemplates that testimony can be presented initially in writing, with orality commencing upon supplemental questioning by the court and opposing parties. Concerning the various procedures for interrogation of witnesses, see Principle 16.4 and Comment P-16E.

P-19B Forum procedure may permit or require electronic communication of written or oral presentations. See Principle 5.7.

P-19C In many civil-law systems, the primary interrogation is conducted by the court with limited intervention by the parties, whereas in most common-law systems, the roles of judge and lawyers are the reverse. In any event, the parties should be afforded opportunity to address questions directly to a witness. See Principle 16.4.


text:
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import DenormalizeSelectors from '../../selectors/denormalize.selectors';

@Component({
  selector: 'app-post-solve-message',
  templateUrl: './post-solve-message.component.html',
  styleUrls: ['./post-solve-message.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PostSolveMessageComponent implements OnInit {
  isSolutionStale$: Observable<boolean>;
  isSolutionIllegal$: Observable<boolean>;

  constructor(private store: Store) {}

  ngOnInit(): void {
    this.isSolutionStale$ = this.store.pipe(select(DenormalizeSelectors.selectIsSolutionStale));
    this.isSolutionIllegal$ = this.store.pipe(select(DenormalizeSelectors.selectIsSolutionIllegal));
  }
}


text:
<?php

namespace Magento\Framework\App;

class SetupInfoTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A default fixture
     *
     * @var array
     */
    private static $fixture = ['DOCUMENT_ROOT' => '/doc/root', 'SCRIPT_FILENAME' => '/doc/root/dir/file.php'];

    /**
     * @param array $server
     * @param string $expectedError
     * @dataProvider constructorExceptionsDataProvider
     */
    public function testConstructorExceptions($server, $expectedError)
    {
        $this->setExpectedException('\InvalidArgumentException', $expectedError);
        new SetupInfo($server);
    }

    public function constructorExceptionsDataProvider()
    {
        $docRootErr = 'DOCUMENT_ROOT variable is unavailable.';
        $projectRootErr = 'Project root cannot be automatically detected.';
        return [
            [[], $docRootErr],
            [['DOCUMENT_ROOT' => ''], $docRootErr],
            [['DOCUMENT_ROOT' => '/foo'], $projectRootErr],
            [['DOCUMENT_ROOT' => '/foo', 'SCRIPT_FILENAME' => ''], $projectRootErr],
        ];
    }

    /**
     * @param array $server
     * @param string $expected
     * @dataProvider getUrlDataProvider
     */
    public function testGetUrl($server, $expected)
    {
        $info = new SetupInfo($server);
        $this->assertEquals($expected, $info->getUrl());
    }

    /**
     * @return array
     */
    public function getUrlDataProvider()
    {
        return [
            [
                self::$fixture,
                '/setup/'
            ],
            [
                self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => 'install'],
                '/install/',
            ],
            [
                self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL => 'http://example.com/'],
                'http://example.com/',
            ],
        ];
    }

    /**
     * @param array $server
     * @param string $expected
     * @dataProvider getProjectUrlDataProvider
     */
    public function testGetProjectUrl($server, $expected)
    {
        $info = new SetupInfo($server);
        $this->assertEquals($expected, $info->getProjectUrl());
    }

    /**
     * @return array
     */
    public function getProjectUrlDataProvider()
    {
        return [
            [self::$fixture, ''],
            [self::$fixture + ['HTTP_HOST' => ''], ''],
            [['DOCUMENT_ROOT' => '/foo/bar', 'SCRIPT_FILENAME' => '/other/baz.php', 'HTTP_HOST' => 'example.com'], ''],
            [self::$fixture + ['HTTP_HOST' => 'example.com'], 'http://example.com/dir/'],
            [
                ['DOCUMENT_ROOT' => '/foo/bar', 'SCRIPT_FILENAME' => '/foo/bar/baz.php', 'HTTP_HOST' => 'example.com'],
                'http://example.com/'
            ],
        ];
    }

    /**
     * @param array $server
     * @param string $projectRoot
     * @param string $expected
     * @dataProvider getDirDataProvider
     */
    public function testGetDir($server, $projectRoot, $expected)
    {
        $info = new SetupInfo($server);
        $this->assertEquals($expected, $info->getDir($projectRoot));
    }

    /**
     * @return array
     */
    public function getDirDataProvider()
    {
        return [
            [
                self::$fixture,
                '/test/root',
                '/test/root/setup',
            ],
            [
                self::$fixture,
                '/test/root/',
                '/test/root/setup',
            ],
            [
                self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '/install/'],
                '/test/',
                '/test/install',
            ],
        ];
    }

    /**
     * @param array $server
     * @param bool $expected
     * @dataProvider isAvailableDataProvider
     */
    public function testIsAvailable($server, $expected)
    {
        $info = new SetupInfo($server);
        $this->assertEquals($expected, $info->isAvailable());
    }

    /**
     * @return array
     */
    public function isAvailableDataProvider()
    {
        $server = ['DOCUMENT_ROOT' => __DIR__, 'SCRIPT_FILENAME' => __FILE__];
        return [
            'root = doc root, but no "setup" sub-directory' => [
                $server, // it will look for "setup/" sub-directory, but won't find anything
                false
            ],
            'root = doc root, nonexistent sub-directory' => [
                $server + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => 'nonexistent'],
                false
            ],
            'root = doc root, existent sub-directory' => [
                $server + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '_files'],
                true
            ],
            'root within doc root, existent sub-directory' => [
                [
                    'DOCUMENT_ROOT' => dirname(__DIR__),
                    'SCRIPT_FILENAME' => __FILE__,
                    SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '_files'
                ],
                true
            ],
            'root outside of doc root, existent sub-directory' => [
                [
                    'DOCUMENT_ROOT' => __DIR__,
                    'SCRIPT_FILENAME' => dirname(dirname(__DIR__)) . '/foo.php',
                    SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => basename(__DIR__)
                ],
                false
            ],
        ];
    }
}


text:
from main import Abnum, AbnumException
"""
exporting:
- Abnum
- AbnumException
"""

from letter_value import *
"""
exporting:
- data
- greek, hebrew, coptic
- english, sanskrit, arabic
"""

from math import *
"""
exporting:
- digital_root
- digital_sum
- digital_product
- digital_root_summary
"""

from search import find_cumulative_indices
"""
exporting:
- find_cumulative_indices
"""


text:
'use strict';

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var config = require('./config').config;
var mongoose = require('mongoose');

process.app = {};

var db = mongoose.createConnection(config.db);
process.app.connection = db;

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

// CORS
app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS');
  next();
});

var people = require('./modules/people');
process.app.people = people.models.people;

people.api.addRoutes(app);

var port = parseInt(process.env.PORT) || config.port;
app.listen(port);
console.log('somemodel service listening on port ' + port);


text:
import chai, { expect } from 'chai';
import { MockClient, MockHost } from './mocks.js';
import { clientSyncOslo } from '../../plugins/sync-oslo/client.js';
import { hostSyncOslo } from '../../plugins/sync-oslo/host.js';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';

chai.use(sinonChai).should();

describe('sync-oslo', () => {
	let getElementsByTagName;

	beforeEach(() => {
		getElementsByTagName = sinon.stub();
		global.document = {
			getElementsByTagName: getElementsByTagName
		};
		global.window = {
			location: { protocol: 'https:', origin: 'https://dummy' },
			URL: class {
				constructor(path, base) {
					this._href = `${base}/${path}`;
				}
				get href() {
					return this._href;
				}
			}
		};
	});

	describe('client', () => {
		let client, request;

		beforeEach(() => {
			client = new MockClient();
			request = sinon.stub(client, 'request');
		});

		it('should request for "oslo"', () => {
			getElementsByTagName
				.withArgs('html')
				.returns([]);
			request
				.withArgs('oslo')
				.returns(Promise.resolve({}));
			clientSyncOslo(client);
			request.should.have.been.calledWith('oslo');
		});

		it('should apply oslo JSON to HTML element', (done) => {

			const osloData = {
				batch: 'batch',
				collection: 'collection',
				version: 'version'
			};

			const setAttribute = sinon.stub();
			getElementsByTagName
				.withArgs('html')
				.returns([{
					setAttribute: setAttribute
				}]);

			request
				.withArgs('oslo')
				.returns(Promise.resolve(osloData));

			clientSyncOslo(client).then(() => {
				setAttribute.should.have.been.calledWith(
					'data-oslo',
					JSON.stringify(osloData)
				);
				done();
			});
		});

		it('should do nothing if HTML element is not present', (done) => {

			getElementsByTagName
				.withArgs('html')
				.returns([]);

			request
				.withArgs('oslo')
				.returns(new Promise((resolve) => {
					resolve(true);
				}));

			clientSyncOslo(client).then(done);
		});
	});

	describe('host', () => {
		let host, onRequest;

		beforeEach(() => {
			host = new MockHost();
			onRequest = sinon.spy(host, 'onRequest');
		});

		it('should add request handler for "oslo"', () => {
			hostSyncOslo(host);
			onRequest.should.have.been.calledWith('oslo');
		});

		it('should return parsed value of "data-oslo" attribute from HTML element', () => {

			const osloData = {
				batch: 'batch',
				collection: 'collection',
				version: 'version'
			};

			const hasAttribute = sinon.stub();
			hasAttribute
				.withArgs('data-oslo')
				.returns(true);

			const getAttribute = sinon.stub();
			getAttribute
				.withArgs('data-oslo')
				.returns(JSON.stringify(osloData));

			getElementsByTagName
				.withArgs('html')
				.returns([{
					getAttribute: getAttribute,
					hasAttribute: hasAttribute
				}]);

			hostSyncOslo(host);

			const value = onRequest.args[0][1]();
			expect(value).to.eql({
				batch: 'https://dummy/batch',
				collection: 'https://dummy/collection',
				version: 'version'
			});
		});

		it('should return empty object if "data-oslo" attribute not present', () => {

			const hasAttribute = sinon.stub();
			hasAttribute
				.withArgs('data-oslo')
				.returns(false);

			getElementsByTagName
				.withArgs('html')
				.returns([{
					hasAttribute: hasAttribute
				}]);

			hostSyncOslo(host);

			const value = onRequest.args[0][1]();
			expect(value).to.be.undefined;
		});
	});
});


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

	<title>Ash framework</title>

	<meta name="description" content="" />
	<meta name="author" content="Jakub Mazanec" />

	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

	<link rel="stylesheet" href="css/app.css" type="text/css" />

%CONTENT%

%CONTENT%

%CONTENT%


text:
<?php

namespace Bugzorcist\Symfony\Bundle\DataCollector;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpKernel\KernelInterface;

use Bugzorcist\Profiler\DataProfiler\DataProfilerManager;

/**
 * BugzorcistDataCollector
 * @author Stephen Berquet <stephen.berquet@gmail.com>
 */
class BugzorcistDataCollector extends DataCollector
{
    /**
     * @var \Bugzorcist\Profiler\DataProfiler\DataProfilerManager
     */
    private $dataProfilerManager;

    /**
     * @var \Symfony\Component\HttpKernel\KernelInterface
     */
    private $kernel;

    /**
     * Constructor
     * @param \Bugzorcist\Profiler\DataProfiler\DataProfilerManager $dataProfilerManager
     * @param \Symfony\Component\HttpKernel\KernelInterface $kernel
     */
    public function __construct(DataProfilerManager $dataProfilerManager, KernelInterface $kernel)
    {
        $this->dataProfilerManager  = $dataProfilerManager;
        $this->kernel               = $kernel;
    }

    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $queryCount     = 0;
        $queryTime      = 0;
        $dataSources    = array();

        foreach ($this->dataProfilerManager as $profiler) {
            $queryCount        += $profiler->count();
            $queryTime         += $profiler->getTotalElapsedSecs();

            $name               = $profiler->getDataSourceName();
            $dataSources[$name] = array(
                "queryTime"         => $profiler->getTotalElapsedSecs(),
                "queryCount"        => $profiler->count(),
                "profiles"          => array()
            );

            foreach ($profiler as $profile) {
                $dataSources[$name]["profiles"][] = array(
                    "queryTime"             => $profile->hasEnded() ? $profile->getElapsedSecs() : false,
                    "queryText"             => $profiler->getFormatter()->formatHtml($profile->getQueryText()),
                    "params"                => $this->formatQueryParams($profile->getQueryParams()),
                    "startTime"             => $profile->getStartMicrotime() - $this->kernel->getStartTime(),
                    "endTime"               => $profile->hasEnded() ? $profile->getEndMicrotime() - $this->kernel->getStartTime() : false,
                    "startMemoryUsage"      => $profile->getStartMemoryUsage(true),
                    "endMemoryUsage"        => $profile->hasEnded() ? $profile->getEndMemoryUsage(true) : false,
                    "startPeakMemoryUsage"  => $profile->getStartPeakMemoryUsage(true),
                    "endPeakMemoryUsage"    => $profile->hasEnded() ? $profile->getEndPeakMemoryUsage(true) : false,
                );
            }
        }

        $this->data["queryCount"]   = $queryCount;
        $this->data["queryTime"]    = $queryTime;
        $this->data["dataSources"]  = $dataSources;
    }

    /**
     * Returns the total number of queries
     * @return int
     */
    public function queryCount()
    {
        return $this->data["queryCount"];
    }

    /**
     * Returns the total execution time of all queries
     * @return float
     */
    public function queryTime()
    {
        return $this->data["queryTime"];
    }

    /**
     * Returns data sources
     * @return array
     */
    public function dataSources()
    {
        return $this->data["dataSources"];
    }

    /**
     * Format query params
     * @param array $queryParams
     * @return array
     */
    private function formatQueryParams(array $queryParams)
    {
        $params = array();

        if (empty($queryParams)) {
            return $params;
        }

        // look for the longest parameter name
        $maxKeyLength = 0;

        foreach ($queryParams as $paramName => $paramValue) {
            $maxKeyLength = strlen($paramName) > $maxKeyLength ? strlen($paramName) : $maxKeyLength;
        }

        // build parameters
        foreach ($queryParams as $paramName => $paramValue) {
            $paramType  = "object" == gettype($paramValue) ? get_class($paramValue) : gettype($paramValue);

            switch ($paramType){
                case "string":
                case "integer":
                case "long":
                case "float":
                case "double":
                    // leave value as is
                    break;

                case "bool":
                case "boolean":
                    $paramValue = $paramValue ? "true" : "false";
                    break;

                case "null":
                case "NULL":
                case "array":
                case "object":
                default:
                    $paramValue = "";
            }

            $params[] = array(
                "name"      => str_pad($paramName, $maxKeyLength, " ", STR_PAD_RIGHT),
                "type"      => $paramType,
                "value"     => $paramValue
            );
        }

        return $params;
    }

    /**
     * {@inheritdoc}
     */
    function getName()
    {
        return "bugzorcist-data-source";
    }
}


text:
from vilya.libs import api_errors
from vilya.models.team import Team
from vilya.views.api.utils import jsonize
from vilya.views.api.teams.doc_project import DocProjectUI
from vilya.views.api.teams.groups import GroupsUI

_q_exports = []

def _q_lookup(request, name):
    return TeamUI(name)

class TeamUI(object):
    _q_exports = ['projects', 'members', 'doc_project', 'groups']

    def __init__(self, name):
        self.team = Team.get_by_uid(name)

    def __call__(self, request):
        return self._index(request)

    @jsonize
    def _index(self, request):
        if not self.team:
            raise api_errors.NotFoundError('team')
        return self.team.as_dict()

    def _q_access(self, request):
        request.response.set_content_type('application/json; charset=utf-8')

    @jsonize
    def projects(self, request):
        d = []
        projects = self.team.projects
        for project in projects:
            d.append(project.as_dict())
        return d

    @jsonize
    def members(self, request):
        d = []
        members = self.team.users
        for member in members:
            d.append(member.as_dict())
        return d

    @property
    def groups(self):
        return GroupsUI(self.team)

    @property
    def doc_project(self):
        return DocProjectUI(self.team)


text:
var fs = require('fs')
  , XT = require('..');

var xml = fs.readFileSync(__dirname + '/feed.xml', 'utf8');
var feed = XT(xml);

console.log(feed.children('title').text());
for (var link = feed.children().first('link'); link.length > 0; link = link.next('link')) {
  console.log(link.attr('href'));
}
for (var entry = feed.children().first('entry'); entry.length > 0; entry = entry.next('entry')) {
  console.log('Entry: ' + entry.children('title').text());
}


text:
using System;
using System.Drawing;
namespace Netron.Lithium
{
	/// <summary>
	/// A simple text label
	/// </summary>
	public class TextLabel : ShapeBase
	{
		#region Fields

		#endregion

		#region Constructor
		/// <summary>
		/// Default ctor
		/// </summary>
		/// <param name="s"></param>
		public TextLabel(LithiumControl s) : base(s)
		{
			this.shapeColor = Color.Transparent;
		}
		#endregion

		#region Methods
		/// <summary>
		/// Tests whether the mouse hits this shape
		/// </summary>
		/// <param name="p"></param>
		/// <returns></returns>
		public override bool Hit(System.Drawing.Point p)
		{
			Rectangle r= new Rectangle(p, new Size(5,5));
			return rectangle.Contains(r);
		}

		/// <summary>
		/// Paints the shape on the canvas
		/// </summary>
		/// <param name="g"></param>
		public override void Paint(System.Drawing.Graphics g)
		{
			g.FillRectangle(shapeBrush,rectangle);
			if(hovered || isSelected)
				g.DrawRectangle(new Pen(Color.Red,2F),rectangle);

			//well, a lot should be said here like
			//the fact that one should measure the text before drawing it,
			//resize the width and height if the text if bigger than the rectangle,
			//alignment can be set and changes the drawing as well...
			//here we keep it really simple:
			if(text !=string.Empty)
				g.DrawString(text,font,Brushes.Black, rectangle.X+10,rectangle.Y+10);
		}

		/// <summary>
		/// Invalidates the shape
		/// </summary>
		public override void Invalidate()
		{
			Rectangle r = rectangle;
			r.Offset(-5,-5);
			r.Inflate(20,20);
			site.Invalidate(r);
		}

		/// <summary>
		/// Overrides the resize to repaint the shape
		/// </summary>
		/// <param name="width"></param>
		/// <param name="height"></param>
		public override void Resize(int width, int height)
		{
			base.Resize (width, height);
			Invalidate();
		}

		#endregion
	}
}


text:
from paypal.interface import PayPalInterface
from paypal.settings import PayPalConfig
from paypal.exceptions import PayPalError, PayPalConfigError, PayPalAPIResponseError
import paypal.countries

VERSION = '1.0.3'


text:
This wizard will help you to setup and configure Catalyst to manage DevOps assets across data center and cloud.

1. Configuration Management: Configure your own chef server. You can add either a hosted chef server or an on-premise installation of chefserver.

2. Provider Configuration: You can configure multiple cloud provider accounts of type Aws, Azure, OpenStack and VmWare within RLCatalyst.

3. Repositories: You can configure Nexus repository, Docker Repository and Jenkins Server.

4. Telemetry Configuration: Configure ELK, StackStorm and Sensu application for monitoring heath of the data center.

5. CMDB Configuration: You can configure Configure ServiceNow ITMS application.

            <input type="button" name="next1" id="next1" class="nextFormWizard btn btn-primary" value="Next"/>


text:
package monix.reactive.internal.operators

import minitest.TestSuite
import monix.execution.Ack.Continue
import monix.execution.schedulers.TestScheduler
import monix.execution.exceptions.DummyException
import monix.reactive.{Observable, Observer}
import scala.concurrent.Promise

object MiscFailedSuite extends TestSuite[TestScheduler] {
  def setup() = TestScheduler()
  def tearDown(s: TestScheduler) = {
    assert(s.state.tasks.isEmpty, "TestScheduler should have no pending tasks")
  }

  test("should complete") { implicit s =>
    var received = 0
    var wasCompleted = false

    Observable
      .now(1)
      .failed
      .unsafeSubscribeFn(new Observer[Throwable] {
        def onNext(elem: Throwable) = {
          received += 1
          Continue
        }

        def onError(ex: Throwable) = ()
        def onComplete() = wasCompleted = true
      })

    assertEquals(received, 0)
    assert(wasCompleted)
  }

  test("should signal error without back-pressure applied") { implicit s =>
    var wasCompleted = false
    var thrown: Throwable = null
    val p = Promise[Continue.type]()

    Observable
      .raiseError(DummyException("dummy"))
      .failed
      .unsafeSubscribeFn(new Observer[Throwable] {
        def onError(ex: Throwable) = ()
        def onComplete() = wasCompleted = true
        def onNext(elem: Throwable) = {
          thrown = elem
          p.future
        }
      })

    assertEquals(thrown, DummyException("dummy"))
    assert(wasCompleted)
    p.success(Continue)
    s.tick()
  }
}


text:
Please refer to [official docker homepage](https://www.docker.com) for help. Simply put, you can think of it as a lightweight virtual machine although this is not an exact description.

## Why to use tachyon-dev

If you're developing tachyon on your host machine, you make some modifications to tachyon on host
and want to see how will it work on a cluster. With tachyon-dev, just `mvn package` on host
machine, and follow the instructions below to deploy the current tachyon "release" of your own on a
"docker cluster".

## What is included
* **precise** in the docker containers' names mean that the container's base image is **ubuntu:precise**
* **dnsmasq-precise:** a container serving as dns server to resolve hosts in the virtualized cluster
* **apache-hadoop-hdfs1.0.4-precise:** a container with the following software preinstalled like hadoop1.0.4, openjdk6, and some system utils like ping, python2.7, sudo
* The two containers above are modified from [github:amplab/docker-scripts](https://github.com/amplab/docker-scripts)
* **tachyon-dev/tachyon-base:** a container built from apache-hadoop-hdfs1.0.4-precise with configurations of tachyon
* **tachyon-dev/tachyon-master:** a container built from tachyon-base, serving as tachyon's master node
* **tachyon-dev/tachyon-worker:** a container built from tachyon-base, serving as tachyon's worker node
* in the future, there will be **tachyon-0.4.0**, **tachyon-0.5.0**, etc. all directories will be named as **tachyon-{version}**
* tachyon-dev is unique because it deploys the tachyon source directory containing the docker directory on your host to the cluster, so, before deploying tachyon-dev, you have to run `mvn package`. while the future tachyon-0.4.0, tachyon-0.5.0 etc. will deploy tachyon releases downloaded from online repositories to the cluster
to your cluster.
* **deploy:** scripts to start and stop the cluster

## Tips for Mac Users

It will be much easier to use docker on a **ubuntu:14.04** virtual machine, other versions of ubuntu won't provide docker in apt-get, and low version of kernel may lack the feature needed by docker.

since docker leverages linux kernel features, even if you install docker directly on Mac according to [official document](https://docs.docker.com/installation/), it actually
installs a tiny-core linux virtual machine on VirtualBox, but this tiny-core linux doesn't have a
browser for you to view tachyon web UI, you need to configure the network between your host and VirtualBox and share folders
between them.

If you would prefer to use a Mac enviornment, first ssh into boot2docker.

* boot2docker ssh

Then install bash.

* tce-ab
* Search for bash.tcz, then install

Clone the repo in your boot2docker VM.

SCP the tachyon snapshot jar you wish to test to tachyon/core/target. You can get the VM's ip by

* boot2docker ip

Now you can build and deploy.

* cd tachyon-dev
* ./build
* cd ..
* ./deploy/deploy.sh

## How to use tachyon-dev
### Enter docker directory
* Make sure the docker directory is under the tachyon development directory on your host and enter the docker directory, run `pwd`, you should get something like `/..../tachyon/docker`

### Install docker
* If you haven't installed docker, please refer to [official docker document](https://docs.docker.com/installation/) for help.
* **sudo apt-get install docker** will install something related to KDE3/GENOME's docklet instead of the docker we want to use, do visit the official site for instructions!

### Configure tachyon-dev
* Before building containers, please configure tachyon template configuration files in
`tachyon-dev/tachyon-base/files`, otherwise, default configurations will be used
* If the configuration files are modified, you have to run `cd tachyon-dev`, `./build` to re-build containers in tachyon-dev

### Become root
* Since docker typically needs to be run as root(of course, you can change its executive privilege), run `sudo -s` to become root before the following steps

### Build containers
* Make sure you are under the docker directory now
* `./build` to build all docker containers, this may take a while because some containers need to download several packages
* If you want to independently build images in e.x. tachyon-dev, `cd tachyon-dev`, `./build` or in dnsmasq-precise, `cd dnsmasq-precise`, `./build`

### Check containers
* You can check whether containers in tachyon-dev have been successfully built by running `docker images | grep tachyon`, you should see information related to tachyon-base:dev, tachyon-master:dev and tachyon-worker:dev

### Package tachyon snapshot
* If tachyon jars on your host are not up-to-date, run `mvn package`

### Deploy the cluster
* Make sure to be under the docker directory
* `./deploy/deploy.sh` to start nameserver, master and worker nodes. Default worker
number is 2, you can change the default value of `NUM_WORKERS` in `deploy/deploy.sh`

### Wait for several seconds

* Now, you have a virtualized tachyon cluster on your host.
* there is help information on how to ssh into your cluster, how to see the web UI, etc in stdout

### Stop the cluster
* `./deploy/killAll.sh`, this will kill dnsmasq, tachyon-master, tachyon-worker containers

## Example Usages:
### Testing environment:
* ubuntu14.04 and ubuntu12.04
* docker0.9.1

*If you're running a virtual machine, all the examples below should be run in the VM, you need to
share the tachyon home folder on your host with your VM.*

### Example 0

#### Goal
* run a tachyon cluster in local mode with 1 master and 2 workers
* ssh into master, run tachyon tests
* finally have a look at web UI

#### Instructions
set `TACHYON_UNDERFS_ADDRESS` in `tachyon-dev/tachyon-base/files/tachyon-env.sh.template` to `$TACHYON_HOME/underfs`

Then:

    sudo -s

if you have built other containers, just re-build containers in tachyon-dev via `cd tachyon-dev && ./build && cd ..` or you can re-build all containers via `./build`

Then:

    ./deploy/deploy.sh

you'll have output in your terminal like:

    starting nameserver container
    WARNING: Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : [8.8.8.8 8.8.4.4]
    started nameserver container:  4cc00    bdcb23bf76264a3c807a328c439d36aca0452fe1c80af04270ef9c31c40
    DNS host->IP file mapped:      /tmp/dnsdir_29039/0hosts
    NAMESERVER_IP:                 172.17.0.9
    waiting for nameserver to come up
    starting master container
    local tachyon directory is resolved to: /media/sf_tachyon
    started master container:     323f34924a44781a338d6a60baf181cfc779c6dde47c7ef8a90329650a44cbe1
    MASTER_IP:                    172.17.0.10
    NO.1 remote worker
    starting worker1
    started worker container: 1df5589fb07a32f0160c00b51f479eba8c9f667090ea9409add120465c44485e
    WORKER_IP:                 172.17.0.11
    NO.2 remote worker
    starting worker2
    started worker container: e3a2a61c7177848432c8ad70b1461c8c467d98f41a0af83b7a6d545c30fe7dad
    WORKER_IP:                 172.17.0.12
    **************************************************

    visit Tachyon Web UI at: http://172.17.0.10:19999

    ssh into master via:     ssh -i /tmp/id_rsa13436 -o UserKnownHostsFile=/dev/null -o     StrictHostKeyChecking=no root@172.17.0.10
    you can also ssh into workers via the command above with the ip substituted

    after ssh into either master/worker, /root/tachyon_container is tachyon home

    to enable the host to resolve {'master', 'worker1', 'worker2'...} to corresponding ip, set 'nameserver     172.17.0.9' as first line in your host's /etc/resolv.conf

    **************************************************

The instructions between star lines will tell you how to see Tachyon web UI and how to ssh to cluster nodes.

Copy the web UI's URL in the instruction to your browser, you should see tachyon's web UI, if worker
number is not 2, refresh the page after a while because workers may be connecting to master.

copy the command for sshing into master node from the instruction to your command line, run it and you should be in your master node as root now.

cd to the tachyon home on your master node:

    cd /opt/tachyon_container

start a local worker on master because runTests need a local worker:

    bin/tachyon-start.sh worker Mount

after the local worker start, refresh the web UI, 3 workers should be active now

run tests:

    bin/tachyon runTests

all tests should pass if everything works well

refresh web UI again, and browse the file system in the UI, see files in memory!

If something goes wrong, you can check via:

    # get the container ID of a running container you want to inspect
    docker ps
    # copy the first column(container ID),
    docker logs #containerID

or ssh into master, worker, then:

    cd /opt/tachyon_container/logs
    ls

and view the logs

after all the work, remember to stop the cluster, if you're now in a container, exit it and then

    ./deploy/killAll.sh

### Example 1

#### Goal
* deploy hdfs as under filesystem for tachyon.

#### Instructions
set `TACHYON_UNDERFS_ADDRESS` in `tachyon-dev/tachyon-base/files/tachyon-env.sh.template` to `hdfs://master:9000`

Now follow the same instructions in Example 0 above, except the first step


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
JsUnit Class Hierarchy
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

  Overview
   File
   Class
     Tree
      Index
      Help

JsUnit

 PREV
 NEXT

  FRAMES
 NO FRAMES

All Classes

Class Hierarchy

Object

Clock

JsUnitAssertionArgumentError

JsUnitError

JsUnitFailure

JsUnitTestSuite

MockXmlHttpRequest

Utilities

  Overview
   File
   Class
     Tree
      Index
      Help

JsUnit

 PREV
 NEXT

  FRAMES
 NO FRAMES

All Classes

www.jsunit.net

Documentation generated by JSDoc on Sun Sep  9 15:34:58 2007


text:
"""askp_site URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url

urlpatterns = [
    url(r'^', include('askp.urls')),
]

# TODO: better move it somewhere
def check_and_reset_auth_data():
    from django.db.utils import OperationalError
    from django.contrib.sites.models import Site
    from allauth.socialaccount.models import SocialApp

    from config.config import COMMON_APP_CONFIG
    from config.config import SERVER_CONFIG

    if COMMON_APP_CONFIG['social_auth'] is None:
        return

    try:
        site = Site.objects.get(id=1)
    except OperationalError: # This happens during database initializations
        return
    site.name = SERVER_CONFIG['domain']
    site.domain = SERVER_CONFIG['domain']
    site.save()

    # Providers could be set via django admin
    auth_config = SERVER_CONFIG['auth_config']
    if auth_config is None:
        return

    cfg = auth_config['google']
    if cfg is not None:
        try:
            app = SocialApp.objects.get(provider='google')
            app.secret = cfg['secret']
            app.client_id = cfg['client_id']
            app.save()
        except SocialApp.DoesNotExist:
            app = SocialApp.objects.create(
                provider='google',
                secret=cfg['secret'],
                client_id=cfg['client_id'],
                name='google provider')
            app.sites.add(site)
            app.save()

# Perform this code once when server starts
check_and_reset_auth_data()


text:
package net.chriswareham.da;

import java.io.Serializable;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * This class provides a unit test for the memory cache.
 *
 * @author Chris Wareham
 */
public class MemoryCacheTest {
    /**
     * The memory cache.
     */
    private MemoryCache<Integer, TestObject> cache;

    /**
     * Setup the test fixture.
     *
     * @throws Exception if an error occurs
     */
    @Before
    public void setUp() throws Exception {
        cache = new MemoryCache<>();
        cache.start();
    }

    /**
     * Teardown the test fixture.
     *
     * @throws Exception if an error occurs
     */
    @After
    public void tearDown() throws Exception {
        cache.stop();
    }

    /**
     * Test the MemoryCache::store() method.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testStore() throws Exception {
        TestObject obj = new TestObject(1);
        cache.store(obj.getId(), obj);
    }

    /**
     * Test the MemoryCache::fetch() method.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testFetch() throws Exception {
        TestObject obj = new TestObject(2);
        cache.store(obj.getId(), obj);
        TestObject objRead = cache.fetch(obj.getId());
        Assert.assertTrue(objRead != null);
    }

    /**
     * Test the MemoryCache::flushAndStore() method.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testFlushAndStore() throws Exception {
        TestObject obj = new TestObject(3);
        cache.store(obj.getId(), obj);
        cache.flushAndStore(obj.getId(), obj);
        TestObject objRead = cache.fetch(obj.getId());
        Assert.assertTrue(objRead != null);
    }

    /**
     * Test the MemoryCache::flush() method.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testFlush() throws Exception {
        TestObject obj = new TestObject(4);
        cache.store(obj.getId(), obj);
        cache.flush(obj.getId());
        TestObject objRead = cache.fetch(obj.getId());
        Assert.assertTrue(objRead == null);
    }

    /**
     * Test the MemoryCache::flush() method.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testFlushAll() throws Exception {
        TestObject obj = new TestObject(5);
        cache.store(obj.getId(), obj);
        cache.flush();
        TestObject objRead = cache.fetch(obj.getId());
        Assert.assertTrue(objRead == null);
    }

    /**
     * This class provides a test object suitable for caching.
     */
    private static class TestObject implements Serializable {
        /**
         * The serial version UID.
         */
        private static final long serialVersionUID = 1L;

        /**
         * The id of the test object.
         */
        private final int id;

        /**
         * Constructs a new instance of a test object.
         *
         * @param i the id of the test object
         */
        TestObject(final int i) {
            id = i;
        }

        /**
         * Get the id of the test object.
         *
         * @return the id of the test object
         */
        public int getId() {
            return id;
        }
    }
}


text:
import test from 'ava';
import { MinBucketAggregation } from '../../src';
import { setsAggType } from '../_macros';

test(setsAggType, MinBucketAggregation, 'min_bucket');

test('constructor sets buckets_path', t => {
    const value = new MinBucketAggregation(
        'my_agg',
        'my_buckets_path'
    ).toJSON();
    const expected = {
        my_agg: {
            min_bucket: {
                buckets_path: 'my_buckets_path'
            }
        }
    };
    t.deepEqual(value, expected);
});


text:
#include <kernel.h>
#include <bitmacros.h>
#include <dispatch.h>
#include <string.h>
#include <stdio.h>

#include <barrelfish_kpi/init.h>
#include <barrelfish_kpi/syscalls.h>
#include <elf/elf.h>

#include <arch/arm/platform.h>
#include <paging_kernel_arch.h>
#include <exceptions.h>
#include <cpiobin.h>
#include <init.h>
#include <barrelfish_kpi/paging_arch.h>
#include <barrelfish_kpi/arm_core_data.h>
#include <kernel_multiboot.h>
#include <offsets.h>
#include <startup_arch.h>
#include <global.h>
#include <kcb.h>
#include <arch/arm/startup_arm.h>

#define CNODE(cte)              get_address(&cte->cap)

#define STARTUP_PROGRESS()      debug(SUBSYS_STARTUP, "%s:%d\n",          \
                                      __FUNCTION__, __LINE__);

#define BSP_INIT_MODULE_NAME    BF_BINARY_PREFIX "armv7/sbin/init"
#define APP_INIT_MODULE_NAME    BF_BINARY_PREFIX "armv7/sbin/monitor"

#define MSG(format, ...) printk( LOG_NOTE, "ARMv7-A: "format, ## __VA_ARGS__ )

//static phys_mmap_t* g_phys_mmap;        // Physical memory map
static union arm_l1_entry * init_l1;              // L1 page table for init
static union arm_l2_entry * init_l2;              // L2 page tables for init

static struct spawn_state spawn_state;

/// Pointer to bootinfo structure for init
struct bootinfo* bootinfo = (struct bootinfo*)INIT_BOOTINFO_VBASE;

/* There is only one copy of the global locks, which is allocated alongside
 * the BSP kernel.  All kernels have their pointers set to the BSP copy. */
struct global *global= NULL;

/**
 * Map frames into init process address space. Init has a contiguous set of
 * l2 entries so this is straightforward.
 *
 * @param l2_table      pointer to init's L2 table.
 * @param l2_base       virtual address represented by first L2 table entry
 * @param va_base       virtual address to map.
 * @param pa_base       physical address to associate with virtual address.
 * @param bytes         number of bytes to map.
 * @param l2_flags      ARM L2 small page flags for mapped pages.
 */
static void
spawn_init_map(union arm_l2_entry* l2_table,
               lvaddr_t   l2_base,
               lvaddr_t   va_base,
               lpaddr_t   pa_base,
               size_t     bytes,
               uintptr_t  l2_flags)
{
    assert(va_base >= l2_base);
    assert(0 == (va_base & (BASE_PAGE_SIZE - 1)));
    assert(0 == (pa_base & (BASE_PAGE_SIZE - 1)));
    assert(0 == (bytes & (BASE_PAGE_SIZE - 1)));

    int bi = (va_base - l2_base) / BASE_PAGE_SIZE;
    int li = bi + bytes / BASE_PAGE_SIZE;

    while (bi < li) {
        paging_set_l2_entry((uintptr_t *)&l2_table[bi], pa_base, l2_flags);
        pa_base += BASE_PAGE_SIZE;
        bi++;
    }
}

static uint32_t elf_to_l2_flags(uint32_t eflags)
{
    switch (eflags & (PF_W|PF_R)) {
    case PF_W|PF_R:
        return (ARM_L2_SMALL_USR_RW |
                ARM_L2_SMALL_CACHEABLE |
                ARM_L2_SMALL_BUFFERABLE);
    case PF_R:
        return (ARM_L2_SMALL_USR_RO |
                ARM_L2_SMALL_CACHEABLE |
                ARM_L2_SMALL_BUFFERABLE);
    default:
        panic("Unknown ELF flags combination.");
    }
}

struct startup_l2_info
{
    union arm_l2_entry* l2_table;
    lvaddr_t   l2_base;
};

static errval_t
startup_alloc_init(
    void*      state,
    genvaddr_t gvbase,
    size_t     bytes,
    uint32_t   flags,
    void**     ret
    )
{
    const struct startup_l2_info* s2i = (const struct startup_l2_info*)state;

    lvaddr_t sv = ROUND_DOWN((lvaddr_t)gvbase, BASE_PAGE_SIZE);
    size_t   off = (lvaddr_t)gvbase - sv;
    lvaddr_t lv = ROUND_UP((lvaddr_t)gvbase + bytes, BASE_PAGE_SIZE);
    lpaddr_t pa;

    //STARTUP_PROGRESS();
    if(cpu_is_bsp()) {
        pa = bsp_alloc_phys_aligned((lv - sv), BASE_PAGE_SIZE);
    } else {
        pa = app_alloc_phys_aligned((lv - sv), BASE_PAGE_SIZE);
    }
    if (lv > sv && (pa != 0)) {
        spawn_init_map(s2i->l2_table, s2i->l2_base, sv,
                       pa, lv - sv, elf_to_l2_flags(flags));
        *ret = (void*)(local_phys_to_mem(pa) + off);
    } else {
        *ret = 0;
    }
    return SYS_ERR_OK;
}

static void
load_init_image(
    struct startup_l2_info* l2i,
    const char *name,
    genvaddr_t* init_ep,
    genvaddr_t* got_base
    )
{
    lvaddr_t elf_base;
    size_t elf_bytes;
    errval_t err;

    *init_ep = *got_base = 0;

    /* Load init ELF32 binary */
    struct multiboot_modinfo *module = multiboot_find_module(name);
    if (module == NULL) {
        panic("Could not find init module!");
    }

    elf_base =  local_phys_to_mem(module->mod_start);
    elf_bytes = MULTIBOOT_MODULE_SIZE(*module);

    debug(SUBSYS_STARTUP, "load_init_image %p %08x\n", elf_base, elf_bytes);
    //printf("load_init_image %p %08x\n", elf_base, elf_bytes);

    err = elf_load(EM_ARM, startup_alloc_init, l2i,
            elf_base, elf_bytes, init_ep);
    if (err_is_fail(err)) {
        //err_print_calltrace(err);
        panic("ELF load of " BSP_INIT_MODULE_NAME " failed!\n");
    }

    // TODO: Fix application linkage so that it's non-PIC.
    struct Elf32_Shdr* got_shdr =
        elf32_find_section_header_name((lvaddr_t)elf_base, elf_bytes, ".got");
    if (got_shdr) {
        *got_base = got_shdr->sh_addr;
    }
}

/// Setup the module cnode, which contains frame caps to all multiboot modules
void create_module_caps(struct spawn_state *st)
{
    struct multiboot_info *mb=
        (struct multiboot_info *)core_data->multiboot_header;
    errval_t err;

    /* Create caps for multiboot modules */
    struct multiboot_modinfo *module =
        (struct multiboot_modinfo *)local_phys_to_mem(mb->mods_addr);

    // Allocate strings area
    lpaddr_t mmstrings_phys = bsp_alloc_phys(BASE_PAGE_SIZE);
    lvaddr_t mmstrings_base = local_phys_to_mem(mmstrings_phys);
    lvaddr_t mmstrings = mmstrings_base;

    // create cap for strings area in first slot of modulecn
    assert(st->modulecn_slot == 0);
    err = caps_create_new(ObjType_Frame, mmstrings_phys, BASE_PAGE_SIZE,
                          BASE_PAGE_SIZE, my_core_id,
                          caps_locate_slot(CNODE(st->modulecn),
                                           st->modulecn_slot++));
    assert(err_is_ok(err));

    /* Walk over multiboot modules, creating frame caps */
    for (int i = 0; i < mb->mods_count; i++) {
        struct multiboot_modinfo *m = &module[i];

        // Set memory regions within bootinfo
        struct mem_region *region =
            &bootinfo->regions[bootinfo->regions_length++];

        genpaddr_t remain = MULTIBOOT_MODULE_SIZE(*m);
        genpaddr_t base_addr = local_phys_to_gen_phys(m->mod_start);

        region->mr_type = RegionType_Module;
        region->mr_base = base_addr;
        region->mrmod_slot = st->modulecn_slot;  // first slot containing caps
        region->mrmod_size = remain;  // size of image _in bytes_
        region->mrmod_data = mmstrings - mmstrings_base; // offset of string in area

        // round up to page size for caps
        remain = ROUND_UP(remain, BASE_PAGE_SIZE);
        assert((base_addr & BASE_PAGE_MASK) == 0);
        assert((remain & BASE_PAGE_MASK) == 0);

        assert(st->modulecn_slot < cnode_get_slots(&st->modulecn->cap));
        // create as DevFrame cap to avoid zeroing memory contents
        err = caps_create_new(ObjType_DevFrame, base_addr, remain,
                              remain, my_core_id,
                              caps_locate_slot(CNODE(st->modulecn),
                                               st->modulecn_slot++));
        assert(err_is_ok(err));

        // Copy multiboot module string to mmstrings area
        strcpy((char *)mmstrings, MBADDR_ASSTRING(m->string));
        mmstrings += strlen(MBADDR_ASSTRING(m->string)) + 1;
        assert(mmstrings < mmstrings_base + BASE_PAGE_SIZE);
    }
}

/* Create physical address range or RAM caps to unused physical memory.
   init_alloc_addr is the last address allocated for the init process, plus
   one. */
static void create_phys_caps(lpaddr_t init_alloc_addr)
{
    struct multiboot_info *mb=
        (struct multiboot_info *)core_data->multiboot_header;
    errval_t err;

    /* Walk multiboot MMAP structure, and create appropriate caps for memory.
       This function assumes that the memory map is sorted by base address,
       and contains no overlaps.  We also assume that the kernel, and init,
       have been allocated at the beginning of the first RAM region, and thus
       that init_alloc_addr represents the lowest unallocated RAM address. */
    genpaddr_t last_end_addr= 0;
    genpaddr_t first_free_byte= local_phys_to_gen_phys(init_alloc_addr);
    debug(SUBSYS_STARTUP, "First free byte is PA:0x%"PRIxGENPADDR".\n",
                          first_free_byte);

    lvaddr_t mmap_vaddr= local_phys_to_mem((lpaddr_t)mb->mmap_addr);
    for(uint32_t i= 0; i < mb->mmap_length; i++) {
        struct multiboot_mmap *mmap = (struct multiboot_mmap *)mmap_vaddr;

        genpaddr_t base_addr = mmap->base_addr;
        genpaddr_t end_addr  = base_addr + (mmap->length - 1);

        debug(SUBSYS_STARTUP, "MMAP PA:0x%"PRIxGENPADDR"-0x%"
                              PRIxGENPADDR" type %"PRIu32"\n",
                              base_addr, end_addr, mmap->type);

        switch(mmap->type) {
            case MULTIBOOT_MEM_TYPE_RAM:
                /* Only map RAM which is greater than init_alloc_addr. */
                if (end_addr >= first_free_byte) {
                    if(base_addr < first_free_byte)
                        base_addr= first_free_byte;
                    debug(SUBSYS_STARTUP, "RAM PA:0x%"PRIxGENPADDR"-0x%"
                                          PRIxGENPADDR"\n",
                                          base_addr, end_addr);

                    assert(end_addr >= base_addr);
                    err= create_caps_to_cnode(base_addr,
                            (end_addr - base_addr) + 1,
                            RegionType_Empty, &spawn_state, bootinfo);
                    assert(err_is_ok(err));
                }
                break;

            case MULTIBOOT_MEM_TYPE_DEVICE:
                /* Device memory will be handled explicitly later. */
                break;

            default:
                if (mmap->base_addr >= first_free_byte) {
                    /* XXX: The multiboot spec just says that mapping types
                     * other than RAM are "reserved", but GRUB always maps the
                     * ACPI tables as type 3, and things like the IOAPIC tend
                     * to show up as type 2 or 4, so we map all these regions
                     * as platform data.  */
                    debug(SUBSYS_STARTUP, "Platform data PA:0x%"PRIxGENPADDR
                                          "-0x%"PRIxGENPADDR"\n", base_addr,
                                          end_addr);
                    assert(base_addr >= first_free_byte);
                    err = create_caps_to_cnode(base_addr, mmap->length,
                            RegionType_PlatformData, &spawn_state, bootinfo);
                    assert(err_is_ok(err));
                }
        }

        last_end_addr= end_addr;
        mmap_vaddr+= mmap->size;
    }

    // Assert that we have some physical address space
    assert(last_end_addr != 0);
}

/*
 * \brief Initialzie page tables
 *
 * This includes setting up page tables for the init process.
 */
static void init_page_tables(void)
{
    // Create page table for init
    if(cpu_is_bsp()) {
        init_l1 =  (union arm_l1_entry *)local_phys_to_mem(bsp_alloc_phys_aligned(INIT_L1_BYTES, ARM_L1_ALIGN));
        memset(init_l1, 0, INIT_L1_BYTES);

        init_l2 = (union arm_l2_entry *)local_phys_to_mem(bsp_alloc_phys_aligned(INIT_L2_BYTES, ARM_L2_ALIGN));
        memset(init_l2, 0, INIT_L2_BYTES);
    } else {
        init_l1 =  (union arm_l1_entry *)local_phys_to_mem(app_alloc_phys_aligned(INIT_L1_BYTES, ARM_L1_ALIGN));
        memset(init_l1, 0, INIT_L1_BYTES);

        init_l2 = (union arm_l2_entry *)local_phys_to_mem(app_alloc_phys_aligned(INIT_L2_BYTES, ARM_L2_ALIGN));
        memset(init_l2, 0, INIT_L2_BYTES);
    }

    MSG("init_page_tables done: init_l1=%p init_l2=%p\n",
            init_l1, init_l2);

    /* Map pagetables into page CN */
    int pagecn_pagemap = 0;

    /*
     * ARM has:
     *
     * L1 has 4096 entries (16KB).
     * L2 Coarse has 256 entries (256 * 4B = 1KB).
     *
     * CPU driver currently fakes having 1024 entries in L1 and
     * L2 with 1024 entries by treating a page as 4 consecutive
     * L2 tables and mapping this as a unit in L1.
     */
    caps_create_new(ObjType_VNode_ARM_l1,
                    mem_to_local_phys((lvaddr_t)init_l1),
                    vnode_objsize(ObjType_VNode_ARM_l1), 0, my_core_id,
                    caps_locate_slot(CNODE(spawn_state.pagecn),
                        pagecn_pagemap++)
                    );

    //STARTUP_PROGRESS();

    // Map L2 into successive slots in pagecn
    size_t i;
    for (i = 0; i < INIT_L2_BYTES / ARM_L2_TABLE_BYTES; i++) {
        size_t objsize_vnode = vnode_objsize(ObjType_VNode_ARM_l2);
        assert(objsize_vnode == ARM_L2_TABLE_BYTES);
        caps_create_new(
                        ObjType_VNode_ARM_l2,
                        mem_to_local_phys((lvaddr_t)init_l2) + i*objsize_vnode,
                        objsize_vnode, 0, my_core_id,
                        caps_locate_slot(CNODE(spawn_state.pagecn),
                            pagecn_pagemap++)
                        );
    }

    /*
     * Initialize init page tables - this just wires the L1
     * entries through to the corresponding L2 entries.
     */
    STATIC_ASSERT(0 == (INIT_VBASE % ARM_L1_SECTION_BYTES), "");
    for (lvaddr_t vaddr = INIT_VBASE;
         vaddr < INIT_SPACE_LIMIT;
         vaddr += ARM_L1_SECTION_BYTES) {
        uintptr_t section = (vaddr - INIT_VBASE) / ARM_L1_SECTION_BYTES;
        uintptr_t l2_off = section * ARM_L2_TABLE_BYTES;
        lpaddr_t paddr = mem_to_local_phys((lvaddr_t)init_l2) + l2_off;
        paging_map_user_pages_l1((lvaddr_t)init_l1, vaddr, paddr);
    }

    MSG("Calling paging_context_switch with address = %"PRIxLVADDR"\n",
           mem_to_local_phys((lvaddr_t) init_l1));
    paging_context_switch(mem_to_local_phys((lvaddr_t)init_l1));
}

/* Locate the first device region below 4GB listed in the multiboot memory
 * map, and truncate it to fit. */
static void
first_device_region(lpaddr_t *base, lpaddr_t *length) {
    struct multiboot_info *mb=
        (struct multiboot_info *)core_data->multiboot_header;

    lvaddr_t mmap_vaddr= local_phys_to_mem((lpaddr_t)mb->mmap_addr);
    for(uint32_t i= 0; i < mb->mmap_length; i++) {
        struct multiboot_mmap *mmap= (struct multiboot_mmap *)mmap_vaddr;

        if(mmap->type == MULTIBOOT_MEM_TYPE_DEVICE) {
            uint64_t base64=   mmap->base_addr;
            uint64_t length64= mmap->length;

            if(base64 > (uint64_t)UINT32_MAX) {
                MSG("device region %"PRIu32" lies above 4GB.\n", i);
            }
            else if(base64 + (length64 - 1) > (uint64_t)UINT32_MAX) {
                MSG("device region %"PRIu32" extends beyond 4GB, "
                    "truncating it.\n", i);
                length64= ((uint64_t)UINT32_MAX - base64) + 1;
            }

            *base=   (lpaddr_t)base64;
            *length= (lpaddr_t)length64;
            return;
        }

        mmap_vaddr+= mmap->size;
    }

    panic("No device regions specified in multiboot memory map.\n");
}

static struct dcb *
spawn_init_common(const char *name, int argc, const char *argv[],
                  lpaddr_t bootinfo_phys, alloc_phys_func alloc_phys,
                  alloc_phys_aligned_func alloc_phys_aligned)
{
    MSG("spawn_init_common %s\n", name);

    lvaddr_t paramaddr;
    struct dcb *init_dcb = spawn_module(&spawn_state, name,
                                        argc, argv,
                                        bootinfo_phys, INIT_ARGS_VBASE,
                                        alloc_phys, alloc_phys_aligned,
                                        &paramaddr);

    init_page_tables();

    MSG("about to call mem_to_local_phys with lvaddr=%"PRIxLVADDR"\n",
           init_l1);

    init_dcb->vspace = mem_to_local_phys((lvaddr_t)init_l1);

    spawn_init_map(init_l2, INIT_VBASE, INIT_ARGS_VBASE,
                   spawn_state.args_page, ARGS_SIZE, INIT_PERM_RW);

    // Map dispatcher
    spawn_init_map(init_l2, INIT_VBASE, INIT_DISPATCHER_VBASE,
                   mem_to_local_phys(init_dcb->disp), DISPATCHER_FRAME_SIZE,
                   INIT_PERM_RW);

    /* Locate the memory-mapped device region. */
    lpaddr_t device_base, device_length;
    first_device_region(&device_base, &device_length);
    MSG("Using device region at PA:0x%"PRIx32"-0x%"PRIx32"\n",
            device_base, device_base + (device_length - 1));
    if((1UL << log2ceil(device_length)) != device_length) {
        panic("Device region isn't a power of two in size.\n");
    }

    /*
     * We create the capability to the devices at this stage and store it
     * in the TASKCN_SLOT_IO, where on x86 the IO capability is stored for
     * device access on PCI.
     *
     * PCI is not available on our existing ARMv7 platforms, but this may be a
     * problem in future.
     */
    struct cte *iocap=
        caps_locate_slot(CNODE(spawn_state.taskcn), TASKCN_SLOT_IO);
    errval_t err=
        caps_create_new(ObjType_DevFrame, device_base, device_length,
                        device_length, my_core_id, iocap);
    assert(err_is_ok(err));

    struct dispatcher_shared_generic *disp
        = get_dispatcher_shared_generic(init_dcb->disp);
    struct dispatcher_shared_arm *disp_arm
        = get_dispatcher_shared_arm(init_dcb->disp);

    /* Initialize dispatcher */
    disp->disabled = true;
    strncpy(disp->name, argv[0], DISP_NAME_LEN);

    /* tell init the vspace addr of its dispatcher */
    disp->udisp = INIT_DISPATCHER_VBASE;

    /* Write the context ID for init - see arch/arm/dispatch.c. */
    cp15_write_contextidr(((uint32_t)init_dcb) & ~MASK(8));

    disp_arm->enabled_save_area.named.r0   = paramaddr;
    disp_arm->enabled_save_area.named.cpsr = ARM_MODE_USR | CPSR_F_MASK;
    arch_set_thread_register(INIT_DISPATCHER_VBASE);

    MSG("spawn_init_common: starting from=%"PRIxLVADDR"\n");

    dump_dispatcher(disp);

    return init_dcb;
}

struct dcb *
spawn_bsp_init(const char *name)
{
    MSG("spawn_bsp_init\n");

    /* Only the first core can run this code */
    assert(cpu_is_bsp());

    /* Allocate bootinfo */
    lpaddr_t bootinfo_phys = bsp_alloc_phys_aligned(BOOTINFO_SIZE, BASE_PAGE_SIZE);
    memset((void *)local_phys_to_mem(bootinfo_phys), 0, BOOTINFO_SIZE);

    /* Construct cmdline args */
    char bootinfochar[16];
    snprintf(bootinfochar, sizeof(bootinfochar), "%u", INIT_BOOTINFO_VBASE);
    const char *argv[] = { "init", bootinfochar };
    int argc = 2;

    struct dcb *init_dcb =
        spawn_init_common(name, argc, argv, bootinfo_phys,
                          bsp_alloc_phys, bsp_alloc_phys_aligned);

    // Map bootinfo
    spawn_init_map(init_l2, INIT_VBASE, INIT_BOOTINFO_VBASE,
                   bootinfo_phys, BOOTINFO_SIZE, INIT_PERM_RW);

    struct startup_l2_info l2_info = { init_l2, INIT_VBASE };

    genvaddr_t init_ep, got_base;
    load_init_image(&l2_info, BSP_INIT_MODULE_NAME, &init_ep, &got_base);

    struct dispatcher_shared_arm *disp_arm =
        get_dispatcher_shared_arm(init_dcb->disp);
    disp_arm->enabled_save_area.named.r9   = got_base;
    disp_arm->got_base = got_base;

    disp_arm->disabled_save_area.named.pc   = init_ep;
    disp_arm->disabled_save_area.named.cpsr = ARM_MODE_USR | CPSR_F_MASK;
    disp_arm->disabled_save_area.named.r9   = got_base;

    /* Create caps for init to use */
    create_module_caps(&spawn_state);
    lpaddr_t init_alloc_end = bsp_alloc_phys(0); // XXX
    create_phys_caps(init_alloc_end);

    /* Fill bootinfo struct */
    //bootinfo->mem_spawn_core = KERNEL_IMAGE_SIZE; // Size of kernel

    return init_dcb;
}

struct dcb *spawn_app_init(struct arm_core_data *new_core_data, const char *name)
{
    errval_t err;

    /* Construct cmdline args */
    // Core id of the core that booted this core
    char coreidchar[10];
    snprintf(coreidchar, sizeof(coreidchar), "%d", core_data->src_core_id);

    // IPI channel id of core that booted this core
    char chanidchar[30];
    snprintf(chanidchar, sizeof(chanidchar), "chanid=%"PRIu32, core_data->chan_id);

    // Arch id of the core that booted this core
    char archidchar[30];
    snprintf(archidchar, sizeof(archidchar), "archid=%d",
             core_data->src_arch_id);

    const char *argv[5] = { name, coreidchar, chanidchar, archidchar };
    int argc = 4;

    struct dcb *init_dcb=
        spawn_init_common(name, argc, argv, 0, app_alloc_phys, app_alloc_phys_aligned);

    // Urpc frame cap
    struct cte *urpc_frame_cte =
        caps_locate_slot(CNODE(spawn_state.taskcn), TASKCN_SLOT_MON_URPC);
    // XXX: Create as devframe so the memory is not zeroed out
    err = caps_create_new(ObjType_DevFrame,
                          core_data->urpc_frame_base,
                          core_data->urpc_frame_size,
                          core_data->urpc_frame_size,
                          my_core_id,
                          urpc_frame_cte);
    assert(err_is_ok(err));
    urpc_frame_cte->cap.type = ObjType_Frame;
    lpaddr_t urpc_ptr = gen_phys_to_local_phys(urpc_frame_cte->cap.u.frame.base);

    /* Map urpc frame at MON_URPC_BASE */
    spawn_init_map(init_l2, INIT_VBASE, MON_URPC_VBASE, urpc_ptr, MON_URPC_SIZE,
                           INIT_PERM_RW);

    struct startup_l2_info l2_info = { init_l2, INIT_VBASE };

    // elf load the domain
    lvaddr_t monitor_binary=
        local_phys_to_mem(core_data->monitor_module.mod_start);
    size_t monitor_binary_size=
        core_data->monitor_module.mod_end -
        core_data->monitor_module.mod_start + 1;
    genvaddr_t entry_point, got_base=0;
    err = elf_load(EM_ARM, startup_alloc_init, &l2_info,
                monitor_binary, monitor_binary_size, &entry_point);
    if (err_is_fail(err)) {
        //err_print_calltrace(err);
        panic("ELF load of init module failed!");
    }

    // TODO: Fix application linkage so that it's non-PIC.
    struct Elf32_Shdr* got_shdr =
        elf32_find_section_header_name(monitor_binary, monitor_binary_size,
                                       ".got");
    if (got_shdr) {
        got_base = got_shdr->sh_addr;
    }

    struct dispatcher_shared_arm *disp_arm =
        get_dispatcher_shared_arm(init_dcb->disp);
    disp_arm->enabled_save_area.named.r9   = got_base;
    disp_arm->got_base = got_base;

    disp_arm->disabled_save_area.named.pc   = entry_point;
    disp_arm->disabled_save_area.named.cpsr = ARM_MODE_USR | CPSR_F_MASK;
    disp_arm->disabled_save_area.named.r9   = got_base;
    arch_set_thread_register(INIT_DISPATCHER_VBASE);

    return init_dcb;
}

void arm_kernel_startup(void)
{
    MSG("arm_kernel_startup entered \n");
    struct dcb *init_dcb;

    if (cpu_is_bsp()) {
        MSG("Doing BSP related bootup \n");

        struct multiboot_info *mb=
            (struct multiboot_info *)core_data->multiboot_header;
        size_t max_addr = max(multiboot_end_addr(mb),
                              (uintptr_t)&kernel_final_byte);

        /* Initialize the location to allocate phys memory from */
        bsp_init_alloc_addr = mem_to_local_phys(max_addr);

        /* Initial KCB was allocated by the boot driver. */
        assert(kcb_current);

        // Bring up init
        init_dcb = spawn_bsp_init(BSP_INIT_MODULE_NAME);
    } else {
        MSG("Doing non-BSP related bootup \n");

        kcb_current = (struct kcb *)
            local_phys_to_mem((lpaddr_t) kcb_current);

        /* Initialize the allocator with the information passed to us */
        app_alloc_phys_start = core_data->memory_base_start;
        app_alloc_phys_end   = app_alloc_phys_start + core_data->memory_bytes;

        init_dcb = spawn_app_init(core_data, APP_INIT_MODULE_NAME);

        // uint32_t irq = platform_get_active_irq();
        // platform_acknowledge_irq(irq);
    }

    /* XXX - this really shouldn't be necessary. */
    // MSG("Trying to enable interrupts\n");
    // __asm volatile ("CPSIE aif");
    // MSG("Done enabling interrupts\n");

    /* printf("HOLD BOOTUP - SPINNING\n"); */
    /* while (1); */
    /* printf("THIS SHOULD NOT HAPPEN\n"); */

    // Should not return
    MSG("Calling dispatch from arm_kernel_startup, start address is=%"PRIxLVADDR"\n",
           get_dispatcher_shared_arm(init_dcb->disp)->enabled_save_area.named.r0);
    dispatch(init_dcb);
    panic("Error spawning init!");

}


text:
{-# LANGUAGE OverloadedStrings #-}
module HStyle.Alignment where

import Data.List (sort)
import Data.Maybe (catMaybes, listToMaybe)
import Data.Text (Text)
import qualified Data.Map as M

import HStyle.Block

-- | In many cases, we want to search for a specific form of
-- "backward-alignment".
--
-- > case x of
-- >     X               -> undefined
-- >     Y y | y < 0     -> undefined
-- >         | otherwise -> undefined
--
-- We can easily figure out the positions of the 'undefined' nodes. However, to
-- get the actual alignment, we need to backtrace and get the alignment of the
-- '->' strings. This is what this function is for.
backwardAlignment :: Range       -- ^ Relevant range
                  -> [Position]  -- ^ Position of the nodes
                  -> [Text]      -- ^ Strings to search for
                  -> Block       -- ^ Source code
                  -> [Position]  -- ^ Found alignment
backwardAlignment range positions strings block =
    catMaybes $ map backwardAlignment' positions
  where
    backwardAlignment' position =
        let cand = [findBackwards range position str block | str <- strings]
        in case catMaybes cand of
            [] -> Nothing
            xs -> Just $ maximum xs

checkAlignmentHead :: [Position]
                   -> Bool
checkAlignmentHead positions = equal $ catMaybes $
    map (listToMaybe . sort . snd) $ M.toAscList $
        foldr (\(l, c) m -> M.insertWith (++) l [c] m) M.empty positions

equal :: Eq a
      => [a]
      -> Bool
equal (x : y : r)
    | x == y    = equal (y : r)
    | otherwise  = False
equal _         = True


text:
package v1alpha3

type ServiceEntryExpansion interface{}

type VirtualServiceExpansion interface{}


text:
from __future__ import print_function
import os
from django.db.models.fields import SlugField
import re
from django.template.loader import get_template
from django.template import Context

class Baker(object):
    """
        Given a dictionary of apps and models, Baker will bake up a bunch of files that will help get your new app up
        and running quickly.
    """

    def bake(self, apps_and_models):
        """
            Iterates a dictionary of apps and models and creates all the necessary files to get up and running quickly.
        """
        for app_label, models in apps_and_models.iteritems():
            model_names = {model.__name__: self.get_field_names_for_model(model) for model in models}
            self.create_directories(app_label)
            self.create_init_files(app_label, model_names.keys(), models)
            self.remove_empty_startapp_files(app_label)
            for file_name in ["forms", "admin"]:
                file_path = "%s/%s.py" % (app_label, file_name)
                template_path = "django_baker/%s" % (file_name)
                self.create_file_from_template(file_path, template_path, {"model_names": model_names})
            for model in models:
                model_attributes = self.model_attributes(app_label, model)
                self.create_files_from_templates(model_attributes)

    def get_field_names_for_model(self, model):
        """
            Returns fields other than id and uneditable fields (DateTimeField where auto_now or auto_now_add is True)
        """
        return [field.name for field in model._meta.fields if field.name != "id" and not
                (field.get_internal_type() == "DateTimeField" and
                 (field.auto_now is True or field.auto_now_add is True))]

    def create_directories(self, app_label):
        """
            If not already there, adds a directory for views, urls and templates.
        """
        for folder_name in ["views", "urls", "templates/%s" % app_label]:
            directory_path = "%s/%s" % (app_label, folder_name)
            if not os.path.exists(directory_path):
                os.makedirs(directory_path)

    def create_init_files(self, app_label, model_names, models):
        """
            If not already there, creates a new init file in views and urls directory.  Init file imports from all
            of the files within the directory.
        """
        model_name_slugs = ["%s_views" % (self.camel_to_slug(model_name)) for model_name in model_names]
        model_names_dict = {self.camel_to_slug(model.__name__): self.camel_to_slug(self.model_name_plural(model)) for
                            model in models}
        for folder_name in ["views", "urls"]:
            file_path = "%s/%s/__init__.py" % (app_label, folder_name)
            template_path = "django_baker/__init__%s" % folder_name
            self.create_file_from_template(file_path, template_path, {"app_label": app_label,
                                                                      "model_name_slugs": model_name_slugs,
                                                                      "model_names_dict": model_names_dict
                                                                      })

    def model_attributes(self, app_label, model):
        """
            Creates a dictionary of model attributes that will be used in the templates.
        """
        model_name = model.__name__
        model_name_plural = self.model_name_plural(model)
        slug_field = self.get_unique_slug_field_name(model)
        slug_field_name = slug_field.name if slug_field else "slug"
        lookup_field = slug_field_name if slug_field else "pk"
        return {
            'app_label': app_label,
            'model': model,
            'model_name': model_name,
            'model_name_slug': self.camel_to_slug(model_name),
            'model_name_plural': model_name_plural,
            'model_name_plural_slug': self.camel_to_slug(model_name_plural),
            'model_fields': self.get_field_names_for_model(model),
            'slug_field': slug_field,
            'slug_field_name': slug_field_name,
            'lookup_field': lookup_field
        }

    def create_files_from_templates(self, model_attributes):
        """
            Determines the correct path to put each file and then calls create file method.
        """
        for folder_name in ["views", "urls"]:
            file_path = "%s/%s/%s_%s.py" % (model_attributes['app_label'], folder_name,
                                            model_attributes['model_name_slug'], folder_name)
            template_path = "django_baker/%s" % (folder_name)
            self.create_file_from_template(file_path, template_path, model_attributes)
        for file_name in ["base", "list", "detail", "create", "update", "delete"]:
            file_path = "%s/templates/%s/%s_%s.html" % (model_attributes['app_label'], model_attributes['app_label'],
                                                        model_attributes['model_name_slug'], file_name)
            template_path = "django_baker/%s.html" % (file_name)
            self.create_file_from_template(file_path, template_path, model_attributes)

    def create_file_from_template(self, file_path, template_path, context_variables):
        """
            Takes template file and context variables and uses django's render method to create new file.
        """
        if os.path.exists(file_path):
            print("\033[91m" + file_path + " already exists.  Skipping." + "\033[0m")
            return
        with open(file_path, 'w') as new_file:
            new_file.write(get_template(template_path).render(Context(context_variables)))
            print("\033[92m" + "successfully baked " + file_path + "\033[0m")

    def remove_empty_startapp_files(self, app_label):
        """
            Removes 'empty' (less than or equal to 4 lines, as that is what they begin with) views, admin, and tests
            files.
        """
        for file_name in ["views", "admin", "tests"]:
            file_path = "%s/%s.py" % (app_label, file_name)
            if os.path.exists(file_path):
                num_lines = sum(1 for line in open(file_path))
                if num_lines <= 4:
                    os.remove(file_path)

    def camel_to_slug(self, name):
        """
            Helper method to convert camel case string (PumpernickelBread) to slug string (pumpernickel_bread)
        """
        name = re.sub(r'([a-z])([A-Z])', r'\1 \2', name).title().replace(" ", "").replace("_", "")
        s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
        slug = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
        return slug

    def model_name_plural(self, model):
        """
            Gets the pluralized version of a model.  Simply adds an 's' to model name if verbose_name_plural isn't set.
        """
        if isinstance(model._meta.verbose_name_plural, str):
            return model._meta.verbose_name_plural
        return "%ss" % model.__name__

    def get_unique_slug_field_name(self, model):
        """
            Determines if model has exactly 1 SlugField that is unique.  If so, returns it.  Otherwise returns None.
        """
        slug_fields = []
        for field in model._meta.fields:
            if field.unique and isinstance(field, SlugField):
                slug_fields.append(field)
        if len(slug_fields) == 1:
            return slug_fields[0]
        return None


text:
<?php

namespace Joselfonseca\LaravelTactician\Locator;

use League\Tactician\Exception\MissingHandlerException;

/**
 * Class LaravelLocator
 *
 * @package Joselfonseca\LaravelTactician\Locator
 */
class LaravelLocator implements LocatorInterface
{

    /**
     * The handlers
     * @var
     */
    protected $handlers;

    /**
     * Bind a handler instance to receive all commands with a certain class
     *
     * @param string $handler          Handler to receive class name
     * @param string $commandClassName Command class e.g. "My\TaskAddedCommand"
     */
    public function addHandler($handler, $commandClassName)
    {
        $handlerInstance = app($handler);
        $this->handlers[$commandClassName] = $handlerInstance;
    }

    /**
     * Allows you to add multiple handlers at once.
     *
     * The map should be an array in the format of:
     *  [
     *      AddTaskCommand::class      => $someHandlerClassName,
     *      CompleteTaskCommand::class => $someHandlerClassName,
     *  ]
     *
     * @param array $commandClassToHandlerMap
     */
    public function addHandlers(array $commandClassToHandlerMap)
    {
        foreach ($commandClassToHandlerMap as $commandClass => $handler) {
            $this->addHandler($handler, $commandClass);
        }
    }

    /**
     * Retrieves the handler for a specified command
     *
     * @param string $commandName
     *
     * @return object
     *
     * @throws MissingHandlerException
     */
    public function getHandlerForCommand($commandName)
    {
        if (!isset($this->handlers[$commandName])) {
            throw MissingHandlerException::forCommand($commandName);
        }

        return $this->handlers[$commandName];
    }
}


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var request = require('request');
var logger = require('winston');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
//app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//Get Environment Variables
var config = require('./config.js');

//Set Logger Information
logger.add(logger.transports.File, { filename: config.log_filename });
logger.level = config.log_level;

logger.debug("TWILIO_ACCOUNT_SID: " + process.env.TWILIO_ACCOUNT_SID)
logger.debug("TWILIO_AUTH_TOKEN: " + process.env.TWILIO_AUTH_TOKEN)
logger.debug("AUTHY_API_KEY: " + process.env.AUTHY_API_KEY)
logger.debug("TWILIO_PHONE_SID:" + process.env.TWILIO_PHONE_SID)
logger.debug("-------------------------------------------");

const twilio = require('twilio')(config.TWILIO_ACCOUNT_SID, config.TWILIO_AUTH_TOKEN);
const enums = require('authy-client').enums;
const Client = require('authy-client').Client;
const authy = new Client({key: config.AUTHY_API_KEY});

var phone_number = null;
var country_code = null;
var authy_id = null;
var phone_sid = null;
var reuse_number = false;
var reporting = [
	{'product':'Phone Verification','status':false,'description':'Phone Verification Tests Not Executed'},
	{'product':'OneCode','status':false,'description':'OneCode Tests Not Executed'}
];

//Receive OneCode SMS Content to be validated
app.post('/onecode', function (req, res) {
  logger.info("Received message: " + req.body.Body);
  var token = req.body.Body.match(/\d/g);
  token = token.join("");
  oneCodeVerify(token);
  res.send('Success!');
})

//Receive Phone Verification SMS Content to be validated
app.post('/verification', function (req, res) {
  logger.info("Received message: " + req.body.Body);
  var token = req.body.Body.match(/\d/g);
  token = token.join("");
  phoneVerificationVerify(token);
  res.send('Success!');
})

//Start the test framework via API
app.post('/start', function (req, res) {
	logger.info("Received request to start testing framework...");
  	tryPhoneVerification();
  	res.send('Success!');
})

/* API Home Page */
app.get('/', function (req, res) {
	res.render('index',{ title : 'Authy OneCode and Phone Verification Automated Testing Framework' })
});

//Get a Twilio Number and set the SMS Webhook - Get the Phone_Number
function tryPhoneVerification(){
	if(config.phone_verification == true){
		logger.info("Running Phone Verification Testing");
		if (config.useExistingNumber == true){
			logger.info("Updating Existing Number to Phone Verification Webhook");
			twilio.incomingPhoneNumbers(process.env.TWILIO_PHONE_SID).update({
				SmsUrl: config.pv_sms_url,
				SmsMethod: 'POST',
				FriendlyName: 'PhoneVerificationTestingNumber'
			}, function(err, number){
				if(err == null){
					country_code = number.phone_number.substring(0,2);
					phone_number = number.phone_number.substring(2,12);
					phone_sid = number.sid;
					logger.info("Country Code: " + country_code + " and Phone Number: " + phone_number);
					logger.debug("Phone SID: " + phone_sid);
					logger.info("Updated existing number to send callback to: " + number.sms_url);
					if(config.onecode == true){
						reuse_number = true;
					}
					//Call Authy Phone Verification
					phoneVerificationRequest(country_code, phone_number);
				}else{
					logger.error("ERROR: " + err.message);
				}
			});
		}else{
			twilio.incomingPhoneNumbers.create({
			SmsUrl: config.pv_sms_url,
			AreaCode: config.area_code,
			FriendlyName: 'PhoneVerificationTestingNumber'
		}, function(err, number){
			if (err == null){
				logger.info("New Twilio Number Registered is: " + number.phone_number);
				country_code = number.phone_number.substring(0,2);
				phone_number = number.phone_number.substring(2,12);
				phone_sid = number.sid;
				logger.info("Country Code: " + country_code + " and Phone Number: " + phone_number);
				logger.debug("Phone SID: " + phone_sid);
				logger.info("Twilio Phone Number has been set to send callback to: " + number.sms_url);
				if(config.onecode == true){
					reuse_number = true;
				}
				//Call Authy Phone Verification
				phoneVerificationRequest(country_code, phone_number);
			}else{
				logger.error("ERROR: " + err.message);
			}
		});
		}
	}else{
		tryOneCode();
	}
}

function tryOneCode(){
	if(config.onecode == true){
		logger.info("Running Authy OneCode Testing");
		if(reuse_number == false && config.useExistingNumber == false){
			logger.info("Getting a New Twilio Number");
			twilio.incomingPhoneNumbers.create({
			SmsUrl: config.oc_sms_url,
			AreaCode: config.area_code,
			FriendlyName: 'OneCodeTestingNumber'
		}, function(err, number){
				if (err == null){
					logger.info("New Twilio Number Registered is: " + number.phone_number);
					country_code = number.phone_number.substring(0,2);
					phone_number = number.phone_number.substring(2,12);
					phone_sid = number.sid;
					logger.info("Country Code: " + country_code + " and Phone Number: " + phone_number);
					logger.debug("Phone SID: " + phone_sid);
					//Call Authy User Registration
					registerUser(country_code, phone_number);
				}else{
					logger.error("ERROR: " + err.message);
				}
			});
		}else{
			logger.info("Reusing Existing Twilio Number");
			logger.info("Updating Existing Number to OneCode Webhook");
			twilio.incomingPhoneNumbers(process.env.TWILIO_PHONE_SID).update({
				SmsUrl: config.oc_sms_url,
				FriendlyName: 'OneCodeTestingNumber'
			}, function(err, number){
				if(err == null){
					country_code = number.phone_number.substring(0,2);
					phone_number = number.phone_number.substring(2,12);
					phone_sid = number.sid;
					logger.info("Country Code: " + country_code + " and Phone Number: " + phone_number);
					logger.debug("Phone SID: " + phone_sid);
					logger.info("Updated existing number to send callback to: " + number.sms_url);
					//Call Authy User Registration
					registerUser(country_code, phone_number);
				} else{
					logger.error("ERROR: " + err.message);
				}
			});
		}
	}
}

 //Remove Twilio Number
 function removeTwilioNumber(){
 	if(reuse_number == false && config.useExistingNumber == false){
	 	twilio.incomingPhoneNumbers(phone_sid).delete(function(err){
	 		if (err) throw err;
	 		logger.info("Twilio Phone Number Released");
	 	});
 	}
}

 //Register the user with Authy - Get the Authy_ID
 function registerUser(country_code, phone_number){
 	reuse_number = false;
 	authy.registerUser({
 		countryCode: 'US',
		email: 'test@test.com',
		phone: phone_number
	}, function (err, registration) {
		if (err) throw err;
		authy_id = registration.user.id;
		logger.info("Authy User Registered: " + authy_id);
		//Call Authy OneCode API
		oneCodeRequest(authy_id);
	});
 }

 //Remove Authy User
function removeUser(authyID){
	logger.info("Removing User " + authyID + " from Authy application");
	var options = {
		url: 'https://api.authy.com/protected/json/users/' + authyID + '/delete',
		method: 'POST',
		form: {'api_key':config.AUTHY_API_KEY}
	}
	request(options, function(error, response, body){
		if(!error && response.statusCode == 200){
			logger.debug(body);
			logger.info('User has been removed from application');
		}else{
			logger.error("ERROR: " + error);
		}
	})
}

//Trigger OneCode Request
function oneCodeRequest(authyID){
	authy.requestSms({ authyId: authyID }, function(err, res) {
  		if (err) throw err;
  		logger.info('Message sent successfully to', phone_number);
  		if (config.polling == true){
				pollTwilioNumber(false);
  		}
	});
}

//Validate OneCode Request
function oneCodeVerify(token){
	logger.info("Validating token: " + token + " for Authy ID: " + authy_id);
	authy.verifyToken({ authyId: authy_id, token: token }, function(err, res) {
		if (err){
			console.log(JSON.stringify(reporting));
		}else{
			logger.info("Token: " + res.token);
			reporting[1].status = true;
			reporting[1].description = 'OneCode Tests Executed Successfully';
			console.log(JSON.stringify(reporting));
		}
	});
	removeUser(authy_id);
	if(config.remove_number == true){
		removeTwilioNumber();
	}
}

//Trigger Phone Verification
function phoneVerificationRequest(country_code, phone_number){
	logger.info("Starting Phone Verification for: " + phone_number);
	var options = {
		url: 'https://api.authy.com/protected/json/phones/verification/start',
		method: 'POST',
		form: {'api_key':config.AUTHY_API_KEY,'country_code':country_code,'phone_number':phone_number,'via':'sms'}
	}
	request(options, function(error, response, body){
		if(!error && response.statusCode == 200){
			logger.debug("Phone Information: " + body);
			if (config.polling == true){
				pollTwilioNumber(true);
  			}
		}else{
			logger.error("ERROR: " + error);
		}
	})
}

//Validate Phone Verification Request
function phoneVerificationVerify(token){
	authy.verifyPhone({
		countryCode: 'US',
		phone: phone_number,
		token: token }, function(err, res) {
			if (err){
				console.log(JSON.stringify(reporting));
			}else{
				logger.info(res.message);
				reporting[0].status = true;
				reporting[0].description = 'Phone Verification Tests Executed Successfully';
				if(config.onecode == false){
					console.log(JSON.stringify(reporting));
				}
			}
		});
	if(config.remove_number == true){
		removeTwilioNumber();
	}
	tryOneCode();
}

//Poll Twilio Number for New SMS Messages
function pollTwilioNumber(verify){
	logger.info("Polling Twilio Number for new SMS messages");
	setTimeout(function () {
		twilio.messages.list(function(err, data) {
			if(err){
				logger.error(err.message)
			}else{
				_msg = data.messages[0].body;
				console.log("Got message: " + _msg);
				var token = _msg.match(/\d/g);
				token = token.join("");
				if(verify == true){
					phoneVerificationVerify(token);
				}else{
					oneCodeVerify(token);
				}
			}
		});
	}, 3000);

}

//Start Testing Framework Automatically
if(config.runOnStartup == true){
	tryPhoneVerification();
}

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
import re

import six

from nailgun.settings import settings
from nailgun.test import base

class TestSettings(base.BaseTestCase):

    def test_log_format_remote_openstack(self):
        syslog_w_app = (
            '2014-12-12T11:00:30.098105+00:00 info: 2014-12-12 11:00:30.003 '
            '14349 INFO neutron.common.config [-] Logging enabled!')
        syslog = (
            '2014-12-12T10:57:15.437488+00:00 debug: Loading app ec2 from '
            '/etc/nova/api-paste.ini')

        openstack_format = filter(
            lambda log: log['log_format_id'] == 'remote_openstack',
            settings.LOG_FORMATS)[0]

        regexp = re.compile(openstack_format['regexp'])
        syslog_w_app_re = regexp.match(syslog_w_app)
        syslog_re = regexp.match(syslog)

        syslog_result = {
            'text': 'Loading app ec2 from /etc/nova/api-paste.ini',
            'level': 'debug',
            'date': '2014-12-12T10:57:15'}

        syslog_w_app_result = {
            'text': 'neutron.common.config [-] Logging enabled!',
            'level': 'info',
            'date': '2014-12-12T11:00:30'}

        for group, value in six.iteritems(syslog_result):
            self.assertEqual(syslog_re.group(group),
                             syslog_result[group])

        for group, value in six.iteritems(syslog_w_app_result):
            self.assertEqual(syslog_w_app_re.group(group),
                             syslog_w_app_result[group])


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary.

  Built-in Tomcat manager roles:
    - manager-gui    - allows access to the HTML GUI and the status pages
    - manager-script - allows access to the HTTP API and the status pages
    - manager-jmx    - allows access to the JMX proxy and the status pages
    - manager-status - allows access to the status pages only

  The users below are wrapped in a comment and are therefore ignored. If you
  wish to configure one or more of these users for use with the manager web
  application, do not forget to remove the <!.. ..> that surrounds them. You
  will also need to set the passwords to something appropriate.
-->
<!--
  <user username="admin" password="<must-be-changed>" roles="manager-gui"/>
  <user username="robot" password="<must-be-changed>" roles="manager-script"/>
-->
<!--
  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
</tomcat-users>


text:
package info.tongrenlu.mapper;

import info.tongrenlu.domain.ArticleBean;

import java.util.Map;

public interface ArticleMapper {

    public void insert(ArticleBean articleBean);

    public void update(Map<String, Object> param);

    public void delete(ArticleBean articleBean);

    public void publish(Map<String, Object> param);

}