text:
#include "clar_libgit2.h"

#include "fileops.h"
#include "git2/reflog.h"
#include "reflog.h"
#include "refs.h"
#include "reflog_helpers.h"

static const char *g_email = "foo@example.com";
static git_repository *g_repo;

/* Fixture setup and teardown */
void test_refs_reflog_messages__initialize(void)
{
	g_repo = cl_git_sandbox_init("testrepo.git");
	cl_git_pass(git_repository_set_ident(g_repo, "Foo Bar", g_email));
}

void test_refs_reflog_messages__cleanup(void)
{
	cl_git_sandbox_cleanup();
}

void test_refs_reflog_messages__setting_head_updates_reflog(void)
{
	git_object *tag;
	git_signature *sig;
	git_annotated_commit *annotated;

	cl_git_pass(git_signature_now(&sig, "me", "foo@example.com"));

	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/haacked")); /* 4 */
	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/unborn"));
	cl_git_pass(git_revparse_single(&tag, g_repo, "tags/test"));
	cl_git_pass(git_repository_set_head_detached(g_repo, git_object_id(tag))); /* 3 */
	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/haacked"));        /* 2 */
	cl_git_pass(git_repository_set_head(g_repo, "refs/tags/test"));            /* 1 */
	cl_git_pass(git_repository_set_head(g_repo, "refs/remotes/test/master"));  /* 0 */

	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 4,
		NULL, "refs/heads/haacked",
		"foo@example.com",
		"checkout: moving from master to haacked");
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 3,
		NULL, "tags/test^{commit}",
		"foo@example.com",
		"checkout: moving from unborn to e90810b8df3e80c413d903f631643c716887138d");
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 2,
		"tags/test^{commit}", "refs/heads/haacked",
		"foo@example.com",
		"checkout: moving from e90810b8df3e80c413d903f631643c716887138d to haacked");
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 1,
		"refs/heads/haacked", "tags/test^{commit}",
		"foo@example.com",
		"checkout: moving from haacked to test");
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		"tags/test^{commit}", "refs/remotes/test/master",
		"foo@example.com",
		"checkout: moving from e90810b8df3e80c413d903f631643c716887138d to test/master");

	cl_git_pass(git_annotated_commit_from_revspec(&annotated, g_repo, "haacked~0"));
	cl_git_pass(git_repository_set_head_detached_from_annotated(g_repo, annotated));

	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		NULL, "refs/heads/haacked",
		"foo@example.com",
		"checkout: moving from be3563ae3f795b2b4353bcce3a527ad0a4f7f644 to haacked~0");

	git_annotated_commit_free(annotated);
	git_object_free(tag);
	git_signature_free(sig);
}

void test_refs_reflog_messages__setting_head_to_same_target_ignores_reflog(void)
{
	size_t nentries, nentries_after;

	nentries = reflog_entrycount(g_repo, GIT_HEAD_FILE);

	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/haacked"));
	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/haacked"));

	nentries_after = reflog_entrycount(g_repo, GIT_HEAD_FILE);

	cl_assert_equal_i(nentries + 1, nentries_after);
}

void test_refs_reflog_messages__detaching_writes_reflog(void)
{
	git_signature *sig;
	git_oid id;
	const char *msg;

	cl_git_pass(git_signature_now(&sig, "me", "foo@example.com"));

	msg = "checkout: moving from master to e90810b8df3e80c413d903f631643c716887138d";
	git_oid_fromstr(&id, "e90810b8df3e80c413d903f631643c716887138d");
	cl_git_pass(git_repository_set_head_detached(g_repo, &id));
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"e90810b8df3e80c413d903f631643c716887138d",
		NULL, msg);

	msg = "checkout: moving from e90810b8df3e80c413d903f631643c716887138d to haacked";
	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/haacked"));
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		"e90810b8df3e80c413d903f631643c716887138d",
		"258f0e2a959a364e40ed6603d5d44fbb24765b10",
		NULL, msg);

	git_signature_free(sig);
}

void test_refs_reflog_messages__orphan_branch_does_not_count(void)
{
	git_oid id;
	const char *msg;

	/* Have something known */
	msg = "checkout: moving from master to e90810b8df3e80c413d903f631643c716887138d";
	git_oid_fromstr(&id, "e90810b8df3e80c413d903f631643c716887138d");
	cl_git_pass(git_repository_set_head_detached(g_repo, &id));
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"e90810b8df3e80c413d903f631643c716887138d",
		NULL, msg);

	/* Switching to an orphan branch does not write to the reflog */
	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/orphan"));
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"e90810b8df3e80c413d903f631643c716887138d",
		NULL, msg);

	/* And coming back, we set the source to zero */
	msg = "checkout: moving from orphan to haacked";
	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/haacked"));
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		"0000000000000000000000000000000000000000",
		"258f0e2a959a364e40ed6603d5d44fbb24765b10",
		NULL, msg);
}

void test_refs_reflog_messages__branch_birth(void)
{
	git_signature *sig;
	git_oid id;
	git_tree *tree;
	git_reference *ref;
	const char *msg;
	size_t nentries, nentries_after;

	nentries = reflog_entrycount(g_repo, GIT_HEAD_FILE);

	cl_git_pass(git_signature_now(&sig, "me", "foo@example.com"));

	cl_git_pass(git_repository_head(&ref, g_repo));
	cl_git_pass(git_reference_peel((git_object **) &tree, ref, GIT_OBJECT_TREE));

	cl_git_pass(git_repository_set_head(g_repo, "refs/heads/orphan"));

	nentries_after = reflog_entrycount(g_repo, GIT_HEAD_FILE);

	cl_assert_equal_i(nentries, nentries_after);

	msg = "message 2";
	cl_git_pass(git_commit_create(&id, g_repo, "HEAD", sig, sig, NULL, msg, tree, 0, NULL));

	cl_assert_equal_i(1, reflog_entrycount(g_repo, "refs/heads/orphan"));

	nentries_after = reflog_entrycount(g_repo, GIT_HEAD_FILE);

	cl_assert_equal_i(nentries + 1, nentries_after);

	git_signature_free(sig);
	git_tree_free(tree);
	git_reference_free(ref);
}

void test_refs_reflog_messages__commit_on_symbolic_ref_updates_head_reflog(void)
{
	git_signature *sig;
	git_oid id;
	git_tree *tree;
	git_reference *ref1, *ref2;
	const char *msg;
	size_t nentries_head, nentries_master;

	nentries_head = reflog_entrycount(g_repo, GIT_HEAD_FILE);

	cl_git_pass(git_signature_now(&sig, "me", "foo@example.com"));

	cl_git_pass(git_repository_head(&ref1, g_repo));
	cl_git_pass(git_reference_peel((git_object **) &tree, ref1, GIT_OBJECT_TREE));

	nentries_master = reflog_entrycount(g_repo, "refs/heads/master");

	msg = "message 1";
	cl_git_pass(git_reference_symbolic_create(&ref2, g_repo, "refs/heads/master", "refs/heads/foo", 1, msg));

	cl_assert_equal_i(0, reflog_entrycount(g_repo, "refs/heads/foo"));
	cl_assert_equal_i(nentries_head, reflog_entrycount(g_repo, GIT_HEAD_FILE));
	cl_assert_equal_i(nentries_master, reflog_entrycount(g_repo, "refs/heads/master"));

	msg = "message 2";
	cl_git_pass(git_commit_create(&id, g_repo, "HEAD", sig, sig, NULL, msg, tree, 0, NULL));

	cl_assert_equal_i(1, reflog_entrycount(g_repo, "refs/heads/foo"));
	cl_assert_equal_i(nentries_head + 1, reflog_entrycount(g_repo, GIT_HEAD_FILE));
	cl_assert_equal_i(nentries_master, reflog_entrycount(g_repo, "refs/heads/master"));

	git_signature_free(sig);
	git_reference_free(ref1);
	git_reference_free(ref2);
	git_tree_free(tree);
}

void test_refs_reflog_messages__show_merge_for_merge_commits(void)
{
	git_oid b1_oid;
	git_oid b2_oid;
	git_oid merge_commit_oid;
	git_commit *b1_commit;
	git_commit *b2_commit;
	git_signature *s;
	git_commit *parent_commits[2];
	git_tree *tree;

	cl_git_pass(git_signature_now(&s, "alice", "alice@example.com"));

	cl_git_pass(git_reference_name_to_id(&b1_oid, g_repo, "HEAD"));
	cl_git_pass(git_reference_name_to_id(&b2_oid, g_repo, "refs/heads/test"));

	cl_git_pass(git_commit_lookup(&b1_commit, g_repo, &b1_oid));
	cl_git_pass(git_commit_lookup(&b2_commit, g_repo, &b2_oid));

	parent_commits[0] = b1_commit;
	parent_commits[1] = b2_commit;

	cl_git_pass(git_commit_tree(&tree, b1_commit));

	cl_git_pass(git_commit_create(&merge_commit_oid,
		g_repo, "HEAD", s, s, NULL,
		"Merge commit", tree,
		2, (const struct git_commit **) parent_commits));

	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		NULL,
		git_oid_tostr_s(&merge_commit_oid),
		NULL, "commit (merge): Merge commit");

	git_tree_free(tree);
	git_commit_free(b1_commit);
	git_commit_free(b2_commit);
	git_signature_free(s);
}

void test_refs_reflog_messages__creating_a_direct_reference(void)
{
	git_reference *reference;
	git_oid id;
	git_reflog *reflog;
	const git_reflog_entry *entry;

	const char *name = "refs/heads/new-head";
	const char *message = "You've been logged, mate!";

	cl_git_pass(git_reference_name_to_id(&id, g_repo, "HEAD"));

	cl_git_pass(git_reference_create(&reference, g_repo, name, &id, 0, message));

	cl_git_pass(git_reflog_read(&reflog, g_repo, name));
	cl_assert_equal_sz(1, git_reflog_entrycount(reflog));

	entry = git_reflog_entry_byindex(reflog, 0);
	cl_assert(git_oid_streq(&entry->oid_old, GIT_OID_HEX_ZERO) == 0);
	cl_assert_equal_oid(&id, &entry->oid_cur);
	cl_assert_equal_s(message, entry->msg);

	git_reflog_free(reflog);
	git_reference_free(reference);
}

