text:
"""
Manage Apache Confs

.. versionadded:: 2016.3.0

Enable and disable apache confs.

.. code-block:: yaml

    Enable security conf:
      apache_conf.enabled:
        - name: security

    Disable security conf:
      apache_conf.disabled:
        - name: security
"""

import salt.utils.path

def __virtual__():
    """
    Only load if a2enconf is available.
    """
    if "apache.a2enconf" in __salt__ and salt.utils.path.which("a2enconf"):
        return "apache_conf"
    return (False, "apache module could not be loaded")

def enabled(name):
    """
    Ensure an Apache conf is enabled.

    name
        Name of the Apache conf
    """
    ret = {"name": name, "result": True, "comment": "", "changes": {}}

    is_enabled = __salt__["apache.check_conf_enabled"](name)
    if not is_enabled:
        if __opts__["test"]:
            msg = "Apache conf {} is set to be enabled.".format(name)
            ret["comment"] = msg
            ret["changes"]["old"] = None
            ret["changes"]["new"] = name
            ret["result"] = None
            return ret
        status = __salt__["apache.a2enconf"](name)["Status"]
        if isinstance(status, str) and "enabled" in status:
            ret["result"] = True
            ret["changes"]["old"] = None
            ret["changes"]["new"] = name
        else:
            ret["result"] = False
            ret["comment"] = "Failed to enable {} Apache conf".format(name)
            if isinstance(status, str):
                ret["comment"] = ret["comment"] + " ({})".format(status)
            return ret
    else:
        ret["comment"] = "{} already enabled.".format(name)
    return ret

def disabled(name):
    """
    Ensure an Apache conf is disabled.

    name
        Name of the Apache conf
    """
    ret = {"name": name, "result": True, "comment": "", "changes": {}}

    is_enabled = __salt__["apache.check_conf_enabled"](name)
    if is_enabled:
        if __opts__["test"]:
            msg = "Apache conf {} is set to be disabled.".format(name)
            ret["comment"] = msg
            ret["changes"]["old"] = name
            ret["changes"]["new"] = None
            ret["result"] = None
            return ret
        status = __salt__["apache.a2disconf"](name)["Status"]
        if isinstance(status, str) and "disabled" in status:
            ret["result"] = True
            ret["changes"]["old"] = name
            ret["changes"]["new"] = None
        else:
            ret["result"] = False
            ret["comment"] = "Failed to disable {} Apache conf".format(name)
            if isinstance(status, str):
                ret["comment"] = ret["comment"] + " ({})".format(status)
            return ret
    else:
        ret["comment"] = "{} already disabled.".format(name)
    return ret


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="10"
        android:title="@string/action_graph_settings"
        app:showAsAction="never" />

    <!--<item
        android:id="@+id/full_screen_live_graph"
        android:title="Full Screen"
        app:showAsAction="collapseActionView"
        android:orderInCategory="100"
        />-->

    <item
        android:id="@+id/action_reset_zoom_live_graph"
        android:orderInCategory="200"
        android:title="@string/action_reset_zoom"
        app:showAsAction="never" />

</menu>

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JavaScript Engine testing utilities.
 *
 * The Initial Developer of the Original Code is
 * Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Jason Orendorff <jorendorff@mozilla.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var gTestfile = 'simple-tree.js';
//-----------------------------------------------------------------------------

var summary = "Create a tree of threads";

var N = 50;  // number of threads to create

printStatus (summary);

function range(start, stop) {
  var a = [];
  for (var i = start; i < stop; i++)
    a.push(i);
  return a;
}

function tree(start, stop) {
  sleep(0.001);

  if (start >= stop)
    return [];
  else if (start + 1 >= stop)
    return [start];

  sleep(0.001);

  let mid = start + Math.floor((stop - start) / 2);
  let halves = scatter([function () { return tree(start, mid); },
                        function () { return tree(mid, stop); }]);
  sleep(0.001);
  return Array.prototype.concat.apply([], halves);
}

var expect;
var actual;

if (typeof scatter == 'undefined' || typeof sleep == 'undefined') {
  print('Test skipped. scatter or sleep not defined.');
  expect = actual = 'Test skipped.';
} else {
  expect = range(0, N).toSource();
  actual = tree(0, N).toSource();
}

reportCompare(expect, actual, summary);


text:
require_relative '../../bundler_setup'
require 'VMwareWebService/MiqVimBroker'

MAX_CLIENT        = 6
BROKER_SERVER     = "MiqVimBrokerServer.rb"
BROKER_SERVER_LOG = "./broker.log"
BROKER_SERVER_CMD = "ruby #{BROKER_SERVER} > #{BROKER_SERVER_LOG} 2>&1 &"

TESTS = [
  "MiqVimBrokerClient.rb",
  "browserTest.rb",
  "brokerObjCountTest.rb",
  "logTest.rb",
  "virtualDiskPerf.rb",
  "virtualApp.rb",
  "selectionSpecVimTest.rb",
  "MiqVimPerfTest.rb"
]

ERROR_STRINGS = [
  "VimSyncDebug - Locking Thread has terminated:",
  "VimSyncDebug - Lock timeout:",
  "VimSyncDebug - Watchdog ERROR:"
]

def client_count
  `ps -o command | grep ".rb" | wc -l`.to_i - 4
end

def get_broker_pid
  rva = `ps -Ao pid,command | grep #{BROKER_SERVER}`.split("\n")
  ri = rva.find_index { |ai|  ai["ruby #{BROKER_SERVER}"] }
  raise "Could not determine server's PID." unless ri
  rva[ri].split(" ")[0]
end

def error_count(str = "ERROR")
  `grep "#{str}" #{BROKER_SERVER_LOG} | wc -l`.to_i
end

def print_errors
  ERROR_STRINGS.each do |estr|
    if (c = error_count(estr)) > 0
      puts "\t\t#{estr} #{c}"
    end
  end
end

run            = true
broker_pid     = nil

trap(:INT) do
  puts "#{$0}: Shutting down..."
  run = false
end

#
# Start the VIM broker server.
#
begin

  if `ps -Ao command | grep #{BROKER_SERVER} | wc -l`.to_i <= 2
    system(BROKER_SERVER_CMD)
    raise "*** Command \"#{BROKER_SERVER_CMD}\" failed: status = #{$?.exitstatus}" unless $? == 0
    broker_pid = get_broker_pid
    puts "VIM broker started: PID = #{broker_pid}"
    sleep 5
  else
    #
    # If the broker is already running, use that instance.
    #
    puts "Broker server \"#{BROKER_SERVER}\" already running."
  end

rescue => err
  $stderr.puts "Could not start the VIM broker: #{BROKER_SERVER}"
  puts err.to_s
  exit(1)
end

begin

  broker = MiqVimBroker.new(:client)
  unless broker.serverAlive?
    puts "Broker server isn't running"
    exit(1)
  end

  srand Time.now.to_i

  while run
    ec = error_count
    print "#{Time.now} - Clients: #{client_count} [ERRORS = #{ec}]"
    if client_count < MAX_CLIENT
      cmd = TESTS[rand(TESTS.length)]
      puts "\t** Starting: #{cmd}"
      `ruby #{cmd} > /dev/null 2>&1 &`
    else
      puts "\t** Waiting..."
    end
    print_errors if ec > 0
    sleep 1
  end

  #
  # Kill the broker, only if we started it.
  #
  puts
  if broker_pid
    puts "Killing VIM broker server #{BROKER_SERVER}: PID = #{broker_pid}"
    system("kill -9 #{broker_pid}")
  else
    puts "Pre-existing broker instance continuing to run."
  end

  exit(0)

rescue => err
  puts err.to_s
  puts err.class.to_s
  puts err.backtrace.join("\n")
  exit(1)
end


text:
/**
 * final startup code which needs all components present
 *
 */
(function () {
    'use strict';
    CPM.namespace('nodes.usermanagement');

    (function (usermanagement, core) {

    })(CPM.nodes.usermanagement, CPM.core);

})();


text:
package org.oscm.app.vmware.business.balancer;

import java.util.Collection;

import org.apache.commons.configuration.HierarchicalConfiguration;
import org.oscm.app.v2_0.exceptions.APPlatformException;
import org.oscm.app.vmware.business.VMPropertyHandler;
import org.oscm.app.vmware.business.model.VMwareHost;
import org.oscm.app.vmware.i18n.Messages;

/**
 * Balancer implementation determining dynamically from vSphere the host with
 * the lowest number of VMs running on it.
 *
 * @author Oliver Petrovski
 *
 */
public class DynamicEquipartitionHostBalancer extends HostBalancer {

    @Override
    public void setConfiguration(HierarchicalConfiguration xmlConfig) {
        super.setConfiguration(xmlConfig);
    }

    @Override
    public VMwareHost next(VMPropertyHandler properties)
            throws APPlatformException {

        VMwareHost selectedHost = null;
        int minVM = Integer.MAX_VALUE;

        Collection<VMwareHost> hosts = inventory.getHosts();
        for (VMwareHost host : hosts) {
            int numVM = host.getAllocatedVMs();
            if (numVM < minVM) {
                selectedHost = host;
                minVM = numVM;
            }
        }

        if (selectedHost == null) {
            throw new APPlatformException(Messages.getAll("error_outof_host"));
        }

        return selectedHost;
    }
}


text:
<TITLE>Review for One-Eyed Jacks (1961)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

One-Eyed Jacks (1961)

reviewed by
Brian Koller

One-Eyed Jacks (1961)

Grade: 77

"One-Eyed Jacks" is famous for being Marlon
Brando's sole effort as director.  At first,
Stanley Kubrick was the director, but a clash
of egos led to his abandoning the project.
Brando extended the shooting schedule from
sixty days to six months, and turned in a
four hour film.  Studio executives had the
film cut to 141 minutes, and the expensive
film lost money when finally released.

Who knows whether Kubrick's version would
have been much better.  Certainly Brando's
character would have been less heroic, and
his various romances would likely have been
downplayed.  The good news is that Brando's
version of "One-Eyed Jacks" is entertaining,
interesting and original.  It is also
clearly better than "Spartacus", the 1960
Kubrick-directed epic.

The story begins in Mexico in the year 1880.
Karl Malden and Brando are bank robbers
who are being tracked by Federales.  They
have only one horse, which can hold only
one rider.  Malden leaves Brando with promises
of returning with another horse.  He doesn't,
and Brando is captured, spending five years
in a squalid prison.

Brando escapes with Larry Duran, and the two
link up with bad-tempered bank robbers
Ben Johnson and Sam Gilman.  Brando learns
that Malden is now the affable sheriff of
Monterey, California.  The gang rides 900
miles (!) to Monterey, to rob its bank and
for Brando to exact revenge on Malden.
Various misadventures follow: Brando seduces
Malden's adopted daughter Pina Pellicer, kills
troublemaker Timothy Carey in self-defense,
and is whipped and jailed by Malden.  Finally,
there is an inevitable showdown between
Brando and Malden.

Brando is stone-faced and tight-lipped
throughout, but he remains charismatic and
likeable.  Slim Pickens has a great supporting
role as Malden's brutal deputy.  Malden also
gives a fine performance.

kollers@mpsi.net
http://members.tripod.com/~Brian_Koller/movies.html

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="black">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/splash/splash-icon.png">
<link rel="apple-touch-startup-image" href="images/splash/splash-screen.png" 			media="screen and (max-device-width: 320px)" />
<link rel="apple-touch-startup-image" href="images/splash/splash-screen@2x.png" 		media="(max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2)" />
<link rel="apple-touch-startup-image" sizes="640x1096" href="images/splash/splash-screen@3x.png" />
<link rel="apple-touch-startup-image" sizes="1024x748" href="images/splash/splash-screen-ipad-landscape" media="screen and (min-device-width : 481px) and (max-device-width : 1024px) and (orientation : landscape)" />
<link rel="apple-touch-startup-image" sizes="768x1004" href="images/splash/splash-screen-ipad-portrait.png" media="screen and (min-device-width : 481px) and (max-device-width : 1024px) and (orientation : portrait)" />
<link rel="apple-touch-startup-image" sizes="1536x2008" href="images/splash/splash-screen-ipad-portrait-retina.png"   media="(device-width: 768px)	and (orientation: portrait)	and (-webkit-device-pixel-ratio: 2)"/>
<link rel="apple-touch-startup-image" sizes="1496x2048" href="images/splash/splash-screen-ipad-landscape-retina.png"   media="(device-width: 768px)	and (orientation: landscape)	and (-webkit-device-pixel-ratio: 2)"/>

