text:
package de.grafelhaft.winespray.app.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import de.grafelhaft.grafellib.adapter.OnRecyclerViewItemClickListener;
import de.grafelhaft.grafellib.adapter.OnRecyclerViewItemLongClickListener;
import de.grafelhaft.grafellib.adapter.OnRecyclerViewItemSelectedListener;
import de.grafelhaft.grafellib.fragment.BaseFragment;
import de.grafelhaft.winespray.app.R;
import de.grafelhaft.winespray.app.adapter.realm.NoteRealmRecyclerViewAdapter;
import de.grafelhaft.winespray.app.dialog.DeleteRealmObjectDialog;
import de.grafelhaft.winespray.app.dialog.MapDialog;
import de.grafelhaft.winespray.app.dialog.NoteDialog;
import de.grafelhaft.winespray.app.dialog.OnDialogCallbackListener;
import de.grafelhaft.winespray.model.Note;
import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by Markus on 14.09.2016.
 */
public class NoteListFragment extends BaseFragment implements OnRecyclerViewItemClickListener, OnRecyclerViewItemSelectedListener, OnRecyclerViewItemLongClickListener, View.OnClickListener {

    private RecyclerView _recyclerView;
    private NoteRealmRecyclerViewAdapter _adapter;

    @Override
    protected int inflateLayoutRes() {
        return R.layout.fragment_note_list;
    }

    @Override
    protected void init(Bundle bundle) {
        setHasOptionsMenu(true);

        _adapter = new NoteRealmRecyclerViewAdapter(getActivity(), Realm.getDefaultInstance().where(Note.class).findAllAsync(), true);
        _adapter.setOnRecyclerViewItemClickListener(this);
        _adapter.addOnRecyclerViewItemSelectedListener(this);
        _adapter.setOnRecyclerViewItemLongClickListener(this);

        _recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        _recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        _recyclerView.setHasFixedSize(true);
        _recyclerView.setAdapter(_adapter);
        _recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .drawable(R.drawable.shape_divider_horizontal)
                .margin(getResources().getDimensionPixelSize(R.dimen.activity_vertical_margin), getResources().getDimensionPixelSize(R.dimen.activity_vertical_margin))
                .build());

        findViewById(R.id.fab).setOnClickListener(this);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_note_list, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_add) {
            NoteDialog dialog = new NoteDialog();
            dialog.show(getActivity().getSupportFragmentManager(), "ADD_DIALOG");
        }
        if (item.getItemId() == R.id.action_clear) {
            Realm.getDefaultInstance().executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    Realm.getDefaultInstance().where(Note.class).equalTo("isChecked", true).findAll().deleteAllFromRealm();
                }
            });
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClicked(View view, int i) {
        final Note note = _adapter.getData().get(i);

        NoteDialog dialog = NoteDialog.create(note);
        dialog.setOnDialogCallbackListener(new OnDialogCallbackListener() {
            @Override
            public void onCallback(boolean positive, boolean negative, boolean neutral) {
                if (neutral) {
                    MapDialog mapDialog = MapDialog.create(note.getLocation());
                    mapDialog.show(getActivity().getSupportFragmentManager(), "MAP_DIALOG");
                }
            }
        });
        dialog.show(getActivity().getSupportFragmentManager(), "NOTE_DIALOG");
    }

    @Override
    public void onItemSelected(int position, final boolean selected) {
        final Note note = _adapter.getData().get(position);
        Realm.getDefaultInstance().executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                note.setChecked(selected);
            }
        });
    }

    @Override
    public boolean onItemLongClicked(View view, int i) {
        Note note = _adapter.getData().get(i);
        DeleteRealmObjectDialog dialog = DeleteRealmObjectDialog.create(note);
        dialog.show(getActivity().getSupportFragmentManager(), "DELETE_DIALOG");
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab:
                NoteDialog dialog = new NoteDialog();
                dialog.show(getActivity().getSupportFragmentManager(), "ADD_DIALOG");
                break;
        }
    }
}


text:
package org.mockito.internal.runners.util;

import org.junit.Test;

import java.lang.reflect.Method;

public class TestMethodsFinder {

    private TestMethodsFinder() {}

    public static boolean hasTestMethods(Class<?> klass) {
        Method[] methods = klass.getMethods();
        for(Method m:methods) {
            if (m.isAnnotationPresent(Test.class)) {
                return true;
            }
        }
        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Enum. pl. (Kjbenhavn) 2: 209 (1803)

#### Original name
Trichia elongata Schumach.

### Remarks
null


text:
package org.apache.deltaspike.test.jpa.api.entitymanager;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.spi.PersistenceProviderResolverHolder;

import org.apache.deltaspike.jpa.spi.entitymanager.PersistenceConfigurationProvider;
import org.apache.deltaspike.test.category.SeCategory;
import org.apache.deltaspike.test.jpa.api.shared.TestEntityManager;
import org.apache.deltaspike.test.util.ArchiveUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;

import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
@Category(SeCategory.class)
public class EntityManagerFactoryProducerTest
{

    @Deployment
    public static WebArchive deploy()
    {
        // set the dummy PersistenceProviderResolver which creates our DummyEntityManagerFactory
        PersistenceProviderResolverHolder.setPersistenceProviderResolver(new TestPersistenceProviderResolver());

        JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, "unitDefinitionTest.jar")
                .addPackage(ArchiveUtils.SHARED_PACKAGE)
                .addPackage(EntityManagerFactoryProducerTest.class.getPackage().getName())
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsResource(new StringAsset(TestPersistenceProviderResolver.class.getName()),
                        "META-INF/services/javax.persistence.spi.PersistenceProviderResolver");

        return ShrinkWrap.create(WebArchive.class)
                .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndJpaArchive())
                .addAsLibraries(testJar)
                .addAsWebInfResource(ArchiveUtils.getBeansXml(), "beans.xml");
    }

    @Inject
    @SampleDb
    private EntityManager entityManager;

    private @Inject PersistenceConfigurationProvider persistenceConfigurationProvider;

    @Test
    public void testUnitDefinitionQualifier() throws Exception
    {
        Assert.assertNotNull(entityManager);
        Assert.assertNotNull(entityManager.getDelegate());

        Assert.assertTrue(entityManager.getDelegate() instanceof TestEntityManager);
        TestEntityManager tem = (TestEntityManager) entityManager.getDelegate();
        Assert.assertEquals("testPersistenceUnit", tem.getUnitName());
    }
}


text:
"""
Test the base Resource class
"""
import unittest
from mock import Mock
from nose.tools import assert_equals
from nose.tools import raises
from twilio.rest.resources import Resource
from twilio.rest.resources import ListResource
from twilio.rest.resources import InstanceResource

base_uri = "https://api.twilio.com/2010-04-01"
account_sid = "AC123"
auth = (account_sid, "token")

def test_resource_init():
    r = Resource(base_uri, auth)
    uri = "{}/{}".format(base_uri, r.name)

    assert_equals(r.base_uri, base_uri)
    assert_equals(r.auth, auth)
    assert_equals(r.uri, uri)

def test_equivalence():
    p = ListResource(base_uri, auth)
    r1 = p.load_instance({"sid": "AC123"})
    r2 = p.load_instance({"sid": "AC123"})
    assert_equals(r1, r2)

class ListResourceTest(unittest.TestCase):

    def setUp(self):
        self.r = ListResource(base_uri, auth)

    def testListResourceInit(self):
        uri = "{}/{}".format(base_uri, self.r.name)
        self.assertEquals(self.r.uri, uri)

    def testKeyValue(self):
        self.assertEquals(self.r.key, self.r.name.lower())

    def testKeyValue(self):
        self.r.key = "Hey"
        self.assertEquals(self.r.key, "Hey")

    def testInstanceLoading(self):
        instance = self.r.load_instance({"sid": "foo"})

        self.assertIsInstance(instance, InstanceResource)
        self.assertEquals(instance.sid, "foo")

class testInstanceResourceInit(unittest.TestCase):

    def setUp(self):
        self.parent = ListResource(base_uri, auth)
        self.r = InstanceResource(self.parent, "123")
        self.uri = "%s/%s" % (self.parent.uri, "123")

    def testInit(self):
        self.assertEquals(self.r.uri, self.uri)

    def testLoad(self):
        self.r.load({"hey": "you"})
        self.assertEquals(self.r.hey, "you")

    def testLoadWithUri(self):
        self.r.load({"hey": "you", "uri": "foobar"})
        self.assertEquals(self.r.hey, "you")
        self.assertEquals(self.r.uri, self.uri)

    def testLoadWithFrom(self):
        self.r.load({"from": "foo"})
        self.assertEquals(self.r.from_, "foo")

    def testLoadSubresources(self):
        m = Mock()
        self.r.subresources = [m]
        self.r.load_subresources()
        m.assert_called_with(self.r.uri, self.r.auth)


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

#include "depfile_parser.h"
#include "util.h"

#include <algorithm>

using namespace std;

DepfileParser::DepfileParser(DepfileParserOptions options)
  : options_(options)
{
}

// A note on backslashes in Makefiles, from reading the docs:
// Backslash-newline is the line continuation character.
// Backslash-# escapes a # (otherwise meaningful as a comment start).
// Backslash-% escapes a % (otherwise meaningful as a special).
// Finally, quoting the GNU manual, "Backslashes that are not in danger
// of quoting '%' characters go unmolested."
// How do you end a line with a backslash?  The netbsd Make docs suggest
// reading the result of a shell command echoing a backslash!
//
// Rather than implement all of above, we follow what GCC/Clang produces:
// Backslashes escape a space or hash sign.
// When a space is preceded by 2N+1 backslashes, it is represents N backslashes
// followed by space.
// When a space is preceded by 2N backslashes, it represents 2N backslashes at
// the end of a filename.
// A hash sign is escaped by a single backslash. All other backslashes remain
// unchanged.
//
// If anyone actually has depfiles that rely on the more complicated
// behavior we can adjust this.
bool DepfileParser::Parse(string* content, string* err) {
  // in: current parser input point.
  // end: end of input.
  // parsing_targets: whether we are parsing targets or dependencies.
  char* in = &(*content)[0];
  char* end = in + content->size();
  bool have_target = false;
  bool parsing_targets = true;
  bool poisoned_input = false;
  while (in < end) {
    bool have_newline = false;
    // out: current output point (typically same as in, but can fall behind
    // as we de-escape backslashes).
    char* out = in;
    // filename: start of the current parsed filename.
    char* filename = out;
    for (;;) {
      // start: beginning of the current parsed span.
      const char* start = in;
      char* yymarker = NULL;
      /*!re2c
      re2c:define:YYCTYPE = "unsigned char";
      re2c:define:YYCURSOR = in;
      re2c:define:YYLIMIT = end;
      re2c:define:YYMARKER = yymarker;

      re2c:yyfill:enable = 0;

      re2c:indent:top = 2;
      re2c:indent:string = "  ";

      nul = "\000";
      newline = '\r'?'\n';

      '\\\\'* '\\ ' {
        // 2N+1 backslashes plus space -> N backslashes plus space.
        int len = (int)(in - start);
        int n = len / 2 - 1;
        if (out < start)
          memset(out, '\\', n);
        out += n;
        *out++ = ' ';
        continue;
      }
      '\\\\'+ ' ' {
        // 2N backslashes plus space -> 2N backslashes, end of filename.
        int len = (int)(in - start);
        if (out < start)
          memset(out, '\\', len - 1);
        out += len - 1;
        break;
      }
      '\\'+ '#' {
        // De-escape hash sign, but preserve other leading backslashes.
        int len = (int)(in - start);
        if (len > 2 && out < start)
          memset(out, '\\', len - 2);
        out += len - 2;
        *out++ = '#';
        continue;
      }
      '\\'+ ':' [\x00\x20\r\n\t] {
        // Backslash followed by : and whitespace.
        // It is therefore normal text and not an escaped colon
        int len = (int)(in - start - 1);
        // Need to shift it over if we're overwriting backslashes.
        if (out < start)
          memmove(out, start, len);
        out += len;
        if (*(in - 1) == '\n')
          have_newline = true;
        break;
      }
      '\\'+ ':' {
        // De-escape colon sign, but preserve other leading backslashes.
        // Regular expression uses lookahead to make sure that no whitespace
        // nor EOF follows. In that case it'd be the : at the end of a target
        int len = (int)(in - start);
        if (len > 2 && out < start)
          memset(out, '\\', len - 2);
        out += len - 2;
        *out++ = ':';
        continue;
      }
      '$$' {
        // De-escape dollar character.
        *out++ = '$';
        continue;
      }
      '\\'+ [^\000\r\n] | [a-zA-Z0-9+,/_:.~()}{%=@\x5B\x5D!\x80-\xFF-]+ {
        // Got a span of plain text.
        int len = (int)(in - start);
        // Need to shift it over if we're overwriting backslashes.
        if (out < start)
          memmove(out, start, len);
        out += len;
        continue;
      }
      nul {
        break;
      }
      '\\' newline {
        // A line continuation ends the current file name.
        break;
      }
      newline {
        // A newline ends the current file name and the current rule.
        have_newline = true;
        break;
      }
      [^] {
        // For any other character (e.g. whitespace), swallow it here,
        // allowing the outer logic to loop around again.
        break;
      }
      */
    }

    int len = (int)(out - filename);
    const bool is_dependency = !parsing_targets;
    if (len > 0 && filename[len - 1] == ':') {
      len--;  // Strip off trailing colon, if any.
      parsing_targets = false;
      have_target = true;
    }

    if (len > 0) {
      StringPiece piece = StringPiece(filename, len);
      // If we've seen this as an input before, skip it.
      std::vector<StringPiece>::iterator pos = std::find(ins_.begin(), ins_.end(), piece);
      if (pos == ins_.end()) {
        if (is_dependency) {
          if (poisoned_input) {
            *err = "inputs may not also have inputs";
            return false;
          }
          // New input.
          ins_.push_back(piece);
        } else {
          // Check for a new output.
          if (std::find(outs_.begin(), outs_.end(), piece) == outs_.end())
            outs_.push_back(piece);
        }
      } else if (!is_dependency) {
        // We've passed an input on the left side; reject new inputs.
        poisoned_input = true;
      }
    }

    if (have_newline) {
      // A newline ends a rule so the next filename will be a new target.
      parsing_targets = true;
      poisoned_input = false;
    }
  }
  if (!have_target) {
    *err = "expected ':' in depfile";
    return false;
  }
  return true;
}