void test_refs_reflog_messages__renaming_ref(void)
{
	git_reference *ref, *new_ref;

	cl_git_pass(git_reference_lookup(&ref, g_repo, "refs/heads/master"));
	cl_git_pass(git_reference_rename(&new_ref, ref, "refs/heads/renamed", false,
									 "message"));

	cl_reflog_check_entry(g_repo, git_reference_name(new_ref), 0,
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"foo@example.com", "message");

	git_reference_free(ref);
	git_reference_free(new_ref);
}

void test_refs_reflog_messages__updating_a_direct_reference(void)
{
	git_reference *ref, *ref_out, *target_ref;
	git_oid target_id;
	const char *message = "You've been logged, mate!";

	git_reference_name_to_id(&target_id, g_repo, "refs/heads/haacked");
	cl_git_pass(git_reference_lookup(&target_ref, g_repo, "refs/heads/haacked"));

	cl_git_pass(git_reference_lookup(&ref, g_repo, "refs/heads/master"));

	cl_git_pass(git_reference_set_target(&ref_out, ref, &target_id, message));

	cl_reflog_check_entry(g_repo, "refs/heads/master", 0,
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"258f0e2a959a364e40ed6603d5d44fbb24765b10",
		NULL, message);

	git_reference_free(target_ref);
	git_reference_free(ref);
	git_reference_free(ref_out);
}

#define NEW_BRANCH_NAME "new-branch-on-the-block"

void test_refs_reflog_messages__creating_branches_default_messages(void)
{
	git_buf buf = GIT_BUF_INIT;
	git_annotated_commit *annotated;
	git_object *obj;
	git_commit *target;
	git_reference *branch1, *branch2;

	cl_git_pass(git_revparse_single(&obj, g_repo, "e90810b8df3"));
	cl_git_pass(git_commit_lookup(&target, g_repo, git_object_id(obj)));
	git_object_free(obj);

	cl_git_pass(git_branch_create(&branch1, g_repo, NEW_BRANCH_NAME, target, false));

	cl_git_pass(git_buf_printf(&buf, "branch: Created from %s", git_oid_tostr_s(git_commit_id(target))));
	cl_reflog_check_entry(g_repo, "refs/heads/" NEW_BRANCH_NAME, 0,
		GIT_OID_HEX_ZERO,
		git_oid_tostr_s(git_commit_id(target)),
		g_email, git_buf_cstr(&buf));

	cl_git_pass(git_reference_remove(g_repo, "refs/heads/" NEW_BRANCH_NAME));

	cl_git_pass(git_annotated_commit_from_revspec(&annotated, g_repo, "e90810b8df3"));
	cl_git_pass(git_branch_create_from_annotated(&branch2, g_repo, NEW_BRANCH_NAME, annotated, true));

	cl_reflog_check_entry(g_repo, "refs/heads/" NEW_BRANCH_NAME, 0,
		GIT_OID_HEX_ZERO,
		git_oid_tostr_s(git_commit_id(target)),
		g_email, "branch: Created from e90810b8df3");

	git_annotated_commit_free(annotated);
	git_buf_dispose(&buf);
	git_commit_free(target);
	git_reference_free(branch1);
	git_reference_free(branch2);
}

void test_refs_reflog_messages__moving_branch_default_message(void)
{
	git_reference *branch;
	git_reference *new_branch;
	git_oid id;

	cl_git_pass(git_reference_lookup(&branch, g_repo, "refs/heads/master"));
	git_oid_cpy(&id, git_reference_target(branch));
	cl_git_pass(git_branch_move(&new_branch, branch, "master2", 0));

	cl_reflog_check_entry(g_repo, git_reference_name(new_branch), 0,
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		g_email,
		"branch: renamed refs/heads/master to refs/heads/master2");

	git_reference_free(branch);
	git_reference_free(new_branch);
}

void test_refs_reflog_messages__detaching_head_default_message(void)
{
	git_reference *ref;

	cl_assert_equal_i(false, git_repository_head_detached(g_repo));

	cl_git_pass(git_repository_detach_head(g_repo));
	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		NULL, "checkout: moving from master to a65fedf39aefe402d3bb6e24df4d4f5fe4547750");
	cl_assert_equal_i(true, git_repository_head_detached(g_repo));

	/* take the repo back to its original state */
	cl_git_pass(git_reference_symbolic_create(&ref, g_repo, "HEAD", "refs/heads/master",
											  true, "REATTACH"));

	cl_reflog_check_entry(g_repo, GIT_HEAD_FILE, 0,
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		"a65fedf39aefe402d3bb6e24df4d4f5fe4547750",
		NULL, "REATTACH");

	cl_assert_equal_i(false, git_repository_head_detached(g_repo));

	git_reference_free(ref);
}


text:
<?php

namespace Google\Cloud\Core\Tests\Unit\Batch;

use Google\Cloud\Core\Batch\JobConfig;
use Google\Cloud\Core\Batch\BatchJob;
use PHPUnit\Framework\TestCase;

/**
 * @group core
 * @group batch
 */
class JobConfigTest extends TestCase
{
    private $config;
    private $identifier;
    private $func;
    private $idNum;

    public function setUp()
    {
        $this->config = new JobConfig();
        $this->identifier = 'job1';
        $this->func = 'myFunc';
        $this->config->registerJob(
            $this->identifier,
            function ($id) {
                return new BatchJob($this->identifier, $this->func, $id);
            },
            []
        );
        // It must have 1 as the idNum.
        $this->idNum = 1;
    }

    public function testGetJobFromId()
    {
        $job = $this->config->getJobFromId($this->identifier);
        $this->assertEquals($this->idNum, $job->id());
        $this->assertEquals($this->identifier, $job->identifier());
        $this->assertNull($this->config->getJobFromId('bogus'));
    }

    public function testGetJobFromIdNum()
    {
        $job = $this->config->getJobFromIdNum($this->idNum);
        $this->assertEquals($this->idNum, $job->id());
        $this->assertEquals($this->identifier, $job->identifier());
        $this->assertNull($this->config->getJobFromIdNum(10));
    }

    public function testRegisterJob()
    {
        $identifier = 'job2';
        $this->config->registerJob(
            $identifier,
            function ($id) use ($identifier) {
                return new BatchJob($identifier, $this->func, $id);
            },
            []
        );
        // The idNum is 1 origin, incremented by 1
        $job = $this->config->getJobFromIdNum(2);
        $this->assertEquals(2, $job->id());
        $this->assertEquals($identifier, $job->identifier());
    }

