text:
from oslib import Command

class GetAllImages(Command):
    object = 'ami'
    verb = 'dump'
    def fill_parser(self, parser):
        pass

    def execute(self, *args, **kwargs):
        for ami in self.conn.get_all_images():
            print "==== %s ==== " % ami.id
            print "    name: %s" % ami.name
            print "    description: %s" % ami.description
            print "    architecture: %s" % ami.architecture
            print "    root_device_name: %s" % ami.root_device_name
            print "    block_device_mapping = "
            for device in ami.block_device_mapping:
                device_type = ami.block_device_mapping[device]
                print "        %s:" % (device)
                print "            size: %s" % device_type.size
                print "            snapshot_id: %s" % device_type.snapshot_id
            print

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace marty;

use mako\view\renderers\RendererInterface;
use Smarty;
use SmartyException;

class SmartyRenderer implements RendererInterface
{
    private $smarty;

    public function __construct(Smarty $smarty)
    {
        $this->smarty = $smarty;
    }

    /**
     * Render the view into a string.
     *
     * @param string $view The filename of the view.
     * @param array $variables Assigned variables
     * @return string The resulting view.
     * @throws SmartyException should anything fail with template parsing.
     */
    public function render(string $view, array $variables) : string
    {
        $smarty = $this->smarty;
        $smarty->clearAllAssign();

        $smarty->assign($variables);

        return $smarty->fetch($view);
    }
}


text:
module.exports = function(statment, compileOne, compileScope){
	return [
		compileOne(statment.getProperty("target")),
		compileOne(statment.getProperty("args")),
		compileOne(statment.getProperty("spreads")),
		compileScope(statment.getProperty("scope"))
	];
}


text:
package selfreferencingnativetype;

import jsinterop.annotations.JsType;

@JsType(namespace = "zoo")
public class Foo {
  public static String getMe() {
    return "me";
  }

  // Refer to the implementation "zoo.Foo$impl" instead to avoid creating an "invalid" circular
  // reference.
  @JsType(isNative = true, name = "Foo$impl", namespace = "zoo")
  public static class ZooFoo {
    public static native String getMe();
  }

  public static String getMeViaNative() {
    return ZooFoo.getMe();
  }
}


text:
from supybot.test import *

class TopicTestCase(ChannelPluginTestCase):
    plugins = ('Topic','User',)
    def testRemove(self):
        self.assertError('topic remove 1')
        _ = self.getMsg('topic add foo')
        _ = self.getMsg('topic add bar')
        _ = self.getMsg('topic add baz')
        self.assertError('topic remove 0')
        self.assertNotError('topic remove 3')
        self.assertNotError('topic remove 2')
        self.assertNotError('topic remove 1')
        self.assertError('topic remove 1')

    def testRemoveMultiple(self):
        self.assertError('topic remove 1 2')
        _ = self.getMsg('topic add foo')
        _ = self.getMsg('topic add bar')
        _ = self.getMsg('topic add baz')
        _ = self.getMsg('topic add derp')
        _ = self.getMsg('topic add cheese')
        self.assertNotError('topic remove 1 2')
        self.assertNotError('topic remove -1 1')
        self.assertError('topic remove -99 1')

    def testReplace(self):
        _ = self.getMsg('topic add foo')
        _ = self.getMsg('topic add bar')
        _ = self.getMsg('topic add baz')
        self.assertRegexp('topic replace 1 oof', 'oof.*bar.*baz')
        self.assertRegexp('topic replace -1 zab', 'oof.*bar.*zab')
        self.assertRegexp('topic replace 2 lorem ipsum',
                          'oof.*lorem ipsum.*zab')
        self.assertRegexp('topic replace 2 rab', 'oof.*rab.*zab')

    def testGet(self):
        self.assertError('topic get 1')
        _ = self.getMsg('topic add foo')
        _ = self.getMsg('topic add bar')
        _ = self.getMsg('topic add baz')
        self.assertRegexp('topic get 1', '^foo')
        self.assertError('topic get 0')

    def testAdd(self):
        self.assertError('topic add #floorgle')
        m = self.getMsg('topic add foo')
        self.assertEqual(m.command, 'TOPIC')
        self.assertEqual(m.args[0], self.channel)
        self.assertEqual(m.args[1], 'foo')
        m = self.getMsg('topic add bar')
        self.assertEqual(m.command, 'TOPIC')
        self.assertEqual(m.args[0], self.channel)
        self.assertEqual(m.args[1], 'foo | bar')

    def testManageCapabilities(self):
        try:
            self.irc.feedMsg(ircmsgs.mode(self.channel, args=('+o', self.nick),
                                      prefix=self.prefix))
            self.irc.feedMsg(ircmsgs.mode(self.channel, args=('+t'),
                                      prefix=self.prefix))
            world.testing = False
            origuser = self.prefix
            self.prefix = 'stuff!stuff@stuff'
            self.assertNotError('register nottester stuff', private=True)

            self.assertError('topic add foo')
            origconf = conf.supybot.plugins.Topic.requireManageCapability()
            conf.supybot.plugins.Topic.requireManageCapability.setValue('')
            self.assertNotError('topic add foo')
        finally:
            world.testing = True
            self.prefix = origuser
            conf.supybot.plugins.Topic.requireManageCapability.setValue(origconf)

    def testInsert(self):
        m = self.getMsg('topic add foo')
        self.assertEqual(m.args[1], 'foo')
        m = self.getMsg('topic insert bar')
        self.assertEqual(m.args[1], 'bar | foo')

    def testChange(self):
        _ = self.getMsg('topic add foo')
        _ = self.getMsg('topic add bar')
        _ = self.getMsg('topic add baz')
        self.assertRegexp('topic change -1 s/baz/biff/',
                          r'foo.*bar.*biff')
        self.assertRegexp('topic change 2 s/bar/baz/',
                          r'foo.*baz.*biff')
        self.assertRegexp('topic change 1 s/foo/bar/',
                          r'bar.*baz.*biff')
        self.assertRegexp('topic change -2 s/baz/bazz/',
                          r'bar.*bazz.*biff')
        self.assertError('topic change 0 s/baz/biff/')

    def testConfig(self):
        try:
            original = conf.supybot.plugins.Topic.separator()
            conf.supybot.plugins.Topic.separator.setValue(' <==> ')
            _ = self.getMsg('topic add foo')
            m = self.getMsg('topic add bar')
            self.failUnless('<==>' in m.args[1])
        finally:
            conf.supybot.plugins.Topic.separator.setValue(original)

    def testReorder(self):
        _ = self.getMsg('topic add foo')
        _ = self.getMsg('topic add bar')
        _ = self.getMsg('topic add baz')
        self.assertRegexp('topic reorder 2 1 3', r'bar.*foo.*baz')
        self.assertRegexp('topic reorder 3 -2 1', r'baz.*foo.*bar')
        self.assertError('topic reorder 0 1 2')
        self.assertError('topic reorder 1 -2 2')
        self.assertError('topic reorder 1 2')
        self.assertError('topic reorder 2 3 4')
        self.assertError('topic reorder 1 2 2')
        self.assertError('topic reorder 1 1 2 3')
        _ = self.getMsg('topic remove 1')
        _ = self.getMsg('topic remove 1')
        self.assertError('topic reorder 1')
        _ = self.getMsg('topic remove 1')
        self.assertError('topic reorder 0')

    def testList(self):
        _ = self.getMsg('topic add foo')
        self.assertRegexp('topic list', '1: foo')
        _ = self.getMsg('topic add bar')
        self.assertRegexp('topic list', '1: foo.*2: bar')
        _ = self.getMsg('topic add baz')
        self.assertRegexp('topic list', '1: foo.* 2: bar.* and 3: baz')

    def testSet(self):
        _ = self.getMsg('topic add foo')
        self.assertRegexp('topic set -1 bar', 'bar')
        self.assertNotRegexp('topic set -1 baz', 'bar')
        self.assertResponse('topic set foo bar baz', 'foo bar baz')
        # Catch a bug we had where setting topic 1 would reset the whole topic
        orig = conf.supybot.plugins.Topic.format()
        sep = conf.supybot.plugins.Topic.separator()
        try:
            conf.supybot.plugins.Topic.format.setValue('$topic')
            self.assertResponse('topic add baz', 'foo bar baz%sbaz' % sep)
            self.assertResponse('topic set 1 bar', 'bar%sbaz' % sep)
        finally:
            conf.supybot.plugins.Topic.format.setValue(orig)

    def testRestore(self):
        self.getMsg('topic set foo')
        self.assertResponse('topic restore', 'foo')
        self.getMsg('topic remove 1')
        restoreError = 'Error: I haven\'t yet set the topic in #test.'
        self.assertResponse('topic restore', restoreError)

    def testRefresh(self):
        self.getMsg('topic set foo')
        self.assertResponse('topic refresh', 'foo')
        self.getMsg('topic remove 1')
        refreshError = 'Error: I haven\'t yet set the topic in #test.'
        self.assertResponse('topic refresh', refreshError)

    def testUndo(self):
        try:
            original = conf.supybot.plugins.Topic.format()
            conf.supybot.plugins.Topic.format.setValue('$topic')
            self.assertResponse('topic set ""', '')
            self.assertResponse('topic add foo', 'foo')
            self.assertResponse('topic add bar', 'foo | bar')
            self.assertResponse('topic add baz', 'foo | bar | baz')
            self.assertResponse('topic undo', 'foo | bar')
            self.assertResponse('topic undo', 'foo')
            self.assertResponse('topic undo', '')
        finally:
            conf.supybot.plugins.Topic.format.setValue(original)

    def testUndoRedo(self):
        try:
            original = conf.supybot.plugins.Topic.format()
            conf.supybot.plugins.Topic.format.setValue('$topic')
            self.assertResponse('topic set ""', '')
            self.assertResponse('topic add foo', 'foo')
            self.assertResponse('topic add bar', 'foo | bar')
            self.assertResponse('topic add baz', 'foo | bar | baz')
            self.assertResponse('topic undo', 'foo | bar')
            self.assertResponse('topic undo', 'foo')
            self.assertResponse('topic undo', '')
            self.assertResponse('topic redo', 'foo')
            self.assertResponse('topic redo', 'foo | bar')
            self.assertResponse('topic redo', 'foo | bar | baz')
            self.assertResponse('topic undo', 'foo | bar')
            self.assertResponse('topic undo', 'foo')
            self.assertResponse('topic redo', 'foo | bar')
            self.assertResponse('topic undo', 'foo')
            self.assertResponse('topic redo', 'foo | bar')
        finally:
            conf.supybot.plugins.Topic.format.setValue(original)

    def testSwap(self):
        original = conf.supybot.plugins.Topic.format()
        try:
            conf.supybot.plugins.Topic.format.setValue('$topic')
            self.assertResponse('topic set ""', '')
            self.assertResponse('topic add foo', 'foo')
            self.assertResponse('topic add bar', 'foo | bar')
            self.assertResponse('topic add baz', 'foo | bar | baz')
            self.assertResponse('topic swap 1 2', 'bar | foo | baz')
            self.assertResponse('topic swap 1 -1', 'baz | foo | bar')
            self.assertError('topic swap -1 -1')
            self.assertError('topic swap 2 -2')
            self.assertError('topic swap 1 -3')
            self.assertError('topic swap -2 2')
            self.assertError('topic swap -3 1')
        finally:
            conf.supybot.plugins.Topic.format.setValue(original)

    def testDefault(self):
        self.assertError('topic default')
        try:
            original = conf.supybot.plugins.Topic.default()
            conf.supybot.plugins.Topic.default.setValue('foo bar baz')
            self.assertResponse('topic default', 'foo bar baz')
        finally:
            conf.supybot.plugins.Topic.default.setValue(original)

    def testTopic(self):
        original = conf.supybot.plugins.Topic.format()
        try:
            conf.supybot.plugins.Topic.format.setValue('$topic')
            self.assertError('topic addd') # Error to send too many args.
            self.assertResponse('topic add foo', 'foo')
            self.assertResponse('topic add bar', 'foo | bar')
            self.assertResponse('topic', 'foo | bar')
        finally:
            conf.supybot.plugins.Topic.format.setValue(original)

    def testSeparator(self):
        original = conf.supybot.plugins.Topic.format()
        try:
            conf.supybot.plugins.Topic.format.setValue('$topic')
            self.assertResponse('topic add foo', 'foo')
            self.assertResponse('topic add bar', 'foo | bar')
            self.assertResponse('topic add baz', 'foo | bar | baz')
            self.assertResponse('topic separator ::', 'foo :: bar :: baz')
            self.assertResponse('topic separator ||', 'foo || bar || baz')
            self.assertResponse('topic separator |', 'foo | bar | baz')

        finally:
            conf.supybot.plugins.Topic.format.setValue(original)

    def testFit(self):
        original = conf.supybot.plugins.Topic.format()
        try:
            conf.supybot.plugins.Topic.format.setValue('$topic')
            self.irc.state.supported['TOPICLEN'] = 20
            self.assertResponse('topic fit foo', 'foo')
            self.assertResponse('topic fit bar', 'foo | bar')
            self.assertResponse('topic fit baz', 'foo | bar | baz')
            self.assertResponse('topic fit qux', 'bar | baz | qux')
        finally:
            conf.supybot.plugins.Topic.format.setValue(original)
            self.irc.state.supported.pop('TOPICLEN', None)

# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:


text:
package it.sevenbits.jsonformat;

import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;

/**
 * ConversionServiceAwareObjectMapper
 * @author Ivan Pastushenko
 * @version 1.0.0
 * Date: 07.09.2013
 */
public class ConversionServiceAwareObjectMapper extends ObjectMapper {
    @Autowired
    public ConversionServiceAwareObjectMapper(ConversionService conversionService) {
        AnnotationIntrospector introspector = AnnotationIntrospector.pair(new FormatAnnotationIntrospector(conversionService), DEFAULT_ANNOTATION_INTROSPECTOR);
        setAnnotationIntrospector(introspector);
    }
}


text:
<!DOCTYPE html>

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

Let’s write books in HTML! HTMLBook is an open, XHTML5-based standard for the authoring and production of both print and digital books. HTMLBook is built on the following premises:

Books are timeless. The basic “book” structure has persisted for hundreds of years and will continue to persist for our lifetimes, be it in digital or print form.

HTML is the markup language of the world for the foreseeable future.

Single-source document processing will remain valuable for the foreseeable future.

As such, HTMLBook can be characterized in the following ways:

HTMLBook is a subset of XHTML5. All HTMLBook is XHTML5, but not all XHTML5 is HTMLBook.

HTMLBook contains no additional elements or attributes outside of the XHTML5 specification.

HTMLBook is semantically tailored to the structure of a book, including more complex content used in technical and reference documents.

HTMLBook is defined with and can be validated against an XML schema.

HTMLBook stylesheets are written in CSS.

Notes on the HTMLBook Specification

Requirements for HTML5 elements in the HTMLBook specification are below. Special semantic inflections for data-type attributes, unless otherwise noted, come from EPUB 3 Structural Semantics Vocabulary

Many content models refer to “Block Elements” or “Inline Elements”; please see Block Elements and Inline Elements for the corresponding list of HTML5 elements that belong to each of these categories.

If no content model or attribute requirements are explicitly specified, then HTMLBook adopts the corresponding requirements in the [[!HTML5]] Specification

Revision History and Notes

25 February 2015

Clarified HTMLBook specifications for inline semantics/tagging

8 April 2014

Updated specifications for section subtitles to comply with best practices set forth in “Common idioms without dedicated elements” in [[!HTML5]] Specification.

29 December 2013

Minor revisions for clarity

13 August 2013

Revised specification for footnote markup

3 July 2013

Changed spec to use the attribute data-type for specifying book-specific semantics instead of class. The class attribute is
now free to be used for whatever user-defined semantics are desired, and there are no restrictions on class values. Users of the spec may want to replicate data-type values in the class attribute to facilitate CSS styling, but this is completely optional.

19 April 2013

First release of Working Draft

Book Component elements

Book

HTML element: <body>

Attribute requirements: data-type="book" (Not in [[EPUB3SSV]]; from [[DOCBOOK]])

Content model: Optional <h1> that contains book title, or Header block that contains book title and optional subtitle content; then one or more Book Component elements as children (<div> for Part elements, <nav> for Table of Contents, and <section> elements for all other book divisions)

          Example

<body data-type="book">
  <h1>jQuery Cookbook</h1>
  <section data-type="chapter">
    <!-- Chapter content here -->
  </section>
</body>

Note: Just as in standard HTML5, <body> is a child of the root <html> element.

Chapter

HTML element: <section>

Attribute requirements: data-type="chapter"

Content model: First child must be either <h1> that contains chapter title, or Header block that contains chapter title and optional subtitle content; then zero or more Block Elements; then zero or more Sect1 children (<section data-type="sect1">)

          Example

<section data-type="chapter">
  <!-- h1 used for all chapter titles -->
  <h1>Chapter Title</h1>
  <p>Chapter content</p>
  <section data-type="sect1">
    <!-- Section content here... -->
  </section>
</section>

Appendix

HTML element: <section>

Attribute requirements: data-type="appendix" or data-type="afterword", depending on content

Content model: First child must be either <h1> that contains appendix title, or Header block that contains appendix title and optional subtitle content; then zero or more Block Elements; then zero or more Sect1 children (<section data-type="sect1">)

          Example

<section data-type="appendix">
  <h1>Appendix Title</h1>
  <p>Appendix content</p>
  <section data-type="sect1">
    <!-- Section content here... -->
  </section>
</section>

Bibliography

HTML element: <section>

Attribute requirements: data-type="bibliography"

Content model: First child must be either <h1> that contains bibliography title, or Header block that contains bibliography title and optional subtitle content; then zero or more Block Elements; then zero or more Sect1 children (<section data-type="sect1">)

          Example

<section data-type="bibliography">
  <h1>Bibliography Title</h1>
  <p>Bibliography content</p>
  <section data-type="sect1">
    <!-- Section content here... -->
  </section>
</section>

Glossary

HTML element: <section>

Attribute requirements: data-type="glossary"

Content model: First child must be either <h1> that contains glossary title, or Header block that contains glossary title and optional subtitle content; then zero or more Block Elements; then zero or more Sect1 children (<section data-type="sect1">)

Best practices: List of glossary terms should be marked up using <dl> elements with a data-type of "glossary", with <dt> children with a data-type of "glossterm" and <dd> children with a data-type of "glossdef". Term text should be wrapped in a <dfn>. However, none of this is formally required by the spec.

          Example

<section data-type="glossary">
  <h1>Glossary Title</h1>
  <dl data-type="glossary">
    <dt data-type="glossterm">
      <dfn>jQuery</dfn>
    </dt>
    <dd data-type="glossdef">
      Widely used JavaScript library
    </dd>
   </dl>
</section>

Preface

HTML element: <section>

Attribute requirements: data-type="preface", data-type="foreword", or data-type="introduction", depending on content

Content model: First child must be either <h1> that contains preface title, or Header block that contains preface title and optional subtitle content; then zero or more Block Elements; then zero or more Sect1 children (<section data-type="sect1">)

          Example

<section data-type="preface">
  <h1>Preface Title</h1>
  <p>Preface content</p>
  <section data-type="sect1">
    <!-- Section content here... -->
  </section>
</section>

Frontmatter

HTML element: <section>

Attribute requirements: data-type="halftitlepage", data-type="titlepage", data-type="copyright-page", or data-type="dedication", depending on content

Content model: First child must be either <h1> that contains frontmatter section title, or Header block that contains frontmatter title and optional subtitle content; then zero or more Block Elements; then zero or more Sect1 children (<section data-type="sect1">)

          Example

<section data-type="titlepage">
  <h1>Python in a Nutshell</h1>
  <p>By Alex Martelli</p>
</section>

Backmatter

HTML element: <section>

Attribute requirements: data-type="colophon", data-type="acknowledgments", data-type="afterword", or data-type="conclusion", depending on content

Content model: First child must be either <h1> that contains backmatter section title, or Header block that contains backmatter title and optional subtitle content; then zero or more Block Elements; then zero or more Sect1 children (<section data-type="sect1">)

          Example

<section data-type="colophon">
  <h1>Colophon Title</h1>
  <p>Colophon content</p>
  <section data-type="sect1">
    <!-- Section content here... -->
  </section>
</section>

Part

HTML element: <div>

Attribute requirements: data-type="part"

Content model: First child must be either <h1> that contains part title, or Header block that contains part title and optional subtitle content; then zero or more Block Elements that compose the optional Part introduction; then one or more <section> elements representing Book Component children other than a Part

          Example

<div data-type="part">
  <h1>Part One: Introduction to Backbone.js</h1>
  <p>Part Introduction...</p>
  <section data-type="chapter">
    <!-- Chapter content here -->
  </section>
</div>

Table of Contents

HTML element: <nav>

Attribute requirements: data-type="toc"

Content Model: The TOC must be conformant to the specs for the [[EPUB3]] Navigation document. First child is zero or more Heading elements (<h1>-<h6>), followed by an <ol> (with <li> children that can contain only a <span> element or an <a> element plus an optional <ol> child)

          Example

<nav data-type="toc">
  <h1>Table of Contents</h1>
   <ol>
     <li><a href="examples_page.html">A Note Regarding Supplemental Files</a></li>
     <li><a href="pr02.html">Foreword</a></li>
     <li><a href="pr03.html">Contributors</a>
       <ol>
         <li><a href="pr03.html#I_sect1_d1e154">Chapter Authors</a></li>
         <li><a href="pr03.html#I_sect1_d1e260">Tech Editors</a></li>
       </ol>
     </li>
  </ol>
</nav>

Index

HTML element: <section>