text:
package com.quentindommerc.sentencify.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.google.analytics.tracking.android.EasyTracker;
import com.quentindommerc.sentencify.R;

public class About extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_about);
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	protected void onStart() {
		super.onStart();
		EasyTracker.getInstance(this).activityStart(this);
	}

	@Override
	public void onStop() {
		super.onStop();
		EasyTracker.getInstance(this).activityStop(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.about, menu);
		return true;
	}

	public void twitter(View v) {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("twitter://user?screen_name=kentin_dommerc"));
			startActivity(intent);

		} catch (Exception e) {
			startActivity(new Intent(Intent.ACTION_VIEW,
					Uri.parse("https://twitter.com/#!/kentin_dommerc")));
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		}
		return true;
	}
}


text:
.. This file is part of the OpenDSA eTextbook project. See
.. http://algoviz.org/OpenDSA for more details.
.. Copyright (c) 2012-2013 by the OpenDSA Project Contributors, and
.. distributed under an MIT open source license.

.. avmetadata::
   :author: Cliff Shaffer
   :requires: binary tree terminology; recursion
   :satisfies: binary tree traversal
   :topic: Binary Trees

.. odsalink:: AV/Binary/BinExampCON.css
.. odsalink:: AV/Binary/BTCON.css
.. odsalink:: AV/RecurTutor2/AdvancedRecurTutor.css

Binary Tree Traversals
======================
Types of Traversals
-------------------
Often we wish to process a binary tree by "visiting" each of its
nodes, each time performing a specific action such as printing the
contents of the node.
Any process for visiting all of the nodes in some order is
called a :term:`traversal`.
Any traversal that lists every node in the tree exactly once is
called an :term:`enumeration` of the tree's nodes.
Some applications do not require that the nodes be visited in any
particular order as long as each node is visited precisely once.
For other applications, nodes must be visited in an order that
preserves some relationship.
For example, we might wish to make sure that we visit any given node
*before* we visit its children.
This is called a :term:`preorder traversal`.

.. _BinTravExample:

.. inlineav:: BinExampCON dgm
   :align: center

   A binary tree for traversal examples.

.. topic:: Example

   The preorder enumeration for the tree of
   Figure :num:`Figure #BinTravExample` is
   **A B D C E G F H I**.

   The first node printed is the root.
   Then all nodes of the left subtree are printed (in preorder) before
   any node of the right subtree.

.. inlineav:: preorderCON ss
   :output: show

Alternatively, we might wish to visit each node only
*after* we visit its children (and their subtrees).
For example, this would be necessary if we wish to return all nodes
in the tree to free store.
We would like to delete the children of a node before deleting the
node itself.
But to do that requires that the children's children be deleted
first, and so on.
This is called a :term:`postorder traversal`.

.. topic:: Example

   The postorder enumeration for the tree of
   Figure :num:`Figure #BinTravExample` is
   **D B G E H I F C A**.

.. inlineav:: postorderCON ss
   :output: show

An :term:`inorder traversal` first visits the left child
(including its entire subtree), then visits the node, and finally
visits the right child (including its entire
subtree).
The :ref:`binary search tree <binary search tree> <BST>` makes use of
this traversal to print all nodes in ascending order of value.

.. topic:: Example

   The inorder enumeration for the tree of
   Figure :num:`Figure #BinTravExample` is
   **B D A G E C H F I**.

.. inlineav:: inorderCON ss
   :output: show

Now we will discuss some implementations for the traversals, but we
need to define a node ADT to work with.
Just as a linked list is composed of a collection of link objects, a
tree is composed of a collection of node objects.
Here is an ADT for binary tree nodes, called ``BinNode``.
This class will be used by some of the binary tree structures
presented later.
Member functions are provided that set or return the element value,
return a pointer to the left child,
return a pointer to the right child,
or indicate whether the node is a leaf.

.. codeinclude:: Binary/BinNode
   :tag: BinNode

A traversal routine is naturally written as a recursive
function.
Its input parameter is a pointer to a node which we will call
``rt`` because each node can be viewed as the root of a some
subtree.
The initial call to the traversal function passes in a pointer to the
root node of the tree.
The traversal function visits ``rt`` and its children (if any)
in the desired order.
For example, a preorder traversal specifies that ``rt`` be
visited before its children.
This can easily be implemented as follows.

.. codeinclude:: Binary/Preorder
   :tag: preorder

Function ``preorder`` first checks that the tree is not
empty (if it is, then the traversal is done and ``preorder``
simply returns).
Otherwise, ``preorder`` makes  a call to ``visit``,
which processes the root node (i.e., prints the value or performs
whatever computation as required by the application).
Function ``preorder`` is then called recursively on the left
subtree, which will visit all nodes in that subtree.
Finally, ``preorder`` is called on the right subtree,
visiting all nodes in the right subtree.
Postorder and inorder traversals are similar.
They simply change the order in which the node and its children are
visited, as appropriate.

Here are some exercises to practice the traversals.

.. avembed:: AV/Binary/btTravInorderPRO.html pe

.. avembed:: AV/Binary/btTravPostorderPRO.html pe

.. avembed:: AV/Binary/btTravPreorderPRO.html pe

Writing a Recursive Method to Traverse a Binary Tree
----------------------------------------------------

When writing a recursive method to solve a problem that requires traversing a binary tree,
we want to make sure that we are visiting "exactly" the required nodes (no more and no less).

Recall that for any recursive function you should learn two skills:

 #. Formulate the base case and its action.
 #. Formulate the recursive case and its action.

Formulate the base case and its action
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In binary trees, in many binary tree types the base case is to check if we have an empty tree.
One of the common mistakes some people do is considering that the base case
action will be executed only after the recursive calls are executed.
This is not always the case because you may have your input as an empty tree
from the very beginning and in that case no recursive calls will be executed
before the base case action. Make sure when you write a program that traverse a binary tree
to check in the base case if the root of the binary is null (In that case the given tree is empty).

The action that the base case will execute is dependable on the given problem.
For example, if it is required to count the nodes then the base case action will be returning 0.
While, if it is required to check on the existence of a value or not then the base case action
in this case will return false because the given binary tree is empty.

Formulate the recursive case and its action
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Always remember that you should not worry about the recursion details.
Admit that it will do it correctly. So, when your recursive case action
is to  visit recursively the right and left children this means that every node will do that.
You don't need to worry about making sure that every node will do it.

Some problems requires that you traverse the whole tree, in those
problems you must make sure that your function is working for the left and right sides of the tree.
Some other problems requires only traversing the left or the right side
of the tree. You have to make sure that you visit exactly the nodes that are needed by the problem.

An issue to consider when designing a traversal is how to
define the visitor function that is to be executed on every node.
One approach is simply to write a new version of the traversal for
each such visitor function as needed.
The disadvantage to this is that whatever function does the traversal
must have access to the ``BinNode`` class.
It is probably better design to permit only the tree class to have
access to the ``BinNode`` class.

Another approach is for the tree class to supply a generic traversal
function that takes the visitor as a function parameter.
This is known as the
:term:`visitor design pattern`.
A major constraint on this approach is that the
:term:`signature` for all visitor functions, that is,
their return type and parameters, must be fixed in advance.
Thus, the designer of the generic traversal function must be able to
adequately judge what parameters and return type will likely be needed
by potential visitor functions.

.. odsascript:: AV/Binary/BinExampCON.js
.. odsascript:: AV/Binary/inorderCON.js
.. odsascript:: AV/Binary/preorderCON.js
.. odsascript:: AV/Binary/postorderCON.js


text:
            {{question.title}}

                        {{ 'QUESTION.SHOW.RESOLVED' | translate }}

            <form ng-controller="QuestionController" ng-submit="upVote(question)">

                    <button type="submit" class="btn btn-default">

                    </button>

            </form>

                    {{question.vote}}

            <form ng-controller="QuestionController" ng-submit="downVote(question)">

                    <button type="submit" class="btn btn-default">

                    </button>

            </form>

{{question.text}}

        {{question.user.username}}
        {{question.user.reputation}}

        {{ 'CREATED' | translate }} {{ question.created | date:"dd-MM-yyyy HH:mm:ss" }}

            {{ 'EDITED' | translate }} {{ question.edited | date:"dd-MM-yyyy HH:mm:ss" }}

                    <comment comment="comment"></comment>

        <form ng-controller="CommentController" ng-submit="createComment(comment,null,question.id)">

                <textarea type="text" ng-model="comment.text" class="big-textarea add-comment" rows="10"
                            placeholder="Add a new comment..."></textarea>

                <button type="submit" class="btn btn-success add-comment">

                </button>

        </form>

 {{ 'QUESTION.ANSWERS' | translate }}

                    <answer answer="answer"></answer>

        <form ng-controller="AnswerController" ng-submit="createAnswer(answer,question.id)" autocomplete="off">

                <textarea type=text ng-model="answer.text" class="big-textarea add-answer" rows="10" autocomplete="off"
                            placeholder="Add a new answer..."></textarea>

                <button type="submit" class="btn btn-success add-answer">

                </button>

        </form>

            <button type="submit" ng-click="setResolved(question)" class="btn btn-success">

                {{ 'QUESTION.SHOW.SETASRESOLVED' | translate }}

            </button>


text:
<?php
/**
 * Template Name: Debug
 *
 * @package WordPress
 * @subpackage WP Alderaan
 * @since WP Alderaan 1.0
 *
 * Use this template to test out different queries and stuff from the codex
 * and see how the built in wordpress functions work like get_stylesheet_directory_uri()
 */

	Render::partial('document-head');
	Render::partial('header');
?>

Debugger Template

Output the Constants for example

Scripts Directory= <?= SCRIPTS_DIR; ?>