    public function testGetjobs()
    {
        $identifier = 'job2';
        $this->config->registerJob(
            $identifier,
            function ($id) use ($identifier) {
                return new BatchJob($identifier, $this->func, $id);
            },
            []
        );
        $jobs = $this->config->getJobs();
        $this->assertCount(2, $jobs);
        $this->assertEquals($this->idNum, $jobs[$this->identifier]->id());
        $this->assertEquals(2, $jobs[$identifier]->id());
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace RemoteExecution.Dispatchers.Messages
{
	[Serializable]
	internal class ResponseMessage : IResponseMessage
	{
		public ResponseMessage(string id, object value)
		{
			CorrelationId = id;
			Value = value;
		}

		public ResponseMessage() { }

		#region IResponseMessage Members

		public object Value { get; set; }

		public string CorrelationId { get; set; }
		public string MessageType { get { return CorrelationId; } }

		#endregion
	}
}


text:
from __future__ import unicode_literals

from django.db import migrations
import wagtail.core.fields

class Migration(migrations.Migration):

    dependencies = [
        ('home', '0002_create_homepage'),
    ]

    operations = [
        migrations.AlterField(
            model_name='teammember',
            name='bio',
            field=wagtail.core.fields.RichTextField(help_text='The team member bio', max_length=1000),
        ),
    ]


text:
/**
 * DO NOT EDIT
 *
 * This file was automatically generated by
 *   https://github.com/Polymer/gen-typescript-declarations
 *
 * To modify these typings, edit the source file(s):
 *   paper-input-addon-behavior.html
 */

/// <reference path="../polymer/types/polymer.d.ts" />

declare namespace Polymer {

  /**
   * Use `Polymer.PaperInputAddonBehavior` to implement an add-on for
   * `<paper-input-container>`. A add-on appears below the input, and may display
   * information based on the input value and validity such as a character counter
   * or an error message.
   */
  interface PaperInputAddonBehavior {
    attached(): void;

    /**
     * The function called by `<paper-input-container>` when the input value or
     * validity changes.
     *
     * @param state     inputElement: The input element.
     *     value: The input value.
     *     invalid: True if the input value is invalid.
     */
    update(state: {invalid: boolean, inputElement?: Element|null, value?: string}): void;
  }

  const PaperInputAddonBehavior: object;
}


text:
{% extends "base.html" %}
{% block content %}
    {{ block.super }}

403

        You don't have permission to do that. Contact your administrator for additional access.

    {% endblock %}


text:
package geeksforgeeks;

import geeksforgeeks._01DataStructures_BinaryTree_00.Node;

/*
 * http://www.geeksforgeeks.org/find-next-right-node-of-a-given-key/
 * Find next right node of a given key
 */;
 public class _01DataStructures_BinaryTree_45 {
	 public static void main(String[] args) {
		 _01DataStructures_BinaryTree_00 binaryTree1=new _01DataStructures_BinaryTree_00();
		 binaryTree1.insert(null,null,10);
		 binaryTree1.insert(10,"left",2);
		 binaryTree1.insert(10,"right",6);
		 binaryTree1.insert(2,"left",8);
		 binaryTree1.insert(2,"right",4);
		 binaryTree1.insert(6,"right",5);
		 System.out.println(findNextRight(binaryTree1,2));
	 }

	 private static int findNextRight(
			 _01DataStructures_BinaryTree_00 binaryTree1, int data) {
		 return findNextRight(binaryTree1.rootNode,data);
	 }

	 private static int findNextRight(Node node, int data) {
		 tempQueue queue=new tempQueue();
		 queue.add(node);
		 if(node!=null){
			 boolean next=false;
			 while(!queue.isEmpty()){
				 Node n=queue.poll();
				 if(next==true)
					 return n.data;
				 if(n.data==(int)data)
					 next=true;
				 //System.out.println(n.data+",");
				 if(n.left!=null)
					 queue.add(n.left);
				 if(n.right!=null)
					 queue.add(n.right);
			 }
		 }
		 return -1;
	 }

 }


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:background="@android:color/black"
    tools:context=".Excel2SQLiteActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/edt_file_path"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textColorHint="@color/colorAccent"
            android:textColor="@color/colorAccent"
            android:hint="@string/file_path"
            android:inputType="text" />

        <Button
            android:id="@+id/btn_import"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:text="@string/import_"
            android:layout_marginLeft="5dp"
            android:textColor="@color/colorAccent" />
    </LinearLayout>
</LinearLayout>


text:
from wagtail.wagtailcore import blocks
from wagtail.wagtailcore.blocks import RawHTMLBlock, StructBlock
from wagtail.wagtailembeds.blocks import EmbedBlock as WagtailEmbedBlock
from wagtail.wagtailimages.blocks import ImageChooserBlock

class HeadingBlock(blocks.CharBlock):
    class Meta:
        classname = 'full title'
        icon = 'title'
        template = 'widgets/heading.html'

    def get_context(self, value):
        context = super().get_context(value)
        context['level'] = 1
        context['content'] = value
        return context

class RichTextBlock(blocks.RichTextBlock):
    class Meta:
        icon = 'pilcrow'
        template = 'widgets/richtext.html'

    def get_context(self, value):
        context = super().get_context(value)
        context['content'] = value
        return context

class ImageBlock(ImageChooserBlock):
    class Meta:
        icon = 'image'
        template = 'widgets/image.html'

    def get_context(self, value):
        context = super().get_context(value)
        context['url'] = value.get_rendition('max-1200x1200').url
        context['name'] = value.title
        return context

class EmbedBlock(WagtailEmbedBlock):
    class Meta:
        icon = 'media'
        template = 'widgets/embed.html'

    def get_context(self, value):
        context = super().get_context(value)
        embed = value
        context['embed'] = embed
        return context

# class QABlock(StructBlock):
#     question = CharBlock()
#     answer = RichTextBlock()

BASE_BLOCKS = [
    ('heading', HeadingBlock()),
    ('rich_text', RichTextBlock()),
    ('image', ImageBlock()),
    ('embed', EmbedBlock()),
]

ALL_BLOCKS = BASE_BLOCKS + [
    ('html', RawHTMLBlock()),
]


text:
include_recipe "postgresql::client"

# Create a group and user like the package will.
# Otherwise the templates fail.

group "postgres" do
  gid 26
end

user "postgres" do
  shell "/bin/bash"
  comment "PostgreSQL Server"
  home "/var/lib/pgsql"
  gid "postgres"
  system true
  uid 26
  supports :manage_home => false
end

node['postgresql']['server']['packages'].each do |pg_pack|

  package pg_pack

end

execute "/sbin/service #{node['postgresql']['server']['service_name']} initdb" do
  not_if { ::FileTest.exist?(File.join(node['postgresql']['dir'], "PG_VERSION")) }
end

service "postgresql" do
  service_name node['postgresql']['server']['service_name']
  supports :restart => true, :status => true, :reload => true
  action [:enable, :start]
end


text:
<?php

namespace ZendTest\Log;

use Zend\Log\WriterPluginManager;
use Zend\ServiceManager\ServiceManager;

/**
 * @group      Zend_Log
 */
class WriterPluginManagerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var WriterPluginManager
     */
    protected $plugins;

    public function setUp()
    {
        $this->plugins = new WriterPluginManager(new ServiceManager());
    }

    public function testInvokableClassFirephp()
    {
        $firephp = $this->plugins->get('firephp');
        $this->assertInstanceOf('Zend\Log\Writer\Firephp', $firephp);
    }
}


text:
// ReRap Version 0.9
// Copyright 2011 Matthew Mikolay.
//
// This file is part of ReRap.
//
// ReRap is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ReRap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ReRap.  If not, see <http://www.gnu.org/licenses/>.

#include "invalidindex.h"

/*** Constructor ***/
InvalidIndexException::InvalidIndexException(unsigned int pLineNum, unsigned int pColNum, long pValue)
{
	setLineNumber(pLineNum);
	setColumnNumber(pColNum);
	setValue(pValue);
	showArgNum = false;
	updateMessage();
}

/*** Constructor ***/
InvalidIndexException::InvalidIndexException(unsigned int pLineNum, unsigned int pColNum, long pValue, unsigned char pArgNum)
{
	setLineNumber(pLineNum);
	setColumnNumber(pColNum);
	setValue(pValue);
	setArgumentNumber(pArgNum);
	showArgNum = true;
	updateMessage();
}

/*** Set the value ***/
void InvalidIndexException::setValue(long pValue)
{
	value = pValue;
}

/*** Get the value ***/
long InvalidIndexException::getValue()
{
	return value;
}

/*** Set the argument number ***/
void InvalidIndexException::setArgumentNumber(unsigned int pArgNum)
{
	argNum = pArgNum;
}

/*** Get the argument number ***/
unsigned int InvalidIndexException::getArgumentNumber()
{
	return argNum;
}

/*** Update the message ***/
void InvalidIndexException::updateMessage()
{
	std::string mess = "";
	if(showArgNum)
	{
		std::ostringstream oss;
		oss << argNum;
		mess.assign("At argument ");
		mess.append(oss.str());
		mess.append(". . .\n\t");
	}
	std::ostringstream oss;
	oss << getValue();
	mess.append("Invalid integer index with value of " + oss.str() + ".");
	setMessage(mess);
}

/*** Destructor ***/
InvalidIndexException::~InvalidIndexException() throw()
{
}


text:
function Foo() {
}
Foo.prototype[Symbol.iterator] = function() {
  var i = 0;
  return { next: function() { return { value: i++, done: i == 10 } } };
};

var foo = new Foo();
console.log ([1, ...foo][5]);


text:
namespace Antlr4.Runtime.Tree
{
    public interface ITerminalNode : IParseTree
    {
        IToken Symbol
        {
            get;
        }