Attribute requirements: data-type="index"

Content model: First child must be either <h1> that contains index title, or Header block that contains index title and optional subtitle content; then zero or more Block Elements; then zero or more Sect1 children (<section data-type="sect1">)

Best practices: HTMLBook recommends following the [[EPUBINDEX]] specification and using <ol>/<li> elements for marking up index entries, with data-type attributes used for semantic inflection as appropriate, but none of this is a formal spec requirement

          Example

<section data-type="index">
  <h1>Index Title</h1>
  <div data-type="index-group">
    <h2>A</h2>
    <ol>
      <li data-type="index-term">AsciiDoc, <a href="ch01#asciidoc" data-type="index-locator">All about AsciiDoc</a>
	<ol>
           <li data-type="index-term">conversion to HTML,
             <a href="ch01#asctohtml" data-type="index-locator">AsciiDoc Output Formats</a>
           </li>
         </ol>
      </li>
      <li data-type="index-term">azalea, <a href="ch01#azalea" data-type="index-locator">Shrubbery</a></li>
    </ol>
  </div>
</section>

Sections

HTML element: <section>

Attribute requirements: data-type="sect1", data-type="sect2", data-type="sect3", data-type="sect4", data-type="sect5" (From [[DOCBOOK]] vocabulary), depending on hierarchy level. sect1 is used for <section> elements nested directly in main Book Components ("chapter", "appendix", etc.). sect2 is used for <section> elements nested in a sect1 <section>, sect3 is used for <section> elements nested in a sect2 <section>, and so on.

Content model: The first child must either be a main heading element corresponding to the hierarchy level indicated by data-type value, as follows:

"sect1" -> h1
"sect2" -> h2
"sect3" -> h3
"sect4" -> h4
"sect5" -> h5

or a Header block that contains section title and optional subtitle content. This is followed by zero or more Block Elements, followed by zero or more <section> elements with a data-type value one level lower in the hierarchy, as long as the parent section is a "sect4" or higher (e.g., <section data-type="sect4"> nested in <section data-type="sect3">)

Example:

<section data-type="sect1">
  <h1>A-Head</h1>
  <p>If you httpparty, you must party hard</p>
  <!-- Some more paragraphs -->
  <section data-type="sect2">
    <h2>B-Head</h2>
    <p>What's the frequency, Kenneth?</p>
    <!-- And so on... -->
  </section>
</section>

Block Elements

Paragraph

HTML element: <p>

Example:

<p>This is a standard paragraph with some <em>emphasized text</em></p>

Sidebar

HTML element: <aside>

Attribute requirements: data-type="sidebar"

Content model: Zero or one <h5> element that contains the sidebar title); then zero or more Block Elements

Example:

<aside data-type="sidebar">
  <h5>Amusing Digression</h5>
  <p>Did you know that in Boston, they call it "soda", and in Chicago, they call it "pop"?</p>
</aside>

Admonitions

HTML element: <div>

Attribute requirements: data-type="note", data-type="warning", data-type="tip", data-type="caution", or data-type="important", depending on the content within

Content model: Either of the following content models is acceptable:

Text and/or zero or more Inline Elements

Zero or more <h1>–<h6> elements, followed by zero or more Block Elements

Examples:

<div data-type="note">
  <h1>Helpful Info</h1>
  <p>Please take note of this important information</p>
</div>

<div data-type="warning">Make sure to get your AsciiDoc markup right!</div>

Tables

HTML element: <table>

Content model: Zero or one <caption> elements (for titled/captioned tables); then zero or more <colgroup> elements; then zero or more <thead> elements; then a choice between either zero or more <tbody> elements, or zero or more <tr> elements; then zero or more <tfoot> elements

Content model for <caption>: Either of the following is acceptable:

Zero or more <p> and/or <div> elements

Text and/or zero or more Inline Elements

Content model for <colgroup>: Mirrors [[HTML5]] Specification

Content models for <thead>, <tbody>, and <tfoot>: Mirror [[HTML5]] Specification

Content model for <tr>: Mirrors [[HTML5]] Specification, but see content model below for rules for child <td> and <th> elements

Content model for <td> and <th> elements: Either of the following is acceptable:

Text and/or zero or more Inline Elements

Zero or more Block Elements

Examples:

<table>
<caption>State capitals</caption>
<tr>
  <th>State</th>
  <th>Capital</th>
</tr>
<tr>
  <td>Massachusetts</td>
  <td>Boston</td>
</tr>
<!-- And so on -->
</table>

<table>
  <thead>
    <tr>
      <th>First</th>
      <th>Middle Initial</th>
      <th>Last</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Alfred</td>
      <td>E.</td>
      <td>Newman</td>
    </tr>
    <!-- And so on -->
  </tbody>
</table>

Figures

HTML element: <figure>

Content model: Either of the following is acceptable:

A <figcaption> element followed by zero or more Block Elements and/or <img> elements

Zero or more Block Elements and/or <img> elements, followed by a <figcaption> element

Example:

<figure>
<figcaption>Adorable cat</figcaption>
<img src="cute_kitty.gif" alt="Photo of an adorable cat"/>
</figure>

Examples

HTML element: <div>

Attribute requirements: data-type="example"

Content model: Either of the following content models is acceptable:

Text and/or zero or more Inline Elements

Zero or more <h1>–<h6> elements (for title and subtitles), followed by zero or more Block Elements

Example:

<div data-type="example">
<h5>Hello World in Python</h5>
<pre data-type="programlisting">print "Hello World"</pre>
</div>

Code listings

HTML element: <pre>

Attribute requirements: data-type="programlisting"

Optional HTMLBook-specific attribute: data-code-language, used to indicate language of code listing (e.g., data-code-language="python")

Example:

<pre data-type="programlisting">print "<em>Hello World</em>"</pre>

Ordered lists

HTML element: <ol>

Content model: Zero or more <li> children for each list item

Content model for <li> children: Either of the following is acceptable:

Text and/or zero or more Inline Elements

Zero or more Block Elements

Example:

<ol>
<li>Step 1</li>
<li>
  <p>Step 2</p>
  <p>Step 2 continued</p>
</li>
<!-- And so on -->
</ol>

Itemized lists

HTML element: <ul>

Content model: Zero or more <li> children for each list item

Content model for <li> children: Either of the following is acceptable:

Text and/or zero or more Inline Elements

Zero or more Block Elements

Example:

<ul>
<li>Red</li>
<li>Orange</li>
<!-- And so on -->
</ul>

Definition lists

HTML element: <dl>

Content model: Mirrors [[HTML5]] Specification

Content model for <dt> children: text and/or zero or more Inline Elements

Content model for <dd> children: Either of the following is acceptable:

Text and/or zero or more Inline Elements

Zero or more Block Elements

Example:

<dl>
  <dt>Constant Width Bold font</dt>
  <dd>Used to indicate user input</dd>
</dl>

Blockquote

HTML element: <blockquote>

Content model: Either of the following is acceptable:

Text and/or zero or more Inline Elements

Zero or more Block Elements

Example:

<blockquote>
  <p>When in the course of human events...</p>
  <p data-type="attribution">U.S. Declaration of Independence</p>
</blockquote>

Note: If the blockquote is an epigraph, add data-type="epigraph", e.g.:

<section data-type="chapter">
  <h1>Conclusion</h1>
  <blockquote data-type="epigraph">
    <p>It ain't over till it's over.</p>
    <p data-type="attribution">Yogi Berra</p>
  </blockquote>
  <p>In this final chapter of the book, we will…<p>
</section>

Equation

HTML element: <div>

Attribute requirements: data-type="equation" (From [[DOCBOOK]]; no close match in [[EPUB3SSV]])

Note: HTMLBook supports embedded MathML in HTML content documents, which can be used here.

Example:

<div data-type="equation">
<h5>Pythagorean Theorem</h5>
<math xmlns="http://www.w3.org/1998/Math/MathML">
  <msup><mi>a</mi><mn>2</mn></msup>
  <mo>+</mo>
  <msup><mi>b</mi><mn>2</mn></msup>
  <mo>=</mo>
  <msup><mi>c</mi><mn>2</mn></msup>
</math>
</div>

Inline Elements

HTMLBook is primarily focused on codifying structural semantics for book authoring, and as such, it does not formally define specifications for phrase-level semantics (such as the DocBook varname or personname elements) beyond that which is codified in the [[!HTML5]] specification. Nor does it formally define specifications for purely presentational markup (such as underline or strikethrough rendering). HTMLBook users are encouraged to employ the appropriate standard HTML5 phrasing elements for inline semantics when available (e.g., <strong>, <em>, <s>, <u>) and to use <span> elements with custom-defined classes in other cases, as illustrated in the following examples.

Emphasis (generally for italic)

HTML element: <em>

Example:

<p>I <em>love</em> HTML!</p>

Strong (generally for bold)

HTML element: <strong>

Example:

<p>I <strong>love</strong> HTML!</p>

Literal (for inline code elements: variables, functions, etc.)

HTML element: <code>

Example:

<p>Enter <code>echo "Hello World"</code> on the command line</p>

General-purpose phrase markup for other styling

HTML element: <span>

Example:

<p>Use your own class attributes for custom styling for formatting
like <span class="underline">underlined text</span></p>

Footnote, endnote

HTML element: <span>

Attribute requirements: data-type="footnote"

Content model: text and/or zero or more Inline Elements

Example:

<p>Five out of every six people who try AsciiDoc prefer it to
Markdown<span data-type="footnote">Totally made-up statistic</span></p>

Notes:

The <span> element does not accept block element children (and as of April 2014, nor does any other HTML5 element that can be used in an inline context and is an acceptable semantic fit for footnotes). If you need to include multiple blocks of content in a footnote, use <br/> elements to delimit them, e.g.:

<p>This is a really short paragraph.<span data-type="footnote">Largely because I like
to put lots and lots of content in footnotes.<br/><br/>
For example, let me tell you a story about my dog...</span></p>

Desired rendering of footnote content (i.e., floating/moving footnotes to the bottom of a page or end of a section, adding appropriate marker symbols/numeration) should be handled by XSL/CSS stylesheet processing.

Cross-references

HTML element: <a>

Attribute requirements: data-type="xref" (From [[DOCBOOK]]); an href attribute that should point to the id of a
local HTMLBook resource referenced; data-xrefstyle (optional) for specifying the style of XREF

Example:

<section id="html5" data-type="chapter">
  <h1>Intro to HTML5<h1>
  <p>As I said at the beginning of <a data-type="xref" href="#html5">Chapter 1</a>, HTML5 is great...</p>
  <!-- Blah blah blah -->
</section>

Index Term

HTML element: <a>

Attribute requirements: data-type="indexterm"; for primary index entry value, use data-primary; for secondary index entry value, use data-secondary; for tertiary index entry value, use data-tertiary; for a "see" index reference, use data-see; for a "see also" index reference, use data-seealso; for a "sort" value to indicate alphabetization, use data-primary-sortas, data-secondary-sortas, or data-tertiary-sortas; for an "end-of-range" tag that marks the end of an index range, use data-startref="id_of_opening_index_marker" (Semantics from [[DOCBOOK]])