<title>FISDMobile - Version 1.0</title>

<link href="styles/style.css"     		rel="stylesheet" type="text/css">
<link href="styles/framework.css" 		rel="stylesheet" type="text/css">
<link href="styles/owl.carousel.css" 	 rel="stylesheet" type="text/css">
<link href="styles/owl.theme.css" 		rel="stylesheet" type="text/css">
<link href="styles/swipebox.css"		 rel="stylesheet" type="text/css">
<link href="styles/colorbox.css"		 rel="stylesheet" type="text/css">

			Loading the content...
            Loading depends on your connection speed!

Navigation

                    Home

                    News

                    Media

                    Contact

                    Close

contact

Get in touch!

                    we would love to hear from you

Send us an email!

Use this form to send us a message.

Message Sent

                                x

Your message has been successfully sent. Please allow up to 48 hours for a reply! Thank you!

                        <form action="php/contact.php" method="post" class="contactForm" id="contactForm">
                            <fieldset>

Name required

Email required

Invalid Email

Message field is empty

                                    Name:(required)
                                    <input type="text" name="contactNameField" value="" class="contactField requiredField" id="contactNameField"/>

                                    Email: (required)
                                    <input type="text" name="contactEmailField" value="" class="contactField requiredField requiredEmailField" id="contactEmailField"/>

                                    Message: (required)
                                    <textarea name="contactMessageTextarea" class="contactTextarea requiredField" id="contactMessageTextarea"></textarea>

                                    <input type="submit" class="buttonWrap button button-green contactSubmitButton" id="contactSubmitButton" value="SUBMIT" data-formId="contactForm"/>

                            </fieldset>
                        </form>

Contact Information

                        Administrative Building

                        302 Laurel Dr

                        Friendswood, TX 77546

                        Friendswood High School

                        702 Greenbriar Dr

                        Friendswood, TX 77546

                        Friendswood Junior High

                        702 Greenbriar Dr

                        Friendswood, TX 77546

                        Westwood-Bales Elementary

                        211 Stadium Ln

                        Friendswood, TX 77546

                        Windsong Intermediate

                        2100 W Parkwood Ave

                        Friendswood, TX 77546

                        Cline Elementary

                        505 Briarmeadow Ave

                        Friendswood, TX 77546

                        Phone: (281) 482-1267
                        Facebook: FriendswoodISD
                        Twitter: @friendswoodisd

Copyright 2014
 All rights reserved


text:
package org.dasein.persist.attributes;

import java.sql.SQLException;
import java.sql.Types;
import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import org.dasein.attributes.AttributeMap;
import org.dasein.attributes.DataTypeFactory;
import org.dasein.attributes.DataTypeMap;
import org.dasein.persist.Execution;
import org.dasein.persist.PersistenceException;
import org.dasein.persist.Transaction;
import org.dasein.util.Translator;
import org.apache.log4j.Logger;

public class CreateAttributes extends Execution {
    private static final Logger logger = Logger.getLogger(CreateAttributes.class);

    static private final int TYPE_CLASS  = 1;
    static private final int TYPE_ID     = 2;
    static private final int OWNER_CLASS = 3;
    static private final int OWNER_ID    = 4;
    static private final int NAME        = 5;
    static private final int LANGUAGE    = 6;
    static private final int COUNTRY     = 7;
    static private final int VALUE       = 8;
    static private final int ORDER       = 9;

    private String sql = null;

    public synchronized String getStatement() throws SQLException {
        if( sql == null ) {
        	StringBuilder str = new StringBuilder();

            str.append("INSERT INTO ");
            str.append(getIdentifier(LoadAttributes.ATTRIBUTE_TABLE));
            str.append(" ( ");
            str.append(getIdentifier("type_class"));
            str.append(", ");
            str.append(getIdentifier("type_id"));
            str.append(", ");
            str.append(getIdentifier("owner_class"));
            str.append(", ");
            str.append(getIdentifier("owner_id"));
            str.append(", ");
            str.append(getIdentifier("name"));
            str.append(", ");
            str.append(getIdentifier("language"));
            str.append(", ");
            str.append(getIdentifier("country"));
            str.append(", ");
            str.append(getIdentifier("text_value"));
            str.append(", ");
            str.append(getIdentifier("value_order"));
            str.append(" ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )");
            sql = str.toString();
        }
        return sql;
    }

    public Map<String, Object> run(Transaction xaction, Map<String,Object> params) throws PersistenceException, SQLException {
        AttributeMap attrs = (AttributeMap)params.get(AttributeDAO.ATTRIBUTES);
        DataTypeMap types = (DataTypeMap)params.get(AttributeDAO.TYPES);
        String ocls = (String)params.get(AttributeDAO.OWNER_CLASS);
        String oid = (String)params.get(AttributeDAO.OWNER_ID);
        String tcls = (String)params.get(AttributeDAO.TYPE_CLASS);
        String tid = (String)params.get(AttributeDAO.TYPE_ID);

        if( tid == null ) {
            tid = "";
        }
        for( Map.Entry<String,Object> entry : attrs.entrySet() ) {
            String attr = entry.getKey();
            Object val = entry.getValue();

            if( val instanceof Collection ) {
                int i = 1;

                for( Object ob : (Collection<?>)val ) {
                    if( ob != null ) {
                        save(types, tcls, tid, ocls, oid, attr, ob, i++);
                    }
                }
            }
            else {
                if( val != null ) {
                    save(types, tcls, tid, ocls, oid, attr, val, 1);
                }
            }
        }
        return null;
    }

    private void save(DataTypeMap types, String tcls, String tid, String ocls, String oid, String attr, Object val, int order) throws PersistenceException, SQLException {

        if (types == null || !types.containsKey(attr)) {
            logger.warn("Owner Class: " +  ocls + " Owner ID: " + oid + " Attribute: " + attr + " doesn't have a type! Please check the types for Type Class: " + tcls + " Type ID: " + tid);
            return;
        }

        DataTypeFactory<?> factory = types.get(attr).getFactory();
        if( val instanceof Translator ) {
            Translator<?> trans = (Translator<?>)val;
            Iterator<String> languages = trans.languages();

            while( languages.hasNext() ) {
                String lang = languages.next();
                Iterator<String> countries;
                boolean nullctry = false;

                countries = trans.countries(lang);
                while( countries.hasNext() ) {
                    String ctry = countries.next();
                    Locale loc;
                    Object ob;

                    if( ctry == null || ctry.equals("") ) {
                        if( nullctry ) {
                            continue;
                        }
                        loc = new Locale(lang);
                        nullctry = true;
                        ctry = null;
                    }
                    else {
                        loc = new Locale(lang, ctry);
                    }
                    ob = trans.getExactTranslation(loc).getData();
                    if( ob == null && !nullctry ) {
                        loc = new Locale(lang);
                        ob = trans.getExactTranslation(loc).getData();
                        nullctry = true;
                    }
                    save(tcls, tid, ocls, oid, attr, lang, ctry, order, factory.getStringValue(ob));
                }
            }
        }
        else {
            save(tcls, tid, ocls, oid, attr, null, null, order, factory.getStringValue(val));
        }
    }

    private void save(String tcls, String tid, String ocls, String oid, String att, String lang, String ctry, int order, String val) throws PersistenceException, SQLException {
        statement.setString(TYPE_CLASS, tcls);
        statement.setString(TYPE_ID, tid);
        statement.setString(OWNER_CLASS, ocls);
        statement.setString(OWNER_ID, oid);
        statement.setString(NAME, att);
        if( lang == null ) {
            statement.setNull(LANGUAGE, Types.VARCHAR);
        }
        else {
            statement.setString(LANGUAGE, lang);
        }
        if( ctry == null ) {
            statement.setNull(COUNTRY, Types.VARCHAR);
        }
        else {
            statement.setString(COUNTRY, ctry);
        }
        statement.setString(VALUE, val);
        statement.setInt(ORDER, order);
        statement.executeUpdate();
        statement.clearParameters();
    }
}


text:
using System.Collections.Generic;

namespace ObservableEntitiesLightTracking.ComponentModel
{
    /// <summary>
    /// Defines members that data entity classes can implement to provide support for receiving validation errors with severity levels from an external validator.
    /// </summary>
    public interface IWriteDataErrorInfo
    {
        /// <summary>
        /// Passes a collection of <see cref="ValidationResultWithSeverityLevel" /> to the specified object.
        /// </summary>
        /// <param name="validationResults">The validation results.</param>
        void AddValidationErrors(ICollection<ValidationResultWithSeverityLevel> validationResults);

        void AddPropertyValidationErrors(string propertyName, ICollection<ValidationResultWithSeverityLevel> validationResults);
    }
}


text:
/*!
	\file Iterator.h
	\date Tuesday March 12, 2009
	\author Gregory Diamos
	\brief Header file for Iterator classes and concepts
*/

#ifndef ITERATOR_H_INCLUDED
#define ITERATOR_H_INCLUDED

#include <iterator>

namespace hydrazine
{

	/*!
		\brief Define typedefs for iterator classes
	*/
	template< typename Category, typename T, typename Distance,
		typename Pointer, typename Reference >
	struct Iterator
	{
		//! Concept
		typedef Category iterator_category;
		//! The type "pointed to" by the iterator.
		typedef T value_type;
		//! Distance between iterators is represented as this type.
		typedef Distance difference_type;
		//! This type represents a pointer-to-value_type.
		typedef Pointer pointer;
		//! This type represents a reference-to-value_type.
		typedef Reference reference;
	};

	/*!
		\brief A class for specializing pointer and reference types
	*/
	template< typename Pointer >
	struct IteratorTraits
	{
		typedef typename Pointer::iterator_category iterator_category;
		typedef typename Pointer::value_type value_type;
		typedef typename Pointer::difference_type difference_type;
		typedef typename Pointer::pointer pointer;
		typedef typename Pointer::reference reference;
	};

	template< typename T >
	struct IteratorTraits< T* >
	{
		typedef std::random_access_iterator_tag iterator_category;
		typedef T value_type;
		typedef ptrdiff_t difference_type;
		typedef T* pointer;
		typedef T& reference;
	};

	template< typename T >
	struct IteratorTraits< const T* >
	{
		typedef std::random_access_iterator_tag iterator_category;
		typedef T value_type;
		typedef ptrdiff_t difference_type;
		typedef const T* pointer;
		typedef const T& reference;
	};

	/*!
		\brief A generic iterator class wrapper for iterators derived from
			pointers.

		Container is here so that different iterator types get instantiated
		for containers using the same underlying pointer as in GCC-4.3.3
	*/
	template< typename Type, typename Container >
	class PointerIterator
	{
		protected:
			Type _current;

		public:
			typedef Type iterator_type;
			typedef typename IteratorTraits< Type >::iterator_category
				iterator_category;
			typedef typename IteratorTraits< Type >::value_type value_type;
			typedef typename IteratorTraits< Type >::difference_type
				difference_type;
			typedef typename IteratorTraits< Type >::pointer pointer;
			typedef typename IteratorTraits< Type >::reference reference;

		public:
			PointerIterator() : _current( Type() ) {}

			explicit PointerIterator( const Type& it ) : _current( it )
			{}

			template< typename _Assignee >
			PointerIterator( const PointerIterator< _Assignee,
				typename Container::type >& it ) : _current( it.base() )
			{

			}

			reference operator*() const
			{
				return *_current;
			}

			pointer operator->() const
			{
				return _current;
			}

			PointerIterator& operator++()
			{
				++_current;
				return *this;
			}

			PointerIterator operator++( int )
			{
				return PointerIterator( _current++ );
			}

			PointerIterator& operator--()
			{
				--_current;
				return *this;
			}

			PointerIterator operator--( int )
			{
				return PointerIterator( _current-- );
			}

			reference operator[]( const difference_type& n )
			{
				return _current[ n ];
			}