        new IRuleNode Parent
        {
            get;
        }
    }
}


text:
typedef struct {
    int (*update_url)(pt_idata_pipe *pipe, const char *url);
    int (*destroy)(pt_idata_pipe *pipe);
} pt_ipipe_interface;

typedef struct pt_idata_pipe {
    pt_ipipe_interface *interface;
} pt_idata_pipe;

#endif


text:
[Full Changelog](https://github.com/camptocamp/facterdb/compare/0.0.1...0.1.0)

**Implemented enhancements:**

- Add missing facts [\#3](https://github.com/camptocamp/facterdb/issues/3)
- No need for include with self.\# [\#2](https://github.com/camptocamp/facterdb/pull/2) ([raphink](https://github.com/raphink))
- Use jgrep to filter out OS facts [\#1](https://github.com/camptocamp/facterdb/pull/1) ([raphink](https://github.com/raphink))

**Fixed bugs:**

- Use a relative factsdir for the lib [\#4](https://github.com/camptocamp/facterdb/pull/4) ([raphink](https://github.com/raphink))

## [0.0.1](https://rubygems.org/gems/facterdb/versions/0.0.1) (2015-05-29)

\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*


text:
package com.facebook.buck.intellij.ideabuck.actions;

import com.facebook.buck.intellij.ideabuck.ui.BuckUIManager;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;

public class ScrollToEndAction extends ToggleAction implements DumbAware {

  public ScrollToEndAction() {
    final String message = ActionsBundle.message("action.EditorConsoleScrollToTheEnd.text");
    getTemplatePresentation().setDescription(message);
    getTemplatePresentation().setText(message);
    getTemplatePresentation().setIcon(AllIcons.RunConfigurations.Scroll_down);
  }

  @Override
  public boolean isSelected(AnActionEvent anActionEvent) {
    Project project = anActionEvent.getProject();
    return project != null
        && BuckUIManager.getInstance(project)
            .getBuckTreeViewPanel()
            .getModifiableModel()
            .shouldScrollToEnd();
  }

  @Override
  public void setSelected(AnActionEvent anActionEvent, boolean b) {
    Project project = anActionEvent.getProject();
    if (project != null) {
      BuckUIManager buckUIManager = BuckUIManager.getInstance(project);
      buckUIManager.getBuckTreeViewPanel().getModifiableModel().setScrollToEnd(b);
      if (b) {
        buckUIManager.getBuckTreeViewPanel().getModifiableModel().scrollToEnd();
      }
    }
  }
}


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

import org.openjdk.jol.info.ClassLayout;

import java.util.BitSet;

import static com.facebook.presto.plugin.turbonium.storage.Util.sizeOfBitSet;
import static io.airlift.slice.SizeOf.sizeOf;

public interface Values
{
    default long getLong(int position)
    {
        throw new UnsupportedOperationException();
    }

    default int getInt(int position)
    {
        throw new UnsupportedOperationException();
    }

    default short getShort(int position)
    {
        throw new UnsupportedOperationException();
    }

    default byte getByte(int position)
    {
        throw new UnsupportedOperationException();
    }

    default boolean getBoolean(int position)
    {
        throw new UnsupportedOperationException();
    }

    default long getSizeBytes()
    {
        throw new UnsupportedOperationException();
    }

    class IntValues
            implements Values
    {
        private static final int INSTANCE_SIZE = ClassLayout.parseClass(IntValues.class).instanceSize();
        private final int[] values;

        public IntValues(int[] values)
        {
            this.values = values;
        }

        @Override
        public long getLong(int position)
        {
            return 0xffff_ffffL & values[position];
        }

        @Override
        public long getSizeBytes()
        {
            return INSTANCE_SIZE + sizeOf(values);
        }
    }

    class ShortValues
            implements Values
    {
        private static final int INSTANCE_SIZE = ClassLayout.parseClass(ShortValues.class).instanceSize();
        private final short[] values;

        public ShortValues(short[] values)
        {
            this.values = values;
        }

        public long getLong(int position)
        {
            return getInt(position);
        }

        public int getInt(int position)
        {
            return 0xffff & values[position];
        }

        @Override
        public long getSizeBytes()
        {
            return INSTANCE_SIZE + sizeOf(values);
        }
    }

    class ByteValues
            implements Values
    {
        private static final int INSTANCE_SIZE = ClassLayout.parseClass(ShortValues.class).instanceSize();
        private final byte[] values;

        public ByteValues(byte[] values)
        {
            this.values = values;
        }

        public long getLong(int position)
        {
            return getShort(position);
        }

        public int getInt(int position)
        {
            return getShort(position);
        }

        public short getShort(int position)
        {
            return (short) (0xff & values[position]);
        }
        @Override
        public long getSizeBytes()
        {
            return INSTANCE_SIZE + sizeOf(values);
        }
    }

    class BooleanValues
            implements Values
    {
        private static final int INSTANCE_SIZE = ClassLayout.parseClass(ShortValues.class).instanceSize();
        private final BitSet values;

        public BooleanValues(BitSet values)
        {
            this.values = values;
        }

        public long getLong(int position)
        {
            return getByte(position);
        }

        public int getInt(int position)
        {
            return getByte(position);
        }

        public short getShort(int position)
        {
            return getByte(position);
        }

        public byte getByte(int position)
        {
            return (byte) (values.get(position) ? 1 : 0);
        }

        public boolean getBoolean(int position)
        {
            return values.get(position);
        }
        @Override
        public long getSizeBytes()
        {
            return INSTANCE_SIZE + sizeOfBitSet(values);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcPlayground.Models
{
    public class Order
    {
        public int ID { get; set; }
        public int? UserID { get; set; }
        public string Product { get; set; }
        public double Units { get; set; }
        public double Price { get; set; }
        public virtual Customer Customer { get; set; }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Elench. fung. (Halle) 135 (1783)

#### Original name
Clavaria cornu-cervi Batsch

### Remarks
null


text:
package turnpike

// Message is a generic container for a WAMP message.
type Message interface {
	MessageType() MessageType
}

type MessageType int

func (mt MessageType) New() Message {
	switch mt {
	case HELLO:
		return new(Hello)
	case WELCOME:
		return new(Welcome)
	case ABORT:
		return new(Abort)
	case CHALLENGE:
		return new(Challenge)
	case AUTHENTICATE:
		return new(Authenticate)
	case GOODBYE:
		return new(Goodbye)
	case HEARTBEAT:
		return new(Heartbeat)
	case ERROR:
		return new(Error)

	case PUBLISH:
		return new(Publish)
	case PUBLISHED:
		return new(Published)

	case SUBSCRIBE:
		return new(Subscribe)
	case SUBSCRIBED:
		return new(Subscribed)
	case UNSUBSCRIBE:
		return new(Unsubscribe)
	case UNSUBSCRIBED:
		return new(Unsubscribed)
	case EVENT:
		return new(Event)

	case CALL:
		return new(Call)
	case CANCEL:
		return new(Cancel)
	case RESULT:
		return new(Result)

	case REGISTER:
		return new(Register)
	case REGISTERED:
		return new(Registered)
	case UNREGISTER:
		return new(Unregister)
	case UNREGISTERED:
		return new(Unregistered)
	case INVOCATION:
		return new(Invocation)
	case INTERRUPT:
		return new(Interrupt)
	case YIELD:
		return new(Yield)
	default:
		// TODO: allow custom message types?
		return nil
	}
}

func (mt MessageType) String() string {
	switch mt {
	case HELLO:
		return "HELLO"
	case WELCOME:
		return "WELCOME"
	case ABORT:
		return "ABORT"
	case CHALLENGE:
		return "CHALLENGE"
	case AUTHENTICATE:
		return "AUTHENTICATE"
	case GOODBYE:
		return "GOODBYE"
	case HEARTBEAT:
		return "HEARTBEAT"
	case ERROR:
		return "ERROR"

	case PUBLISH:
		return "PUBLISH"
	case PUBLISHED:
		return "PUBLISHED"

	case SUBSCRIBE:
		return "SUBSCRIBE"
	case SUBSCRIBED:
		return "SUBSCRIBED"
	case UNSUBSCRIBE:
		return "UNSUBSCRIBE"
	case UNSUBSCRIBED:
		return "UNSUBSCRIBED"
	case EVENT:
		return "EVENT"

	case CALL:
		return "CALL"
	case CANCEL:
		return "CANCEL"
	case RESULT:
		return "RESULT"

	case REGISTER:
		return "REGISTER"
	case REGISTERED:
		return "REGISTERED"
	case UNREGISTER:
		return "UNREGISTER"
	case UNREGISTERED:
		return "UNREGISTERED"
	case INVOCATION:
		return "INVOCATION"
	case INTERRUPT:
		return "INTERRUPT"
	case YIELD:
		return "YIELD"
	default:
		// TODO: allow custom message types?
		panic("Invalid message type")
	}
}

const (
	HELLO        MessageType = 1
	WELCOME      MessageType = 2
	ABORT        MessageType = 3
	CHALLENGE    MessageType = 4
	AUTHENTICATE MessageType = 5
	GOODBYE      MessageType = 6
	HEARTBEAT    MessageType = 7
	ERROR        MessageType = 8

	PUBLISH   MessageType = 16 //	Tx 	Rx
	PUBLISHED MessageType = 17 //	Rx 	Tx

	SUBSCRIBE    MessageType = 32 //	Rx 	Tx
	SUBSCRIBED   MessageType = 33 //	Tx 	Rx
	UNSUBSCRIBE  MessageType = 34 //	Rx 	Tx
	UNSUBSCRIBED MessageType = 35 //	Tx 	Rx
	EVENT        MessageType = 36 //	Tx 	Rx

	CALL   MessageType = 48 //	Tx 	Rx
	CANCEL MessageType = 49 //	Tx 	Rx
	RESULT MessageType = 50 //	Rx 	Tx

	REGISTER     MessageType = 64 //	Rx 	Tx
	REGISTERED   MessageType = 65 //	Tx 	Rx
	UNREGISTER   MessageType = 66 //	Rx 	Tx
	UNREGISTERED MessageType = 67 //	Tx 	Rx
	INVOCATION   MessageType = 68 //	Tx 	Rx
	INTERRUPT    MessageType = 69 //	Tx 	Rx
	YIELD        MessageType = 70 //	Rx 	Tx
)

// URIs are dot-separated identifiers, where each component *should* only contain letters, numbers or underscores.
//
// See the documentation for specifics: https://github.com/wamp-proto/wamp-proto/blob/master/rfc/text/basic/bp_identifiers.md#uris-uris
type URI string

// An ID is a unique, non-negative number. Different uses may have additional restrictions.
type ID uint64

// [HELLO, Realm|uri, Details|dict]
type Hello struct {
	Realm   URI
	Details map[string]interface{}
}

func (msg *Hello) MessageType() MessageType {
	return HELLO
}

// [WELCOME, Session|id, Details|dict]
type Welcome struct {
	ID      ID
	Details map[string]interface{}
}

func (msg *Welcome) MessageType() MessageType {
	return WELCOME
}

// [ABORT, Details|dict, Reason|uri]
type Abort struct {
	Details map[string]interface{}
	Reason  URI
}

func (msg *Abort) MessageType() MessageType {
	return ABORT
}

// [CHALLENGE, AuthMethod|string, Extra|dict]
type Challenge struct {
	AuthMethod string
	Extra      map[string]interface{}
}

func (msg *Challenge) MessageType() MessageType {
	return CHALLENGE
}

// [AUTHENTICATE, Signature|string, Extra|dict]
type Authenticate struct {
	Signature string
	Extra     map[string]interface{}
}

func (msg *Authenticate) MessageType() MessageType {
	return AUTHENTICATE
}

// [GOODBYE, Details|dict, Reason|uri]
type Goodbye struct {
	Details map[string]interface{}
	Reason  URI
}

func (msg *Goodbye) MessageType() MessageType {
	return GOODBYE
}

// [HEARTBEAT, IncomingSeq|integer, OutgoingSeq|integer
// [HEARTBEAT, IncomingSeq|integer, OutgoingSeq|integer, Discard|string]
type Heartbeat struct {
	IncomingSeq uint
	OutgoingSeq uint
	Discard     string
}

func (msg *Heartbeat) MessageType() MessageType {
	return HEARTBEAT
}

// [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri]
// [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri, Arguments|list]
// [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri, Arguments|list, ArgumentsKw|dict]
type Error struct {
	Type        MessageType
	Request     ID
	Details     map[string]interface{}
	Error       URI
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

func (msg *Error) MessageType() MessageType {
	return ERROR
}

// [PUBLISH, Request|id, Options|dict, Topic|uri]
// [PUBLISH, Request|id, Options|dict, Topic|uri, Arguments|list]
// [PUBLISH, Request|id, Options|dict, Topic|uri, Arguments|list, ArgumentsKw|dict]
type Publish struct {
	Request     ID
	Options     map[string]interface{}
	Topic       URI
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

func (msg *Publish) MessageType() MessageType {
	return PUBLISH
}

// [PUBLISHED, PUBLISH.Request|id, Publication|id]
type Published struct {
	Request     ID
	Publication ID
}

func (msg *Published) MessageType() MessageType {
	return PUBLISHED
}

// [SUBSCRIBE, Request|id, Options|dict, Topic|uri]
type Subscribe struct {
	Request ID
	Options map[string]interface{}
	Topic   URI
}

func (msg *Subscribe) MessageType() MessageType {
	return SUBSCRIBE
}

// [SUBSCRIBED, SUBSCRIBE.Request|id, Subscription|id]
type Subscribed struct {
	Request      ID
	Subscription ID
}

func (msg *Subscribed) MessageType() MessageType {
	return SUBSCRIBED
}

// [UNSUBSCRIBE, Request|id, SUBSCRIBED.Subscription|id]
type Unsubscribe struct {
	Request      ID
	Subscription ID
}

func (msg *Unsubscribe) MessageType() MessageType {
	return UNSUBSCRIBE
}

// [UNSUBSCRIBED, UNSUBSCRIBE.Request|id]
type Unsubscribed struct {
	Request ID
}

func (msg *Unsubscribed) MessageType() MessageType {
	return UNSUBSCRIBED
}

// [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id, Details|dict]
// [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id, Details|dict, PUBLISH.Arguments|list]
// [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id, Details|dict, PUBLISH.Arguments|list,
//     PUBLISH.ArgumentsKw|dict]
type Event struct {
	Subscription ID
	Publication  ID
	Details      map[string]interface{}
	Arguments    []interface{}          `wamp:"omitempty"`
	ArgumentsKw  map[string]interface{} `wamp:"omitempty"`
}

func (msg *Event) MessageType() MessageType {
	return EVENT
}

// CallResult represents the result of a CALL.
type CallResult struct {
	Args   []interface{}
	Kwargs map[string]interface{}
	Err    URI
}

// [CALL, Request|id, Options|dict, Procedure|uri]
// [CALL, Request|id, Options|dict, Procedure|uri, Arguments|list]
// [CALL, Request|id, Options|dict, Procedure|uri, Arguments|list, ArgumentsKw|dict]
type Call struct {
	Request     ID
	Options     map[string]interface{}
	Procedure   URI
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

func (msg *Call) MessageType() MessageType {
	return CALL
}

// [RESULT, CALL.Request|id, Details|dict]
// [RESULT, CALL.Request|id, Details|dict, YIELD.Arguments|list]
// [RESULT, CALL.Request|id, Details|dict, YIELD.Arguments|list, YIELD.ArgumentsKw|dict]
type Result struct {
	Request     ID
	Details     map[string]interface{}
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

func (msg *Result) MessageType() MessageType {
	return RESULT
}

// [REGISTER, Request|id, Options|dict, Procedure|uri]
type Register struct {
	Request   ID
	Options   map[string]interface{}
	Procedure URI
}

func (msg *Register) MessageType() MessageType {
	return REGISTER
}

// [REGISTERED, REGISTER.Request|id, Registration|id]
type Registered struct {
	Request      ID
	Registration ID
}

func (msg *Registered) MessageType() MessageType {
	return REGISTERED
}

// [UNREGISTER, Request|id, REGISTERED.Registration|id]
type Unregister struct {
	Request      ID
	Registration ID
}

func (msg *Unregister) MessageType() MessageType {
	return UNREGISTER
}

// [UNREGISTERED, UNREGISTER.Request|id]
type Unregistered struct {
	Request ID
}

func (msg *Unregistered) MessageType() MessageType {
	return UNREGISTERED
}

// [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict]
// [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict, CALL.Arguments|list]
// [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict, CALL.Arguments|list, CALL.ArgumentsKw|dict]
type Invocation struct {
	Request      ID
	Registration ID
	Details      map[string]interface{}
	Arguments    []interface{}          `wamp:"omitempty"`
	ArgumentsKw  map[string]interface{} `wamp:"omitempty"`
}

func (msg *Invocation) MessageType() MessageType {
	return INVOCATION
}

// [YIELD, INVOCATION.Request|id, Options|dict]
// [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list]
// [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list, ArgumentsKw|dict]
type Yield struct {
	Request     ID
	Options     map[string]interface{}
	Arguments   []interface{}          `wamp:"omitempty"`
	ArgumentsKw map[string]interface{} `wamp:"omitempty"`
}

func (msg *Yield) MessageType() MessageType {
	return YIELD
}

// [CANCEL, CALL.Request|id, Options|dict]
type Cancel struct {
	Request ID
	Options map[string]interface{}
}

func (msg *Cancel) MessageType() MessageType {
	return CANCEL
}

// [INTERRUPT, INVOCATION.Request|id, Options|dict]
type Interrupt struct {
	Request ID
	Options map[string]interface{}
}

func (msg *Interrupt) MessageType() MessageType {
	return INTERRUPT
}


text:
var _ = require('underscore');

var VALID_TYPE = {
  EMAIL     : {name: "Email", error: "is not a valid email"},
  STRING    : {name: "String", error: "is not a string"},
  DEPENDENT : {name: "Dependent", error: "depencency is also not valid"},
  DATE      : {name: "Date", error: "is not a valid RFC 2822 formatted date"}
};

function Validation(validType, required, optionalDependent) {
  this.validType = validType;
  this.required = required;
  if (validType === VALID_TYPE.DEPENDENT) {
    if (_.isUndefined(optionalDependent) {
      throw new Error("Missing dependent field");
    } else {
      this.dependent = optionalDependent;
    }
  }
}

Validation.prototype.isValid = function(first_argument) {
  // body...
};

module.exports.Validate = Validate;


text:
.class Lcom/android/server/pm/PackageManagerService$PostInstallData;
.super Ljava/lang/Object;
.source "PackageManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/pm/PackageManagerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "PostInstallData"
.end annotation

# instance fields
.field public args:Lcom/android/server/pm/PackageManagerService$InstallArgs;

.field public res:Lcom/android/server/pm/PackageManagerService$PackageInstalledInfo;

.field final synthetic this$0:Lcom/android/server/pm/PackageManagerService;

# direct methods
.method constructor <init>(Lcom/android/server/pm/PackageManagerService;Lcom/android/server/pm/PackageManagerService$InstallArgs;Lcom/android/server/pm/PackageManagerService$PackageInstalledInfo;)V
    .registers 4
    .param p2    # Lcom/android/server/pm/PackageManagerService$InstallArgs;
    .param p3    # Lcom/android/server/pm/PackageManagerService$PackageInstalledInfo;

    iput-object p1, p0, Lcom/android/server/pm/PackageManagerService$PostInstallData;->this$0:Lcom/android/server/pm/PackageManagerService;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p2, p0, Lcom/android/server/pm/PackageManagerService$PostInstallData;->args:Lcom/android/server/pm/PackageManagerService$InstallArgs;

    iput-object p3, p0, Lcom/android/server/pm/PackageManagerService$PostInstallData;->res:Lcom/android/server/pm/PackageManagerService$PackageInstalledInfo;

    return-void
.end method


text:
package com.yitong.weixin.test.entity;

import com.yitong.weixin.modules.sys.entity.User;
import com.yitong.weixin.modules.sys.entity.Office;
import com.yitong.weixin.modules.sys.entity.Area;
import org.hibernate.validator.constraints.Length;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;

import com.yitong.weixin.common.persistence.DataEntity;

/**
 * 单表生成Entity
 * @author ThinkGem
 * @version 2015-04-06
 */
public class TestData extends DataEntity<TestData> {

	private static final long serialVersionUID = 1L;
	private User user;		// 归属用户
	private Office office;		// 归属部门
	private Area area;		// 归属区域
	private String name;		// 名称
	private String sex;		// 性别
	private Date inDate;		// 加入日期
	private Date beginInDate;		// 开始 加入日期
	private Date endInDate;		// 结束 加入日期

	public TestData() {
		super();
	}

	public TestData(String id){
		super(id);
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Office getOffice() {
		return office;
	}

	public void setOffice(Office office) {
		this.office = office;
	}

	public Area getArea() {
		return area;
	}

	public void setArea(Area area) {
		this.area = area;
	}

	@Length(min=0, max=100, message="名称长度必须介于 0 和 100 之间")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Length(min=0, max=1, message="性别长度必须介于 0 和 1 之间")
	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date getInDate() {
		return inDate;
	}

	public void setInDate(Date inDate) {
		this.inDate = inDate;
	}

	public Date getBeginInDate() {
		return beginInDate;
	}

	public void setBeginInDate(Date beginInDate) {
		this.beginInDate = beginInDate;
	}

	public Date getEndInDate() {
		return endInDate;
	}

	public void setEndInDate(Date endInDate) {
		this.endInDate = endInDate;
	}

}


text:
function [press_fun,Vm_fun,T_fun]=Redlich_Kwong(R,Tc,pc,mole_fr)

mixture_components=length(Tc);
%get parameters for R-K EOS
a=zeros(1,mixture_components);
b=zeros(1,mixture_components);
for i=1:mixture_components
    a(i)=RK_a(R,Tc(i),pc(i));
    b(i)=RK_b(R,Tc(i),pc(i));
end

%get all attractive constants for cross species interactions http://en.wikipedia.org/wiki/Redlich%E2%80%93Kwong_equation_of_state
%attractive forces between species 1 and 2 and so on
%all combinations!
mole_fr_a=mole_fr.^2;

counter=1;
start=1;
for i=1:mixture_components
    start=start+1;
    for j=start:mixture_components
        a(mixture_components+counter)=sqrt(a(i)*a(j));
        mole_fr_a(mixture_components+counter)=mole_fr(i)*mole_fr(j);
        counter=counter+1;
    end
end

%define weighting factor for density calculation http://en.wikipedia.org/wiki/Molar_volume
% molar_vol_factor=sum(mole_fr.*mol_m);

% for i=1:mixture_components
%     a(mixture_components+i)=a(i)*a(i+1)
% end
b_weighted=sum(b.*mole_fr);
a_weighted=sum(a.*mole_fr_a);

% Redlich-Kwong will be solved either for volume, pressure or temperature
syms P Vm T
%define equation
f(P,Vm)=P-R*T/(Vm-b_weighted)+a_weighted/sqrt(T)/(Vm*(Vm+b_weighted));
%get expression for pressure as a function of Vm and T
press_eq=solve(f,P);
%get expression of Vm as a function of P and T
Vm_eq=solve(f,Vm);
%get expression of T as a function of P and Vm
T_eq=solve(f,T);

%convert to expressions matlabfunctions, which can be later called for
press_fun=matlabFunction(press_eq);
Vm_fun=matlabFunction(Vm_eq); %Vm gives as a result three values in complex domain - then Vm=real(Vm(1))
T_fun=matlabFunction(T_eq);


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>pmsoft.twitter.killer</groupId>
    <artifactId>server</artifactId>
    <version>0.1</version>
    <packaging>war</packaging>

    <build>
        <finalName>server</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.1.4.v20140401</version>

                <configuration>
                    <stopPort>9999</stopPort>
                    <stopKey>STOP</stopKey>
                    <stopWait>10</stopWait>
                    <httpConnector>
                        <port>1234</port>
                    </httpConnector>
                </configuration>

                <executions>
                    <execution>
                        <id>start-jetty</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <scanIntervalSeconds>0</scanIntervalSeconds>
                            <daemon>true</daemon>
                        </configuration>
                    </execution>

                    <execution>
                        <id>stop-jetty</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>

            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.8</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.8</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.4.0-rc3</version>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.objenesis</groupId>
            <artifactId>objenesis</artifactId>
            <version>1.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.1.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
</project>


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

from pants.base.config import Config
from pants.option.errors import ParseError

def _parse_error(s, msg):
  """Return a ParseError with a usefully formatted message, for the caller to throw.

  :param s: The option value we're parsing.
  :param msg: An extra message to add to the ParseError.
  """
  return ParseError('Error while parsing option value {0}: {1}'.format(s, msg))

def dict_type(s):
  """An option of type 'dict'.

  The value (on the command-line, in an env var or in the config file) must be eval'able to a dict.
  """
  return _convert(s, (dict,))

def list_type(s):
  """An option of type 'list'.

  The value (on the command-line, in an env var or in the config file) must be eval'able to a
  list or tuple.
  """
  return _convert(s, (list, tuple))

def _convert(val, acceptable_types):
  """Ensure that val is one of the acceptable types, converting it if needed."""
  if isinstance(val, acceptable_types):
    return val
  try:
    parsed_value = eval(val, {}, {})
  except Exception as e:
    raise _parse_error(val, 'Value cannot be evaluated: {msg}\n{value}'.format(
      msg=e.message, value=Config.format_raw_value(val)))
  if not isinstance(parsed_value, acceptable_types):
    raise _parse_error(val, 'Value is not of the acceptable types: {msg}\n{value}'.format(
      msg=acceptable_types, value=Config.format_raw_value(val)))
  return parsed_value


text:
from __future__ import division, absolute_import, print_function

import re
import sys
import textwrap
import warnings

import jinja2

from numpydoc.docscrape import (
    NumpyDocString,
    FunctionDoc,
    ClassDoc,
    ParseError
)
from numpydoc.docscrape_sphinx import (SphinxDocString, SphinxClassDoc,
                                       SphinxFunctionDoc)
from nose.tools import (assert_equal, assert_raises, assert_list_equal,
                        assert_true)

assert_list_equal.__self__.maxDiff = None

if sys.version_info[0] >= 3:
    sixu = lambda s: s
else:
    sixu = lambda s: unicode(s, 'unicode_escape')

doc_txt = '''\
  numpy.multivariate_normal(mean, cov, shape=None, spam=None)

  Draw values from a multivariate normal distribution with specified
  mean and covariance.

  The multivariate normal or Gaussian distribution is a generalisation
  of the one-dimensional normal distribution to higher dimensions.

  Parameters
  ----------
  mean : (N,) ndarray
      Mean of the N-dimensional distribution.

      .. math::

         (1+2+3)/3

  cov : (N, N) ndarray
      Covariance matrix of the distribution.
  shape : tuple of ints
      Given a shape of, for example, (m,n,k), m*n*k samples are
      generated, and packed in an m-by-n-by-k arrangement.  Because
      each sample is N-dimensional, the output shape is (m,n,k,N).

  Returns
  -------
  out : ndarray
      The drawn samples, arranged according to `shape`.  If the
      shape given is (m,n,...), then the shape of `out` is
      (m,n,...,N).

      In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
      value drawn from the distribution.
  list of str
      This is not a real return value.  It exists to test
      anonymous return values.
  no_description

  Other Parameters
  ----------------
  spam : parrot
      A parrot off its mortal coil.

  Raises
  ------
  RuntimeError
      Some error

  Warns
  -----
  RuntimeWarning
      Some warning

  Warnings
  --------
  Certain warnings apply.

  Notes
  -----
  Instead of specifying the full covariance matrix, popular
  approximations include:

    - Spherical covariance (`cov` is a multiple of the identity matrix)
    - Diagonal covariance (`cov` has non-negative elements only on the diagonal)

  This geometrical property can be seen in two dimensions by plotting
  generated data-points:

  >>> mean = [0,0]
  >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis

  >>> x,y = multivariate_normal(mean,cov,5000).T
  >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()

  Note that the covariance matrix must be symmetric and non-negative
  definite.

  References
  ----------
  .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
         Processes," 3rd ed., McGraw-Hill Companies, 1991
  .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
         2nd ed., Wiley, 2001.

  See Also
  --------
  some, other, funcs
  otherfunc : relationship

  Examples
  --------
  >>> mean = (1,2)
  >>> cov = [[1,0],[1,0]]
  >>> x = multivariate_normal(mean,cov,(3,3))
  >>> print x.shape
  (3, 3, 2)

  The following is probably true, given that 0.6 is roughly twice the
  standard deviation:

  >>> print list( (x[0,0,:] - mean) < 0.6 )
  [True, True]

  .. index:: random
     :refguide: random;distributions, random;gauss

  '''
doc = NumpyDocString(doc_txt)

doc_yields_txt = """
Test generator

Yields
------
a : int
    The number of apples.
b : int
    The number of bananas.
int
    The number of unknowns.
"""
doc_yields = NumpyDocString(doc_yields_txt)

def test_signature():
    assert doc['Signature'].startswith('numpy.multivariate_normal(')
    assert doc['Signature'].endswith('spam=None)')

def test_summary():
    assert doc['Summary'][0].startswith('Draw values')
    assert doc['Summary'][-1].endswith('covariance.')

def test_extended_summary():
    assert doc['Extended Summary'][0].startswith('The multivariate normal')

def test_parameters():
    assert_equal(len(doc['Parameters']), 3)
    assert_equal([n for n,_,_ in doc['Parameters']], ['mean','cov','shape'])

    arg, arg_type, desc = doc['Parameters'][1]
    assert_equal(arg_type, '(N, N) ndarray')
    assert desc[0].startswith('Covariance matrix')
    assert doc['Parameters'][0][-1][-1] == '   (1+2+3)/3'

def test_other_parameters():
    assert_equal(len(doc['Other Parameters']), 1)
    assert_equal([n for n,_,_ in doc['Other Parameters']], ['spam'])
    arg, arg_type, desc = doc['Other Parameters'][0]
    assert_equal(arg_type, 'parrot')
    assert desc[0].startswith('A parrot off its mortal coil')

def test_returns():
    assert_equal(len(doc['Returns']), 3)
    arg, arg_type, desc = doc['Returns'][0]
    assert_equal(arg, 'out')
    assert_equal(arg_type, 'ndarray')
    assert desc[0].startswith('The drawn samples')
    assert desc[-1].endswith('distribution.')

    arg, arg_type, desc = doc['Returns'][1]
    assert_equal(arg, 'list of str')
    assert_equal(arg_type, '')
    assert desc[0].startswith('This is not a real')
    assert desc[-1].endswith('anonymous return values.')

    arg, arg_type, desc = doc['Returns'][2]
    assert_equal(arg, 'no_description')
    assert_equal(arg_type, '')
    assert not ''.join(desc).strip()

def test_yields():
    section = doc_yields['Yields']
    assert_equal(len(section), 3)
    truth = [('a', 'int', 'apples.'),
             ('b', 'int', 'bananas.'),
             ('int', '', 'unknowns.')]
    for (arg, arg_type, desc), (arg_, arg_type_, end) in zip(section, truth):
        assert_equal(arg, arg_)
        assert_equal(arg_type, arg_type_)
        assert desc[0].startswith('The number of')
        assert desc[0].endswith(end)

def test_returnyield():
    doc_text = """
Test having returns and yields.

Returns
-------
int
    The number of apples.

Yields
------
a : int
    The number of apples.
b : int
    The number of bananas.

"""
    assert_raises(ValueError, NumpyDocString, doc_text)

def test_section_twice():
    doc_text = """
Test having a section Notes twice

Notes
-----
See the next note for more information

Notes
-----
That should break...
"""
    assert_raises(ValueError, NumpyDocString, doc_text)

    # if we have a numpydoc object, we know where the error came from
    class Dummy(object):
        """
        Dummy class.

        Notes
        -----
        First note.

        Notes
        -----
        Second note.

        """
        def spam(self, a, b):
            """Spam\n\nSpam spam."""
            pass

        def ham(self, c, d):
            """Cheese\n\nNo cheese."""
            pass

    def dummy_func(arg):
        """
        Dummy function.

        Notes
        -----
        First note.

        Notes
        -----
        Second note.
        """

    try:
        SphinxClassDoc(Dummy)
    except ValueError as e:
        # python 3 version or python 2 version
        assert_true("test_section_twice.<locals>.Dummy" in str(e)
                    or 'test_docscrape.Dummy' in str(e))

    try:
        SphinxFunctionDoc(dummy_func)
    except ValueError as e:
        # python 3 version or python 2 version
        assert_true("test_section_twice.<locals>.dummy_func" in str(e)
                    or 'function dummy_func' in str(e))

def test_notes():
    assert doc['Notes'][0].startswith('Instead')
    assert doc['Notes'][-1].endswith('definite.')
    assert_equal(len(doc['Notes']), 17)

def test_references():
    assert doc['References'][0].startswith('..')
    assert doc['References'][-1].endswith('2001.')

def test_examples():
    assert doc['Examples'][0].startswith('>>>')
    assert doc['Examples'][-1].endswith('True]')

def test_index():
    assert_equal(doc['index']['default'], 'random')
    assert_equal(len(doc['index']), 2)
    assert_equal(len(doc['index']['refguide']), 2)

def _strip_blank_lines(s):
    "Remove leading, trailing and multiple blank lines"
    s = re.sub(r'^\s*\n', '', s)
    s = re.sub(r'\n\s*$', '', s)
    s = re.sub(r'\n\s*\n', r'\n\n', s)
    return s

def line_by_line_compare(a, b):
    a = textwrap.dedent(a)
    b = textwrap.dedent(b)
    a = [l.rstrip() for l in _strip_blank_lines(a).split('\n')]
    b = [l.rstrip() for l in _strip_blank_lines(b).split('\n')]
    assert_list_equal(a, b)

def test_str():
    # doc_txt has the order of Notes and See Also sections flipped.
    # This should be handled automatically, and so, one thing this test does
    # is to make sure that See Also precedes Notes in the output.
    line_by_line_compare(str(doc),
"""numpy.multivariate_normal(mean, cov, shape=None, spam=None)

Draw values from a multivariate normal distribution with specified
mean and covariance.

The multivariate normal or Gaussian distribution is a generalisation
of the one-dimensional normal distribution to higher dimensions.

Parameters
----------
mean : (N,) ndarray
    Mean of the N-dimensional distribution.

    .. math::

       (1+2+3)/3
cov : (N, N) ndarray
    Covariance matrix of the distribution.
shape : tuple of ints
    Given a shape of, for example, (m,n,k), m*n*k samples are
    generated, and packed in an m-by-n-by-k arrangement.  Because
    each sample is N-dimensional, the output shape is (m,n,k,N).

Returns
-------
out : ndarray
    The drawn samples, arranged according to `shape`.  If the
    shape given is (m,n,...), then the shape of `out` is
    (m,n,...,N).

    In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
    value drawn from the distribution.
list of str
    This is not a real return value.  It exists to test
    anonymous return values.
no_description

Other Parameters
----------------
spam : parrot
    A parrot off its mortal coil.

Raises
------
RuntimeError
    Some error

Warns
-----
RuntimeWarning
    Some warning

Warnings
--------
Certain warnings apply.

See Also
--------

`some`_, `other`_, `funcs`_

`otherfunc`_
    relationship

Notes
-----
Instead of specifying the full covariance matrix, popular
approximations include:

  - Spherical covariance (`cov` is a multiple of the identity matrix)
  - Diagonal covariance (`cov` has non-negative elements only on the diagonal)

This geometrical property can be seen in two dimensions by plotting
generated data-points:

>>> mean = [0,0]
>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis

>>> x,y = multivariate_normal(mean,cov,5000).T
>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()

Note that the covariance matrix must be symmetric and non-negative
definite.

References
----------
.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
       Processes," 3rd ed., McGraw-Hill Companies, 1991
.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
       2nd ed., Wiley, 2001.

Examples
--------
>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
>>> print x.shape
(3, 3, 2)

The following is probably true, given that 0.6 is roughly twice the
standard deviation:

>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]

.. index:: random
   :refguide: random;distributions, random;gauss""")

def test_yield_str():
    line_by_line_compare(str(doc_yields),
"""Test generator

Yields
------
a : int
    The number of apples.
b : int
    The number of bananas.
int
    The number of unknowns.

.. index:: """)

def test_sphinx_str():
    sphinx_doc = SphinxDocString(doc_txt)
    line_by_line_compare(str(sphinx_doc),
"""
.. index:: random
   single: random;distributions, random;gauss

Draw values from a multivariate normal distribution with specified
mean and covariance.

The multivariate normal or Gaussian distribution is a generalisation
of the one-dimensional normal distribution to higher dimensions.

:Parameters:

    mean : (N,) ndarray
        Mean of the N-dimensional distribution.

        .. math::

           (1+2+3)/3

    cov : (N, N) ndarray
        Covariance matrix of the distribution.

    shape : tuple of ints
        Given a shape of, for example, (m,n,k), m*n*k samples are
        generated, and packed in an m-by-n-by-k arrangement.  Because
        each sample is N-dimensional, the output shape is (m,n,k,N).

:Returns:

    out : ndarray
        The drawn samples, arranged according to `shape`.  If the
        shape given is (m,n,...), then the shape of `out` is
        (m,n,...,N).

        In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
        value drawn from the distribution.

    list of str
        This is not a real return value.  It exists to test
        anonymous return values.

    no_description
        ..

:Other Parameters:

    spam : parrot
        A parrot off its mortal coil.

:Raises:

    RuntimeError
        Some error

:Warns:

    RuntimeWarning
        Some warning

.. warning::

    Certain warnings apply.

.. seealso::

    :obj:`some`, :obj:`other`, :obj:`funcs`

    :obj:`otherfunc`
        relationship

.. rubric:: Notes

Instead of specifying the full covariance matrix, popular
approximations include:

  - Spherical covariance (`cov` is a multiple of the identity matrix)
  - Diagonal covariance (`cov` has non-negative elements only on the diagonal)

This geometrical property can be seen in two dimensions by plotting
generated data-points:

>>> mean = [0,0]
>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis

>>> x,y = multivariate_normal(mean,cov,5000).T
>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()

Note that the covariance matrix must be symmetric and non-negative
definite.

.. rubric:: References

.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
       Processes," 3rd ed., McGraw-Hill Companies, 1991
.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
       2nd ed., Wiley, 2001.

.. only:: latex

   [1]_, [2]_

.. rubric:: Examples

>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
>>> print x.shape
(3, 3, 2)

The following is probably true, given that 0.6 is roughly twice the
standard deviation:

>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
""")

def test_sphinx_yields_str():
    sphinx_doc = SphinxDocString(doc_yields_txt)
    line_by_line_compare(str(sphinx_doc),
"""Test generator

:Yields:

    a : int
        The number of apples.

    b : int
        The number of bananas.

    int
        The number of unknowns.
""")

doc2 = NumpyDocString("""
    Returns array of indices of the maximum values of along the given axis.

    Parameters
    ----------
    a : {array_like}
        Array to look in.
    axis : {None, integer}
        If None, the index is into the flattened array, otherwise along
        the specified axis""")

def test_parameters_without_extended_description():
    assert_equal(len(doc2['Parameters']), 2)

doc3 = NumpyDocString("""
    my_signature(*params, **kwds)

    Return this and that.
    """)

def test_escape_stars():
    signature = str(doc3).split('\n')[0]
    assert_equal(signature, 'my_signature(\*params, \*\*kwds)')

    def my_func(a, b, **kwargs):
        pass

    fdoc = FunctionDoc(func=my_func)
    assert_equal(fdoc['Signature'], 'my_func(a, b, \*\*kwargs)')

doc4 = NumpyDocString(
    """a.conj()

    Return an array with all complex-valued elements conjugated.""")

def test_empty_extended_summary():
    assert_equal(doc4['Extended Summary'], [])

doc5 = NumpyDocString(
    """
    a.something()

    Raises
    ------
    LinAlgException
        If array is singular.

    Warns
    -----
    SomeWarning
        If needed
    """)

def test_raises():
    assert_equal(len(doc5['Raises']), 1)
    name,_,desc = doc5['Raises'][0]
    assert_equal(name,'LinAlgException')
    assert_equal(desc,['If array is singular.'])

def test_warns():
    assert_equal(len(doc5['Warns']), 1)
    name,_,desc = doc5['Warns'][0]
    assert_equal(name,'SomeWarning')
    assert_equal(desc,['If needed'])

def test_see_also():
    doc6 = NumpyDocString(
    """
    z(x,theta)

    See Also
    --------
    func_a, func_b, func_c
    func_d : some equivalent func
    foo.func_e : some other func over
             multiple lines
    func_f, func_g, :meth:`func_h`, func_j,
    func_k
    :obj:`baz.obj_q`
    :obj:`~baz.obj_r`
    :class:`class_j`: fubar
        foobar
    """)

    assert len(doc6['See Also']) == 13
    for func, desc, role in doc6['See Also']:
        if func in ('func_a', 'func_b', 'func_c', 'func_f',
                    'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q',
                    '~baz.obj_r'):
            assert(not desc)
        else:
            assert(desc)

        if func == 'func_h':
            assert role == 'meth'
        elif func == 'baz.obj_q' or func == '~baz.obj_r':
            assert role == 'obj'
        elif func == 'class_j':
            assert role == 'class'
        else:
            assert role is None

        if func == 'func_d':
            assert desc == ['some equivalent func']
        elif func == 'foo.func_e':
            assert desc == ['some other func over', 'multiple lines']
        elif func == 'class_j':
            assert desc == ['fubar', 'foobar']

def test_see_also_parse_error():
    text = (
    """
    z(x,theta)

    See Also
    --------
    :func:`~foo`
    """)
    with assert_raises(ParseError) as err:
        NumpyDocString(text)
    assert_equal(
        str(r":func:`~foo` is not a item name in '\n    z(x,theta)\n\n    See Also\n    --------\n    :func:`~foo`\n    '"),
        str(err.exception)
    )

def test_see_also_print():
    class Dummy(object):
        """
        See Also
        --------
        func_a, func_b
        func_c : some relationship
                 goes here
        func_d
        """
        pass

    obj = Dummy()
    s = str(FunctionDoc(obj, role='func'))
    assert(':func:`func_a`, :func:`func_b`' in s)
    assert('    some relationship' in s)
    assert(':func:`func_d`' in s)

def test_unknown_section():
    doc_text = """
Test having an unknown section

Mope
----
This should be ignored and warned about
"""

    class BadSection(object):
        """Class with bad section.

        Nope
        ----
        This class has a nope section.
        """
        pass

    with warnings.catch_warnings(record=True) as w:
        NumpyDocString(doc_text)
        assert len(w) == 1
        assert "Unknown section Mope" == str(w[0].message)

    with warnings.catch_warnings(record=True) as w:
        SphinxClassDoc(BadSection)
        assert len(w) == 1
        assert_true('test_docscrape.test_unknown_section.<locals>.BadSection'
                    in str(w[0].message)
                    or 'test_docscrape.BadSection' in str(w[0].message))

doc7 = NumpyDocString("""

        Doc starts on second line.

        """)

def test_empty_first_line():
    assert doc7['Summary'][0].startswith('Doc starts')

def test_no_summary():
    str(SphinxDocString("""
    Parameters
    ----------"""))

def test_unicode():
    doc = SphinxDocString("""
    öäöäöäöäöåååå

    öäöäöäööäååå

    Parameters
    ----------
    ååå : äää
        ööö

    Returns
    -------
    ååå : ööö
        äää

    """)
    assert isinstance(doc['Summary'][0], str)
    assert doc['Summary'][0] == 'öäöäöäöäöåååå'

def test_plot_examples():
    cfg = dict(use_plots=True)

    doc = SphinxDocString("""
    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> plt.plot([1,2,3],[4,5,6])
    >>> plt.show()
    """, config=cfg)
    assert 'plot::' in str(doc), str(doc)

    doc = SphinxDocString("""
    Examples
    --------
    >>> from matplotlib import pyplot as plt
    >>> plt.plot([1,2,3],[4,5,6])
    >>> plt.show()
    """, config=cfg)
    assert 'plot::' in str(doc), str(doc)

    doc = SphinxDocString("""
    Examples
    --------
    .. plot::

       import matplotlib.pyplot as plt
       plt.plot([1,2,3],[4,5,6])
       plt.show()
    """, config=cfg)
    assert str(doc).count('plot::') == 1, str(doc)

def test_use_blockquotes():
    cfg = dict(use_blockquotes=True)
    doc = SphinxDocString("""
    Parameters
    ----------
    abc : def
        ghi
    jkl
        mno

    Returns
    -------
    ABC : DEF
        GHI
    JKL
        MNO
    """, config=cfg)
    line_by_line_compare(str(doc), '''
    :Parameters:

        **abc** : def

            ghi

        **jkl**

            mno

    :Returns:

        **ABC** : DEF

            GHI

        **JKL**

            MNO
    ''')

def test_class_members():

    class Dummy(object):
        """
        Dummy class.

        """
        def spam(self, a, b):
            """Spam\n\nSpam spam."""
            pass
        def ham(self, c, d):
            """Cheese\n\nNo cheese."""
            pass
        @property
        def spammity(self):
            """Spammity index"""
            return 0.95

        class Ignorable(object):
            """local class, to be ignored"""
            pass

    for cls in (ClassDoc, SphinxClassDoc):
        doc = cls(Dummy, config=dict(show_class_members=False))
        assert 'Methods' not in str(doc), (cls, str(doc))
        assert 'spam' not in str(doc), (cls, str(doc))
        assert 'ham' not in str(doc), (cls, str(doc))
        assert 'spammity' not in str(doc), (cls, str(doc))
        assert 'Spammity index' not in str(doc), (cls, str(doc))

        doc = cls(Dummy, config=dict(show_class_members=True))
        assert 'Methods' in str(doc), (cls, str(doc))
        assert 'spam' in str(doc), (cls, str(doc))
        assert 'ham' in str(doc), (cls, str(doc))
        assert 'spammity' in str(doc), (cls, str(doc))

        if cls is SphinxClassDoc:
            assert '.. autosummary::' in str(doc), str(doc)
        else:
            assert 'Spammity index' in str(doc), str(doc)

    class SubDummy(Dummy):
        """
        Subclass of Dummy class.

        """
        def ham(self, c, d):
            """Cheese\n\nNo cheese.\nOverloaded Dummy.ham"""
            pass

        def bar(self, a, b):
            """Bar\n\nNo bar"""
            pass

    for cls in (ClassDoc, SphinxClassDoc):
        doc = cls(SubDummy, config=dict(show_class_members=True,
                                        show_inherited_class_members=False))
        assert 'Methods' in str(doc), (cls, str(doc))
        assert 'spam' not in str(doc), (cls, str(doc))
        assert 'ham' in str(doc), (cls, str(doc))
        assert 'bar' in str(doc), (cls, str(doc))
        assert 'spammity' not in str(doc), (cls, str(doc))

        if cls is SphinxClassDoc:
            assert '.. autosummary::' in str(doc), str(doc)
        else:
            assert 'Spammity index' not in str(doc), str(doc)

        doc = cls(SubDummy, config=dict(show_class_members=True,
                                        show_inherited_class_members=True))
        assert 'Methods' in str(doc), (cls, str(doc))
        assert 'spam' in str(doc), (cls, str(doc))
        assert 'ham' in str(doc), (cls, str(doc))
        assert 'bar' in str(doc), (cls, str(doc))
        assert 'spammity' in str(doc), (cls, str(doc))

        if cls is SphinxClassDoc:
            assert '.. autosummary::' in str(doc), str(doc)
        else:
            assert 'Spammity index' in str(doc), str(doc)

def test_duplicate_signature():
    # Duplicate function signatures occur e.g. in ufuncs, when the
    # automatic mechanism adds one, and a more detailed comes from the
    # docstring itself.

    doc = NumpyDocString(
    """
    z(x1, x2)

    z(a, theta)
    """)

    assert doc['Signature'].strip() == 'z(a, theta)'

class_doc_txt = """
    Foo

    Parameters
    ----------
    f : callable ``f(t, y, *f_args)``
        Aaa.
    jac : callable ``jac(t, y, *jac_args)``

        Bbb.

    Attributes
    ----------
    t : float
        Current time.
    y : ndarray
        Current variable values.

        * hello
        * world
    an_attribute : float
        The docstring is printed instead
    no_docstring : str
        But a description
    no_docstring2 : str
    multiline_sentence
    midword_period
    no_period

    Methods
    -------
    a
    b
    c

    Examples
    --------
    For usage examples, see `ode`.
"""

def test_class_members_doc():
    doc = ClassDoc(None, class_doc_txt)
    line_by_line_compare(str(doc),
    """
    Foo

    Parameters
    ----------
    f : callable ``f(t, y, *f_args)``
        Aaa.
    jac : callable ``jac(t, y, *jac_args)``
        Bbb.

    Examples
    --------
    For usage examples, see `ode`.

    Attributes
    ----------
    t : float
        Current time.
    y : ndarray
        Current variable values.

        * hello
        * world
    an_attribute : float
        The docstring is printed instead
    no_docstring : str
        But a description
    no_docstring2 : str
    multiline_sentence
    midword_period
    no_period

    Methods
    -------
    a
    b
    c

    .. index::

    """)

def test_class_members_doc_sphinx():
    class Foo:
        @property
        def an_attribute(self):
            """Test attribute"""
            return None

        @property
        def no_docstring(self):
            return None

        @property
        def no_docstring2(self):
            return None

        @property
        def multiline_sentence(self):
            """This is a
            sentence. It spans multiple lines."""
            return None

        @property
        def midword_period(self):
            """The sentence for numpy.org."""
            return None

        @property
        def no_period(self):
            """This does not have a period
            so we truncate its summary to the first linebreak

            Apparently.
            """
            return None

    doc = SphinxClassDoc(Foo, class_doc_txt)
    line_by_line_compare(str(doc),
    """
    Foo

    :Parameters:

        f : callable ``f(t, y, *f_args)``
            Aaa.

        jac : callable ``jac(t, y, *jac_args)``
            Bbb.

    .. rubric:: Examples

    For usage examples, see `ode`.

    :Attributes:

        t : float
            Current time.

        y : ndarray
            Current variable values.

            * hello
            * world

        :obj:`an_attribute <an_attribute>` : float
            Test attribute

        no_docstring : str
            But a description

        no_docstring2 : str
            ..

        :obj:`multiline_sentence <multiline_sentence>`
            This is a sentence.

        :obj:`midword_period <midword_period>`
            The sentence for numpy.org.

        :obj:`no_period <no_period>`
            This does not have a period

    .. rubric:: Methods

    =====  ==========
    **a**
    **b**
    **c**
    =====  ==========

    """)

def test_templated_sections():
    doc = SphinxClassDoc(None, class_doc_txt,
                         config={'template': jinja2.Template('{{examples}}\n{{parameters}}')})
    line_by_line_compare(str(doc),
    """
    .. rubric:: Examples

    For usage examples, see `ode`.

    :Parameters:

        f : callable ``f(t, y, *f_args)``
            Aaa.

        jac : callable ``jac(t, y, *jac_args)``
            Bbb.

    """)

if __name__ == "__main__":
    import nose
    nose.run()