Content model: Empty

Example:

<p>The Atlas build system<a data-type="indexterm" data-primary="Atlas" data-secondary="build system"/> lets
you build EPUB, Mobi, PDF, and HTML content</p>

Superscripts

HTML element: <sup>

Example:

<p>The area of a circle is πr<sup>2</sup></p>

Subscripts

HTML element: <sub>

Example:

<p>The formula for water is H<sub>2</sub>O</p>

Heading Elements

Headings

HTML elements: <h1>, <h2>, <h3>, <h4>, <h5>, or <h6>

Content Model: text and/or zero or more Inline Elements

Notes: Many main book components (e.g., chapters, parts, appendixes) require headings. The appropriate
element from <h1>–<h6> is outlined below, as well as in the corresponding documentation for these
components:

book title -> h1
part title -> h1
chapter title -> h1
preface title -> h1
appendix title -> h1
colophon title -> h1
dedication title -> h1
glossary title -> h1
bibliography title -> h1
sect1 title -> h1
sect2 title -> h2
sect3 title -> h3
sect4 title -> h4
sect5 title -> h5
sidebar title -> h5

Header

HTML element: <header>

Content Model: A Heading element at the proper level designated (h1–h5)
	  for the parent Book Component, as outlined in the previous Headings section (e.g., an <h1> for a chapter <header>); then zero or more <p> elements for subtitles or author attributions, each of which must have a data-type of either subtitle or author

Example:

<section data-type="chapter">
  <header>
    <h1>Chapter title</h1>
    <p data-type="subtitle">Chapter subtitle</p>
  </header>
  <!-- Chapter content here... -->
</section>

Interactive Elements

Video

HTML element: <video>

Example:

Note: Fallback content is strongly recommended for output formats that do not support HTML5 interactive content

<video id="asteroids_video" width="480" height="270" controls="controls" poster="images/fallback_image.png">
<source src="video/html5_asteroids.mp4" type="video/mp4"/>
<source src="video/html5_asteroids.ogg" type="video/ogg"/>
<em>Sorry, the &lt;video&gt; element not supported in your
  reading system. View the video online at http://example.com.</em>
</video>

Audio

HTML element: <audio>

Note: Fallback content is strongly recommended for output formats that do not support HTML5 interactive content

Example:

<audio id="new_slang">
<source src="audio/new_slang.wav" type="audio/wav"/>
<source src="audio/new_slang.mp3" type="audio/mp3"/>
<source src="audionew_slang.ogg" type="audio/ogg"/>
<em>Sorry, the &lt;audio&gt; element is not supported in your
  reading system. Hear the audio online at http://example.com.</em>
</audio>

Canvas

HTML element: <canvas>

Notes: Should include fallbacks for environments that don’t support HTML5 or JavaScript (e.g., link or image).
You may include <script> elements in your HTMLBook document <head> elements to include/reference JS code for
Canvas handling.

Examples:

<canvas id="canvas" width="400" height="400">
 Your browser does not support the HTML 5 Canvas. See the interactive example at http://example.com.
</canvas>

Comments

To add comments to an HTMLBook document, either use standard HTML/XML comment syntax:

<!-- This is a comment -->

Or add a data-type="comment" attribute to any HTML element, e.g.:

<div data-type="comment">This is a comment preceding a paragraph of text</div>
<p>This is a paragraph of text <span data-type="comment">Inline comment in paragraph</span></p>

Metadata

Metadata points

HTML element: <meta>

Attribute requirements: name (for name of metadata point); content (for value of metadata point)

Content model: Empty

Note: All <meta> elements must be children of the <head> element of the HTML file.

Example:

<head>
  <title>Title of the Book</title>
  <meta name="isbn-13" content="9781449344856"/>
</head>

Element Classification

Block Elements

In HTMLBook, the majority of elements classified by the HTML5 specification as Flow Content (minus elements also categorized as Heading Content, Phrasing Content, and Sectioning Content) are considered to be Block Elements. Here is a complete list:

              <address>

              <aside>

              <audio>

              <blockquote>

              <canvas>

              <dd>

              <details>

              <div>

              <dl>

              <embed>

              <fieldset>

              <figure>

              <form>

              <hr>

              <iframe>

              <map>