			PointerIterator& operator+=( const difference_type& n )
			{
				_current += n;
				return *this;
			}

			PointerIterator operator+( const difference_type& n )
			{
				return PointerIterator( _current + n );
			}

			PointerIterator& operator-=( const difference_type& n )
			{
				_current -= n;
				return *this;
			}

			PointerIterator operator-( const difference_type& n )
			{
				return PointerIterator( _current - n );
			}

			const Type& base() const
			{
				return _current;
			}

	};

	template<typename TypeL, typename TypeR, typename Container>
	inline bool operator==(const PointerIterator<TypeL, Container>& left,
		const PointerIterator<TypeR, Container>& right)
	{
		return left.base() == right.base();
	}

	template<typename Pointer, typename Container>
	inline bool operator==(const PointerIterator<Pointer, Container>& left,
		const PointerIterator<Pointer, Container>& right)
	{
		return left.base() == right.base();
	}

	template<typename TypeL, typename TypeR, typename Container>
	inline bool operator!=(const PointerIterator<TypeL, Container>& left,
		const PointerIterator<TypeR, Container>& right)
	{
		return left.base() != right.base();
	}

	template<typename Pointer, typename Container>
	inline bool operator!=(const PointerIterator<Pointer, Container>& left,
		const PointerIterator<Pointer, Container>& right)
	{
		return left.base() != right.base();
	}

	template<typename TypeL, typename TypeR, typename Container>
	inline bool operator<(const PointerIterator<TypeL, Container>& left,
		const PointerIterator<TypeR, Container>& right)
	{
		return left.base() < right.base();
	}

	template<typename Pointer, typename Container>
	inline bool operator<(const PointerIterator<Pointer, Container>& left,
		const PointerIterator<Pointer, Container>& right)
	{
		return left.base() < right.base();
	}

	template<typename TypeL, typename TypeR, typename Container>
	inline bool operator>(const PointerIterator<TypeL, Container>& left,
		const PointerIterator<TypeR, Container>& right)
	{
		return left.base() > right.base();
	}

	template<typename Pointer, typename Container>
	inline bool operator>(const PointerIterator<Pointer, Container>& left,
		const PointerIterator<Pointer, Container>& right)
	{
		return left.base() > right.base();
	}

	template<typename TypeL, typename TypeR, typename Container>
	inline bool operator<=(const PointerIterator<TypeL, Container>& left,
		const PointerIterator<TypeR, Container>& right)
	{
		return left.base() <= right.base();
	}

	template<typename Pointer, typename Container>
	inline bool operator<=(const PointerIterator<Pointer, Container>& left,
		const PointerIterator<Pointer, Container>& right)
	{
		return left.base() <= right.base();
	}

	template<typename TypeL, typename TypeR, typename Container>
	inline bool operator>=(const PointerIterator<TypeL, Container>& left,
		const PointerIterator<TypeR, Container>& right)
	{
		return left.base() >= right.base();
	}

	template<typename Pointer, typename Container>
	inline bool operator>=(const PointerIterator<Pointer, Container>& left,
		const PointerIterator<Pointer, Container>& right)
	{
		return left.base() >= right.base();
	}

	template<typename TypeL, typename TypeR, typename Container>
	inline typename PointerIterator<TypeL, Container>::difference_type
		operator-(const PointerIterator<TypeL, Container>& left,
		const PointerIterator<TypeR, Container>& right)
	{
		return left.base() - right.base();
	}

	template<typename Pointer, typename Container>
	inline typename PointerIterator<Pointer, Container>::difference_type
		operator-(const PointerIterator<Pointer, Container>& left,
		const PointerIterator<Pointer, Container>& right)
	{
		return left.base() - right.base();
	}

	template<typename Pointer, typename Container>
	inline PointerIterator<Pointer, Container>
		operator+(typename PointerIterator<Pointer, Container>::difference_type
		n, const PointerIterator<Pointer, Container>& it )
	{
		return PointerIterator<Pointer, Container>( it.base() + n );
	}

}

#endif


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Utilities for processing words within strings and nodes.

class WordUtils {
  constructor() {}

  /**
   * Searches through text starting at an index to find the next word's
   * start boundary.
   * @param {string|undefined} text The string to search through
   * @param {number} indexAfter The index into text at which to start
   *      searching.
   * @param {ParagraphUtils.NodeGroupItem} nodeGroupItem The node whose name we
   *      are searching through.
   * @return {number} The index of the next word's start
   */
  static getNextWordStart(text, indexAfter, nodeGroupItem) {
    if (nodeGroupItem.hasInlineText && nodeGroupItem.node.children.length > 0) {
      const node = ParagraphUtils.findInlineTextNodeByCharacterIndex(
          nodeGroupItem.node, indexAfter - nodeGroupItem.startChar);
      const startCharInParent = ParagraphUtils.getStartCharIndexInParent(node);
      for (var i = 0; i < node.wordStarts.length; i++) {
        if (node.wordStarts[i] + nodeGroupItem.startChar + startCharInParent <
            indexAfter) {
          continue;
        }
        return node.wordStarts[i] + nodeGroupItem.startChar + startCharInParent;
      }
      // Default: We are just off the edge of this node.
      return node.name.length + nodeGroupItem.startChar + startCharInParent;
    } else {
      // Try to parse using a regex, which is imperfect.
      // Fall back to the given index if we can't find a match.
      return WordUtils.nextWordHelper(
          text, indexAfter, WordUtils.WORD_START_REGEXP, indexAfter);
    }
  }

  /**
   * Searches through text starting at an index to find the next word's
   * end boundary.
   * @param {string|undefined} text The string to search through
   * @param {number} indexAfter The index into text at which to start
   *      searching.
   * @param {ParagraphUtils.NodeGroupItem} nodeGroupItem The node whose name we
   *      are searching through.
   * @return {number} The index of the next word's end
   */
  static getNextWordEnd(text, indexAfter, nodeGroupItem) {
    if (nodeGroupItem.hasInlineText && nodeGroupItem.node.children.length > 0) {
      const node = ParagraphUtils.findInlineTextNodeByCharacterIndex(
          nodeGroupItem.node, indexAfter - nodeGroupItem.startChar + 1);
      const startCharInParent = ParagraphUtils.getStartCharIndexInParent(node);
      for (var i = 0; i < node.wordEnds.length; i++) {
        if (node.wordEnds[i] + nodeGroupItem.startChar + startCharInParent - 1 <
            indexAfter) {
          continue;
        }
        const result =
            node.wordEnds[i] + nodeGroupItem.startChar + startCharInParent;
        return text.length > result ? result : text.length;
      }
      // Default.
      return text.length;
    } else {
      // Try to parse using a regex, which is imperfect.
      // Fall back to the full length of the text if we can't find a match.
      return WordUtils.nextWordHelper(
                 text, indexAfter, WordUtils.WORD_END_REGEXP, text.length - 1) +
          1;
    }
  }

  /**
   * Searches through text to find the first index of a regular expression
   * after a given starting index. Returns a default value if no match is
   * found.
   * @param {string|undefined} text The string to search through
   * @param {number} indexAfter The index at which to start searching
   * @param {RegExp} re A regular expression to search for
   * @param {number} defaultValue The default value to return if no
                       match is found.
   * @return {number} The index found by the regular expression, or -1
   *                    if none found.
   */
  static nextWordHelper(text, indexAfter, re, defaultValue) {
    if (text === undefined) {
      return defaultValue;
    }
    const result = re.exec(text.substr(indexAfter));
    if (result != null && result.length > 0) {
      return indexAfter + result.index;
    }
    return defaultValue;
  }
}

/**
 * Regular expression to find the start of the next word after a word boundary.
 * We cannot use \b\W to find the next word because it does not match many
 * unicode characters.
 * @type {RegExp}
 */
WordUtils.WORD_START_REGEXP = /\b\S/;

/**
 * Regular expression to find the end of the next word, which is followed by
 * whitespace. We cannot use \w\b to find the end of the previous word because
 * \w does not know about many unicode characters.
 * @type {RegExp}
 */
WordUtils.WORD_END_REGEXP = /\S\s/;


text:
define(['../../../dist/workerpool'], function(workerpool) {
  'use strict';

  var pool = workerpool.pool();

  return pool.exec(function(value) {
    return value + 1;
  }, [1]).then(function(results) {
    document.write('results: ' + results);

    pool.clear();
  });

});


text:
package br.com.transmetais.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.transmetais.bean.GrupoMaterial;
import br.com.transmetais.bean.Produto;
import br.com.transmetais.bean.RegraTributacao;
import br.com.transmetais.bean.UnidadeMedida;
import br.com.transmetais.dao.GrupoMaterialDAO;
import br.com.transmetais.dao.ProdutoDAO;
import br.com.transmetais.dao.UnidadeMedidaDAO;
import br.com.transmetais.dao.commons.DAOException;
import br.com.transmetais.dao.impl.BaseDeCalculoDaoImpl;
import br.com.transmetais.dao.impl.BaseDeCalculoSTDaoImpl;
import br.com.transmetais.dao.impl.CfopDaoImpl;
import br.com.transmetais.dao.impl.OrigemMercadoriaDaoImpl;
import br.com.transmetais.dao.impl.SituacaoTributariaDaoImpl;
import br.com.transmetais.dao.impl.TipoOperacaoDaoImpl;

import com.google.gson.Gson;

@Resource
@Path("/produto")
public class ProdutoController extends BaseController<Produto, ProdutoDAO>{

	private UnidadeMedidaDAO unidadeMedidaDao;
	private GrupoMaterialDAO grupoMaterialDao;
	private TipoOperacaoDaoImpl tipoOperacaoDao;
	private OrigemMercadoriaDaoImpl origemMercadoriaDao;
	private BaseDeCalculoDaoImpl baseDeCalculoDao;
	private BaseDeCalculoSTDaoImpl baseDeCalculoSTDao;
	private SituacaoTributariaDaoImpl situacaoTributariaDao;
	private CfopDaoImpl cfopDao;

	@Override
	protected void prePersistUpdate(Produto bean) {
	    for (RegraTributacao regra : bean.getRegrasTributacao()) {
			if(regra.getBaseCalculoST() != null
					&& regra.getBaseCalculoST().getId() == 0){
				regra.setBaseCalculoST(null);
			}
		}
	}
	@Override
	protected void initForm(Produto bean)  {
		try{
			List<UnidadeMedida> unidadesMedidas = unidadeMedidaDao.findAll();
			result.include("unidadesMedidas",unidadesMedidas);

			List<GrupoMaterial> grupos = grupoMaterialDao.findAll();
			result.include("grupos",grupos);

			Gson gson = new Gson();
			String json = gson.toJson(tipoOperacaoDao.retrieveCombo());
			this.result.include("tipoOperacaoList", json);

			json = gson.toJson(origemMercadoriaDao.retrieveCombo());
			result.include("origemMercadoriaList",json);

			json = gson.toJson(situacaoTributariaDao.retrieveCombo());
			result.include("situacaoTributariaList",json);

			json = gson.toJson(cfopDao.retrieveCombo());
			result.include("cfopList",json);

			json = gson.toJson(baseDeCalculoDao.retrieveCombo());
			result.include("baseDeCalculoList",json);

			json = gson.toJson(baseDeCalculoSTDao.retrieveCombo());
			result.include("baseDeCalculoSTList",json);

			json = gson.toJson(bean.getRegrasTributacao());
			result.include("regras",json);

		}catch(DAOException e){
			e.printStackTrace();
		}
	}

	@Autowired
	public void setUnidadeMedidaDao(UnidadeMedidaDAO unidadeMedidaDao) {
		this.unidadeMedidaDao = unidadeMedidaDao;
	}

	@Autowired
	public void setGrupoMaterialDao(GrupoMaterialDAO grupoMaterialDao) {
		this.grupoMaterialDao = grupoMaterialDao;
	}

	@Autowired
	public void setTipoOperacaoDao(TipoOperacaoDaoImpl tipoOperacaoDao) {
		this.tipoOperacaoDao = tipoOperacaoDao;
	}

	@Autowired
	public void setOrigemMercadoriaDao(OrigemMercadoriaDaoImpl origemMercadoriaDao) {
		this.origemMercadoriaDao = origemMercadoriaDao;
	}