Styles Directory= <?= STYLESHEET_DIR; ?>

<? Render::partial('footer'); ?>


text:
"""
score.py

THIS FILE SHOULD BE REMOVED ONCE THE DDG SCHEDULER HAS BEEN REWRITTEN.

Created by Shane O'Connor 2012.
Copyright (c) 2012 __UCSF__. All rights reserved.
"""

class ddgScore(object):
	type = None
	version = None

	def __init__(self, data = {}):
		self.data = data

	def getType(self):
		return type

	def getVersion(self):
		return version

	def setData(self, data):
		self.data = data

	def getScores(self):
		return {"type" : self.type, "version" : self.version, "data" : self.data}

class ddgTestScore(ddgScore):
	type = "test"
	version = "0.1"


text:
layout: article
title: "Reading Notes: Streaming Graph Partition Schemes (1)"
categories: blogs
modified: 2016-02-20T15:39:59-06:00
image:
  feature: "GP480_250.jpg"
  teaser: "GP480_250.jpg"
  thumb: "GP480_250.jpg"
tags: [Graph Partitioning]
comments: true
ads: false
date: 2016-02-20T15:39:59-06:00
---

Recently, I'm doing research on Graph Partitioning for HPC system. Since usually the HPC system features multiple distributed computing nodes, while carrying out graph related computation on such platform, it is obvious to think about the data distribution problem which naturally can be transformed into graph partitioning problem.

{% include toc.html %}

## Intro and Background

When talking about graph computing problem, the first thing to know is the type of computatoinal operation. There are two different types of operation, OLTP and OLAP. While OLTP focuses on fast transactional operations like traditional CRUD operations against vertices and edges, the OLAP operations focus more on the complex analytical operations, such as graph eccentricity, community structure, centralality measure, isomorphism, etc. Although OLAP seems to be fancier, many of the subroutine of OLAP operations consists of multiple OLTP operations. Especially when it comes to dynamic graph which changes all the time such as social graph, e.g. Facebook or Twitter, the speed to accomplish data processing really matters. Thus, having a streaming graph partiioning scheme becomes really important.

## Four Different Streaming Graph Partitioning Schemes

So far, I've been looking at some different papers talking about streaming graph partitioning approaches.

### Streaming Graph Partitioning for Large Distributed Graphs - Isabelle Stanton & Gabriel Kliot

In this paper, their major contribution focuses on 10 different streaming graph partitioning heuristics and the relevant


text:
<?php namespace Znck\Attach\Exceptions;

use Exception;

class InvalidDiskException extends Exception
{

}


text:
using SpeakEasy.Bodies;

namespace SpeakEasy.Requests
{
    internal abstract class PostLikeRequest : HttpRequest
    {
        protected PostLikeRequest(Resource resource)
            : base(resource, new PostRequestBody(resource))
        {
        }

        protected PostLikeRequest(Resource resource, IRequestBody body)
            : base(resource, body)
        {
        }
    }
}


text:
<?php

/*
	Class: Element
		The Element abstract class
*/
abstract class Element {

    /*
       Variable: $identifier
         Element identifier.
    */
	public $identifier;

    /*
		Variable: app
			App instance.
    */
	public $app;

    /*
       Variable: $config
         Config AppData object.
    */
	public $config;

    /*
       Variable: $_type
         Elements related type object.
    */
	protected $_type;

    /*
       Variable: $_item
         Elements related item object.
    */
	protected $_item;

    /*
       Variable: $_callbacks
         Element callbacks.
    */
	protected $_callbacks = array();

	/*
	   Function: Constructor
	*/
	public function __construct() {

		// set app
		$this->app = App::getInstance('zoo');

		$this->config = $this->app->data->create();

	}

	/*
		Function: getElementType
			Gets the elements type.

		Returns:
			string - the elements type
	*/
	public function getElementType() {
		return strtolower(str_replace('Element', '', get_class($this)));
	}

	/*
		Function: get
			Gets the elements data.

		Returns:
			Mixed - the elements data
	*/
	public function get($key, $default = null) {
		return $this->_item->elements->find("{$this->identifier}.{$key}", $default);
	}

	/*
		Function: set
			Sets the elements data.

		Returns:
			Element - this
	*/
	public function set($key, $value) {
		$this->_item->elements[$this->identifier][$key] = $value;
		return $this;
	}

	/*
		Function: bindData
			Set data through data array.

		Parameters:
			$data - array

		Returns:
			Void
	*/
	public function bindData($data = array()) {
		if (isset($this->_item)) {
			$this->_item->elements->set($this->identifier, $data);
		}
	}

	/*
		Function: data
			Gets data array.

		Returns:
			Array - data
	*/
	public function data() {
		if (isset($this->_item)) {
			return $this->_item->elements->get($this->identifier);
		}

		return array();
	}

	/* @deprecated as of version 2.5 beta */
	public function getElementData() {
		return $this->app->data->create($this->data());
	}

	/* @deprecated as of version 2.5 beta */
	public function getConfig() {
		return $this->config;
	}

	/*
		Function: getLayout
			Get element layout path and use override if exists.

		Returns:
			String - Layout path
	*/
	public function getLayout($layout = null) {

		// init vars
		$type = $this->getElementType();

		// set default
		if ($layout == null) {
			$layout = "{$type}.php";
		}

		// find layout
		return $this->app->path->path("elements:{$type}/tmpl/{$layout}");

	}

	/*
		Function: getSearchData
			Get elements search data.

		Returns:
			String - Search data
	*/
	public function getSearchData() {
		return null;
	}

	/*
		Function: getItem
			Get related item object.

		Returns:
			Item - item object
	*/
	public function getItem() {
		return $this->_item;
	}

	/*
		Function: getType
			Get related type object.

		Returns:
			Type - type object
	*/
	public function getType() {
		return $this->_type;
	}

	/*
		Function: getGroup
			Get element group.

		Returns:
			string - group
	*/
	public function getGroup() {
		return $this->getMetadata('group');
	}

	/*
		Function: setItem
			Set related item object.

		Parameters:
			$item - item object

		Returns:
			Void
	*/
	public function setItem($item) {
		$this->_item = $item;
	}

	/*
		Function: setType
			Set related type object.

		Parameters:
			$type - type object

		Returns:
			Void
	*/
	public function setType($type) {
		$this->_type = $type;
	}

	/*
		Function: hasValue
			Checks if the element's value is set.

	   Parameters:
			$params - render parameter

		Returns:
			Boolean - true, on success
	*/
	public function hasValue($params = array()) {
		$value = $this->get('value', $this->config->get('default'));
		return !empty($value);
	}

	/*
		Function: render
			Renders the element.

	   Parameters:
            $params - render parameter

		Returns:
			String - html
	*/
	public function render($params = array()) {

		// render layout
		if ($layout = $this->getLayout()) {
			return $this->renderLayout($layout, array('value' => $this->get('value')));
		}

		return $this->get('value');
	}

	/*
		Function: renderLayout
			Renders the element using template layout file.

	   Parameters:
            $__layout - layouts template file
	        $__args - layouts template file args

		Returns:
			String - html
	*/
	protected function renderLayout($__layout, $__args = array()) {

		// init vars
		if (is_array($__args)) {
			foreach ($__args as $__var => $__value) {
				$$__var = $__value;
			}
		}

		// render layout
		$__html = '';
		ob_start();
		include($__layout);
		$__html = ob_get_contents();
		ob_end_clean();

		return $__html;
	}

	/*
	   Function: edit
	       Renders the edit form field.
		   Must be overloaded by the child class.

	   Returns:
	       String - html
	*/
	abstract public function edit();

	/*
		Function: loadAssets
			Load elements css/js assets.

		Returns:
			Void
	*/
	public function loadAssets() {
		return $this;
	}

	/*
		Function: loadConfigAssets
			Load elements css/js config assets.

		Returns:
			Element
	*/
	public function loadConfigAssets() {
		return $this;
	}

	/*
		Function: registerCallback
			Register a callback function.

		Returns:
			Void
	*/
	public function registerCallback($method) {
		if (!in_array(strtolower($method), $this->_callbacks)) {
			$this->_callbacks[] = strtolower($method);
		}
	}

	/*
		Function: callback
			Execute elements callback function.

		Returns:
			Mixed
	*/
	public function callback($method, $args = array()) {

		// try to call a elements class method
		if (in_array(strtolower($method), $this->_callbacks) && method_exists($this, $method)) {
			// call method
			$res = call_user_func_array(array($this, $method), $args);
			// output if method returns a string
			if (is_string($res)) {
				echo $res;
			}
		}
	}

	/*
		Function: getConfigForm
			Get parameter form object to render input form.

		Returns:
			Parameter Object
	*/
	public function getConfigForm() {

		// get form
		$form = $this->app->parameterform->create();

		// get config xml files
		$params = array();
		$class = new ReflectionClass($this);
		while ($class !== false) {
			$type = $class->getName() == 'Element' ? 'element' : strtolower(str_replace('Element', '', $class->getName()));
			if ($xml = $this->app->path->path("elements:$type/$type.xml")) {
				array_unshift($params, $xml);
			}
			$class = $class->getParentClass();
		}

		// trigger configparams event
		$params = $this->app->event->dispatcher->notify($this->app->event->create($this, 'element:configparams')->setReturnValue($params))->getReturnValue();

		// skip if there are no config files
		if (empty($params)) {
			return null;
		}

		// add config xml files
		foreach ($params as $xml) {
			$form->addXML($xml);
		}

		// set values
		$form->setValues($this->config);

		// add reference to element
		$form->element = $this;

		// trigger configform event
		$this->app->event->dispatcher->notify($this->app->event->create($this, 'element:configform', compact('form')));

		return $form;

	}

	/*
		Function: getMetaData
			Get elements xml meta data.

		Returns:
			Array - Meta information
	*/
	public function getMetaData($key = null) {

		$data = array();
		$type = $this->getElementType();
		$xml  = $this->loadXML();

		if (!$xml) {
			return false;
		}

		$data['type'] 		  = $xml->attributes()->type ? (string) $xml->attributes()->type : 'Unknown';
		$data['group'] 		  = $xml->attributes()->group ? (string) $xml->attributes()->group : 'Unknown';
		$data['hidden'] 	  = $xml->attributes()->hidden ? (string) $xml->attributes()->hidden : 'false';
        $data['trusted'] 	  = $xml->attributes()->trusted ? (string) $xml->attributes()->trusted : 'false';
		$data['orderable']	  = $xml->attributes()->orderable ? (string) $xml->attributes()->orderable : 'false';
		$data['name'] 		  = (string) $xml->name;
		$data['creationdate'] = $xml->creationDate ? (string) $xml->creationDate : 'Unknown';
		$data['author'] 	  = $xml->author ? (string) $xml->author : 'Unknown';
		$data['copyright'] 	  = (string) $xml->copyright;
		$data['authorEmail']  = (string) $xml->authorEmail;
		$data['authorUrl'] 	  = (string) $xml->authorUrl;
		$data['version'] 	  = (string) $xml->version;
		$data['description']  = (string) $xml->description;

		$data = $this->app->data->create($data);

		return $key == null ? $data : $data->get($key);
	}

	/**
	 * Retrieve Element XML file info
	 *
	 * @return Object the XML loaded file
	 *
	 * @since 3.0.9
	 */
	public function loadXML() {

		$type = $this->getElementType();
		return simplexml_load_file($this->app->path->path("elements:$type/$type.xml"));
	}

	/*
		Function: getControlName
			Gets the controle name for given name.

		Returns:
			String - the control name
	*/
	public function getControlName($name, $array = false) {
		return "elements[{$this->identifier}][{$name}]" . ($array ? "[]":"");
	}

	/*
    	Function: canAccess
    	  Check if element is accessible with users access rights.

	   Returns:
	      Boolean - True, if access granted
 	*/
	public function canAccess($user = null) {
		return $this->app->user->canAccess($user, $this->config->get('access', $this->app->joomla->getDefaultAccess()));
	}