<math> (In MathML vocabulary; must be namespaced under http://www.w3.org/1998/Math/MathML)

              <menu>

              <object>

              <ol>

              <p>

              <pre>

<svg> (In SVG vocabulary; must be namespaced under http://www.w3.org/2000/svg)

              <table>

              <ul>

              <video>

Inline Elements

In HTMLBook, the majority of elements classified by the HTML5 specification as Phrasing Content are considered to be Inline Elements. Here is a complete list:

              <a>

              <abbr>

              <b>

              <bdi>

              <bdo>

              <br>

              <button>

              <command>

              <cite>

              <code>

              <datalist>

              <del>

              <dfn>

              <dt>

              <em>

              <i>

              <input>

              <img>

              <ins>

              <kbd>

              <keygen>

              <label>

              <mark>

              <meter>

              <output>

              <progress>

              <q>

              <ruby>

              <s>

              <samp>

              <select>

              <small>

              <span>

              <strong>

              <sub>

              <sup>

              <textarea>

              <time>

              <u>

              <var>

              <wbr>


text:
<?php
/*
 *  Required object values:
 *  data -
 */

class subresGet extends openSRS_base {
	private $_dataObject;
	private $_formatHolder = "";
	public $resultFullRaw;
	public $resultRaw;
	public $resultFullFormatted;
	public $resultFormatted;

	public function __construct ($formatString, $dataObject) {
		parent::__construct();
		$this->_dataObject = $dataObject;
		$this->_formatHolder = $formatString;
		$this->_validateObject ();
	}

	public function __destruct () {
		parent::__destruct();
	}

	// Validate the object
	private function _validateObject (){
		$allPassed = true;

		// Command required values
		if (!isSet($this->_dataObject->data->username) || $this->_dataObject->data->username == "") {
			trigger_error ("oSRS Error - username is not defined.", E_USER_WARNING);
			$allPassed = false;
		}

		// Run the command
		if ($allPassed) {
			// Execute the command
			$this->_processRequest ();
		} else {
			trigger_error ("oSRS Error - Incorrect call.", E_USER_WARNING);
		}
	}

	// Post validation functions
	private function _processRequest (){
		$cmd = array(
			'protocol' => 'XCP',
			'object' => 'SUBRESELLER',
			'action' => 'GET',
			'attributes' => array (
				'username' => $this->_dataObject->data->username
			)
		);

		$xmlCMD = $this->_opsHandler->encode($cmd);					// Flip Array to XML
		$XMLresult = $this->send_cmd($xmlCMD);						// Send XML
		$arrayResult = $this->_opsHandler->decode($XMLresult);		// Flip XML to Array

		// Results
		$this->resultFullRaw = $arrayResult;
                if (isSet($arrayResult['attributes'])){
                    $this->resultRaw = $arrayResult['attributes'];
                } else {
			$this->resultRaw = $arrayResult;
		}
		$this->resultFullFormatted = convertArray2Formatted ($this->_formatHolder, $this->resultFullRaw);
		$this->resultFormatted = convertArray2Formatted ($this->_formatHolder, $this->resultRaw);
	}
}


text:
<?php
require(dirname(__FILE__).'/kcaptcha.lib.php');
?>


text:
'''
Grid Layout
===========

.. only:: html

    .. image:: images/gridlayout.gif
        :align: right

.. only:: latex

    .. image:: images/gridlayout.png
        :align: right

.. versionadded:: 1.0.4

The :class:`GridLayout` arranges children in a matrix. It takes the available
space and divides it into columns and rows, then adds widgets to the resulting
"cells".

.. versionchanged:: 1.0.7
    The implementation has changed to use the widget size_hint for calculating
    column/row sizes. `uniform_width` and `uniform_height` have been removed
    and other properties have added to give you more control.

Background
----------

Unlike many other toolkits, you cannot explicitly place a widget in a specific
column/row. Each child is automatically assigned a position determined by the
layout configuration and the child's index in the children list.

A GridLayout must always have at least one input constraint:
:attr:`GridLayout.cols` or :attr:`GridLayout.rows`. If you do not specify cols
or rows, the Layout will throw an exception.

Column Width and Row Height
---------------------------

The column width/row height are determined in 3 steps:

    - The initial size is given by the :attr:`col_default_width` and
      :attr:`row_default_height` properties. To customize the size of a single
      column or row, use :attr:`cols_minimum` or :attr:`rows_minimum`.
    - The `size_hint_x`/`size_hint_y` of the children are taken into account.
      If no widgets have a size hint, the maximum size is used for all
      children.
    - You can force the default size by setting the :attr:`col_force_default`
      or :attr:`row_force_default` property. This will force the layout to
      ignore the `width` and `size_hint` properties of children and use the
      default size.

Using a GridLayout
------------------

In the example below, all widgets will have an equal size. By default, the
`size_hint` is (1, 1), so a Widget will take the full size of the parent::

    layout = GridLayout(cols=2)
    layout.add_widget(Button(text='Hello 1'))
    layout.add_widget(Button(text='World 1'))
    layout.add_widget(Button(text='Hello 2'))
    layout.add_widget(Button(text='World 2'))

.. image:: images/gridlayout_1.jpg

Now, let's fix the size of Hello buttons to 100px instead of using
size_hint_x=1::

    layout = GridLayout(cols=2)
    layout.add_widget(Button(text='Hello 1', size_hint_x=None, width=100))
    layout.add_widget(Button(text='World 1'))
    layout.add_widget(Button(text='Hello 2', size_hint_x=None, width=100))
    layout.add_widget(Button(text='World 2'))

.. image:: images/gridlayout_2.jpg

Next, let's fix the row height to a specific size::

    layout = GridLayout(cols=2, row_force_default=True, row_default_height=40)
    layout.add_widget(Button(text='Hello 1', size_hint_x=None, width=100))
    layout.add_widget(Button(text='World 1'))
    layout.add_widget(Button(text='Hello 2', size_hint_x=None, width=100))
    layout.add_widget(Button(text='World 2'))

.. image:: images/gridlayout_3.jpg

'''

__all__ = ('GridLayout', 'GridLayoutException')

from kivy.logger import Logger
from kivy.uix.layout import Layout
from kivy.properties import NumericProperty, BooleanProperty, DictProperty, \
    BoundedNumericProperty, ReferenceListProperty, VariableListProperty, \
    ObjectProperty, StringProperty
from math import ceil

def nmax(*args):
    # merge into one list
    args = [x for x in args if x is not None]
    return max(args)

class GridLayoutException(Exception):
    '''Exception for errors if the grid layout manipulation fails.
    '''
    pass

class GridLayout(Layout):
    '''Grid layout class. See module documentation for more information.
    '''

    spacing = VariableListProperty([0, 0], length=2)
    '''Spacing between children: [spacing_horizontal, spacing_vertical].

    spacing also accepts a one argument form [spacing].

    :attr:`spacing` is a
    :class:`~kivy.properties.VariableListProperty` and defaults to [0, 0].
    '''

    padding = VariableListProperty([0, 0, 0, 0])
    '''Padding between the layout box and it's children: [padding_left,
    padding_top, padding_right, padding_bottom].

    padding also accepts a two argument form [padding_horizontal,
    padding_vertical] and a one argument form [padding].

    .. versionchanged:: 1.7.0
        Replaced NumericProperty with VariableListProperty.

    :attr:`padding` is a :class:`~kivy.properties.VariableListProperty` and
    defaults to [0, 0, 0, 0].
    '''

    cols = BoundedNumericProperty(None, min=0, allownone=True)
    '''Number of columns in the grid.

    .. versionchanged:: 1.0.8
        Changed from a NumericProperty to BoundedNumericProperty. You can no
        longer set this to a negative value.

    :attr:`cols` is a :class:`~kivy.properties.NumericProperty` and defaults to
    0.
    '''

    rows = BoundedNumericProperty(None, min=0, allownone=True)
    '''Number of rows in the grid.

    .. versionchanged:: 1.0.8
        Changed from a NumericProperty to a BoundedNumericProperty. You can no
        longer set this to a negative value.

    :attr:`rows` is a :class:`~kivy.properties.NumericProperty` and defaults to
    0.
    '''

    col_default_width = NumericProperty(0)
    '''Default minimum size to use for a column.

    .. versionadded:: 1.0.7

    :attr:`col_default_width` is a :class:`~kivy.properties.NumericProperty`
    and defaults to 0.
    '''

    row_default_height = NumericProperty(0)
    '''Default minimum size to use for row.

    .. versionadded:: 1.0.7

    :attr:`row_default_height` is a :class:`~kivy.properties.NumericProperty`
    and defaults to 0.
    '''

    col_force_default = BooleanProperty(False)
    '''If True, ignore the width and size_hint_x of the child and use the
    default column width.

    .. versionadded:: 1.0.7

    :attr:`col_force_default` is a :class:`~kivy.properties.BooleanProperty`
    and defaults to False.
    '''

    row_force_default = BooleanProperty(False)
    '''If True, ignore the height and size_hint_y of the child and use the
    default row height.

    .. versionadded:: 1.0.7

    :attr:`row_force_default` is a :class:`~kivy.properties.BooleanProperty`
    and defaults to False.
    '''

    cols_minimum = DictProperty({})
    '''Dict of minimum width for each column. The dictionary keys are the
    column numbers, e.g. 0, 1, 2...

    .. versionadded:: 1.0.7

    :attr:`cols_minimum` is a :class:`~kivy.properties.DictProperty` and
    defaults to {}.
    '''

    rows_minimum = DictProperty({})
    '''Dict of minimum height for each row. The dictionary keys are the
    row numbers, e.g. 0, 1, 2...

    .. versionadded:: 1.0.7

    :attr:`rows_minimum` is a :class:`~kivy.properties.DictProperty` and
    defaults to {}.
    '''

    minimum_width = NumericProperty(0)
    '''Automatically computed minimum width needed to contain all children.

    .. versionadded:: 1.0.8

    :attr:`minimum_width` is a :class:`~kivy.properties.NumericProperty` and
    defaults to 0. It is read only.
    '''

    minimum_height = NumericProperty(0)
    '''Automatically computed minimum height needed to contain all children.

    .. versionadded:: 1.0.8

    :attr:`minimum_height` is a :class:`~kivy.properties.NumericProperty` and
    defaults to 0. It is read only.
    '''

    minimum_size = ReferenceListProperty(minimum_width, minimum_height)
    '''Automatically computed minimum size needed to contain all children.

    .. versionadded:: 1.0.8

    :attr:`minimum_size` is a
    :class:`~kivy.properties.ReferenceListProperty` of
    (:attr:`minimum_width`, :attr:`minimum_height`) properties. It is read
    only.
    '''

    def __init__(self, **kwargs):
        self._cols = self._rows = None
        super(GridLayout, self).__init__(**kwargs)
        fbind = self.fbind
        update = self._trigger_layout
        fbind('col_default_width', update)
        fbind('row_default_height', update)
        fbind('col_force_default', update)
        fbind('row_force_default', update)
        fbind('cols', update)
        fbind('rows', update)
        fbind('parent', update)
        fbind('spacing', update)
        fbind('padding', update)
        fbind('children', update)
        fbind('size', update)
        fbind('pos', update)

    def get_max_widgets(self):
        if self.cols and self.rows:
            return self.rows * self.cols
        else:
            return None

    def on_children(self, instance, value):
        # if that makes impossible to construct things with deffered method,
        # migrate this test in do_layout, and/or issue a warning.
        smax = self.get_max_widgets()
        if smax and len(value) > smax:
            raise GridLayoutException(
                'Too many children in GridLayout. Increase rows/cols!')

    def _init_rows_cols_sizes(self, count):
        # the goal here is to calculate the minimum size of every cols/rows
        # and determine if they have stretch or not
        current_cols = self.cols
        current_rows = self.rows

        # if no cols or rows are set, we can't calculate minimum size.
        # the grid must be contrained at least on one side
        if not current_cols and not current_rows:
            Logger.warning('%r have no cols or rows set, '
                           'layout is not triggered.' % self)
            return
        if current_cols is None:
            current_cols = int(ceil(count / float(current_rows)))
        elif current_rows is None:
            current_rows = int(ceil(count / float(current_cols)))

        current_cols = max(1, current_cols)
        current_rows = max(1, current_rows)

        self._cols = cols = [self.col_default_width] * current_cols
        self._cols_sh = cols_sh = [None] * current_cols
        self._rows = rows = [self.row_default_height] * current_rows
        self._rows_sh = rows_sh = [None] * current_rows

        # update minimum size from the dicts
        # FIXME index might be outside the bounds ?
        for index, value in self.cols_minimum.items():
            cols[index] = value
        for index, value in self.rows_minimum.items():
            rows[index] = value
        return True

    def _fill_rows_cols_sizes(self):
        cols, rows = self._cols, self._rows
        cols_sh, rows_sh = self._cols_sh, self._rows_sh

        # calculate minimum size for each columns and rows
        n_cols = len(cols)
        for i, child in enumerate(reversed(self.children)):
            (shw, shh), (w, h) = child.size_hint, child.size
            row, col = divmod(i, n_cols)

            # compute minimum size / maximum stretch needed
            if shw is None:
                cols[col] = nmax(cols[col], w)
            else:
                cols_sh[col] = nmax(cols_sh[col], shw)

            if shh is None:
                rows[row] = nmax(rows[row], h)
            else:
                rows_sh[row] = nmax(rows_sh[row], shh)

    def _update_minimum_size(self):
        # calculate minimum width/height needed, starting from padding +
        # spacing
        l, t, r, b = self.padding
        spacing_x, spacing_y = self.spacing
        cols, rows = self._cols, self._rows
        width = l + r + spacing_x * (len(cols) - 1)
        height = t + b + spacing_y * (len(rows) - 1)
        # then add the cell size
        width += sum(cols)
        height += sum(rows)

        # finally, set the minimum size
        self.minimum_size = (width, height)

    def _finalize_rows_cols_sizes(self):
        selfw = self.width
        selfh = self.height

        # resolve size for each column
        if self.col_force_default:
            cols = [self.col_default_width] * len(self._cols)
            for index, value in self.cols_minimum.items():
                cols[index] = value
            self._cols = cols
        else:
            cols = self._cols
            cols_sh = self._cols_sh
            cols_weigth = sum([x for x in cols_sh if x])
            strech_w = max(0, selfw - self.minimum_width)
            for index, col_stretch in enumerate(cols_sh):
                # if the col don't have strech information, nothing to do
                if not col_stretch:
                    continue
                # add to the min width whatever remains from size_hint
                cols[index] += strech_w * col_stretch / cols_weigth

        # same algo for rows
        if self.row_force_default:
            rows = [self.row_default_height] * len(self._rows)
            for index, value in self.rows_minimum.items():
                rows[index] = value
            self._rows = rows
        else:
            rows = self._rows
            rows_sh = self._rows_sh
            rows_weigth = sum([x for x in rows_sh if x])
            strech_h = max(0, selfh - self.minimum_height)
            for index in range(len(rows)):
                # if the row don't have strech information, nothing to do
                row_stretch = rows_sh[index]
                if not row_stretch:
                    continue
                # add to the min height whatever remains from size_hint
                rows[index] += strech_h * row_stretch / rows_weigth

    def _iterate_layout(self, count):
        selfx = self.x
        padding_left = self.padding[0]
        padding_top = self.padding[1]
        spacing_x, spacing_y = self.spacing

        i = count - 1
        y = self.top - padding_top
        cols = self._cols
        for row_height in self._rows:
            x = selfx + padding_left
            for col_width in cols:
                if i < 0:
                    break

                yield i, x, y - row_height, col_width, row_height
                i = i - 1
                x = x + col_width + spacing_x
            y -= row_height + spacing_y

    def do_layout(self, *largs):
        children = self.children
        if not children or not self._init_rows_cols_sizes(len(children)):
            l, t, r, b = self.padding
            self.minimum_size = l + r, t + b
            return
        self._fill_rows_cols_sizes()
        self._update_minimum_size()
        self._finalize_rows_cols_sizes()

        for i, x, y, w, h in self._iterate_layout(len(children)):
            c = children[i]
            c.pos = x, y
            shw, shh = c.size_hint
            if shw is None:
                if shh is not None:
                    c.height = h
            else:
                if shh is None:
                    c.width = w
                else:
                    c.size = (w, h)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3f51b5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#4070ff</color>

    <color name="body_text_white">#FFFFFFFF</color>
    <color name="black_alpha_40">#66000000</color>
    <color name="grey_300">#E0E0E0</color>

    <color name="golden">#FFD700</color>

    <color name="translucent_black">#55000000</color>
    <color name="color_white">#FFFFFFFF</color>
</resources>


text:
#ifndef _ONYX_NET_UDP_H
#define _ONYX_NET_UDP_H

#include <stdint.h>

#include <onyx/net/ip.h>
#include <onyx/net/network.h>
#include <onyx/scoped_lock.h>
#include <onyx/semaphore.h>
#include <onyx/wait_queue.h>

struct udphdr
{
    uint16_t source_port;
    uint16_t dest_port;
    uint16_t len;
    uint16_t checksum;
};

struct udp_packet
{
    struct sockaddr_in addr;
    void *payload;
    size_t size;
    struct udp_packet *next;
};

#define UDP_CORK  1
#define UDP_ENCAP 100

#define UDP_ENCAP_ESPINUDP_NON_IKE 1
#define UDP_ENCAP_ESPINUDP         2
#define UDP_ENCAP_L2TPINUDP        3
#define UDP_ENCAP_GTP0             4
#define UDP_ENCAP_GTP1U            5

class udp_socket : public inet_socket
{
    packetbuf *get_rx_head()
    {
        if (list_is_empty(&rx_packet_list))
            return nullptr;

        return list_head_cpp<packetbuf>::self_from_list_head(list_first_element(&rx_packet_list));
    }

    bool has_data_available()
    {
        return !list_is_empty(&rx_packet_list);
    }

    expected<packetbuf *, int> get_datagram(int flags);

    int wait_for_dgrams()
    {
        return wait_for_event_socklocked_interruptible(&rx_wq, !list_is_empty(&rx_packet_list));
    }

    template <typename AddrType>
    ssize_t udp_sendmsg(const msghdr *msg, int flags, const inet_sock_address &dst);

    unsigned int wants_cork : 1;

    inet_cork cork;

public:
    udp_socket() : wants_cork{0}, cork{SOCK_DGRAM}
    {
    }

    int bind(sockaddr *addr, socklen_t len) override;
    int connect(sockaddr *addr, socklen_t len, int flags) override;
    ssize_t sendmsg(const msghdr *msg, int flags) override;
    int getsockopt(int level, int optname, void *val, socklen_t *len) override;
    int setsockopt(int level, int optname, const void *val, socklen_t len) override;
    int send_packet(const msghdr *msg, ssize_t payload_size, in_port_t source_port,
                    in_port_t dest_port, inet_route &route, int msg_domain);
    ssize_t recvmsg(msghdr *msg, int flags) override;

    void rx_dgram(packetbuf *buf);

    short poll(void *poll_file, short events) override;

    int getsockname(sockaddr *addr, socklen_t *len) override;
    int getpeername(sockaddr *addr, socklen_t *len) override;

    /**
     * @brief Handle UDP socket backlog
     *
     */
    void handle_backlog() override;
};

struct socket *udp_create_socket(int type);
int udp_init_netif(struct netif *netif);
int udp_handle_packet(const inet_route &route, packetbuf *buf);
int udp_handle_packet_v6(netif *netif, packetbuf *buf);

#endif


text:
package org.apache.axis2.jaxws.server.endpoint.lifecycle;

import org.apache.axis2.jaxws.lifecycle.LifecycleException;

public class EndpointLifecycleException extends LifecycleException {

    public EndpointLifecycleException() {
        super();
    }

    /** @param message  */
    public EndpointLifecycleException(String message) {
        super(message);
    }

    /**
     * @param message
     * @param cause
     */
    public EndpointLifecycleException(String message, Throwable cause) {
        super(message, cause);
    }

    /** @param cause  */
    public EndpointLifecycleException(Throwable cause) {
        super(cause);
    }

}


text:
package org.broadinstitute.dsde.workbench.sam.api

import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.broadinstitute.dsde.workbench.sam.TestSupport
import org.broadinstitute.dsde.workbench.sam.model.SamUser
import org.broadinstitute.dsde.workbench.sam.util.SamRequestContext
import org.mockito.ArgumentMatchers.any
import org.mockito.internal.verification.AtLeast
import org.mockito.Mockito
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.yaml.snakeyaml.Yaml

import scala.jdk.CollectionConverters._

/** These tests verify that the apis published in swagger/api-docs.yaml call the correct SamUserDirectives.
  */
class RouteSecuritySpec extends AnyFlatSpec with Matchers with ScalatestRouteTest with TestSupport {
  lazy val routesFromApiYml: Iterable[PathAndMethod] = {
    val apiDocsPath = "swagger/api-docs.yaml"
    val apiDocsStream = getClass.getClassLoader.getResourceAsStream(apiDocsPath)
    val apiDocsYaml = new Yaml().load[java.util.Map[String, Any]](apiDocsStream).asScala
    apiDocsStream.close()

    for {
      pathEntry <- apiDocsYaml("paths").asInstanceOf[java.util.Map[String, Any]].asScala
      path = pathEntry._1
      methodEntry <- pathEntry._2.asInstanceOf[java.util.Map[String, Any]].asScala
      method = methodEntry._1
    } yield PathAndMethod(path, method)
  }

  for (PathAndMethod(path, method) <- routesFromApiYml if path.startsWith("/api"))
    s"$method $path" should "call withActiveUser" in {
      val samRoutes = Mockito.spy(TestSamRoutes(Map.empty))

      createRequest(path, method) ~> samRoutes.route ~> check {
        withClue(s"$method $path did not call withActiveUser") {
          Mockito.verify(samRoutes, new AtLeast(1)).withActiveUser(any[SamRequestContext])
        }
      }
    }

  for (PathAndMethod(path, method) <- routesFromApiYml if path.startsWith("/register"))
    s"$method $path" should "call withUserAllowInactive" in {
      val samRoutes = Mockito.spy(TestSamRoutes(Map.empty))

      createRequest(path, method) ~> samRoutes.route ~> check {
        withClue(s"$method $path did not call withUserAllowInactive") {
          Mockito.verify(samRoutes, new AtLeast(1)).withUserAllowInactive(any[SamRequestContext])
        }
      }
    }

  for (PathAndMethod(path, method) <- routesFromApiYml if path.startsWith("/api/admin/user") || path.startsWith("/api/admin/v1/user"))
    s"$method $path" should "call withWorkbenchAdmin" in {
      val samRoutes = Mockito.spy(TestSamRoutes(Map.empty))

      createRequest(path, method) ~> samRoutes.route ~> check {
        withClue(s"$method $path did not call withWorkbenchAdmin") {
          Mockito.verify(samRoutes, new AtLeast(1)).asWorkbenchAdmin(any[SamUser])
        }
      }
    }

  for (PathAndMethod(path, method) <- routesFromApiYml if path.startsWith("/api/admin/v1/resourceTypes"))
    s"$method $path" should "call asSamSuperAdmin" in {
      val samRoutes = Mockito.spy(TestSamRoutes(Map.empty))

      createRequest(path, method) ~> samRoutes.route ~> check {
        withClue(s"$method $path did not call withWorkbenchAdmin") {
          Mockito.verify(samRoutes, new AtLeast(1)).asSamSuperAdmin(any[SamUser])
        }
      }
    }

  private def createRequest(path: String, method: String) =
    method.toLowerCase match {
      case "get" => Get(path)
      case "put" => Put(path)
      case "post" => Post(path)
      case "delete" => Delete(path)
    }
}

case class PathAndMethod(path: String, method: String)


text:
using System.Collections.Generic;

using DotNetNuke.Modules.Announcements.Components.Business;

namespace DotNetNuke.Modules.Announcements.Components.Template
{
    public interface ITemplate
    {
        void LoadTemplate();

        void UpdateTemplate();

        string RenderTemplate(IEnumerable<AnnouncementInfo> announcements, bool editEnabled);
    }

}


text:
package com.sequenceiq.datalake.flow.datalake.cmsync;

import com.sequenceiq.datalake.flow.FillInMemoryStateStoreRestartAction;
import com.sequenceiq.flow.core.FlowState;
import com.sequenceiq.flow.core.RestartAction;
import com.sequenceiq.flow.core.restart.DefaultRestartAction;

public enum SdxCmSyncState implements FlowState {
    INIT_STATE,
    CORE_CM_SYNC_STATE,
    CORE_CM_SYNC_IN_PROGRESS_STATE,
    SDX_CDH_VERSION_UPDATE_STATE,
    SDX_CM_SYNC_FINISHED_STATE,
    SDX_CM_SYNC_FAILED_STATE,
    FINAL_STATE;

    private Class<? extends DefaultRestartAction> restartAction = FillInMemoryStateStoreRestartAction.class;

    @Override
    public Class<? extends RestartAction> restartAction() {
        return restartAction;
    }
}


text:
/* Include this file in your html if you are using the CSP mode. */

.uib-datepicker .uib-title {
  width: 100%;
}

.uib-day button, .uib-month button, .uib-year button {
  min-width: 100%;
}

.uib-datepicker-popup.dropdown-menu {
  display: block;
}

.uib-button-bar {
  padding: 10px 9px 2px;
}

.ng-animate.item:not(.left):not(.right) {
  -webkit-transition: 0s ease-in-out left;
  transition: 0s ease-in-out left
}
.uib-time input {
  width: 50px;
}

[uib-typeahead-popup].dropdown-menu {
  display: block;
}


text:
/*
 *
 *  Somado (System Optymalizacji Małych Dostaw)
 *  Optymalizacja dostaw towarów, dane OSM, problem VRP
 *
 *  Autor: Maciej Kawecki 2016 (praca inż. EE PW)
 *
 */

package datamodel;

import java.sql.ResultSet;
import java.sql.SQLException;
import somado.IConf;
import somado.Lang;

/**
 *
 * Szablon obiektu reprezentującego model pojazdu
 *
 * @author Maciej Kawecki
 * @version 1.0
 *
 */
public class VehicleModel implements IDataEditable {

   /** Klucz w tabeli BD */
   private Integer id;
   /** Nazwa modelu pojazdu */
   private String name;
   /** Ładowność [t] */
   private double maximumLoad;
   /** Średnie zużycie paliwa [l/100km] */
   private double avgFuelConsumption;

   /**
    * Konstruktor
    * @param id Id rekordu w bazie danych
    * @param name Nazwa
    * @param maximumLoad Ładowność [t]
    * @param avgFuelConsumption Średnie zużycie paliwa [l/100km]
    */
   public VehicleModel(int id, String name, double maximumLoad, double avgFuelConsumption) {

     this.id = id;
     this.name = name;
     this.maximumLoad = maximumLoad;
     this.avgFuelConsumption = avgFuelConsumption;

   }

   /**
    * Konstruktor obiektu modelu pojazdu (z BD)
    * @param rs Zestaw wyników zapytania do BD
    * @param prefix Prefix pól dot. modelu pojazdu w zapytaniu
    * @throws SQLException Błąd SQL
    */
   public VehicleModel(ResultSet rs, String prefix) throws SQLException {

     this.id = rs.getInt(prefix + "id");
     this.name = rs.getString(prefix + "name");
     this.maximumLoad = rs.getDouble(prefix + "maximum_load");
     this.avgFuelConsumption = rs.getDouble(prefix + "avg_fuel_consumption");

   }

   /**
    * Konstruktor obiektu produktu (z BD)
    * @param rs Zestaw wyników zapytania do BD
    * @throws SQLException Błąd SQL
    */
   public VehicleModel(ResultSet rs) throws SQLException {

     this(rs, "");

   }

    /**
     * Konstruktor pustego obiektu (nowego)
     */
    public VehicleModel() {

      this(0, "", IConf.MIN_VEHICLE_MAXLOAD, IConf.MIN_VEHICLE_FUEL_CONSUMPTION);

    }

   @Override
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public double getMaximumLoad() {
        return maximumLoad;
    }

    public void setMaximumLoad(double maximumLoad) {
        this.maximumLoad = maximumLoad;
    }

    public double getAvgFuelConsumption() {
        return avgFuelConsumption;
    }

    public void setAvgFuelConsumption(double avgFuelConsumption) {
        this.avgFuelConsumption = avgFuelConsumption;
    }

   @Override
   public String toString() {

     return name;

   }

   @Override
   public void verify() throws Exception {

      if (name.isEmpty())  throw new Exception(Lang.get("Data.VehicleModel.MissingName"));
      if (maximumLoad<IConf.MIN_VEHICLE_MAXLOAD || maximumLoad>IConf.MAX_VEHICLE_MAXLOAD)
          throw new Exception(Lang.get("Data.VehicleModel.WrongCapacity"));

   }

}


text:
import { NgModule }     from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { routedComponents, routing } from './hero.routing';

@NgModule({
  imports:      [ SharedModule, routing ],
  declarations: [ routedComponents ]
})
export class HeroModule { }


text:
@interface MyTableViewController () <PTTextViewCellDelegate>

@property (nonatomic, strong) NSString *text;
@property (nonatomic, strong) NSAttributedString *attributedText;

@end

@implementation MyTableViewController

//===============================================
#pragma mark -
#pragma mark Initialization
//===============================================

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {

    _text = @"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n1\n2\n3\n4\n5\n6\n7";
    _attributedText = [[NSAttributedString alloc] initWithString:self.text attributes:@{NSFontAttributeName: [UIFont fontWithName:@"AvenirNext-Bold" size:20.0]}];
}

//===============================================
#pragma mark -
#pragma mark View
//===============================================

- (void)viewDidLoad
{
    [super viewDidLoad];

//    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

    [self.tableView registerClass:[PTTextViewCell class] forCellReuseIdentifier:PTTextViewCellReuseIdentifier];

//    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PTTextViewCell class]) bundle:nil] forCellReuseIdentifier:PTTextViewCellReuseIdentifier];

    UIBarButtonItem *keyboardDismissButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done)];
    self.navigationItem.rightBarButtonItem = keyboardDismissButton;
}