	@Autowired
	public void setBaseDeCalculoDao(BaseDeCalculoDaoImpl baseDeCalculoDao) {
		this.baseDeCalculoDao = baseDeCalculoDao;
	}

	@Autowired
	public void setBaseDeCalculoSTDao(BaseDeCalculoSTDaoImpl baseDeCalculoSTDao) {
		this.baseDeCalculoSTDao = baseDeCalculoSTDao;
	}

	@Autowired
	public void setSituacaoTributariaDao(
			SituacaoTributariaDaoImpl situacaoTributariaDao) {
		this.situacaoTributariaDao = situacaoTributariaDao;
	}

	@Autowired
	public void setCfopDao(CfopDaoImpl cfopDao) {
		this.cfopDao = cfopDao;
	}

	@Override
	protected Produto createInstance() {
		return new Produto();
	}
	@Override
	protected void postPersistUpdate(Produto bean, Result result) {
		// TODO Auto-generated method stub

	}

}


text:
package com.intellij.plugins.haxe.lang.psi.impl;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Pair;
import com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes;
import com.intellij.plugins.haxe.lang.psi.*;
import com.intellij.plugins.haxe.util.UsefulPsiTreeUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.InheritanceImplUtil;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.PsiSuperMethodImplUtil;
import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
import com.intellij.psi.impl.java.stubs.PsiTypeParameterListStub;
import com.intellij.psi.impl.java.stubs.PsiTypeParameterStub;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Collection;
import java.util.List;

/**
 * Created by ebishton on 10/18/14.
 */
public class HaxeTypeParamPsiMixinImpl extends HaxePsiCompositeElementImpl implements HaxeTypeParamPsiMixin {

  public HaxeTypeParamPsiMixinImpl(ASTNode node) {
    super(node);
  }

  @Override
  public PsiTypeParameter[] getTypeParameters() {
    HaxeTypeList list = (HaxeTypeList) UsefulPsiTreeUtil.getChildOfType(this, HaxeTokenTypes.TYPE_LIST);
    HaxeTypeListPart[] parts = UsefulPsiTreeUtil.getChildrenOfType(list, HaxeTypeListPart.class, null);
    return null != parts ? parts : new PsiTypeParameter[0];
  }

  @Override
  public int getTypeParameterIndex(PsiTypeParameter typeParameter) {
    PsiTypeParameter[] params = getTypeParameters();
    int i = 0;
    for (; i < params.length; ++i) {
      if (typeParameter == params[i]) {
        break;
      }
    }
    return i < params.length ? i : -1;
  }

}


text:
package net.cattaka.android.humitemp4pd.dialog;

import net.cattaka.android.humitemp4pd.R;
import net.cattaka.android.humitemp4pd.entity.MySocketAddress;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

public class EditAddrresDialog implements DialogInterface.OnClickListener,
        DialogInterface.OnCancelListener {

    public interface IEditAddrresDialogListener {
        public void onEditAddrresDialogFinished(MySocketAddress result);

        public void onEditAddrresDialogDelete(Long id);

        public void onEditAddrresDialogCanceled();
    }

    private AlertDialog mDialog;

    private IEditAddrresDialogListener mListener;

    private EditText mHostNameEdit;

    private EditText mPortEdit;

    private Long mCurrentId;

    private EditAddrresDialog() {

    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (which == DialogInterface.BUTTON_POSITIVE) {
            String hostName = mHostNameEdit.getText().toString();
            int port = net.cattaka.libgeppa.Constants.DEFAULT_SERVER_PORT;
            try {
                port = Integer.parseInt(mPortEdit.getText().toString());
            } catch (NumberFormatException e) {
                // Ignore
            }
            MySocketAddress addr = new MySocketAddress();
            addr.setId(mCurrentId);
            addr.setHostName(hostName);
            addr.setPort(port);
            mListener.onEditAddrresDialogFinished(addr);
        } else if (which == DialogInterface.BUTTON_NEGATIVE) {
            dialog.cancel();
        } else if (which == DialogInterface.BUTTON_NEUTRAL) {
            mListener.onEditAddrresDialogDelete(mCurrentId);
        }
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        mListener.onEditAddrresDialogCanceled();
    }

    public AlertDialog getDialog() {
        return mDialog;
    }

    public void show(MySocketAddress addr) {
        mDialog.show();
        if (addr != null) {
            mDialog.setTitle(R.string.title_edit_socket_address);
            mDialog.getButton(DialogInterface.BUTTON_NEUTRAL).setVisibility(View.VISIBLE);
            mCurrentId = addr.getId();
            mHostNameEdit.setText(addr.getHostName());
            if (addr.getPort() != null) {
                mPortEdit.setText(String.valueOf(addr.getPort()));
            } else {
                mPortEdit.setText(String
                        .valueOf(net.cattaka.libgeppa.Constants.DEFAULT_SERVER_PORT));
            }
        } else {
            mDialog.setTitle(R.string.title_input_socket_address);
            mDialog.getButton(DialogInterface.BUTTON_NEUTRAL).setVisibility(View.INVISIBLE);
            mHostNameEdit.setText("");
            mPortEdit.setText(String.valueOf(net.cattaka.libgeppa.Constants.DEFAULT_SERVER_PORT));
            mCurrentId = null;
        }
    }

    public static EditAddrresDialog createEditAddrresDialog(Context context,
            IEditAddrresDialogListener listener) {
        View view;
        EditAddrresDialog holder = new EditAddrresDialog();
        holder.mListener = listener;
        {
            LayoutInflater inflater = LayoutInflater.from(context);
            view = inflater.inflate(R.layout.dialog_edit_address, null);
            holder.mHostNameEdit = (EditText)view.findViewById(R.id.hostNameEdit);
            holder.mPortEdit = (EditText)view.findViewById(R.id.portEdit);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.title_input_socket_address);
        builder.setView(view);
        builder.setPositiveButton(android.R.string.ok, holder);
        builder.setNegativeButton(android.R.string.cancel, holder);
        builder.setNeutralButton(R.string.btn_delete, holder);
        builder.setOnCancelListener(holder);
        holder.mDialog = builder.create();
        return holder;
    }
}


text:
package org.dcm4chex.archive.ejb.session;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmElement;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.dict.Status;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.UIDs;
import org.dcm4che.net.DcmServiceException;
import org.dcm4chex.archive.common.Availability;
import org.dcm4chex.archive.ejb.conf.AttributeFilter;
import org.dcm4chex.archive.ejb.interfaces.InstanceLocal;
import org.dcm4chex.archive.ejb.interfaces.InstanceLocalHome;
import org.dcm4chex.archive.ejb.interfaces.MPPSLocal;
import org.dcm4chex.archive.ejb.interfaces.MPPSLocalHome;
import org.dcm4chex.archive.ejb.interfaces.MWLItemLocal;
import org.dcm4chex.archive.ejb.interfaces.MWLItemLocalHome;
import org.dcm4chex.archive.ejb.interfaces.PatientLocal;
import org.dcm4chex.archive.ejb.interfaces.PatientLocalHome;
import org.dcm4chex.archive.ejb.interfaces.SeriesLocal;
import org.dcm4chex.archive.ejb.interfaces.SeriesLocalHome;
import org.dcm4chex.archive.ejb.interfaces.StudyLocal;

/**
 * @author gunter.zeilinter@tiani.com
 * @version $Revision: 4952 $ $Date: 2007-09-04 22:42:41 +0800 (周二, 04 9月 2007) $
 * @since 21.03.2004
 *
 * @ejb.bean name="MPPSManager" type="Stateless" view-type="remote"
 * 	jndi-name="ejb/MPPSManager"
 * @ejb.transaction-type  type="Container"
 * @ejb.transaction type="Required"
 * @ejb.ejb-ref ejb-name="Patient" view-type="local" ref-name="ejb/Patient"
 * @ejb.ejb-ref ejb-name="MPPS" view-type="local" ref-name="ejb/MPPS"
 * @ejb.ejb-ref ejb-name="MWLItem" view-type="local" ref-name="ejb/MWLItem"
 * @ejb.ejb-ref ejb-name="Series" view-type="local" ref-name="ejb/Series"
 * @ejb.ejb-ref ejb-name="Instance" view-type="local" ref-name="ejb/Instance"
 *
 */
public abstract class MPPSManagerBean implements SessionBean {

    private static Logger log = Logger.getLogger(MPPSManagerBean.class);
    private static final String NO_LONGER_BE_UPDATED_ERR_MSG =
        "Performed Procedure Step Object may no longer be updated";
    private static final int NO_LONGER_BE_UPDATED_ERR_ID = 0xA710;
	private static final int DELETED = 1;
    private static final int[] PATIENT_ATTRS_EXC = {
            Tags.RefPatientSeq,
            Tags.PatientName,
            Tags.PatientID,
            Tags.PatientBirthDate,
            Tags.PatientSex,
    };
    private static final int[] PATIENT_ATTRS_INC = {
            Tags.PatientName,
            Tags.PatientID,
            Tags.PatientBirthDate,
            Tags.PatientSex,
    };
    private PatientLocalHome patHome;
	private SeriesLocalHome seriesHome;
	private InstanceLocalHome instHome;
    private MPPSLocalHome mppsHome;
	private MWLItemLocalHome mwlItemHome;
    private SessionContext sessionCtx;

    public void setSessionContext(SessionContext ctx) {
        sessionCtx = ctx;
        Context jndiCtx = null;
        try {
            jndiCtx = new InitialContext();
            patHome =
                (PatientLocalHome) jndiCtx.lookup("java:comp/env/ejb/Patient");
			seriesHome = (SeriesLocalHome) jndiCtx.lookup("java:comp/env/ejb/Series");
			instHome = (InstanceLocalHome) jndiCtx.lookup("java:comp/env/ejb/Instance");
            mppsHome = (MPPSLocalHome) jndiCtx.lookup("java:comp/env/ejb/MPPS");
			mwlItemHome = (MWLItemLocalHome) jndiCtx.lookup("java:comp/env/ejb/MWLItem");
        } catch (NamingException e) {
            throw new EJBException(e);
		} finally {
            if (jndiCtx != null) {
                try {
                    jndiCtx.close();
                } catch (NamingException ignore) {}
            }
        }
    }

    public void unsetSessionContext() {
        sessionCtx = null;
        mppsHome = null;
        patHome = null;
		seriesHome = null;
		instHome = null;
    }

    /**
     * @ejb.interface-method
     */
    public void createMPPS(Dataset ds)
        throws DcmServiceException {
        checkDuplicate(ds.getString(Tags.SOPInstanceUID));
        try {
             mppsHome.create(ds.subSet(PATIENT_ATTRS_EXC, true, true),
                     findOrCreatePatient(ds));
        } catch (CreateException e) {
            log.error("Creation of MPPS(iuid="
                    + ds.getString(Tags.SOPInstanceUID) + ") failed: ", e);
            throw new DcmServiceException(Status.ProcessingFailure);
        }
    }

    private void checkDuplicate(String ppsiuid) throws DcmServiceException {
        try {
            mppsHome.findBySopIuid(ppsiuid);
            throw new DcmServiceException(Status.DuplicateSOPInstance);
        } catch (ObjectNotFoundException e) { // Ok
        } catch (FinderException e) {
            log.error("Query for GMPS(iuid=" + ppsiuid + ") failed: ", e);
            throw new DcmServiceException(Status.ProcessingFailure);
        }
    }
    private PatientLocal findOrCreatePatient(Dataset ds)
            throws DcmServiceException {
        try {
            try {
                return patHome.searchFor(ds, true);
            } catch (ObjectNotFoundException onfe) {
                return patHome.create(ds.subSet(PATIENT_ATTRS_INC));
            }
        } catch (Exception e) {
            throw new DcmServiceException(Status.ProcessingFailure, e);
        }
    }

    /**
     * @ejb.interface-method
     */
    public Dataset getMPPS(String iuid) throws FinderException {
        final MPPSLocal mpps = mppsHome.findBySopIuid(iuid);
        final PatientLocal pat = mpps.getPatient();
        Dataset attrs = mpps.getAttributes();
		attrs.putAll(pat.getAttributes(false));
		return attrs;
    }