	/*
		Function: getPath
			Get path to element's base directory.

		Returns:
			String - Path
	*/
	public function getPath() {
		return $this->app->path->path("elements:".$this->getElementType());
	}

	/*
		Function: __get
			Magic getter for deprecated _data and _config properties

		Returns:
			misc
	*/
	public function __get($name) {
		switch ($name) {
			case '_data':
				return $this->getElementData();
			case '_config':
				return $this->config;
		}
	}

}

// Declare the interface 'iSubmittable'
interface iSubmittable {

	/*
		Function: renderSubmission
			Renders the element in submission.

	   Parameters:
            $params - AppData submission parameters

		Returns:
			String - html
	*/
    public function renderSubmission($params = array());

    /*
		Function: validateSubmission
			Validates the submitted element

	   Parameters:
            $value  - AppData value
            $params - AppData submission parameters

		Returns:
			Array - cleaned value
	*/
    public function validateSubmission($value, $params);
}

// deprecated as of version 2.5.7
interface iSubmissionUpload {

	// deprecated as of version 2.5.7 use beforeSubmissionSave callback instead
    public function doUpload();
}

/*
	Class: ElementException
*/
class ElementException extends AppException {}


text:
pub use self::dependency::Dependency;
pub use self::features::{CliUnstable, Edition, Feature, Features};
pub use self::manifest::{EitherManifest, VirtualManifest};
pub use self::manifest::{LibKind, Manifest, Target, TargetKind};
pub use self::package::{Package, PackageSet};
pub use self::package_id::PackageId;
pub use self::package_id_spec::PackageIdSpec;
pub use self::registry::Registry;
pub use self::resolver::Resolve;
pub use self::shell::{Shell, Verbosity};
pub use self::source::{GitReference, Source, SourceId, SourceMap};
pub use self::summary::{FeatureMap, FeatureValue, Summary};
pub use self::workspace::{Members, Workspace, WorkspaceConfig, WorkspaceRootConfig};

pub mod compiler;
pub mod dependency;
mod features;
mod interning;
pub mod manifest;
pub mod package;
pub mod package_id;
mod package_id_spec;
pub mod profiles;
pub mod registry;
pub mod resolver;
pub mod shell;
pub mod source;
pub mod summary;
mod workspace;


text:
package kuberuntime

import (
	"encoding/json"
	"strconv"

	v1 "k8s.io/api/core/v1"
	kubetypes "k8s.io/apimachinery/pkg/types"
	"k8s.io/klog/v2"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
	"k8s.io/kubernetes/pkg/kubelet/types"
)

const (
	// TODO: change those label names to follow kubernetes's format
	podDeletionGracePeriodLabel    = "io.kubernetes.pod.deletionGracePeriod"
	podTerminationGracePeriodLabel = "io.kubernetes.pod.terminationGracePeriod"

	containerHashLabel                     = "io.kubernetes.container.hash"
	containerRestartCountLabel             = "io.kubernetes.container.restartCount"
	containerTerminationMessagePathLabel   = "io.kubernetes.container.terminationMessagePath"
	containerTerminationMessagePolicyLabel = "io.kubernetes.container.terminationMessagePolicy"
	containerPreStopHandlerLabel           = "io.kubernetes.container.preStopHandler"
	containerPortsLabel                    = "io.kubernetes.container.ports"
)

type labeledPodSandboxInfo struct {
	// Labels from v1.Pod
	Labels       map[string]string
	PodName      string
	PodNamespace string
	PodUID       kubetypes.UID
}

type annotatedPodSandboxInfo struct {
	// Annotations from v1.Pod
	Annotations map[string]string
}

type labeledContainerInfo struct {
	ContainerName string
	PodName       string
	PodNamespace  string
	PodUID        kubetypes.UID
}

type annotatedContainerInfo struct {
	Hash                      uint64
	RestartCount              int
	PodDeletionGracePeriod    *int64
	PodTerminationGracePeriod *int64
	TerminationMessagePath    string
	TerminationMessagePolicy  v1.TerminationMessagePolicy
	PreStopHandler            *v1.Handler
	ContainerPorts            []v1.ContainerPort
}

// newPodLabels creates pod labels from v1.Pod.
func newPodLabels(pod *v1.Pod) map[string]string {
	labels := map[string]string{}

	// Get labels from v1.Pod
	for k, v := range pod.Labels {
		labels[k] = v
	}

	labels[types.KubernetesPodNameLabel] = pod.Name
	labels[types.KubernetesPodNamespaceLabel] = pod.Namespace
	labels[types.KubernetesPodUIDLabel] = string(pod.UID)

	return labels
}

// newPodAnnotations creates pod annotations from v1.Pod.
func newPodAnnotations(pod *v1.Pod) map[string]string {
	return pod.Annotations
}

// newContainerLabels creates container labels from v1.Container and v1.Pod.
func newContainerLabels(container *v1.Container, pod *v1.Pod) map[string]string {
	labels := map[string]string{}
	labels[types.KubernetesPodNameLabel] = pod.Name
	labels[types.KubernetesPodNamespaceLabel] = pod.Namespace
	labels[types.KubernetesPodUIDLabel] = string(pod.UID)
	labels[types.KubernetesContainerNameLabel] = container.Name

	return labels
}

// newContainerAnnotations creates container annotations from v1.Container and v1.Pod.
func newContainerAnnotations(container *v1.Container, pod *v1.Pod, restartCount int, opts *kubecontainer.RunContainerOptions) map[string]string {
	annotations := map[string]string{}

	// Kubelet always overrides device plugin annotations if they are conflicting
	for _, a := range opts.Annotations {
		annotations[a.Name] = a.Value
	}

	annotations[containerHashLabel] = strconv.FormatUint(kubecontainer.HashContainer(container), 16)
	annotations[containerRestartCountLabel] = strconv.Itoa(restartCount)
	annotations[containerTerminationMessagePathLabel] = container.TerminationMessagePath
	annotations[containerTerminationMessagePolicyLabel] = string(container.TerminationMessagePolicy)

	if pod.DeletionGracePeriodSeconds != nil {
		annotations[podDeletionGracePeriodLabel] = strconv.FormatInt(*pod.DeletionGracePeriodSeconds, 10)
	}
	if pod.Spec.TerminationGracePeriodSeconds != nil {
		annotations[podTerminationGracePeriodLabel] = strconv.FormatInt(*pod.Spec.TerminationGracePeriodSeconds, 10)
	}

	if container.Lifecycle != nil && container.Lifecycle.PreStop != nil {
		// Using json encoding so that the PreStop handler object is readable after writing as a label
		rawPreStop, err := json.Marshal(container.Lifecycle.PreStop)
		if err != nil {
			klog.ErrorS(err, "Unable to marshal lifecycle PreStop handler for container", "containerName", container.Name, "pod", klog.KObj(pod))
		} else {
			annotations[containerPreStopHandlerLabel] = string(rawPreStop)
		}
	}

	if len(container.Ports) > 0 {
		rawContainerPorts, err := json.Marshal(container.Ports)
		if err != nil {
			klog.ErrorS(err, "Unable to marshal container ports for container", "containerName", container.Name, "pod", klog.KObj(pod))
		} else {
			annotations[containerPortsLabel] = string(rawContainerPorts)
		}
	}

	return annotations
}

// getPodSandboxInfoFromLabels gets labeledPodSandboxInfo from labels.
func getPodSandboxInfoFromLabels(labels map[string]string) *labeledPodSandboxInfo {
	podSandboxInfo := &labeledPodSandboxInfo{
		Labels:       make(map[string]string),
		PodName:      getStringValueFromLabel(labels, types.KubernetesPodNameLabel),
		PodNamespace: getStringValueFromLabel(labels, types.KubernetesPodNamespaceLabel),
		PodUID:       kubetypes.UID(getStringValueFromLabel(labels, types.KubernetesPodUIDLabel)),
	}

	// Remain only labels from v1.Pod
	for k, v := range labels {
		if k != types.KubernetesPodNameLabel && k != types.KubernetesPodNamespaceLabel && k != types.KubernetesPodUIDLabel {
			podSandboxInfo.Labels[k] = v
		}
	}

	return podSandboxInfo
}

// getPodSandboxInfoFromAnnotations gets annotatedPodSandboxInfo from annotations.
func getPodSandboxInfoFromAnnotations(annotations map[string]string) *annotatedPodSandboxInfo {
	return &annotatedPodSandboxInfo{
		Annotations: annotations,
	}
}

// getContainerInfoFromLabels gets labeledContainerInfo from labels.
func getContainerInfoFromLabels(labels map[string]string) *labeledContainerInfo {
	return &labeledContainerInfo{
		PodName:       getStringValueFromLabel(labels, types.KubernetesPodNameLabel),
		PodNamespace:  getStringValueFromLabel(labels, types.KubernetesPodNamespaceLabel),
		PodUID:        kubetypes.UID(getStringValueFromLabel(labels, types.KubernetesPodUIDLabel)),
		ContainerName: getStringValueFromLabel(labels, types.KubernetesContainerNameLabel),
	}
}

// getContainerInfoFromAnnotations gets annotatedContainerInfo from annotations.
func getContainerInfoFromAnnotations(annotations map[string]string) *annotatedContainerInfo {
	var err error
	containerInfo := &annotatedContainerInfo{
		TerminationMessagePath:   getStringValueFromLabel(annotations, containerTerminationMessagePathLabel),
		TerminationMessagePolicy: v1.TerminationMessagePolicy(getStringValueFromLabel(annotations, containerTerminationMessagePolicyLabel)),
	}

	if containerInfo.Hash, err = getUint64ValueFromLabel(annotations, containerHashLabel); err != nil {
		klog.ErrorS(err, "Unable to get label value from annotations", "label", containerHashLabel, "annotations", annotations)
	}
	if containerInfo.RestartCount, err = getIntValueFromLabel(annotations, containerRestartCountLabel); err != nil {
		klog.ErrorS(err, "Unable to get label value from annotations", "label", containerRestartCountLabel, "annotations", annotations)
	}
	if containerInfo.PodDeletionGracePeriod, err = getInt64PointerFromLabel(annotations, podDeletionGracePeriodLabel); err != nil {
		klog.ErrorS(err, "Unable to get label value from annotations", "label", podDeletionGracePeriodLabel, "annotations", annotations)
	}
	if containerInfo.PodTerminationGracePeriod, err = getInt64PointerFromLabel(annotations, podTerminationGracePeriodLabel); err != nil {
		klog.ErrorS(err, "Unable to get label value from annotations", "label", podTerminationGracePeriodLabel, "annotations", annotations)
	}

	preStopHandler := &v1.Handler{}
	if found, err := getJSONObjectFromLabel(annotations, containerPreStopHandlerLabel, preStopHandler); err != nil {
		klog.ErrorS(err, "Unable to get label value from annotations", "label", containerPreStopHandlerLabel, "annotations", annotations)
	} else if found {
		containerInfo.PreStopHandler = preStopHandler
	}

	containerPorts := []v1.ContainerPort{}
	if found, err := getJSONObjectFromLabel(annotations, containerPortsLabel, &containerPorts); err != nil {
		klog.ErrorS(err, "Unable to get label value from annotations", "label", containerPortsLabel, "annotations", annotations)
	} else if found {
		containerInfo.ContainerPorts = containerPorts
	}

	return containerInfo
}

func getStringValueFromLabel(labels map[string]string, label string) string {
	if value, found := labels[label]; found {
		return value
	}
	// Do not report error, because there should be many old containers without label now.
	klog.V(3).InfoS("Container doesn't have requested label, it may be an old or invalid container", "label", label)
	// Return empty string "" for these containers, the caller will get value by other ways.
	return ""
}

func getIntValueFromLabel(labels map[string]string, label string) (int, error) {
	if strValue, found := labels[label]; found {
		intValue, err := strconv.Atoi(strValue)
		if err != nil {
			// This really should not happen. Just set value to 0 to handle this abnormal case
			return 0, err
		}
		return intValue, nil
	}
	// Do not report error, because there should be many old containers without label now.
	klog.V(3).InfoS("Container doesn't have requested label, it may be an old or invalid container", "label", label)
	// Just set the value to 0
	return 0, nil
}