- (void)done {
    [self.view endEditing:YES];
}

//===============================================
#pragma mark -
#pragma mark UITableViewDataSource
//===============================================

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    PTTextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PTTextViewCellReuseIdentifier forIndexPath:indexPath];

    cell.delegate = self;

//    cell.textView.text = self.text;

    cell.textView.attributedText = self.attributedText;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

//    return [PTTextViewCell requiredHeightForString:self.text cellWidth:CGRectGetWidth(tableView.bounds)];

    return [PTTextViewCell requiredHeightForAttributedString:self.attributedText cellWidth:CGRectGetWidth(tableView.bounds)];
}

//===============================================
#pragma mark -
#pragma mark PTTextViewCellDelegate
//===============================================

- (void)textViewCellDidChange:(PTTextViewCell *)textViewCell {

//    self.text = textViewCell.textView.text;

    self.attributedText = textViewCell.textView.attributedText;

    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

@end


text:
package io.nxnet.commons.mvnutils.pom.resolver.impl;

import java.util.Arrays;
import java.util.List;

import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.repository.RepositoryPolicy;

import io.nxnet.commons.mvnutils.pom.resolver.ProxyDefinition;
import io.nxnet.commons.mvnutils.pom.resolver.ProxyDefinitionFactory;
import io.nxnet.commons.mvnutils.pom.resolver.RemoteRepositoryFactory;
import io.nxnet.commons.mvnutils.pom.resolver.ServiceRegistry;

public class CentralRemoteRepositoryFactory implements RemoteRepositoryFactory
{
    private ProxyDefinitionFactory proxyDefinitionFactory;

    public CentralRemoteRepositoryFactory()
    {
        this.proxyDefinitionFactory = new LocalhostProxyDefinitionFactory();
    }

    public CentralRemoteRepositoryFactory(ProxyDefinitionFactory proxyDefinitionFactory)
    {
        this.proxyDefinitionFactory = proxyDefinitionFactory;
    }

    public void init(ServiceRegistry serviceLocator)
    {
        this.proxyDefinitionFactory = serviceLocator.getService(ProxyDefinitionFactory.class);
    }

    @Override
    public List<RemoteRepository> getRemoteRepositories()
    {
        // Set repo location
        RemoteRepository.Builder repositoryBuilder = new RemoteRepository.Builder(
                "central", "default", "http://central.maven.org/maven2/");
        repositoryBuilder.setSnapshotPolicy(new RepositoryPolicy(false, RepositoryPolicy.UPDATE_POLICY_NEVER,
                RepositoryPolicy.CHECKSUM_POLICY_WARN));

        // Set repo proxy
        ProxyDefinition proxyDefinition = this.proxyDefinitionFactory.getProxyDefinition();
        if (proxyDefinition != null)
        {
            repositoryBuilder.setProxy(proxyDefinition.getProxy());
        }

        return Arrays.asList(repositoryBuilder.build());
    }

    /**
     * @return the proxyDefinitionFactory
     */
    public ProxyDefinitionFactory getProxyDefinitionFactory()
    {
        return proxyDefinitionFactory;
    }

    /**
     * @param proxyDefinitionFactory the proxyDefinitionFactory to set
     */
    public void setProxyDefinitionFactory(ProxyDefinitionFactory proxyDefinitionFactory)
    {
        this.proxyDefinitionFactory = proxyDefinitionFactory;
    }

}


text:
/**
 * Dynamic Jquery Logs Table
 */
$( document ).ready(function() {

	$('#hipay_logs').dataTable( {
		"bJQueryUI": true,
		"aaSorting": [[ 0, "desc" ]],
		"sPaginationType": "full_numbers",
                "oLanguage": {
                   "sEmptyTable":     "No data available in table",
                    "sInfo":           "Showing _START_ to _END_ of _TOTAL_ entries",
                    "sInfoEmpty":      "Showing 0 to 0 of 0 entries",
                    "sInfoFiltered":   "(filtered from _MAX_ total entries)",
                    "sInfoPostFix":    "",
                    "sInfoThousands":  ",",
                    "sLengthMenu":     "Show _MENU_ entries",
                    "sLoadingRecords": "Loading...",
                    "sProcessing":     "Processing...",
                    "sSearch":         "Search:",
                    "sZeroRecords":    "No matching records found",
                    "oPaginate": {
                        "sFirst":    "First",
                        "sLast":     "Last",
                        "sNext":     "Next",
                        "sPrevious": "Previous"
                    },
                    "oAria": {
                        "sSortAscending":  ": activate to sort column ascending",
                        "sSortDescending": ": activate to sort column descending"
                    }
                }
	});

});


text:
package com.facebook.buck.dotnet;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Either;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Ordering;

import java.nio.file.Path;
import java.util.Map;

public class CSharpLibrary extends AbstractBuildRule {

  @AddToRuleKey(stringify = true)
  private final Path output;
  @AddToRuleKey
  private final ImmutableSortedSet<SourcePath> srcs;
  @AddToRuleKey
  private final ImmutableList<Either<BuildRule, String>> refs;
  @AddToRuleKey
  private final ImmutableMap<String, SourcePath> resources;
  @AddToRuleKey
  private final FrameworkVersion version;

  protected CSharpLibrary(
      BuildRuleParams params,
      SourcePathResolver resolver,
      String dllName,
      ImmutableSortedSet<SourcePath> srcs,
      ImmutableList<Either<BuildRule, String>> refs,
      ImmutableMap<String, SourcePath> resources,
      FrameworkVersion version) {
    super(params, resolver);

    Preconditions.checkArgument(dllName.endsWith(".dll"));

    this.srcs = srcs;
    this.refs = refs;
    this.resources = resources;
    this.version = version;

    this.output = BuildTargets.getGenPath(
        params.getBuildTarget(),
        String.format("%%s/%s", dllName));
  }

  @Override
  public ImmutableList<Step> getBuildSteps(
      BuildContext context,
      BuildableContext buildableContext) {
    ProjectFilesystem filesystem = getProjectFilesystem();

    ImmutableSortedSet<Path> sourceFiles = FluentIterable.from(srcs)
        .transform(getResolver().getAbsolutePathFunction())
        .toSortedSet(Ordering.natural());

    ImmutableListMultimap.Builder<Path, String> resolvedResources = ImmutableListMultimap.builder();
    for (Map.Entry<String, SourcePath> resource : resources.entrySet()) {
      resolvedResources.put(getResolver().getAbsolutePath(resource.getValue()), resource.getKey());
    }

    ImmutableList<Either<Path, String>> references = resolveReferences(refs);

    ImmutableList.Builder<Step> steps = ImmutableList.builder();

    steps.add(new MakeCleanDirectoryStep(filesystem, output.getParent()));
    steps.add(
        new CSharpLibraryCompile(
            filesystem.resolve(output),
            sourceFiles,
            references,
            resolvedResources.build(),
            version));

    return steps.build();
  }

  private ImmutableList<Either<Path, String>> resolveReferences(
      ImmutableList<Either<BuildRule, String>> refs) {
    ImmutableList.Builder<Either<Path, String>> resolved = ImmutableList.builder();

    for (Either<BuildRule, String> ref : refs) {
      if (ref.isLeft()) {
        // TODO(simons): Do this in the constructor? Or the Description?
        BuildRule rule = ref.getLeft();
        Preconditions.checkArgument(
            rule instanceof CSharpLibrary ||
            rule instanceof PrebuiltDotNetLibrary);

        Path outputPath = Preconditions.checkNotNull(rule.getPathToOutput());
        resolved.add(Either.<Path, String>ofLeft(rule.getProjectFilesystem().resolve(outputPath)));
      } else {
        resolved.add(Either.<Path, String>ofRight(ref.getRight()));
      }
    }

    return resolved.build();
  }

  @Override
  public Path getPathToOutput() {
    return output;
  }
}


text:
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Copyright: (c) 2014, EURL Tweag
-- License: BSD3
--
-- Runner for given CH test suite. The test suite to run is given by the
-- expansion of the @TEST_SUITE_MODULE@ macro.

module Main where

import TEST_SUITE_MODULE (tests)

import Network.Transport.Test (TestTransport(..))
import Network.Transport.ZMQ
  ( createTransportExposeInternals
  , defaultZMQParameters
  , breakConnection
  )
import Test.Framework (defaultMain)

main :: IO ()
main = do
    (zmqt, transport) <- createTransportExposeInternals defaultZMQParameters "127.0.0.1"
    defaultMain =<< tests TestTransport
      { testTransport = transport
      , testBreakConnection = breakConnection zmqt
      }


text:
""" Website UX for user authentication.

    Handle user login flow via Google Sign-in.

    Requests handled:

        /login - directs user to Google sign-in page.
        /callback - successful login to Google sign-in page causes a redirect
            here. This handler fetches user information and establishes a session
            with that information.
        /logout - deletes the user login session and revokes the long-lived
            refresh token.

    For more information, see https://developers.google.com/identity/protocols/oauth2/web-server
    and related pages for background information on this process.
"""

from flask import (
    Blueprint,
    current_app,
    make_response,
    redirect,
    render_template,
    request,
    session,
)

import requests
from google.oauth2 import id_token
from google.auth.transport import requests as reqs
from middleware.logging import log
from middleware import session

auth_bp = Blueprint("auth", __name__, template_folder="templates")

@auth_bp.route("/login", methods=["GET"])
def login_get():
    """login_get

    Handles requests made to the path /login. This may occur due to a user
    following a link, or other website pages redirecting here.

    The request may include a query parameter called return_to, which will lead
    to the user being directed to that path following a successful login. This
    path is relative to the application's root URL and special characters must
    be url-encoded.

    Example:

        GET /login?return_to=view_campaign%2F3x87f3
    """

    return_to = request.args.get("return_to", "/")

    # Link to redirect to Google auth service, including required query parameters.
    sign_in_url = "https://accounts.google.com/o/oauth2/v2/auth?"

    # Client apps and their callbacks must be registered and supplied here
    sign_in_url += "redirect_uri={}&".format(current_app.config["REDIRECT_URI"])
    sign_in_url += "client_id={}&".format(current_app.config["CLIENT_ID"])

    # Asking for user email and any previously granted scopes
    sign_in_url += "scope=openid%20email&"
    sign_in_url += "include_granted_scopes=true&"

    # The next two parameters are essential to get a refresh token
    sign_in_url += "prompt=consent&"
    sign_in_url += "access_type=offline&"

    # Asking for a code that can then be exchanged for user information
    sign_in_url += "response_type=code&"

    # Remember this info and echo it back to me so I'll know what to do next
    sign_in_url += "state={}&".format(return_to)

    return redirect(sign_in_url)

@auth_bp.route("/callback", methods=["GET"])
def handle_callback():
    """handle_callback

    A successful login using Google sign-in will end with the user's browser
    being redirected to this path, providing query parameters can can be used
    to retrieve user information.
    """
    args = request.args.to_dict()

    # After handling login info and session creation, where should the user go?
    redirect_path = args.get("state", "/")

    code = args.get("code")
    if code is None:
        log("No authorization code provided to callback.", severity="CRITICAL")
        return render_template("errors/403.html"), 403

    # Exchange the code for tokens
    r = requests.post(
        "https://oauth2.googleapis.com/token",
        data={
            "code": code,
            "client_id": current_app.config["CLIENT_ID"],
            "client_secret": current_app.config["CLIENT_SECRET"],
            "redirect_uri": current_app.config["REDIRECT_URI"],
            "grant_type": "authorization_code",
        },
    )

    try:
        resp = r.json()
    except Exception as e:
        log(f"Request has bad OAuth2 id token: {e}", severity="CRITICAL")
        return render_template("errors/403.html"), 403

    token = resp.get("id_token")
    refresh_token = resp.get("refresh_token")

    try:
        info = id_token.verify_oauth2_token(token, reqs.Request())
        if "email" not in info:
            log(
                f"Decoded OAuth2 id token is missing email: {info}", severity="CRITICAL"
            )
            return render_template("errors/403.html"), 403
    except Exception as e:
        log(f"Request has bad OAuth2 id token: {e}", severity="CRITICAL")
        return render_template("errors/403.html"), 403

    session_id = session.create(
        {
            "id_token": token,
            "refresh_token": refresh_token,
            "email": info["email"],
            "expiration": info["exp"],
        }
    )

    if session_id is None:
        log(f"Could not create session", severity="CRITICAL")
        return render_template("errors/403.html"), 403
    else:
        response = redirect(redirect_path)
        response.set_cookie("session_id", value=session_id, secure=True, httponly=True)
        return response

@auth_bp.route("/logout", methods=["GET"])
def logout():
    """logout

    User is logged out.

    Three actions are taken:
        - refresh token is revoked
        - cookie "session_id" is deleted
        - stored session data for "session_id" is deleted
    """

    session_id = request.cookies.get("session_id")
    if session_id is None:
        # Nothing to do if the user doesn't have a session. Send them home.
        log("Logout request from user without a session cookie", severity="INFO")
        return redirect("/")

    session_data = session.read(session_id)
    if session_data is None:
        # This is bad. User has a session cookie, but there's no corresponding
        # session data. Log it and send the user back home.
        log("Logout request but session data does not exist", severity="CRITICAL")
        return redirect("/")

    refresh_token = session_data.get("refresh_token", "")

    # Best effort to revoke the token
    response = requests.post(
        f"https://oauth2.googleapis.com/revoke?token={refresh_token}", data={}
    )
    if response.status_code >= 400:
        log(
            f"Failed to revoke refresh token on logging out. Message is '{response.text}'",
            severity="WARNING",
        )

    # Delete the session data
    session.delete(session_id)

    # Wipe out the session cookie
    response = make_response(render_template("auth/logout.html"), 200)
    response.delete_cookie("session_id")

    return response


text:
<!DOCTYPE html>

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

    <title>MDInsider ♥ Open Source / Attend Our First-Ever Scala Hacker Hours Meetup on Aug. 7</title>

    <meta name="author" content="MDInsider, Inc.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="/assets/themes//img/favicon.ico">
    <link href="/atom.xml" type="application/atom+xml" rel="alternate" title="Sitewide ATOM Feed">
    <link href="/rss.xml" type="application/rss+xml" rel="alternate" title="Sitewide RSS Feed">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/assets/themes//css/github-light.css">
    <link rel="stylesheet/less" href="/assets/themes//css/style.less">

    Join MD Insider Tech
    MDInsider.com

            Categories

              <input type="search" placeholder="Search …" title="Search for:" />

            <menu id="categories-menu">

              <menuitem>
                AWS
              </menuitem>

              <menuitem>
                Leadership
              </menuitem>

              <menuitem>
                agile
              </menuitem>

              <menuitem>
                analytics
              </menuitem>

              <menuitem>
                aws
              </menuitem>

              <menuitem>
                blog
              </menuitem>

              <menuitem>
                conferences
              </menuitem>

              <menuitem>
                culture
              </menuitem>

              <menuitem>
                deployment
              </menuitem>

              <menuitem>
                front-end
              </menuitem>

              <menuitem>
                mobile
              </menuitem>

              <menuitem>
                scala
              </menuitem>

              <menuitem>
                swift
              </menuitem>

              <menuitem>
                tech
              </menuitem>

              <menuitem>
                tvOS
              </menuitem>

            </menu>
            <menu id="search-results">
            </menu>

Tech Blog

Attend Our First-Ever Scala Hacker Hours Meetup on Aug. 7

    <time>17 July 2013</time>

New to Scala? Working on a Scala project and need some guidance? Curious about the Typesafe platform, and interested in exploring it? Then grab your laptop and head on over to our 2 Park Ave. office in Manhattan on Wednesday, August 7 for our first-ever Scala Hacker Hours NYC meetup. The meetup begins at 6:30 PM and ends at 8:30 PM; light refreshments will be provided.

What’s a “hacker hours,” you ask? In his brand-new, open-source Hacker Hours DIY Guide, NYC developer and experienced hacker-hour host Aidan Feldman describes them as “free office hours for programming help; open to anyone, regardless of age or skill level; not a class, and not a lecture.” For our kick-off Scala session, several Gilt engineers will be available to answer your Scala-centric questions and point you in the right direction.

If you can’t make it on August 7, fret not: We’ll be hosting Scala Hacker Hours every other week. Join the meetup group to make sure you receive our announcements. Hope to see you on August 7!

    scala 11

    typesafe 2

    scala hacker hours nyc 1

    aidan feldman 1

    gilttech 332

    Join MD Insider Tech
    MDInsider.com

          © 2015 MDInsider, Inc. • Archives


text:
<?xml version="1.0" encoding="UTF-8"?>

		<item value="298" key="DIALOG_WIDTH"/>
		<item value="378" key="DIALOG_HEIGHT"/>
		<item value="1|Lucida Grande|13.0|0|COCOA|1|LucidaGrande" key="DIALOG_FONT_NAME"/>

		<item value="800" key="DIALOG_WIDTH"/>
		<item value=", com.qnx.tools.ide.bbt.debug.ui.BBTLaunch, " key="org.eclipse.debug.ui.EXPANDED_NODES"/>
		<item value="640" key="DIALOG_HEIGHT"/>
		<item value="237" key="org.eclipse.debug.ui.DIALOG_SASH_WEIGHTS_1"/>
		<item value="1|Lucida Grande|13.0|0|COCOA|1|LucidaGrande" key="DIALOG_FONT_NAME"/>
		<item value="762" key="org.eclipse.debug.ui.DIALOG_SASH_WEIGHTS_2"/>

		<item value="312" key="DIALOG_WIDTH"/>
		<item value="430" key="DIALOG_HEIGHT"/>
		<item value="1|Lucida Grande|13.0|0|COCOA|1|LucidaGrande" key="DIALOG_FONT_NAME"/>


text:
layout: page
title: Archive
---

{% for post in site.posts %}
{{ post.date | date_to_string }}       [ {{ post.title }} ]({{ post.url }})
{% endfor %}


text:
package joshie.harvest.player.command;

import joshie.harvest.api.knowledge.Note;
import joshie.harvest.core.HFTrackers;
import joshie.harvest.core.commands.CommandManager.CommandLevel;
import joshie.harvest.core.commands.HFCommand;
import joshie.harvest.player.PlayerTrackerServer;
import joshie.harvest.player.tracking.TrackingServer;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;

import javax.annotation.Nonnull;

@HFCommand
@SuppressWarnings("unused")
public class HFCommandNote extends CommandBase {
    @Override
    @Nonnull
    public String getName() {
        return "note";
    }

    @Override
    @Nonnull
    public String getUsage(@Nonnull ICommandSender sender) {
        return "/hf note [player] <value|all|clear>";
    }

    @Override
    public int getRequiredPermissionLevel() {
        return CommandLevel.OP_AFFECT_GAMEPLAY.ordinal();
    }

    @Override
    public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, @Nonnull String[] parameters) throws CommandException {
        if (parameters.length == 1 || parameters.length == 2) {
            EntityPlayerMP player = parameters.length == 1? CommandBase.getCommandSenderAsPlayer(sender) : CommandBase.getPlayer(server, sender, parameters[0]);
            TrackingServer tracking = HFTrackers.<PlayerTrackerServer>getPlayerTrackerFromPlayer(player).getTracking();
            String note = parameters[parameters.length - 1];
            switch (note) {
                case "all":
                    Note.REGISTRY.values().forEach(tracking::learnNote);
                    tracking.sync(player);
                    break;
                case "clear":
                    tracking.learnNote(null);
                    tracking.sync(player);
                    break;
                default:
                    if (!note.contains(":")) note = "harvestfestival:" + note;
                    tracking.learnNote(Note.REGISTRY.get(new ResourceLocation(note)));
                    tracking.sync(player);
                    break;
            }
        } else throw new WrongUsageException(getUsage(sender));
    }
}