    /**
     * @ejb.interface-method
     */
    public void updateMPPS(Dataset ds)
        throws DcmServiceException {
        MPPSLocal mpps;
        try {
            mpps = mppsHome.findBySopIuid(ds.getString(Tags.SOPInstanceUID));
        } catch (ObjectNotFoundException e) {
            throw new DcmServiceException(Status.NoSuchObjectInstance);
        } catch (FinderException e) {
            throw new DcmServiceException(Status.ProcessingFailure, e);
        }
        if (!"IN PROGRESS".equals(mpps.getPpsStatus())) {
            DcmServiceException e =
                new DcmServiceException(
                    Status.ProcessingFailure,
                    NO_LONGER_BE_UPDATED_ERR_MSG);
            e.setErrorID(NO_LONGER_BE_UPDATED_ERR_ID);
            throw e;
        }
        Dataset attrs = mpps.getAttributes();
        attrs.putAll(ds);
        mpps.setAttributes(attrs);
    }

    /**
     * @ejb.interface-method
     */
    public Dataset createIAN(String iuid) {
    	final MPPSLocal mpps;
        try {
			mpps = mppsHome.findBySopIuid(iuid);
		} catch (ObjectNotFoundException onf) {
			return null;
		} catch (FinderException e) {
			throw new EJBException(e);
		}
        Dataset attrs = mpps.getAttributes();
        if (ignoreMPPS(attrs)) {
        	return null;
        }
        Dataset ian = DcmObjectFactory.getInstance().newDataset();
        DcmElement refSeriesSq = ian.putSQ(Tags.RefSeriesSeq);
        DcmElement perfSeriesSq = attrs.get(Tags.PerformedSeriesSeq);
        for (int i = 0, n = perfSeriesSq.countItems(); i < n; i++) {
        	Dataset perfSeries = perfSeriesSq.getItem(i);
        	String seriesIUID =  perfSeries.getString(Tags.SeriesInstanceUID);
        	DcmElement refImageSeq = perfSeries.get(Tags.RefImageSeq);
        	DcmElement refNonImageSeq = perfSeries.get(
        			Tags.RefNonImageCompositeSOPInstanceSeq);
            final Collection insts;
			try {
				insts = instHome.findBySeriesIuid(seriesIUID);
			} catch (FinderException e) {
				throw new EJBException(e);
			}
            int countImage = refImageSeq != null
            		? refImageSeq.countItems() : 0;
            int countNonImage = refNonImageSeq != null
            		? refNonImageSeq.countItems() : 0;
            if (insts.size() <  countImage + countNonImage) {
            	return null;
            }
            Dataset refSeries = refSeriesSq.addNewItem();
            refSeries.putUI(Tags.SeriesInstanceUID, seriesIUID);
            DcmElement refSOPSeq = refSeries.putSQ(Tags.RefSOPSeq);
            if (refImageSeq != null
            		&& !containsAll(insts, refImageSeq, refSOPSeq)) {
            	return null;
            }
            if (refNonImageSeq != null
            		&& !containsAll(insts, refNonImageSeq, refSOPSeq)) {
            	return null;
            }
        }
        Dataset ssa = attrs.getItem(Tags.ScheduledStepAttributesSeq);
        String studyIUID = ssa != null
        		? ssa.getString(Tags.StudyInstanceUID) : null;
        DcmElement refPPSSeq = ian.putSQ(Tags.RefPPSSeq);
        Dataset refPPS = refPPSSeq.addNewItem();
        refPPS.putUI(Tags.RefSOPClassUID, UIDs.ModalityPerformedProcedureStep);
        refPPS.putUI(Tags.RefSOPInstanceUID, iuid);
        refPPS.putSQ(Tags.PerformedWorkitemCodeSeq);
        ian.putUI(Tags.StudyInstanceUID, studyIUID);
        return ian;
    }

    private static boolean containsAll(Collection insts,
    		DcmElement srcRefSOPSeq, DcmElement dstRefSOPSeq) {
        for (int i = 0, n = srcRefSOPSeq.countItems(); i < n; i++) {
        	Dataset srcRefSOP = srcRefSOPSeq.getItem(i);
        	String iuid = srcRefSOP.getString(Tags.RefSOPInstanceUID);
        	InstanceLocal inst = selectByIuid(insts, iuid);
        	if (inst == null) {
        		return false;
        	}
        	Dataset dstRefSOP = dstRefSOPSeq.addNewItem();
        	dstRefSOP.putUI(Tags.RefSOPClassUID, inst.getSopCuid());
        	dstRefSOP.putUI(Tags.RefSOPInstanceUID, iuid);
        	dstRefSOP.putCS(Tags.InstanceAvailability,
        			Availability.toString(inst.getAvailabilitySafe()));
        	dstRefSOP.putAE(Tags.RetrieveAET, inst.getRetrieveAETs());
        }
		return true;
	}

	private static InstanceLocal selectByIuid(Collection insts, String iuid) {
		for (Iterator iter = insts.iterator(); iter.hasNext();) {
			InstanceLocal inst = (InstanceLocal) iter.next();
			if (inst.getSopIuid().equals(iuid)) {
				return inst;
			}
		}
		return null;
	}

	private static boolean ignoreMPPS(Dataset mpps) {
        DcmElement perfSeriesSeq = mpps.get(Tags.PerformedSeriesSeq);
		if (perfSeriesSeq == null || perfSeriesSeq.isEmpty()) {
            return true;
        }
        String status = mpps.getString(Tags.PPSStatus);
        if ("COMPLETED".equals(status)) {
            return false;
        }
        if (!"DISCONTINUE".equals(status)) {
            return true;
        }
        Dataset item = mpps.getItem(Tags.PPSDiscontinuationReasonCodeSeq);
        if (item != null && "110514".equals(item.getString(Tags.CodeValue))
                && "DCM".equals(item.getString(Tags.CodingSchemeDesignator))) {
            log.info("Ignore MPPS with Discontinuation Reason Code: " +
                        "Wrong Worklist Entry Selected");
            return true;
        }
        return false;
	}

	/**
     * Links a mpps to a mwl entry (LOCAL).
     *

     * This method can be used if MWL entry is locally available.
     *

     * Sets SpsID and AccessionNumber from mwl entry.
     *

     * Returns a Map with following key/value pairs.
     *

     *
mppsAttrs: (Dataset)

     *
  Attributes of mpps entry. (for notification)

     *
mwlPat: (Dataset)

     *
  Patient of MWL entry.

     *
  (The dominant patient of patient merge).

     *
mppsPat: (Dataset)

     *
  Patient of MPPS entry.

     *
  (The merged patient).

     *

     * @param mwlPk pk to select MWL entry
     * @param mppsIUID Instance UID of mpps.
     *
     * @return A map with mpps attributes and patient attributes to merge.
     *
     * @ejb.interface-method
     */
    public Map linkMppsToMwl(String rpid, String spsid, String mppsIUID) throws DcmServiceException {
    	log.info("linkMppsToMwl spsId:"+spsid+" mpps:"+mppsIUID);
		MWLItemLocal mwlItem;
        MPPSLocal mpps;
        try {
            mwlItem = mwlItemHome.findByRpIdAndSpsId(rpid, spsid);
            mpps = mppsHome.findBySopIuid(mppsIUID);
            PatientLocal mwlPat = mwlItem.getPatient();
            PatientLocal mppsPat = mpps.getPatient();
            Dataset mwlAttrs = mwlItem.getAttributes();
    		Map map = updateLinkedMpps(mpps, mwlItem, mwlAttrs);
            if ( ! mwlPat.equals(mppsPat) ) {
        		map.put( "mwlPat", mwlPat.getAttributes(true));
        		map.put( "mppsPat",mppsPat.getAttributes(true));
            }
            return map;
        } catch (ObjectNotFoundException e) {
            throw new DcmServiceException(Status.NoSuchObjectInstance);
        } catch (FinderException e) {
            throw new DcmServiceException(Status.ProcessingFailure, e);
        }
    }

    private Map updateLinkedMpps(MPPSLocal mpps, MWLItemLocal mwlItem, Dataset mwlAttrs) {
        Map map = new HashMap();
        Dataset ssa;
        Dataset mppsAttrs = mpps.getAttributes();
        log.debug("MPPS attrs:");log.debug(mppsAttrs);
        log.debug("MWL attrs:");log.debug(mwlAttrs);
        String rpid = mwlAttrs.getString(Tags.RequestedProcedureID);
        String spsid = mwlAttrs.getItem(Tags.SPSSeq).getString(Tags.SPSID);
        String accNo = mwlAttrs.getString(Tags.AccessionNumber);
        DcmElement ssaSQ = mppsAttrs.get(Tags.ScheduledStepAttributesSeq);
        String ssaSpsID, studyIUID = null;
        boolean spsNotInList = true;
        for ( int i = 0, len = ssaSQ.countItems() ; i < len ; i++ ) {
        	ssa = ssaSQ.getItem(i);
        	if ( ssa != null ) {
        		if ( studyIUID == null ) {
        			studyIUID = ssa.getString(Tags.StudyInstanceUID);
            		if ( !studyIUID.equals(
            				mwlAttrs.getString(Tags.StudyInstanceUID) ) ) {
                        if ( mwlItem != null ) {
                			log.info("StudyInstanceUID corrected for spsID "+spsid);
                			mwlAttrs.putUI(Tags.StudyInstanceUID, studyIUID );
                			mwlItem.setAttributes( mwlAttrs );
                        } else {
                            log.warn("StudyInstanceUID of external MWL entry can not be corrected! spsID "+spsid);
                            log.warn("--- StudyIUID MWL:"+mwlAttrs.getString(Tags.StudyInstanceUID)+"   StudyIUID MPPS:"+studyIUID);
                        }
            		}
        		}
        		ssaSpsID = ssa.getString(Tags.SPSID);
        		if ( ssaSpsID == null || spsid.equals(ssaSpsID) ) {
        			ssa.putSH(Tags.AccessionNumber,accNo);
        			ssa.putSH(Tags.SPSID, spsid);
                                    ssa.putSH(Tags.RequestedProcedureID, rpid);
        			ssa.putUI(Tags.StudyInstanceUID, studyIUID);
        			spsNotInList = false;
        		}
        	}
        }
        if ( spsNotInList ) {
        	ssa = ssaSQ.addNewItem();
        	Dataset spsDS = mwlAttrs.getItem(Tags.SPSSeq);
        	ssa.putUI(Tags.StudyInstanceUID, studyIUID);
        	ssa.putSH(Tags.SPSID, spsid);
            ssa.putSH(Tags.RequestedProcedureID, rpid);
            ssa.putSH(Tags.AccessionNumber, accNo);
        	ssa.putSQ(Tags.RefStudySeq);
        	ssa.putSH(Tags.RequestedProcedureID, mwlAttrs.getString(Tags.RequestedProcedureID));
        	ssa.putLO(Tags.SPSDescription, spsDS.getString(Tags.SPSDescription));
        	DcmElement mppsSPCSQ = ssa.putSQ(Tags.ScheduledProtocolCodeSeq);
        	DcmElement mwlSPCSQ = spsDS.get(Tags.ScheduledProtocolCodeSeq);
        	if ( mwlSPCSQ != null && mwlSPCSQ.countItems() > 0 ) {
        		for ( int i = 0, len = mwlSPCSQ.countItems() ; i < len ; i++ ) {
        			mppsSPCSQ.addNewItem().putAll(mwlSPCSQ.getItem(i));
        		}
        	}
        	log.debug("add new scheduledStepAttribute item:");log.debug(ssa);
        	log.debug("new mppsAttrs:");log.debug(mppsAttrs);
        }
        mppsAttrs.putAll(mpps.getPatient().getAttributes(false));
        mpps.setAttributes(mppsAttrs);
        map.put("mppsAttrs",mppsAttrs);
        map.put("mwlAttrs",mwlAttrs);
        return map;
    }