func getUint64ValueFromLabel(labels map[string]string, label string) (uint64, error) {
	if strValue, found := labels[label]; found {
		intValue, err := strconv.ParseUint(strValue, 16, 64)
		if err != nil {
			// This really should not happen. Just set value to 0 to handle this abnormal case
			return 0, err
		}
		return intValue, nil
	}
	// Do not report error, because there should be many old containers without label now.
	klog.V(3).InfoS("Container doesn't have requested label, it may be an old or invalid container", "label", label)
	// Just set the value to 0
	return 0, nil
}

func getInt64PointerFromLabel(labels map[string]string, label string) (*int64, error) {
	if strValue, found := labels[label]; found {
		int64Value, err := strconv.ParseInt(strValue, 10, 64)
		if err != nil {
			return nil, err
		}
		return &int64Value, nil
	}
	// If the label is not found, return pointer nil.
	return nil, nil
}

// getJSONObjectFromLabel returns a bool value indicating whether an object is found.
func getJSONObjectFromLabel(labels map[string]string, label string, value interface{}) (bool, error) {
	if strValue, found := labels[label]; found {
		err := json.Unmarshal([]byte(strValue), value)
		return found, err
	}
	// If the label is not found, return not found.
	return false, nil
}


text:
$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + "/..")
$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + "/../lib")

require "rubygems" unless defined?(Gem)
require "benchmark" unless defined?(Benchmark)
require "yajl"
begin
  require "json" unless defined?(JSON)
rescue LoadError
end
require "yaml" unless defined?(YAML)

# JSON section
filename = "benchmark/subjects/ohai.json"
json = File.new(filename, "r")

times = ARGV[0] ? ARGV[0].to_i : 1000
puts "Starting benchmark parsing #{File.size(filename)} bytes of JSON data #{times} times\n\n"
Benchmark.bmbm do |x|
  parser = Yajl::Parser.new
  parser.on_parse_complete = ->(obj) {} if times > 1
  x.report do
    puts "Yajl::Parser#parse"
    times.times do
      json.rewind
      parser.parse(json)
    end
  end
  if defined?(JSON)
    x.report do
      puts "JSON.parse"
      times.times do
        json.rewind
        JSON.parse(json.read, max_nesting: false)
      end
    end
  end
end
json.close

# YAML section
filename = "benchmark/subjects/ohai.yml"
yaml = File.new(filename, "r")

puts "Starting benchmark parsing #{File.size(filename)} bytes of YAML data #{times} times\n\n"
Benchmark.bmbm do |x|
  x.report do
    puts "YAML.load_stream"
    times.times do
      yaml.rewind
      YAML.load(yaml)
    end
  end