    /**
     * Links a mpps to a mwl entry (external).
     *

     * This Method can be used to link a MPPS entry with an MWL entry from an external Modality Worklist.
     *

     * Sets SpsID and AccessionNumber from mwlDs.
     *

     * Returns a Map with following key/value pairs.
     *

     *
mppsAttrs: (Dataset)

     *
  Attributes of mpps entry. (for notification)

     *
mwlPat: (Dataset)

     *
  Patient of MWL entry.

     *
  (The dominant patient of patient merge).

     *
mppsPat: (Dataset)

     *
  Patient of MPPS entry.

     *
  (The merged patient).

     *

     * @param mwlDs Datset of MWL entry
     * @param mppsIUID Instance UID of mpps.
     *
     * @return A map with mpps attributes and patient attributes to merge.
     * @throws FinderException
     * @throws CreateException
     *
     * @ejb.interface-method
     */
    public Map linkMppsToMwl(Dataset mwlAttrs, String mppsIUID) throws DcmServiceException, FinderException, CreateException {
        String spsID = mwlAttrs.get(Tags.SPSSeq).getItem().getString(Tags.SPSID);
        log.info("linkMppsToMwl sps:"+spsID+" mpps:"+mppsIUID);
        MPPSLocal mpps = mppsHome.findBySopIuid(mppsIUID);
        AttributeFilter filter = AttributeFilter.getPatientAttributeFilter();
        Dataset mwlPatDs = filter.filter(mwlAttrs);
        PatientLocal mppsPat = mpps.getPatient();
        Map map = updateLinkedMpps(mpps, null, mwlAttrs);
        if ( ! isSamePatient(mwlPatDs,mppsPat) ) {
            Collection col = patHome.findByPatientIdWithIssuer(mwlPatDs.getString(Tags.PatientID),
                    mwlPatDs.getString(Tags.IssuerOfPatientID));
            PatientLocal mwlPat = col.isEmpty() ?
                    patHome.create(mwlPatDs) : (PatientLocal) col.iterator().next();
            map.put( "mwlPat", mwlPat.getAttributes(true));
            map.put( "mppsPat",mppsPat.getAttributes(true));
        }
        return map;
    }

    private boolean isSamePatient(Dataset mwlPatDs, PatientLocal mppsPat) {
        String mppsPatId = mppsPat.getPatientId();
        if ( mppsPatId == null ) {
            log.warn("Link MPPS to MWL: MPPS patient without PatientID! try to check via Patient Name");
            String name = mppsPat.getPatientName();
            if (name == null) {
                log.error("Link MPPS to MWL: MPPS patient without Patient Name! Ignore differences to avoid merge!");
                return true;
            }
            return name.equals(mwlPatDs.getString(Tags.PatientName));
        } else if ( ! mppsPat.getPatientId().equals(mwlPatDs.getString(Tags.PatientID) ) )
            return false;
        String issuer = mppsPat.getIssuerOfPatientId();
        return ( issuer != null ) ? issuer.equals(mwlPatDs.getString(Tags.IssuerOfPatientID)) : true;
    }

    /**
     * @ejb.interface-method
     */
    public void unlinkMpps( String mppsIUID ) throws FinderException {
    	MPPSLocal mpps = mppsHome.findBySopIuid(mppsIUID);
    	Dataset mppsAttrs = mpps.getAttributes();
		DcmElement ssaSQ = mppsAttrs.get(Tags.ScheduledStepAttributesSeq);
		Dataset ds = null;
		String rpID, spsID;
		for ( int i = ssaSQ.countItems()-1 ; i >= 0 ; i-- ) {
			ds = ssaSQ.getItem(i);
                        rpID = ds.getString(Tags.RequestedProcedureID);
			spsID = ds.getString(Tags.SPSID);
			if ( spsID != null ) {
				try {
					MWLItemLocal mwlItem = mwlItemHome.findByRpIdAndSpsId(rpID, spsID);
					Dataset mwlDS = mwlItem.getAttributes();
					mwlDS.getItem(Tags.SPSSeq).putCS(Tags.SPSStatus, "SCHEDULED");
					mwlItem.setAttributes(mwlDS);
				} catch ( FinderException ignore ) {}
			}
		}
		String studyIUID = ds.getString(Tags.StudyInstanceUID);
		ds.clear();
		ds.putUI(Tags.StudyInstanceUID, studyIUID);
		//add empty type 2 attributes.
		ds.putSH(Tags.SPSID, (String)null);
		ds.putSH(Tags.AccessionNumber, (String)null);
		ds.putSQ(Tags.RefStudySeq);
		ds.putSH(Tags.RequestedProcedureID, (String)null);
		ds.putLO(Tags.SPSDescription, (String)null);
		ds.putSQ(Tags.ScheduledProtocolCodeSeq);
		mppsAttrs.putSQ(Tags.ScheduledStepAttributesSeq).addItem(ds);
    	mpps.setAttributes(mppsAttrs);
    }

    /**
     * Delete a list of mpps entries.
     *
     * @ejb.interface-method
     */
    public boolean deleteMPPSEntries( String[] iuids ) {
    	for ( int i = 0 ; i < iuids.length ; i++ ) {
    		try {
				mppsHome.findBySopIuid( iuids[i] ).remove();
			} catch (Exception x) {
				log.error("Cant delete mpps:"+iuids[i], x);
			}
    	}
    	return true;
    }

    /**
     * @ejb.interface-method
     */
    public Collection getSeriesIUIDs(String mppsIUID) throws FinderException {
        Collection col = new ArrayList();
    	Collection series = seriesHome.findByPpsIuid(mppsIUID);
        for ( Iterator iter = series.iterator() ; iter.hasNext() ; ) {
        	col.add( ( (SeriesLocal) iter.next()).getSeriesIuid() );
        }
        return col;
    }

    /**
     * @ejb.interface-method
     */
    public Collection getSeriesAndStudyDS(String mppsIUID) throws FinderException {
        Collection col = new ArrayList();
    	Collection seriess = seriesHome.findByPpsIuid(mppsIUID);
    	SeriesLocal series;
    	Dataset ds;
        for ( Iterator iter = seriess.iterator() ; iter.hasNext() ; ) {
            series = (SeriesLocal) iter.next();
            ds = series.getAttributes(true);
            ds.putAll(series.getStudy().getAttributes(true));
        	col.add( ds );
        }
        return col;
    }

    /**
     * Returns a StudyMgt Dataset.
     *
     * @ejb.interface-method
     */
    public Dataset updateSeriesAndStudy(Collection seriesDS) throws FinderException, CreateException {
        Dataset ds = null;
        String iuid;
        SeriesLocal series = null;
        Dataset dsN = DcmObjectFactory.getInstance().newDataset();
        DcmElement refSeriesSeq = dsN.putSQ( Tags.RefSeriesSeq );
        Dataset dsSer;
        for ( Iterator iter = seriesDS.iterator() ; iter.hasNext() ; ) {
            ds = (Dataset) iter.next();
            iuid = ds.getString(Tags.SeriesInstanceUID);
            series = seriesHome.findBySeriesIuid(iuid);
	        series.updateAttributes(ds, true);
            dsSer = refSeriesSeq.addNewItem();
            dsSer.putAll(series.getAttributes(true));
            Iterator iter2 = series.getInstances().iterator();
            if ( iter2.hasNext()) {
                DcmElement refSopSeq = dsSer.putSQ( Tags.RefSOPSeq );
                InstanceLocal il;
                Dataset dsInst;
                while ( iter2.hasNext() ) {
                    il = (InstanceLocal) iter2.next();
                    dsInst = refSopSeq.addNewItem();
                    dsInst.putUI( Tags.RefSOPClassUID, il.getSopCuid() );
                    dsInst.putUI( Tags.RefSOPInstanceUID, il.getSopIuid() );
                    dsInst.putAE( Tags.RetrieveAET, il.getRetrieveAETs() );
                }
            }
        }
        if ( series != null ) {
           StudyLocal study = series.getStudy();
           study.setAttributes(ds);
           dsN.putAll( study.getAttributes(true) );
        }
        return dsN;
    }
}


text:
package master

import (
	"reflect"
	"testing"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/registrytest"
	"github.com/fsouza/go-dockerclient"
)

type FakePodInfoGetter struct {
	host string
	id   string
	data api.PodInfo
	err  error
}

func (f *FakePodInfoGetter) GetPodInfo(host, id string) (api.PodInfo, error) {
	f.host = host
	f.id = id
	return f.data, f.err
}

func TestPodCacheGet(t *testing.T) {
	cache := NewPodCache(nil, nil)

	expected := api.PodInfo{"foo": docker.Container{ID: "foo"}}
	cache.podInfo["foo"] = expected

	info, err := cache.GetPodInfo("host", "foo")
	if err != nil {
		t.Errorf("Unexpected error: %#v", err)
	}
	if !reflect.DeepEqual(info, expected) {
		t.Errorf("Unexpected mismatch. Expected: %#v, Got: #%v", &expected, info)
	}
}

func TestPodCacheGetMissing(t *testing.T) {
	cache := NewPodCache(nil, nil)

	info, err := cache.GetPodInfo("host", "foo")
	if err == nil {
		t.Errorf("Unexpected non-error: %#v", err)
	}
	if info != nil {
		t.Errorf("Unexpected info: %#v", info)
	}
}

func TestPodGetPodInfoGetter(t *testing.T) {
	expected := api.PodInfo{"foo": docker.Container{ID: "foo"}}
	fake := FakePodInfoGetter{
		data: expected,
	}
	cache := NewPodCache(&fake, nil)

	cache.updatePodInfo("host", "foo")

	if fake.host != "host" || fake.id != "foo" {
		t.Errorf("Unexpected access: %#v", fake)
	}

	info, err := cache.GetPodInfo("host", "foo")
	if err != nil {
		t.Errorf("Unexpected error: %#v", err)
	}
	if !reflect.DeepEqual(info, expected) {
		t.Errorf("Unexpected mismatch. Expected: %#v, Got: #%v", &expected, info)
	}
}

func TestPodUpdateAllContainers(t *testing.T) {
	pod := api.Pod{
		JSONBase: api.JSONBase{ID: "foo"},
		CurrentState: api.PodState{
			Host: "machine",
		},
	}

	pods := []api.Pod{pod}
	mockRegistry := registrytest.NewPodRegistry(pods)

	expected := api.PodInfo{"foo": docker.Container{ID: "foo"}}
	fake := FakePodInfoGetter{
		data: expected,
	}
	cache := NewPodCache(&fake, mockRegistry)

	cache.UpdateAllContainers()

	if fake.host != "machine" || fake.id != "foo" {
		t.Errorf("Unexpected access: %#v", fake)
	}

	info, err := cache.GetPodInfo("machine", "foo")
	if err != nil {
		t.Errorf("Unexpected error: %#v", err)
	}
	if !reflect.DeepEqual(info, expected) {
		t.Errorf("Unexpected mismatch. Expected: %#v, Got: #%v", &expected, info)
	}
}


text:
package com.oregonscientific.meep.home.test;

import junit.framework.Test;
import junit.framework.TestSuite;
import android.content.Intent;

import com.bitbar.recorder.extensions.ExtSolo;
import com.oregonscientific.meep.home.HomeActivity;
import com.oregonscientific.meep.home.R;
import com.oregonscientific.meep.home.TutorialActivity;
import com.oregonscientific.meep.home.view.CircleIndicator;
import com.oregonscientific.meep.junit.test.BaseSingleLaunchActivityTestCase;

public class TutorialTest extends
	BaseSingleLaunchActivityTestCase {

	private final String TUTORIAL_PACKAGE_NAME = "com.oregonscientific.meep.home.TutorialActivity";
	@Override
	public void setUp() throws Exception {
		super.setUp();

		solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
				.getCanonicalName(), getName());

	}

	@Override
	public void tearDown() throws Exception {
		//solo.goBackToActivity("com.oregonscientific.meep.home.HomeActivity");
		solo.goBack();
		solo.tearDown();
		super.tearDown();
	}

	public void test1_Tutorial_Normal_Usage() {
		solo.waitForActivity("HomeActivity", 3000);
		solo.assertCurrentActivity("Fail to detect home activity", HomeActivity.class);
		getActivity().startActivity(new Intent(getActivity(), TutorialActivity.class));
		assertTrue("Fail to launch tutorial activity", solo.waitForActivity("TutorialActivity", 5000));

		CircleIndicator ci = (CircleIndicator) solo.findViewById(R.id.tutorial_circle_indicator);
		assertTrue("Tutorial not at Page 1", ci.getCurrentIndex() == 0);
		solo.sleep(6400);
		solo.drag(solo.toScreenX(0.854f), solo.toScreenX(0.370f),
				solo.toScreenY(0.498f), solo.toScreenY(0.568f), 6);
		solo.sleep(4200);
		assertTrue("Tutorial not at Page 2", ci.getCurrentIndex() == 1);
		solo.drag(solo.toScreenX(0.845f), solo.toScreenX(0.390f),
				solo.toScreenY(0.615f), solo.toScreenY(0.687f), 10);
		solo.sleep(2600);
		assertTrue("Tutorial not at Page 3", ci.getCurrentIndex() == 2);
		solo.drag(solo.toScreenX(0.855f), solo.toScreenX(0.401f),
				solo.toScreenY(0.597f), solo.toScreenY(0.606f), 10);
		solo.sleep(2500);
		assertTrue("Tutorial not at Page 4", ci.getCurrentIndex() == 3);
		solo.drag(solo.toScreenX(0.925f), solo.toScreenX(0.374f),
				solo.toScreenY(0.568f), solo.toScreenY(0.545f), 10);
		solo.sleep(2700);
		assertTrue("Tutorial not at Page 5", ci.getCurrentIndex() == 4);
		solo.drag(solo.toScreenX(0.884f), solo.toScreenX(0.369f),
				solo.toScreenY(0.586f), solo.toScreenY(0.619f), 11);
		solo.sleep(2600);
		assertTrue("Tutorial not at Page 6", ci.getCurrentIndex() == 5);
		solo.drag(solo.toScreenX(0.911f), solo.toScreenX(0.459f),
				solo.toScreenY(0.615f), solo.toScreenY(0.588f), 11);
		solo.sleep(1070);

	}

	public void test2_Tutorial_Swipe_RightAndLeft() {

		solo.waitForActivity("HomeActivity", 3000);
		solo.assertCurrentActivity("Fail to detect home activity", HomeActivity.class);

		getActivity().startActivity(new Intent(getActivity(), TutorialActivity.class));
		assertTrue("Fail to launch tutorial activity", solo.waitForActivity("TutorialActivity", 5000));

		// swipe right to last page
		CircleIndicator ci = (CircleIndicator) solo.findViewById(R.id.tutorial_circle_indicator);
		assertTrue("Tutorial not at Page 1", ci.getCurrentIndex() == 0);
		solo.sleep(6400);
		solo.drag(solo.toScreenX(0.854f), solo.toScreenX(0.370f),
				solo.toScreenY(0.498f), solo.toScreenY(0.568f), 6);
		solo.sleep(4200);
		assertTrue("Tutorial not at Page 2", ci.getCurrentIndex() == 1);
		solo.drag(solo.toScreenX(0.845f), solo.toScreenX(0.390f),
				solo.toScreenY(0.615f), solo.toScreenY(0.687f), 10);
		solo.sleep(2600);
		assertTrue("Tutorial not at Page 3", ci.getCurrentIndex() == 2);
		solo.drag(solo.toScreenX(0.855f), solo.toScreenX(0.401f),
				solo.toScreenY(0.597f), solo.toScreenY(0.606f), 10);
		solo.sleep(2500);
		assertTrue("Tutorial not at Page 4", ci.getCurrentIndex() == 3);
		solo.drag(solo.toScreenX(0.925f), solo.toScreenX(0.374f),
				solo.toScreenY(0.568f), solo.toScreenY(0.545f), 10);
		solo.sleep(2700);
		assertTrue("Tutorial not at Page 5", ci.getCurrentIndex() == 4);
		solo.drag(solo.toScreenX(0.884f), solo.toScreenX(0.369f),
				solo.toScreenY(0.586f), solo.toScreenY(0.619f), 11);
		solo.sleep(2600);
		assertTrue("Tutorial not at Page 6", ci.getCurrentIndex() == 5);

		// swipe left back to first page
		solo.drag(solo.toScreenX(0.370f), solo.toScreenX(0.854f),
				solo.toScreenY(0.498f), solo.toScreenY(0.568f), 6);
		solo.sleep(4200);
		assertTrue("Tutorial not at Page 5", ci.getCurrentIndex() == 4);
		solo.drag(solo.toScreenX(0.390f), solo.toScreenX(0.854f),
				solo.toScreenY(0.615f), solo.toScreenY(0.687f), 10);
		solo.sleep(2600);
		assertTrue("Tutorial not at Page 4", ci.getCurrentIndex() == 3);
		solo.drag(solo.toScreenX(0.401f), solo.toScreenX(0.855f),
				solo.toScreenY(0.597f), solo.toScreenY(0.606f), 10);
		solo.sleep(2500);
		assertTrue("Tutorial not at Page 3", ci.getCurrentIndex() == 2);
		solo.drag(solo.toScreenX(0.374f), solo.toScreenX(0.925f),
				solo.toScreenY(0.568f), solo.toScreenY(0.545f), 10);
		solo.sleep(2700);
		assertTrue("Tutorial not at Page 2", ci.getCurrentIndex() == 1);
		solo.drag(solo.toScreenX(0.369f), solo.toScreenX(0.884f),
				solo.toScreenY(0.586f), solo.toScreenY(0.619f), 11);
		solo.sleep(2600);
		assertTrue("Tutorial not at Page 1", ci.getCurrentIndex() == 0);
		solo.sleep(1000);

		for (int i=0; i < 6; i++) {
			solo.sleep(500);
			solo.drag(solo.toScreenX(0.854f), solo.toScreenX(0.370f),
				solo.toScreenY(0.498f), solo.toScreenY(0.568f), 6);
			solo.sleep(500);
		}

	}

	public void test3_Tutorial_Swipe_RightAndLeftQuickly() {
		int currentIndex = 0;
		int assertIndex = 0;
		int swipeCount = 10;

		solo.waitForActivity("HomeActivity", 3000);
		solo.assertCurrentActivity("Fail to detect home activity", HomeActivity.class);
		getActivity().startActivity(new Intent(getActivity(), TutorialActivity.class));
		assertTrue("Fail to launch tutorial activity", solo.waitForActivity("TutorialActivity", 5000));

		// swipe right to last page
		CircleIndicator ci = (CircleIndicator) solo.findViewById(R.id.tutorial_circle_indicator);

		for (int i=0; i < swipeCount; i++) {

			boolean right = true;
			if (currentIndex != 0 && currentIndex != 5) {
				right = (Math.round(Math.random() * 100) % 2) == 1;
			} else if (currentIndex == 0) {
				right = true;
			} else if (currentIndex == 5) {
				right = false;
			}

			if (right) {
				assertIndex = currentIndex + 1;
				solo.sleep(500);
				solo.drag(solo.toScreenX(0.854f), solo.toScreenX(0.370f),
					solo.toScreenY(0.498f), solo.toScreenY(0.568f), 6);
				solo.sleep(500);
				assertTrue("Right Swipe: Tutorial not at Page " + (assertIndex +1) + " but is at Page " + (ci.getCurrentIndex()+1), ci.getCurrentIndex() == assertIndex);
				currentIndex = ci.getCurrentIndex();
			} else {
				assertIndex = currentIndex - 1;
				solo.sleep(500);
				solo.drag(solo.toScreenX(0.370f), solo.toScreenX(0.854f),
					solo.toScreenY(0.498f), solo.toScreenY(0.568f), 6);
				solo.sleep(500);
				assertTrue("Left Swipe: Tutorial not at Page " + (assertIndex + 1) + " but is at Page " + (ci.getCurrentIndex()+1), ci.getCurrentIndex() == assertIndex);
				currentIndex = ci.getCurrentIndex();
			}
		}

		for (int i=0; i < 6; i++) {
			solo.sleep(500);
			solo.drag(solo.toScreenX(0.854f), solo.toScreenX(0.370f),
				solo.toScreenY(0.498f), solo.toScreenY(0.568f), 6);
			solo.sleep(500);
		}
	}

	public static Test suite() {
		TestSuite suite = new TestSuite(
				TutorialTest.class);
		return suite;
	}
}


text:
<?php

namespace FibonacciSerie\ResultFilters;

class ResultFilterFactory {

    const FILTER_ARRAY = 'Array';
    const FILTER_STRING_COMMA = 'StringComma';
    const FILTER_STRING_SEMICOLON = 'StringSemicolon';

    /**
     *
     * @param string $filterType
     * @return ResultFilterInterface
     */
    static public function createFilter($filterType) {
        $filterName = '\FibonacciSerie\ResultFilters\ResultFilter'.$filterType;
        if (class_exists($filterName)) {
            return new $filterName;
        } else {
            throw new \InvalidArgumentException('FilterType `'.$filterType.'` does not exists.');
        }
    }

}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name='description'  content='Geek, Google Fanboy, Tech News Junkie, Entrepreneur - Drinker of tea :)'>
	<META NAME="robots" CONTENT="nofollow">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
	<meta name="og:title" property="og:title" content="Lovell Felix" />
	<meta name="og:type" property="og:type" content="public_figure" />
	<meta name="og:image" property="og:image" content="assets/img/grav.png"/>
	<meta name="og:url" property="og:url" content="http://lovellfelix.com/" />
	<meta name="og:site_name" property="og:site_name" content="Lovell Felix" />
	<link rel='me' href='https://plus.google.com/102676824509364241023' />
    <link href="assets/css/bootstrap.css" rel="stylesheet">
    <link href="assets/css/font-awesome.css" rel="stylesheet">
    <link href="assets/css/lf.css" rel="stylesheet">
    <link href="assets/css/google-bootstrap.css" rel="stylesheet">
	<link href="assets/js/google-code-prettify/prettify.css" rel="stylesheet">
	<link rel="shortcut icon" href="assets/img/grav.png">

    <title>Lovell Felix</title>
    </style>

* · Lovell Felix

					   More...

 home

 blog

 labs

 resume

I have no special talents. I am only passionately curious."

Albert Einstein

		© 2012 Lovell Felix


text:
package com.mailrest.maildal.support;

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

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

public class RecipientsTest {

	@Test(expected=IllegalArgumentException.class)
	public void testSingleNull() {

		Recipients.INSTANCE.parseSingle(null);

	}

	@Test(expected=IllegalArgumentException.class)
	public void testMultiNull() {

		Recipients.INSTANCE.parseMulti(null, false);

	}

	@Test(expected=InvalidEmailException.class)
	public void testSingleEmpty() {

		Recipients.INSTANCE.parseSingle("");

	}

	@Test
	public void testMultiEmpty() {

		Assert.assertEquals(0, Recipients.INSTANCE.parseMulti(",,,", false).size());

	}

	@Test
	public void testSingleAddressValid() {

		Recipient rec = Recipients.INSTANCE.parseSingle("a@albertshift.com");

		Assert.assertFalse(rec.getName().isPresent());
		Assert.assertEquals("a@albertshift.com", rec.getEmail());

	}

	@Test
	public void testSingleNameAddressValid() {

		Recipient rec = Recipients.INSTANCE.parseSingle("Albert Shift <a@albertshift.com>");

		Assert.assertEquals("Albert Shift", rec.getName().get());
		Assert.assertEquals("a@albertshift.com", rec.getEmail());

	}

	@Test
	public void testSingleNameAddressWithSingleQuoteValid() {

		Recipient rec = Recipients.INSTANCE.parseSingle("'Albert Shift' <a@albertshift.com>");

		Assert.assertEquals("Albert Shift", rec.getName().get());
		Assert.assertEquals("a@albertshift.com", rec.getEmail());

	}

	@Test
	public void testSingleNameAddressWithDoubleSingleQuoteValid() {

		Recipient rec = Recipients.INSTANCE.parseSingle("\"Albert Shift\" <a@albertshift.com>");

		Assert.assertEquals("Albert Shift", rec.getName().get());
		Assert.assertEquals("a@albertshift.com", rec.getEmail());

	}