end
yaml.close


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Regulations of Title Change of Land and Improved Buildings for Credit Unions</英文法規名稱>
<中文法規名稱>儲蓄互助社土地及建築改良物更名作業辦法</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=D0050129</法規網址>
<最新英文異動日期>20190603</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件 />
<沿革內容><![CDATA[1.Promulgated on December 18, 2002
2.Amended on June 3, 2019]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[The regulations are based on Paragraph 3 of Article 30 in Credit Union Act (hereinafter called the "Act").]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The regulations apply to the registered credit unions that acquired land and improved buildings with their own reserves by registered as a natural person or in the name of Credit Union League of the Republic of China (hereinafter called the "League") before the regulations were amended and implemented on February 6, 2002.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[For the situations specified in Paragraph 2 of Article 30 in the Act, Credit Unions have to prepare the following documents and deliver to the League for review.
1. An application (Appendix 1).
2. Certificates or documents that shall be proved land or improved buildings  were purchased with their own reserves.
3. A copy of registration of Credit Unions.
4. A report of final accounts for the previous year.
5. A transcript of registers of land or improved buildings.
6. Other documents designated by the central competent authority.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[Certificates or documents specified in Subparagraph 2 of Article 3 refer to any of the following papers:
1. Contracts of sale: Contracts that specify land or improved buildings purchased in the name of credit unions.
2. Minutes of the General meeting of members: Minutes that specify resolutions of purchase of land or improved buildings.
3. Account books and forms: Accounts or forms that specify expenditures of buying land or improved buildings, balance sheets or inventories of properties.
4. Letter of consent of the League: For registrations in the name of the League, the League shall present a letter of authorization for title change.
5. Affidavit of owner, successor or administrator of land or improved buildings: The affidavit should specify the land or improved buildings are not possessed by a certain natural person and agree to change its ownership to a certain credit union.
6. Other documents designated by the central competent authority.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[The League shall report the qualified applications to the respective competent authorities of municipalities, counties or cities for issuing the certificate (Appendix 2).
Credit unions may take this certificate to apply to their local land administration offices for title change registration.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[The regulations will be executed upon the date of announcement.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
namespace CanvasToy {

    class SphereGeometry extends Geometry {
        constructor(public radius: number, public perVertDistance: number) {
            super();
            for (let y = - radius; y <= radius; y += perVertDistance) {
                let circlrRadius = Math.sqrt(radius * radius - y * y);
                for (let x = -circlrRadius; x <= circlrRadius; x += perVertDistance) {
                    let z1 = Math.sqrt(circlrRadius * circlrRadius - x * x);
                    let z2 = -z1;
                    this.attributes.position.data.push(x, y, z1);
                    this.attributes.position.data.push(x, y, z2);
                }
            }
            // TODO: generate faces
        }
    }
}


text:
Basic Price:

      <Price decimalsSeparator="," thousandsSeparator="." underlined value={50153.30} />

      <Price decimalsSeparator="." symbol="د.إ." symbolPosition="right" thousandsSeparator=" " underlined value={50153.30} />

      <Price decimalsSeparator="," showDecimals={false} thousandsSeparator="." underlined value={50153.30} />

Price with additional text:

      <Price additionalText="per day" underlined value={50153.30} />

Price with asterisk:

      <Price discount={50200.30} showAsterisk size="s" underlined value={50153.30} />

      <Price additionalText="total" discount={50200.30} showAsterisk size="m" symbolPosition="right" underlined value={50153.30} />

      <Price additionalText="total" discount={50200.30} showAsterisk size="xl" value={50153.30} />

Price with discount:

      <Price discount={50200.30} size="s" underlined value={50153.30} />

      <Price additionalText="total" discount={50200.30} size="m" underlined value={50153.30} />

Unstyled price:

      <Price value={12345.67} unstyled />

Sizes:

      <Price showAsterisk size="xs" underlined value={50153.30} />

      <Price size="s" underlined value={50153.30} />

      <Price size="m" underlined value={50153.30} />

      <Price showAsterisk size="l" underlined value={50153.30} />

      <Price size="xl" underlined value={50153.30} />


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:property-placeholder/>

    <bean id="meterSupplier" class="com.heliosapm.streams.metrics.processors.impl.StreamedMetricMeterSupplier">
    	<property name="aggregationPeriod" value="5"/>
    	<property name="period" value="5000"/>
    	<property name="sources" value="tsdb.metrics.metrics"/>
    	<property name="topicSink" value="tsdb.metrics.binary"/>
    	<property name="sourceKeySerde">
    		<util:constant static-field="com.heliosapm.streams.serialization.HeliosSerdes.STRING_SERDE"/>
    	</property>
    	<property name="sourceValueSerde">
    		<util:constant static-field="com.heliosapm.streams.serialization.HeliosSerdes.STREAMED_METRIC_SERDE_THROUGH_STRING"/>
    	</property>
    	<property name="sinkKeySerde">
    		<util:constant static-field="com.heliosapm.streams.serialization.HeliosSerdes.STRING_SERDE"/>
    	</property>
    	<property name="sinkValueSerde">
    		<util:constant static-field="com.heliosapm.streams.serialization.HeliosSerdes.STREAMED_METRIC_SERDE"/>
    	</property>
    	<property name="stateStoreDefinitions" >
	    	<util:set>
	    		<ref bean="metricTimestampStoreDefinition"/>
	    	</util:set>
    	</property>
    </bean>

    <bean id="textRouter" class="com.heliosapm.streams.metrics.router.text.TextMetricStreamRouter">
		<constructor-arg ref="streamsConfigProps"/>
    	<property name="processorSuppliers">
    		<util:list>
    			<ref bean="meterSupplier"/>
    		</util:list>
    	</property>
    </bean>

    <bean id="streamsConfigProps" class="java.util.Properties" factory-bean="streamsConfig" factory-method="buildProperties"/>

    <bean id="streamsConfig" class="com.heliosapm.streams.metrics.router.config.StreamsConfigBuilder" >
    	<property name="applicationId" value="StreamHub"/>
    	<property name="bootstrapServers" value="${test.kafka.connect}"/>
    	<property name="zookeeperConnect" value="${test.zookeeper.connect}"/>
    	<property name="clientId">
    		<util:constant static-field="com.heliosapm.streams.metrics.router.config.StreamsConfigBuilder.DEFAULT_CLIENT_ID" />
    	</property>
    	<property name="pollWaitMs" value="${streamhub.config.pollwaitms:10}"/>
    	<property name="stateStoreDir">
    		<util:constant static-field="com.heliosapm.streams.metrics.router.config.StreamsConfigBuilder.DEFAULT_STATE_STORE_NAME" />
    	</property>
    	<property name="timeExtractor" value="${streamhub.config.timeextractor:com.heliosapm.streams.metrics.TextLineTimestampExtractor}"/>
    </bean>

    <!--
    <bean id="streamsConfigProperties" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  		<property name="targetObject" ref="streamsConfig" />
  		<property name="targetMethod" value="buildProperties" />
	</bean>
	-->

</beans>


text:
namespace boost {
namespace fibers {
namespace spin {

class BOOST_FIBER_DECL barrier : private noncopyable
{
private:
	std::size_t		initial_;
	std::size_t		current_;
	bool			cycle_;
	mutex			mtx_;
	condition		cond_;

public:
	barrier( std::size_t);

	bool wait();
};

}}}

# if defined(BOOST_MSVC)
# pragma warning(pop)
# endif

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_FIBERS_SPIN_BARRIER_H


text:
"""Asserts to use in energy tests."""

from physalia.models import Measurement

def consumption_below(sample, energy_consumption_baseline):
    """Test for energy consumption lower than a given value in Joules (avg).

    Args:
        sample (list of Measurement): sample of measurements
        energy_consumption (number): baseline energy consumption in Joules.
    """
    energy_consumption_mean = Measurement.mean_energy_consumption(sample)
    assert energy_consumption_mean < energy_consumption_baseline

def consumption_lower_than_app(sample, app, use_case=None):
    """Test that a given sample spends less energy than a known app.

    Args:
        sample (list of Measurement): sample of measurements
        app (string): identifier/package of the app to be compared
        use_case (string): select only data from a given use case
    """
    baseline_measurements = Measurement.get_all_entries_of_app(app, use_case)
    baseline_consumption = Measurement.mean_energy_consumption(
        baseline_measurements
    )
    consumption_below(sample, baseline_consumption)

def top_percentile(sample, nth):
    """Test that a given sample is in the top nth percentile.

    Args:
        sample (list of Measurement): sample of measurements
        nth (number): percentage of the position in which the sample should fit
        app (string): identifier of the application within the sample should be compared
        use_case (string: identifier of the use case used to create the ranking
    """
    position, total = Measurement.get_position_in_ranking(sample)
    percentile_position = float(position)/total*100
    assert percentile_position <= nth,\
           ("Given sample is not on {:.1f}% top percentile "
            "(Position: {:.1f}%)".format(
                nth,
                percentile_position
            ))


text:
require 'delayed_job'

class Delayed::Job
  class DelayedJobFake < Array
    # fake out arel
    def order(*args)
      DelayedJobFake.new
    end

    def offset(*args)
      DelayedJobFake.new
    end

    def limit(*args)
      DelayedJobFake.new
    end
  end

  def self.where(*args)
    DelayedJobFake.new
  end

  def self.count(*args)
    0
  end

  def self.order(*args)
    DelayedJobFake.new
  end

  def self.find(*args)
    DelayedJobFake.new
  end
end


text:
#include <memory>
#include <boost/thread.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>

#include "slg/renderconfig.h"
#include "slg/renderengine.h"
#include "slg/film/film.h"

#include "slg/samplers/random.h"
#include "slg/samplers/sobol.h"
#include "slg/samplers/metropolis.h"

#include "slg/film/filters/box.h"
#include "slg/film/filters/gaussian.h"
#include "slg/film/filters/mitchell.h"
#include "slg/film/filters/mitchellss.h"
#include "slg/film/filters/blackmanharris.h"

#include "slg/film/imagepipeline/plugins/tonemaps/autolinear.h"
#include "slg/film/imagepipeline/plugins/tonemaps/linear.h"
#include "slg/film/imagepipeline/plugins/tonemaps/luxlinear.h"
#include "slg/film/imagepipeline/plugins/tonemaps/reinhard02.h"

#include "slg/film/imagepipeline/plugins/cameraresponse.h"
#include "slg/film/imagepipeline/plugins/contourlines.h"
#include "slg/film/imagepipeline/plugins/gammacorrection.h"
#include "slg/film/imagepipeline/plugins/gaussianblur3x3.h"
#include "slg/film/imagepipeline/plugins/nop.h"
#include "slg/film/imagepipeline/plugins/outputswitcher.h"

#include "slg/engines/rtpathocl/rtpathocl.h"
#include "slg/engines/rtbiaspathocl/rtbiaspathocl.h"
#include "slg/engines/lightcpu/lightcpu.h"
#include "slg/engines/pathcpu/pathcpu.h"
#include "slg/engines/bidircpu/bidircpu.h"
#include "slg/engines/bidirvmcpu/bidirvmcpu.h"
#include "slg/engines/filesaver/filesaver.h"
#include "slg/engines/biaspathcpu/biaspathcpu.h"
#include "slg/engines/biaspathocl/biaspathocl.h"

using namespace std;
using namespace luxrays;
using namespace slg;

static boost::mutex defaultPropertiesMutex;
static auto_ptr<Properties> defaultProperties;

void RenderConfig::InitDefaultProperties() {
	// Check if I have to initialize the default Properties
	if (!defaultProperties.get()) {
		boost::unique_lock<boost::mutex> lock(defaultPropertiesMutex);
		if (!defaultProperties.get()) {
			defaultProperties.reset(new Properties());

			defaultProperties->Set(Property("accelerator.instances.enable")(true));
			defaultProperties->Set(Property("accelerator.type")("AUTO"));

			defaultProperties->Set(Property("lightstrategy.type")("LOG_POWER"));

			// Batch related Properties
			defaultProperties->Set(Property("batch.halttime")(0u));
			defaultProperties->Set(Property("batch.haltspp")(0u));
			defaultProperties->Set(Property("batch.haltthreshold")(-1.f));
			defaultProperties->Set(Property("batch.haltdebug")(0u));

			// Film Filter related Properties
			defaultProperties->Set(Property("film.filter.type")("BLACKMANHARRIS"));
			defaultProperties->Set(Property("film.filter.width")(2.f));
			defaultProperties->Set(Property("film.filter.gaussian.alpha")(2.f));
			defaultProperties->Set(Property("film.filter.mitchell.b")(1.f / 3.f));
			defaultProperties->Set(Property("film.filter.mitchell.c")(1.f / 3.f));
			defaultProperties->Set(Property("film.filter.mitchellss.b")(1.f / 3.f));
			defaultProperties->Set(Property("film.filter.mitchellss.c")(1.f / 3.f));

			defaultProperties->Set(Property("film.height")(480u));
			defaultProperties->Set(Property("film.width")(640u));

			// Sampler related Properties
			defaultProperties->Set(Property("sampler.type")("RANDOM"));
			defaultProperties->Set(Property("sampler.metropolis.largesteprate")(.4f));
			defaultProperties->Set(Property("sampler.metropolis.maxconsecutivereject")(512));
			defaultProperties->Set(Property("sampler.metropolis.imagemutationrate")(.1f));

			defaultProperties->Set(Property("images.scale")(1.f));
			defaultProperties->Set(Property("renderengine.type")("PATHOCL"));
			defaultProperties->Set(Property("scene.file")("scenes/luxball/luxball.scn"));
			defaultProperties->Set(Property("screen.refresh.interval")(100u));

			// Specific RenderEngine settings are defined in each RenderEngine::Start() method
		}
	}
}

const Properties &RenderConfig::GetDefaultProperties() {
	InitDefaultProperties();

	return *defaultProperties;
}

RenderConfig::RenderConfig(const luxrays::Properties &props, Scene *scn) : scene(scn) {
	InitDefaultProperties();

	SLG_LOG("Configuration: ");
	const vector<string> &keys = props.GetAllNames();
	for (vector<string>::const_iterator i = keys.begin(); i != keys.end(); ++i)
		SLG_LOG("  " << props.Get(*i));

	// Set the Scene
	if (scn) {
		scene = scn;
		allocatedScene = false;
	} else {
		// Create the Scene
		const string defaultSceneName = GetDefaultProperties().Get("scene.file").Get<string>();
		const string sceneFileName = props.Get(Property("scene.file")(defaultSceneName)).Get<string>();
		const float defaultImageScale = GetDefaultProperties().Get("images.scale").Get<float>();
		const float imageScale = Max(.01f, props.Get(Property("images.scale")(defaultImageScale)).Get<float>());

		scene = new Scene(sceneFileName, imageScale);
		allocatedScene = true;
	}

	// Parse the configuration
	Parse(props);
}

RenderConfig::~RenderConfig() {
	// Check if the scene was allocated by me
	if (allocatedScene)
		delete scene;
}

const luxrays::Property RenderConfig::GetProperty(const std::string &name) const {
	if (cfg.IsDefined(name))
		return cfg.Get(name);
	else {
		// Use the default value
		return defaultProperties->Get(name);
	}
}

void RenderConfig::Parse(const luxrays::Properties &props) {
	cfg.Set(props);

	scene->enableInstanceSupport = GetProperty("accelerator.instances.enable").Get<bool>();
	const string accelType = GetProperty("accelerator.type").Get<string>();
	// "-1" is for compatibility with the past. However all other old values are
	// not emulated (i.e. the "AUTO" behavior is preferred in that case)
	if ((accelType == "AUTO") || (accelType == "-1"))
		scene->accelType = ACCEL_AUTO;
	else if (accelType == "BVH")
		scene->accelType = ACCEL_BVH;
	else if (accelType == "MBVH")
		scene->accelType = ACCEL_MBVH;
	else if (accelType == "QBVH")
		scene->accelType = ACCEL_QBVH;
	else if (accelType == "MQBVH")
		scene->accelType = ACCEL_MQBVH;
	else if (accelType == "EMBREE")
		scene->accelType = ACCEL_EMBREE;
	else {
		SLG_LOG("Unknown accelerator type (using AUTO instead): " << accelType);
	}

	const string lightStrategy = GetProperty("lightstrategy.type").Get<string>();
	if (lightStrategy == "UNIFORM")
		scene->lightDefs.SetLightStrategy(TYPE_UNIFORM);
	else if (lightStrategy == "POWER")
		scene->lightDefs.SetLightStrategy(TYPE_POWER);
	else if (lightStrategy == "LOG_POWER")
		scene->lightDefs.SetLightStrategy(TYPE_LOG_POWER);
	else {
		SLG_LOG("Unknown light strategy type (using AUTO instead): " << lightStrategy);
	}

	// Update the Camera
	u_int filmFullWidth, filmFullHeight, filmSubRegion[4];
	u_int *subRegion = GetFilmSize(&filmFullWidth, &filmFullHeight, filmSubRegion) ?
		filmSubRegion : NULL;
	scene->camera->Update(filmFullWidth, filmFullHeight, subRegion);
}

void RenderConfig::Delete(const string &prefix) {
	cfg.DeleteAll(cfg.GetAllNames(prefix));
}

bool RenderConfig::GetFilmSize(u_int *filmFullWidth, u_int *filmFullHeight,
		u_int *filmSubRegion) const {
	u_int width = 640;
	if (cfg.IsDefined("image.width")) {
		SLG_LOG("WARNING: deprecated property image.width");
		width = cfg.Get(Property("image.width")(width)).Get<u_int>();
	}
	width = GetProperty("film.width").Get<u_int>();

	u_int height = 480;
	if (cfg.IsDefined("image.height")) {
		SLG_LOG("WARNING: deprecated property image.height");
		height = cfg.Get(Property("image.height")(height)).Get<u_int>();
	}
	height = GetProperty("film.height").Get<u_int>();

	// Check if I'm rendering a film subregion
	u_int subRegion[4];
	bool subRegionUsed;
	if (cfg.IsDefined("film.subregion")) {
		const Property &prop = cfg.Get(Property("film.subregion")(0, width - 1u, 0, height - 1u));

		subRegion[0] = Max(0u, Min(width - 1, prop.Get<u_int>(0)));
		subRegion[1] = Max(0u, Min(width - 1, Max(subRegion[0] + 1, prop.Get<u_int>(1))));
		subRegion[2] = Max(0u, Min(height - 1, prop.Get<u_int>(2)));
		subRegion[3] = Max(0u, Min(height - 1, Max(subRegion[2] + 1, prop.Get<u_int>(3))));
		subRegionUsed = true;
	} else {
		subRegion[0] = 0;
		subRegion[1] = width - 1;
		subRegion[2] = 0;
		subRegion[3] = height - 1;
		subRegionUsed = false;
	}

	if (filmFullWidth)
		*filmFullWidth = width;
	if (filmFullHeight)
		*filmFullHeight = height;

	if (filmSubRegion) {
		filmSubRegion[0] = subRegion[0];
		filmSubRegion[1] = subRegion[1];
		filmSubRegion[2] = subRegion[2];
		filmSubRegion[3] = subRegion[3];
	}

	return subRegionUsed;
}

Film *RenderConfig::AllocFilm(FilmOutputs &filmOutputs) const {
	//--------------------------------------------------------------------------
	// Create the filter
	//--------------------------------------------------------------------------

	const FilterType filterType = Filter::String2FilterType(GetProperty("film.filter.type").Get<string>());
	const float defaultFilterWidth = GetProperty("film.filter.width").Get<float>();
	const float filterXWidth = cfg.Get(Property("film.filter.xwidth")(defaultFilterWidth)).Get<float>();
	const float filterYWidth = cfg.Get(Property("film.filter.ywidth")(defaultFilterWidth)).Get<float>();

	auto_ptr<Filter> filter;
	switch (filterType) {
		case FILTER_NONE:
			break;
		case FILTER_BOX:
			filter.reset(new BoxFilter(filterXWidth, filterYWidth));
			break;
		case FILTER_GAUSSIAN: {
			const float alpha = GetProperty("film.filter.gaussian.alpha").Get<float>();
			filter.reset(new GaussianFilter(filterXWidth, filterYWidth, alpha));
			break;
		}
		case FILTER_MITCHELL: {
			const float b = GetProperty("film.filter.mitchell.b").Get<float>();
			const float c = GetProperty("film.filter.mitchell.c").Get<float>();
			filter.reset(new MitchellFilter(filterXWidth, filterYWidth, b, c));
			break;
		}
		case FILTER_MITCHELL_SS: {
			const float b = GetProperty("film.filter.mitchellss.b").Get<float>();
			const float c = GetProperty("film.filter.mitchellss.c").Get<float>();
			filter.reset(new MitchellFilterSS(filterXWidth, filterYWidth, b, c));
			break;
		}
		case FILTER_BLACKMANHARRIS: {
			filter.reset(new BlackmanHarrisFilter(filterXWidth, filterYWidth));
			break;
		}
		default:
			throw runtime_error("Unknown filter type: " + boost::lexical_cast<string>(filterType));
	}

	//--------------------------------------------------------------------------
	// Create the image pipeline
	//--------------------------------------------------------------------------

	auto_ptr<ImagePipeline> imagePipeline(new ImagePipeline());
	vector<string> imagePipelineKeys = cfg.GetAllUniqueSubNames("film.imagepipeline");
	if (imagePipelineKeys.size() > 0) {
		// Sort the entries
		sort(imagePipelineKeys.begin(), imagePipelineKeys.end());

		for (vector<string>::const_iterator imagePipelineKey = imagePipelineKeys.begin(); imagePipelineKey != imagePipelineKeys.end(); ++imagePipelineKey) {
			// Extract the plugin priority name
			const string pluginPriority = Property::ExtractField(*imagePipelineKey, 2);
			if (pluginPriority == "")
				throw runtime_error("Syntax error in image pipeline plugin definition: " + *imagePipelineKey);
			const string prefix = "film.imagepipeline." + pluginPriority;

			const string type = cfg.Get(Property(prefix + ".type")("")).Get<string>();
			if (type == "")
				throw runtime_error("Syntax error in " + prefix + ".type");

			if (type == "TONEMAP_LINEAR") {
				imagePipeline->AddPlugin(new LinearToneMap(
					cfg.Get(Property(prefix + ".scale")(1.f)).Get<float>()));
			} else if (type == "TONEMAP_REINHARD02") {
				imagePipeline->AddPlugin(new Reinhard02ToneMap(
					cfg.Get(Property(prefix + ".prescale")(1.f)).Get<float>(),
					cfg.Get(Property(prefix + ".postscale")(1.2f)).Get<float>(),
					cfg.Get(Property(prefix + ".burn")(3.75f)).Get<float>()));
			} else if (type == "TONEMAP_AUTOLINEAR") {
				imagePipeline->AddPlugin(new AutoLinearToneMap());
			} else if (type == "TONEMAP_LUXLINEAR") {
				imagePipeline->AddPlugin(new LuxLinearToneMap(
					cfg.Get(Property(prefix + ".sensitivity")(100.f)).Get<float>(),
					cfg.Get(Property(prefix + ".exposure")(1.f / 1000.f)).Get<float>(),
					cfg.Get(Property(prefix + ".fstop")(2.8f)).Get<float>()));
			} else if (type == "NOP") {
				imagePipeline->AddPlugin(new NopPlugin());
			} else if (type == "GAMMA_CORRECTION") {
				imagePipeline->AddPlugin(new GammaCorrectionPlugin(
					cfg.Get(Property(prefix + ".value")(2.2f)).Get<float>(),
					// 4096 => 12bit resolution
					cfg.Get(Property(prefix + ".table.size")(4096u)).Get<u_int>()));
			} else if (type == "OUTPUT_SWITCHER") {
				imagePipeline->AddPlugin(new OutputSwitcherPlugin(
					Film::String2FilmChannelType(cfg.Get(Property(prefix + ".channel")("DEPTH")).Get<string>()),
					cfg.Get(Property(prefix + ".index")(0u)).Get<u_int>()));
			} else if (type == "GAUSSIANFILTER_3x3") {
				imagePipeline->AddPlugin(new GaussianBlur3x3FilterPlugin(
					cfg.Get(Property(prefix + ".weight")(.15f)).Get<float>()));
			} else if (type == "CAMERA_RESPONSE_FUNC") {
				imagePipeline->AddPlugin(new CameraResponsePlugin(
					cfg.Get(Property(prefix + ".name")("Advantix_100CD")).Get<string>()));
			} else if (type == "CONTOUR_LINES") {
				const float scale = cfg.Get(Property(prefix + ".scale")(179.f)).Get<float>();
				const float range = Max(0.f, cfg.Get(Property(prefix + ".range")(100.f)).Get<float>());
				const u_int steps = Max(2u, cfg.Get(Property(prefix + ".steps")(8)).Get<u_int>());
				const int zeroGridSize = cfg.Get(Property(prefix + ".zerogridsize")(8)).Get<int>();
				imagePipeline->AddPlugin(new ContourLinesPlugin(scale, range, steps, zeroGridSize));
			} else
				throw runtime_error("Unknown image pipeline plugin type: " + type);
		}
	} else {
		// The definition of image pipeline is missing, use the default
		imagePipeline->AddPlugin(new AutoLinearToneMap());
		imagePipeline->AddPlugin(new GammaCorrectionPlugin(2.2f, 4096));
	}

	if (cfg.IsDefined("film.gamma")) {
		SLG_LOG("WARNING: ignored deprecated property film.gamma");
	}

	//--------------------------------------------------------------------------
	// Create the Film
	//--------------------------------------------------------------------------

	u_int filmFullWidth, filmFullHeight, filmSubRegion[4];
	GetFilmSize(&filmFullWidth, &filmFullHeight, filmSubRegion);

	SLG_LOG("Film resolution: " << filmFullWidth << "x" << filmFullHeight);
	auto_ptr<Film> film(new Film(filmFullWidth, filmFullHeight));
	film->SetFilter(filter.release());
	film->SetImagePipeline(imagePipeline.release());

	// For compatibility with the past
	if (cfg.IsDefined("film.alphachannel.enable")) {
		SLG_LOG("WARNING: deprecated property film.alphachannel.enable");

		if (cfg.Get(Property("film.alphachannel.enable")(0)).Get<bool>())
			film->AddChannel(Film::ALPHA);
		else
			film->RemoveChannel(Film::ALPHA);
	}

	//--------------------------------------------------------------------------
	// Initialize the FilmOutputs
	//--------------------------------------------------------------------------

	set<string> outputNames;
	vector<string> outputKeys = cfg.GetAllNames("film.outputs.");
	for (vector<string>::const_iterator outputKey = outputKeys.begin(); outputKey != outputKeys.end(); ++outputKey) {
		const string &key = *outputKey;
		const size_t dot1 = key.find(".", string("film.outputs.").length());
		if (dot1 == string::npos)
			continue;

		// Extract the output type name
		const string outputName = Property::ExtractField(key, 2);
		if (outputName == "")
			throw runtime_error("Syntax error in film output definition: " + outputName);

		if (outputNames.count(outputName) > 0)
			continue;

		outputNames.insert(outputName);
		const string type = cfg.Get(Property("film.outputs." + outputName + ".type")("RGB_TONEMAPPED")).Get<string>();
		const string fileName = cfg.Get(Property("film.outputs." + outputName + ".filename")("image.png")).Get<string>();

		SDL_LOG("Film output definition: " << type << " [" << fileName << "]");

//		// Check if it is a supported file format
//		FREE_IMAGE_FORMAT fif = FREEIMAGE_GETFIFFROMFILENAME(FREEIMAGE_CONVFILENAME(fileName).c_str());
//		if (fif == FIF_UNKNOWN)
//			throw runtime_error("Unknown image format in film output: " + outputName);

		// HDR image or not
		bool hdrImage = false;
		string lowerFileName = boost::algorithm::to_lower_copy(fileName);
#if defined _MSC_VER
        string file_extension  = boost::filesystem::path(lowerFileName).extension().string();
#else
        string file_extension  = boost::filesystem::path(lowerFileName).extension().native();
#endif

		if (file_extension == ".exr" || file_extension == ".hdr")
			hdrImage = true;

		if (type == "RGB") {
			if (hdrImage)
				filmOutputs.Add(FilmOutputs::RGB, fileName);
			else
				throw runtime_error("Not tonemapped image can be saved only in HDR formats: " + outputName);
		} else if (type == "RGBA") {
			if (hdrImage) {
				film->AddChannel(Film::ALPHA);
				filmOutputs.Add(FilmOutputs::RGBA, fileName);
			} else
				throw runtime_error("Not tonemapped image can be saved only in HDR formats: " + outputName);
		} else if (type == "RGB_TONEMAPPED")
			filmOutputs.Add(FilmOutputs::RGB_TONEMAPPED, fileName);
		else if (type == "RGBA_TONEMAPPED") {
			film->AddChannel(Film::ALPHA);
			filmOutputs.Add(FilmOutputs::RGBA_TONEMAPPED, fileName);
		} else if (type == "ALPHA") {
			film->AddChannel(Film::ALPHA);
			filmOutputs.Add(FilmOutputs::ALPHA, fileName);
		} else if (type == "DEPTH") {
			if (hdrImage) {
				film->AddChannel(Film::DEPTH);
				filmOutputs.Add(FilmOutputs::DEPTH, fileName);
			} else
				throw runtime_error("Depth image can be saved only in HDR formats: " + outputName);
		} else if (type == "POSITION") {
			if (hdrImage) {
				film->AddChannel(Film::DEPTH);
				film->AddChannel(Film::POSITION);
				filmOutputs.Add(FilmOutputs::POSITION, fileName);
			} else
				throw runtime_error("Position image can be saved only in HDR formats: " + outputName);
		} else if (type == "GEOMETRY_NORMAL") {
			if (hdrImage) {
				film->AddChannel(Film::DEPTH);
				film->AddChannel(Film::GEOMETRY_NORMAL);
				filmOutputs.Add(FilmOutputs::GEOMETRY_NORMAL, fileName);
			} else
				throw runtime_error("Geometry normal image can be saved only in HDR formats: " + outputName);
		} else if (type == "SHADING_NORMAL") {
			if (hdrImage) {
				film->AddChannel(Film::DEPTH);
				film->AddChannel(Film::SHADING_NORMAL);
				filmOutputs.Add(FilmOutputs::SHADING_NORMAL, fileName);
			} else
				throw runtime_error("Shading normal image can be saved only in HDR formats: " + outputName);
		} else if (type == "MATERIAL_ID") {
			if (!hdrImage) {
				film->AddChannel(Film::DEPTH);
				film->AddChannel(Film::MATERIAL_ID);
				filmOutputs.Add(FilmOutputs::MATERIAL_ID, fileName);
			} else
				throw runtime_error("Material ID image can be saved only in non HDR formats: " + outputName);
		} else if (type == "DIRECT_DIFFUSE") {
			if (hdrImage) {
				film->AddChannel(Film::DIRECT_DIFFUSE);
				filmOutputs.Add(FilmOutputs::DIRECT_DIFFUSE, fileName);
			} else
				throw runtime_error("Direct diffuse image can be saved only in HDR formats: " + outputName);
		} else if (type == "DIRECT_GLOSSY") {
			if (hdrImage) {
				film->AddChannel(Film::DIRECT_GLOSSY);
				filmOutputs.Add(FilmOutputs::DIRECT_GLOSSY, fileName);
			} else
				throw runtime_error("Direct glossy image can be saved only in HDR formats: " + outputName);
		} else if (type == "EMISSION") {
			if (hdrImage) {
				film->AddChannel(Film::EMISSION);
				filmOutputs.Add(FilmOutputs::EMISSION, fileName);
			} else
				throw runtime_error("Emission image can be saved only in HDR formats: " + outputName);
		} else if (type == "INDIRECT_DIFFUSE") {
			if (hdrImage) {
				film->AddChannel(Film::INDIRECT_DIFFUSE);
				filmOutputs.Add(FilmOutputs::INDIRECT_DIFFUSE, fileName);
			} else
				throw runtime_error("Indirect diffuse image can be saved only in HDR formats: " + outputName);
		} else if (type == "INDIRECT_GLOSSY") {
			if (hdrImage) {
				film->AddChannel(Film::INDIRECT_GLOSSY);
				filmOutputs.Add(FilmOutputs::INDIRECT_GLOSSY, fileName);
			} else
				throw runtime_error("Indirect glossy image can be saved only in HDR formats: " + outputName);
		} else if (type == "INDIRECT_SPECULAR") {
			if (hdrImage) {
				film->AddChannel(Film::INDIRECT_SPECULAR);
				filmOutputs.Add(FilmOutputs::INDIRECT_SPECULAR, fileName);
			} else
				throw runtime_error("Indirect specular image can be saved only in HDR formats: " + outputName);
		} else if (type == "MATERIAL_ID_MASK") {
			const u_int materialID = cfg.Get(Property("film.outputs." + outputName + ".id")(255)).Get<u_int>();
			Properties prop;
			prop.Set(Property("id")(materialID));

			film->AddChannel(Film::MATERIAL_ID);
			film->AddChannel(Film::MATERIAL_ID_MASK, &prop);
			filmOutputs.Add(FilmOutputs::MATERIAL_ID_MASK, fileName, &prop);
		} else if (type == "DIRECT_SHADOW_MASK") {
			film->AddChannel(Film::DIRECT_SHADOW_MASK);
			filmOutputs.Add(FilmOutputs::DIRECT_SHADOW_MASK, fileName);
		} else if (type == "INDIRECT_SHADOW_MASK") {
			film->AddChannel(Film::INDIRECT_SHADOW_MASK);
			filmOutputs.Add(FilmOutputs::INDIRECT_SHADOW_MASK, fileName);
		} else if (type == "RADIANCE_GROUP") {
			const u_int lightID = cfg.Get(Property("film.outputs." + outputName + ".id")(0)).Get<u_int>();
			Properties prop;
			prop.Set(Property("id")(lightID));

			filmOutputs.Add(FilmOutputs::RADIANCE_GROUP, fileName, &prop);
		} else if (type == "UV") {
			film->AddChannel(Film::DEPTH);
			film->AddChannel(Film::UV);
			filmOutputs.Add(FilmOutputs::UV, fileName);
		} else if (type == "RAYCOUNT") {
			film->AddChannel(Film::RAYCOUNT);
			filmOutputs.Add(FilmOutputs::RAYCOUNT, fileName);
		} else if (type == "BY_MATERIAL_ID") {
			const u_int materialID = cfg.Get(Property("film.outputs." + outputName + ".id")(255)).Get<u_int>();
			Properties prop;
			prop.Set(Property("id")(materialID));

			film->AddChannel(Film::MATERIAL_ID);
			film->AddChannel(Film::BY_MATERIAL_ID, &prop);
			filmOutputs.Add(FilmOutputs::BY_MATERIAL_ID, fileName, &prop);
		} else if (type == "IRRADIANCE") {
			film->AddChannel(Film::IRRADIANCE);
			filmOutputs.Add(FilmOutputs::IRRADIANCE, fileName);
		} else
			throw runtime_error("Unknown type in film output: " + type);
	}

	// For compatibility with the past
	if (cfg.IsDefined("image.filename")) {
		SLG_LOG("WARNING: deprecated property image.filename");
		filmOutputs.Add(film->HasChannel(Film::ALPHA) ? FilmOutputs::RGBA_TONEMAPPED : FilmOutputs::RGB_TONEMAPPED,
				cfg.Get(Property("image.filename")("image.png")).Get<string>());
	}

	// Default setting
	if (filmOutputs.GetCount() == 0)
		filmOutputs.Add(FilmOutputs::RGB_TONEMAPPED, "image.png");

	return film.release();
}

Sampler *RenderConfig::AllocSampler(RandomGenerator *rndGen, Film *film,
		double *metropolisSharedTotalLuminance, double *metropolisSharedSampleCount) const {
	const SamplerType samplerType = Sampler::String2SamplerType(GetProperty("sampler.type").Get<string>());
	switch (samplerType) {
		case RANDOM:
			return new RandomSampler(rndGen, film);
		case METROPOLIS: {
			const float rate = GetProperty("sampler.metropolis.largesteprate").Get<float>();
			const float reject = GetProperty("sampler.metropolis.maxconsecutivereject").Get<float>();
			const float mutationrate = GetProperty("sampler.metropolis.imagemutationrate").Get<float>();

			return new MetropolisSampler(rndGen, film, reject, rate, mutationrate,
					metropolisSharedTotalLuminance, metropolisSharedSampleCount);
		}
		case SOBOL:
			return new SobolSampler(rndGen, film);
		default:
			throw runtime_error("Unknown sampler.type: " + boost::lexical_cast<string>(samplerType));
	}
}

RenderEngine *RenderConfig::AllocRenderEngine(Film *film, boost::mutex *filmMutex) const {
	const RenderEngineType renderEngineType = RenderEngine::String2RenderEngineType(
		GetProperty("renderengine.type").Get<string>());

	switch (renderEngineType) {
		case LIGHTCPU:
			return new LightCPURenderEngine(this, film, filmMutex);
		case PATHOCL:
#ifndef LUXRAYS_DISABLE_OPENCL
			return new PathOCLRenderEngine(this, film, filmMutex);
#else
			SLG_LOG("OpenCL unavailable, falling back to CPU rendering");
#endif
		case PATHCPU:
			return new PathCPURenderEngine(this, film, filmMutex);
		case BIDIRCPU:
			return new BiDirCPURenderEngine(this, film, filmMutex);
		case BIDIRVMCPU:
			return new BiDirVMCPURenderEngine(this, film, filmMutex);
		case FILESAVER:
			return new FileSaverRenderEngine(this, film, filmMutex);
		case RTPATHOCL:
#ifndef LUXRAYS_DISABLE_OPENCL
			return new RTPathOCLRenderEngine(this, film, filmMutex);
#else
			SLG_LOG("OpenCL unavailable, falling back to CPU rendering");
			return new PathCPURenderEngine(this, film, filmMutex);
#endif
		case BIASPATHCPU:
			return new BiasPathCPURenderEngine(this, film, filmMutex);
		case BIASPATHOCL:
#ifndef LUXRAYS_DISABLE_OPENCL
			return new BiasPathOCLRenderEngine(this, film, filmMutex);
#else
			SLG_LOG("OpenCL unavailable, falling back to CPU rendering");
			return new BiasPathCPURenderEngine(this, film, filmMutex);
#endif
		case RTBIASPATHOCL:
#ifndef LUXRAYS_DISABLE_OPENCL
			return new RTBiasPathOCLRenderEngine(this, film, filmMutex);
#else
			SLG_LOG("OpenCL unavailable, falling back to CPU rendering");
			return new BiasPathCPURenderEngine(this, film, filmMutex);
#endif
		default:
			throw runtime_error("Unknown render engine type: " + boost::lexical_cast<string>(renderEngineType));
	}
}


text:
using Sakuno.ING.Game.Json.Converters;
using System.Text.Json.Serialization;

namespace Sakuno.ING.Game.Models.MasterData
{
#nullable disable
    public sealed class RawMapArea : IIdentifiable<MapAreaId>
    {
        [JsonPropertyName("api_id")]
        public MapAreaId Id { get; set; }
        [JsonPropertyName("api_name")]
        public string Name { get; set; }
        [JsonPropertyName("api_type")]
        [JsonConverter(typeof(IntToBooleanConverter))]
        public bool IsEventArea { get; set; }
    }
#nullable enable
}


text:
package org.jdbx.test;

import org.jdbx.JdbxException;
import org.jdbx.MultiStmt;
import org.jdbx.StaticStmt;
import org.junit.Test;

public class MultiStmtTest extends JdbxTest
{
	@Test public void test() throws JdbxException
	{
		StaticStmt staticStmt;
		try (MultiStmt mstmt = new MultiStmt(con()))
		{
			assertSame(mstmt.getConnection(), con());

			assertEquals(0, mstmt.size());
			staticStmt = mstmt.newStaticStmt();
			assertEquals(1, mstmt.size());
			mstmt.closeStmts();
			assertEquals(0, mstmt.size());

			staticStmt = mstmt.newStaticStmt();
		}

		assertTrue(staticStmt.isClosed());
	}
}


text:
#pragma once
#include <aws/transcribe/TranscribeService_EXPORTS.h>
#include <aws/transcribe/model/MedicalTranscriptionJob.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace TranscribeService
{
namespace Model
{
  class AWS_TRANSCRIBESERVICE_API GetMedicalTranscriptionJobResult
  {
  public:
    GetMedicalTranscriptionJobResult();
    GetMedicalTranscriptionJobResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    GetMedicalTranscriptionJobResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
An object that contains the results of the medical transcription job.

     */
    inline const MedicalTranscriptionJob& GetMedicalTranscriptionJob() const{ return m_medicalTranscriptionJob; }

    /**
     *
An object that contains the results of the medical transcription job.

     */
    inline void SetMedicalTranscriptionJob(const MedicalTranscriptionJob& value) { m_medicalTranscriptionJob = value; }

    /**
     *
An object that contains the results of the medical transcription job.

     */
    inline void SetMedicalTranscriptionJob(MedicalTranscriptionJob&& value) { m_medicalTranscriptionJob = std::move(value); }

    /**
     *
An object that contains the results of the medical transcription job.

     */
    inline GetMedicalTranscriptionJobResult& WithMedicalTranscriptionJob(const MedicalTranscriptionJob& value) { SetMedicalTranscriptionJob(value); return *this;}

    /**
     *
An object that contains the results of the medical transcription job.

     */
    inline GetMedicalTranscriptionJobResult& WithMedicalTranscriptionJob(MedicalTranscriptionJob&& value) { SetMedicalTranscriptionJob(std::move(value)); return *this;}

  private:

    MedicalTranscriptionJob m_medicalTranscriptionJob;
  };

} // namespace Model
} // namespace TranscribeService
} // namespace Aws


text:
'''Adding support to termcolor.
Failures and errors are red and sucessful is green.

>>> SupportToTermcolor.run()
False
>>> colored_output2 = """Story: Support to termcolor
...   As a pyhistorian commiter
...   I want to have support to colored output
...   So that the output becomes more readable
...
...   Scenario 1: Green color
... """+green_output+"""
...   Scenario 2: Red color
... """+red_output+"""
...   Scenario 3: Green and red colors
... """+green_and_red_output+"""
...   Ran 3 scenarios with 3 failures, 0 errors and 0 pending steps
... """
>>> checker.check_output(colored_output2, output.getvalue(), doctest.ELLIPSIS)
True
'''

from pyhistorian import *
from pyhistorian.output import colored
from should_dsl import *
from cStringIO import StringIO
import os
import doctest

HERE = os.path.dirname(__file__) + '/colors.py'
checker = doctest.OutputChecker()

class GreenColor(Scenario):
    @Given('I want my output colored and it pass')
    def nothing(self):
        pass

    @Then('I have green messages')
    def nothing2(self):
        pass

class RedColor(Scenario):
    @Given('I want my output colored and it fails')
    def fail1(self):
         'this scenario' |should_be| 'red colored'

    @Then('I have red messages')
    def fail2(self):
        'this fail color' |should_be| 'red'

class GreenAndRedColors(Scenario):
   @Given('I want my output colored (green and red)')
   def nothing(self):
       pass

   @Then('I have green message')
   def green_message(self):
       pass

   @Then('I have red message')
   def red_message(self):
       'this step' |should_be| 'red'

def red_colored(text):
    return colored(text, color='red')

def green_colored(text):
    return colored(text, color='green')

output = StringIO()

class SupportToTermcolor(Story):
    """As a pyhistorian commiter
       I want to have support to colored output
       So that the output becomes more readable"""
    output = output
    colored = True
    scenarios = (GreenColor, RedColor, GreenAndRedColors)

green_output = green_colored('\
    Given I want my output colored and it pass   ... OK\n')+ \
  green_colored('\
    Then I have green messages   ... OK\n')

red_output = red_colored('\
    Given I want my output colored and it fails   ... FAIL\n')+ \
  red_colored('\
    Then I have red messages   ... FAIL\n') +\
  red_colored('\n  Failures:\n')+\
  red_colored("""    File "%(here)s", line ..., in fail1
      'this scenario' |should_be| 'red colored'
    ...
    ShouldNotSatisfied: 'this scenario' is not 'red colored'

""" % {'here': HERE})+\
  red_colored("""    File "%(here)s", line ..., in fail2
      'this fail color' |should_be| 'red'
    ...
    ShouldNotSatisfied: 'this fail color' is not 'red'

""" % {'here': HERE})
green_and_red_output = green_colored('\
    Given I want my output colored (green and red)   ... OK\n')+\
  green_colored('\
    Then I have green message   ... OK\n') + \
  red_colored('\
    And I have red message   ... FAIL\n') +\
  red_colored('\n  Failures:\n') + \
  red_colored("""    File "%(here)s", line ..., in red_message
      'this step' |should_be| 'red'
    ...
    ShouldNotSatisfied: 'this step' is not 'red'

""" % {'here': HERE})