	@Test
	public void testMultiNameAddressWithDoubleSingleQuoteValid() {

		List<Recipient> list = new ArrayList<Recipient>();

		Recipients.INSTANCE.parseMulti("\"Albert Shift\" <a@albertshift.com>, 'Albert Shift' <a@albertshift.com>", false, list);

		for (Recipient rec : list) {
			Assert.assertEquals("Albert Shift", rec.getName().get());
			Assert.assertEquals("a@albertshift.com", rec.getEmail());
		}

	}

	@Test
	public void testMultiNameAddressWithDoubleSingleQuoteValidWithErrors() {

		List<Recipient> list = new ArrayList<Recipient>();

		Recipients.INSTANCE.parseMulti("\"Albert Shift\" <a@albertshift.com>, 'Albert Shift' <a@albertshift.com>, ffffff", true, list);

		for (Recipient rec : list) {
			Assert.assertEquals("Albert Shift", rec.getName().get());
			Assert.assertEquals("a@albertshift.com", rec.getEmail());
		}

	}

}


text:
require 'uri'

# Extend the standard ruby {URI} with AMQP and AMQPS schemes
module URI
  # monkey patch register_scheme for earlier versions of ruby
  if !self.respond_to? :register_scheme
    def self.register_scheme (scheme, klass)
      @@schemes[scheme] = klass
    end
  end

  # AMQP URI scheme for the AMQP protocol
  class AMQP < Generic
    DEFAULT_PORT = 5672

    # @return [String] The AMQP address is the {#path} stripped of any leading "/"
    def amqp_address() path[0] == "/" ? path[1..-1] : path; end
  end
  register_scheme 'AMQP', AMQP

  # AMQPS URI scheme for the AMQP protocol over TLS
  class AMQPS < AMQP
    DEFAULT_PORT = 5671
  end
  register_scheme 'AMQPS', AMQPS
end

module Qpid::Proton
  private
  # Make sure to allow empty hostnames, Ruby 2.0.0 does not.
  DEFAULT_URI_PARSER = URI::Parser.new(:HOSTNAME => /(?:#{URI::PATTERN::HOSTNAME})|/)

  public

  # Convert +s+ to an amqp: or amqps: URI
  #
  # This does not give the same result as the standard URI parser in all cases.
  # Short-cut strings like "host:port" are allowed, an "amqp://" prefix is added if +s+ does
  # not already look like an 'amqp:' or 'amqps:' URI.
  #
  # @param s [String,URI] String to convert to a URI, or a URI object.
  # @return [URI] A valid AMQP or AMQPS URI
  # @raise [URI::BadURIError] s is a URI object with a non-AMQP scheme
  # @raise [URI::InvalidURIError] s cannot be parsed as a URI or shortcut
  # @raise [::ArgumentError] s is not a string or URI
  #
  def self.uri(s)
    case s
    when URI::AMQP then s       # This is already an AMQP or AMQPS URL.
    when URI::Generic           # Re-parse a generic URI that was not parsed as AMQP/AMQPS class
      s.scheme ||= 'amqp'       # Default to amqp: scheme
      u = DEFAULT_URI_PARSER.parse(s.to_s)
      raise URI::BadURIError, "Not an AMQP URI: '#{u}'" unless u.is_a? URI::AMQP
      u
    else
      s = String.try_convert s
      raise ::ArgumentError, "bad argument (expected URI object or URI string)" unless s
      case s
      when %r{^amqps?:} then DEFAULT_URI_PARSER.parse(s)      # Looks like an AMQP URI
      when %r{^//} then DEFAULT_URI_PARSER.parse("amqp:#{s}") # Looks like an authority with no scheme
      else DEFAULT_URI_PARSER.parse("amqp://#{s}")            # Treat as a bare host:port/path string
      end
    end
  rescue =>e
    raise e.class, "#{self}.#{__method__}(#{s.inspect}): #{e}"
  end
end


text:
package de.unitrier.st.soposthistory.urls;

import javax.persistence.*;

@Entity
@Table(name = "PostVersionUrl", schema = "stackoverflow16_12")
public class PostVersionUrl{
    private int id;
    private Integer postId;
    private Integer postHistoryId;
    private Integer postBlockVersionId;
    private String url;

    public PostVersionUrl(){
        this.postHistoryId = null;
        this.url = null;
    }

    public PostVersionUrl(int postId, int postHistoryId, int postBlockVersionId, String urls){
        this.postId = postId;
        this.postHistoryId = postHistoryId;
        this.postBlockVersionId = postBlockVersionId;
        this.url = urls;
    }

    @Id
    @Column(name = "Id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int getId() {
        return id;
    }

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

    @Basic
    @Column(name = "PostId")
    public Integer getPostId() {
        return postId;
    }

    public void setPostId(Integer postId) {
        this.postId = postId;
    }

    @Basic
    @Column(name = "PostHistoryId")
    public Integer getPostHistoryId() {
        return postHistoryId;
    }

    public void setPostHistoryId(Integer postHistoryId) {
        this.postHistoryId = postHistoryId;
    }

    @Basic
    @Column(name = "PostBlockVersionId")
    public Integer getPostBlockVersionId() {
        return postBlockVersionId;
    }

    public void setPostBlockVersionId(Integer postBlockVersionId) {
        this.postBlockVersionId = postBlockVersionId;
    }

    @Basic
    @Column(name = "Url")
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "Url: " + url + "\n";
    }
}


text:
/**
 * Get the value of a computed style for the first element in set of
 * matched elements or set one or more CSS properties for every matched element.
 *
 * @memberof tiny
 * @param {String|HTMLElement} elem CSS selector or an HTML Element
 * @param {String|Object} key A CSS property or a map of <property, value> when used as setter.
 * @param {Sreing} value A value to set for the property
 *
 * @returns {String|Void}
 */
export default function css(elem, key, value) {
    var args = arguments,
        elements = getElements(elem),
        length = elements.length,
        setter;

    // Get attribute
    if (typeof key === 'string' && args.length === 2) {
        return length === 0 ? '' : getElStyle(elements[0], key);
    }

    // Set attributes
    if (args.length === 3) {
        setter = function(el) {
            el.style[key] = value;
        };
    } else if (typeof key === 'object') {
        setter = function(el) {
            Object.keys(key).forEach(function(name) {
                el.style[name] = key[name];
            });
        };
    }

    for (let i = 0; i < length; i++) {
        setter(elements[i]);
    }
}

function getElStyle(el, prop) {
    if (window.getComputedStyle) {
        return window.getComputedStyle(el, null).getPropertyValue(prop);
        // IE
    } else {
        // Turn style name into camel notation
        prop = prop.replace(/\-(\w)/g, function (str, $1) { return $1.toUpperCase(); });
        return el.currentStyle[prop];
    }
}

function getElements(el) {
    if (!el) {
        return [];
    }

    if (typeof el === 'string') {
        return nodeListToArray(document.querySelectorAll(el));
    } else if (/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(el)) &&
        (typeof el.length === 'number' || Object.prototype.hasOwnProperty.call(el, 'length')) &&
         el.length > 0 && el[0].nodeType > 0) {

        return nodeListToArray(el);
    } else {
        return [el];
    }
}

function nodeListToArray(elements) {
    let i = 0,
        length = elements.length,
        arr = [];

    for (; i < length; i++) {
        arr.push(elements[i]);
    }

    return arr;
}


text:
layout: page
title: Mcfarland King Group Seminar
date: 2016-05-24
author: Grace Downs
tags: weekly links, java
status: published
summary: Phasellus eu nisl ut est semper.
banner: images/banner/office-01.jpg
booking:
  startDate: 10/27/2018
  endDate: 10/28/2018
  ctyhocn: SANDLHX
  groupCode: MKGS
published: true
---
Aenean facilisis tellus ipsum, nec feugiat libero tincidunt id. In semper bibendum ante, in viverra enim imperdiet lobortis. Donec placerat, nunc nec molestie malesuada, sapien turpis dictum ex, et aliquam ante sem in lectus. Donec sit amet elit tempor, ultricies urna sit amet, dapibus sem. Fusce consequat lectus ac sodales mollis. Maecenas fermentum est sit amet tempor placerat. Vivamus faucibus dolor a convallis cursus. Aenean egestas in urna eget elementum. In tincidunt venenatis dui.
Vestibulum lacinia elit dolor, eget malesuada est vehicula et. Donec id nibh eget nulla ullamcorper laoreet a et sapien. Nunc non sapien bibendum, ullamcorper augue vel, posuere turpis. Sed scelerisque, enim id fermentum aliquet, mauris nunc congue mauris, sed luctus tortor sem eget neque. Mauris molestie dolor eget mollis tempor. Integer pharetra dictum nunc at malesuada. Phasellus quis massa lacus. Nam pulvinar leo lacus, ut venenatis sem ornare vel. Curabitur enim nulla, tempor ac sem at, hendrerit sollicitudin ante. Ut augue lacus, tempor vel tellus sit amet, malesuada congue ipsum.

* Phasellus ac tortor sed nibh fermentum porta
* Nunc nec augue porttitor, pretium erat a, vehicula lacus
* Nam gravida urna tempor, condimentum magna non, pulvinar nulla
* Integer vulputate justo vitae velit posuere dapibus.

Donec congue ac turpis nec gravida. Aliquam ultricies pharetra ultricies. In convallis turpis nulla, ornare lacinia odio suscipit a. Morbi vitae placerat mauris. Ut ullamcorper justo et nibh luctus tincidunt. Aenean consequat massa in tempor porta. Integer nec lacus mi.


text:
Strata2014ScaldingTutorial
==========================

This is a template project for a tutorial on [Effective Data Science With Scalding](http://strataconf.com/strata2014/public/schedule/detail/31957)
at [Strata 2014 Conference](http://strataconf.com/strata2014).

This project is based on amazingly simple [Scalding Example Project by Snowplow Analytics](https://github.com/snowplow/scalding-example-project).

To make best use of your time at the tutorial, please do the following preparation steps:

1. Install SBT
--------------

We use [SBT build tool](http://www.scala-sbt.org/) version [0.12.3](http://www.scala-sbt.org/0.12.3/docs/home.html).

If you don't have it installed on your machine, one way to install it on Mac OS X would be
by using [Homebrew](http://brew.sh/):

     > brew install sbt

[The SBT documentation](http://www.scala-sbt.org/0.12.3/docs/Getting-Started/Setup.html) contains
detailed information about install on other systems.

2. Clone this project
---------------------

     > git clone https://github.com/vitalyg/Strata2014ScaldingTutorial.git
     > cd Strata2014ScaldingTutorial

Some people reported problems with git command. As an alternative, you can download the [zip file](http://github.com/vitalyg/Strata2014ScaldingTutorial/archive/master.zip) and uncompress it:

     > wget http://github.com/vitalyg/Strata2014ScaldingTutorial/archive/master.zip
     > unzip master.zip
     > cd Strata2014ScaldingTutorial-master

3. Enter SBT Command Line
-------------------------

     > sbt
     ...
     Tutorial >

This step may take quite a bit of time downloading all the parts and dependencies so it
makes so much sense to run it in advance.

4. Compile and Run the WordCount Example
----------------------------------------

     Tutorial > run tutorial.WordCountJob
     ...
     [success] Total time: 2 s, completed Feb 3, 2014 9:15:12 PM
     Tutorial >

This step can also take quite a bit of time.

5. See the Results
------------------

The file `grimmWordCounts.tsv` should be created in the `data` directory.

FAQ
---

### I am getting java.lang.OutOfMemoryError ###

You will need to set JVM runtime parameters. Depending on the type of error you will need to increase
heap size (`-Xmx` or PermGen space `-XX:MaxPermSize`).

You can set up options in the SBT command or in file located at `~/.sbtconfig`, for example:

     > cat > ~/.sbtconfig
     export SBT_OPTS="-Xmx1024m -XX:MaxPermSize=256m"
     <ctrl>D
     >

Copyright and license
---------------------

Copyright 2012-2013 Snowplow Analytics Ltd, with significant portions copyright 2012 Twitter, Inc.

Licensed under the [Apache License, Version 2.0] [license] (the "License");
you may not use this software except in compliance with the License.

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.

[license]: http://www.apache.org/licenses/LICENSE-2.0